datumesh-http 0.4.0

The Datumesh engine behind HTTPS: cell envelopes, batches, slices (JSON and Arrow), receipts, jobs, verification and cross-mesh resolution; the datumesh-mesh server.
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
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
//! [`Mesh`]: the engine, its store and everything the endpoints share; the blocking
//! operations each endpoint is built on, usable as library calls.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::PathBuf;
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant};

use datumesh_core::json::{self, Value};
use datumesh_core::{keys_from_response, verify, ErrorCode, FunctionDescriptor, KeyDoc, Keys, Receipt, SigningKey};
use datumesh_engine::{Answer, Clock, Engine, EngineError, Runtime, SystemClock};
use datumesh_formula::runtime::FormulaRuntime;
use datumesh_store::Store;

use crate::apikeys::Principal;
use crate::call::{self, Bindings, Bound, Rejection, Target};
use crate::config::{Config, ConfigError, Rule};
use crate::envelope::{self, Cache, Reply};
use crate::foreign::{host_of, CrossMesh, Foreign, ForeignError, KeyCache};
use crate::jobs::Jobs;
use crate::limit::Limiter;
use crate::metrics::Metrics;
use crate::pool::Pool;

/// Why a mesh could not be built.
#[derive(Debug)]
#[non_exhaustive]
pub enum BuildError {
    /// The configuration.
    Config(ConfigError),
    /// The engine's configuration (the key, its publication in the store, the runtimes).
    Engine(datumesh_engine::ConfigError),
    /// The base URL ([`Config::base_url`]). Since 0.2.0.
    BaseUrl(crate::config::BaseUrlError),
}

impl std::fmt::Display for BuildError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BuildError::Config(e) => write!(f, "{e}"),
            BuildError::Engine(e) => write!(f, "engine: {e}"),
            BuildError::BaseUrl(e) => write!(f, "configuration: base URL: {e}"),
        }
    }
}

impl std::error::Error for BuildError {}

/// Builds a [`Mesh`].
pub struct MeshBuilder {
    config: Config,
    store: Arc<dyn Store + Send + Sync>,
    key: Option<SigningKey>,
    key_file: Option<PathBuf>,
    runtimes: Vec<Arc<dyn Runtime>>,
    formula: bool,
    clock: Arc<dyn Clock>,
    fuel: Option<u64>,
    licence: Option<String>,
    memo_capacity: Option<usize>,
}

impl std::fmt::Debug for MeshBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MeshBuilder").field("host", &self.config.host).finish_non_exhaustive()
    }
}

impl MeshBuilder {
    /// The mesh's signing key.
    pub fn signing_key(mut self, key: SigningKey) -> Self {
        self.key = Some(key);
        self.key_file = None;
        self
    }

    /// The mesh's signing key, from a file of its 32-byte seed (32 bytes or 64 hex digits),
    /// which must have mode 0600.
    pub fn signing_key_file(mut self, path: impl Into<PathBuf>) -> Self {
        self.key_file = Some(path.into());
        self.key = None;
        self
    }

    /// Adds a runtime (the formula runtime is added unless [`MeshBuilder::without_formula`]).
    pub fn runtime(mut self, runtime: Arc<dyn Runtime>) -> Self {
        self.runtimes.push(runtime);
        self
    }

    /// No formula runtime.
    pub fn without_formula(mut self) -> Self {
        self.formula = false;
        self
    }

    /// The clock (default: the system clock).
    pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
        self.clock = clock;
        self
    }

    /// The engine's fuel per request.
    pub fn fuel(mut self, fuel: u64) -> Self {
        self.fuel = Some(fuel);
        self
    }

    /// The licence of the receipts the engine signs.
    pub fn licence(mut self, licence: impl Into<String>) -> Self {
        self.licence = Some(licence.into());
        self
    }

    /// The engine's memo capacity.
    pub fn memo_capacity(mut self, n: usize) -> Self {
        self.memo_capacity = Some(n);
        self
    }

    /// Checks the configuration, builds the engine (its key must be published in the store's
    /// namespace record for the host) and the mesh.
    pub fn build(self) -> Result<Mesh, BuildError> {
        if let Some(u) = &self.config.base_url {
            crate::config::check_base_url(&self.config.host, u).map_err(BuildError::BaseUrl)?;
        }
        self.config.check().map_err(BuildError::Config)?;
        let keys = Arc::new(KeyCache::default());
        let foreign = Arc::new(Foreign::new(&self.config, self.store.clone(), keys.clone(), self.clock.clone()));
        let mut b = Engine::builder(self.store.clone(), self.config.host.clone()).clock(self.clock.clone());
        b = match (self.key, &self.key_file) {
            (Some(k), _) => b.signing_key(k),
            (None, Some(p)) => {
                crate::config::read_secret_file(p).map_err(BuildError::Config)?;
                b.signing_key_file(p.clone())
            }
            (None, None) => b,
        };
        let mut runtimes = self.runtimes;
        if self.formula {
            runtimes.push(Arc::new(FormulaRuntime::new(self.store.clone())));
        }
        if self.config.test_cells {
            crate::testrun::install_test_cases(&*self.store, &self.config.host)
                .map_err(|e| BuildError::Config(ConfigError::new("DATUMESH_TEST_CELLS", e)))?;
            runtimes.push(Arc::new(crate::testrun::TestCases { store: self.store.clone() }));
        }
        for rt in runtimes {
            b = b.runtime(Arc::new(CrossMesh::new(rt, foreign.clone())));
        }
        if let Some(f) = self.fuel {
            b = b.fuel(f);
        }
        if let Some(l) = self.licence {
            b = b.licence(l);
        }
        if let Some(n) = self.memo_capacity {
            b = b.memo_capacity(n);
        }
        let engine = b.build().map_err(BuildError::Engine)?;
        let config = self.config;
        let embed = config.embed_url.as_deref().map(crate::embed::EmbedClient::new);
        let inner = Inner {
            generic: RwLock::new(Arc::new(crate::find::stopwords())),
            embed,
            reindex: Mutex::new(()),
            pool: Arc::new(Pool::new(config.pool_size)),
            jobs: Jobs::new(config.ttl.job, config.max_jobs),
            limiter: Limiter::new(config.rate.clone()),
            metrics: Metrics::default(),
            engine: Arc::new(engine),
            store: self.store,
            clock: self.clock,
            keys,
            foreign,
            descriptors: Mutex::new(HashMap::new()),
            last_good: Mutex::new(HashMap::new()),
            infos: (0..32).map(|_| Mutex::new(HashMap::new())).collect(),
            by_hash: (0..32).map(|_| Mutex::new(HashMap::new())).collect(),
            latest: Latest::new(),
            targets: Targets::new(),
            slices: Mutex::new(Vec::new()),
            known: Mutex::new(crate::describe::Index::default()),
            started: Instant::now(),
            config,
        };
        let mesh = Mesh { inner: Arc::new(inner) };
        // The operator's catalogue, then the index: now, and every 30 s (a bundle or a publish
        // from another process reaches the index within that). The thread stops with the mesh.
        // On a thread of its own: the store's synchronous client must not run on a runtime's thread.
        std::thread::scope(|s| {
            let inner = mesh.inner.clone();
            let _ = s.spawn(move || crate::find::sync_operator_catalog(&inner)).join();
        });
        let weak = Arc::downgrade(&mesh.inner);
        let spawned = std::thread::Builder::new().name("datumesh-index".into()).spawn(move || loop {
            let Some(inner) = weak.upgrade() else { break };
            crate::find::reindex(&inner);
            drop(inner);
            std::thread::sleep(Duration::from_secs(30));
        });
        if let Err(e) = spawned {
            tracing::warn!(error = %e, "the index thread is not started; find sees the catalogue as it is at start");
        }
        Ok(mesh)
    }
}

