datumesh-http 0.4.3

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
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
//! The endpoints: an axum router over a [`Mesh`].

use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use axum::body::{Body, Bytes};
use axum::extract::{ConnectInfo, MatchedPath, Path, Query, Request, State};
use axum::http::{header, HeaderMap, HeaderValue, StatusCode, Uri};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::Router;
use datumesh_core::json::{self, Value};
use datumesh_core::{lexical, ErrorCode, Pending, Request as CoreRequest};
use tracing::Instrument;
use utoipa::OpenApi;

use crate::apikeys::Principal;
use crate::envelope::{self, Cache, Reply, JSON};
use crate::jobs::Poll;
use crate::limit::Client;
use crate::mesh::{Inner, Memo, Mesh};

/// The principal of a request, for the access log.
#[derive(Clone)]
struct Who(Option<String>);

fn to_response(r: Reply) -> Response {
    let mut resp = Response::new(Body::from(r.body));
    *resp.status_mut() = StatusCode::from_u16(r.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
    let h = resp.headers_mut();
    h.insert(header::CONTENT_TYPE, HeaderValue::from_static(r.content_type));
    if let Ok(v) = HeaderValue::from_str(&r.cache.header()) {
        h.insert(header::CACHE_CONTROL, v);
    }
    if let Some(c) = r.canonical {
        if let Ok(v) = HeaderValue::from_str(&format!("<{c}>; rel=\"canonical\"")) {
            h.insert(header::LINK, v);
        }
    }
    if let Some(s) = r.retry_after {
        h.insert(header::RETRY_AFTER, HeaderValue::from(s));
    }
    resp
}

fn plain_json(status: u16, v: Value, cache: Cache) -> Response {
    to_response(Reply::json(status, v.to_jcs(), cache))
}

fn not_found(what: &str) -> Response {
    plain_json(404, Value::Object(vec![("error".into(), Value::String(format!("no such {what}")))]), Cache::Public(60))
}

/// The client: its IP and, with a valid API key, its principal. An `Authorization` header
/// that is not a key of this mesh is answered `unlicensed`.
fn who(inner: &Inner, headers: &HeaderMap, peer: IpAddr) -> Result<(Client, Option<Principal>), Reply> {
    let ip = client_ip(inner, headers, peer);
    match headers.get(header::AUTHORIZATION) {
        None => Ok((Client::Ip(ip), None)),
        Some(v) => {
            let p = v
                .to_str()
                .ok()
                .and_then(|s| s.strip_prefix("Bearer "))
                .and_then(|k| inner.config.api_keys.principal(k.trim()));
            match p {
                Some(p) => Ok((Client::Key(p.id.clone(), p.per_minute), Some(p.clone()))),
                None => Err(Reply::json(403, envelope::unlicensed(), Cache::Private)),
            }
        }
    }
}

fn client_ip(inner: &Inner, headers: &HeaderMap, peer: IpAddr) -> IpAddr {
    if inner.config.trust_proxy {
        if let Some(ip) = headers
            .get("x-forwarded-for")
            .and_then(|v| v.to_str().ok())
            .and_then(|s| s.rsplit(',').next())
            .and_then(|s| s.trim().parse::<IpAddr>().ok())
        {
            return ip;
        }
    }
    peer
}

fn peer_of(req: &Request) -> IpAddr {
    req.extensions().get::<ConnectInfo<SocketAddr>>().map(|c| c.0.ip()).unwrap_or(IpAddr::V4(Ipv4Addr::UNSPECIFIED))
}

/// `rest` of a `/<prefix>/<rest>` request, query included, as received.
fn rest_of(uri: &Uri, prefix: &str) -> String {
    let path = uri.path().strip_prefix(prefix).unwrap_or("");
    match uri.query() {
        Some(q) => format!("{path}?{q}"),
        None => path.to_string(),
    }
}

/// Runs `f` on the pool within the request's budget: its reply, or, past the budget, a
/// `pending` envelope whose job gets the reply when `f` finishes. `f` reports the request
/// description as soon as it knows it.
async fn within_budget(
    inner: Arc<Inner>,
    f: impl FnOnce(&Inner, &mut dyn FnMut(&crate::call::Target)) -> Reply + Send + 'static,
) -> Reply {
    let deadline = tokio::time::Instant::now() + inner.config.budget;
    let (tx, mut rx) = tokio::sync::watch::channel::<Option<CoreRequest>>(None);
    let pool = inner.pool.clone();
    let i2 = inner.clone();
    let mut task = tokio::spawn(async move {
        pool.run(move || {
            let mut on = |t: &crate::call::Target| {
                if let Some(r) = request_of(t) {
                    let _ = tx.send(Some(r));
                }
            };
            f(&i2, &mut on)
        })
        .await
    });
    match tokio::time::timeout_at(deadline, &mut task).await {
        Ok(Ok(Some(r))) => r,
        Ok(_) => envelope::error_reply(ErrorCode::EvalUnavailable),
        Err(_) => {
            let request = rx.borrow_and_update().clone();
            let Some(request) = request else {
                // Past the budget before the request was even resolved (the store or another
                // mesh is slow): the mesh cannot say what it is computing.
                return envelope::error_reply(ErrorCode::EvalUnavailable);
            };
            pend(inner, request, task)
        }
    }
}

/// The request description of a target: its cell id, asof and pin (spec-0.4.2).
fn request_of(t: &crate::call::Target) -> Option<CoreRequest> {
    let r = CoreRequest::new(t.cell_id(), t.asof()).ok()?;
    match &t.pin {
        Some(p) => r.with_pin(p).ok(),
        None => Some(r),
    }
}

/// A job for a request still running in `task`.
fn pend(inner: Arc<Inner>, request: CoreRequest, task: tokio::task::JoinHandle<Option<Reply>>) -> Reply {
    let Some(id) = inner.jobs.create(request.clone()) else {
        return envelope::error_reply(ErrorCode::EvalUnavailable);
    };
    let poll = format!("{}/jobs/{id}", inner.config.origin());
    let est = inner.jobs.estimate(inner.config.budget.as_secs());
    let i2 = inner.clone();
    let id2 = id.clone();
    tokio::spawn(async move {
        let r = match task.await {
            Ok(Some(r)) if r.status != 202 => r,
            _ => envelope::error_reply(ErrorCode::EvalUnavailable),
        };
        let mut r = r;
        r.cache = Cache::NoStore;
        r.canonical = None;
        i2.jobs.complete(&id2, r);
    });
    match Pending::new(&id, est, &poll, request) {
        Ok(p) => Reply::json(202, envelope::pending(&p), Cache::NoStore),
        Err(_) => envelope::error_reply(ErrorCode::EvalUnavailable),
    }
}

fn admit(inner: &Inner, client: &Client, cost: u32) -> Result<(), Reply> {
    inner.limiter.admit(client, cost).map_err(envelope::rate_limited_reply)
}

#[derive(OpenApi)]
#[openapi(
    info(
        title = "datumesh-mesh",
        description = "The Datumesh engine behind HTTPS (spec-0.4.1): cell envelopes (SPEC 5.5), batches, slices, receipts, descriptors, manifests, blobs, lineage, search, verification, jobs, key and mesh documents (SPEC 9.2, 9.6), bindings (SPEC 9.7).",
        license(name = "Apache-2.0")
    ),
    paths(
        cell,
        cells,
        slice,
        versions,
        receipt,
        descriptor,
        manifest,
        blob,
        explain,
        find,
        verify_receipt,
        job,
        key_document,
        mesh_document,
        bindings,
        describe,
        whatif,
        health,
        metrics,
        openapi_json
    )
)]
struct ApiDoc;

/// The OpenAPI document (generated from the handlers' annotations).
pub fn openapi() -> utoipa::openapi::OpenApi {
    ApiDoc::openapi()
}

/// The envelope of a cell.
#[utoipa::path(get, path = "/cell/{cell}",
    params(("cell" = String, Path, description = "A cell URI's rest (SPEC 5.3), byte for byte, `asof` included; or a call (SPEC 15.3's read syntax, URL-encoded) with an optional `?asof=`.")),
    responses(
        (status = 200, description = "`ok` or `stale`", content_type = "application/json"),
        (status = 202, description = "`pending`: poll the job (SPEC 5.5)", content_type = "application/json"),
        (status = 400, description = "`bad_request`", content_type = "application/json"),
        (status = 402, description = "`payment_required`", content_type = "application/json"),
        (status = 403, description = "`unlicensed`", content_type = "application/json"),
        (status = 404, description = "`not_covered` (with `fault` when the evaluation faulted)", content_type = "application/json"),
        (status = 406, description = "the Accept header excludes JSON"),
        (status = 429, description = "`rate_limited`, with `Retry-After`", content_type = "application/json"),
        (status = 500, description = "`error`", content_type = "application/json"),
        (status = 503, description = "`error`: the store or another mesh is unavailable", content_type = "application/json"),
    ))]
