Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support deserializing events of previous and current version #61

Merged
merged 2 commits into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions rs/canister/api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,7 @@ edition = "2021"
candid.workspace = true
serde.workspace = true
serde_bytes.workspace = true

[dev-dependencies]
rmp-serde = "1.1.2"
test-case.workspace = true
153 changes: 151 additions & 2 deletions rs/canister/api/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
use candid::{CandidType, Deserialize};
use serde::Serialize;
use serde::__private::from_utf8_lossy;
use serde::de::{EnumAccess, Error, Unexpected, VariantAccess};
use serde::{Deserializer, Serialize};
use std::fmt;
use std::fmt::Formatter;
use std::marker::PhantomData;

mod lifecycle;
mod queries;
Expand Down Expand Up @@ -45,7 +50,7 @@
pub payload: Vec<u8>,
}

#[derive(CandidType, Serialize, Deserialize, Clone, Debug)]
#[derive(CandidType, Serialize, Clone, Debug)]
pub enum Anonymizable {
Public(String),
Anonymize(String),
Expand All @@ -71,3 +76,147 @@
matches!(self, Anonymizable::Public(_))
}
}

impl<'de> Deserialize<'de> for Anonymizable {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
enum Field {
Field0,
Field1,
Value(String),
}
#[doc(hidden)]
struct FieldVisitor;
impl<'de> serde::de::Visitor<'de> for FieldVisitor {
type Value = Field;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
write!(formatter, "variant identifier")
}
fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
where
E: Error,
{
match value {
0u64 => Ok(Field::Field0),
1u64 => Ok(Field::Field1),
_ => Err(Error::invalid_value(
Unexpected::Unsigned(value),
&"variant index 0 <= i < 2",
)),
}
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: Error,
{
match value {
"Public" => Ok(Field::Field0),
"Anonymize" => Ok(Field::Field1),
value => Ok(Field::Value(value.to_string())),
}
}
fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
match value {
b"Public" => Ok(Field::Field0),
b"Anonymize" => Ok(Field::Field1),
_ => {
let value = &from_utf8_lossy(value);
Err(Error::unknown_variant(value, VARIANTS))
}
}
}
}
impl<'de> Deserialize<'de> for Field {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Deserializer::deserialize_identifier(deserializer, FieldVisitor)
}
}
#[doc(hidden)]
struct Visitor<'de> {
marker: PhantomData<Anonymizable>,
lifetime: PhantomData<&'de ()>,
}
impl<'de> serde::de::Visitor<'de> for Visitor<'de> {
type Value = Anonymizable;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
Formatter::write_str(formatter, "enum Anonymizable")
}
fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
where
A: EnumAccess<'de>,
{
match EnumAccess::variant(data)? {
(Field::Field0, variant) => Result::map(
VariantAccess::newtype_variant::<String>(variant),
Anonymizable::Public,
),
(Field::Field1, variant) => Result::map(
VariantAccess::newtype_variant::<String>(variant),
Anonymizable::Anonymize,
),
(Field::Value(value), _) => Ok(Self::Value::Public(value)),
}
}
}
#[doc(hidden)]
const VARIANTS: &'static [&'static str] = &["Public", "Anonymize"];

Check failure on line 171 in rs/canister/api/src/lib.rs

View workflow job for this annotation

GitHub Actions / run clippy

constants have by default a `'static` lifetime

Check failure on line 171 in rs/canister/api/src/lib.rs

View workflow job for this annotation

GitHub Actions / run clippy

constants have by default a `'static` lifetime
Deserializer::deserialize_enum(
deserializer,
"Anonymizable",
VARIANTS,
Visitor {
marker: PhantomData::<Anonymizable>,
lifetime: PhantomData,
},
)
}
}

#[test_case::test_case(true)]

Check failure on line 184 in rs/canister/api/src/lib.rs

View workflow job for this annotation

GitHub Actions / run clippy

failed to resolve: use of undeclared crate or module `test_case`

Check failure on line 184 in rs/canister/api/src/lib.rs

View workflow job for this annotation

GitHub Actions / run unit tests

failed to resolve: use of undeclared crate or module `test_case`
#[test_case::test_case(false)]

Check failure on line 185 in rs/canister/api/src/lib.rs

View workflow job for this annotation

GitHub Actions / run clippy

failed to resolve: use of undeclared crate or module `test_case`

Check failure on line 185 in rs/canister/api/src/lib.rs

View workflow job for this annotation

GitHub Actions / run unit tests

failed to resolve: use of undeclared crate or module `test_case`
fn deserialization_succeeds(current_version: bool) {
let bytes: Vec<_>;
if current_version {
let value = IdempotentEvent {
idempotency_key: 1,
name: "name".to_string(),
timestamp: 2,
user: Some(Anonymizable::Public("user".to_string())),
source: Some(Anonymizable::Public("source".to_string())),
payload: vec![1, 2, 3],
};

bytes = rmp_serde::to_vec_named(&value).unwrap();

Check failure on line 198 in rs/canister/api/src/lib.rs

View workflow job for this annotation

GitHub Actions / run clippy

failed to resolve: use of undeclared crate or module `rmp_serde`

Check failure on line 198 in rs/canister/api/src/lib.rs

View workflow job for this annotation

GitHub Actions / run unit tests

failed to resolve: use of undeclared crate or module `rmp_serde`
} else {
let value = IdempotentEventPrevious {
idempotency_key: 1,
name: "name".to_string(),
timestamp: 2,
user: Some("user".to_string()),
source: Some("source".to_string()),
payload: vec![1, 2, 3],
};

bytes = rmp_serde::to_vec_named(&value).unwrap();

Check failure on line 209 in rs/canister/api/src/lib.rs

View workflow job for this annotation

GitHub Actions / run clippy

failed to resolve: use of undeclared crate or module `rmp_serde`

Check failure on line 209 in rs/canister/api/src/lib.rs

View workflow job for this annotation

GitHub Actions / run unit tests

failed to resolve: use of undeclared crate or module `rmp_serde`
}

let deserialized: IdempotentEvent = rmp_serde::from_slice(&bytes).unwrap();

Check failure on line 212 in rs/canister/api/src/lib.rs

View workflow job for this annotation

GitHub Actions / run clippy

failed to resolve: use of undeclared crate or module `rmp_serde`

Check failure on line 212 in rs/canister/api/src/lib.rs

View workflow job for this annotation

GitHub Actions / run unit tests

failed to resolve: use of undeclared crate or module `rmp_serde`

assert_eq!(deserialized.idempotency_key, 1);
assert_eq!(deserialized.name, "name");
assert_eq!(deserialized.timestamp, 2);
assert_eq!(deserialized.user.clone().unwrap().as_str(), "user");
assert!(deserialized.user.clone().unwrap().is_public());
assert_eq!(deserialized.source.clone().unwrap().as_str(), "source");
assert!(deserialized.source.clone().unwrap().is_public());
assert_eq!(deserialized.payload, vec![1, 2, 3]);
}
Loading