datumesh-core 0.3.14

Datumesh protocol core: strict JSON and JCS, canonical forms, cell URIs, receipts, keys, envelopes and offline verification.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
//! describe answers (16.8, `spec-0.5.0`): a client's check of a mesh's describe answer for a
//! class or for an object against the class descriptors the client holds.

use std::collections::BTreeMap;

use crate::class::{ClassDescriptor, ClassKey};
use crate::descriptor::FunctionDescriptor;
use crate::envelope::integer_member;
use crate::error::{err, Error, ErrorCode, Result};
use crate::json::{self, Value};
use crate::lexical;
use crate::model::{Scalar, Type};
use crate::object::{format_object_key, parse_object_key, short_id, KeyValue, ObjectKey};
use crate::schema;

/// Which kind of describe answer was checked.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DescribeKind {
    /// `"kind": "class"`.
    Class,
    /// `"kind": "object"`.
    Object,
    /// `"kind": "function"` (since `spec-0.6.0`): a function name, with its `fn_hash`, `args`
    /// and `returns`.
    Function,
    /// `"kind": "catalog"` (the classes round, C7): the catalogue root of a mesh, at
    /// `describe/<host>/catalog`. It names no class and no function.
    Catalog,
}

/// The `tests` member of a method entry or a function answer (16.8, `spec-0.6.0`): the mesh's
/// statement of the tests it holds for the function hash (7.2). Four integers: `covered` is at
/// most `branches`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct DescribeTests {
    /// The tests held.
    pub count: u64,
    /// The branches of the function.
    pub branches: u64,
    /// The branches the tests cover, at most `branches`.
    pub covered: u64,
    /// The tests whose expected result the function did not give.
    pub counterexamples: u64,
}

impl DescribeTests {
    fn check(&self) -> Result<()> {
        if self.covered > self.branches {
            return err(ErrorCode::Describe, "$.tests", "covered is at most branches");
        }
        Ok(())
    }
}

/// The `source` member of a relayed function (16.8, `spec-0.6.0`): where the function's value is
/// taken from, the mesh that relays it, and where the source can take over publishing.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct DescribeSource {
    /// The source's DNS name (2.1).
    pub name: String,
    /// The mesh's own host, which relays the function.
    pub relayed_by: String,
    /// An `https://` URL where the source can take over publishing these cells.
    pub takeover: String,
}

impl DescribeSource {
    fn check(&self) -> Result<()> {
        lexical::check_dns_name(&self.name, "$.source.name").map_err(|e| e.recode(ErrorCode::Describe))?;
        lexical::check_dns_name(&self.relayed_by, "$.source.relayed_by").map_err(|e| e.recode(ErrorCode::Describe))?;
        takeover_check(&self.takeover, "$.source.takeover")
    }
}

/// One entry of `extensions` in an object answer (16.8, K9, the classes round): a function that extends the
/// object's class (the extension-method rule of 16.3), by its name, its `fn_hash` and its publisher.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct DescribeExtension {
    /// The function's full name (2.3).
    pub function: String,
    /// The function's hash: 64 lowercase hex digits.
    pub fn_hash: String,
    /// The publisher: the host of `function`, exactly (D108).
    pub publisher: String,
}

/// A takeover URL (16.8, 8.1): `https://` by the licence URL rule, else `E_DESCRIBE`.
fn takeover_check(u: &str, path: &str) -> Result<()> {
    if !u.starts_with("https://") {
        return err(ErrorCode::Describe, path, "takeover is an https:// URL");
    }
    lexical::check_licence(u, path).map_err(|e| e.recode(ErrorCode::Describe))
}

fn tests_of(v: &Value, p: &str) -> Result<DescribeTests> {
    let m = schema::object_or(v, p, ErrorCode::Describe, "tests")?;
    schema::exact(m, &["branches", "count", "counterexamples", "covered"], &[], p, ErrorCode::Describe)?;
    let int =
        |k: &str| integer_member(schema::get(m, k), &format!("{p}.{k}")).map_err(|e| e.recode(ErrorCode::Describe));
    let t = DescribeTests {
        count: int("count")?,
        branches: int("branches")?,
        covered: int("covered")?,
        counterexamples: int("counterexamples")?,
    };
    t.check()?;
    Ok(t)
}

fn source_of(v: &Value, p: &str) -> Result<DescribeSource> {
    let m = schema::object_or(v, p, ErrorCode::Describe, "source")?;
    schema::exact(m, &["name", "relayed_by", "takeover"], &[], p, ErrorCode::Describe)?;
    let t = DescribeSource {
        name: schema::string_or(m, "name", p, ErrorCode::Describe)?.into(),
        relayed_by: schema::string_or(m, "relayed_by", p, ErrorCode::Describe)?.into(),
        takeover: schema::string_or(m, "takeover", p, ErrorCode::Describe)?.into(),
    };
    t.check()?;
    Ok(t)
}

/// A function's `args` and `returns`, as its descriptor's signature gives them (7).
fn signature(f: &FunctionDescriptor) -> Result<(Value, Value)> {
    let fv = f.to_value();
    let top = schema::object_or(&fv, "$", ErrorCode::Describe, "a function")?;
    let sig = schema::object_or(schema::get(top, "signature"), "$.signature", ErrorCode::Describe, "a signature")?;
    let pick = |name: &str| sig.iter().find(|(k, _)| k == name).map(|(_, v)| v.clone()).unwrap_or(Value::Null);
    Ok((pick("args"), pick("returns")))
}