async fn cell(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
    let inner = mesh.inner.clone();
    let (client, principal) = match who(&inner, &headers, peer_of(&req)) {
        Ok(x) => x,
        Err(r) => return to_response(r),
    };
    let mut resp = match admit(&inner, &client, 1) {
        Err(r) => to_response(r),
        Ok(()) => {
            let rest = rest_of(&uri, "/cell/");
            let p = principal.clone();
            let r = within_budget(inner.clone(), move |i, on| {
                let now = i.now();
                i.answer(&rest, p.as_ref(), i, &now, on)
            })
            .await;
            if let Some(o) = r.outcome() {
                inner.metrics.outcome("/cell/{cell}", &o);
            }
            to_response(r)
        }
    };
    resp.extensions_mut().insert(Who(principal.map(|p| p.id)));
    resp
}

/// A batch of cells.
#[utoipa::path(post, path = "/cells",
    request_body(content = String, description = "A JSON array of requests, each a call or a cell URI (`cell://...`) as a string, or `{\"cell\": <that>}`; at most the configured bound (1,000).", content_type = "application/json"),
    responses(
        (status = 200, description = "A JSON array of envelopes, in order; each has the HTTP status its outcome has (`error`: 500)", content_type = "application/json"),
        (status = 400, description = "Not such an array, or too long", content_type = "application/json"),
        (status = 429, description = "`rate_limited` (a batch of n cells counts as n / 50 requests)", content_type = "application/json"),
    ))]
async fn cells(State(mesh): State<Mesh>, headers: HeaderMap, req: Request) -> Response {
    let inner = mesh.inner.clone();
    let peer = peer_of(&req);
    let (client, principal) = match who(&inner, &headers, peer) {
        Ok(x) => x,
        Err(r) => return to_response(r),
    };
    let body = match axum::body::to_bytes(req.into_body(), 64 << 20).await {
        Ok(b) => b,
        Err(_) => return to_response(envelope::bad_request_reply(ErrorCode::CanonLimit)),
    };
    let items = match parse_batch(&body, inner.config.batch_max) {
        Ok(i) => i,
        // A refusal of the whole batch (5.7): one envelope.
        Err((code, detail)) => {
            tracing::info!(target: "datumesh_http", detail = %detail, "batch refused");
            return to_response(envelope::bad_request_reply(code));
        }
    };
    if let Err(r) = admit(&inner, &client, inner.limiter.batch_cost(items.len())) {
        return to_response(r);
    }
    let pieces = batch(inner.clone(), items, principal.clone()).await;
    let mut counts: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new();
    for w in &pieces {
        for (o, k) in &w.outcomes {
            *counts.entry(o).or_default() += k;
        }
    }
    for (o, k) in counts {
        inner.metrics.outcomes("/cells", o, k);
    }
    // 5.7: [{"envelope": <the envelope>, "status": <its status>}] in request order: the
    // chunks' runs as they wrote them (the first opening the array).
    let mut out = Vec::with_capacity(pieces.iter().map(|w| w.bytes.len()).sum::<usize>() + 2);
    for w in &pieces {
        out.extend_from_slice(&w.bytes);
    }
    out.extend_from_slice(if pieces.is_empty() { b"[]" } else { b"]" });
    let mut resp =
        to_response(Reply::json(200, out, if principal.is_some() { Cache::Private } else { Cache::NoStore }));
    resp.extensions_mut().insert(Who(principal.map(|p| p.id)));
    resp
}

fn batch_error(e: &str) -> Response {
    plain_json(400, Value::Object(vec![("error".into(), Value::String(e.to_string()))]), Cache::NoStore)
}

/// The batch's requests, or the code of its refusal: `E_PARSE_URI` for a body that is not an
/// array of requests, `E_CANON_LIMIT` for more than the mesh accepts (5.7).
fn parse_batch(body: &[u8], max: usize) -> Result<Vec<String>, (ErrorCode, String)> {
    let pu = |m: String| (ErrorCode::ParseUri, m);
    // The body is a list of requests, not a protocol object: plain JSON.
    let v: serde_json::Value = serde_json::from_slice(body).map_err(|e| pu(format!("not JSON: {e}")))?;
    let serde_json::Value::Array(items) = v else { return Err(pu("not a JSON array".into())) };
    if items.len() > max {
        return Err((ErrorCode::CanonLimit, format!("{} requests: at most {max}", items.len())));
    }
    items
        .into_iter()
        .map(|i| {
            let s = match i {
                serde_json::Value::String(s) => s,
                serde_json::Value::Object(mut o) => match o.remove("cell") {
                    Some(serde_json::Value::String(s)) => s,
                    _ => return Err(pu("an object without a string cell".to_string())),
                },
                _ => return Err(pu("an item that is neither a string nor an object".to_string())),
            };
            Ok(match s.strip_prefix("cell://") {
                Some(r) => r.to_string(),
                None => s,
            })
        })
        .collect()
}

/// A run of a batch's answers as 5.7 writes them: the items
/// `{"envelope": <the envelope>, "status": <its status>}` (JCS member order) joined by commas,
/// and how many of each outcome they hold. Each chunk writes its own on the pool, in
/// parallel: reading 1,000 envelopes (each a receipt, the function hash echoed) to copy and
/// count them is the costliest part of a warm batch after the answers themselves.
#[derive(Default)]
struct Written {
    bytes: Vec<u8>,
    outcomes: Vec<(String, u64)>,
}

impl Written {
    /// The run of `replies`, opening the array when `first`, else continuing it.
    fn of<'a>(first: bool, replies: impl Iterator<Item = &'a Reply> + Clone) -> Written {
        let mut w = Written {
            bytes: Vec::with_capacity(replies.clone().map(|r| r.body.len() + 32).sum::<usize>() + 1),
            outcomes: vec![],
        };
        w.bytes.push(if first { b'[' } else { b',' });
        for (i, r) in replies.enumerate() {
            if i > 0 {
                w.bytes.push(b',');
            }
            w.push(r);
        }
        w
    }

    fn push(&mut self, r: &Reply) {
        self.bytes.extend_from_slice(b"{\"envelope\":");
        self.bytes.extend_from_slice(&r.body);
        self.bytes.extend_from_slice(b",\"status\":");
        push_u16(&mut self.bytes, r.status);
        self.bytes.push(b'}');
        if let Some(o) = r.outcome_str() {
            match self.outcomes.iter_mut().find(|(x, _)| x == o) {
                Some((_, k)) => *k += 1,
                None => self.outcomes.push((o.to_string(), 1)),
            }
        }
    }
}

/// Appends `n` in decimal (a JSON integer).
fn push_u16(out: &mut Vec<u8>, n: u16) {
    let mut buf = [0u8; 5];
    let (mut i, mut n) = (buf.len(), n);
    loop {
        i -= 1;
        buf[i] = b'0' + (n % 10) as u8;
        n /= 10;
        if n == 0 {
            break;
        }
    }
    out.extend_from_slice(&buf[i..]);
}

/// The machine's parallelism, read once: `available_parallelism` reads the cgroup files on
/// Linux (hundreds of microseconds in a container), too slow to pay on every batch.
fn cores() -> usize {
    static CORES: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
    *CORES.get_or_init(|| std::thread::available_parallelism().map(|c| c.get()).unwrap_or(4))
}