/// The last `ok` receipt served for a cell, for `stale` answers.
struct LastGood {
    info: Arc<ReceiptInfo>,
    at: Instant,
}

/// What the mesh needs of a receipt it serves, kept by its bytes (content-addressed: never
/// stale): its hash, `asof`, trust and its `ok` envelope.
pub(crate) struct ReceiptInfo {
    pub(crate) hash: String,
    pub(crate) asof: String,
    pub(crate) receipt: Vec<u8>,
    pub(crate) parsed: Receipt,
    pub(crate) trust: datumesh_core::TrustLabel,
    /// The `ok` envelope, the function hash echoed.
    pub(crate) ok: crate::envelope::Bytes,
}

pub(crate) struct Inner {
    pub(crate) config: Config,
    pub(crate) store: Arc<dyn Store + Send + Sync>,
    pub(crate) engine: Arc<Engine>,
    pub(crate) clock: Arc<dyn Clock>,
    pub(crate) pool: Arc<Pool>,
    pub(crate) jobs: Jobs,
    pub(crate) limiter: Limiter,
    pub(crate) metrics: Metrics,
    pub(crate) keys: Arc<KeyCache>,
    pub(crate) foreign: Arc<Foreign>,
    descriptors: Mutex<HashMap<String, Arc<FunctionDescriptor>>>,
    last_good: Mutex<HashMap<String, LastGood>>,
    infos: Vec<Mutex<HashMap<u64, Arc<ReceiptInfo>>>>,
    by_hash: Vec<Mutex<HashMap<String, Arc<ReceiptInfo>>>>,
    latest: Latest,
    targets: Targets,
    #[allow(clippy::type_complexity)]
    pub(crate) slices: Mutex<Vec<(String, String, Arc<Vec<datumesh_store::SliceValue>>)>>,
    /// The index of the objects the mesh knows (describe, short ids).
    pub(crate) known: Mutex<crate::describe::Index>,
    pub(crate) started: Instant,
    /// The generic words `find` never matches values by (CONTRACT-build2-part2-read R3).
    pub(crate) generic: RwLock<Arc<HashSet<String>>>,
    /// The embedding service, when `DATUMESH_EMBED_URL` is set (R2).
    pub(crate) embed: Option<crate::embed::EmbedClient>,
    /// One index pass at a time.
    pub(crate) reindex: Mutex<()>,
}

/// A Datumesh mesh: the engine behind the endpoints. Cheap to clone (shared).
#[derive(Clone)]
pub struct Mesh {
    pub(crate) inner: Arc<Inner>,
}

impl std::fmt::Debug for Mesh {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Mesh").field("host", &self.inner.config.host).finish_non_exhaustive()
    }
}

/// Bindings looked up once per name and asof within one batch.
pub(crate) struct Memo<'a> {
    inner: &'a Inner,
    seen: std::borrow::Cow<'a, Seen>,
}

/// A binding a batch looks up: the lookup's result once one succeeded, and the lock held
/// during a lookup, so the batch's chunks, which start together and ask for the same names,
/// make one store round trip per name and asof, not one each.
#[derive(Default)]
struct SeenEntry {
    found: std::sync::OnceLock<Option<Arc<Bound>>>,
    lookup: Mutex<()>,
}

/// The bindings a batch has looked up (shared by its chunks), by name, then asof.
#[derive(Default)]
pub(crate) struct Seen(RwLock<HashMap<String, SeenAsofs>>);

/// A name's entries in [`Seen`], by asof.
type SeenAsofs = Vec<(String, Arc<SeenEntry>)>;

impl Clone for Seen {
    fn clone(&self) -> Seen {
        let m = self.0.read().unwrap_or_else(|p| p.into_inner());
        let copy = m
            .iter()
            .map(|(name, v)| {
                let v = v
                    .iter()
                    .map(|(a, e)| (a.clone(), Arc::new(SeenEntry { found: e.found.clone(), lookup: Mutex::new(()) })))
                    .collect();
                (name.clone(), v)
            })
            .collect();
        Seen(RwLock::new(copy))
    }
}

/// What [`Seen`] has of a name as of an asof.
enum Held {
    Found(Option<Arc<Bound>>),
    Entry(Arc<SeenEntry>),
    Full,
}

impl Seen {
    /// The binding of `fn_name` as of `asof` if found, else its entry (made if there is room:
    /// 64 asofs per name).
    fn held(&self, fn_name: &str, asof: &str) -> Held {
        if let Some(v) = self.0.read().unwrap_or_else(|p| p.into_inner()).get(fn_name) {
            if let Some((_, e)) = v.iter().find(|(a, _)| a == asof) {
                return match e.found.get() {
                    Some(b) => Held::Found(b.clone()),
                    None => Held::Entry(e.clone()),
                };
            }
        }
        let mut m = self.0.write().unwrap_or_else(|p| p.into_inner());
        let v = m.entry(fn_name.to_string()).or_default();
        if let Some((_, e)) = v.iter().find(|(a, _)| a == asof) {
            return Held::Entry(e.clone());
        }
        if v.len() >= 64 {
            return Held::Full;
        }
        let e = Arc::new(SeenEntry::default());
        v.push((asof.to_string(), e.clone()));
        Held::Entry(e)
    }

    /// The binding of `fn_name` as of `asof`: as found before, else looked up by `look`, at
    /// most one lookup at a time per name and asof (the others wait for its result). A failed
    /// lookup is not kept: the next request looks the name up again.
    pub(crate) fn lookup(
        &self,
        fn_name: &str,
        asof: &str,
        look: impl FnOnce() -> Result<Option<Arc<Bound>>, ErrorCode>,
    ) -> Result<Option<Arc<Bound>>, ErrorCode> {
        let e = match self.held(fn_name, asof) {
            Held::Found(b) => return Ok(b),
            Held::Full => return look(),
            Held::Entry(e) => e,
        };
        let _looking = e.lookup.lock().unwrap_or_else(|p| p.into_inner());
        if let Some(b) = e.found.get() {
            return Ok(b.clone());
        }
        let b = look()?;
        let _ = e.found.set(b.clone());
        Ok(b)
    }
}