/// The optional `publisher` of a class or function answer (16.8, `spec-0.6.1`): a DNS name (2.1),
/// and the host of `name` exactly. A domain of a later segment is not the publisher.
fn check_publisher(publisher: &str, name: &str) -> Result<()> {
    lexical::check_dns_name(publisher, "$.publisher").map_err(|e| e.recode(ErrorCode::Describe))?;
    if publisher != lexical::host_of(name) {
        return err(ErrorCode::Describe, "$.publisher", "publisher is the host of the name's namespace");
    }
    Ok(())
}

/// The facet keys of 9.6 (the classes round), the only ones a `facets` member holds.
const FACET_KEYS: [&str; 5] = ["domain", "frequency", "measure", "region", "thing"];

/// 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
/// 8 names (2.2) of at most 32 bytes, ascending and unique. `E_DESCRIBE` otherwise.
fn facets_of(v: &Value, p: &str) -> Result<BTreeMap<String, Vec<String>>> {
    let Value::Object(m) = v else {
        return err(ErrorCode::Describe, p, "facets is an object of facet lists");
    };
    if m.is_empty() {
        return err(ErrorCode::Describe, p, "facets, when present, holds at least one key");
    }
    let mut out = BTreeMap::new();
    for (key, list) in m {
        let kp = format!("{p}.{key}");
        if !FACET_KEYS.contains(&key.as_str()) {
            return err(ErrorCode::Describe, &kp, "a facet key is domain, frequency, measure, region or thing");
        }
        let Value::Array(items) = list else {
            return err(ErrorCode::Describe, &kp, "a facet is a list of values");
        };
        if items.is_empty() || items.len() > 8 {
            return err(ErrorCode::Describe, &kp, "a facet holds 1 to 8 values");
        }
        let mut values = Vec::with_capacity(items.len());
        for item in items {
            let Value::String(x) = item else {
                return err(ErrorCode::Describe, &kp, "a value is a string");
            };
            if !lexical::is_name_grammar(x) || x.len() > 32 {
                return err(ErrorCode::Describe, &kp, "a value is a name (2.2) of at most 32 bytes");
            }
            values.push(x.clone());
        }
        if values.windows(2).any(|w| w[0] >= w[1]) {
            return err(ErrorCode::Describe, &kp, "a facet's values are ascending and unique");
        }
        out.insert(key.clone(), values);
    }
    Ok(out)
}

/// Writes facets as the JSON object of the `facets` member (keys ascending, values as given).
fn facets_value(f: &BTreeMap<String, Vec<String>>) -> Value {
    Value::Object(
        f.iter()
            .map(|(k, vs)| (k.clone(), Value::Array(vs.iter().map(|x| Value::String(x.clone())).collect())))
            .collect(),
    )
}

/// The optional `facets` member of a function answer or a class answer (C2).
fn optional_facets(m: &[(String, Value)], p: &str) -> Result<Option<BTreeMap<String, Vec<String>>>> {
    match schema::opt(m, "facets") {
        Some(f) => facets_of(f, &format!("{p}.facets")).map(Some),
        None => Ok(None),
    }
}

/// `E_DESCRIBE` for a non-negative integer member that is not one (C7).
fn count_of(v: &Value, p: &str) -> Result<u64> {
    integer_member(v, p).map_err(|e| e.recode(ErrorCode::Describe))
}

/// The optional `extensions` member of an object answer (K9, 16.8): a non-empty array, ascending by `fn` and
/// unique, of entries with exactly `fn`, `fn_hash` and `publisher`; the publisher is the host of `fn`.
fn extensions_of(v: &Value, p: &str) -> Result<Vec<DescribeExtension>> {
    let Value::Array(items) = v else {
        return err(ErrorCode::Describe, p, "extensions is an array");
    };
    if items.is_empty() {
        return err(ErrorCode::Describe, p, "extensions is omitted when there is none");
    }
    let mut out: Vec<DescribeExtension> = Vec::with_capacity(items.len());
    for (i, item) in items.iter().enumerate() {
        let ip = format!("{p}[{i}]");
        let e = schema::object_or(item, &ip, ErrorCode::Describe, "an extension")?;
        schema::exact(e, &["fn", "fn_hash", "publisher"], &[], &ip, ErrorCode::Describe)?;
        let function = schema::string_or(e, "fn", &ip, ErrorCode::Describe)?;
        lexical::check_function_name(function, &format!("{ip}.fn")).map_err(|e| e.recode(ErrorCode::Describe))?;
        let fn_hash = schema::string_or(e, "fn_hash", &ip, ErrorCode::Describe)?;
        lexical::check_hex(fn_hash, 64, &format!("{ip}.fn_hash")).map_err(|e| e.recode(ErrorCode::Describe))?;
        let publisher = schema::string_or(e, "publisher", &ip, ErrorCode::Describe)?;
        check_publisher(publisher, function)?;
        if out.last().is_some_and(|last| last.function.as_str() >= function) {
            return err(ErrorCode::Describe, p, "extensions is ascending by fn and unique");
        }
        out.push(DescribeExtension { function: function.into(), fn_hash: fn_hash.into(), publisher: publisher.into() });
    }
    Ok(out)
}