/// Answers a batch within the budget: the requests are answered in chunks across the pool
/// (one chunk per core; bindings looked up once per name and asof within the batch), each
/// chunk writing its answers ([`Written`]). Those not answered within the budget become
/// jobs: each is resolved again to the request it describes (a store read), and its chunk's
/// answer completes the job. The runs are in request order.
async fn batch(inner: Arc<Inner>, items: Vec<String>, principal: Option<Principal>) -> Vec<Written> {
    let n = items.len();
    let deadline = tokio::time::Instant::now() + inner.config.budget;
    let chunks = n.div_ceil(64).clamp(1, inner.config.pool_size.min(cores()));
    let per = n.div_ceil(chunks).max(1);
    let ranges: Vec<(usize, usize)> =
        (0..chunks).map(|c| (c * per, ((c + 1) * per).min(n))).take_while(|(lo, hi)| lo < hi).collect();
    let now = inner.now();
    let items = Arc::new(items);
    // Each chunk's answers so far; once the budget has passed (`late`), its answers go to
    // the channel instead, to complete their jobs. A chunk done within the budget leaves
    // its answers written instead.
    let shared: Slots = Arc::new(ranges.iter().map(|_| Mutex::new(Slot::default())).collect());
    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<(usize, Reply)>();
    let seen = Arc::new(crate::mesh::Seen::default());
    let mut tasks = Vec::new();
    for (c, &(lo, hi)) in ranges.iter().enumerate() {
        let (i2, items, tx, p, now, shared) =
            (inner.clone(), items.clone(), tx.clone(), principal.clone(), now.clone(), shared.clone());
        let seen = seen.clone();
        let pool = inner.pool.clone();
        tasks.push(tokio::spawn(async move {
            pool.run(move || {
                let memo = Memo::shared(&i2, &seen);
                for k in lo..hi {
                    let reply = i2.answer_with(&items[k], p.as_ref(), &memo, &now, &mut |_| {}, false);
                    let mut slot = shared[c].lock().unwrap_or_else(|p| p.into_inner());
                    if slot.late {
                        let _ = tx.send((k, reply));
                    } else {
                        slot.answers.push((k, reply));
                    }
                }
                let mut slot = shared[c].lock().unwrap_or_else(|p| p.into_inner());
                if !slot.late {
                    let answers = std::mem::take(&mut slot.answers);
                    slot.written = Some(Written::of(c == 0, answers.iter().map(|(_, r)| r)));
                }
            })
            .await
        }));
    }
    drop(tx);
    let all = futures_join(&mut tasks, deadline).await;
    let mut done: Vec<Option<Reply>> = vec![None; n];
    let mut written: Vec<Option<Written>> = Vec::with_capacity(ranges.len());
    for slot in shared.iter() {
        let mut s = slot.lock().unwrap_or_else(|p| p.into_inner());
        s.late = true;
        for (k, r) in s.answers.drain(..) {
            done[k] = Some(r);
        }
        written.push(s.written.take());
    }
    // A chunk's run: as it wrote it, else its answers (an error for any it has none of: its
    // task panicked, or the answer completes a job).
    let runs = |done: Vec<Option<Reply>>, written: Vec<Option<Written>>| -> Vec<Written> {
        let error = envelope::error_reply(ErrorCode::EvalUnavailable);
        ranges
            .iter()
            .zip(written)
            .enumerate()
            .map(|(c, (&(lo, hi), w))| {
                w.unwrap_or_else(|| Written::of(c == 0, done[lo..hi].iter().map(|d| d.as_ref().unwrap_or(&error))))
            })
            .collect()
    };
    if all {
        return runs(done, written);
    }
    // Past the budget: every request not answered yet becomes a job, resolved again to the
    // request it describes.
    let open: Vec<usize> = ranges
        .iter()
        .zip(&written)
        .filter(|(_, w)| w.is_none())
        .flat_map(|(&(lo, hi), _)| lo..hi)
        .filter(|k| done[*k].is_none())
        .collect();
    let (i2, items2, open2, now2) = (inner.clone(), items.clone(), open.clone(), now.clone());
    let requests: Vec<Option<CoreRequest>> = inner
        .pool
        .run(move || {
            let memo = Memo::new(&i2);
            open2
                .iter()
                .map(|k| {
                    crate::call::resolve(&items2[*k], &now2, &i2.config.aliases, &memo, false)
                        .ok()
                        .and_then(|t| request_of(&t))
                })
                .collect()
        })
        .await
        .unwrap_or_default();
    let poll_base = format!("{}/jobs/", inner.config.origin());
    let est = inner.jobs.estimate(inner.config.budget.as_secs());
    let mut jobs: Vec<Option<String>> = vec![None; n];
    for (i, k) in open.iter().enumerate() {
        let reply = match requests.get(i).cloned().flatten() {
            Some(req) => match inner.jobs.create(req.clone()) {
                Some(id) => {
                    let p = Pending::new(&id, est, &format!("{poll_base}{id}"), req);
                    jobs[*k] = Some(id);
                    match p {
                        Ok(p) => Reply::json(202, envelope::pending(&p), Cache::NoStore),
                        Err(_) => envelope::error_reply(ErrorCode::EvalUnavailable),
                    }
                }
                None => envelope::error_reply(ErrorCode::EvalUnavailable),
            },
            None => envelope::error_reply(ErrorCode::EvalUnavailable),
        };
        done[*k] = Some(reply);
    }
    let i3 = inner.clone();
    tokio::spawn(async move {
        while let Some((k, mut reply)) = rx.recv().await {
            if let Some(id) = &jobs[k] {
                reply.cache = Cache::NoStore;
                reply.canonical = None;
                i3.jobs.complete(id, reply);
            }
        }
        for t in tasks {
            let _ = t.await;
        }
        // Jobs whose task ended without an answer (a panic) are given up.
        for id in jobs.into_iter().flatten() {
            if let Poll::Running(..) = i3.jobs.poll_peek(&id) {
                i3.jobs.complete(&id, envelope::error_reply(ErrorCode::EvalUnavailable));
            }
        }
    });
    runs(done, written)
}

/// A batch chunk's state: whether the budget has passed, its answers so far, and its
/// answers written once it is done within the budget.
#[derive(Default)]
struct Slot {
    late: bool,
    answers: Vec<(usize, Reply)>,
    written: Option<Written>,
}

/// Each batch chunk's state.
type Slots = Arc<Vec<Mutex<Slot>>>;

/// Waits for every task until `deadline`: whether all finished.
async fn futures_join(tasks: &mut [tokio::task::JoinHandle<Option<()>>], deadline: tokio::time::Instant) -> bool {
    for t in tasks.iter_mut() {
        if t.is_finished() {
            continue;
        }
        if tokio::time::timeout_at(deadline, t).await.is_err() {
            return false;
        }
    }
    true
}

/// The versions of a stored cell (SPEC 9.8, spec-0.4.2).
#[utoipa::path(get, path = "/versions/{cell}",
    params(("cell" = String, Path, description = "A cell URI's rest without asof (a pin allowed), then optionally `from=` and `to=` (instants, inclusive bounds on tx) as its last parameters.")),
    responses(
        (status = 200, description = "`{\"cell\", \"versions\": [{\"asof\", \"receipt\", \"tx\"}], \"next\"?}` ascending by tx", content_type = "application/json"),
        (status = 400, description = "`bad_request`", content_type = "application/json"),
        (status = 404, description = "`not_covered` (with `E_NAME_UNBOUND` for an unbound name)", content_type = "application/json"),
    ))]
async fn versions(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
        return r;
    }
    let inner = mesh.inner.clone();
    let rest = rest_of(&uri, "/versions/");
    let r = inner
        .pool
        .clone()
        .run(move || inner.versions(&rest))
        .await
        .unwrap_or_else(|| envelope::error_reply(ErrorCode::EvalUnavailable));
    to_response(r)
}

/// The most versions in one answer of the versions endpoint.
const VERSIONS_PAGE: usize = 1000;

