update_package/
epoch.rs
1use epoch::EpochFile;
8use fidl_fuchsia_io as fio;
9use thiserror::Error;
10use zx_status::Status;
11
12#[derive(Debug, Error)]
14#[allow(missing_docs)]
15pub enum ParseEpochError {
16 #[error("while opening the file")]
17 OpenFile(#[source] fuchsia_fs::node::OpenError),
18
19 #[error("while reading the file")]
20 ReadFile(#[source] fuchsia_fs::file::ReadError),
21
22 #[error("while deserializing: `{0:?}`")]
23 Deserialize(String, #[source] serde_json::Error),
24}
25
26pub(crate) async fn epoch(proxy: &fio::DirectoryProxy) -> Result<Option<u64>, ParseEpochError> {
27 let file = match fuchsia_fs::directory::open_file(proxy, "epoch.json", fio::PERM_READABLE).await
28 {
29 Ok(file) => file,
30 Err(fuchsia_fs::node::OpenError::OpenError(Status::NOT_FOUND)) => return Ok(None),
31 Err(e) => return Err(ParseEpochError::OpenFile(e)),
32 };
33 let contents =
34 fuchsia_fs::file::read_to_string(&file).await.map_err(ParseEpochError::ReadFile)?;
35 match serde_json::from_str(&contents).map_err(|e| ParseEpochError::Deserialize(contents, e))? {
36 EpochFile::Version1 { epoch } => Ok(Some(epoch)),
37 }
38}
39
40#[cfg(test)]
41mod tests {
42 use super::*;
43 use crate::TestUpdatePackage;
44 use assert_matches::assert_matches;
45 use fuchsia_async as fasync;
46
47 #[fasync::run_singlethreaded(test)]
48 async fn parse_epoch_success() {
49 let p = TestUpdatePackage::new()
50 .add_file("epoch.json", serde_json::to_vec(&EpochFile::Version1 { epoch: 3 }).unwrap())
51 .await;
52 assert_matches!(p.epoch().await, Ok(Some(3)));
53 }
54
55 #[fasync::run_singlethreaded(test)]
56 async fn parse_epoch_success_missing_epoch_file() {
57 let p = TestUpdatePackage::new();
58 assert_matches!(p.epoch().await, Ok(None));
59 }
60
61 #[fasync::run_singlethreaded(test)]
62 async fn parse_epoch_fail_deserialize() {
63 let p = TestUpdatePackage::new().add_file("epoch.json", "oh no! this isn't json.").await;
64 assert_matches!(
65 p.epoch().await,
66 Err(ParseEpochError::Deserialize(s,_)) if s == "oh no! this isn't json."
67 );
68 }
69}