1use base64::Engine as _;
19use prost_reflect::{DescriptorPool, DynamicMessage};
20use serde_json::Value;
21
22use crate::bundle::Bundle;
23use crate::wire::Tag;
24
25#[derive(Debug, Clone, PartialEq)]
27pub enum Rendered {
28 Value(Value),
30 Opaque { media_type: String, size: usize },
33 Undecodable {
36 declared: String,
37 size: usize,
38 reason: String,
39 },
40}
41
42#[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#[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
75fn contract_encoding(bundle: &Bundle, ty: &Value) -> Option<String> {
78 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
100pub struct Context {
101 pub tag: Option<Tag>,
104 pub epoch: Option<i64>,
108}
109
110impl Context {
111 #[must_use]
113 pub fn tagged(tag: Tag) -> Self {
114 Self {
115 tag: Some(tag),
116 epoch: None,
117 }
118 }
119}
120
121#[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#[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 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 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 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#[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
264fn 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 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 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 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 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}