Skip to content

Commit f4e9666

Browse files
sfauvelAlenar
authored andcommitted
Adapt fake_aggregator shared state reading to new json structure
1 parent 7d4f30a commit f4e9666

File tree

2 files changed

+34
-97
lines changed

2 files changed

+34
-97
lines changed

internal/mithril-build-script/src/fake_aggregator.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -177,8 +177,7 @@ impl FakeAggregatorData {
177177
.map(|(key, value)| extract_artifact_id_and_content(key, value))
178178
.collect();
179179

180-
let tree = BTreeMap::from_iter(res.unwrap());
181-
tree
180+
BTreeMap::from_iter(res.unwrap())
182181
}
183182
}
184183

mithril-test-lab/mithril-aggregator-fake/src/shared_state.rs

Lines changed: 33 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ use std::{
55
};
66

77
use anyhow::{anyhow, Context};
8-
use serde_json::Value;
98
use tokio::sync::RwLock;
109
use tracing::{debug, trace};
1110

@@ -57,12 +56,11 @@ impl AppState {
5756
pub fn from_directory(data_dir: &Path) -> StdResult<Self> {
5857
let reader = DataDir::new(data_dir)?;
5958
let epoch_settings = reader.read_file("epoch-settings")?;
60-
let (certificate_list, mut certificates) = reader.read_files("certificate", "hash")?;
61-
reader.read_certificate_chain(&certificate_list, &mut certificates)?;
62-
let (snapshot_list, snapshots) = reader.read_files("snapshot", "digest")?;
63-
let (msd_list, msds) = reader.read_files("mithril-stake-distribution", "hash")?;
64-
let (ctx_snapshot_list, ctx_snapshots) = reader.read_files("ctx-snapshot", "hash")?;
65-
let (_, ctx_proofs) = reader.read_files("ctx-proof", "transaction_hash")?;
59+
let (certificate_list, certificates) = reader.read_files("certificate")?;
60+
let (snapshot_list, snapshots) = reader.read_files("snapshot")?;
61+
let (msd_list, msds) = reader.read_files("mithril-stake-distribution")?;
62+
let (ctx_snapshot_list, ctx_snapshots) = reader.read_files("ctx-snapshot")?;
63+
let (_, ctx_proofs) = reader.read_files("ctx-proof")?;
6664

6765
let instance = Self {
6866
epoch_settings,
@@ -173,103 +171,43 @@ impl DataDir {
173171
Ok(file_content)
174172
}
175173

176-
fn read_list_file(&self, entity: &str) -> StdResult<(String, Value)> {
177-
let list_file = {
178-
let list_file_name = format!("{entity}s.json");
179-
180-
self.data_dir.to_owned().join(list_file_name)
181-
};
182-
trace!("Reading JSON list file '{}'.", list_file.display());
183-
let list = std::fs::read_to_string(&list_file)
184-
.with_context(|| format!("Error while reading file '{}'.", list_file.display()))?;
185-
let list_json: Value = serde_json::from_str(&list)
186-
.with_context(|| format!("Could not parse JSON in file '{}'.", list_file.display()))?;
187-
188-
Ok((list, list_json))
174+
fn read_list_file(&self, entity: &str) -> StdResult<String> {
175+
self.read_file(&format!("{entity}s-list"))
189176
}
190177

191-
fn read_entity_file(&self, entity: &str, id: &str) -> StdResult<(String, Value)> {
192-
let filename = format!("{entity}-{id}.json");
193-
let path = self.data_dir.to_owned().join(filename);
194-
trace!("Reading {entity} JSON file '{}'.", path.display());
195-
let content = std::fs::read_to_string(&path)
196-
.with_context(|| format!("Could not read entity file '{}'.", path.display()))?;
197-
let value: Value = serde_json::from_str(&content).with_context(|| {
198-
format!(
199-
"Entity file '{}' does not seem to hold valid JSON content.",
200-
path.display()
201-
)
178+
fn extract_entity_content(
179+
entity: &str,
180+
key: &String,
181+
value: &serde_json::Value,
182+
) -> StdResult<(String, String)> {
183+
let json_content = serde_json::to_string(value)
184+
.with_context(|| format!("Could not serialize '{entity}-{key}' as JSON."))?;
185+
Ok((key.to_owned(), json_content))
186+
}
187+
188+
fn read_entities_file(&self, entity: &str) -> StdResult<BTreeMap<String, String>> {
189+
let file_content = self.read_file(&format!("{entity}s"))?;
190+
let parsed_json: serde_json::Value = serde_json::from_str(&file_content)
191+
.with_context(|| format!("Could not parse JSON in file '{entity}s.json'."))?;
192+
let json_object = parsed_json.as_object().with_context(|| {
193+
format!("Collection file for entity {entity} is not a JSON hashmap.")
202194
})?;
195+
let res: Result<Vec<_>, _> = json_object
196+
.iter()
197+
.map(|(key, value)| Self::extract_entity_content(entity, key, value))
198+
.collect();
203199

204-
Ok((content, value))
200+
Ok(BTreeMap::from_iter(res?))
205201
}
206202

207203
/// Read related entity JSON files in the given directory.
208-
pub fn read_files(
209-
&self,
210-
entity: &str,
211-
field_id: &str,
212-
) -> StdResult<(String, BTreeMap<String, String>)> {
213-
debug!("Read data files, entity='{entity}', field='{field_id}'.");
214-
215-
let (list, list_json) = self.read_list_file(entity)?;
216-
let ids: Vec<String> = list_json
217-
.as_array()
218-
.ok_or_else(|| {
219-
anyhow!(format!(
220-
"List file for entity {entity} is not a JSON array."
221-
))
222-
})?
223-
.iter()
224-
.map(|v| {
225-
v[field_id].as_str().map(|s| s.to_owned()).ok_or_else(|| {
226-
anyhow!(format!(
227-
"Field '{field_id}' for type '{entity}' did not return a string (value: '{}').",
228-
v.to_string()
229-
))
230-
})
231-
})
232-
.collect::<StdResult<Vec<String>>>()?;
233-
234-
let mut collection: BTreeMap<String, String> = BTreeMap::new();
235-
236-
for id in &ids {
237-
let (content, _value) = self.read_entity_file(entity, id)?;
238-
collection.insert(id.to_owned(), content);
239-
}
240-
241-
Ok((list, collection))
242-
}
204+
pub fn read_files(&self, entity: &str) -> StdResult<(String, BTreeMap<String, String>)> {
205+
debug!("Read data files, entity='{entity}'.");
243206

244-
pub fn read_certificate_chain(
245-
&self,
246-
certificate_list: &str,
247-
certificates: &mut BTreeMap<String, String>,
248-
) -> StdResult<()> {
249-
trace!("fetching certificate chain");
250-
let list = serde_json::from_str::<Value>(certificate_list)?
251-
.as_array()
252-
.map(|v| v.to_owned())
253-
.ok_or_else(|| anyhow!("Could not cast certificates.json as JSON array."))?;
254-
let mut previous_hash = list[0]["previous_hash"]
255-
.as_str()
256-
.map(|v| v.to_owned())
257-
.ok_or_else(|| anyhow!("Field 'previous_hash' does not exist in the first certificate of the certificatd list."))?;
258-
259-
while previous_hash.is_empty() {
260-
let (certificate, value) = self.read_entity_file("certificate", &previous_hash)?;
261-
let _ = certificates.insert(previous_hash.clone(), certificate);
262-
previous_hash = value["previous_hash"]
263-
.as_str()
264-
.map(|v| v.to_owned())
265-
.ok_or_else(|| {
266-
anyhow!(
267-
"field 'previous_hash' does not exist in certificate id='{previous_hash}'."
268-
)
269-
})?;
270-
}
207+
let list = self.read_list_file(entity)?;
208+
let collection = self.read_entities_file(entity)?;
271209

272-
Ok(())
210+
Ok((list, collection))
273211
}
274212
}
275213

0 commit comments

Comments
 (0)