1use std::collections::BTreeMap;
5
6use crate::class::{ClassDescriptor, ClassKey};
7use crate::descriptor::FunctionDescriptor;
8use crate::envelope::integer_member;
9use crate::error::{err, Error, ErrorCode, Result};
10use crate::json::{self, Value};
11use crate::lexical;
12use crate::model::{Scalar, Type};
13use crate::object::{format_object_key, parse_object_key, short_id, KeyValue, ObjectKey};
14use crate::schema;
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18#[non_exhaustive]
19pub enum DescribeKind {
20 Class,
22 Object,
24 Function,
27 Catalog,
30}
31
32#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
36pub struct DescribeTests {
37 pub count: u64,
39 pub branches: u64,
41 pub covered: u64,
43 pub counterexamples: u64,
45}
46
47impl DescribeTests {
48 fn check(&self) -> Result<()> {
49 if self.covered > self.branches {
50 return err(ErrorCode::Describe, "$.tests", "covered is at most branches");
51 }
52 Ok(())
53 }
54}
55
56#[derive(Clone, Debug, PartialEq, Eq, Hash)]
59pub struct DescribeSource {
60 pub name: String,
62 pub relayed_by: String,
64 pub takeover: String,
66}
67
68impl DescribeSource {
69 fn check(&self) -> Result<()> {
70 lexical::check_dns_name(&self.name, "$.source.name").map_err(|e| e.recode(ErrorCode::Describe))?;
71 lexical::check_dns_name(&self.relayed_by, "$.source.relayed_by").map_err(|e| e.recode(ErrorCode::Describe))?;
72 takeover_check(&self.takeover, "$.source.takeover")
73 }
74}
75
76#[derive(Clone, Debug, PartialEq, Eq, Hash)]
79#[non_exhaustive]
80pub struct DescribeExtension {
81 pub function: String,
83 pub fn_hash: String,
85 pub publisher: String,
87}
88
89fn takeover_check(u: &str, path: &str) -> Result<()> {
91 if !u.starts_with("https://") {
92 return err(ErrorCode::Describe, path, "takeover is an https:// URL");
93 }
94 lexical::check_licence(u, path).map_err(|e| e.recode(ErrorCode::Describe))
95}
96
97fn tests_of(v: &Value, p: &str) -> Result<DescribeTests> {
98 let m = schema::object_or(v, p, ErrorCode::Describe, "tests")?;
99 schema::exact(m, &["branches", "count", "counterexamples", "covered"], &[], p, ErrorCode::Describe)?;
100 let int =
101 |k: &str| integer_member(schema::get(m, k), &format!("{p}.{k}")).map_err(|e| e.recode(ErrorCode::Describe));
102 let t = DescribeTests {
103 count: int("count")?,
104 branches: int("branches")?,
105 covered: int("covered")?,
106 counterexamples: int("counterexamples")?,
107 };
108 t.check()?;
109 Ok(t)
110}
111
112fn source_of(v: &Value, p: &str) -> Result<DescribeSource> {
113 let m = schema::object_or(v, p, ErrorCode::Describe, "source")?;
114 schema::exact(m, &["name", "relayed_by", "takeover"], &[], p, ErrorCode::Describe)?;
115 let t = DescribeSource {
116 name: schema::string_or(m, "name", p, ErrorCode::Describe)?.into(),
117 relayed_by: schema::string_or(m, "relayed_by", p, ErrorCode::Describe)?.into(),
118 takeover: schema::string_or(m, "takeover", p, ErrorCode::Describe)?.into(),
119 };
120 t.check()?;
121 Ok(t)
122}
123
124fn signature(f: &FunctionDescriptor) -> Result<(Value, Value)> {
126 let fv = f.to_value();
127 let top = schema::object_or(&fv, "$", ErrorCode::Describe, "a function")?;
128 let sig = schema::object_or(schema::get(top, "signature"), "$.signature", ErrorCode::Describe, "a signature")?;
129 let pick = |name: &str| sig.iter().find(|(k, _)| k == name).map(|(_, v)| v.clone()).unwrap_or(Value::Null);
130 Ok((pick("args"), pick("returns")))
131}
132
133fn check_publisher(publisher: &str, name: &str) -> Result<()> {
136 lexical::check_dns_name(publisher, "$.publisher").map_err(|e| e.recode(ErrorCode::Describe))?;
137 if publisher != lexical::host_of(name) {
138 return err(ErrorCode::Describe, "$.publisher", "publisher is the host of the name's namespace");
139 }
140 Ok(())
141}
142
143const FACET_KEYS: [&str; 5] = ["domain", "frequency", "measure", "region", "thing"];
145
146fn facets_of(v: &Value, p: &str) -> Result<BTreeMap<String, Vec<String>>> {
149 let Value::Object(m) = v else {
150 return err(ErrorCode::Describe, p, "facets is an object of facet lists");
151 };
152 if m.is_empty() {
153 return err(ErrorCode::Describe, p, "facets, when present, holds at least one key");
154 }
155 let mut out = BTreeMap::new();
156 for (key, list) in m {
157 let kp = format!("{p}.{key}");
158 if !FACET_KEYS.contains(&key.as_str()) {
159 return err(ErrorCode::Describe, &kp, "a facet key is domain, frequency, measure, region or thing");
160 }
161 let Value::Array(items) = list else {
162 return err(ErrorCode::Describe, &kp, "a facet is a list of values");
163 };
164 if items.is_empty() || items.len() > 8 {
165 return err(ErrorCode::Describe, &kp, "a facet holds 1 to 8 values");
166 }
167 let mut values = Vec::with_capacity(items.len());
168 for item in items {
169 let Value::String(x) = item else {
170 return err(ErrorCode::Describe, &kp, "a value is a string");
171 };
172 if !lexical::is_name_grammar(x) || x.len() > 32 {
173 return err(ErrorCode::Describe, &kp, "a value is a name (2.2) of at most 32 bytes");
174 }
175 values.push(x.clone());
176 }
177 if values.windows(2).any(|w| w[0] >= w[1]) {
178 return err(ErrorCode::Describe, &kp, "a facet's values are ascending and unique");
179 }
180 out.insert(key.clone(), values);
181 }
182 Ok(out)
183}
184
185fn facets_value(f: &BTreeMap<String, Vec<String>>) -> Value {
187 Value::Object(
188 f.iter()
189 .map(|(k, vs)| (k.clone(), Value::Array(vs.iter().map(|x| Value::String(x.clone())).collect())))
190 .collect(),
191 )
192}
193
194fn optional_facets(m: &[(String, Value)], p: &str) -> Result<Option<BTreeMap<String, Vec<String>>>> {
196 match schema::opt(m, "facets") {
197 Some(f) => facets_of(f, &format!("{p}.facets")).map(Some),
198 None => Ok(None),
199 }
200}
201
202fn count_of(v: &Value, p: &str) -> Result<u64> {
204 integer_member(v, p).map_err(|e| e.recode(ErrorCode::Describe))
205}
206
207fn extensions_of(v: &Value, p: &str) -> Result<Vec<DescribeExtension>> {
210 let Value::Array(items) = v else {
211 return err(ErrorCode::Describe, p, "extensions is an array");
212 };
213 if items.is_empty() {
214 return err(ErrorCode::Describe, p, "extensions is omitted when there is none");
215 }
216 let mut out: Vec<DescribeExtension> = Vec::with_capacity(items.len());
217 for (i, item) in items.iter().enumerate() {
218 let ip = format!("{p}[{i}]");
219 let e = schema::object_or(item, &ip, ErrorCode::Describe, "an extension")?;
220 schema::exact(e, &["fn", "fn_hash", "publisher"], &[], &ip, ErrorCode::Describe)?;
221 let function = schema::string_or(e, "fn", &ip, ErrorCode::Describe)?;
222 lexical::check_function_name(function, &format!("{ip}.fn")).map_err(|e| e.recode(ErrorCode::Describe))?;
223 let fn_hash = schema::string_or(e, "fn_hash", &ip, ErrorCode::Describe)?;
224 lexical::check_hex(fn_hash, 64, &format!("{ip}.fn_hash")).map_err(|e| e.recode(ErrorCode::Describe))?;
225 let publisher = schema::string_or(e, "publisher", &ip, ErrorCode::Describe)?;
226 check_publisher(publisher, function)?;
227 if out.last().is_some_and(|last| last.function.as_str() >= function) {
228 return err(ErrorCode::Describe, p, "extensions is ascending by fn and unique");
229 }
230 out.push(DescribeExtension { function: function.into(), fn_hash: fn_hash.into(), publisher: publisher.into() });
231 }
232 Ok(out)
233}
234
235fn check_catalog(m: &[(String, Value)]) -> Result<Described> {
239 schema::exact(m, &["kind", "host", "domains", "rule"], &[], "$", ErrorCode::Describe)?;
240 let host = schema::string_or(m, "host", "$", ErrorCode::Describe)?;
241 lexical::check_dns_name(host, "$.host").map_err(|e| e.recode(ErrorCode::Describe))?;
242 let rule = schema::string_or(m, "rule", "$", ErrorCode::Describe)?;
243 if rule != format!("https://{host}/catalog/rule") {
244 return err(ErrorCode::Describe, "$.rule", "rule is the url of /catalog/rule on this host (https)");
245 }
246 let Value::Array(domains) = schema::get(m, "domains") else {
247 return err(ErrorCode::Describe, "$.domains", "domains is an array");
248 };
249 let mut previous: Option<(u64, &str)> = None;
250 for (i, d) in domains.iter().enumerate() {
251 let p = format!("$.domains[{i}]");
252 let dm = schema::object_or(d, &p, ErrorCode::Describe, "a domain")?;
253 schema::exact(dm, &["domain", "label", "names", "subjects", "top"], &[], &p, ErrorCode::Describe)?;
254 let domain = schema::string_or(dm, "domain", &p, ErrorCode::Describe)?;
255 lexical::check_name(domain, &format!("{p}.domain")).map_err(|e| e.recode(ErrorCode::Describe))?;
256 let label = schema::string_or(dm, "label", &p, ErrorCode::Describe)?;
257 if label.is_empty() || lexical::check_string(label, &p).is_err() {
258 return err(ErrorCode::Describe, &p, "a label is a string of 3.5");
259 }
260 count_of(schema::get(dm, "names"), &format!("{p}.names"))?;
261 let subjects = count_of(schema::get(dm, "subjects"), &format!("{p}.subjects"))?;
262 if let Some((n, name)) = previous {
264 if subjects > n || (subjects == n && name >= domain) {
265 return err(ErrorCode::Describe, &p, "domains are by subjects, descending, then by name");
266 }
267 }
268 previous = Some((subjects, domain));
269 let Value::Array(top) = schema::get(dm, "top") else {
270 return err(ErrorCode::Describe, &p, "top is an array of subjects");
271 };
272 if top.is_empty() || top.len() > 5 {
273 return err(ErrorCode::Describe, &p, "top holds 1 to 5 subjects");
274 }
275 for (j, t) in top.iter().enumerate() {
276 let tp = format!("{p}.top[{j}]");
277 let tm = schema::object_or(t, &tp, ErrorCode::Describe, "a top subject")?;
278 schema::exact(tm, &["subject", "label", "source"], &[], &tp, ErrorCode::Describe)?;
279 let subject = schema::string_or(tm, "subject", &tp, ErrorCode::Describe)?;
280 parse_object_key(subject).map_err(|e| e.recode(ErrorCode::Describe))?;
281 let source = schema::string_or(tm, "source", &tp, ErrorCode::Describe)?;
282 lexical::check_function_name(source, &format!("{tp}.source")).map_err(|e| e.recode(ErrorCode::Describe))?;
283 let label = schema::string_or(tm, "label", &tp, ErrorCode::Describe)?;
284 if label.is_empty() || lexical::check_string(label, &tp).is_err() {
285 return err(ErrorCode::Describe, &tp, "a label is a string of 3.5");
286 }
287 }
288 }
289 Ok(Described {
290 kind: DescribeKind::Catalog,
291 class: String::new(),
292 class_hash: String::new(),
293 object_id: None,
294 function: None,
295 fn_hash: None,
296 tests: None,
297 source: None,
298 publisher: None,
299 facets: None,
300 extensions: Vec::new(),
301 })
302}
303
304#[derive(Clone, Debug, PartialEq, Eq)]
308#[non_exhaustive]
309pub struct FindResult {
310 pub publisher: Option<String>,
312 pub source: Option<String>,
314 pub facets: Option<BTreeMap<String, Vec<String>>>,
316}
317
318pub fn check_find_result(result: &[u8]) -> Result<FindResult> {
320 let v = json::parse(result)?;
321 json::check_value_depth(&v)?;
322 let m = schema::object_or(&v, "$", ErrorCode::Describe, "a find result")?;
323 let name = match schema::opt(m, "fn") {
324 Some(Value::String(n)) => {
325 lexical::check_function_name(n, "$.fn").map_err(|e| e.recode(ErrorCode::Describe))?;
326 Some(n.as_str())
327 }
328 Some(_) => return err(ErrorCode::Describe, "$.fn", "fn is a string"),
329 None => None,
330 };
331 let publisher = match schema::opt(m, "publisher") {
332 Some(Value::String(p)) => {
333 let Some(n) = name else {
334 return err(ErrorCode::Describe, "$.publisher", "publisher is given with fn");
335 };
336 check_publisher(p, n)?;
337 Some(p.clone())
338 }
339 Some(_) => return err(ErrorCode::Describe, "$.publisher", "publisher is a string"),
340 None => None,
341 };
342 let source = match schema::opt(m, "source") {
343 Some(Value::String(s)) => {
344 lexical::check_dns_name(s, "$.source").map_err(|e| e.recode(ErrorCode::Describe))?;
345 Some(s.clone())
346 }
347 Some(_) => return err(ErrorCode::Describe, "$.source", "source is a DNS name"),
348 None => None,
349 };
350 let facets = optional_facets(m, "$")?;
351 Ok(FindResult { publisher, source, facets })
352}
353
354#[derive(Clone, Debug, PartialEq, Eq)]
356#[non_exhaustive]
357pub struct Described {
358 pub kind: DescribeKind,
360 pub class: String,
362 pub class_hash: String,
364 pub object_id: Option<String>,
366 pub function: Option<String>,
368 pub fn_hash: Option<String>,
370 pub tests: Option<DescribeTests>,
373 pub source: Option<DescribeSource>,
375 pub publisher: Option<String>,
378 pub facets: Option<BTreeMap<String, Vec<String>>>,
382 pub extensions: Vec<DescribeExtension>,
385}
386
387pub fn check_describe(answer: &[u8], held: &BTreeMap<String, ClassDescriptor>) -> Result<Described> {
392 check_describe_with(answer, held, &[])
393}
394
395pub fn check_describe_with(
415 answer: &[u8],
416 held: &BTreeMap<String, ClassDescriptor>,
417 functions: &[FunctionDescriptor],
418) -> Result<Described> {
419 let v = json::parse(answer)?;
420 json::check_value_depth(&v)?;
421 let m = schema::object_or(&v, "$", ErrorCode::Describe, "a describe answer")?;
422 match schema::string_or(m, "kind", "$", ErrorCode::Describe)? {
423 "class" => check_class(m, held, functions),
424 "object" => check_object(m, held),
425 "function" => check_function(m, functions),
426 "catalog" => check_catalog(m),
427 other => {
428 err(ErrorCode::Describe, "$.kind", format!("kind is class, object, function or catalog, not {other:?}"))
429 }
430 }
431}
432
433fn held_by_hash<'a>(held: &'a BTreeMap<String, ClassDescriptor>, class_hash: &str) -> Option<&'a ClassDescriptor> {
435 held.values().find(|h| h.hash() == class_hash)
436}
437
438fn check_class(
440 m: &[(String, Value)],
441 held: &BTreeMap<String, ClassDescriptor>,
442 functions: &[FunctionDescriptor],
443) -> Result<Described> {
444 schema::exact(
445 m,
446 &["kind", "class", "class_hash", "descriptor", "methods"],
447 &["publisher", "facets"],
448 "$",
449 ErrorCode::Describe,
450 )?;
451 let facets = optional_facets(m, "$")?;
452 let class = schema::string_or(m, "class", "$", ErrorCode::Describe)?;
453 lexical::check_function_name(class, "$.class").map_err(|e| e.recode(ErrorCode::Describe))?;
454 let publisher = match schema::opt(m, "publisher") {
455 Some(Value::String(p)) => {
456 check_publisher(p, class)?;
457 Some(p.clone())
458 }
459 Some(_) => return err(ErrorCode::Describe, "$.publisher", "publisher is a string"),
460 None => None,
461 };
462 let class_hash = schema::string_or(m, "class_hash", "$", ErrorCode::Describe)?;
463 lexical::check_hex(class_hash, 64, "$.class_hash").map_err(|e| e.recode(ErrorCode::Describe))?;
464 let descriptor =
465 ClassDescriptor::from_value(schema::get(m, "descriptor")).map_err(|e| e.recode(ErrorCode::Describe))?;
466 if descriptor.hash() != class_hash {
468 return err(ErrorCode::Describe, "$.class_hash", "class_hash is not the hash of the descriptor");
469 }
470 let methods = schema::object_or(schema::get(m, "methods"), "$.methods", ErrorCode::Describe, "methods")?;
471 if methods.len() != descriptor.methods.len() {
472 return err(ErrorCode::Describe, "$.methods", "a method table has every method of the class, and no other");
473 }
474 for (name, entry) in methods {
475 let p = format!("$.methods.{name}");
476 let Some(fn_hash) = descriptor.methods.get(name) else {
477 return err(ErrorCode::Describe, &p, "a method the class does not have");
478 };
479 let e = schema::object_or(entry, &p, ErrorCode::Describe, "a method entry")?;
480 let members: &[&str] = &["fn", "fn_hash", "args", "returns"];
481 schema::exact(e, members, &["description", "tests", "source"], &p, ErrorCode::Describe)?;
482 if let Some(t) = schema::opt(e, "tests") {
483 tests_of(t, &format!("{p}.tests"))?;
484 }
485 if let Some(src) = schema::opt(e, "source") {
486 source_of(src, &format!("{p}.source"))?;
487 }
488 if schema::string_or(e, "fn", &p, ErrorCode::Describe)? != format!("{class}/{name}") {
489 return err(ErrorCode::Describe, &p, "fn is the class's name and the method's");
490 }
491 if schema::string_or(e, "fn_hash", &p, ErrorCode::Describe)? != fn_hash {
492 return err(ErrorCode::Describe, &p, "fn_hash is the descriptor's hash for the method");
493 }
494 schema::object_or(schema::get(e, "args"), &p, ErrorCode::Describe, "args")?;
495 match schema::get(e, "returns") {
496 Value::String(_) | Value::Object(_) => {}
497 _ => return err(ErrorCode::Describe, &p, "returns is a type name or an object"),
498 }
499 if let Some(d) = schema::opt(e, "description") {
501 let Value::String(d) = d else {
502 return err(ErrorCode::Describe, &p, "description is a string");
503 };
504 if d.is_empty() || d.len() > 1024 || lexical::check_string(d, &p).is_err() {
505 return err(ErrorCode::Describe, &p, "description is a string of 1 to 1024 bytes");
506 }
507 }
508 }
509 let Some(held_class) = held_by_hash(held, class_hash) else {
511 return Ok(Described {
512 kind: DescribeKind::Class,
513 class: class.into(),
514 class_hash: class_hash.into(),
515 object_id: None,
516 function: None,
517 fn_hash: None,
518 tests: None,
519 source: None,
520 publisher,
521 facets,
522 extensions: Vec::new(),
523 });
524 };
525 if held_class.canonical() != descriptor.canonical() {
527 return err(ErrorCode::Describe, "$.descriptor", "the descriptor is not the class the caller holds");
528 }
529 for (name, entry) in methods {
532 let p = format!("$.methods.{name}");
533 let fn_hash = schema::string_or(
534 schema::object_or(entry, &p, ErrorCode::Describe, "a method entry")?,
535 "fn_hash",
536 &p,
537 ErrorCode::Describe,
538 )?;
539 let Some(f) = functions.iter().find(|f| f.hash() == fn_hash) else {
540 continue;
541 };
542 let e = schema::object_or(entry, &p, ErrorCode::Describe, "a method entry")?;
543 let signature = f.to_value();
544 let sig = schema::get(schema::object_or(&signature, &p, ErrorCode::Describe, "a function")?, "signature");
545 let sig = schema::object_or(sig, &p, ErrorCode::Describe, "a signature")?;
546 let (_, want_args) = sig
547 .iter()
548 .find(|(k, _)| k == "args")
549 .ok_or_else(|| Error::new(ErrorCode::Describe, &p, "a function has arguments"))?;
550 let want_args: Vec<(String, Value)> = match want_args {
551 Value::Object(a) => a.iter().filter(|(n, _)| !held_class.keys.contains_key(n)).cloned().collect(),
552 _ => return err(ErrorCode::Describe, &p, "a function's arguments are an object"),
553 };
554 if Value::Object(schema::object_or(schema::get(e, "args"), &p, ErrorCode::Describe, "args")?.to_vec()).to_jcs()
555 != Value::Object(want_args).to_jcs()
556 {
557 return err(ErrorCode::Describe, &p, "args are the function's arguments other than the class keys");
558 }
559 let want_returns = sig.iter().find(|(k, _)| k == "returns").map(|(_, v)| v.to_jcs());
560 if want_returns.as_deref() != Some(schema::get(e, "returns").to_jcs().as_slice()) {
561 return err(ErrorCode::Describe, &p, "returns is the function's returns");
562 }
563 }
564 Ok(Described {
565 kind: DescribeKind::Class,
566 class: class.into(),
567 class_hash: class_hash.into(),
568 object_id: None,
569 function: None,
570 fn_hash: None,
571 tests: None,
572 source: None,
573 publisher,
574 facets,
575 extensions: Vec::new(),
576 })
577}
578
579fn check_object(m: &[(String, Value)], held: &BTreeMap<String, ClassDescriptor>) -> Result<Described> {
581 schema::exact(
582 m,
583 &["kind", "object", "object_id", "short_id", "call", "methods"],
584 &["same_as", "resolved", "extensions"],
585 "$",
586 ErrorCode::Describe,
587 )?;
588 let object = schema::object_or(schema::get(m, "object"), "$.object", ErrorCode::Describe, "an object")?;
589 schema::exact(object, &["class", "class_hash", "keys"], &[], "$.object", ErrorCode::Describe)?;
590 let class = schema::string_or(object, "class", "$.object", ErrorCode::Describe)?;
591 lexical::check_function_name(class, "$.object.class").map_err(|e| e.recode(ErrorCode::Describe))?;
592 let class_hash = schema::string_or(object, "class_hash", "$.object", ErrorCode::Describe)?;
593 lexical::check_hex(class_hash, 64, "$.object.class_hash").map_err(|e| e.recode(ErrorCode::Describe))?;
594 let keys_v = schema::object_or(schema::get(object, "keys"), "$.object.keys", ErrorCode::Describe, "keys")?;
596 let mut keys = BTreeMap::new();
597 let mut typed: BTreeMap<&str, (&str, String)> = BTreeMap::new();
598 for (name, kv) in keys_v {
599 let p = format!("$.object.keys.{name}");
600 let kvm = schema::object_or(kv, &p, ErrorCode::Describe, "a typed scalar")?;
601 schema::exact(kvm, &["type", "value"], &[], &p, ErrorCode::Describe)?;
602 let ty_name = schema::string_or(kvm, "type", &p, ErrorCode::Describe)?;
603 let ty = match Type::from_name(ty_name) {
604 Some(t) if t != Type::Blob => t,
605 _ => return err(ErrorCode::Describe, &p, "a key's type is a scalar type of section 3"),
606 };
607 let text = match schema::get(kvm, "value") {
608 Value::String(s) => s.clone(),
609 Value::Bool(b) => b.to_string(),
610 _ => return err(ErrorCode::Describe, &p, "a value is a string or a boolean"),
611 };
612 let scalar = Scalar::from_lexical(ty, &text).map_err(|e| e.recode(ErrorCode::Describe))?;
613 keys.insert(name.clone(), KeyValue::Scalar(scalar));
614 typed.insert(name.as_str(), (ty_name, text));
615 }
616 let key = ObjectKey::new(class, keys).map_err(|e| e.recode(ErrorCode::Describe))?;
617 let expected = key.object_value(class_hash).map_err(|e| e.recode(ErrorCode::Describe))?;
618 if expected.to_jcs() != Value::Object(object.to_vec()).to_jcs() {
619 return err(ErrorCode::Describe, "$.object", "the object is not in its canonical form");
620 }
621 let object_id = key.object_id(class_hash).map_err(|e| e.recode(ErrorCode::Describe))?;
622 if schema::string_or(m, "object_id", "$", ErrorCode::Describe)? != object_id {
623 return err(ErrorCode::Describe, "$.object_id", "object_id is the object's id");
624 }
625 let short = short_id(&object_id).map_err(|e| e.recode(ErrorCode::Describe))?;
626 if schema::string_or(m, "short_id", "$", ErrorCode::Describe)? != short {
627 return err(ErrorCode::Describe, "$.short_id", "short_id is the first 12 digits of object_id");
628 }
629 if schema::string_or(m, "call", "$", ErrorCode::Describe)? != key.call_form() {
630 return err(ErrorCode::Describe, "$.call", "call is the object's canonical call form");
631 }
632 if let Some(r) = schema::opt(m, "resolved") {
633 check_object_resolved(r, &key)?;
634 }
635 let extensions = match schema::opt(m, "extensions") {
636 Some(e) => extensions_of(e, "$.extensions")?,
637 None => Vec::new(),
638 };
639 let methods = schema::get(m, "methods");
640 let Value::Array(names) = methods else {
641 return err(ErrorCode::Describe, "$.methods", "methods is an array of method names");
642 };
643 let mut previous: Option<&str> = None;
644 for item in names {
645 let Value::String(s) = item else {
646 return err(ErrorCode::Describe, "$.methods", "a method name is a string");
647 };
648 lexical::check_name(s, "$.methods").map_err(|e| e.recode(ErrorCode::Describe))?;
649 if previous.is_some_and(|p| p >= s.as_str()) {
650 return err(ErrorCode::Describe, "$.methods", "methods are ascending and unique");
651 }
652 previous = Some(s);
653 }
654 if let Some(same) = schema::opt(m, "same_as") {
655 let Value::Array(items) = same else {
656 return err(ErrorCode::Describe, "$.same_as", "same_as is an array of object keys");
657 };
658 if items.is_empty() {
659 return err(ErrorCode::Describe, "$.same_as", "same_as has at least one object key");
660 }
661 let mut previous: Option<&str> = None;
662 for item in items {
663 let Value::String(s) = item else {
664 return err(ErrorCode::Describe, "$.same_as", "an object key is a string");
665 };
666 parse_object_key(s).map_err(|e| e.recode(ErrorCode::Describe))?;
667 if previous.is_some_and(|p| p >= s.as_str()) {
668 return err(ErrorCode::Describe, "$.same_as", "same_as is ascending and unique");
669 }
670 previous = Some(s);
671 }
672 }
673 let Some(held_class) = held_by_hash(held, class_hash) else {
675 return Ok(Described {
676 kind: DescribeKind::Object,
677 class: class.into(),
678 class_hash: class_hash.into(),
679 object_id: Some(object_id),
680 function: None,
681 fn_hash: None,
682 tests: None,
683 source: None,
684 publisher: None,
685 facets: None,
686 extensions: extensions.clone(),
687 });
688 };
689 if keys_v.len() != held_class.keys.len() {
691 return err(ErrorCode::Describe, "$.object.keys", "an object binds exactly the class's keys");
692 }
693 for (name, (ty_name, text)) in &typed {
694 let p = format!("$.object.keys.{name}");
695 let Some(decl) = held_class.keys.get(*name) else {
696 return err(ErrorCode::Describe, &p, "a key the class does not have");
697 };
698 match decl {
699 ClassKey::Class(c) => {
700 if *ty_name != "string" {
701 return err(ErrorCode::Describe, &p, "a class-typed key is a string holding its encoding");
702 }
703 let nested = parse_object_key(text).map_err(|e| e.recode(ErrorCode::Describe))?;
704 if nested.class != *c {
705 return err(ErrorCode::Describe, &p, "a class-typed key is an object of its class");
706 }
707 }
708 ClassKey::Scalar { ty: want, key_normalisation, .. } => {
709 if *ty_name != want.as_str() {
710 return err(ErrorCode::Describe, &p, format!("the key is {}", want.as_str()));
711 }
712 if let Some(rule) = key_normalisation {
713 rule.check(text).map_err(|e| e.recode(ErrorCode::Describe))?;
714 }
715 }
716 }
717 }
718 let want: Vec<Value> = held_class.methods.keys().map(|k| Value::String(k.clone())).collect();
719 if *methods != Value::Array(want) {
720 return err(ErrorCode::Describe, "$.methods", "methods are the class's method names, ascending");
721 }
722 Ok(Described {
723 kind: DescribeKind::Object,
724 class: class.into(),
725 class_hash: class_hash.into(),
726 object_id: Some(object_id),
727 function: None,
728 fn_hash: None,
729 tests: None,
730 source: None,
731 publisher: None,
732 facets: None,
733 extensions,
734 })
735}
736
737fn check_object_resolved(v: &Value, key: &ObjectKey) -> Result<()> {
741 let m = schema::object_or(v, "$.resolved", ErrorCode::Describe, "resolved")?;
742 schema::exact(m, &["call", "resolutions"], &[], "$.resolved", ErrorCode::Describe)?;
743 if schema::string_or(m, "call", "$.resolved", ErrorCode::Describe)? != key.call_form() {
744 return err(ErrorCode::Describe, "$.resolved.call", "call is the object's own call form");
745 }
746 let Value::Array(items) = schema::get(m, "resolutions") else {
747 return err(ErrorCode::Describe, "$.resolved.resolutions", "resolutions is an array");
748 };
749 let [item] = items.as_slice() else {
750 return err(ErrorCode::Describe, "$.resolved.resolutions", "resolved holds the one lookup resolution");
751 };
752 let rp = "$.resolved.resolutions[0]";
753 let r = schema::object_or(item, rp, ErrorCode::Describe, "a resolution")?;
754 schema::exact(r, &["from", "kind", "to", "asof"], &[], rp, ErrorCode::Describe)?;
755 schema::string_or(r, "from", rp, ErrorCode::Describe)?;
756 if schema::string_or(r, "kind", rp, ErrorCode::Describe)? != "lookup" {
757 return err(ErrorCode::Describe, rp, "an object answer's resolution is a lookup");
758 }
759 if schema::string_or(r, "to", rp, ErrorCode::Describe)? != format_object_key(key) {
760 return err(ErrorCode::Describe, rp, "to is the key encoding of the object described");
761 }
762 let asof = schema::string_or(r, "asof", rp, ErrorCode::Describe)?;
763 lexical::check_instant(asof, rp).map_err(|e| e.recode(ErrorCode::Describe))?;
764 Ok(())
765}
766
767fn check_function(m: &[(String, Value)], functions: &[FunctionDescriptor]) -> Result<Described> {
770 schema::exact(
771 m,
772 &["kind", "fn", "fn_hash", "args", "returns"],
773 &["description", "tests", "source", "publisher", "facets"],
774 "$",
775 ErrorCode::Describe,
776 )?;
777 let facets = optional_facets(m, "$")?;
778 let name = schema::string_or(m, "fn", "$", ErrorCode::Describe)?;
779 lexical::check_function_name(name, "$.fn").map_err(|e| e.recode(ErrorCode::Describe))?;
780 let publisher = match schema::opt(m, "publisher") {
781 Some(Value::String(p)) => {
782 check_publisher(p, name)?;
783 Some(p.clone())
784 }
785 Some(_) => return err(ErrorCode::Describe, "$.publisher", "publisher is a string"),
786 None => None,
787 };
788 let fn_hash = schema::string_or(m, "fn_hash", "$", ErrorCode::Describe)?;
789 lexical::check_hex(fn_hash, 64, "$.fn_hash").map_err(|e| e.recode(ErrorCode::Describe))?;
790 let args = schema::get(m, "args");
791 schema::object_or(args, "$.args", ErrorCode::Describe, "args")?;
792 let returns = schema::get(m, "returns");
793 match returns {
794 Value::String(_) | Value::Object(_) => {}
795 _ => return err(ErrorCode::Describe, "$.returns", "returns is a type name or an object"),
796 }
797 if let Some(d) = schema::opt(m, "description") {
798 let Value::String(d) = d else { return err(ErrorCode::Describe, "$.description", "description is a string") };
799 if d.is_empty() || d.len() > 1024 || lexical::check_string(d, "$.description").is_err() {
800 return err(ErrorCode::Describe, "$.description", "description is a string of 1 to 1024 bytes");
801 }
802 }
803 let tests = match schema::opt(m, "tests") {
804 Some(t) => Some(tests_of(t, "$.tests")?),
805 None => None,
806 };
807 let source = match schema::opt(m, "source") {
808 Some(src) => Some(source_of(src, "$.source")?),
809 None => None,
810 };
811 if let Some(f) = functions.iter().find(|f| f.hash() == fn_hash) {
813 let (want_args, want_returns) = signature(f)?;
814 if args.to_jcs() != want_args.to_jcs() {
815 return err(ErrorCode::Describe, "$.args", "args are the function's arguments");
816 }
817 if returns.to_jcs() != want_returns.to_jcs() {
818 return err(ErrorCode::Describe, "$.returns", "returns is the function's returns");
819 }
820 }
821 Ok(Described {
822 kind: DescribeKind::Function,
823 class: String::new(),
824 class_hash: String::new(),
825 object_id: None,
826 function: Some(name.into()),
827 fn_hash: Some(fn_hash.into()),
828 tests,
829 source,
830 publisher,
831 facets,
832 extensions: Vec::new(),
833 })
834}
835
836#[derive(Clone, Debug, PartialEq)]
841pub struct FunctionAnswer {
842 name: String,
843 fn_hash: String,
844 args: Value,
845 returns: Value,
846 description: Option<String>,
847 tests: Option<DescribeTests>,
848 source: Option<DescribeSource>,
849 publisher: Option<String>,
850 facets: Option<BTreeMap<String, Vec<String>>>,
851}
852
853impl FunctionAnswer {
854 pub fn new(name: &str, d: &FunctionDescriptor) -> Result<FunctionAnswer> {
856 lexical::check_function_name(name, "$.fn").map_err(|e| e.recode(ErrorCode::Describe))?;
857 let (args, returns) = signature(d)?;
858 Ok(FunctionAnswer {
859 name: name.into(),
860 fn_hash: d.hash(),
861 args,
862 returns,
863 description: None,
864 tests: None,
865 source: None,
866 publisher: None,
867 facets: None,
868 })
869 }
870
871 pub fn with_description(self, description: &str) -> Result<FunctionAnswer> {
873 if description.is_empty()
874 || description.len() > 1024
875 || lexical::check_string(description, "$.description").is_err()
876 {
877 return err(ErrorCode::Describe, "$.description", "description is a string of 1 to 1024 bytes");
878 }
879 Ok(FunctionAnswer { description: Some(description.into()), ..self })
880 }
881
882 pub fn with_tests(self, tests: DescribeTests) -> Result<FunctionAnswer> {
884 tests.check()?;
885 Ok(FunctionAnswer { tests: Some(tests), ..self })
886 }
887
888 pub fn with_source(self, source: DescribeSource) -> Result<FunctionAnswer> {
891 source.check()?;
892 Ok(FunctionAnswer { source: Some(source), ..self })
893 }
894
895 pub fn with_publisher(self, publisher: &str) -> Result<FunctionAnswer> {
898 check_publisher(publisher, &self.name)?;
899 Ok(FunctionAnswer { publisher: Some(publisher.into()), ..self })
900 }
901
902 pub fn with_facets(self, facets: BTreeMap<String, Vec<String>>) -> Result<FunctionAnswer> {
905 let checked = facets_of(&facets_value(&facets), "$.facets")?;
906 Ok(FunctionAnswer { facets: Some(checked), ..self })
907 }
908
909 pub fn to_value(&self) -> Value {
911 let s = |x: &str| Value::String(x.into());
912 let mut m = vec![
913 ("kind".to_string(), s("function")),
914 ("fn".to_string(), s(&self.name)),
915 ("fn_hash".to_string(), s(&self.fn_hash)),
916 ("args".to_string(), self.args.clone()),
917 ("returns".to_string(), self.returns.clone()),
918 ];
919 if let Some(d) = &self.description {
920 m.push(("description".into(), s(d)));
921 }
922 if let Some(t) = &self.tests {
923 m.push((
924 "tests".into(),
925 Value::Object(vec![
926 ("branches".into(), num(t.branches)),
927 ("count".into(), num(t.count)),
928 ("counterexamples".into(), num(t.counterexamples)),
929 ("covered".into(), num(t.covered)),
930 ]),
931 ));
932 }
933 if let Some(p) = &self.publisher {
934 m.push(("publisher".into(), s(p)));
935 }
936 if let Some(f) = &self.facets {
937 m.push(("facets".into(), facets_value(f)));
938 }
939 if let Some(src) = &self.source {
940 m.push((
941 "source".into(),
942 Value::Object(vec![
943 ("name".into(), s(&src.name)),
944 ("relayed_by".into(), s(&src.relayed_by)),
945 ("takeover".into(), s(&src.takeover)),
946 ]),
947 ));
948 }
949 Value::Object(m)
950 }
951
952 pub fn to_json(&self) -> Vec<u8> {
954 self.to_value().to_jcs()
955 }
956}
957
958fn num(x: u64) -> Value {
960 json::parse(x.to_string().as_bytes()).unwrap_or(Value::Null)
961}