impl<'a> Memo<'a> {
    pub(crate) fn new(inner: &'a Inner) -> Memo<'a> {
        Memo { inner, seen: std::borrow::Cow::Owned(Seen::default()) }
    }

    pub(crate) fn shared(inner: &'a Inner, seen: &'a Seen) -> Memo<'a> {
        Memo { inner, seen: std::borrow::Cow::Borrowed(seen) }
    }
}

impl Bindings for Memo<'_> {
    fn pinned(&self, fn_hash: &str) -> Result<Option<Arc<Bound>>, ErrorCode> {
        Bindings::pinned(self.inner, fn_hash)
    }

    fn alias(&self, alias: &str) -> Option<String> {
        Bindings::alias(self.inner, alias)
    }

    fn class(&self, name: &str, asof: &str) -> Result<Option<Arc<call::BoundClass>>, ErrorCode> {
        Bindings::class(self.inner, name, asof)
    }

    fn aliases_tx(&self) -> Option<String> {
        Bindings::aliases_tx(self.inner)
    }

    fn lookup(&self, class: &str, label: &str, asof: &str) -> Result<Option<String>, ErrorCode> {
        Bindings::lookup(self.inner, class, label, asof)
    }

    fn cached(&self, fn_hash: &str, rest: &str) -> Option<Arc<Target>> {
        self.inner.targets.get(fn_hash, rest)
    }

    fn remember(&self, rest: &str, target: &Arc<Target>) {
        self.inner.targets.put(rest, target);
    }

    fn binding(&self, fn_name: &str, asof: &str) -> Result<Option<Arc<Bound>>, ErrorCode> {
        self.seen.lookup(fn_name, asof, || Bindings::binding(self.inner, fn_name, asof))
    }
}

impl Bindings for Inner {
    fn pinned(&self, fn_hash: &str) -> Result<Option<Arc<Bound>>, ErrorCode> {
        match self.descriptor(fn_hash) {
            Ok(d) => Ok(Some(Arc::new(Bound::new(fn_hash, "", d)))),
            Err(ErrorCode::FnUnavailable) => Ok(None),
            Err(c) => Err(c),
        }
    }

    fn alias(&self, alias: &str) -> Option<String> {
        self.config.aliases.get(alias).cloned()
    }

    fn class(&self, name: &str, asof: &str) -> Result<Option<Arc<call::BoundClass>>, ErrorCode> {
        let c = self.class_binding(name, asof)?;
        if c.is_some() {
            self.hear_of_class(name);
        }
        Ok(c)
    }

    /// The mesh's configured alias map has no snapshot.
    fn aliases_tx(&self) -> Option<String> {
        None
    }

    fn lookup(&self, class: &str, label: &str, asof: &str) -> Result<Option<String>, ErrorCode> {
        let Some(c) = Bindings::class(self, class, asof)? else { return Ok(None) };
        let Some(method) = &c.descriptor.lookup else { return Ok(None) };
        let name = format!("{class}/{method}");
        let Some(b) = Bindings::binding(self, &name, asof)? else { return Ok(None) };
        let (ns, fn_name) = name.rsplit_once('/').unwrap_or((&name, ""));
        let mut args = datumesh_core::Args::new();
        args.insert("label".into(), datumesh_core::Arg::Value(datumesh_core::Scalar::String(label.to_string())));
        let cell = datumesh_core::Cell { ns: ns.into(), fn_name: fn_name.into(), fn_hash: b.fn_hash.clone(), args };
        match self.engine.get_cell(&cell, Some(asof)) {
            Ok(Answer::Receipt(bytes)) => match Receipt::from_json(&bytes).map(|r| r.value().clone()) {
                Ok(datumesh_core::Scalar::String(k)) => Ok(Some(k)),
                _ => Ok(None),
            },
            Err(EngineError::Store(_)) => Err(ErrorCode::InputUnavailable),
            _ => Ok(None),
        }
    }

    fn cached(&self, fn_hash: &str, rest: &str) -> Option<Arc<Target>> {
        self.targets.get(fn_hash, rest)
    }

    fn remember(&self, rest: &str, target: &Arc<Target>) {
        self.targets.put(rest, target);
    }

    fn binding(&self, fn_name: &str, asof: &str) -> Result<Option<Arc<Bound>>, ErrorCode> {
        let mut failed = None;
        if self.foreign.is_foreign(fn_name) {
            if let Err(e) = self.foreign.ensure_name(fn_name) {
                tracing::warn!(target: "datumesh_http", name = fn_name, detail = %e.detail, "cross-mesh binding");
                // `Bindings::binding` answers a bare code: the detail of E_FOREIGN_UNAVAILABLE
                // waits on this thread for `rejection`, which answers on the same thread.
                FOREIGN_DETAIL.with(|d| d.set(e.foreign_detail()));
                failed = Some(e.code);
            }
        }
        let b = self.store.resolve_binding(fn_name, asof).map_err(|e| {
            tracing::warn!(target: "datumesh_http", error = %e, "resolve_binding");
            ErrorCode::InputUnavailable
        })?;
        // The other mesh is unreachable: a binding imported before still names the cell
        // (whose answer is then stale or an error), else the name cannot be resolved.
        if let (Some(code), None) = (failed, &b) {
            return Err(code);
        }
        match b {
            None => Ok(None),
            Some(b) => {
                let d = self.descriptor(&b.fn_hash)?;
                Ok(Some(Arc::new(Bound::new(b.fn_hash, b.tx, d))))
            }
        }
    }
}

thread_local! {
    /// Why the other mesh could not be reached, from the last cross-mesh name resolution on
    /// this thread (see `Inner::binding` and `Inner::rejection`).
    static FOREIGN_DETAIL: std::cell::Cell<Option<datumesh_core::ForeignDetail>> = const { std::cell::Cell::new(None) };
}

/// Latest answers by key: the receipt, the cell id and the asof answered at.
type LatestShard = RwLock<HashMap<String, (Arc<ReceiptInfo>, String, String)>>;

/// The latest answers of local stored cells, as of when they were answered: such an answer
/// stands for every later asof until a version of the cell is added, which the mesh is told
/// of ([`Mesh::stored_version_added`]), as the engine's memo is. It saves the engine's work
/// (the cell id, the memo) on the hottest path: warm gets of stored cells.
struct Latest {
    shards: Vec<LatestShard>,
    by_cell: Mutex<HashMap<String, Vec<String>>>,
}

impl Latest {
    fn new() -> Latest {
        Latest { shards: (0..32).map(|_| RwLock::new(HashMap::new())).collect(), by_cell: Mutex::new(HashMap::new()) }
    }

    fn shard(&self, key: &str) -> &LatestShard {
        use std::hash::{Hash, Hasher};
        let mut h = std::collections::hash_map::DefaultHasher::new();
        key.hash(&mut h);
        &self.shards[(h.finish() % self.shards.len() as u64) as usize]
    }