/// A catalogue root (C7, 16.8, the classes round): `kind` `catalog`, `host`, `domains` and `rule`, nothing else. Each
/// domain is a name with a label, its counts and up to five top subjects; the domains are by subjects,
/// descending, then by name ascending, each once.
fn check_catalog(m: &[(String, Value)]) -> Result<Described> {
    schema::exact(m, &["kind", "host", "domains", "rule"], &[], "$", ErrorCode::Describe)?;
    let host = schema::string_or(m, "host", "$", ErrorCode::Describe)?;
    lexical::check_dns_name(host, "$.host").map_err(|e| e.recode(ErrorCode::Describe))?;
    let rule = schema::string_or(m, "rule", "$", ErrorCode::Describe)?;
    if rule != format!("https://{host}/catalog/rule") {
        return err(ErrorCode::Describe, "$.rule", "rule is the url of /catalog/rule on this host (https)");
    }
    let Value::Array(domains) = schema::get(m, "domains") else {
        return err(ErrorCode::Describe, "$.domains", "domains is an array");
    };
    let mut previous: Option<(u64, &str)> = None;
    for (i, d) in domains.iter().enumerate() {
        let p = format!("$.domains[{i}]");
        let dm = schema::object_or(d, &p, ErrorCode::Describe, "a domain")?;
        schema::exact(dm, &["domain", "label", "names", "subjects", "top"], &[], &p, ErrorCode::Describe)?;
        let domain = schema::string_or(dm, "domain", &p, ErrorCode::Describe)?;
        lexical::check_name(domain, &format!("{p}.domain")).map_err(|e| e.recode(ErrorCode::Describe))?;
        let label = schema::string_or(dm, "label", &p, ErrorCode::Describe)?;
        if label.is_empty() || lexical::check_string(label, &p).is_err() {
            return err(ErrorCode::Describe, &p, "a label is a string of 3.5");
        }
        count_of(schema::get(dm, "names"), &format!("{p}.names"))?;
        let subjects = count_of(schema::get(dm, "subjects"), &format!("{p}.subjects"))?;
        // Ascending by the order of the list: subjects descending, then name ascending, each domain once.
        if let Some((n, name)) = previous {
            if subjects > n || (subjects == n && name >= domain) {
                return err(ErrorCode::Describe, &p, "domains are by subjects, descending, then by name");
            }
        }
        previous = Some((subjects, domain));
        let Value::Array(top) = schema::get(dm, "top") else {
            return err(ErrorCode::Describe, &p, "top is an array of subjects");
        };
        if top.is_empty() || top.len() > 5 {
            return err(ErrorCode::Describe, &p, "top holds 1 to 5 subjects");
        }
        for (j, t) in top.iter().enumerate() {
            let tp = format!("{p}.top[{j}]");
            let tm = schema::object_or(t, &tp, ErrorCode::Describe, "a top subject")?;
            schema::exact(tm, &["subject", "label", "source"], &[], &tp, ErrorCode::Describe)?;
            let subject = schema::string_or(tm, "subject", &tp, ErrorCode::Describe)?;
            parse_object_key(subject).map_err(|e| e.recode(ErrorCode::Describe))?;
            let source = schema::string_or(tm, "source", &tp, ErrorCode::Describe)?;
            lexical::check_function_name(source, &format!("{tp}.source")).map_err(|e| e.recode(ErrorCode::Describe))?;
            let label = schema::string_or(tm, "label", &tp, ErrorCode::Describe)?;
            if label.is_empty() || lexical::check_string(label, &tp).is_err() {
                return err(ErrorCode::Describe, &tp, "a label is a string of 3.5");
            }
        }
    }
    Ok(Described {
        kind: DescribeKind::Catalog,
        class: String::new(),
        class_hash: String::new(),
        object_id: None,
        function: None,
        fn_hash: None,
        tests: None,
        source: None,
        publisher: None,
        facets: None,
        extensions: Vec::new(),
    })
}

/// A find result (C2, the classes round): a JSON object of the mesh's, of which `fn` (a function name, optional),
/// `publisher` (the host of `fn`, with `fn`), `source` (a DNS name) and `facets` are checked. The rest is the
/// mesh's and is not read. Text that is not strict JSON is 6.1's code, not `E_DESCRIBE`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct FindResult {
    /// The publisher of `fn`, when the result gives one.
    pub publisher: Option<String>,
    /// The source's DNS name, when the result gives one.
    pub source: Option<String>,
    /// The facets, when the result gives them (C2).
    pub facets: Option<BTreeMap<String, Vec<String>>>,
}

/// Checks a find result (C2, the classes round) given as JSON text; see [`FindResult`].
pub fn check_find_result(result: &[u8]) -> Result<FindResult> {
    let v = json::parse(result)?;
    json::check_value_depth(&v)?;
    let m = schema::object_or(&v, "$", ErrorCode::Describe, "a find result")?;
    let name = match schema::opt(m, "fn") {
        Some(Value::String(n)) => {
            lexical::check_function_name(n, "$.fn").map_err(|e| e.recode(ErrorCode::Describe))?;
            Some(n.as_str())
        }
        Some(_) => return err(ErrorCode::Describe, "$.fn", "fn is a string"),
        None => None,
    };
    let publisher = match schema::opt(m, "publisher") {
        Some(Value::String(p)) => {
            let Some(n) = name else {
                return err(ErrorCode::Describe, "$.publisher", "publisher is given with fn");
            };
            check_publisher(p, n)?;
            Some(p.clone())
        }
        Some(_) => return err(ErrorCode::Describe, "$.publisher", "publisher is a string"),
        None => None,
    };
    let source = match schema::opt(m, "source") {
        Some(Value::String(s)) => {
            lexical::check_dns_name(s, "$.source").map_err(|e| e.recode(ErrorCode::Describe))?;
            Some(s.clone())
        }
        Some(_) => return err(ErrorCode::Describe, "$.source", "source is a DNS name"),
        None => None,
    };
    let facets = optional_facets(m, "$")?;
    Ok(FindResult { publisher, source, facets })
}