impl Inner {
    fn versions(&self, rest: &str) -> Reply {
        // `from=` and `to=` are the endpoint's, taken off the end of the query.
        let (path, query) = match rest.split_once('?') {
            Some((p, q)) => (p, q),
            None => (rest, ""),
        };
        let mut ps: Vec<&str> = if query.is_empty() { vec![] } else { query.split('&').collect() };
        let (mut from, mut to) = (None, None);
        while let Some(last) = ps.last() {
            if let Some(v) = last.strip_prefix("from=") {
                from = Some(v.to_string());
            } else if let Some(v) = last.strip_prefix("to=") {
                to = Some(v.to_string());
            } else {
                break;
            }
            ps.pop();
        }
        for t in [&from, &to].into_iter().flatten() {
            if lexical::check_instant(t, "$").is_err() {
                return envelope::bad_request_reply(ErrorCode::CanonInstant);
            }
        }
        let cell_rest = if ps.is_empty() { path.to_string() } else { format!("{path}?{}", ps.join("&")) };
        let now = self.now();
        let target = match crate::call::resolve(&cell_rest, &now, &self.config.aliases, self, false) {
            Ok(t) => t,
            Err(r) => return self.rejection(r, None),
        };
        if target.asof().is_some() {
            return envelope::bad_request_reply(ErrorCode::ParseUri);
        }
        let lo = from.unwrap_or_else(|| "0001-01-01T00:00:00.000000Z".into());
        let hi = to.clone().unwrap_or_else(|| "9999-12-31T23:59:59.999999Z".into());
        let mut vs = match self.store.versions(target.cell_id(), &lo, &hi) {
            Ok(v) => v,
            Err(_) => return envelope::error_answer_reply(ErrorCode::InputUnavailable, Some(&target.bound.fn_hash)),
        };
        vs.sort_by(|a, b| (&a.tx, &a.receipt_hash).cmp(&(&b.tx, &b.receipt_hash)));
        let more = vs.len() > VERSIONS_PAGE;
        vs.truncate(VERSIONS_PAGE);
        let list: Vec<Value> = vs
            .iter()
            .map(|v| {
                Value::Object(vec![
                    ("asof".into(), Value::String(v.asof.clone())),
                    ("receipt".into(), Value::String(v.receipt_hash.clone())),
                    ("tx".into(), Value::String(v.tx.clone())),
                ])
            })
            .collect();
        let mut body = vec![("cell".to_string(), target.cell.to_value()), ("versions".to_string(), Value::Array(list))];
        if more {
            if let Some(last) = vs.last() {
                let us = datumesh_formula::calendar::parse_instant(&last.tx).unwrap_or(0) + 1;
                let next_from = datumesh_formula::calendar::instant_text(us).unwrap_or_default();
                let mut next = format!("{}/versions/{cell_rest}", self.config.origin());
                next.push(if cell_rest.contains('?') { '&' } else { '?' });
                next.push_str(&format!("from={next_from}"));
                if let Some(t) = &to {
                    next.push_str(&format!("&to={t}"));
                }
                body.push(("next".to_string(), Value::String(next)));
            }
        }
        Reply::json(200, Value::Object(body).to_jcs(), Cache::Public(self.config.ttl.latest_max_age.as_secs()))
    }
}

/// The members of a slice.
#[utoipa::path(get, path = "/slice/{cell}",
    params(
        ("cell" = String, Path, description = "A slice: a cell URI's rest or a call with `*` for open arguments, of a stored function; `?asof=`, `limit=` (JSON, default 1,000, at most 10,000), `after=` (the cursor of the previous page)."),
    ),
    responses(
        (status = 200, description = "JSON page of members, or with `Accept: application/vnd.apache.arrow.stream` an Arrow IPC stream", content_type = "application/json"),
        (status = 400, description = "`bad_request`", content_type = "application/json"),
        (status = 404, description = "`not_covered`", content_type = "application/json"),
    ))]
async fn slice(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
    let inner = mesh.inner.clone();
    let (client, _) = match who(&inner, &headers, peer_of(&req)) {
        Ok(x) => x,
        Err(r) => return to_response(r),
    };
    if let Err(r) = admit(&inner, &client, 1) {
        return to_response(r);
    }
    // One manifest path since spec-0.4.2: /manifest/<slice id>/<members hash>.
    let rest = rest_of(&uri, "/slice/");
    let arrow = accepts(&headers, crate::slice::ARROW);
    let r = inner
        .pool
        .clone()
        .run(move || {
            let now = inner.now();
            inner.slice(&rest, &now, arrow)
        })
        .await
        .unwrap_or_else(|| envelope::error_reply(ErrorCode::EvalUnavailable));
    to_response(r)
}

fn accepts(headers: &HeaderMap, media: &str) -> bool {
    headers
        .get_all(header::ACCEPT)
        .iter()
        .filter_map(|v| v.to_str().ok())
        .any(|v| v.split(',').any(|p| p.split(';').next().unwrap_or("").trim() == media))
}

/// Whether the client takes JSON (no `Accept`, `*/*`, `application/*` or
/// `application/json`); for slices also Arrow.
fn acceptable(headers: &HeaderMap, also: Option<&str>) -> bool {
    let vals: Vec<&str> = headers.get_all(header::ACCEPT).iter().filter_map(|v| v.to_str().ok()).collect();
    if vals.is_empty() {
        return true;
    }
    vals.iter().flat_map(|v| v.split(',')).any(|p| {
        let mut parts = p.split(';');
        let m = parts.next().unwrap_or("").trim();
        let q0 = parts.any(|x| {
            let x = x.trim();
            x == "q=0" || x == "q=0.0" || x == "q=0.00" || x == "q=0.000"
        });
        !q0 && (m == "*/*" || m == "application/*" || m == JSON || also == Some(m))
    })
}

async fn object(
    inner: Arc<Inner>,
    what: &'static str,
    f: impl FnOnce(&Inner) -> Option<Vec<u8>> + Send + 'static,
) -> Response {
    let i2 = inner.clone();
    match inner.pool.run(move || f(&i2)).await.flatten() {
        Some(bytes) => {
            let ct = if what == "blob" { "application/octet-stream" } else { JSON };
            to_response(Reply {
                status: 200,
                body: bytes.into(),
                content_type: ct,
                cache: Cache::Immutable,
                canonical: None,
                retry_after: None,
            })
        }
        None => not_found(what),
    }
}

/// The refusal of a request by its client's rate limit (or key), if it is refused.
fn ip_admit(inner: &Inner, headers: &HeaderMap, req: &Request) -> Option<Response> {
    let client = match who(inner, headers, peer_of(req)) {
        Ok((c, _)) => c,
        Err(r) => return Some(to_response(r)),
    };
    admit(inner, &client, 1).err().map(to_response)
}

/// A receipt by its hash (canonical bytes; gzip when asked).
#[utoipa::path(get, path = "/receipt/{hash}", params(("hash" = String, Path, description = "The receipt hash (SPEC 8.3).")),
    responses((status = 200, description = "The receipt's canonical JSON; immutable", content_type = "application/json"), (status = 404, description = "Not held")))]
async fn receipt(State(mesh): State<Mesh>, Path(hash): Path<String>, headers: HeaderMap, req: Request) -> Response {
    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
        return r;
    }
    if lexical::check_hex(&hash, 64, "$").is_err() {
        return not_found("receipt");
    }
    object(mesh.inner.clone(), "receipt", move |i| i.store.receipt(&hash).map(|c| c.into_owned())).await
}

/// A descriptor by its function hash.
#[utoipa::path(get, path = "/descriptor/{hash}", params(("hash" = String, Path, description = "The function hash.")),
    responses((status = 200, description = "The descriptor's canonical JSON; immutable", content_type = "application/json"), (status = 404, description = "Not held")))]
async fn descriptor(State(mesh): State<Mesh>, Path(hash): Path<String>, headers: HeaderMap, req: Request) -> Response {
    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
        return r;
    }
    if lexical::check_hex(&hash, 64, "$").is_err() {
        return not_found("descriptor");
    }
    object(mesh.inner.clone(), "descriptor", move |i| i.store.descriptor(&hash).map(|c| c.into_owned())).await
}

async fn manifest_of(inner: Arc<Inner>, entry: String) -> Response {
    object(inner, "manifest", move |i| i.store.manifest(&entry).map(|c| c.into_owned())).await
}

/// A slice manifest (SPEC 15.13), by its entry's slice id and members hash.
#[utoipa::path(get, path = "/manifest/{slice_id}/{members_hash}",
    params(("slice_id" = String, Path, description = "The slice id."), ("members_hash" = String, Path, description = "The members hash.")),
    responses((status = 200, description = "The manifest's canonical JSON; immutable", content_type = "application/json"), (status = 404, description = "Not held")))]
async fn manifest(
    State(mesh): State<Mesh>,
    Path((slice_id, members)): Path<(String, String)>,
    headers: HeaderMap,
    req: Request,
) -> Response {
    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
        return r;
    }
    if lexical::check_hex(&slice_id, 64, "$").is_err() || lexical::check_hex(&members, 64, "$").is_err() {
        return not_found("manifest");
    }
    manifest_of(mesh.inner.clone(), format!("slice:{slice_id}:{members}")).await
}

/// Blob content by SHA-256.
#[utoipa::path(get, path = "/blob/{sha256}", params(("sha256" = String, Path, description = "The content's SHA-256.")),
    responses((status = 200, description = "The bytes; immutable", content_type = "application/octet-stream"), (status = 404, description = "Not held")))]
async fn blob(State(mesh): State<Mesh>, Path(sha): Path<String>, headers: HeaderMap, req: Request) -> Response {
    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
        return r;
    }
    if lexical::check_hex(&sha, 64, "$").is_err() {
        return not_found("blob");
    }
    object(mesh.inner.clone(), "blob", move |i| i.store.blob(&sha).ok().flatten().map(|c| c.into_owned())).await
}

