mithril_aggregator_client/query/get/
get_snapshot.rs1use async_trait::async_trait;
2use reqwest::StatusCode;
3
4use mithril_common::messages::SnapshotMessage;
5
6use crate::AggregatorHttpClientResult;
7use crate::query::{AggregatorQuery, QueryContext, QueryMethod, ResponseExt};
8
9pub struct GetSnapshotQuery {
11 hash: String,
12}
13
14impl GetSnapshotQuery {
15 pub fn by_hash<H: Into<String>>(hash: H) -> Self {
17 Self { hash: hash.into() }
18 }
19}
20
21#[cfg_attr(target_family = "wasm", async_trait(?Send))]
22#[cfg_attr(not(target_family = "wasm"), async_trait)]
23impl AggregatorQuery for GetSnapshotQuery {
24 type Response = Option<SnapshotMessage>;
25 type Body = ();
26
27 fn method() -> QueryMethod {
28 QueryMethod::Get
29 }
30
31 fn route(&self) -> String {
32 format!("artifact/snapshot/{}", self.hash)
33 }
34
35 async fn handle_response(
36 &self,
37 context: QueryContext,
38 ) -> AggregatorHttpClientResult<Self::Response> {
39 match context.response.status() {
40 StatusCode::OK => context.response.parse_json_option().await,
41 StatusCode::NOT_FOUND => Ok(None),
42 _ => Err(context.unhandled_status_code().await),
43 }
44 }
45}
46
47#[cfg(test)]
48mod tests {
49 use serde_json::json;
50
51 use mithril_common::test::double::Dummy;
52
53 use crate::AggregatorHttpClientError;
54 use crate::test::{assert_error_matches, setup_server_and_client};
55
56 use super::*;
57
58 #[tokio::test]
59 async fn test_snapshot_details_ok_200() {
60 let (server, client) = setup_server_and_client();
61 let expected_message = SnapshotMessage::dummy();
62 let _server_mock = server.mock(|when, then| {
63 when.path(format!("/artifact/snapshot/{}", expected_message.digest));
64 then.status(200).body(json!(expected_message).to_string());
65 });
66
67 let fetched_message = client
68 .send(GetSnapshotQuery::by_hash(&expected_message.digest))
69 .await
70 .unwrap();
71
72 assert_eq!(Some(expected_message), fetched_message);
73 }
74
75 #[tokio::test]
76 async fn test_snapshot_details_ok_404() {
77 let (server, client) = setup_server_and_client();
78 let _server_mock = server.mock(|when, then| {
79 when.any_request();
80 then.status(404);
81 });
82
83 let fetched_message = client.send(GetSnapshotQuery::by_hash("whatever")).await.unwrap();
84
85 assert_eq!(None, fetched_message);
86 }
87
88 #[tokio::test]
89 async fn test_snapshot_details_ko_500() {
90 let (server, client) = setup_server_and_client();
91 let _server_mock = server.mock(|when, then| {
92 when.any_request();
93 then.status(500).body("an error occurred");
94 });
95
96 let error = client.send(GetSnapshotQuery::by_hash("whatever")).await.unwrap_err();
97
98 assert_error_matches!(error, AggregatorHttpClientError::RemoteServerTechnical(_));
99 }
100}