    /// The answer for `key` as of `a`, if one answered as of `a` or earlier is held.
    fn get(&self, key: &str, a: &str) -> Option<Arc<ReceiptInfo>> {
        let m = self.shard(key).read().unwrap_or_else(|p| p.into_inner());
        let (info, _, at) = m.get(key)?;
        (a >= at.as_str()).then(|| info.clone())
    }

    fn put(&self, key: String, cell_id: String, info: Arc<ReceiptInfo>, at: String) {
        {
            let mut b = self.by_cell.lock().unwrap_or_else(|p| p.into_inner());
            if b.len() > 200_000 {
                b.clear();
                for s in &self.shards {
                    s.write().unwrap_or_else(|p| p.into_inner()).clear();
                }
            }
            b.entry(cell_id.clone()).or_default().push(key.clone());
        }
        self.shard(&key).write().unwrap_or_else(|p| p.into_inner()).insert(key, (info, cell_id, at));
    }

    fn forget(&self, cell_id: &str) {
        let keys = self.by_cell.lock().unwrap_or_else(|p| p.into_inner()).remove(cell_id).unwrap_or_default();
        for k in keys {
            self.shard(&k).write().unwrap_or_else(|p| p.into_inner()).remove(&k);
        }
    }

    fn clear(&self) {
        self.by_cell.lock().unwrap_or_else(|p| p.into_inner()).clear();
        for s in &self.shards {
            s.write().unwrap_or_else(|p| p.into_inner()).clear();
        }
    }
}

/// Cell URI rests already parsed, by function hash (parsing depends on the signature
/// alone): resolving a hot cell costs a binding lookup and no parse.
struct Targets {
    #[allow(clippy::type_complexity)]
    shards: Vec<RwLock<HashMap<String, HashMap<String, Arc<Target>>>>>,
}

impl Targets {
    fn new() -> Targets {
        Targets { shards: (0..32).map(|_| RwLock::new(HashMap::new())).collect() }
    }

    #[allow(clippy::type_complexity)]
    fn shard(&self, rest: &str) -> &RwLock<HashMap<String, HashMap<String, Arc<Target>>>> {
        use std::hash::{Hash, Hasher};
        let mut h = std::collections::hash_map::DefaultHasher::new();
        rest.hash(&mut h);
        &self.shards[(h.finish() % self.shards.len() as u64) as usize]
    }

    fn get(&self, fn_hash: &str, rest: &str) -> Option<Arc<Target>> {
        self.shard(rest).read().unwrap_or_else(|p| p.into_inner()).get(rest)?.get(fn_hash).cloned()
    }

    fn put(&self, rest: &str, t: &Arc<Target>) {
        let mut m = self.shard(rest).write().unwrap_or_else(|p| p.into_inner());
        if m.len() >= 4_096 {
            m.clear();
        }
        let v = m.entry(rest.to_string()).or_default();
        if v.len() >= 8 {
            v.clear();
        }
        v.insert(t.bound.fn_hash.clone(), t.clone());
    }
}

/// The key of a cell's last good answer: the function hash and the URI (without asof: the
/// last good answer is kept for requests about now only).
fn last_good_key(t: &Target) -> String {
    t.cell_key().to_string()
}

/// The engine's error as an envelope code (the engine's table, "For the HTTP layer").
pub(crate) fn engine_code(e: &EngineError) -> (bool, ErrorCode) {
    match e {
        EngineError::Invalid(e) if envelope::is_request_code(e.code()) => (true, e.code()),
        EngineError::Invalid(e) if envelope::is_error_code(e.code()) => (false, e.code()),
        EngineError::NameUnresolved { .. } => (false, ErrorCode::FnUnavailable),
        EngineError::UndeclaredInput { .. } => (false, ErrorCode::InputUndeclared),
        EngineError::Sign(e) if envelope::is_error_code(e.code()) => (false, e.code()),
        EngineError::Store(_) => (false, ErrorCode::InputUnavailable),
        _ => (false, ErrorCode::EvalUnavailable),
    }
}

impl Inner {
    pub(crate) fn now(&self) -> String {
        self.clock.now()
    }

    /// A descriptor by hash (cached: content-addressed).
    pub(crate) fn descriptor(&self, fn_hash: &str) -> Result<Arc<FunctionDescriptor>, ErrorCode> {
        if let Some(d) = self.descriptors.lock().unwrap_or_else(|p| p.into_inner()).get(fn_hash) {
            return Ok(d.clone());
        }
        let bytes = self.store.descriptor(fn_hash).ok_or(ErrorCode::FnUnavailable)?;
        let d = Arc::new(FunctionDescriptor::from_json(&bytes).map_err(|_| ErrorCode::FnUnavailable)?);
        let mut m = self.descriptors.lock().unwrap_or_else(|p| p.into_inner());
        if m.len() > 10_000 {
            m.clear();
        }
        m.insert(fn_hash.to_string(), d.clone());
        Ok(d)
    }

    /// The `ok` reply with a receipt, remembered for `stale` answers.
    fn ok_reply(
        &self,
        target: &Target,
        info: Arc<ReceiptInfo>,
        a: &str,
        now: &str,
        private: bool,
        link: bool,
    ) -> Reply {
        let mut reply = Reply::json(200, info.ok.clone(), Cache::Immutable);
        if target.asof().is_none() {
            let mut lg = self.last_good.lock().unwrap_or_else(|p| p.into_inner());
            if lg.len() > 100_000 {
                lg.clear();
            }
            lg.insert(last_good_key(target), LastGood { info, at: Instant::now() });
        }
        self.cache_rules(&mut reply, target, a, now, private, link);
        reply
    }

    /// Remembers the answer as of now `a` for a local stored cell, when it is the cell's
    /// latest version (a version with a later `tx` would answer later asofs).
    fn remember_latest(&self, target: &Target, info: &Arc<ReceiptInfo>, a: &str) {
        match self.store.latest(target.cell_id()) {
            Ok(Some(v)) if v.receipt_hash == info.hash => {
                self.latest.put(
                    target.cell_key().to_string(),
                    target.cell_id().to_string(),
                    info.clone(),
                    a.to_string(),
                );
            }
            _ => {}
        }
    }

    /// A stored version was added for `cell_id`: the engine's memo, the latest answers and
    /// the slice cache forget what rests on it.
    pub(crate) fn version_added(&self, cell_id: &str) {
        self.engine.stored_version_added(cell_id);
        self.latest.forget(cell_id);
        self.slices.lock().unwrap_or_else(|p| p.into_inner()).clear();
        self.known.lock().unwrap_or_else(|p| p.into_inner()).announce(cell_id);
    }