/// A cell's lineage as nested envelopes.
#[utoipa::path(get, path = "/explain/{cell}",
    params(("cell" = String, Path, description = "As for /cell; `depth=` (default 4, at most 16) bounds the walk.")),
    responses(
        (status = 200, description = "`{\"envelope\", \"inputs\": [{\"entry\", \"envelope\", \"inputs\"} | {\"entry\", \"slice\", \"members\"}], \"truncated\"}`", content_type = "application/json"),
        (status = 202, description = "`pending`: the cell is being computed; ask again", content_type = "application/json"),
        (status = 400, description = "`bad_request`", content_type = "application/json"),
        (status = 404, description = "`not_covered`", content_type = "application/json"),
    ))]
async fn explain(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
    let inner = mesh.inner.clone();
    let (client, principal) = match who(&inner, &headers, peer_of(&req)) {
        Ok(x) => x,
        Err(r) => return to_response(r),
    };
    if let Err(r) = admit(&inner, &client, 1) {
        return to_response(r);
    }
    let mut rest = rest_of(&uri, "/explain/");
    let mut depth = inner.config.explain_depth;
    // `depth=` is the explain's own parameter: taken off the query.
    if let Some((p, q)) = rest.clone().split_once('?') {
        let kept: Vec<&str> = q.split('&').filter(|x| !x.starts_with("depth=")).collect();
        if let Some(d) = q.split('&').find_map(|x| x.strip_prefix("depth=")) {
            depth = d.parse::<usize>().unwrap_or(depth);
        }
        rest = if kept.is_empty() { p.to_string() } else { format!("{p}?{}", kept.join("&")) };
    }
    let depth = depth.min(16);
    let r = within_budget(inner, move |i, on| {
        let now = i.now();
        let r = i.answer(&rest, principal.as_ref(), i, &now, on);
        if r.status != 200 {
            return r;
        }
        let env = json::parse(&r.body).unwrap_or(Value::Null);
        let mut budget = 2_000usize;
        let v = i.explain_node(env, depth, &mut budget);
        Reply::json(200, v.to_jcs(), Cache::NoStore)
    })
    .await;
    to_response(r)
}

impl Inner {
    /// An envelope with its inputs' envelopes, `depth` levels down, at most `budget` nodes.
    fn explain_node(&self, envelope: Value, depth: usize, budget: &mut usize) -> Value {
        let inputs: Vec<String> = envelope
            .get("receipt")
            .and_then(|r| r.get("inputs"))
            .and_then(|i| {
                if let Value::Array(a) = i {
                    Some(a.iter().filter_map(Value::as_str).map(str::to_string).collect())
                } else {
                    None
                }
            })
            .unwrap_or_default();
        let mut truncated = false;
        let mut out = Vec::new();
        for e in inputs {
            if depth == 0 || *budget == 0 {
                truncated = true;
                break;
            }
            *budget -= 1;
            if e.starts_with("slice:") {
                let m = self.store.manifest(&e).and_then(|m| datumesh_core::Manifest::from_json(&m).ok());
                let mut node = vec![("entry".to_string(), Value::String(e.clone()))];
                if let Some(m) = m {
                    node.push(("members".to_string(), envelope::num(m.members().len() as u64)));
                    node.push(("slice".to_string(), m.slice().to_value()));
                }
                out.push(Value::Object(node));
                continue;
            }
            let child = match self.receipt_info_by_hash(&e) {
                Some(info) => self.explain_node(json::parse(&info.ok).unwrap_or(Value::Null), depth - 1, budget),
                None => json::parse(&envelope::not_covered(None)).unwrap_or(Value::Null),
            };
            let mut node = vec![("entry".to_string(), Value::String(e.clone()))];
            if let Value::Object(m) = child {
                node.extend(m);
            }
            out.push(Value::Object(node));
        }
        let mut node = vec![("envelope".to_string(), envelope.clone()), ("inputs".to_string(), Value::Array(out))];
        node.push(("truncated".to_string(), Value::Bool(truncated)));
        Value::Object(node)
    }
}

#[derive(serde::Deserialize)]
struct FindQuery {
    q: Option<String>,
    limit: Option<usize>,
    summary: Option<String>,
}

/// The hybrid `/find` (CONTRACT-build2-part2-read R3; see `crate::find`), and `/find?summary=1`.
#[utoipa::path(get, path = "/find",
    params(("q" = Option<String>, Query, description = "The query: words, a name, a label, an alias or a value, or a request such as `<book> <chapter>:<verse>`. Matching is case-insensitive after NFC."), ("limit" = Option<usize>, Query, description = "At most this many results (default 10, at most 50)."), ("summary" = Option<String>, Query, description = "`1`: the catalogue summary (`classes`, `functions`, with labels, cell counts and small dictionaries) instead of results.")),
    responses((status = 200, description = "`{\"query\", \"vector\": bool, \"results\": [...], \"resolution\"?: {...}}`. Each result has `kind` (`function`, `method` or `class`), `name`, `label`, `description`, `call` (the template with typed placeholders, or the filled call of a resolved request), `match` (`exact`, `text` or `vector`), `score`, and the members of its kind (`descriptor`, `fn_hash`, `since`; a class has `class_hash` and `methods`; a method has `class`). `resolution` has `status` `exact` (`call`, `label`), `ambiguous` (`candidates`, `keys`) or `range` (`error`: `E_RANGE_REFUSED`).", content_type = "application/json")))]
async fn find(State(mesh): State<Mesh>, Query(q): Query<FindQuery>, headers: HeaderMap, req: Request) -> Response {
    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
        return r;
    }
    let inner = mesh.inner.clone();
    let query = q.q.unwrap_or_default();
    let limit = q.limit.unwrap_or(crate::find::DEFAULT_LIMIT).clamp(1, crate::find::MAX_LIMIT);
    let summary = q.summary.as_deref() == Some("1");
    let r = inner
        .pool
        .clone()
        .run(move || if summary { crate::find::summary(&inner) } else { crate::find::answer(&inner, &query, limit) })
        .await
        .unwrap_or(Value::Null);
    plain_json(200, r, Cache::Public(60))
}

#[derive(serde::Deserialize)]
struct VerifyQuery {
    level: Option<String>,
    blob: Option<String>,
    form: Option<String>,
}

/// Verification as a service: the core verifier on a submitted receipt, with this mesh's
/// keys; free, unauthenticated, rate-limited per IP.
#[utoipa::path(post, path = "/verify",
    params(("level" = Option<String>, Query, description = "`recomputed` (default: recompute with the engine as the resolver) or `signed` (steps 1-6)."), ("blob" = Option<String>, Query, description = "Blob content for step 7.7, as hex (at most 1 MiB)."), ("form" = Option<String>, Query, description = "`offered`: the body is `{\"receipt\": <its JSON text>, \"recompute\"?: <SPEC 11's recompute object>, \"blob_hex\"?}` and step 7 uses what is offered instead of this mesh's engine.")),
    request_body(content = String, description = "The receipt's JSON text, exactly as received (or the offered form).", content_type = "application/json"),
    responses(
        (status = 200, description = "`{\"ok\", \"level\", \"code\", \"hash\", \"computed_by\", \"path\", \"detail\", \"blob_checked\"}`", content_type = "application/json"),
        (status = 429, description = "`rate_limited`", content_type = "application/json"),
    ))]
async fn verify_receipt(
    State(mesh): State<Mesh>,
    Query(q): Query<VerifyQuery>,
    headers: HeaderMap,
    req: Request,
) -> Response {
    let inner = mesh.inner.clone();
    let ip = client_ip(&inner, &headers, peer_of(&req));
    if let Err(s) = inner.limiter.admit_verify(ip) {
        return to_response(envelope::rate_limited_reply(s));
    }
    let body: Bytes = match axum::body::to_bytes(req.into_body(), 4 << 20).await {
        Ok(b) => b,
        Err(_) => return batch_error("body too large"),
    };
    if q.form.as_deref() == Some("offered") {
        let Ok(v) = json::parse(&body) else { return batch_error("form=offered: not strict JSON") };
        let Some(receipt) = v.get("receipt").and_then(Value::as_str).map(|s| s.as_bytes().to_vec()) else {
            return batch_error("form=offered: no receipt text");
        };
        let blob = match v.get("blob_hex").and_then(Value::as_str).map(hex) {
            None => None,
            Some(Some(b)) if b.len() <= 1 << 20 => Some(b),
            Some(_) => return batch_error("blob_hex: hex of at most 1 MiB"),
        };
        let m = mesh.clone();
        let rc = v.get("recompute").cloned();
        let r = inner.pool.run(move || m.verify_offered(&receipt, rc.as_ref(), blob.as_deref())).await;
        return match r {
            Some(v) => to_response(Reply::json(200, v.body, Cache::NoStore)),
            None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
        };
    }
    let signed = q.level.as_deref() == Some("signed");
    let blob = match q.blob.as_deref().map(hex) {
        None => None,
        Some(Some(b)) if b.len() <= 1 << 20 => Some(b),
        Some(_) => return batch_error("blob: hex of at most 1 MiB"),
    };
    let m = mesh.clone();
    let r = inner.pool.run(move || m.verify(&body, signed, blob.as_deref())).await;
    match r {
        Some(v) => to_response(Reply::json(200, v.body, Cache::NoStore)),
        None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
    }
}