/// A describe answer that passed [`check_describe`].
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Described {
    /// Whether the answer is for a class or an object.
    pub kind: DescribeKind,
    /// The class name (`class`, or `object.class`).
    pub class: String,
    /// The class hash (`class_hash`, or `object.class_hash`).
    pub class_hash: String,
    /// The object id (an object answer only).
    pub object_id: Option<String>,
    /// The function name (a function answer only, `spec-0.6.0`).
    pub function: Option<String>,
    /// The function hash (a function answer only, `spec-0.6.0`).
    pub fn_hash: Option<String>,
    /// The tests the mesh holds (a function answer's, or a method entry's, `spec-0.6.0`).
    /// `None` for an object answer, a class, and any entry without `tests`.
    pub tests: Option<DescribeTests>,
    /// Where a relayed function's value is taken from (`spec-0.6.0`); `None` when not relayed.
    pub source: Option<DescribeSource>,
    /// The publisher (`spec-0.6.1`, 16.8): the host of a class's or a function's namespace, when the
    /// answer gives one. `None` for an object answer and for an answer without `publisher`.
    pub publisher: Option<String>,
    /// The facets (the classes round, C2, 9.6): the facet lists of a function answer, a class answer or a
    /// find result, by facet key (`domain`, `frequency`, `measure`, `region`, `thing`), each ascending
    /// and unique. `None` when the answer has none, and for an object answer and a catalogue root.
    pub facets: Option<BTreeMap<String, Vec<String>>>,
    /// The functions that extend the object's class (the classes round, K9, 16.8): ascending by `function`,
    /// empty when the answer has no `extensions`, and for every other kind of answer.
    pub extensions: Vec<DescribeExtension>,
}

/// Checks a describe answer (16.8) given as JSON text against the classes the caller holds
/// (flattened descriptors by class name, as `describe` vectors give them). Any failure is
/// `E_DESCRIBE`, or the 6.1 code of a text that is not strict JSON. It is
/// [`check_describe_with`] with no method function held.
pub fn check_describe(answer: &[u8], held: &BTreeMap<String, ClassDescriptor>) -> Result<Described> {
    check_describe_with(answer, held, &[])
}

/// Checks a describe answer (16.8), the six steps of its check, in order, reporting the first
/// failure. What the client holds decides how far it goes:
///
/// 1. parse the text as strict JSON (6.1's codes, not `E_DESCRIBE`);
/// 2. the shape: exactly the members of its `kind`, with their types, the names and hashes in
///    their forms, each `description` 1 to 1024 bytes, an object's `same_as` ascending and unique;
/// 3. internal consistency, which needs nothing held: a class's `class_hash` is its descriptor's
///    hash and its method table has the descriptor's methods; an object's `object_id`, `short_id`
///    and `call` follow from its `object`;
/// 4. the held class is the one whose hash is the answer's `class_hash` (for an object,
///    `object.class_hash`), never the one of that name; a client holding none stops here;
/// 5. against the held class: a class's descriptor is the held one; an object's keys are the
///    class's, of their types, with each class-typed key an encoding of an object of its class and
///    each string key canonical under its rule (16.4); its methods are the class's;
/// 6. against the held method functions (`functions`, found by `fn_hash`), for a class answer: each
///    such method's `args` are exactly its function's arguments other than the class keys, and its
///    `returns` exactly the function's `returns`. A method whose function is not held is unchecked.
///
/// An empty `functions` leaves step 6 unchecked, as [`check_describe`]. Since 0.3.8 (`spec-0.5.0`).
pub fn check_describe_with(
    answer: &[u8],
    held: &BTreeMap<String, ClassDescriptor>,
    functions: &[FunctionDescriptor],
) -> Result<Described> {
    let v = json::parse(answer)?;
    json::check_value_depth(&v)?;
    let m = schema::object_or(&v, "$", ErrorCode::Describe, "a describe answer")?;
    match schema::string_or(m, "kind", "$", ErrorCode::Describe)? {
        "class" => check_class(m, held, functions),
        "object" => check_object(m, held),
        "function" => check_function(m, functions),
        "catalog" => check_catalog(m),
        other => {
            err(ErrorCode::Describe, "$.kind", format!("kind is class, object, function or catalog, not {other:?}"))
        }
    }
}

/// The held class whose hash is `class_hash` (16.8 step 4): found by hash, never by name.
fn held_by_hash<'a>(held: &'a BTreeMap<String, ClassDescriptor>, class_hash: &str) -> Option<&'a ClassDescriptor> {
    held.values().find(|h| h.hash() == class_hash)
}