    /// The receipt's hash, asof, trust and `ok` envelope (cached by its bytes).
    fn receipt_info(&self, bytes: &[u8]) -> Option<Arc<ReceiptInfo>> {
        use std::hash::{Hash, Hasher};
        let mut h = std::collections::hash_map::DefaultHasher::new();
        bytes.hash(&mut h);
        let key = h.finish();
        let shard = &self.infos[(key % self.infos.len() as u64) as usize];
        if let Some(i) = shard.lock().unwrap_or_else(|p| p.into_inner()).get(&key) {
            if i.receipt == bytes {
                return Some(i.clone());
            }
        }
        let r = Receipt::from_json(bytes).ok()?;
        let trust = envelope::trust_label_of(&r, &self.config.host);
        let ok = envelope::with_fn_hash(datumesh_core::Answer::ok(r.clone(), trust), Some(&r.cell().fn_hash)).to_json();
        let info = Arc::new(ReceiptInfo {
            hash: r.hash().to_string(),
            asof: r.asof().to_string(),
            receipt: bytes.to_vec(),
            parsed: r,
            trust,
            ok: ok.into(),
        });
        let mut m = shard.lock().unwrap_or_else(|p| p.into_inner());
        if m.len() >= 4_096 {
            m.clear();
        }
        m.insert(key, info.clone());
        Some(info)
    }

    /// A receipt's info by its hash: from the cache, else the store.
    pub(crate) fn receipt_info_by_hash(&self, hash: &str) -> Option<Arc<ReceiptInfo>> {
        use std::hash::{Hash, Hasher};
        let mut h = std::collections::hash_map::DefaultHasher::new();
        hash.hash(&mut h);
        let shard = &self.by_hash[(h.finish() % self.by_hash.len() as u64) as usize];
        if let Some(i) = shard.lock().unwrap_or_else(|p| p.into_inner()).get(hash) {
            return Some(i.clone());
        }
        let bytes = self.store.receipt(hash)?;
        let info = self.receipt_info(&bytes)?;
        let mut m = shard.lock().unwrap_or_else(|p| p.into_inner());
        if m.len() >= 2_048 {
            m.clear();
        }
        m.insert(hash.to_string(), info.clone());
        Some(info)
    }

    /// The reply to a request the call parser rejected.
    pub(crate) fn rejection(&self, r: Rejection, asof: Option<&str>) -> Reply {
        match r {
            Rejection::BadRequest(c) => envelope::bad_request_reply(c),
            Rejection::NotCovered => {
                let _ = asof;
                Reply::json(404, envelope::not_covered(None), Cache::Public(self.config.ttl.latest_max_age.as_secs()))
            }
            Rejection::Error(ErrorCode::NameUnbound) => {
                envelope::name_unbound_reply(self.config.ttl.latest_max_age.as_secs())
            }
            Rejection::Error(ErrorCode::ForeignUnavailable) => {
                // The other mesh could not be reached while resolving the name (spec-0.4.3).
                let d = FOREIGN_DETAIL.with(|d| d.take()).unwrap_or(datumesh_core::ForeignDetail::Network);
                envelope::answer_reply(&datumesh_core::Answer::foreign_unavailable(d), Cache::NoStore)
            }
            Rejection::Error(c) => envelope::error_reply(c),
        }
    }

    /// The licence and payment rules for a target and principal: a refusal, and whether the
    /// answer depends on who asks.
    pub(crate) fn policy(&self, target: &Target, principal: Option<&Principal>) -> (Option<Reply>, bool) {
        if self.config.policy.rules.is_empty() {
            return (None, false);
        }
        match self.config.policy.rule(&target.fn_name()) {
            None => (None, false),
            Some(Rule::Principals(ps)) => {
                if principal.is_some_and(|p| ps.contains(&p.id)) {
                    (None, true)
                } else {
                    let a = envelope::with_fn_hash(datumesh_core::Answer::unlicensed(), Some(&target.bound.fn_hash));
                    (Some(envelope::answer_reply(&a, Cache::Private)), true)
                }
            }
            Some(Rule::Price { amount, currency }) => {
                let authorise = format!("{}/pay/{}", self.config.origin(), target.cell_id());
                let quote = datumesh_core::Quote { amount: amount.clone(), currency: currency.clone(), authorise };
                let a =
                    envelope::with_fn_hash(datumesh_core::Answer::payment_required(quote), Some(&target.bound.fn_hash));
                (Some(envelope::answer_reply(&a, Cache::Private)), true)
            }
        }
    }

    /// Answers a `/cell` request (blocking; no budget: see [`Mesh::cell`]). `on_target` is
    /// told the request description as soon as it is known (for `pending`).
    pub(crate) fn answer(
        &self,
        rest: &str,
        principal: Option<&Principal>,
        bindings: &dyn Bindings,
        now: &str,
        on_target: &mut dyn FnMut(&Target),
    ) -> Reply {
        self.answer_with(rest, principal, bindings, now, on_target, true)
    }

    /// As [`Inner::answer`]; without the canonical link when `link` is false (a batch's
    /// envelopes have no headers).
    pub(crate) fn answer_with(
        &self,
        rest: &str,
        principal: Option<&Principal>,
        bindings: &dyn Bindings,
        now: &str,
        on_target: &mut dyn FnMut(&Target),
        link: bool,
    ) -> Reply {
        let target = match call::resolve(rest, now, &self.config.aliases, bindings, false) {
            Ok(t) => t,
            Err(r) => return self.rejection(r, None),
        };
        on_target(&target);
        let (refused, private) = self.policy(&target, principal);
        let reply = match refused {
            Some(r) => r,
            None => self.answer_target(&target, now, private, link),
        };
        // What the request resolved is per request: the answers are built from cached bytes.
        match &target.resolved {
            Some(r) => envelope::with_resolved(reply, r),
            None => reply,
        }
    }

