Skip to main content

tembra_runtime/
codec.rs

1//! Portable values use the same tagged JSON convention as the JavaScript SDK.
2//! Custom infrastructure codecs may replace this wire policy without changing the kernel.
3use crate::core::Reason;
4use crate::{Error, Result};
5use serde_json::{Value, json};
6
7pub trait Codec {
8    /// Return the stable codec identity shared with other adapters.
9    fn id(&self) -> &str;
10    /// Encode portable values using this codec's wire contract.
11    fn serialize(&self, value: &Value) -> Result<Vec<u8>>;
12    /// Decode portable values without narrowing large integers.
13    fn deserialize(&self, bytes: &[u8]) -> Result<Value>;
14}
15
16pub struct Json;
17impl Codec for Json {
18    /// Return the stable codec identity shared with other adapters.
19    fn id(&self) -> &str {
20        "tembra-json/1"
21    }
22
23    /// Encode portable values using this codec's wire contract.
24    fn serialize(&self, value: &Value) -> Result<Vec<u8>> {
25        encode(value)
26    }
27
28    /// Decode portable values without narrowing large integers.
29    fn deserialize(&self, bytes: &[u8]) -> Result<Value> {
30        decode(bytes)
31    }
32}
33
34/// Portable decimal integer. Rust callers can apply checked conversion to their chosen width.
35#[derive(Clone, Debug, Eq, PartialEq)]
36pub struct Integer(pub String);
37impl serde::Serialize for Integer {
38    /// Encode portable values using this codec's wire contract.
39    fn serialize<S: serde::Serializer>(
40        &self,
41        serializer: S,
42    ) -> std::result::Result<S::Ok, S::Error> {
43        bigint(self.0.clone())
44            .map_err(serde::ser::Error::custom)?
45            .serialize(serializer)
46    }
47}
48impl<'de> serde::Deserialize<'de> for Integer {
49    /// Decode portable values without narrowing large integers.
50    fn deserialize<D: serde::Deserializer<'de>>(
51        deserializer: D,
52    ) -> std::result::Result<Self, D::Error> {
53        let value = Value::deserialize(deserializer)?;
54        let tagged = &value["$tembra"];
55        if tagged[0] != "bigint" {
56            return Err(serde::de::Error::custom("expected a portable BigInt"));
57        }
58        let decimal = tagged[1]
59            .as_str()
60            .ok_or_else(|| serde::de::Error::custom("expected decimal text"))?;
61        bigint(decimal).map_err(serde::de::Error::custom)?;
62        Ok(Self(decimal.into()))
63    }
64}
65
66/// Validate decimal integer text and wrap it in the portable tag.
67pub fn bigint(decimal: impl Into<String>) -> Result<Value> {
68    let decimal = decimal.into();
69    let digits = decimal.strip_prefix('-').unwrap_or(&decimal);
70    if digits.is_empty()
71        || (digits.len() > 1 && digits.starts_with('0'))
72        || !digits.bytes().all(|byte| byte.is_ascii_digit())
73    {
74        return Err(Error::invalid(Reason::Bigint, "expected a decimal integer"));
75    }
76    Ok(json!({"$tembra": ["bigint", decimal]}))
77}
78
79/// Wrap bytes in the portable tagged representation.
80pub fn bytes(value: &[u8]) -> Value {
81    json!({"$tembra": ["bytes", value]})
82}
83
84/// Encode a portable JSON value or report serialization failure.
85pub fn encode(value: &Value) -> Result<Vec<u8>> {
86    serde_json::to_vec(value)
87        .map_err(|error| Error::invalid(Reason::Serialization, error.to_string()))
88}
89
90/// Decode JSON bytes or report malformed serialized data.
91pub fn decode(bytes: &[u8]) -> Result<Value> {
92    serde_json::from_slice(bytes)
93        .map_err(|error| Error::invalid(Reason::Serialization, error.to_string()))
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn portable_integer_text_matches_javascript() {
102        for decimal in [
103            "0",
104            "-0",
105            "7",
106            "-7",
107            "9007199254740993",
108            "-18446744073709551616",
109        ] {
110            let integer = Integer(decimal.into());
111            let wire = serde_json::to_value(&integer).unwrap();
112            assert_eq!(serde_json::from_value::<Integer>(wire).unwrap(), integer);
113        }
114        for decimal in ["", "-", "+7", "007", "-007", "00", "-00", "1.0", " 7", "7"] {
115            assert!(bigint(decimal).is_err(), "accepted {decimal:?}");
116            assert!(serde_json::to_value(Integer(decimal.into())).is_err());
117            assert!(
118                serde_json::from_value::<Integer>(json!({"$tembra": ["bigint", decimal]})).is_err()
119            );
120        }
121    }
122}