/// A class answer (16.8): steps 2 and 3, then 4 to 6.
fn check_class(
    m: &[(String, Value)],
    held: &BTreeMap<String, ClassDescriptor>,
    functions: &[FunctionDescriptor],
) -> Result<Described> {
    schema::exact(
        m,
        &["kind", "class", "class_hash", "descriptor", "methods"],
        &["publisher", "facets"],
        "$",
        ErrorCode::Describe,
    )?;
    let facets = optional_facets(m, "$")?;
    let class = schema::string_or(m, "class", "$", ErrorCode::Describe)?;
    lexical::check_function_name(class, "$.class").map_err(|e| e.recode(ErrorCode::Describe))?;
    let publisher = match schema::opt(m, "publisher") {
        Some(Value::String(p)) => {
            check_publisher(p, class)?;
            Some(p.clone())
        }
        Some(_) => return err(ErrorCode::Describe, "$.publisher", "publisher is a string"),
        None => None,
    };
    let class_hash = schema::string_or(m, "class_hash", "$", ErrorCode::Describe)?;
    lexical::check_hex(class_hash, 64, "$.class_hash").map_err(|e| e.recode(ErrorCode::Describe))?;
    let descriptor =
        ClassDescriptor::from_value(schema::get(m, "descriptor")).map_err(|e| e.recode(ErrorCode::Describe))?;
    // Step 3.
    if descriptor.hash() != class_hash {
        return err(ErrorCode::Describe, "$.class_hash", "class_hash is not the hash of the descriptor");
    }
    let methods = schema::object_or(schema::get(m, "methods"), "$.methods", ErrorCode::Describe, "methods")?;
    if methods.len() != descriptor.methods.len() {
        return err(ErrorCode::Describe, "$.methods", "a method table has every method of the class, and no other");
    }
    for (name, entry) in methods {
        let p = format!("$.methods.{name}");
        let Some(fn_hash) = descriptor.methods.get(name) else {
            return err(ErrorCode::Describe, &p, "a method the class does not have");
        };
        let e = schema::object_or(entry, &p, ErrorCode::Describe, "a method entry")?;
        let members: &[&str] = &["fn", "fn_hash", "args", "returns"];
        schema::exact(e, members, &["description", "tests", "source"], &p, ErrorCode::Describe)?;
        if let Some(t) = schema::opt(e, "tests") {
            tests_of(t, &format!("{p}.tests"))?;
        }
        if let Some(src) = schema::opt(e, "source") {
            source_of(src, &format!("{p}.source"))?;
        }
        if schema::string_or(e, "fn", &p, ErrorCode::Describe)? != format!("{class}/{name}") {
            return err(ErrorCode::Describe, &p, "fn is the class's name and the method's");
        }
        if schema::string_or(e, "fn_hash", &p, ErrorCode::Describe)? != fn_hash {
            return err(ErrorCode::Describe, &p, "fn_hash is the descriptor's hash for the method");
        }
        schema::object_or(schema::get(e, "args"), &p, ErrorCode::Describe, "args")?;
        match schema::get(e, "returns") {
            Value::String(_) | Value::Object(_) => {}
            _ => return err(ErrorCode::Describe, &p, "returns is a type name or an object"),
        }
        // Step 2: a description is 1 to 1024 bytes, valid by 3.5.
        if let Some(d) = schema::opt(e, "description") {
            let Value::String(d) = d else {
                return err(ErrorCode::Describe, &p, "description is a string");
            };
            if d.is_empty() || d.len() > 1024 || lexical::check_string(d, &p).is_err() {
                return err(ErrorCode::Describe, &p, "description is a string of 1 to 1024 bytes");
            }
        }
    }
    // Step 4: nothing held for this class ends the check.
    let Some(held_class) = held_by_hash(held, class_hash) else {
        return Ok(Described {
            kind: DescribeKind::Class,
            class: class.into(),
            class_hash: class_hash.into(),
            object_id: None,
            function: None,
            fn_hash: None,
            tests: None,
            source: None,
            publisher,
            facets,
            extensions: Vec::new(),
        });
    };
    // Step 5: the descriptor is the held one (equal hashes: equal canonical bytes).
    if held_class.canonical() != descriptor.canonical() {
        return err(ErrorCode::Describe, "$.descriptor", "the descriptor is not the class the caller holds");
    }
    // Step 6: each method whose function is held has the function's arguments but the keys, and its
    // returns.
    for (name, entry) in methods {
        let p = format!("$.methods.{name}");
        let fn_hash = schema::string_or(
            schema::object_or(entry, &p, ErrorCode::Describe, "a method entry")?,
            "fn_hash",
            &p,
            ErrorCode::Describe,
        )?;
        let Some(f) = functions.iter().find(|f| f.hash() == fn_hash) else {
            continue;
        };
        let e = schema::object_or(entry, &p, ErrorCode::Describe, "a method entry")?;
        let signature = f.to_value();
        let sig = schema::get(schema::object_or(&signature, &p, ErrorCode::Describe, "a function")?, "signature");
        let sig = schema::object_or(sig, &p, ErrorCode::Describe, "a signature")?;
        let (_, want_args) = sig
            .iter()
            .find(|(k, _)| k == "args")
            .ok_or_else(|| Error::new(ErrorCode::Describe, &p, "a function has arguments"))?;
        let want_args: Vec<(String, Value)> = match want_args {
            Value::Object(a) => a.iter().filter(|(n, _)| !held_class.keys.contains_key(n)).cloned().collect(),
            _ => return err(ErrorCode::Describe, &p, "a function's arguments are an object"),
        };
        if Value::Object(schema::object_or(schema::get(e, "args"), &p, ErrorCode::Describe, "args")?.to_vec()).to_jcs()
            != Value::Object(want_args).to_jcs()
        {
            return err(ErrorCode::Describe, &p, "args are the function's arguments other than the class keys");
        }
        let want_returns = sig.iter().find(|(k, _)| k == "returns").map(|(_, v)| v.to_jcs());
        if want_returns.as_deref() != Some(schema::get(e, "returns").to_jcs().as_slice()) {
            return err(ErrorCode::Describe, &p, "returns is the function's returns");
        }
    }
    Ok(Described {
        kind: DescribeKind::Class,
        class: class.into(),
        class_hash: class_hash.into(),
        object_id: None,
        function: None,
        fn_hash: None,
        tests: None,
        source: None,
        publisher,
        facets,
        extensions: Vec::new(),
    })
}