    /// Answers a resolved target as of its asof (or `now`).
    pub(crate) fn answer_target(&self, target: &Target, now: &str, private: bool, link: bool) -> Reply {
        let a = target.asof().unwrap_or(now);
        let stored = target.bound.descriptor.lang == "stored";
        let local = stored && !self.foreign.is_foreign(&target.cell.ns);
        if local {
            if let Some(info) = self.latest.get(target.cell_key(), a) {
                let mut reply = Reply::json(200, info.ok.clone(), Cache::Immutable);
                self.cache_rules(&mut reply, target, a, now, private, link);
                return reply;
            }
        }
        if let Err(e) = self.foreign.prepare(&target.cell, stored, target.asof()) {
            return self.unavailable(target, e);
        }
        // Since 0.2.1: before computing another mesh's function, its publisher's key document
        // (its declarations, SPEC 8.5), fetched again after its TTL.
        if !stored {
            if let Err(e) = self.foreign.ensure_publisher(&target.cell.ns) {
                return self.unavailable(target, e);
            }
        }
        let mut attempt = 0;
        loop {
            let r = self.engine.get_cell(&target.cell, Some(a));
            let inval = self.foreign.take_invalidated();
            for id in &inval {
                self.version_added(id);
            }
            if !inval.is_empty() && attempt < 2 {
                attempt += 1;
                continue;
            }
            // A formula cell answered: the describe index learns of it (CONTRACT-1.8b H4).
            if !stored && matches!(r, Ok(Answer::Receipt(_))) {
                self.known.lock().unwrap_or_else(|p| p.into_inner()).note_computed(&target.cell);
            }
            return match r {
                Ok(Answer::Receipt(bytes)) => {
                    let Some(info) = self.receipt_info(&bytes) else {
                        return envelope::error_answer_reply(ErrorCode::EvalUnavailable, Some(&target.bound.fn_hash));
                    };
                    if attempt < 2 {
                        match self.foreign.refresh_deps(&info.hash, a) {
                            Ok(true) => {
                                for id in self.foreign.take_invalidated() {
                                    self.version_added(&id);
                                }
                                attempt += 1;
                                continue;
                            }
                            Ok(false) => {}
                            Err(e) => return self.unavailable(target, e),
                        }
                    }
                    if local && target.asof().is_none() {
                        self.remember_latest(target, &info, a);
                    }
                    self.ok_reply(target, info, a, now, private, link)
                }
                Ok(Answer::NotCovered { fault }) => {
                    let mut ans =
                        envelope::with_fn_hash(datumesh_core::Answer::not_covered(), Some(&target.bound.fn_hash));
                    if let Some(f) = fault {
                        ans = ans.with_fault(f);
                    }
                    let mut reply = envelope::answer_reply(&ans, Cache::Public(0));
                    self.cache_rules(&mut reply, target, a, now, private, link);
                    if target.asof().is_some() {
                        reply.cache = if private {
                            Cache::Private
                        } else {
                            Cache::Public(self.config.ttl.latest_max_age.as_secs())
                        };
                    }
                    reply
                }
                Ok(_) => envelope::error_answer_reply(ErrorCode::EvalUnavailable, Some(&target.bound.fn_hash)),
                Err(EngineError::Unlicensed { cell_id, reason }) => {
                    // Licence inheritance refuses the cell (SPEC 8.5, spec-0.4.3): `unlicensed`,
                    // no new code. Not immutable: a declaration may come later.
                    tracing::info!(target: "datumesh_http", cell_id = %cell_id, reason = reason.as_str(), "unlicensed");
                    let a = envelope::with_fn_hash(datumesh_core::Answer::unlicensed(), Some(&target.bound.fn_hash));
                    let cache =
                        if private { Cache::Private } else { Cache::Public(self.config.ttl.latest_max_age.as_secs()) };
                    envelope::answer_reply(&a, cache)
                }
                Err(EngineError::Cycle { path }) => {
                    return self.cycle_reply(&path, Some(a), Some(&target.bound.fn_hash))
                }
                Err(e) => {
                    let (bad, code) = engine_code(&e);
                    tracing::info!(target: "datumesh_http", error = %e, code = code.as_str(), "engine");
                    if code == ErrorCode::ForeignUnavailable {
                        // A cross-mesh fetch inside the evaluation got no response (ForeignError::eval).
                        let detail = match &e {
                            EngineError::Invalid(c) => {
                                c.detail().strip_prefix("cross-mesh: ").unwrap_or(c.detail()).to_string()
                            }
                            other => other.to_string(),
                        };
                        return self.unavailable(target, ForeignError { code, detail });
                    }
                    if bad {
                        envelope::bad_request_reply(code)
                    } else if code == ErrorCode::InputUnavailable {
                        self.unavailable(target, ForeignError { code, detail: e.to_string() })
                    } else {
                        envelope::error_answer_reply(code, Some(&target.bound.fn_hash))
                    }
                }
            };
        }
    }

    fn cache_rules(&self, reply: &mut Reply, target: &Target, a: &str, now: &str, private: bool, link: bool) {
        let latest = self.config.ttl.latest_max_age.as_secs();
        reply.cache = if private {
            Cache::Private
        } else {
            match target.asof() {
                Some(x) if x <= now => Cache::Immutable,
                Some(_) => Cache::Public(latest),
                None => Cache::Public(latest),
            }
        };
        if link && target.asof().is_none() {
            reply.canonical = Some(format!("{}/cell/{}", self.config.origin(), target.rest_asof(a)));
        }
    }

    /// The answer when something the mesh depends on failed: `stale` with the last receipt
    /// it served for the cell, when it has one that answers the request; else `error`.
    fn unavailable(&self, target: &Target, e: ForeignError) -> Reply {
        tracing::info!(target: "datumesh_http", code = e.code.as_str(), detail = %e.detail, "unavailable");
        // A suspended namespace (9.9, 5.5): the import is refused, so `not_covered` with its error,
        // and not the last receipt served (a cell served before is served as before, not imported).
        if e.code == crate::foreign::NAMESPACE_SUSPENDED {
            if let Ok(a) = datumesh_core::Answer::not_covered().with_error(ErrorCode::NamespaceSuspended) {
                return envelope::answer_reply(&envelope::with_fn_hash(a, Some(&target.bound.fn_hash)), Cache::NoStore);
            }
        }
        let lg = self.last_good.lock().unwrap_or_else(|p| p.into_inner());
        if let Some(g) = lg.get(&last_good_key(target)) {
            if target.asof().is_none_or(|a| g.info.asof.as_str() <= a) {
                let age = g.at.elapsed().as_secs();
                let a = datumesh_core::Answer::stale(g.info.parsed.clone(), g.info.trust, age);
                let a = envelope::with_fn_hash(a, Some(&g.info.parsed.cell().fn_hash));
                return envelope::answer_reply(&a, Cache::NoStore);
            }
        }
        if let Some(d) = e.foreign_detail() {
            let a = envelope::with_fn_hash(datumesh_core::Answer::foreign_unavailable(d), Some(&target.bound.fn_hash));
            return envelope::answer_reply(&a, Cache::NoStore);
        }
        envelope::error_answer_reply(e.code, Some(&target.bound.fn_hash))
    }

    /// The keys to verify `receipt` with: the documents of its signer and of the signers of
    /// its inputs and slice members held in the store, from the cache or the store's
    /// namespace records.
    pub(crate) fn keys_for_receipt(&self, receipt: &[u8]) -> Keys {
        let mut hosts = std::collections::BTreeSet::new();
        if let Ok(v) = json::parse(receipt) {
            if let Some(h) = v.get("computed_by").and_then(Value::as_str) {
                hosts.insert(h.split('#').next().unwrap_or("").to_string());
            }
            if let Some(Value::Array(ins)) = v.get("inputs") {
                let mut members = Vec::new();
                for i in ins.iter().filter_map(Value::as_str).take(10_000) {
                    if i.starts_with("slice:") {
                        if let Some(m) =
                            self.store.manifest(i).and_then(|m| datumesh_core::Manifest::from_json(&m).ok())
                        {
                            members.extend(m.members().iter().take(10_000).cloned());
                        }
                    } else {
                        members.push(i.to_string());
                    }
                }
                for h in members.iter().take(20_000) {
                    if let Some(r) = self.store.receipt(h).and_then(|b| Receipt::from_json(&b).ok()) {
                        hosts.insert(r.signer_host().to_string());
                    }
                }
            }
        }
        let mut keys = Keys::new();
        for h in hosts {
            if let Some(r) = self.keys.result(&h) {
                keys.insert_result(&h, r);
            } else if let Some(doc) = self.key_doc(&h) {
                keys.insert(doc);
            }
        }
        keys
    }

