Skip to main content

datumesh_core/
describe.rs

1//! describe answers (16.8, `spec-0.5.0`): a client's check of a mesh's describe answer for a
2//! class or for an object against the class descriptors the client holds.
3
4use 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/// Which kind of describe answer was checked.
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18#[non_exhaustive]
19pub enum DescribeKind {
20    /// `"kind": "class"`.
21    Class,
22    /// `"kind": "object"`.
23    Object,
24    /// `"kind": "function"` (since `spec-0.6.0`): a function name, with its `fn_hash`, `args`
25    /// and `returns`.
26    Function,
27    /// `"kind": "catalog"` (the classes round, C7): the catalogue root of a mesh, at
28    /// `describe/<host>/catalog`. It names no class and no function.
29    Catalog,
30}
31
32/// The `tests` member of a method entry or a function answer (16.8, `spec-0.6.0`): the mesh's
33/// statement of the tests it holds for the function hash (7.2). Four integers: `covered` is at
34/// most `branches`.
35#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
36pub struct DescribeTests {
37    /// The tests held.
38    pub count: u64,
39    /// The branches of the function.
40    pub branches: u64,
41    /// The branches the tests cover, at most `branches`.
42    pub covered: u64,
43    /// The tests whose expected result the function did not give.
44    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/// The `source` member of a relayed function (16.8, `spec-0.6.0`): where the function's value is
57/// taken from, the mesh that relays it, and where the source can take over publishing.
58#[derive(Clone, Debug, PartialEq, Eq, Hash)]
59pub struct DescribeSource {
60    /// The source's DNS name (2.1).
61    pub name: String,
62    /// The mesh's own host, which relays the function.
63    pub relayed_by: String,
64    /// An `https://` URL where the source can take over publishing these cells.
65    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/// One entry of `extensions` in an object answer (16.8, K9, the classes round): a function that extends the
77/// object's class (the extension-method rule of 16.3), by its name, its `fn_hash` and its publisher.
78#[derive(Clone, Debug, PartialEq, Eq, Hash)]
79#[non_exhaustive]
80pub struct DescribeExtension {
81    /// The function's full name (2.3).
82    pub function: String,
83    /// The function's hash: 64 lowercase hex digits.
84    pub fn_hash: String,
85    /// The publisher: the host of `function`, exactly (D108).
86    pub publisher: String,
87}
88
89/// A takeover URL (16.8, 8.1): `https://` by the licence URL rule, else `E_DESCRIBE`.
90fn 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
124/// A function's `args` and `returns`, as its descriptor's signature gives them (7).
125fn 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
133/// The optional `publisher` of a class or function answer (16.8, `spec-0.6.1`): a DNS name (2.1),
134/// and the host of `name` exactly. A domain of a later segment is not the publisher.
135fn 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
143/// The facet keys of 9.6 (the classes round), the only ones a `facets` member holds.
144const FACET_KEYS: [&str; 5] = ["domain", "frequency", "measure", "region", "thing"];
145
146/// The `facets` member (C2, 9.6, the classes round): an object of at least one of the five keys, each a list of 1 to
147/// 8 names (2.2) of at most 32 bytes, ascending and unique. `E_DESCRIBE` otherwise.
148fn 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
185/// Writes facets as the JSON object of the `facets` member (keys ascending, values as given).
186fn 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
194/// The optional `facets` member of a function answer or a class answer (C2).
195fn 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
202/// `E_DESCRIBE` for a non-negative integer member that is not one (C7).
203fn count_of(v: &Value, p: &str) -> Result<u64> {
204    integer_member(v, p).map_err(|e| e.recode(ErrorCode::Describe))
205}
206
207/// The optional `extensions` member of an object answer (K9, 16.8): a non-empty array, ascending by `fn` and
208/// unique, of entries with exactly `fn`, `fn_hash` and `publisher`; the publisher is the host of `fn`.
209fn 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
235/// A catalogue root (C7, 16.8, the classes round): `kind` `catalog`, `host`, `domains` and `rule`, nothing else. Each
236/// domain is a name with a label, its counts and up to five top subjects; the domains are by subjects,
237/// descending, then by name ascending, each once.
238fn 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        // Ascending by the order of the list: subjects descending, then name ascending, each domain once.
263        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/// A find result (C2, the classes round): a JSON object of the mesh's, of which `fn` (a function name, optional),
305/// `publisher` (the host of `fn`, with `fn`), `source` (a DNS name) and `facets` are checked. The rest is the
306/// mesh's and is not read. Text that is not strict JSON is 6.1's code, not `E_DESCRIBE`.
307#[derive(Clone, Debug, PartialEq, Eq)]
308#[non_exhaustive]
309pub struct FindResult {
310    /// The publisher of `fn`, when the result gives one.
311    pub publisher: Option<String>,
312    /// The source's DNS name, when the result gives one.
313    pub source: Option<String>,
314    /// The facets, when the result gives them (C2).
315    pub facets: Option<BTreeMap<String, Vec<String>>>,
316}
317
318/// Checks a find result (C2, the classes round) given as JSON text; see [`FindResult`].
319pub 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/// A describe answer that passed [`check_describe`].
355#[derive(Clone, Debug, PartialEq, Eq)]
356#[non_exhaustive]
357pub struct Described {
358    /// Whether the answer is for a class or an object.
359    pub kind: DescribeKind,
360    /// The class name (`class`, or `object.class`).
361    pub class: String,
362    /// The class hash (`class_hash`, or `object.class_hash`).
363    pub class_hash: String,
364    /// The object id (an object answer only).
365    pub object_id: Option<String>,
366    /// The function name (a function answer only, `spec-0.6.0`).
367    pub function: Option<String>,
368    /// The function hash (a function answer only, `spec-0.6.0`).
369    pub fn_hash: Option<String>,
370    /// The tests the mesh holds (a function answer's, or a method entry's, `spec-0.6.0`).
371    /// `None` for an object answer, a class, and any entry without `tests`.
372    pub tests: Option<DescribeTests>,
373    /// Where a relayed function's value is taken from (`spec-0.6.0`); `None` when not relayed.
374    pub source: Option<DescribeSource>,
375    /// The publisher (`spec-0.6.1`, 16.8): the host of a class's or a function's namespace, when the
376    /// answer gives one. `None` for an object answer and for an answer without `publisher`.
377    pub publisher: Option<String>,
378    /// The facets (the classes round, C2, 9.6): the facet lists of a function answer, a class answer or a
379    /// find result, by facet key (`domain`, `frequency`, `measure`, `region`, `thing`), each ascending
380    /// and unique. `None` when the answer has none, and for an object answer and a catalogue root.
381    pub facets: Option<BTreeMap<String, Vec<String>>>,
382    /// The functions that extend the object's class (the classes round, K9, 16.8): ascending by `function`,
383    /// empty when the answer has no `extensions`, and for every other kind of answer.
384    pub extensions: Vec<DescribeExtension>,
385}
386
387/// Checks a describe answer (16.8) given as JSON text against the classes the caller holds
388/// (flattened descriptors by class name, as `describe` vectors give them). Any failure is
389/// `E_DESCRIBE`, or the 6.1 code of a text that is not strict JSON. It is
390/// [`check_describe_with`] with no method function held.
391pub fn check_describe(answer: &[u8], held: &BTreeMap<String, ClassDescriptor>) -> Result<Described> {
392    check_describe_with(answer, held, &[])
393}
394
395/// Checks a describe answer (16.8), the six steps of its check, in order, reporting the first
396/// failure. What the client holds decides how far it goes:
397///
398/// 1. parse the text as strict JSON (6.1's codes, not `E_DESCRIBE`);
399/// 2. the shape: exactly the members of its `kind`, with their types, the names and hashes in
400///    their forms, each `description` 1 to 1024 bytes, an object's `same_as` ascending and unique;
401/// 3. internal consistency, which needs nothing held: a class's `class_hash` is its descriptor's
402///    hash and its method table has the descriptor's methods; an object's `object_id`, `short_id`
403///    and `call` follow from its `object`;
404/// 4. the held class is the one whose hash is the answer's `class_hash` (for an object,
405///    `object.class_hash`), never the one of that name; a client holding none stops here;
406/// 5. against the held class: a class's descriptor is the held one; an object's keys are the
407///    class's, of their types, with each class-typed key an encoding of an object of its class and
408///    each string key canonical under its rule (16.4); its methods are the class's;
409/// 6. against the held method functions (`functions`, found by `fn_hash`), for a class answer: each
410///    such method's `args` are exactly its function's arguments other than the class keys, and its
411///    `returns` exactly the function's `returns`. A method whose function is not held is unchecked.
412///
413/// An empty `functions` leaves step 6 unchecked, as [`check_describe`]. Since 0.3.8 (`spec-0.5.0`).
414pub 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
433/// The held class whose hash is `class_hash` (16.8 step 4): found by hash, never by name.
434fn 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
438/// A class answer (16.8): steps 2 and 3, then 4 to 6.
439fn 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    // Step 3.
467    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        // Step 2: a description is 1 to 1024 bytes, valid by 3.5.
500        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    // Step 4: nothing held for this class ends the check.
510    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    // Step 5: the descriptor is the held one (equal hashes: equal canonical bytes).
526    if held_class.canonical() != descriptor.canonical() {
527        return err(ErrorCode::Describe, "$.descriptor", "the descriptor is not the class the caller holds");
528    }
529    // Step 6: each method whose function is held has the function's arguments but the keys, and its
530    // returns.
531    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
579/// An object answer (16.8): steps 2 and 3, then 4 and 5 against the held class.
580fn 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    // Step 2: every key is a typed scalar valid by section 3 (a class-typed key is a string).
595    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    // Step 4: nothing held for this class ends the check after step 3.
674    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    // Step 5: the keys are the class's, of their types, and the methods are the class's.
690    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
737/// The `resolved` member of an object answer (K8, 16.7, the classes round): the object was named by a label. It is
738/// exactly `call` (the object's call form) and `resolutions`, which holds one `lookup` resolution (`from`, `kind`,
739/// `to` and `asof`): `to` is the key encoding of the object, and `asof` an instant.
740fn 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
767/// A function answer (16.8, `spec-0.6.0`): the shape, then step 6 against the held function
768/// descriptor when one is held: its `args`, all of them, and its `returns`.
769fn 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    // Step 6: the held function with this hash (none held: unchecked).
812    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/// A function answer (16.8, `spec-0.6.0`) built from its descriptor, with the members of
837/// [`check_describe_with`]: `kind` `"function"`, `fn`, `fn_hash`, `args` and `returns`, and
838/// optionally `description`, `tests` and `source`. The name is a function name (2.3); the
839/// description, tests and source are checked as the client checks them.
840#[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    /// The answer for the function named `name` (a function name, 2.3) with descriptor `d`.
855    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    /// With `description`: 1 to 1024 bytes, valid by 3.5 (`E_DESCRIBE` otherwise).
872    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    /// With `tests` (`E_DESCRIBE` when `covered` exceeds `branches`).
883    pub fn with_tests(self, tests: DescribeTests) -> Result<FunctionAnswer> {
884        tests.check()?;
885        Ok(FunctionAnswer { tests: Some(tests), ..self })
886    }
887
888    /// With `source`, for a relayed function (`E_DESCRIBE` for a name that is not a DNS name, a
889    /// `relayed_by` that is not one, or a takeover that is not `https://`).
890    pub fn with_source(self, source: DescribeSource) -> Result<FunctionAnswer> {
891        source.check()?;
892        Ok(FunctionAnswer { source: Some(source), ..self })
893    }
894
895    /// With `publisher` (`spec-0.6.1`): the host of the function's namespace, which must be exactly
896    /// that host (16.8; `E_DESCRIBE` for anything else, a domain of a later segment included).
897    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    /// With `facets` (C2, 9.6, the classes round): one to five keys, each a list of 1 to 8 names of at most 32 bytes,
903    /// ascending and unique (`E_DESCRIBE` otherwise).
904    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    /// The answer as a JSON value.
910    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    /// The answer's body: its canonical JSON text (JCS).
953    pub fn to_json(&self) -> Vec<u8> {
954        self.to_value().to_jcs()
955    }
956}
957
958/// A count as a JSON number (its canonical text).
959fn num(x: u64) -> Value {
960    json::parse(x.to_string().as_bytes()).unwrap_or(Value::Null)
961}