fn hex(s: &str) -> Option<Vec<u8>> {
    if !s.len().is_multiple_of(2) {
        return None;
    }
    (0..s.len()).step_by(2).map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()).collect()
}

/// A job: `pending` again while it runs, then the envelope of the original request.
#[utoipa::path(get, path = "/jobs/{job}", params(("job" = String, Path, description = "The job id of a `pending` envelope.")),
    responses(
        (status = 202, description = "`pending`, the same job and request", content_type = "application/json"),
        (status = 400, description = "`bad_request` with `E_JOB_UNKNOWN`: unknown or expired", content_type = "application/json"),
        (status = 200, description = "The completed envelope (any outcome but pending, with its status), bound to the original request", content_type = "application/json"),
    ))]
async fn job(State(mesh): State<Mesh>, Path(id): Path<String>, headers: HeaderMap, req: Request) -> Response {
    let inner = mesh.inner.clone();
    let (client, _) = match who(&inner, &headers, peer_of(&req)) {
        Ok(x) => x,
        Err(r) => return to_response(r),
    };
    if let Err(r) = admit(&inner, &client, 1) {
        return to_response(r);
    }
    let unknown = || to_response(Reply::json(400, envelope::bad_request(ErrorCode::JobUnknown), Cache::NoStore));
    let valid = (32..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
    if !valid {
        return unknown();
    }
    match inner.jobs.poll(&id) {
        Poll::Unknown => unknown(),
        Poll::Done(r) => to_response(r),
        Poll::Running(request, elapsed) => {
            let poll = format!("{}/jobs/{id}", inner.config.origin());
            match Pending::new(&id, inner.jobs.estimate(elapsed), &poll, request) {
                Ok(p) => to_response(Reply::json(202, envelope::pending(&p), Cache::NoStore)),
                Err(_) => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
            }
        }
    }
}

/// The key document (SPEC 9.2): the store's namespace record for this mesh's host.
#[utoipa::path(get, path = "/.well-known/datumesh.json", responses((status = 200, description = "The key document", content_type = "application/json"), (status = 404, description = "None stored")))]
async fn key_document(State(mesh): State<Mesh>) -> Response {
    let m = mesh.clone();
    match mesh.inner.pool.run(move || m.key_document()).await.flatten() {
        Some(doc) => to_response(Reply::json(200, doc, Cache::Public(300))),
        None => not_found("key document"),
    }
}

/// The mesh document (SPEC 9.6).
#[utoipa::path(get, path = "/.well-known/datumesh-mesh.json", responses((status = 200, description = "The mesh document", content_type = "application/json")))]
async fn mesh_document(State(mesh): State<Mesh>) -> Response {
    to_response(Reply::json(200, mesh.mesh_document(), Cache::Public(300)))
}

/// Which function each name denotes as of an instant (SPEC 9.7).
#[utoipa::path(get, path = "/bindings",
    params(("name" = String, Query, description = "A function name, percent-encoded as in SPEC 5.1; repeat for several."), ("asof" = Option<String>, Query, description = "An instant (default: now).")),
    responses((status = 200, description = "`{\"asof\", \"bindings\": {name: {\"fn_hash\", \"since\"}}}`", content_type = "application/json"), (status = 400, description = "A malformed name or asof", content_type = "application/json")))]
async fn bindings(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
        return r;
    }
    let inner = mesh.inner.clone();
    let mut names = Vec::new();
    let mut asof = None;
    for p in uri.query().unwrap_or("").split('&').filter(|p| !p.is_empty()) {
        let (k, v) = p.split_once('=').unwrap_or((p, ""));
        let Some(v) = pct_decode(v) else { return batch_error("percent-encoding (SPEC 5.1)") };
        match k {
            "name" if lexical::check_function_name(&v, "$").is_ok() => names.push(v),
            "asof" if lexical::check_instant(&v, "$").is_ok() && asof.is_none() => asof = Some(v),
            _ => return batch_error(&format!("parameter {k}")),
        }
    }
    let r = inner
        .pool
        .clone()
        .run(move || {
            let at = asof.unwrap_or_else(|| inner.now());
            let mut out = Vec::new();
            for n in names {
                if !inner.config.owns(crate::foreign::host_of(&n)) {
                    continue;
                }
                // A class name is answered with its class hash (9.7, spec-0.5.0); any other name
                // with the function it means.
                let found = match inner.store.resolve_class_binding(&n, &at) {
                    Ok(Some(c)) => ("class_hash", c.class_hash, c.tx),
                    Ok(None) => match inner.store.resolve_binding(&n, &at) {
                        Ok(Some(b)) => ("fn_hash", b.fn_hash, b.tx),
                        Ok(None) => continue,
                        Err(_) => return None,
                    },
                    Err(_) => return None,
                };
                out.push((
                    n,
                    Value::Object(vec![
                        (found.0.into(), Value::String(found.1)),
                        ("since".into(), Value::String(found.2)),
                    ]),
                ));
            }
            Some(Value::Object(vec![("asof".into(), Value::String(at)), ("bindings".into(), Value::Object(out))]))
        })
        .await
        .flatten();
    match r {
        Some(v) => plain_json(200, v, Cache::Public(inner_latest(&mesh))),
        None => to_response(envelope::error_reply(ErrorCode::InputUnavailable)),
    }
}

fn inner_latest(mesh: &Mesh) -> u64 {
    mesh.inner.config.ttl.latest_max_age.as_secs()
}

/// Strict percent-decoding (SPEC 5.1): literal characters as themselves, `%` and two
/// uppercase hex digits for other bytes, UTF-8.
fn pct_decode(s: &str) -> Option<String> {
    let b = s.as_bytes();
    let mut out = Vec::new();
    let mut i = 0;
    while i < b.len() {
        let c = b[i];
        if c == b'%' {
            let h = b.get(i + 1..i + 3)?;
            if !h.iter().all(|x| x.is_ascii_digit() || (b'A'..=b'F').contains(x)) {
                return None;
            }
            let v = u8::from_str_radix(std::str::from_utf8(h).ok()?, 16).ok()?;
            if v.is_ascii_alphanumeric() || matches!(v, b'-' | b'.' | b'_' | b'~' | b':') {
                return None;
            }
            out.push(v);
            i += 3;
        } else if c.is_ascii_alphanumeric() || matches!(c, b'-' | b'.' | b'_' | b'~' | b':') {
            out.push(c);
            i += 1;
        } else {
            return None;
        }
    }
    String::from_utf8(out).ok()
}

/// Liveness and the store's health.
#[utoipa::path(get, path = "/health", responses((status = 200, description = "`{\"status\": \"ok\"}`", content_type = "application/json"), (status = 503, description = "The store does not answer", content_type = "application/json")))]
async fn health(State(mesh): State<Mesh>) -> Response {
    let m = mesh.clone();
    let ok = tokio::time::timeout(
        Duration::from_secs(5),
        mesh.inner.pool.run(move || m.inner.store.namespace(&m.inner.config.host).is_ok()),
    )
    .await
    .ok()
    .flatten()
    .unwrap_or(false);
    let v = Value::Object(vec![("status".into(), Value::String(if ok { "ok" } else { "store unavailable" }.into()))]);
    plain_json(if ok { 200 } else { 503 }, v, Cache::NoStore)
}

/// Prometheus metrics.
#[utoipa::path(get, path = "/metrics", responses((status = 200, description = "Prometheus text", content_type = "text/plain")))]
async fn metrics(State(mesh): State<Mesh>) -> Response {
    let mut r = Reply::json(200, metrics_text(&mesh.inner).into_bytes(), Cache::NoStore);
    r.content_type = "text/plain; version=0.0.4";
    to_response(r)
}