    /// A host's key document: the cache's, else the store's namespace record.
    fn key_doc(&self, host: &str) -> Option<KeyDoc> {
        if let Some((d, _, _)) = self.keys.get(host) {
            return Some(d);
        }
        let ns = self.store.namespace(host).ok()??;
        keys_from_response(host, 200, Some(&ns.keydoc)).ok()
    }
}

fn verified(r: datumesh_core::VerifyResult) -> Verified {
    let s = |v: Option<&str>| v.map(|x| Value::String(x.to_string())).unwrap_or(Value::Null);
    let body = Value::Object(vec![
        ("blob_checked".into(), Value::Bool(r.blob_checked)),
        ("code".into(), s(r.code.map(|c| c.as_str()))),
        ("computed_by".into(), s(r.computed_by.as_deref())),
        ("detail".into(), Value::String(r.detail.clone())),
        ("hash".into(), s(r.hash.as_deref())),
        ("level".into(), s(r.level.map(|l| l.as_str()))),
        ("ok".into(), Value::Bool(r.ok)),
        ("path".into(), Value::String(r.path.clone())),
    ]);
    Verified { body: body.to_jcs() }
}

/// What `POST /verify` reports.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Verified {
    /// The result as JSON (`ok`, `level`, `code`, `hash`, `computed_by`, `path`, `detail`).
    pub body: Vec<u8>,
}

impl Mesh {
    /// A builder for a mesh on `store` with `config`.
    pub fn builder(config: Config, store: Arc<dyn Store + Send + Sync>) -> MeshBuilder {
        MeshBuilder {
            config,
            store,
            key: None,
            key_file: None,
            runtimes: Vec::new(),
            formula: true,
            clock: Arc::new(SystemClock),
            fuel: None,
            licence: None,
            memo_capacity: None,
        }
    }

    /// The configuration.
    pub fn config(&self) -> &Config {
        &self.inner.config
    }

    /// The engine.
    pub fn engine(&self) -> &Arc<Engine> {
        &self.inner.engine
    }

    /// Forgets every memoised answer (the engine's memo and the mesh's), for a process that
    /// wrote versions without telling the mesh.
    pub fn clear_memo(&self) {
        self.inner.engine.clear_memo();
        self.inner.latest.clear();
        self.inner.slices.lock().unwrap_or_else(|p| p.into_inner()).clear();
    }

    /// The cross-mesh resolver.
    pub fn foreign(&self) -> &Foreign {
        &self.inner.foreign
    }

    /// The store.
    pub fn store(&self) -> &Arc<dyn Store + Send + Sync> {
        &self.inner.store
    }

    /// The key documents the mesh holds for other hosts (fetched, or inserted here): what
    /// `POST /verify` verifies with, besides the store's namespace records.
    pub fn keys(&self) -> &KeyCache {
        &self.inner.keys
    }

    /// Tells the engine that a stored version was added for `cell_id` outside the mesh.
    pub fn stored_version_added(&self, cell_id: &str) {
        self.inner.version_added(cell_id);
    }

    /// The envelope for `rest` (a call or a cell URI's rest, query included, as received at
    /// `/cell/`), for `principal`. Blocking, and without a budget: what a `/cell` request
    /// gets when it finishes within its budget, or its job's result.
    pub fn cell(&self, rest: &str, principal: Option<&Principal>) -> Reply {
        let now = self.inner.now();
        self.inner.answer(rest, principal, &*self.inner, &now, &mut |_| {})
    }

    /// The envelopes of a batch, in order (blocking, no budget).
    pub fn cells(&self, rests: &[String], principal: Option<&Principal>) -> Vec<Reply> {
        let now = self.inner.now();
        let memo = Memo::new(&self.inner);
        rests.iter().map(|r| self.inner.answer(r, principal, &memo, &now, &mut |_| {})).collect()
    }

    /// Resolves a request to its cell, as `/cell` does (or to its slice, with `slice`).
    pub fn resolve(&self, rest: &str, slice: bool) -> Result<Arc<Target>, Rejection> {
        let now = self.inner.now();
        call::resolve(rest, &now, &self.inner.config.aliases, &*self.inner, slice)
    }

    /// The describe answer (SPEC 16.8, 9.6) for `id`: a class name, an object's key encoding, an
    /// object id, a cell id or a short id (12 hex digits). A class or an object: the body is a
    /// `describe-class` or `describe-object` document, `200`; an id the mesh does not know, `404`;
    /// a short id naming more than one object or cell the mesh knows, `400` with
    /// `E_SHORT_ID_AMBIGUOUS`. A class hash is not an id (9.6). Blocking. Since 0.2.2.
    pub fn describe(&self, id: &str) -> Reply {
        self.inner.describe(id)
    }

    /// `POST /whatif` (5.9): the scenario answer to the request's body (see [`crate::scenario`]).
    pub(crate) fn whatif(&self, body: &[u8], principal: Option<&Principal>) -> Reply {
        self.inner.whatif(body, principal)
    }

    /// Verifies a receipt (SPEC 10.1) with the mesh's keys; at level `recomputed` with the
    /// engine as the resolver unless `signed_only`; `blob` is content for step 7.7.
    pub fn verify(&self, receipt: &[u8], signed_only: bool, blob: Option<&[u8]>) -> Verified {
        let keys = self.inner.keys_for_receipt(receipt);
        let resolver: Option<&dyn datumesh_core::Resolver> =
            if signed_only { None } else { Some(&*self.inner.engine as &dyn datumesh_core::Resolver) };
        verified(verify(receipt, &keys, resolver, blob))
    }

