Skip to main content

zenkey_model/
decode.rs

1//! Decoding a payload from a bundle alone (spec `core.md` §7.1–§7.2), for
2//! tools that were never compiled against the contract.
3//!
4//! - **Decode order** (observer §7.3): a payload whose declared type the
5//!   tool holds is decoded by that type, on the wire its sample's
6//!   `Encoding` names. Any other payload is sniffed.
7//! - **protobuf** decodes through the bundle's `FileDescriptorSet`
8//!   (prost-reflect), without codegen; **jsonschema** types are JSON or CBOR.
9//!   Both render field by field, as JSON.
10//! - **packed** (core §7.6) reads through the bundle's layout, under the
11//!   tag the record's envelope carried ([`Context`]): a record with no
12//!   tag, or one its layout refuses, is undecodable with the refusal named.
13//! - **Honest rendering:** a `raw` type renders as its declared media type
14//!   and the sample's size, and bytes that do not decode as their declared
15//!   type render as that type, the size and the reason. Neither garbage nor
16//!   nothing.
17
18use base64::Engine as _;
19use prost_reflect::{DescriptorPool, DynamicMessage};
20use serde_json::Value;
21
22use crate::bundle::Bundle;
23use crate::wire::Tag;
24
25/// What a payload renders as.
26#[derive(Debug, Clone, PartialEq)]
27pub enum Rendered {
28    /// Decoded, field by field, as JSON.
29    Value(Value),
30    /// A type this decoder does not decode: its declared media type and the
31    /// payload's size.
32    Opaque { media_type: String, size: usize },
33    /// Bytes that do not decode as their declared type, named as
34    /// [`declared`] names it (spec §7.2, 0.8).
35    Undecodable {
36        declared: String,
37        size: usize,
38        reason: String,
39    },
40}
41
42/// A canonical type reference in the authoring spelling (spec §7.2, 0.8):
43/// the message name for protobuf, `json:<name>` for a JSON Schema type,
44/// the media type for a raw one. A tool names a type this way wherever it
45/// renders one, decoded or not.
46#[must_use]
47pub fn declared(ty: &Value) -> String {
48    let name = ty["name"].as_str().unwrap_or_default();
49    match ty["kind"].as_str() {
50        Some("jsonschema") => format!("json:{name}"),
51        Some("packed") => format!("packed:{name}"),
52        Some("raw") => ty["media_type"].as_str().unwrap_or_default().to_owned(),
53        _ => name.to_owned(),
54    }
55}
56
57/// The canonical type reference of a resource's member (`type`,
58/// `attachment`, `request`, `response`, `error` or `summary`), found by the
59/// resource's kind token and template.
60#[must_use]
61pub fn type_of<'b>(
62    bundle: &'b Bundle,
63    token: &str,
64    template: &str,
65    member: &str,
66) -> Option<&'b Value> {
67    bundle.contract["resources"]
68        .as_array()?
69        .iter()
70        .find(|r| r["token"] == token && r["template"] == template)
71        .map(|r| &r[member])
72        .filter(|t| t.is_object())
73}
74
75/// The JSON-Schema-type wire encoding of a resource member: the contract's
76/// `encoding` (or `attachment_encoding` for an attachment), JSON by default.
77fn contract_encoding(bundle: &Bundle, ty: &Value) -> Option<String> {
78    // The type reference itself does not carry the encoding; find the
79    // resource that holds this exact reference.
80    bundle.contract["resources"]
81        .as_array()?
82        .iter()
83        .find_map(|r| {
84            if &r["attachment"] == ty {
85                r["attachment_encoding"].as_str().map(str::to_owned)
86            } else if ["type", "request", "response", "error", "summary"]
87                .iter()
88                .any(|m| &r[*m] == ty)
89            {
90                r["encoding"].as_str().map(str::to_owned)
91            } else {
92                None
93            }
94        })
95}
96
97/// What a reader holds of a payload beside its bytes and its `Encoding`:
98/// what a packed record is read with (core §7.6).
99#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
100pub struct Context {
101    /// The tag its envelope's CH carried (core §7.5), when it came in one.
102    /// A packed record that came in none has no tag, and does not decode.
103    pub tag: Option<Tag>,
104    /// The deployment epoch in seconds, for a packed record's `time`
105    /// fields; `None` reads them under [`crate::packed::DEFAULT_EPOCH`],
106    /// since nothing carries one yet (#980).
107    pub epoch: Option<i64>,
108}
109
110impl Context {
111    /// A record that came in an envelope whose CH carried `tag`.
112    #[must_use]
113    pub fn tagged(tag: Tag) -> Self {
114        Self {
115            tag: Some(tag),
116            epoch: None,
117        }
118    }
119}
120
121/// Decodes `bytes` of the type `ty` (a canonical type reference of
122/// `bundle`). `encoding` is the sample's `Encoding` as zenoh spells it
123/// (`application/json`, `application/cbor`, `application/protobuf`, …), if
124/// any. A packed type decodes only with its envelope's tag in hand:
125/// [`decode_in`].
126#[must_use]
127pub fn decode(bundle: &Bundle, ty: &Value, encoding: Option<&str>, bytes: &[u8]) -> Rendered {
128    decode_in(bundle, ty, encoding, bytes, Context::default())
129}
130
131/// [`decode`], with what the reader holds beside the bytes: a packed
132/// record is read through the bundle's layout under its envelope's tag and
133/// the deployment epoch (core §7.6), refused by name as the layout refuses
134/// it.
135#[must_use]
136pub fn decode_in(
137    bundle: &Bundle,
138    ty: &Value,
139    encoding: Option<&str>,
140    bytes: &[u8],
141    cx: Context,
142) -> Rendered {
143    let size = bytes.len();
144    let name = ty["name"].as_str().unwrap_or_default();
145    match ty["kind"].as_str() {
146        Some("raw") => {
147            // The declared media type; for a raw family (`video/*`), the
148            // concrete subtype the sample's `Encoding` carries.
149            let declared = ty["media_type"].as_str().unwrap_or_default();
150            let media_type = match encoding {
151                Some(e) if declared.ends_with("/*") => e.to_owned(),
152                _ => declared.to_owned(),
153            };
154            Rendered::Opaque { media_type, size }
155        }
156        Some("protobuf") => {
157            let fail = |reason: String| Rendered::Undecodable {
158                declared: declared(ty),
159                size,
160                reason,
161            };
162            let Some(pool) = artifact(bundle, ty).and_then(|data| {
163                let b = base64::engine::general_purpose::STANDARD
164                    .decode(data.as_str()?)
165                    .ok()?;
166                DescriptorPool::decode(b.as_slice()).ok()
167            }) else {
168                return fail("the bundle's descriptor set does not decode".to_owned());
169            };
170            let Some(desc) = pool.get_message_by_name(name) else {
171                return fail(format!("{name} is not in the bundle's descriptor set"));
172            };
173            match DynamicMessage::decode(desc, bytes) {
174                Ok(m) => match serde_json::to_value(&m) {
175                    Ok(v) => Rendered::Value(v),
176                    Err(e) => fail(e.to_string()),
177                },
178                Err(e) => fail(e.to_string()),
179            }
180        }
181        Some("jsonschema") => {
182            let wire = match encoding {
183                Some(e) if e.starts_with("application/cbor") => "cbor".to_owned(),
184                Some(e) if e.starts_with("application/json") => "json".to_owned(),
185                _ => contract_encoding(bundle, ty).unwrap_or_else(|| "json".to_owned()),
186            };
187            let decoded = if wire == "cbor" {
188                ciborium::from_reader::<ciborium::Value, _>(bytes)
189                    .map_err(|e| e.to_string())
190                    .and_then(|v| cbor_to_json(&v))
191            } else {
192                serde_json::from_slice::<Value>(bytes).map_err(|e| e.to_string())
193            };
194            match decoded {
195                Ok(v) => Rendered::Value(v),
196                Err(reason) => Rendered::Undecodable {
197                    declared: declared(ty),
198                    size,
199                    reason: format!("as {wire}: {reason}"),
200                },
201            }
202        }
203        // A packed record is read under its envelope's tag, its time
204        // fields from the deployment's epoch (core §7.6), refused by name.
205        Some("packed") => {
206            let fail = |reason: String| Rendered::Undecodable {
207                declared: declared(ty),
208                size,
209                reason,
210            };
211            let Some(tag) = cx.tag else {
212                return fail(
213                    "a packed record travels in an envelope, and this one came in none, so it \
214                     has no tag to read it by"
215                        .to_owned(),
216                );
217            };
218            let layout = match artifact(bundle, ty)
219                .ok_or_else(|| "the bundle carries no such packed artifact".to_owned())
220                .and_then(|doc| crate::packed::layout_in(doc, name))
221            {
222                Ok(l) => l,
223                Err(reason) => return fail(reason),
224            };
225            // No epoch stated: E = 0 (`DEFAULT_EPOCH`), as the codec reads.
226            match layout.read(tag.get(), bytes, cx.epoch) {
227                Ok(v) => Rendered::Value(v),
228                Err(r) => fail(format!("refused by its layout, {}", r.reason())),
229            }
230        }
231        _ => Rendered::Undecodable {
232            declared: ty.to_string(),
233            size,
234            reason: "not a type reference".to_owned(),
235        },
236    }
237}
238
239/// The deployment epoch [`decode_in`] reads a record of `ty` under when
240/// `cx` states none: [`crate::packed::DEFAULT_EPOCH`] for a packed type
241/// whose layout holds a `time` field, `None` for every other type and
242/// whenever `cx` states one. Such a record's `time` values are right only
243/// where the deployment's epoch is that one (core §7.6 carries it nowhere
244/// yet; #980), so a tool that shows them says so beside them.
245#[must_use]
246pub fn epoch_assumed(bundle: &Bundle, ty: &Value, cx: Context) -> Option<i64> {
247    if cx.epoch.is_some() || ty["kind"] != "packed" {
248        return None;
249    }
250    let layout = crate::packed::layout_in(artifact(bundle, ty)?, ty["name"].as_str()?).ok()?;
251    layout
252        .fields()
253        .any(|f| matches!(f.kind, crate::packed::FieldKind::Time { .. }))
254        .then_some(crate::packed::DEFAULT_EPOCH)
255}
256
257fn artifact<'b>(bundle: &'b Bundle, ty: &Value) -> Option<&'b Value> {
258    bundle
259        .schemas
260        .get(ty["schema"].as_str()?)
261        .map(|s| &s["data"])
262}
263
264/// CBOR as JSON, with byte strings as base64 (§7.2: bytes are CBOR byte
265/// strings, or base64 in JSON).
266fn cbor_to_json(v: &ciborium::Value) -> Result<Value, String> {
267    use ciborium::Value as C;
268    Ok(match v {
269        C::Null => Value::Null,
270        C::Bool(b) => Value::Bool(*b),
271        C::Integer(i) => {
272            let n: i128 = (*i).into();
273            i64::try_from(n)
274                .map(Value::from)
275                .or_else(|_| u64::try_from(n).map(Value::from))
276                .map_err(|_| format!("integer {n} out of range"))?
277        }
278        C::Float(f) => serde_json::Number::from_f64(*f)
279            .map(Value::Number)
280            .ok_or_else(|| format!("{f} has no JSON form"))?,
281        C::Text(s) => Value::String(s.clone()),
282        C::Bytes(b) => Value::String(base64::engine::general_purpose::STANDARD.encode(b)),
283        C::Array(a) => Value::Array(a.iter().map(cbor_to_json).collect::<Result<_, _>>()?),
284        C::Map(m) => {
285            let mut out = serde_json::Map::new();
286            for (k, v) in m {
287                let C::Text(k) = k else {
288                    return Err("a map key that is not text".to_owned());
289                };
290                out.insert(k.clone(), cbor_to_json(v)?);
291            }
292            Value::Object(out)
293        }
294        C::Tag(_, inner) => cbor_to_json(inner)?,
295        _ => return Err("an unsupported CBOR value".to_owned()),
296    })
297}
298
299#[cfg(test)]
300mod tests {
301    use super::{Rendered, decode};
302    use crate::bundle::Bundle;
303    use serde_json::json;
304
305    fn bundle(toml: &str, files: &[(&str, &str)]) -> Bundle {
306        let dir =
307            std::env::temp_dir().join(format!("zk2-decode-{}-{}", std::process::id(), toml.len()));
308        std::fs::create_dir_all(&dir).unwrap();
309        for (name, text) in files {
310            std::fs::write(dir.join(name), text).unwrap();
311        }
312        let l = crate::contract::load_str(toml, &dir, None);
313        let c = l.contract.unwrap_or_else(|| panic!("{}", l.report));
314        Bundle::build(&c)
315    }
316
317    #[test]
318    fn protobuf_json_cbor_and_raw_render_honestly() {
319        let b = bundle(
320            "[interface]\nname = \"m\"\nmajor = 1\nminor = 0\n\
321             [schemas]\nprotobuf = [\"m.proto\"]\njsonschema = [\"s.json\"]\n\
322             [resources.pose]\nkind = \"stream\"\ntype = \"m.v1.Pose\"\n\
323             [resources.status]\nkind = \"state\"\ntype = \"json:Status\"\nencoding = \"cbor\"\n\
324             [resources.frame]\nkind = \"stream\"\ntype = { raw = \"application/x-flatbuffers\" }\n",
325            &[
326                (
327                    "m.proto",
328                    "syntax = \"proto3\";\npackage m.v1;\nmessage Pose { double x = 1; string frame = 2; }\n",
329                ),
330                (
331                    "s.json",
332                    r#"{"$defs": {"Status": {"type": "object", "properties": {"up": {"type": "boolean"}}}}}"#,
333                ),
334            ],
335        );
336        // protobuf: x = 1.5 (field 1, fixed64), frame = "map" (field 2).
337        let mut pose = vec![0x09];
338        pose.extend_from_slice(&1.5f64.to_le_bytes());
339        pose.extend_from_slice(&[0x12, 3, b'm', b'a', b'p']);
340        let ty = super::type_of(&b, "stream", "pose", "type").unwrap();
341        assert_eq!(
342            decode(&b, ty, Some("application/protobuf"), &pose),
343            Rendered::Value(json!({"x": 1.5, "frame": "map"}))
344        );
345        assert!(matches!(
346            decode(&b, ty, None, &[0xff, 0xff]),
347            Rendered::Undecodable { size: 2, declared, .. } if declared == "m.v1.Pose"
348        ));
349
350        // jsonschema, CBOR on the wire (the contract's encoding when the
351        // sample says nothing).
352        let mut cbor = Vec::new();
353        ciborium::into_writer(&json!({"up": true}), &mut cbor).unwrap();
354        let ty = super::type_of(&b, "state", "status", "type").unwrap();
355        assert_eq!(
356            decode(&b, ty, None, &cbor),
357            Rendered::Value(json!({"up": true}))
358        );
359        assert_eq!(
360            decode(&b, ty, Some("application/json"), br#"{"up":false}"#),
361            Rendered::Value(json!({"up": false})),
362            "the sample's Encoding comes first"
363        );
364        // Undecodable, named as a decoded value's type is (§7.2, 0.8).
365        assert!(matches!(
366            decode(&b, ty, None, b"{"),
367            Rendered::Undecodable { declared, reason, .. }
368                if declared == "json:Status" && reason.starts_with("as cbor: ")
369        ));
370
371        // raw: the declared type and the size.
372        let ty = super::type_of(&b, "stream", "frame", "type").unwrap();
373        assert_eq!(
374            decode(&b, ty, None, &[0; 42]),
375            Rendered::Opaque {
376                media_type: "application/x-flatbuffers".to_owned(),
377                size: 42
378            }
379        );
380    }
381}