use base64::Engine as _;
use prost_reflect::{DescriptorPool, DynamicMessage};
use serde_json::Value;
use crate::bundle::Bundle;
use crate::wire::Tag;
#[derive(Debug, Clone, PartialEq)]
pub enum Rendered {
Value(Value),
Opaque { media_type: String, size: usize },
Undecodable {
declared: String,
size: usize,
reason: String,
},
}
#[must_use]
pub fn declared(ty: &Value) -> String {
let name = ty["name"].as_str().unwrap_or_default();
match ty["kind"].as_str() {
Some("jsonschema") => format!("json:{name}"),
Some("packed") => format!("packed:{name}"),
Some("raw") => ty["media_type"].as_str().unwrap_or_default().to_owned(),
_ => name.to_owned(),
}
}
#[must_use]
pub fn type_of<'b>(
bundle: &'b Bundle,
token: &str,
template: &str,
member: &str,
) -> Option<&'b Value> {
bundle.contract["resources"]
.as_array()?
.iter()
.find(|r| r["token"] == token && r["template"] == template)
.map(|r| &r[member])
.filter(|t| t.is_object())
}
fn contract_encoding(bundle: &Bundle, ty: &Value) -> Option<String> {
bundle.contract["resources"]
.as_array()?
.iter()
.find_map(|r| {
if &r["attachment"] == ty {
r["attachment_encoding"].as_str().map(str::to_owned)
} else if ["type", "request", "response", "error", "summary"]
.iter()
.any(|m| &r[*m] == ty)
{
r["encoding"].as_str().map(str::to_owned)
} else {
None
}
})
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Context {
pub tag: Option<Tag>,
pub epoch: Option<i64>,
}
impl Context {
#[must_use]
pub fn tagged(tag: Tag) -> Self {
Self {
tag: Some(tag),
epoch: None,
}
}
}
#[must_use]
pub fn decode(bundle: &Bundle, ty: &Value, encoding: Option<&str>, bytes: &[u8]) -> Rendered {
decode_in(bundle, ty, encoding, bytes, Context::default())
}
#[must_use]
pub fn decode_in(
bundle: &Bundle,
ty: &Value,
encoding: Option<&str>,
bytes: &[u8],
cx: Context,
) -> Rendered {
let size = bytes.len();
let name = ty["name"].as_str().unwrap_or_default();
match ty["kind"].as_str() {
Some("raw") => {
let declared = ty["media_type"].as_str().unwrap_or_default();
let media_type = match encoding {
Some(e) if declared.ends_with("/*") => e.to_owned(),
_ => declared.to_owned(),
};
Rendered::Opaque { media_type, size }
}
Some("protobuf") => {
let fail = |reason: String| Rendered::Undecodable {
declared: declared(ty),
size,
reason,
};
let Some(pool) = artifact(bundle, ty).and_then(|data| {
let b = base64::engine::general_purpose::STANDARD
.decode(data.as_str()?)
.ok()?;
DescriptorPool::decode(b.as_slice()).ok()
}) else {
return fail("the bundle's descriptor set does not decode".to_owned());
};
let Some(desc) = pool.get_message_by_name(name) else {
return fail(format!("{name} is not in the bundle's descriptor set"));
};
match DynamicMessage::decode(desc, bytes) {
Ok(m) => match serde_json::to_value(&m) {
Ok(v) => Rendered::Value(v),
Err(e) => fail(e.to_string()),
},
Err(e) => fail(e.to_string()),
}
}
Some("jsonschema") => {
let wire = match encoding {
Some(e) if e.starts_with("application/cbor") => "cbor".to_owned(),
Some(e) if e.starts_with("application/json") => "json".to_owned(),
_ => contract_encoding(bundle, ty).unwrap_or_else(|| "json".to_owned()),
};
let decoded = if wire == "cbor" {
ciborium::from_reader::<ciborium::Value, _>(bytes)
.map_err(|e| e.to_string())
.and_then(|v| cbor_to_json(&v))
} else {
serde_json::from_slice::<Value>(bytes).map_err(|e| e.to_string())
};
match decoded {
Ok(v) => Rendered::Value(v),
Err(reason) => Rendered::Undecodable {
declared: declared(ty),
size,
reason: format!("as {wire}: {reason}"),
},
}
}
Some("packed") => {
let fail = |reason: String| Rendered::Undecodable {
declared: declared(ty),
size,
reason,
};
let Some(tag) = cx.tag else {
return fail(
"a packed record travels in an envelope, and this one came in none, so it \
has no tag to read it by"
.to_owned(),
);
};
let layout = match artifact(bundle, ty)
.ok_or_else(|| "the bundle carries no such packed artifact".to_owned())
.and_then(|doc| crate::packed::layout_in(doc, name))
{
Ok(l) => l,
Err(reason) => return fail(reason),
};
match layout.read(tag.get(), bytes, cx.epoch) {
Ok(v) => Rendered::Value(v),
Err(r) => fail(format!("refused by its layout, {}", r.reason())),
}
}
_ => Rendered::Undecodable {
declared: ty.to_string(),
size,
reason: "not a type reference".to_owned(),
},
}
}
#[must_use]
pub fn epoch_assumed(bundle: &Bundle, ty: &Value, cx: Context) -> Option<i64> {
if cx.epoch.is_some() || ty["kind"] != "packed" {
return None;
}
let layout = crate::packed::layout_in(artifact(bundle, ty)?, ty["name"].as_str()?).ok()?;
layout
.fields()
.any(|f| matches!(f.kind, crate::packed::FieldKind::Time { .. }))
.then_some(crate::packed::DEFAULT_EPOCH)
}
fn artifact<'b>(bundle: &'b Bundle, ty: &Value) -> Option<&'b Value> {
bundle
.schemas
.get(ty["schema"].as_str()?)
.map(|s| &s["data"])
}
fn cbor_to_json(v: &ciborium::Value) -> Result<Value, String> {
use ciborium::Value as C;
Ok(match v {
C::Null => Value::Null,
C::Bool(b) => Value::Bool(*b),
C::Integer(i) => {
let n: i128 = (*i).into();
i64::try_from(n)
.map(Value::from)
.or_else(|_| u64::try_from(n).map(Value::from))
.map_err(|_| format!("integer {n} out of range"))?
}
C::Float(f) => serde_json::Number::from_f64(*f)
.map(Value::Number)
.ok_or_else(|| format!("{f} has no JSON form"))?,
C::Text(s) => Value::String(s.clone()),
C::Bytes(b) => Value::String(base64::engine::general_purpose::STANDARD.encode(b)),
C::Array(a) => Value::Array(a.iter().map(cbor_to_json).collect::<Result<_, _>>()?),
C::Map(m) => {
let mut out = serde_json::Map::new();
for (k, v) in m {
let C::Text(k) = k else {
return Err("a map key that is not text".to_owned());
};
out.insert(k.clone(), cbor_to_json(v)?);
}
Value::Object(out)
}
C::Tag(_, inner) => cbor_to_json(inner)?,
_ => return Err("an unsupported CBOR value".to_owned()),
})
}
#[cfg(test)]
mod tests {
use super::{Rendered, decode};
use crate::bundle::Bundle;
use serde_json::json;
fn bundle(toml: &str, files: &[(&str, &str)]) -> Bundle {
let dir =
std::env::temp_dir().join(format!("zk2-decode-{}-{}", std::process::id(), toml.len()));
std::fs::create_dir_all(&dir).unwrap();
for (name, text) in files {
std::fs::write(dir.join(name), text).unwrap();
}
let l = crate::contract::load_str(toml, &dir, None);
let c = l.contract.unwrap_or_else(|| panic!("{}", l.report));
Bundle::build(&c)
}
#[test]
fn protobuf_json_cbor_and_raw_render_honestly() {
let b = bundle(
"[interface]\nname = \"m\"\nmajor = 1\nminor = 0\n\
[schemas]\nprotobuf = [\"m.proto\"]\njsonschema = [\"s.json\"]\n\
[resources.pose]\nkind = \"stream\"\ntype = \"m.v1.Pose\"\n\
[resources.status]\nkind = \"state\"\ntype = \"json:Status\"\nencoding = \"cbor\"\n\
[resources.frame]\nkind = \"stream\"\ntype = { raw = \"application/x-flatbuffers\" }\n",
&[
(
"m.proto",
"syntax = \"proto3\";\npackage m.v1;\nmessage Pose { double x = 1; string frame = 2; }\n",
),
(
"s.json",
r#"{"$defs": {"Status": {"type": "object", "properties": {"up": {"type": "boolean"}}}}}"#,
),
],
);
let mut pose = vec![0x09];
pose.extend_from_slice(&1.5f64.to_le_bytes());
pose.extend_from_slice(&[0x12, 3, b'm', b'a', b'p']);
let ty = super::type_of(&b, "stream", "pose", "type").unwrap();
assert_eq!(
decode(&b, ty, Some("application/protobuf"), &pose),
Rendered::Value(json!({"x": 1.5, "frame": "map"}))
);
assert!(matches!(
decode(&b, ty, None, &[0xff, 0xff]),
Rendered::Undecodable { size: 2, declared, .. } if declared == "m.v1.Pose"
));
let mut cbor = Vec::new();
ciborium::into_writer(&json!({"up": true}), &mut cbor).unwrap();
let ty = super::type_of(&b, "state", "status", "type").unwrap();
assert_eq!(
decode(&b, ty, None, &cbor),
Rendered::Value(json!({"up": true}))
);
assert_eq!(
decode(&b, ty, Some("application/json"), br#"{"up":false}"#),
Rendered::Value(json!({"up": false})),
"the sample's Encoding comes first"
);
assert!(matches!(
decode(&b, ty, None, b"{"),
Rendered::Undecodable { declared, reason, .. }
if declared == "json:Status" && reason.starts_with("as cbor: ")
));
let ty = super::type_of(&b, "stream", "frame", "type").unwrap();
assert_eq!(
decode(&b, ty, None, &[0; 42]),
Rendered::Opaque {
media_type: "application/x-flatbuffers".to_owned(),
size: 42
}
);
}
}