/// This document.
#[utoipa::path(get, path = "/openapi.json", responses((status = 200, description = "The OpenAPI document", content_type = "application/json")))]
async fn openapi_json() -> Response {
    let mut r = Reply::json(200, openapi().to_json().unwrap_or_default().into_bytes(), Cache::Public(300));
    r.content_type = JSON;
    to_response(r)
}

pub(crate) fn metrics_text(inner: &Inner) -> String {
    use std::fmt::Write;
    use std::sync::atomic::Ordering::Relaxed;
    let mut out = String::new();
    inner.metrics.write(&mut out);
    let p = &inner.pool;
    let g = |out: &mut String, name: &str, help: &str, kind: &str, v: String| {
        let _ = writeln!(out, "# HELP {name} {help}\n# TYPE {name} {kind}\n{name} {v}");
    };
    g(&mut out, "datumesh_pool_size", "The blocking pool's size: the concurrency limit.", "gauge", p.size.to_string());
    g(&mut out, "datumesh_pool_in_use", "Pool threads busy now.", "gauge", p.in_use.load(Relaxed).to_string());
    g(&mut out, "datumesh_pool_peak", "The most pool threads busy at once.", "gauge", p.peak.load(Relaxed).to_string());
    g(&mut out, "datumesh_pool_runs_total", "Tasks run on the pool.", "counter", p.runs.load(Relaxed).to_string());
    g(
        &mut out,
        "datumesh_pool_waited_total",
        "Tasks that found the pool saturated and waited for a thread.",
        "counter",
        p.waited.load(Relaxed).to_string(),
    );
    let (held, running) = inner.jobs.counts();
    g(&mut out, "datumesh_jobs_held", "Jobs held (running or done).", "gauge", held.to_string());
    g(&mut out, "datumesh_jobs_running", "Jobs running.", "gauge", running.to_string());
    g(
        &mut out,
        "datumesh_jobs_created_total",
        "Requests answered pending.",
        "counter",
        inner.jobs.created.load(Relaxed).to_string(),
    );
    g(
        &mut out,
        "datumesh_rate_limited_total",
        "Requests refused by a rate limit.",
        "counter",
        inner.limiter.refused.load(Relaxed).to_string(),
    );
    g(
        &mut out,
        "datumesh_peer_fetches_total",
        "Requests to other meshes.",
        "counter",
        inner.foreign.fetches.load(Relaxed).to_string(),
    );
    g(
        &mut out,
        "datumesh_peer_failures_total",
        "Requests to other meshes that failed.",
        "counter",
        inner.foreign.failures.load(Relaxed).to_string(),
    );
    g(
        &mut out,
        "datumesh_peer_imported_total",
        "Foreign versions imported into the store.",
        "counter",
        inner.foreign.imported.load(Relaxed).to_string(),
    );
    let m = inner.engine.memo_stats();
    g(&mut out, "datumesh_memo_entries", "Engine memo entries.", "gauge", m.entries.to_string());
    g(&mut out, "datumesh_memo_bytes", "Engine memo size, approximately.", "gauge", m.approx_bytes.to_string());
    g(
        &mut out,
        "datumesh_uptime_seconds",
        "Seconds since the mesh started.",
        "gauge",
        inner.started.elapsed().as_secs().to_string(),
    );
    out
}

/// Request ids, the access log, metrics and `Accept`.
async fn around(State(mesh): State<Mesh>, req: Request, next: Next) -> Response {
    let start = Instant::now();
    let route = req.extensions().get::<MatchedPath>().map(|m| m.as_str().to_string()).unwrap_or_else(|| "other".into());
    let route = match route.as_str() {
        "/cell/{*rest}" => "/cell/{cell}".to_string(),
        "/slice/{*rest}" => "/slice/{cell}".to_string(),
        "/explain/{*rest}" => "/explain/{cell}".to_string(),
        "/versions/{*rest}" => "/versions/{cell}".to_string(),
        "/fn/{*name}" => "/fn/{name}".to_string(),
        _ => route,
    };
    let id = req
        .headers()
        .get("x-request-id")
        .and_then(|v| v.to_str().ok())
        .filter(|s| !s.is_empty() && s.len() <= 64 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'))
        .map(str::to_string)
        .unwrap_or_else(|| {
            let mut b = [0u8; 8];
            let _ = getrandom::fill(&mut b);
            lexical::to_hex(&b)
        });
    let ip = client_ip(&mesh.inner, req.headers(), peer_of(&req));
    let method = req.method().clone();
    let also = if route == "/slice/{cell}" { Some(crate::slice::ARROW) } else { None };
    // The function page is HTML for people (Build 2 Part 4, P2) as well as JSON for agents.
    let html_ok = route == "/fn/{name}" && accepts(req.headers(), "text/html");
    let mut resp = if route != "/blob/{sha256}" && route != "/metrics" && !html_ok && !acceptable(req.headers(), also) {
        let mut r = Reply::json(
            406,
            Value::Object(vec![("error".into(), Value::String("not acceptable: application/json only".into()))])
                .to_jcs(),
            Cache::NoStore,
        );
        r.content_type = JSON;
        to_response(r)
    } else {
        next.run(req).instrument(tracing::info_span!("request", request_id = %id)).await
    };
    let elapsed = start.elapsed();
    let status = resp.status().as_u16();
    mesh.inner.metrics.record(&route, status, elapsed);
    let principal = resp.extensions().get::<Who>().and_then(|w| w.0.clone());
    tracing::info!(target: "datumesh_http::access", request_id = %id, %method, route = %route, status, ms = elapsed.as_secs_f64() * 1000.0, ip = %ip, principal = principal.as_deref().unwrap_or("-"), "request");
    if let Ok(v) = HeaderValue::from_str(&id) {
        resp.headers_mut().insert("x-request-id", v);
    }
    resp.headers_mut().insert(header::VARY, HeaderValue::from_static("Accept, Accept-Encoding, Authorization"));
    if let Ok(v) = HeaderValue::from_str(&format!("app;dur={:.3}", elapsed.as_secs_f64() * 1000.0)) {
        resp.headers_mut().insert("server-timing", v);
    }
    resp
}

/// describe (SPEC 16.8): a class or an object, by class name, key encoding, object id, cell id or
/// short id (`{id}`, percent-encoded as a path). A class's method table gives each method its
/// `description` from the catalog entry `{class}/{method}` when that is 1 to 1,024 bytes.
/// `POST /whatif` (spec-0.6.0, 5.9): the scenario of a cell under overrides, labelled a scenario,
/// never a fact.
#[utoipa::path(post, path = "/whatif",
    request_body(content = String, description = "The JSON of 5.9: `cell`, `asof`?, `overrides`, `solve`?", content_type = "application/json"),
    responses(
        (status = 200, description = "`scenario`: `{asof, cell, overrides, type, value[, solved]}`, no receipt", content_type = "application/json"),
        (status = 400, description = "`bad_request`", content_type = "application/json"),
        (status = 404, description = "`not_covered`, with `fault` when the scenario faulted or has no solution", content_type = "application/json"),
        (status = 500, description = "`error`", content_type = "application/json"),
    ))]
async fn whatif(State(mesh): State<Mesh>, headers: HeaderMap, req: Request) -> Response {
    let inner = mesh.inner.clone();
    let peer = peer_of(&req);
    let (client, principal) = match who(&inner, &headers, peer) {
        Ok(x) => x,
        Err(r) => return to_response(r),
    };
    if let Err(r) = admit(&inner, &client, 1) {
        return to_response(r);
    }
    let body = match axum::body::to_bytes(req.into_body(), 1 << 20).await {
        Ok(b) => b,
        Err(_) => return to_response(envelope::bad_request_reply(ErrorCode::CanonLimit)),
    };
    let mesh2 = mesh.clone();
    match inner.pool.clone().run(move || mesh2.whatif(&body, principal.as_ref())).await {
        Some(r) => to_response(r),
        None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
    }
}

#[utoipa::path(get, path = "/describe/{id}",
    params(("id" = String, Path, description = "A class name, an object's key encoding, an object id, a cell id or a short id (12 hex digits).")),
    responses((status = 200, description = "A describe-class or describe-object document (SPEC 16.8)", content_type = "application/json"), (status = 400, description = "`E_KEY_ENCODING`, `E_KEY_NORMALISATION` or `E_SHORT_ID_AMBIGUOUS`", content_type = "application/json"), (status = 404, description = "An id the mesh does not know", content_type = "application/json")))]
