Skip to content

Commit

Permalink
feat: Add serialization traits to Status (#499)
Browse files Browse the repository at this point in the history
  • Loading branch information
bitdivine authored Feb 13, 2024
1 parent 981706c commit f216c74
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

* Changed the return type of `stored_chunks` to a struct.
* Added a prime256v1-based `Identity` impl to complement the ed25519 and secp256k1 `Identity` impls.
* Added serde and candid serialization traits to the `Status` type.

## [0.32.0] - 2024-01-18

Expand Down
1 change: 1 addition & 0 deletions ic-agent/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ web-sys = { version = "0.3", features = ["Window"], optional = true }

[dev-dependencies]
serde_json = "1.0.79"
candid = { workspace = true, features = ["value"]}

[target.'cfg(not(target_family = "wasm"))'.dev-dependencies]
tokio = { version = "1.24.2", features = ["full"] }
Expand Down
49 changes: 47 additions & 2 deletions ic-agent/src/agent/status.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
//! Types for interacting with the status endpoint of a replica. See [`Status`] for details.
use candid::{CandidType, Deserialize};
use serde::Serialize;
use std::{collections::BTreeMap, fmt::Debug};

/// Value returned by the status endpoint of a replica. This is a loose mapping to CBOR values.
/// Because the agent should not return [`serde_cbor::Value`] directly across API boundaries,
/// we reimplement it as [`Value`] here.
#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Clone, Hash)]
#[derive(
Debug, Ord, PartialOrd, Eq, PartialEq, Clone, Hash, CandidType, Serialize, Deserialize,
)]
pub enum Value {
/// See [`Null`](serde_cbor::Value::Null).
Null,
Expand Down Expand Up @@ -40,7 +44,7 @@ impl std::fmt::Display for Value {

/// The structure returned by [`super::Agent::status`], containing the information returned
/// by the status endpoint of a replica.
#[derive(Debug, Ord, PartialOrd, PartialEq, Eq)]
#[derive(Debug, Ord, PartialOrd, PartialEq, Eq, CandidType, Deserialize, Serialize)]
pub struct Status {
/// Optional. The precise git revision of the Internet Computer Protocol implementation.
pub impl_version: Option<String>,
Expand All @@ -55,6 +59,47 @@ pub struct Status {
pub values: BTreeMap<String, Box<Value>>,
}

#[test]
fn can_serilaize_status_as_json() {
let status = Status {
impl_version: None,
replica_health_status: None,
root_key: None,
values: BTreeMap::new(),
};
let expected_json =
r#"{"impl_version":null,"replica_health_status":null,"root_key":null,"values":{}}"#;
let actual_json = serde_json::to_string(&status).expect("Failed to serialize as JSON");
assert_eq!(expected_json, actual_json);
}
#[test]
fn can_serialize_status_as_idl() {
use candid::types::value::IDLValue;
use candid::{Encode, IDLArgs, Result as CandidResult, TypeEnv};
let status = Status {
impl_version: Some("Foo".to_string()),
replica_health_status: None,
root_key: None,
values: BTreeMap::new(),
};
// Expresses data as IDLValue. Then use .to_string() to convert to text-form candid.
// TODO: This function has been added to the Candid library and will be available in the next
// release. Then, this definition here can be deleted.
pub fn try_from_candid_type<T>(data: &T) -> CandidResult<IDLValue>
where
T: CandidType,
{
let blob = Encode!(data)?;
let args = IDLArgs::from_bytes_with_types(&blob, &TypeEnv::default(), &[T::ty()])?;
Ok(args.args[0].clone())
}
let expected_idl = "record {\n values = vec {};\n replica_health_status = null;\n impl_version = opt \"Foo\";\n root_key = null;\n}";
let actual_idl = try_from_candid_type(&status)
.expect("Failed to convert to idl")
.to_string();
assert_eq!(expected_idl, actual_idl);
}

impl std::fmt::Display for Status {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("{\n")?;
Expand Down

0 comments on commit f216c74

Please sign in to comment.