    /// Verifies a receipt with the mesh's keys and what the caller offers for step 7: a
    /// `recompute` object as SPEC 11 describes it (`descriptor`, `inputs`, `manifests`,
    /// `lineage`, `value`), the core's `MapResolver` over it. Without one, steps 1-6 only.
    pub fn verify_offered(&self, receipt: &[u8], recompute: Option<&Value>, blob: Option<&[u8]>) -> Verified {
        let mut keys = self.inner.keys_for_receipt(receipt);
        // The signers of the receipts offered for step 7 too.
        let mut hosts = std::collections::BTreeSet::new();
        for (_, r) in recompute.and_then(|rc| rc.get("inputs")).and_then(Value::as_object).unwrap_or(&[]) {
            if let Some(h) = r
                .as_str()
                .and_then(|t| json::parse(t.as_bytes()).ok())
                .and_then(|v| v.get("computed_by").and_then(Value::as_str).map(str::to_string))
            {
                hosts.insert(h.split('#').next().unwrap_or("").to_string());
            }
        }
        for h in hosts {
            if let Some(r) = self.inner.keys.result(&h) {
                keys.insert_result(&h, r);
            } else if let Some(doc) = self.inner.key_doc(&h) {
                keys.insert(doc);
            }
        }
        let Some(rc) = recompute else {
            return verified(verify(receipt, &keys, None, blob));
        };
        let mut m = datumesh_core::MapResolver::new();
        let cell = json::parse(receipt).ok().and_then(|r| r.get("cell").cloned());
        if let (Some(d), Some(h)) =
            (rc.get("descriptor"), cell.as_ref().and_then(|c| c.get("fn_hash")).and_then(Value::as_str))
        {
            m.insert_descriptor(h, d.to_jcs());
        }
        for (h, r) in rc.get("inputs").and_then(Value::as_object).unwrap_or(&[]) {
            m.insert_receipt(h.as_str(), r.as_str().unwrap_or("").as_bytes());
        }
        for (e, t) in rc.get("manifests").and_then(Value::as_object).unwrap_or(&[]) {
            m.insert_manifest(e.as_str(), t.as_str().unwrap_or("").as_bytes());
        }
        let value = rc.get("value").and_then(|v| datumesh_core::Scalar::from_json(&v.to_jcs()).ok());
        if let (Some(value), Some(c)) = (value, cell.as_ref().and_then(|c| datumesh_core::Cell::from_value(c).ok())) {
            m.insert_value(c.id(), value);
            if let Some(Value::Array(l)) = rc.get("lineage") {
                m.insert_lineage(c.id(), l.iter().filter_map(Value::as_str));
            }
        }
        verified(verify(receipt, &keys, Some(&m), blob))
    }

    /// The mesh document (SPEC 9.6) this mesh serves: its URLs on the base URL when one is
    /// set ([`Config::base_url`]), else on `https://<host>`.
    pub fn mesh_document(&self) -> Vec<u8> {
        let o = self.inner.config.mesh_document_base();
        let ep: BTreeMap<&str, String> = [
            ("blob", format!("{o}/blob/{{sha256}}")),
            ("cell", format!("{o}/cell/{{cell}}")),
            ("cells", format!("{o}/cells")),
            ("describe", format!("{o}/describe/{{id}}")),
            ("descriptor", format!("{o}/descriptor/{{hash}}")),
            ("explain", format!("{o}/explain/{{cell}}")),
            ("find", format!("{o}/find")),
            ("jobs", format!("{o}/jobs/{{job}}")),
            ("manifest", format!("{o}/manifest/{{slice_id}}/{{members_hash}}")),
            ("receipt", format!("{o}/receipt/{{hash}}")),
            ("slice", format!("{o}/slice/{{cell}}")),
            ("verify", format!("{o}/verify")),
            ("whatif", format!("{o}/whatif")),
            ("versions", format!("{o}/versions/{{cell}}")),
        ]
        .into_iter()
        .collect();
        Value::Object(vec![
            ("bindings".into(), Value::String(format!("{o}/bindings"))),
            (
                "endpoints".into(),
                Value::Object(ep.into_iter().map(|(k, v)| (k.to_string(), Value::String(v))).collect()),
            ),
            ("host".into(), Value::String(self.inner.config.host.clone())),
            ("proto".into(), Value::String("datumesh/1".into())),
        ])
        .to_jcs()
    }

    /// The key document this mesh serves: the store's namespace record for its host.
    pub fn key_document(&self) -> Option<Vec<u8>> {
        self.inner.store.namespace(&self.inner.config.host).ok().flatten().map(|n| n.keydoc)
    }

    /// The Prometheus text of `/metrics`.
    pub fn metrics(&self) -> String {
        crate::http::metrics_text(&self.inner)
    }

    /// The number of requests counted for a route template (e.g. `/cell/{cell}`).
    pub fn requests_of(&self, route: &str) -> u64 {
        self.inner.metrics.requests_of(route)
    }

    /// The host of a function name (its first segment).
    pub fn host_of(name: &str) -> &str {
        host_of(name)
    }

    /// How long the mesh has run.
    pub fn uptime(&self) -> Duration {
        self.inner.started.elapsed()
    }
}

impl Inner {
    /// The class `name` is bound to as of `asof`, with its flattened descriptor (not noted for the
    /// describe index: see [`Bindings::class`]).
    pub(crate) fn class_binding(&self, name: &str, asof: &str) -> Result<Option<Arc<call::BoundClass>>, ErrorCode> {
        let store_failed = |e: datumesh_store::Error| {
            tracing::warn!(target: "datumesh_http", error = %e, "resolve_class_binding");
            ErrorCode::InputUnavailable
        };
        let Some(b) = self.store.resolve_class_binding(name, asof).map_err(store_failed)? else { return Ok(None) };
        let Some(bytes) = self.store.class(&b.class_hash).map_err(store_failed)? else {
            return Err(ErrorCode::InputUnavailable);
        };
        let d = datumesh_core::ClassDescriptor::from_json(&bytes).map_err(|_| ErrorCode::InputUnavailable)?;
        Ok(Some(Arc::new(call::BoundClass { class_hash: b.class_hash, since: b.tx, descriptor: Arc::new(d) })))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    /// A batch's chunks start together and ask for the same names: one store round trip per
    /// name and asof for the whole batch, not one per chunk.
    #[test]
    fn a_batch_looks_each_binding_up_once() {
        let seen = Seen::default();
        let lookups = AtomicUsize::new(0);
        let start = std::sync::Barrier::new(6);
        let look = || {
            lookups.fetch_add(1, Ordering::SeqCst);
            std::thread::sleep(Duration::from_millis(50));
            Ok(None)
        };
        std::thread::scope(|s| {
            for _ in 0..6 {
                s.spawn(|| {
                    start.wait();
                    assert!(matches!(seen.lookup("a.example/f", "2026-01-01T00:00:00Z", look), Ok(None)));
                });
            }
        });
        assert_eq!(lookups.load(Ordering::SeqCst), 1, "one lookup for six chunks");
        // Found: no lookup.
        assert!(matches!(seen.lookup("a.example/f", "2026-01-01T00:00:00Z", look), Ok(None)));
        assert_eq!(lookups.load(Ordering::SeqCst), 1);
        // Another asof, another name: looked up.
        assert!(matches!(seen.lookup("a.example/f", "2026-01-02T00:00:00Z", look), Ok(None)));
        assert!(matches!(seen.lookup("a.example/g", "2026-01-01T00:00:00Z", look), Ok(None)));
        assert_eq!(lookups.load(Ordering::SeqCst), 3);
        // A failed lookup is not kept.
        let fail = || Err(ErrorCode::InputUnavailable);
        assert!(matches!(seen.lookup("a.example/h", "2026-01-01T00:00:00Z", fail), Err(ErrorCode::InputUnavailable)));
        assert!(matches!(seen.lookup("a.example/h", "2026-01-01T00:00:00Z", look), Ok(None)));
        assert_eq!(lookups.load(Ordering::SeqCst), 4);
    }
}