1use std::collections::BTreeMap;
13use std::str::FromStr;
14
15use base64::Engine as _;
16use serde::de::DeserializeOwned;
17use serde_json::{Map, Value};
18
19use crate::authoring::{Kind, ParamType};
20use crate::bundle::{Bundle, BundleError};
21use crate::canonical::FORMAT;
22use crate::contract::{
23 Body, Contract, Data, HistoryParams, Operation, Rate, Requirement, Resource, token_of,
24};
25use crate::grammar::{IfaceId, KindToken};
26use crate::schema::{Artifact, ArtifactData, SchemaKind, TypeId};
27use crate::template::Template;
28
29fn shape(at: &str, what: impl std::fmt::Display) -> BundleError {
30 BundleError::Shape(format!("{at}: {what}"))
31}
32
33fn member<'v>(m: &'v Map<String, Value>, k: &str, at: &str) -> Result<&'v Value, BundleError> {
34 m.get(k).ok_or_else(|| shape(at, format!("no `{k}`")))
35}
36
37fn object<'v>(v: &'v Value, at: &str) -> Result<&'v Map<String, Value>, BundleError> {
38 v.as_object().ok_or_else(|| shape(at, "not an object"))
39}
40
41fn text<'v>(m: &'v Map<String, Value>, k: &str, at: &str) -> Result<&'v str, BundleError> {
42 member(m, k, at)?
43 .as_str()
44 .ok_or_else(|| shape(at, format!("`{k}` is not a string")))
45}
46
47fn de<T: DeserializeOwned>(m: &Map<String, Value>, k: &str, at: &str) -> Result<T, BundleError> {
50 serde_json::from_value(member(m, k, at)?.clone()).map_err(|e| shape(at, format!("`{k}`: {e}")))
51}
52
53fn type_id(v: &Value, at: &str) -> Result<TypeId, BundleError> {
54 let m = object(v, at)?;
55 let name = || text(m, "name", at).map(str::to_owned);
56 let schema = || text(m, "schema", at).map(str::to_owned);
57 match text(m, "kind", at)? {
58 "protobuf" => Ok(TypeId::Protobuf {
59 name: name()?,
60 schema: schema()?,
61 }),
62 "jsonschema" => Ok(TypeId::JsonSchema {
63 name: name()?,
64 schema: schema()?,
65 }),
66 "packed" => Ok(TypeId::Packed {
67 name: name()?,
68 schema: schema()?,
69 }),
70 "raw" => Ok(TypeId::Raw {
71 media_type: text(m, "media_type", at)?.to_owned(),
72 media_param: de(m, "media_param", at)?,
73 }),
74 other => Err(shape(at, format!("unknown type kind {other:?}"))),
75 }
76}
77
78fn opt_type(m: &Map<String, Value>, k: &str, at: &str) -> Result<Option<TypeId>, BundleError> {
79 match member(m, k, at)? {
80 Value::Null => Ok(None),
81 v => type_id(v, &format!("{at}.{k}")).map(Some),
82 }
83}
84
85fn resource(v: &Value, i: usize) -> Result<Resource, BundleError> {
86 let at = format!("contract.resources[{i}]");
87 let m = object(v, &at)?;
88 let template = Template::parse(text(m, "template", &at)?).map_err(|e| shape(&at, e))?;
89 let kind: Kind = de(m, "kind", &at)?;
90 let token = KindToken::from_str(text(m, "token", &at)?).map_err(|e| shape(&at, e))?;
91 let explicit = matches!(token, KindToken::ExplicitStream | KindToken::ExplicitState);
92 if token_of(kind, explicit) != token {
93 return Err(shape(
94 &at,
95 format!("token {token} is not one of kind {:?}", kind.as_str()),
96 ));
97 }
98 let body = if kind == Kind::Operation {
99 Body::Operation(Operation {
100 request: type_id(member(m, "request", &at)?, &format!("{at}.request"))?,
101 response: type_id(member(m, "response", &at)?, &format!("{at}.response"))?,
102 error: opt_type(m, "error", &at)?,
103 summary: opt_type(m, "summary", &at)?,
104 encoding: de(m, "encoding", &at)?,
105 idempotent: de(m, "idempotent", &at)?,
106 fanout: de(m, "fanout", &at)?,
107 serving: de(m, "serving", &at)?,
108 replies: de(m, "replies", &at)?,
109 timeout_ms: de(m, "timeout_ms", &at)?,
110 priority: de(m, "priority", &at)?,
111 })
112 } else {
113 let rate = match member(m, "rate", &at)? {
114 Value::Null => None,
115 Value::String(s) => Some(
116 Rate::parse(s).ok_or_else(|| shape(&at, format!("`rate` {s:?} is not a rate")))?,
117 ),
118 _ => return Err(shape(&at, "`rate` is not a string")),
119 };
120 Body::Data(Data {
121 type_: type_id(member(m, "type", &at)?, &format!("{at}.type"))?,
122 attachment: opt_type(m, "attachment", &at)?,
123 encoding: de(m, "encoding", &at)?,
124 attachment_encoding: de(m, "attachment_encoding", &at)?,
125 reliability: de(m, "reliability", &at)?,
126 congestion: de(m, "congestion", &at)?,
127 priority: de(m, "priority", &at)?,
128 express: de(m, "express", &at)?,
129 history: de::<Option<HistoryParams>>(m, "history", &at)?,
130 frame: match m.get("frame") {
131 None => None,
132 Some(f) => Some(
133 crate::frame::FrameParams::from_canonical(f)
134 .map_err(|e| shape(&format!("{at}.frame"), e))?,
135 ),
136 },
137 rate,
138 retention_s: de(m, "retention_s", &at)?,
139 })
140 };
141 Ok(Resource {
142 template,
143 kind,
144 token,
145 doc: None,
146 params: de::<BTreeMap<String, ParamType>>(m, "params", &at)?,
147 cardinality: de(m, "cardinality", &at)?,
148 epoch: de(m, "epoch", &at)?,
149 optional: de(m, "optional", &at)?,
150 gate: de(m, "gate", &at)?,
151 deprecated: de(m, "deprecated", &at)?,
152 annotations: de(m, "annotations", &at)?,
153 body,
154 })
155}
156
157fn requirement(role: &str, v: &Value) -> Result<Requirement, BundleError> {
158 let at = format!("contract.requires.{role}");
159 let m = object(v, &at)?;
160 Ok(Requirement {
161 interface: IfaceId::from_str(text(m, "interface", &at)?).map_err(|e| shape(&at, e))?,
162 resources: de(m, "resources", &at)?,
163 cardinality: de(m, "cardinality", &at)?,
164 optional: de(m, "optional", &at)?,
165 doc: None,
166 annotations: de(m, "annotations", &at)?,
167 })
168}
169
170fn artifact(listed: &Value, b: &Bundle, i: usize) -> Result<(String, Artifact), BundleError> {
171 let at = format!("contract.schemas[{i}]");
172 let m = object(listed, &at)?;
173 let id = text(m, "id", &at)?;
174 let name = text(m, "name", &at)?.to_owned();
175 let entry = b
176 .schemas
177 .get(id)
178 .ok_or_else(|| BundleError::MissingSchema(id.to_owned()))?;
179 let data = entry
180 .get("data")
181 .ok_or_else(|| shape(&format!("schemas.{id}"), "no `data`"))?;
182 let (kind, data) = match text(m, "kind", &at)? {
183 "protobuf" => {
184 let b64 = data
185 .as_str()
186 .ok_or_else(|| shape(&format!("schemas.{id}"), "data is not base64"))?;
187 let bytes = base64::engine::general_purpose::STANDARD
188 .decode(b64)
189 .map_err(|e| shape(&format!("schemas.{id}"), e))?;
190 (SchemaKind::Protobuf, ArtifactData::Protobuf(bytes))
191 }
192 "jsonschema" => (SchemaKind::JsonSchema, ArtifactData::Json(data.clone())),
193 "packed" => (SchemaKind::Packed, ArtifactData::Json(data.clone())),
194 other => return Err(shape(&at, format!("unknown schema kind {other:?}"))),
195 };
196 Ok((id.to_owned(), Artifact { kind, name, data }))
197}
198
199impl Contract {
200 pub fn from_bundle(b: &Bundle) -> Result<Self, BundleError> {
215 let c = object(&b.contract, "contract")?;
216 let format = text(c, "format", "contract")?;
217 if format != FORMAT {
218 return Err(BundleError::Format(format.to_owned()));
219 }
220 let iface = IfaceId::from_str(text(c, "interface", "contract")?)
221 .map_err(|e| shape("contract", e))?;
222 let uses = de::<Vec<String>>(c, "uses", "contract")?
223 .iter()
224 .map(|u| IfaceId::from_str(u).map_err(|e| shape("contract.uses", e)))
225 .collect::<Result<Vec<_>, _>>()?;
226 let resources = member(c, "resources", "contract")?
227 .as_array()
228 .ok_or_else(|| shape("contract.resources", "not a list"))?
229 .iter()
230 .enumerate()
231 .map(|(i, r)| resource(r, i))
232 .collect::<Result<Vec<_>, _>>()?;
233 let requires = object(member(c, "requires", "contract")?, "contract.requires")?
234 .iter()
235 .map(|(role, r)| Ok((role.clone(), requirement(role, r)?)))
236 .collect::<Result<BTreeMap<_, _>, BundleError>>()?;
237 let artifacts = member(c, "schemas", "contract")?
238 .as_array()
239 .ok_or_else(|| shape("contract.schemas", "not a list"))?
240 .iter()
241 .enumerate()
242 .map(|(i, s)| artifact(s, b, i))
243 .collect::<Result<BTreeMap<_, _>, _>>()?;
244 Ok(Self {
245 iface,
246 minor: None,
247 summary: None,
248 uses,
249 resources,
250 requires,
251 artifacts,
252 })
253 }
254}
255
256#[cfg(test)]
257mod tests {
258 use std::path::{Path, PathBuf};
259
260 use crate::bundle::Bundle;
261 use crate::contract::{Contract, load_path};
262
263 fn tomls(dir: &Path, prefix: &str, out: &mut Vec<PathBuf>) {
264 for e in std::fs::read_dir(dir).unwrap().flatten() {
265 let p = e.path();
266 let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
267 if p.is_dir() && !name.starts_with('.') {
268 tomls(&p, prefix, out);
269 } else if name.starts_with(prefix)
270 && name.ends_with(".toml")
271 && !name.ends_with(".bindings.toml")
272 && !name.ends_with(".enrollment.toml")
273 && !name.ends_with(".face.toml")
274 {
275 out.push(p);
276 }
277 }
278 }
279
280 #[test]
285 fn a_bundle_round_trips_through_its_model() {
286 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
287 let mut files = Vec::new();
288 tomls(&root.join("spec/conformance/contracts"), "ok-", &mut files);
289 let ok = files.len();
290 tomls(&root.join("examples/zk2"), "", &mut files);
291 tomls(&root.join("spec/profiles"), "", &mut files);
292 assert!(ok >= 10 && files.len() >= ok + 24, "{} files", files.len());
293 for p in files {
294 let l = load_path(&p);
295 let c = l
296 .contract
297 .unwrap_or_else(|| panic!("{}: {}", p.display(), l.report));
298 let bytes = Bundle::build(&c).to_bytes();
299 let verified = Bundle::verify(&bytes).unwrap();
300 let back =
301 Contract::from_bundle(&verified).unwrap_or_else(|e| panic!("{}: {e}", p.display()));
302 assert_eq!(
303 Bundle::build(&back).to_bytes(),
304 bytes,
305 "{}: the round trip changed the bundle",
306 p.display()
307 );
308 assert_eq!(back.iface, c.iface);
309 assert_eq!(back.resources.len(), c.resources.len());
310 }
311 }
312
313 #[test]
314 fn a_bundle_that_is_not_canonical_is_refused() {
315 let src = "[interface]\nname = \"t\"\nmajor = 1\nminor = 0\n\
316 [resources.a]\nkind = \"stream\"\ntype = { raw = \"text/plain\" }\n";
317 let c = crate::contract::load_str(src, Path::new("."), None)
318 .contract
319 .unwrap();
320 let b = Bundle::build(&c);
321 let mut wrong = b.clone();
322 wrong.contract["resources"][0]["token"] = "@op".into();
323 assert_eq!(Contract::from_bundle(&wrong).unwrap_err().tag(), "shape");
324 let mut wrong = b.clone();
325 wrong.contract["resources"][0]
326 .as_object_mut()
327 .unwrap()
328 .remove("priority");
329 assert_eq!(Contract::from_bundle(&wrong).unwrap_err().tag(), "shape");
330 let mut wrong = b;
331 wrong.contract["format"] = "zk2-contract/draft-0".into();
332 assert_eq!(Contract::from_bundle(&wrong).unwrap_err().tag(), "format");
333 }
334}