/// An object answer (16.8): steps 2 and 3, then 4 and 5 against the held class.
fn check_object(m: &[(String, Value)], held: &BTreeMap<String, ClassDescriptor>) -> Result<Described> {
    schema::exact(
        m,
        &["kind", "object", "object_id", "short_id", "call", "methods"],
        &["same_as", "resolved", "extensions"],
        "$",
        ErrorCode::Describe,
    )?;
    let object = schema::object_or(schema::get(m, "object"), "$.object", ErrorCode::Describe, "an object")?;
    schema::exact(object, &["class", "class_hash", "keys"], &[], "$.object", ErrorCode::Describe)?;
    let class = schema::string_or(object, "class", "$.object", ErrorCode::Describe)?;
    lexical::check_function_name(class, "$.object.class").map_err(|e| e.recode(ErrorCode::Describe))?;
    let class_hash = schema::string_or(object, "class_hash", "$.object", ErrorCode::Describe)?;
    lexical::check_hex(class_hash, 64, "$.object.class_hash").map_err(|e| e.recode(ErrorCode::Describe))?;
    // Step 2: every key is a typed scalar valid by section 3 (a class-typed key is a string).
    let keys_v = schema::object_or(schema::get(object, "keys"), "$.object.keys", ErrorCode::Describe, "keys")?;
    let mut keys = BTreeMap::new();
    let mut typed: BTreeMap<&str, (&str, String)> = BTreeMap::new();
    for (name, kv) in keys_v {
        let p = format!("$.object.keys.{name}");
        let kvm = schema::object_or(kv, &p, ErrorCode::Describe, "a typed scalar")?;
        schema::exact(kvm, &["type", "value"], &[], &p, ErrorCode::Describe)?;
        let ty_name = schema::string_or(kvm, "type", &p, ErrorCode::Describe)?;
        let ty = match Type::from_name(ty_name) {
            Some(t) if t != Type::Blob => t,
            _ => return err(ErrorCode::Describe, &p, "a key's type is a scalar type of section 3"),
        };
        let text = match schema::get(kvm, "value") {
            Value::String(s) => s.clone(),
            Value::Bool(b) => b.to_string(),
            _ => return err(ErrorCode::Describe, &p, "a value is a string or a boolean"),
        };
        let scalar = Scalar::from_lexical(ty, &text).map_err(|e| e.recode(ErrorCode::Describe))?;
        keys.insert(name.clone(), KeyValue::Scalar(scalar));
        typed.insert(name.as_str(), (ty_name, text));
    }
    let key = ObjectKey::new(class, keys).map_err(|e| e.recode(ErrorCode::Describe))?;
    let expected = key.object_value(class_hash).map_err(|e| e.recode(ErrorCode::Describe))?;
    if expected.to_jcs() != Value::Object(object.to_vec()).to_jcs() {
        return err(ErrorCode::Describe, "$.object", "the object is not in its canonical form");
    }
    let object_id = key.object_id(class_hash).map_err(|e| e.recode(ErrorCode::Describe))?;
    if schema::string_or(m, "object_id", "$", ErrorCode::Describe)? != object_id {
        return err(ErrorCode::Describe, "$.object_id", "object_id is the object's id");
    }
    let short = short_id(&object_id).map_err(|e| e.recode(ErrorCode::Describe))?;
    if schema::string_or(m, "short_id", "$", ErrorCode::Describe)? != short {
        return err(ErrorCode::Describe, "$.short_id", "short_id is the first 12 digits of object_id");
    }
    if schema::string_or(m, "call", "$", ErrorCode::Describe)? != key.call_form() {
        return err(ErrorCode::Describe, "$.call", "call is the object's canonical call form");
    }
    if let Some(r) = schema::opt(m, "resolved") {
        check_object_resolved(r, &key)?;
    }
    let extensions = match schema::opt(m, "extensions") {
        Some(e) => extensions_of(e, "$.extensions")?,
        None => Vec::new(),
    };
    let methods = schema::get(m, "methods");
    let Value::Array(names) = methods else {
        return err(ErrorCode::Describe, "$.methods", "methods is an array of method names");
    };
    let mut previous: Option<&str> = None;
    for item in names {
        let Value::String(s) = item else {
            return err(ErrorCode::Describe, "$.methods", "a method name is a string");
        };
        lexical::check_name(s, "$.methods").map_err(|e| e.recode(ErrorCode::Describe))?;
        if previous.is_some_and(|p| p >= s.as_str()) {
            return err(ErrorCode::Describe, "$.methods", "methods are ascending and unique");
        }
        previous = Some(s);
    }
    if let Some(same) = schema::opt(m, "same_as") {
        let Value::Array(items) = same else {
            return err(ErrorCode::Describe, "$.same_as", "same_as is an array of object keys");
        };
        if items.is_empty() {
            return err(ErrorCode::Describe, "$.same_as", "same_as has at least one object key");
        }
        let mut previous: Option<&str> = None;
        for item in items {
            let Value::String(s) = item else {
                return err(ErrorCode::Describe, "$.same_as", "an object key is a string");
            };
            parse_object_key(s).map_err(|e| e.recode(ErrorCode::Describe))?;
            if previous.is_some_and(|p| p >= s.as_str()) {
                return err(ErrorCode::Describe, "$.same_as", "same_as is ascending and unique");
            }
            previous = Some(s);
        }
    }
    // Step 4: nothing held for this class ends the check after step 3.
    let Some(held_class) = held_by_hash(held, class_hash) else {
        return Ok(Described {
            kind: DescribeKind::Object,
            class: class.into(),
            class_hash: class_hash.into(),
            object_id: Some(object_id),
            function: None,
            fn_hash: None,
            tests: None,
            source: None,
            publisher: None,
            facets: None,
            extensions: extensions.clone(),
        });
    };
    // Step 5: the keys are the class's, of their types, and the methods are the class's.
    if keys_v.len() != held_class.keys.len() {
        return err(ErrorCode::Describe, "$.object.keys", "an object binds exactly the class's keys");
    }
    for (name, (ty_name, text)) in &typed {
        let p = format!("$.object.keys.{name}");
        let Some(decl) = held_class.keys.get(*name) else {
            return err(ErrorCode::Describe, &p, "a key the class does not have");
        };
        match decl {
            ClassKey::Class(c) => {
                if *ty_name != "string" {
                    return err(ErrorCode::Describe, &p, "a class-typed key is a string holding its encoding");
                }
                let nested = parse_object_key(text).map_err(|e| e.recode(ErrorCode::Describe))?;
                if nested.class != *c {
                    return err(ErrorCode::Describe, &p, "a class-typed key is an object of its class");
                }
            }
            ClassKey::Scalar { ty: want, key_normalisation, .. } => {
                if *ty_name != want.as_str() {
                    return err(ErrorCode::Describe, &p, format!("the key is {}", want.as_str()));
                }
                if let Some(rule) = key_normalisation {
                    rule.check(text).map_err(|e| e.recode(ErrorCode::Describe))?;
                }
            }
        }
    }
    let want: Vec<Value> = held_class.methods.keys().map(|k| Value::String(k.clone())).collect();
    if *methods != Value::Array(want) {
        return err(ErrorCode::Describe, "$.methods", "methods are the class's method names, ascending");
    }
    Ok(Described {
        kind: DescribeKind::Object,
        class: class.into(),
        class_hash: class_hash.into(),
        object_id: Some(object_id),
        function: None,
        fn_hash: None,
        tests: None,
        source: None,
        publisher: None,
        facets: None,
        extensions,
    })
}