async fn describe(State(mesh): State<Mesh>, uri: Uri, headers: HeaderMap, req: Request) -> Response {
    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
        return r;
    }
    let Some(id) = crate::call::url_decode(uri.path().strip_prefix("/describe/").unwrap_or("")) else {
        return to_response(envelope::bad_request_reply(ErrorCode::CanonPercent));
    };
    let inner = mesh.inner.clone();
    match inner.pool.clone().run(move || mesh.describe(&id)).await {
        Some(r) => {
            // A function's page is named by a `Link` header, not a member of the answer (16.8 is
            // checked strictly by core; Build 2 Part 4, P2).
            let link = function_describe_link(&inner, &r);
            let mut resp = to_response(r);
            if let Some(v) = link.and_then(|l| HeaderValue::from_str(&l).ok()) {
                resp.headers_mut().insert(header::LINK, v);
            }
            resp
        }
        None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
    }
}

/// The `Link` header of a describe answer for a function: its page, `rel="describedby"`.
fn function_describe_link(inner: &Inner, r: &Reply) -> Option<String> {
    if r.status != 200 {
        return None;
    }
    let v = json::parse(&r.body).ok()?;
    if v.get("kind")?.as_str()? != "function" {
        return None;
    }
    let name = v.get("fn")?.as_str()?;
    Some(format!("<{}>; rel=\"describedby\"", crate::fnpage::page_url(inner, name)))
}

/// `POST /bundles` (Build 2 Part 4, P1): a publisher's bundle, checked and imported (see `bundles`).
async fn bundles(State(mesh): State<Mesh>, req: Request) -> Response {
    to_response(crate::bundles::post(mesh.inner.clone(), req.into_body()).await)
}

/// `GET /fn/<name>` (Build 2 Part 4, P2): the function page, HTML or, by `Accept` or `?format=json`,
/// the same data as JSON.
async fn function_page(
    State(mesh): State<Mesh>,
    Path(name): Path<String>,
    uri: Uri,
    headers: HeaderMap,
    req: Request,
) -> Response {
    if let Some(r) = ip_admit(&mesh.inner, &headers, &req) {
        return r;
    }
    let format_json = uri.query().is_some_and(|q| q.split('&').any(|p| p == "format=json"));
    let json_form = format_json || (accepts(&headers, JSON) && !accepts(&headers, "text/html"));
    let inner = mesh.inner.clone();
    match inner.pool.clone().run(move || crate::fnpage::respond(&mesh.inner, &name, json_form)).await {
        Some(r) => to_response(r),
        None => to_response(envelope::error_reply(ErrorCode::EvalUnavailable)),
    }
}

async fn fallback() -> Response {
    not_found("endpoint")
}

impl Mesh {
    /// The router of every endpoint. Serve it with
    /// `into_make_service_with_connect_info::<SocketAddr>()` (the client IP comes from it).
    pub fn router(&self) -> Router {
        Router::new()
            .route("/cell/{*rest}", get(cell))
            .route("/cells", post(cells))
            .route("/slice/{*rest}", get(slice))
            .route("/receipt/{hash}", get(receipt))
            .route("/descriptor/{hash}", get(descriptor))
            .route("/manifest/{slice_id}/{members_hash}", get(manifest))
            .route("/versions/{*rest}", get(versions))
            .route("/blob/{sha256}", get(blob))
            .route("/explain/{*rest}", get(explain))
            .route("/find", get(find))
            .route("/verify", post(verify_receipt))
            .route("/jobs/{job}", get(job))
            .route("/.well-known/datumesh.json", get(key_document))
            .route("/.well-known/datumesh-mesh.json", get(mesh_document))
            .route("/bindings", get(bindings))
            .route("/describe/{*id}", get(describe))
            .route("/fn/{*name}", get(function_page))
            .route("/bundles", post(bundles))
            .route("/whatif", post(whatif))
            .route("/health", get(health))
            .route("/metrics", get(metrics))
            .route("/openapi.json", get(openapi_json))
            .fallback(fallback)
            .layer(middleware::from_fn_with_state(self.clone(), around))
            .layer(tower_http::compression::CompressionLayer::new().gzip(true))
            .with_state(self.clone())
    }

    /// Serves the router on `listener` until `shutdown` resolves.
    pub async fn serve(
        &self,
        listener: tokio::net::TcpListener,
        shutdown: impl std::future::Future<Output = ()> + Send + 'static,
    ) -> std::io::Result<()> {
        axum::serve(listener, self.router().into_make_service_with_connect_info::<SocketAddr>())
            .with_graceful_shutdown(shutdown)
            .await
    }
}

impl IntoResponse for Reply {
    fn into_response(self) -> Response {
        to_response(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn reply(status: u16, body: &str) -> Reply {
        Reply::json(status, body.as_bytes().to_vec(), Cache::NoStore)
    }

    /// The runs the chunks write, concatenated and closed, are the batch as 5.7 writes it, and
    /// count its outcomes.
    #[test]
    fn runs_make_the_batch() {
        let h = "a".repeat(64);
        let replies = [
            reply(200, &format!(r#"{{"fn_hash":"{h}","outcome":"ok","receipt":{{"value":"1"}},"trust":"primary"}}"#)),
            reply(400, r#"{"error":"E_CANON_NUMBER","outcome":"bad_request"}"#),
            reply(
                200,
                &format!(r#"{{"age_seconds":3,"fn_hash":"{h}","outcome":"stale","receipt":{{}},"trust":"computed"}}"#),
            ),
            reply(404, r#"{"error":"E_NAME_UNBOUND","outcome":"not_covered"}"#),
            reply(200, &format!(r#"{{"fn_hash":"{h}","outcome":"ok","receipt":{{"value":"2"}},"trust":"primary"}}"#)),
        ];
        let mut want = b"[".to_vec();
        for (i, r) in replies.iter().enumerate() {
            if i > 0 {
                want.push(b',');
            }
            want.extend_from_slice(b"{\"envelope\":");
            want.extend_from_slice(&r.body);
            want.extend_from_slice(format!(",\"status\":{}}}", r.status).as_bytes());
        }
        want.push(b']');
        for split in 1..replies.len() {
            let runs = [Written::of(true, replies[..split].iter()), Written::of(false, replies[split..].iter())];
            let mut got: Vec<u8> = runs.iter().flat_map(|w| w.bytes.iter().copied()).collect();
            got.push(b']');
            assert_eq!(String::from_utf8(got).unwrap(), String::from_utf8(want.clone()).unwrap());
            let mut counts = std::collections::BTreeMap::new();
            for (o, k) in runs.iter().flat_map(|w| w.outcomes.iter()) {
                *counts.entry(o.as_str()).or_insert(0) += k;
            }
            let want_counts: std::collections::BTreeMap<&str, u64> =
                [("bad_request", 1), ("not_covered", 1), ("ok", 2), ("stale", 1)].into_iter().collect();
            assert_eq!(counts, want_counts);
        }
        for (n, s) in [(0u16, "0"), (7, "7"), (200, "200"), (404, "404"), (65535, "65535")] {
            let mut out = Vec::new();
            push_u16(&mut out, n);
            assert_eq!(out, s.as_bytes());
        }
    }

    /// The outcome of each envelope, whatever members come before it.
    #[test]
    fn outcomes() {
        let h = "0".repeat(64);
        for (body, want) in [
            (format!(r#"{{"fn_hash":"{h}","outcome":"ok","receipt":{{"outcome":"x"}}}}"#), Some("ok")),
            (r#"{"age_seconds":12,"outcome":"stale"}"#.to_string(), Some("stale")),
            (r#"{"error":"E_PARSE_URI","outcome":"bad_request"}"#.to_string(), Some("bad_request")),
            (r#"{"outcome":"pending","poll":"https://a.example/jobs/1"}"#.to_string(), Some("pending")),
            (r#"{"error":"no such endpoint"}"#.to_string(), None),
            (r#"{"outcome""#.to_string(), None),
        ] {
            assert_eq!(reply(200, &body).outcome_str(), want, "{body}");
            assert_eq!(reply(200, &body).outcome(), want.map(str::to_string), "{body}");
        }
        let mut arrow = reply(200, r#"{"outcome":"ok"}"#);
        arrow.content_type = "application/vnd.apache.arrow.stream";
        assert_eq!(arrow.outcome(), None);
    }
}