/// The `resolved` member of an object answer (K8, 16.7, the classes round): the object was named by a label. It is
/// exactly `call` (the object's call form) and `resolutions`, which holds one `lookup` resolution (`from`, `kind`,
/// `to` and `asof`): `to` is the key encoding of the object, and `asof` an instant.
fn check_object_resolved(v: &Value, key: &ObjectKey) -> Result<()> {
    let m = schema::object_or(v, "$.resolved", ErrorCode::Describe, "resolved")?;
    schema::exact(m, &["call", "resolutions"], &[], "$.resolved", ErrorCode::Describe)?;
    if schema::string_or(m, "call", "$.resolved", ErrorCode::Describe)? != key.call_form() {
        return err(ErrorCode::Describe, "$.resolved.call", "call is the object's own call form");
    }
    let Value::Array(items) = schema::get(m, "resolutions") else {
        return err(ErrorCode::Describe, "$.resolved.resolutions", "resolutions is an array");
    };
    let [item] = items.as_slice() else {
        return err(ErrorCode::Describe, "$.resolved.resolutions", "resolved holds the one lookup resolution");
    };
    let rp = "$.resolved.resolutions[0]";
    let r = schema::object_or(item, rp, ErrorCode::Describe, "a resolution")?;
    schema::exact(r, &["from", "kind", "to", "asof"], &[], rp, ErrorCode::Describe)?;
    schema::string_or(r, "from", rp, ErrorCode::Describe)?;
    if schema::string_or(r, "kind", rp, ErrorCode::Describe)? != "lookup" {
        return err(ErrorCode::Describe, rp, "an object answer's resolution is a lookup");
    }
    if schema::string_or(r, "to", rp, ErrorCode::Describe)? != format_object_key(key) {
        return err(ErrorCode::Describe, rp, "to is the key encoding of the object described");
    }
    let asof = schema::string_or(r, "asof", rp, ErrorCode::Describe)?;
    lexical::check_instant(asof, rp).map_err(|e| e.recode(ErrorCode::Describe))?;
    Ok(())
}

/// A function answer (16.8, `spec-0.6.0`): the shape, then step 6 against the held function
/// descriptor when one is held: its `args`, all of them, and its `returns`.
fn check_function(m: &[(String, Value)], functions: &[FunctionDescriptor]) -> Result<Described> {
    schema::exact(
        m,
        &["kind", "fn", "fn_hash", "args", "returns"],
        &["description", "tests", "source", "publisher", "facets"],
        "$",
        ErrorCode::Describe,
    )?;
    let facets = optional_facets(m, "$")?;
    let name = schema::string_or(m, "fn", "$", ErrorCode::Describe)?;
    lexical::check_function_name(name, "$.fn").map_err(|e| e.recode(ErrorCode::Describe))?;
    let publisher = match schema::opt(m, "publisher") {
        Some(Value::String(p)) => {
            check_publisher(p, name)?;
            Some(p.clone())
        }
        Some(_) => return err(ErrorCode::Describe, "$.publisher", "publisher is a string"),
        None => None,
    };
    let fn_hash = schema::string_or(m, "fn_hash", "$", ErrorCode::Describe)?;
    lexical::check_hex(fn_hash, 64, "$.fn_hash").map_err(|e| e.recode(ErrorCode::Describe))?;
    let args = schema::get(m, "args");
    schema::object_or(args, "$.args", ErrorCode::Describe, "args")?;
    let returns = schema::get(m, "returns");
    match returns {
        Value::String(_) | Value::Object(_) => {}
        _ => return err(ErrorCode::Describe, "$.returns", "returns is a type name or an object"),
    }
    if let Some(d) = schema::opt(m, "description") {
        let Value::String(d) = d else { return err(ErrorCode::Describe, "$.description", "description is a string") };
        if d.is_empty() || d.len() > 1024 || lexical::check_string(d, "$.description").is_err() {
            return err(ErrorCode::Describe, "$.description", "description is a string of 1 to 1024 bytes");
        }
    }
    let tests = match schema::opt(m, "tests") {
        Some(t) => Some(tests_of(t, "$.tests")?),
        None => None,
    };
    let source = match schema::opt(m, "source") {
        Some(src) => Some(source_of(src, "$.source")?),
        None => None,
    };
    // Step 6: the held function with this hash (none held: unchecked).
    if let Some(f) = functions.iter().find(|f| f.hash() == fn_hash) {
        let (want_args, want_returns) = signature(f)?;
        if args.to_jcs() != want_args.to_jcs() {
            return err(ErrorCode::Describe, "$.args", "args are the function's arguments");
        }
        if returns.to_jcs() != want_returns.to_jcs() {
            return err(ErrorCode::Describe, "$.returns", "returns is the function's returns");
        }
    }
    Ok(Described {
        kind: DescribeKind::Function,
        class: String::new(),
        class_hash: String::new(),
        object_id: None,
        function: Some(name.into()),
        fn_hash: Some(fn_hash.into()),
        tests,
        source,
        publisher,
        facets,
        extensions: Vec::new(),
    })
}

/// A function answer (16.8, `spec-0.6.0`) built from its descriptor, with the members of
/// [`check_describe_with`]: `kind` `"function"`, `fn`, `fn_hash`, `args` and `returns`, and
/// optionally `description`, `tests` and `source`. The name is a function name (2.3); the
/// description, tests and source are checked as the client checks them.
#[derive(Clone, Debug, PartialEq)]
pub struct FunctionAnswer {
    name: String,
    fn_hash: String,
    args: Value,
    returns: Value,
    description: Option<String>,
    tests: Option<DescribeTests>,
    source: Option<DescribeSource>,
    publisher: Option<String>,
    facets: Option<BTreeMap<String, Vec<String>>>,
}

impl FunctionAnswer {
    /// The answer for the function named `name` (a function name, 2.3) with descriptor `d`.
    pub fn new(name: &str, d: &FunctionDescriptor) -> Result<FunctionAnswer> {
        lexical::check_function_name(name, "$.fn").map_err(|e| e.recode(ErrorCode::Describe))?;
        let (args, returns) = signature(d)?;
        Ok(FunctionAnswer {
            name: name.into(),
            fn_hash: d.hash(),
            args,
            returns,
            description: None,
            tests: None,
            source: None,
            publisher: None,
            facets: None,
        })
    }

    /// With `description`: 1 to 1024 bytes, valid by 3.5 (`E_DESCRIBE` otherwise).
    pub fn with_description(self, description: &str) -> Result<FunctionAnswer> {
        if description.is_empty()
            || description.len() > 1024
            || lexical::check_string(description, "$.description").is_err()
        {
            return err(ErrorCode::Describe, "$.description", "description is a string of 1 to 1024 bytes");
        }
        Ok(FunctionAnswer { description: Some(description.into()), ..self })
    }

    /// With `tests` (`E_DESCRIBE` when `covered` exceeds `branches`).
    pub fn with_tests(self, tests: DescribeTests) -> Result<FunctionAnswer> {
        tests.check()?;
        Ok(FunctionAnswer { tests: Some(tests), ..self })
    }

    /// With `source`, for a relayed function (`E_DESCRIBE` for a name that is not a DNS name, a
    /// `relayed_by` that is not one, or a takeover that is not `https://`).
    pub fn with_source(self, source: DescribeSource) -> Result<FunctionAnswer> {
        source.check()?;
        Ok(FunctionAnswer { source: Some(source), ..self })
    }

    /// With `publisher` (`spec-0.6.1`): the host of the function's namespace, which must be exactly
    /// that host (16.8; `E_DESCRIBE` for anything else, a domain of a later segment included).
    pub fn with_publisher(self, publisher: &str) -> Result<FunctionAnswer> {
        check_publisher(publisher, &self.name)?;
        Ok(FunctionAnswer { publisher: Some(publisher.into()), ..self })
    }

    /// 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,
    /// ascending and unique (`E_DESCRIBE` otherwise).
    pub fn with_facets(self, facets: BTreeMap<String, Vec<String>>) -> Result<FunctionAnswer> {
        let checked = facets_of(&facets_value(&facets), "$.facets")?;
        Ok(FunctionAnswer { facets: Some(checked), ..self })
    }

    /// The answer as a JSON value.
    pub fn to_value(&self) -> Value {
        let s = |x: &str| Value::String(x.into());
        let mut m = vec![
            ("kind".to_string(), s("function")),
            ("fn".to_string(), s(&self.name)),
            ("fn_hash".to_string(), s(&self.fn_hash)),
            ("args".to_string(), self.args.clone()),
            ("returns".to_string(), self.returns.clone()),
        ];
        if let Some(d) = &self.description {
            m.push(("description".into(), s(d)));
        }
        if let Some(t) = &self.tests {
            m.push((
                "tests".into(),
                Value::Object(vec![
                    ("branches".into(), num(t.branches)),
                    ("count".into(), num(t.count)),
                    ("counterexamples".into(), num(t.counterexamples)),
                    ("covered".into(), num(t.covered)),
                ]),
            ));
        }
        if let Some(p) = &self.publisher {
            m.push(("publisher".into(), s(p)));
        }
        if let Some(f) = &self.facets {
            m.push(("facets".into(), facets_value(f)));
        }
        if let Some(src) = &self.source {
            m.push((
                "source".into(),
                Value::Object(vec![
                    ("name".into(), s(&src.name)),
                    ("relayed_by".into(), s(&src.relayed_by)),
                    ("takeover".into(), s(&src.takeover)),
                ]),
            ));
        }
        Value::Object(m)
    }

    /// The answer's body: its canonical JSON text (JCS).
    pub fn to_json(&self) -> Vec<u8> {
        self.to_value().to_jcs()
    }
}

/// A count as a JSON number (its canonical text).
fn num(x: u64) -> Value {
    json::parse(x.to_string().as_bytes()).unwrap_or(Value::Null)
}