printobserver-server 0.18.0

The printobserver 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
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
//! The HTTP surface, built by folding over the declared operations.
//!
//! # The router is the declaration
//!
//! Nothing here writes a route out. [`router`] walks
//! [`OPERATIONS`](crate::operations::OPERATIONS) and registers one route per
//! entry beneath the one versioned prefix, so the set served and the set
//! declared cannot come apart — and the ten mutating operations share one
//! handler which is given the [`ActionKind`] its own entry declares, so a
//! request cannot reach an action the operation it was sent to does not name.
//! The five spool commands share one handler of their own on the same terms.
//!
//! # Every action takes the same one path
//!
//! An action asked for here goes to
//! [`Supervisor::request_action`](printobserver_core::Supervisor::request_action),
//! which is the same call an operator's action makes and an agent's action
//! makes. The policy is not re-implemented here and is not bypassed here: a
//! rejected request answers the rejection the policy made, carrying its reason,
//! the value asked for and the range allowed, and reaches no action method of
//! the printer port at all.
//!
//! # Nothing is served to a caller that did not present a credential
//!
//! Every route beneath the versioned prefix — and the prefix's own fallback, so
//! that a path nothing serves is refused the same way — sits behind
//! [`authenticate`], which runs before any extractor reads a path, a query or a
//! body. A request whose `Authorization` header is not exactly
//! `Bearer <credential>`, for the operator's credential or a live supervision
//! turn's, is answered `401` there, so it reaches no handler, no store, no
//! printer port and no record. There is no route that skips it and no
//! configuration that turns it off: [`ApiState`] cannot be built without what
//! a credential is checked against.
//!
//! # Every request is the identity its credential authenticated
//!
//! What [`authenticate`] admitted is a [`Caller`]: the operator, or one turn —
//! the agent, in one session, on one print. Every handler is given it, and the
//! body's `actor` is a claim held to it **before** the policy is asked
//! anything: a claim that is not the caller — an operator credential claiming
//! to be the agent, a turn claiming to be the operator or another session, and
//! anybody claiming to be the system, whose actions are the server's own — is
//! refused `403` naming both, and nothing is decided or recorded. A turn's
//! credential reaches its own print alone, the listing of prints beside it,
//! and neither of the two writes that are not about a running print: starting
//! one and replacing a manifest. So the class the policy rules on, and the
//! agent's minimum interval with it, is the one the credential authenticated
//! rather than the one the request claimed.
//!
//! The spool ledger is the printer's rather than one print's, so its four
//! reads are open to every caller — a turn included, which is how the agent
//! reads what is loaded and what a file needs — and its commands are held to
//! the same claim and then to the envelope's own grants, which the domain rules
//! on and records.
//!
//! The recovery operations are the printer's too: their read is open to every
//! caller, answering what each action would meet for that caller, and each
//! action is held to the same claim and then to the recovery grants and the
//! machine's own state, which the domain rules on and records.

use std::sync::Arc;
use std::time::Duration;

use axum::Json;
use axum::extract::rejection::{JsonRejection, QueryRejection};
use axum::extract::{DefaultBodyLimit, Extension, Path, Query, Request, State};
use axum::http::{StatusCode, header};
use axum::middleware::{Next, from_fn_with_state};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post, put};
use axum::{Router, routing::MethodRouter};
use printobserver_core::recovery::recovery_detail;
use printobserver_core::store::TimelineQuery;
use printobserver_core::store::{
    EventStore, HistoryQuery, ImageStore, PrintStore, SessionStore, StoreError,
};
use printobserver_core::{
    ActionKind, Actor, ActorClass, ExecutionOutcome, PolicyDecision, RecoveryActionKind,
    RecoveryDecision, SheetId, SpoolId,
};
use printobserver_core::{CoreError, MAX_LOOK_WAIT_S, Supervisor, effective_bounds};
use printobserver_types::serde::Deserialize;
use printobserver_types::serde_json::Value;
use printobserver_types::{EventBody, EventId, EventKind, FileName, ImageId, PrintId, Timestamp};

use crate::operations::{Effect, Method, OPERATIONS, Operation, VERSION_PREFIX};
use crate::server::{CREDENTIAL_ISSUE, OperatorCredential};
use crate::turns::{TurnBinding, TurnCredentials};
use crate::wire::{
    ActionAnswer, ActionBody, BedClearAnswer, BedClearBody, ContextAnswer, ErrorAnswer,
    HistoryAnswer, ImageAnswer, ManifestAnswer, ManifestBody, PreflightAnswer, PrintsAnswer,
    RecoveryAnswer, SpoolAnswer, SpoolCommandAnswer, SpoolsAnswer, StatusAnswer, TimelineAnswer,
    claimed_actor, reason_of, recovery_of, spool_command_of,
};

/// What every handler is given: the supervisor, and the stores the reads
/// answer out of — the four aggregates a route reads, and not the actions,
/// which reach the store through the supervisor alone.
#[derive(Clone)]
pub struct ApiState {
    /// The supervision core, which every action passes through.
    pub supervisor: Arc<Supervisor>,
    /// The print records, their manifests and their narrowings.
    pub prints: Arc<dyn PrintStore>,
    /// The event log.
    pub events: Arc<dyn EventStore>,
    /// The images stored beside the events.
    pub images: Arc<dyn ImageStore>,
    /// The supervision sessions.
    pub sessions: Arc<dyn SessionStore>,
    /// What the operator's credential is checked against before anything
    /// above is reached.
    pub operator: Arc<OperatorCredential>,
    /// The live supervision turns' credentials, checked the same way.
    pub turns: TurnCredentials,
    /// The broadcast an events read waits on, raised once an event is stored.
    pub stored: crate::events::Stored,
    /// What makes every check's image and judges every frame of a print,
    /// which a recheck of a print's camera asks directly; none where nothing
    /// was installed.
    pub check_images: Option<Arc<crate::check_images::PanelImages>>,
    /// What a check of the supervising agent's harness runs against.
    pub harness: Arc<crate::readiness::HarnessCheck>,
}

/// Who one request authenticated as.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Caller {
    /// The operator, by the credential the operator's verifier admits.
    Operator,
    /// One supervision turn's run: the agent, in one session, on one print.
    Turn(TurnBinding),
}

impl Caller {
    /// This caller, as a refusal names it.
    fn named(&self) -> String {
        match self {
            Self::Operator => "the operator".to_owned(),
            Self::Turn(binding) => format!(
                "the agent in session `{}` on print {}",
                binding.session_name(),
                binding.print_id()
            ),
        }
    }
}

/// One claimed actor, as a refusal names it.
fn claimed(actor: &Actor) -> String {
    match actor {
        Actor::Operator => "the operator".to_owned(),
        Actor::System => "the system".to_owned(),
        Actor::Agent { session_name } => format!("the agent in session `{session_name}`"),
    }
}

/// Refuse a claimed actor that is not the caller, before anything is decided.
///
/// The system is claimed by nobody: its actions are the server's own, and no
/// credential this server admits is the server.
fn claim_refused(caller: &Caller, actor: &Actor) -> Option<Response> {
    let held = match (caller, actor) {
        (Caller::Operator, Actor::Operator) => true,
        (Caller::Turn(binding), Actor::Agent { session_name }) => {
            *session_name == binding.session_name()
        }
        _ => false,
    };
    if held {
        return None;
    }
    let why = if matches!(actor, Actor::System) {
        "no credential may claim the system, whose actions are the server's own"
    } else {
        "a request acts as the identity its credential authenticated, and no other"
    };
    Some(refusal(
        StatusCode::FORBIDDEN,
        format!(
            "this request authenticated as {} and claims to be {}: {why}",
            caller.named(),
            claimed(actor)
        ),
    ))
}

/// Refuse a turn's request about any print but its own.
pub(crate) fn scope_refused(caller: &Caller, print_id: PrintId) -> Option<Response> {
    match caller {
        Caller::Turn(binding) if binding.print_id() != print_id => Some(refusal(
            StatusCode::FORBIDDEN,
            format!(
                "this request authenticated as {} and names print {print_id}: a supervision \
                 turn's credential reaches its own print alone",
                caller.named()
            ),
        )),
        _ => None,
    }
}

/// Refuse a turn's request for something that belongs to no print: a turn's
/// credential reaches its own print alone, and what belongs to none is the
/// operator's.
fn printless_refused(caller: &Caller, what: &str) -> Option<Response> {
    match caller {
        Caller::Turn(_) => Some(refusal(
            StatusCode::FORBIDDEN,
            format!(
                "this request authenticated as {} and asks for {what}: a supervision turn's \
                 credential reaches its own print alone",
                caller.named()
            ),
        )),
        Caller::Operator => None,
    }
}

/// Refuse a turn's request for a write that is not about its running print:
/// starting a print, and replacing a manifest, are the operator's alone.
fn operator_refused(caller: &Caller, command: &str) -> Option<Response> {
    match caller {
        Caller::Turn(_) => Some(refusal(
            StatusCode::FORBIDDEN,
            format!(
                "this request authenticated as {} and asks for `{command}`, which is the \
                 operator's alone: a supervision turn's credential does not reach it",
                caller.named()
            ),
        )),
        Caller::Operator => None,
    }
}

/// Refuse a turn's acknowledgement before the turn has taken a look.
///
/// The frames a turn's context names are already old when it reads them, so
/// what a turn writes down of its event is judged from a look it took — or
/// from the image it was handed, which counts as its look, because a turn
/// handed one is allowed no other; the operator, who is not a turn, is held to
/// nothing here.
fn unlooked_refused(
    turns: &TurnCredentials,
    caller: &Caller,
    print_id: PrintId,
) -> Option<Response> {
    match caller {
        Caller::Turn(binding) if !turns.has_looked(binding) => Some(refusal(
            StatusCode::FORBIDDEN,
            format!(
                "this request authenticated as {} and acknowledges an event before the turn \
                 has taken a look: run `printobserver look --print-id {print_id}`, open the \
                 frames it names, and acknowledge what they show",
                caller.named()
            ),
        )),
        _ => None,
    }
}

/// What [`authenticate`] checks a presented credential against.
#[derive(Clone)]
pub struct Admission {
    /// The operator's.
    operator: Arc<OperatorCredential>,
    /// The live turns'.
    turns: TurnCredentials,
}

impl Admission {
    /// Who a presented credential authenticates as, when it is anybody.
    fn caller(&self, presented: &[u8]) -> Option<Caller> {
        if let Some(binding) = self.turns.admit(presented) {
            return Some(Caller::Turn(binding));
        }
        self.operator.admits(presented).then_some(Caller::Operator)
    }
}

impl core::fmt::Debug for ApiState {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter.debug_struct("ApiState").finish_non_exhaustive()
    }
}

/// How many events a history read asks for, when it asks for a number.
#[derive(Debug, Clone, Deserialize)]
#[serde(crate = "printobserver_types::serde")]
pub struct HistoryParams {
    /// The limit asked for; absent takes the port's own default window.
    #[serde(default)]
    pub limit: Option<u32>,
}

/// The event a context read is asked `since`: only the events newer than it
/// are answered, because the caller has read the rest.
#[derive(Debug, Clone, Deserialize)]
#[serde(crate = "printobserver_types::serde")]
pub struct ContextParams {
    /// The newest event the caller has read; absent answers the recent window.
    #[serde(default)]
    pub since: Option<printobserver_types::EventId>,
}

/// How long a look asks to wait for something to arrive, in whole seconds.
#[derive(Debug, Clone, Deserialize)]
#[serde(crate = "printobserver_types::serde")]
pub struct LookParams {
    /// The wait asked for; absent looks at once.
    #[serde(default)]
    pub wait_s: Option<u32>,
}

/// Whether a spools read asks for the retired ones too.
#[derive(Debug, Clone, Deserialize)]
#[serde(crate = "printobserver_types::serde")]
pub struct SpoolsParams {
    /// Asked for; absent, the retired spools are left out.
    #[serde(default)]
    pub include_retired: Option<bool>,
}

/// The file a filament check is about, and the sheet it would go down on.
#[derive(Debug, Clone, Deserialize)]
#[serde(crate = "printobserver_types::serde")]
pub struct PreflightParams {
    /// The file, as the printer names it.
    #[serde(default)]
    pub file_name: Option<String>,
    /// The build sheet the sheet check is read against; absent, the check
    /// reports no sheet result, and a blank one is refused.
    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
    #[serde(default)]
    pub sheet: Option<String>,
}

/// How many of a spool's own events its read carries, newest first.
pub const SPOOL_RECENT_EVENTS: u32 = 20;

/// Every public operation, beneath the one versioned prefix.
///
/// # Panics
///
/// Panics when [`OPERATIONS`] declares an entry this function has no route for,
/// which is a declaration and a router that have come apart — the one state
/// this server must not come up in quietly.
pub fn router(state: ApiState) -> Router {
    let mut api = Router::new();
    for operation in OPERATIONS {
        api = api.route(operation.path, route_for(&operation));
    }
    // The layer is added after every route and the fallback, which is what
    // puts all of them behind it.
    let api = api
        .fallback(nothing_here)
        .layer(from_fn_with_state(
            Admission {
                operator: Arc::clone(&state.operator),
                turns: state.turns.clone(),
            },
            authenticate,
        ))
        .layer(DefaultBodyLimit::max(BODY_BOUND))
        .with_state(state);
    Router::new().nest(VERSION_PREFIX, api)
}

/// The scheme the credential is presented under.
const BEARER: &[u8] = b"Bearer ";

/// How much of a request's body this server reads, admitted or refused.
///
/// One bound for both: the router's body limit is set from it, so it is what
/// every extractor reads an admitted body to, and what [`authenticate`] drains
/// a refused one to — a body the server would have taken is one it drains,
/// and a larger one is left where it is either way.
pub const BODY_BOUND: usize = 2 * 1024 * 1024;

/// How long [`authenticate`] waits for a refused request's body to arrive.
///
/// A caller that sent a head and then nothing would otherwise hold its refusal
/// open for as long as it liked; after this the refusal goes out over whatever
/// arrived, and the connection ends as it did before there was a drain.
pub const DRAIN_BOUND: Duration = Duration::from_secs(2);

/// Admit a request that presented the operator's credential or a live turn's,
/// hand every handler who it authenticated as, and refuse every other request
/// before anything reads it.
///
/// Exactly one `Authorization` header, spelled `Bearer ` and then the
/// credential. Two headers, another scheme, another spelling of this one, and a
/// credential that is nobody's are all the same refusal, which says what to
/// present and nothing about what was presented — and, on a server that has no
/// operator credential yet, names the command that issues one.
///
/// The refusal is decided on the head alone, and the body is then drained, up
/// to [`BODY_BOUND`], before it is answered. Nothing reads what is
/// drained: a connection closed with a body still unread on it is closed with
/// a reset rather than an end, and a caller on Windows — where a reset discards
/// everything received and not yet read — then reads the abort in place of the
/// `401` that was already on its way. Linux hands over what was queued first,
/// which is why the same race is only ever seen there.
pub async fn authenticate(
    State(admission): State<Admission>,
    mut request: Request,
    next: Next,
) -> Response {
    let mut presented = request.headers().get_all(header::AUTHORIZATION).iter();
    let admitted = match (presented.next(), presented.next()) {
        (Some(only), None) => only
            .as_bytes()
            .strip_prefix(BEARER)
            .and_then(|offered| admission.caller(offered)),
        _ => None,
    };
    if let Some(caller) = admitted {
        request.extensions_mut().insert(caller);
        return next.run(request).await;
    }
    {
        let said = if matches!(*admission.operator, OperatorCredential::Unconfigured) {
            format!(
                "this server's API requires a credential, presented as `Authorization: Bearer \
                 <credential>`, and this server has no operator credential yet: run \
                 `{CREDENTIAL_ISSUE}` as the operator, put the `api.credential_verifier` line it \
                 prints into the server's configuration, and restart the service"
            )
        } else {
            format!(
                "this server's API requires the credential it is configured with, presented as \
                 `Authorization: Bearer <credential>`. An operator without one runs \
                 `{CREDENTIAL_ISSUE}`"
            )
        };
        let mut refused = refusal(StatusCode::UNAUTHORIZED, said);
        refused.headers_mut().insert(
            header::WWW_AUTHENTICATE,
            header::HeaderValue::from_static("Bearer"),
        );
        // A body past the bound, or one that has not arrived inside
        // `DRAIN_BOUND`, is left where it is: the refusal is the answer either
        // way, and what a caller then meets on the connection is its own doing.
        let _ = tokio::time::timeout(
            DRAIN_BOUND,
            axum::body::to_bytes(request.into_body(), BODY_BOUND),
        )
        .await;
        refused
    }
}

/// A path beneath the versioned prefix that no operation serves.
async fn nothing_here() -> Response {
    refusal(
        StatusCode::NOT_FOUND,
        "no operation of this server is served at that path",
    )
}

/// The route one declared operation is served by.
fn route_for(operation: &Operation) -> MethodRouter<ApiState> {
    if let Effect::Command(spool_command) = operation.effect {
        let kind = spool_command.action_kind();
        if operation.path.contains("{spool_id}") {
            return post(
                move |state: State<ApiState>,
                      caller: Extension<Caller>,
                      Path(spool_id): Path<SpoolId>,
                      body: Result<Json<Value>, JsonRejection>| async move {
                    command(kind, state, caller, Some(spool_id), body).await
                },
            );
        }
        return post(
            move |state: State<ApiState>,
                  caller: Extension<Caller>,
                  body: Result<Json<Value>, JsonRejection>| async move {
                command(kind, state, caller, None, body).await
            },
        );
    }
    if let Effect::Recovery(kind) = operation.effect {
        return post(
            move |state: State<ApiState>,
                  caller: Extension<Caller>,
                  body: Result<Json<Value>, JsonRejection>| async move {
                recover(kind, state, caller, body).await
            },
        );
    }
    if let Effect::Mutating(kind) = operation.effect {
        return post(
            move |state: State<ApiState>,
                  caller: Extension<Caller>,
                  print_id: PrintPath,
                  body: Result<Json<ActionBody>, JsonRejection>| async move {
                act(kind, state, caller, print_id, body).await
            },
        );
    }
    match (operation.name, operation.method) {
        ("prints", Method::Get) => get(list_and_adopt_prints),
        ("status", Method::Get) => get(status),
        ("context", Method::Get) => get(context),
        ("image", Method::Get) => get(image),
        ("history", Method::Get) => get(history),
        ("events", Method::Get) => get(crate::events::events),
        ("look", Method::Get) => get(look),
        (crate::operations::PRINTER_LOOK, Method::Get) => get(printer_look),
        ("manifest_get", Method::Get) => get(manifest_get),
        ("manifest_set", Method::Put) => put(manifest_set),
        ("spools", Method::Get) => get(spools),
        ("spool", Method::Get) => get(spool),
        ("printer_history", Method::Get) => get(printer_history),
        ("preflight", Method::Get) => get(preflight),
        (crate::operations::RECOVERY_STATUS, Method::Get) => get(recover_status),
        (crate::operations::BED_CLEAR, Method::Post) => post(bed_clear),
        (crate::operations::RECHECK_CAMERA, Method::Post) => post(recheck_camera),
        (crate::operations::CHECK_CAMERA, Method::Get) => get(check_camera),
        (crate::operations::CHECK_HARNESS, Method::Get) => get(check_harness),
        (name, method) => panic!(
            "the operation `{name}` is declared as {method} and this router serves no such route"
        ),
    }
}

/// Whether the supervising agent's harness can run a turn right now: its own
/// status command, then one minimal turn, run as this server's own user.
///
/// The operator's alone: a turn's credential reaches its own print, and a turn
/// asking whether a turn can run would be a second turn started from inside
/// the first. The check is answered whatever it found — a harness that cannot
/// run is the answer, not a failure of the request — and asks nothing of the
/// machine.
async fn check_harness(State(state): State<ApiState>, caller: Extension<Caller>) -> Response {
    if let Some(refused) = printless_refused(&caller, "a check of the supervising harness") {
        return refused;
    }
    let check = Arc::clone(&state.harness);
    match tokio::task::spawn_blocking(move || check.run()).await {
        Ok(readiness) => answer(StatusCode::OK, &readiness),
        Err(error) => refusal(
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("the harness check did not finish: {error}"),
        ),
    }
}

/// One answer, rendered as JSON under the media type every operation answers in.
pub(crate) fn answer<T: printobserver_types::serde::Serialize>(
    status: StatusCode,
    body: &T,
) -> Response {
    let rendered = match printobserver_types::serde_json::to_vec(body) {
        Ok(bytes) => bytes,
        Err(error) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
                format!("{{\"error\":\"{error}\"}}"),
            )
                .into_response();
        }
    };
    (
        status,
        [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
        rendered,
    )
        .into_response()
}

/// One refusal, rendered as JSON under the same media type.
pub(crate) fn refusal(status: StatusCode, detail: impl core::fmt::Display) -> Response {
    answer(status, &ErrorAnswer::saying(detail))
}

/// What a print id that names no print is refused with, after what was wrong
/// with it: what to pass instead.
pub(crate) const PRINT_ID_REFUSED: &str = "a print is named by its id, a UUID, as `printobserver prints` \
lists it; a start with no print open may name none, and is made under one minted for it";

/// The print a route's path names, refused in this server's own error shape,
/// saying what to pass, when the path names no print at all.
pub(crate) struct PrintPath(pub(crate) PrintId);

impl<S: Send + Sync> axum::extract::FromRequestParts<S> for PrintPath {
    type Rejection = Response;

    async fn from_request_parts(
        parts: &mut axum::http::request::Parts,
        state: &S,
    ) -> Result<Self, Self::Rejection> {
        match Path::<PrintId>::from_request_parts(parts, state).await {
            Ok(Path(print_id)) => Ok(Self(print_id)),
            Err(rejected) => Err(refusal(
                StatusCode::BAD_REQUEST,
                format!("{}: {PRINT_ID_REFUSED}", rejected.body_text()),
            )),
        }
    }
}

/// The status a store refusal is answered under.
pub(crate) fn store_status(error: &StoreError) -> StatusCode {
    match error {
        StoreError::NotFound { .. } => StatusCode::NOT_FOUND,
        StoreError::LimitRefused { .. } | StoreError::ConstraintRefused { .. } => {
            StatusCode::BAD_REQUEST
        }
        StoreError::Database { .. } | StoreError::Io { .. } => StatusCode::INTERNAL_SERVER_ERROR,
    }
}

/// The status a core refusal is answered under.
fn core_status(error: &CoreError) -> StatusCode {
    match error {
        CoreError::NoSuchPrint { .. } => StatusCode::NOT_FOUND,
        CoreError::Store(store) => store_status(store),
        _ => StatusCode::INTERNAL_SERVER_ERROR,
    }
}

/// Ask for one action of the vocabulary against one print.
///
/// Who may ask is settled before the policy is: a turn's credential reaches
/// no start and no print but its own — whatever the body says, so those two
/// answer `403` ahead of any rejection of the body itself — and the claimed
/// actor is held to the caller. A
/// request refused here is decided on by nothing and recorded nowhere.
async fn act(
    kind: ActionKind,
    State(state): State<ApiState>,
    Extension(caller): Extension<Caller>,
    PrintPath(print_id): PrintPath,
    body: Result<Json<ActionBody>, JsonRejection>,
) -> Response {
    if kind == ActionKind::StartPrint
        && let Some(refused) =
            operator_refused(&caller, &crate::operations::command_for("start_print"))
    {
        return refused;
    }
    if let Some(refused) = scope_refused(&caller, print_id) {
        return refused;
    }
    let body = match body {
        Ok(Json(body)) => body,
        Err(rejected) => return rejected.into_response(),
    };
    if let Some(refused) = claim_refused(&caller, &body.actor) {
        return refused;
    }
    if kind == ActionKind::AcknowledgeFailure
        && let Some(refused) = unlooked_refused(&state.turns, &caller, print_id)
    {
        return refused;
    }
    let action = match body.into_action(kind) {
        Ok(action) => action,
        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
    };
    let outcome = match state.supervisor.request_action(print_id, action).await {
        Ok(outcome) => outcome,
        Err(error) => return refusal(core_status(&error), error),
    };
    let printer_refusal = match &outcome.record.outcome {
        Some(ExecutionOutcome::Failed { reason }) => Some(reason.clone()),
        _ => None,
    };
    let status = match outcome.record.decision {
        PolicyDecision::Accepted if printer_refusal.is_none() => StatusCode::OK,
        // The policy accepted it and the machine did not. That is a request
        // that was made and refused rather than one that never happened, so
        // the record and the printer's own words are the answer.
        PolicyDecision::Accepted => StatusCode::BAD_GATEWAY,
        // The rejection itself is the answer: its reason, the value asked for
        // and the range allowed are what let a caller ask again correctly.
        PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
    };
    answer(
        status,
        &ActionAnswer {
            record: outcome.record,
            intervention: outcome.intervention,
            printer_refusal,
        },
    )
}

/// Ask the spool ledger for one command.
///
/// The claimed actor is held to the caller before anything else of the body is
/// read, and a body with no reason is refused before the domain is asked —
/// so a request refused here is recorded nowhere. Whether the actor may ask at
/// all is the envelope's grant, which the domain rules on and records like
/// every refusal: a supervision turn's agent is refused there, under the
/// default grants, rather than here.
async fn command(
    kind: ActionKind,
    State(state): State<ApiState>,
    Extension(caller): Extension<Caller>,
    spool_id: Option<SpoolId>,
    body: Result<Json<Value>, JsonRejection>,
) -> Response {
    let body = match body {
        Ok(Json(body)) => body,
        Err(rejected) => return rejected.into_response(),
    };
    let Some(fields) = body.as_object() else {
        return refusal(
            StatusCode::BAD_REQUEST,
            "a spool command's body is a document of its fields",
        );
    };
    let actor = match claimed_actor(fields) {
        Ok(actor) => actor,
        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
    };
    if let Some(refused) = claim_refused(&caller, &actor) {
        return refused;
    }
    let asked = match spool_command_of(kind, spool_id, body) {
        Ok(asked) => asked,
        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
    };
    let outcome = match state.supervisor.request_spool_command(asked).await {
        Ok(outcome) => outcome,
        Err(error) => return refusal(core_status(&error), error),
    };
    let status = match outcome.decision {
        PolicyDecision::Accepted => StatusCode::OK,
        // The refusal is the answer, exactly as a print action's is.
        PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
    };
    answer(
        status,
        &SpoolCommandAnswer {
            decision: outcome.decision,
            spool: outcome.spool,
            events: outcome.events,
        },
    )
}

/// Ask the printer for one recovery action.
///
/// The body is held to the action's own fields, a reason and an actor before
/// anything is decided, and the claimed actor to the caller — so a request
/// refused here is recorded nowhere and reaches no printer. Whether the actor
/// may ask, and whether the printer is in a state the action is safe from, is
/// the supervision core's to rule on and record.
async fn recover(
    kind: RecoveryActionKind,
    State(state): State<ApiState>,
    Extension(caller): Extension<Caller>,
    body: Result<Json<Value>, JsonRejection>,
) -> Response {
    let body = match body {
        Ok(Json(body)) => body,
        Err(rejected) => return rejected.into_response(),
    };
    if let Some(fields) = body.as_object() {
        let actor = match claimed_actor(fields) {
            Ok(actor) => actor,
            Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
        };
        if let Some(refused) = claim_refused(&caller, &actor) {
            return refused;
        }
    }
    let (action, actor, reason) = match recovery_of(kind, body) {
        Ok(asked) => asked,
        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
    };
    let issued = match state
        .supervisor
        .request_recovery(action.clone(), actor, reason)
        .await
    {
        Ok(issued) => issued,
        Err(error) => return refusal(core_status(&error), error),
    };
    let config = state.supervisor.config().recovery;
    let status = match &issued.decision {
        RecoveryDecision::Executed(ExecutionOutcome::Succeeded) => StatusCode::OK,
        // The printer was asked and refused: a request that was made rather
        // than one that never happened, answered with the printer's words.
        RecoveryDecision::Executed(ExecutionOutcome::Failed { .. }) => StatusCode::BAD_GATEWAY,
        // The refusal is the answer, as a print action's is.
        RecoveryDecision::Rejected(_) => StatusCode::CONFLICT,
    };
    answer(
        status,
        &RecoveryAnswer {
            detail: recovery_detail(&action, &issued.decision, config.as_ref()),
            action,
            decision: issued.decision,
            events: vec![issued.requested, issued.settled],
        },
    )
}

/// What a recorded bed-clear means from now on, in a sentence for a person.
pub const BED_CLEAR_DETAIL: &str = "recorded: until the next print starts, a Z home is decided \
    as though it asserted the bed clear, and a heat, a park and an XY home as though they \
    asserted the nozzle clear of the part, wherever the operator's word counts";

/// Record the operator's word that the bed is clear.
///
/// The claimed actor is held to the caller before anything is written, and
/// the one actor admitted is the operator: a turn claiming the operator, any
/// claim to the system, and the agent's own word are each refused `403` and
/// recorded nowhere. A reason that is absent or blank is refused before
/// anything is written.
async fn bed_clear(
    State(state): State<ApiState>,
    Extension(caller): Extension<Caller>,
    body: Result<Json<Value>, JsonRejection>,
) -> Response {
    let body = match body {
        Ok(Json(body)) => body,
        Err(rejected) => return rejected.into_response(),
    };
    let Some(fields) = body.as_object() else {
        return refusal(
            StatusCode::BAD_REQUEST,
            "the body is not a document carrying an `actor` and a `reason`",
        );
    };
    let actor = match claimed_actor(fields) {
        Ok(actor) => actor,
        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
    };
    if let Some(refused) = claim_refused(&caller, &actor) {
        return refused;
    }
    if actor != Actor::Operator {
        return refusal(
            StatusCode::FORBIDDEN,
            format!(
                "{} may not say the bed is clear: an assertion is a person's word for what \
                 they can see, and only the operator's is recorded",
                claimed(&actor)
            ),
        );
    }
    let body: BedClearBody = match printobserver_types::serde_json::from_value(body) {
        Ok(body) => body,
        Err(error) => {
            return refusal(
                StatusCode::BAD_REQUEST,
                format!("the body is not an `actor` and a `reason`: {error}"),
            );
        }
    };
    let reason = match reason_of(body.reason.as_deref()) {
        Ok(reason) => reason,
        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
    };
    match state.supervisor.assert_bed_clear(reason).await {
        Ok(event) => answer(
            StatusCode::OK,
            &BedClearAnswer {
                event,
                detail: BED_CLEAR_DETAIL.to_owned(),
            },
        ),
        Err(error) => refusal(core_status(&error), error),
    }
}

/// Judge a print's camera again on a fresh frame: its view and its first-layer
/// alignment at once, a latched verdict included, taking the correction afresh
/// when the layer is clearly found, and recording each judgement as a check's
/// are. Nothing is sent to the printer.
///
/// The claimed actor is held to the caller before anything is fetched, and a
/// reason that is absent or blank is refused. While the printer reports the
/// print paused its bed stands off the plan's height, so only the view is
/// judged. A store that cannot read the print answers this server's own
/// failure, and a print it does not hold `404`, before anything of the camera
/// is asked. With no calibration or no camera stream configured there is
/// nothing to judge a frame against: the fresh frame is kept as a look's is,
/// and answered as the whole frame for that reason. A server that judges no
/// frames, one with no camera configured, and a camera that gives no good
/// frame are each refused `503`, in this server's own error shape: `409` and
/// `502` are the policy's and the machine's answers to a decision, each
/// carrying its record, and nothing was decided here.
async fn recheck_camera(
    State(state): State<ApiState>,
    Extension(caller): Extension<Caller>,
    PrintPath(print_id): PrintPath,
    body: Result<Json<Value>, JsonRejection>,
) -> Response {
    if let Some(refused) = scope_refused(&caller, print_id) {
        return refused;
    }
    let (actor, reason) = match actor_and_reason(&caller, body) {
        Ok(asked) => asked,
        Err(refused) => return *refused,
    };
    // The store answers first, as it does for every operation: a print it
    // cannot read is this server's own failure, and one it does not hold is
    // missing, whatever the camera would have said.
    match state.prints.print(print_id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return refusal(StatusCode::NOT_FOUND, CoreError::NoSuchPrint { print_id });
        }
        Err(error) => return refusal(store_status(&error), error),
    }
    let Some(images) = state.check_images.clone() else {
        return refusal(
            StatusCode::SERVICE_UNAVAILABLE,
            "nothing judges this server's camera frames",
        );
    };
    if state.supervisor.config().camera_snapshot_url.is_none() {
        return refusal(
            StatusCode::SERVICE_UNAVAILABLE,
            "no camera is configured to judge: set the server's `[camera] snapshot_url`",
        );
    }
    let supervisor = Arc::clone(&state.supervisor);
    let fresh = tokio::task::spawn_blocking(move || {
        printobserver_core::block_on(supervisor.fresh_view(print_id))
    })
    .await;
    let fresh = match fresh {
        Ok(Ok(fresh)) => fresh,
        Ok(Err(error)) => return refusal(core_status(&error), error),
        Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
    };
    let Some((url, image)) = fresh.frame.clone() else {
        return refusal(
            StatusCode::SERVICE_UNAVAILABLE,
            "the camera gave no good frame to judge",
        );
    };
    let sha256 = hex_sha256(image.bytes.as_slice());
    let captured_at = image
        .captured_at
        .unwrap_or_else(printobserver_types::Timestamp::now);
    let alignment = crate::alignment::AlignmentJudging::of_recheck(fresh.paused);
    images.adopt_camera_check(print_id, fresh.camera_check.as_ref());
    let judging = Arc::clone(&images);
    let plan = fresh.plan.clone();
    let bytes = image.bytes.as_slice().to_vec();
    let digest = sha256.clone();
    let judged = tokio::task::spawn_blocking(move || {
        judging.judge_frame(print_id, &bytes, &digest, plan.as_ref(), alignment)
    })
    .await;
    let judged = match judged {
        Ok(Some(judged)) => judged,
        // With no calibration, or no stream it was fitted on, nothing can be
        // judged of the frame: it is kept as a look's is, and answered as the
        // whole frame for that reason.
        Ok(None) => crate::alignment::Judged::nothing_to_judge(
            images.alignment(print_id),
            EventBody::of(&printobserver_core::CameraLookPayload {
                waited_s: 0,
                delivered: Vec::new(),
                frame_captured_at: Some(captured_at),
            })
            .ok(),
        ),
        Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
    };
    if let Some(detail) = &judged.unreadable {
        return refusal(StatusCode::SERVICE_UNAVAILABLE, detail);
    }
    eprintln!(
        "printobserver: print {print_id}: the camera is judged again for {}: {reason}",
        claimed(&actor)
    );
    let frame_path = match stored_with_frame(&state, print_id, &judged, (url, image)).await {
        Ok(path) => path,
        Err(refused) => return refused,
    };
    let shown =
        match image_shown(&images, print_id, &frame_path, captured_at, &fresh, &judged).await {
            Ok(shown) => shown,
            Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
        };
    answer(
        StatusCode::OK,
        &crate::wire::RecheckCameraAnswer {
            frame_path,
            alignment: judged.alignment,
            view_correction: judged.correction,
            image_kind: shown.kind(),
            image_fallback: shown.fallback,
        },
    )
}

/// Check the camera's alignment with its calibration on the empty sheet: one
/// fresh look, judged against the calibration at the bed height the operator
/// read back, answered and written into the printer timeline. Nothing is sent
/// to the printer, no turn is started and no print is changed.
///
/// The operator's: a turn's credential reaches its own print alone. A request
/// naming a sheet this server carries no outline of, or a bed height that is
/// not a finite number of millimetres at or above zero, is refused `400`, and
/// a server with no camera configured `503`; neither records anything. Every
/// look taken is answered `200` with what it came to — a camera that gave no
/// frame or could not be reached included, and a frame with no calibration
/// configured to hold it to — and recorded.
async fn check_camera(
    State(state): State<ApiState>,
    Extension(caller): Extension<Caller>,
    query: Result<Query<crate::camera_check::CheckCameraQuery>, QueryRejection>,
) -> Response {
    if let Some(refused) = printless_refused(&caller, "a check of the printer's camera") {
        return refused;
    }
    let body = match query {
        Ok(Query(query)) => query,
        Err(error) => {
            return refusal(
                StatusCode::BAD_REQUEST,
                format!("a camera check names a `sheet` and a `bed_z_mm`: {error}"),
            );
        }
    };
    let known = printobserver_panels::SheetOutline::committed_sheets();
    let sheet = match printobserver_core::SheetId::try_from(body.sheet.clone()) {
        Ok(sheet) if known.contains(&sheet.as_str()) => sheet,
        _ => {
            return refusal(
                StatusCode::BAD_REQUEST,
                format!(
                    "`sheet` is `{}`, and the sheets a camera check knows the outline of are {}",
                    body.sheet,
                    known.join(", ")
                ),
            );
        }
    };
    if !(body.bed_z_mm.is_finite() && body.bed_z_mm >= 0.0) {
        return refusal(
            StatusCode::BAD_REQUEST,
            "`bed_z_mm` must be the bed's height in millimetres, read back with M114 while idle: \
             a finite number at or above zero",
        );
    }
    // The store answers first, as it does for every operation: a log that
    // cannot be read is this server's own failure, whatever the camera says.
    if let Err(error) = state.events.newest_stored().await {
        return refusal(store_status(&error), error);
    }
    let Some(images) = state.check_images.clone() else {
        return refusal(
            StatusCode::SERVICE_UNAVAILABLE,
            "nothing judges this server's camera frames",
        );
    };
    let calibration = images.calibration().cloned();
    let asked = crate::camera_check::Asked {
        id: printobserver_core::CameraCheckId::new(),
        checked_at: printobserver_types::Timestamp::now(),
        sheet,
        bed_z_mm: body.bed_z_mm,
    };
    let look = match state.supervisor.take_check_look().await {
        Ok(look) => look,
        Err(error) => return refusal(core_status(&error), error),
    };
    let check = match checked(&images, asked, look, calibration).await {
        Ok(check) => check,
        Err(refused) => return *refused,
    };
    let body = match EventBody::of(&crate::camera_check::CameraCheckedPayload {
        camera_check: check.clone(),
    }) {
        Ok(body) => body,
        Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
    };
    if let Err(error) = state
        .events
        .append_event(printobserver_core::store::EventDraft {
            print_id: None,
            source: printobserver_core::operator_source(),
            received_at: check.checked_at,
            body,
            raw: None,
        })
        .await
    {
        return refusal(store_status(&error), error);
    }
    eprintln!(
        "printobserver: camera check {} on {} at bed Z {:.2}: {}",
        check.id,
        check.sheet.as_str(),
        check.bed_z_mm,
        check.verdict.as_str()
    );
    answer(StatusCode::OK, &check)
}

/// What a camera check's one look came to, judged when it gave a frame of a
/// configured calibration's, and its drawn frame written beside the check
/// images; or the refusal of a check no camera is configured for.
async fn checked(
    images: &crate::check_images::PanelImages,
    asked: crate::camera_check::Asked,
    look: printobserver_core::CheckLook,
    calibration: Option<printobserver_panels::CameraCalibration>,
) -> Result<crate::camera_check::CameraCheck, Box<Response>> {
    use crate::camera_check::UnavailableReason;
    Ok(match (look, calibration) {
        (printobserver_core::CheckLook::NoCamera, _) => {
            return Err(Box::new(refusal(
                StatusCode::SERVICE_UNAVAILABLE,
                "no camera is configured to check: set the server's `[camera] snapshot_url`",
            )));
        }
        (printobserver_core::CheckLook::NoFrame { detail, .. }, _) => {
            asked.camera_unavailable(UnavailableReason::NoFrame, &detail, None)
        }
        (printobserver_core::CheckLook::Failed { detail, .. }, _) => {
            asked.camera_unavailable(UnavailableReason::LookFailed, &detail, None)
        }
        (printobserver_core::CheckLook::Framed { frame, path, .. }, None) => {
            asked.camera_unavailable(UnavailableReason::NoCalibration, "", Some((frame, path)))
        }
        (
            printobserver_core::CheckLook::Framed {
                frame,
                path,
                bytes,
                url,
                ..
            },
            Some(calibration),
        ) => {
            let sheet = asked.sheet.clone();
            let bed_z_mm = asked.bed_z_mm;
            let tolerance = calibration.drift_tolerance_px;
            let fitted = tokio::task::spawn_blocking(move || {
                // The sheet was held to the outlines this server carries above.
                printobserver_panels::SheetOutline::committed(sheet.as_str()).map(|outline| {
                    printobserver_panels::fit_sheet(&printobserver_panels::SheetInputs {
                        frame_jpeg: &bytes,
                        camera_snapshot_url: &url,
                        calibration: &calibration,
                        sheet: outline,
                        bed_z_mm,
                    })
                })
            })
            .await;
            let Ok(Some(fitted)) = fitted else {
                return Err(Box::new(refusal(
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "the camera check's fit did not finish",
                )));
            };
            match fitted {
                Ok(fit) => {
                    let drawn = match images.write_camera_check_image(asked.id, &fit.drawn_jpeg) {
                        Ok(drawn) => drawn,
                        Err(error) => {
                            return Err(Box::new(refusal(
                                StatusCode::INTERNAL_SERVER_ERROR,
                                error,
                            )));
                        }
                    };
                    asked.judged(&fit, tolerance, frame, drawn)
                }
                Err(error @ printobserver_panels::ComposeError::FrameMismatch { .. }) => asked
                    .camera_unavailable(
                        UnavailableReason::FrameMismatch,
                        &error.to_string(),
                        Some((frame, path)),
                    ),
                Err(error) => asked.camera_unavailable(
                    UnavailableReason::NoFrame,
                    &error.to_string(),
                    Some((frame, path)),
                ),
            }
        }
    })
}

/// The actor and the reason one request's body carries, the actor held to the
/// caller, or the refusal of the request.
fn actor_and_reason(
    caller: &Caller,
    body: Result<Json<Value>, JsonRejection>,
) -> Result<(Actor, String), Box<Response>> {
    let refused = |status: StatusCode, said: String| Box::new(refusal(status, said));
    let body = match body {
        Ok(Json(body)) => body,
        Err(rejected) => return Err(Box::new(rejected.into_response())),
    };
    let Some(fields) = body.as_object() else {
        return Err(refused(
            StatusCode::BAD_REQUEST,
            "the body is not a document carrying an `actor` and a `reason`".to_owned(),
        ));
    };
    let actor = claimed_actor(fields)
        .map_err(|rejected| refused(StatusCode::BAD_REQUEST, rejected.to_string()))?;
    if let Some(claim) = claim_refused(caller, &actor) {
        return Err(Box::new(claim));
    }
    let body: BedClearBody =
        printobserver_types::serde_json::from_value(body).map_err(|error| {
            refused(
                StatusCode::BAD_REQUEST,
                format!("the body is not an `actor` and a `reason`: {error}"),
            )
        })?;
    let reason = reason_of(body.reason.as_deref())
        .map_err(|rejected| refused(StatusCode::BAD_REQUEST, rejected.to_string()))?;
    Ok((actor, reason))
}

/// The image a check of a print would be shown of a judged fresh frame, made
/// off the request's own thread.
async fn image_shown(
    images: &Arc<crate::check_images::PanelImages>,
    print_id: PrintId,
    frame_path: &std::path::Path,
    captured_at: printobserver_types::Timestamp,
    fresh: &printobserver_core::FreshView,
    judged: &crate::alignment::Judged,
) -> Result<printobserver_core::ShownImage, String> {
    let choosing = Arc::clone(images);
    let path = frame_path.to_path_buf();
    let plan = fresh.plan.clone();
    let paused = fresh.paused;
    let judged = judged.clone();
    tokio::task::spawn_blocking(move || {
        choosing.image_of(
            print_id,
            &crate::check_images::Shown {
                frame: &path,
                captured_at,
                made_for: printobserver_core::ImageUse::Look,
                plan: plan.as_ref(),
                paused,
            },
            Some(&judged),
        )
    })
    .await
    .map_err(|error| error.to_string())?
}

/// Append a judgement's records to a print's history, the fresh frame stored
/// with the first and named by every later one, and answer where it was
/// stored.
async fn stored_with_frame(
    state: &ApiState,
    print_id: PrintId,
    judged: &crate::alignment::Judged,
    frame: (String, printobserver_vision_api::FetchedImage),
) -> Result<std::path::PathBuf, Response> {
    let mut frame = Some(frame);
    let mut stored = None;
    for record in judged.records.clone() {
        let event = state
            .supervisor
            .record_with_frame(print_id, record, frame.take())
            .await
            .map_err(|error| refusal(core_status(&error), error))?;
        if stored.is_none() {
            stored = event.image;
        }
    }
    let unkept = || {
        refusal(
            StatusCode::INTERNAL_SERVER_ERROR,
            "the fresh frame was not kept",
        )
    };
    let reference = stored.ok_or_else(unkept)?;
    match state.images.image(reference.id).await {
        Ok(printobserver_core::store::ImageLookup::Found { path, .. }) => Ok(path),
        _ => Err(unkept()),
    }
}

/// A digest as the image store names a frame: lowercase hexadecimal SHA-256.
fn hex_sha256(bytes: &[u8]) -> String {
    use sha2::Digest as _;
    sha2::Sha256::digest(bytes)
        .iter()
        .fold(String::with_capacity(64), |mut text, byte| {
            use core::fmt::Write as _;
            let _ = write!(text, "{byte:02x}");
            text
        })
}

/// Everything a recovery is checked against now, and what each action would
/// meet for the caller.
async fn recover_status(
    State(state): State<ApiState>,
    Extension(caller): Extension<Caller>,
) -> Response {
    let class = match caller {
        Caller::Operator => ActorClass::Operator,
        Caller::Turn(_) => ActorClass::Agent,
    };
    match state.supervisor.recovery_status(class).await {
        Ok(status) => answer(StatusCode::OK, &status),
        Err(error) => refusal(core_status(&error), error),
    }
}

/// Every spool, beside one line each and the charges a tool is holding.
async fn spools(State(state): State<ApiState>, Query(params): Query<SpoolsParams>) -> Response {
    let listed = match state
        .supervisor
        .spools(params.include_retired.unwrap_or(false))
        .await
    {
        Ok(listed) => listed,
        Err(error) => return refusal(core_status(&error), error),
    };
    match state.supervisor.pending_charges(None).await {
        Ok(pending) => answer(StatusCode::OK, &SpoolsAnswer::of(listed, pending)),
        Err(error) => refusal(core_status(&error), error),
    }
}

/// One spool, and the newest of the printer's own events that name it.
async fn spool(State(state): State<ApiState>, Path(spool_id): Path<SpoolId>) -> Response {
    let found = match state.supervisor.spool(spool_id).await {
        Ok(Some(found)) => found,
        Ok(None) => {
            return refusal(
                StatusCode::NOT_FOUND,
                format!("there is no spool {spool_id}"),
            );
        }
        Err(error) => return refusal(core_status(&error), error),
    };
    let query = TimelineQuery {
        spool_id: Some(spool_id),
        limit: Some(SPOOL_RECENT_EVENTS),
        ..every_timeline_kind()
    };
    match state.supervisor.timeline(query).await {
        Ok(recent) => answer(
            StatusCode::OK,
            &SpoolAnswer {
                spool: found,
                recent,
            },
        ),
        Err(error) => refusal(core_status(&error), error),
    }
}

/// The printer history unfiltered: every timeline kind, the default window.
const fn every_timeline_kind() -> TimelineQuery {
    TimelineQuery {
        kinds: Vec::new(),
        since: None,
        until: None,
        spool_id: None,
        before: None,
        limit: None,
    }
}

/// One value of a printer history read, refused naming it when it is not one.
fn read_one<T: core::str::FromStr>(name: &str, text: &str) -> Result<T, String>
where
    T::Err: core::fmt::Display,
{
    text.parse()
        .map_err(|error: T::Err| format!("`{name}` is `{text}`, which will not do: {error}"))
}

/// The printer history query a request's values make.
///
/// `kinds` may be given any number of times, each one kind; every other value
/// at most once. A value this read does not take is refused naming it rather
/// than ignored, because a filter that was quietly dropped answers more than
/// was asked for.
fn timeline_query(asked: &[(String, String)]) -> Result<TimelineQuery, String> {
    let mut query = every_timeline_kind();
    let mut seen: Vec<&str> = Vec::new();
    for (name, text) in asked {
        if name != "kinds" {
            if seen.contains(&name.as_str()) {
                return Err(format!(
                    "`{name}` was given more than once, and this read takes one"
                ));
            }
            seen.push(name);
        }
        match name.as_str() {
            "kinds" => query.kinds.push(read_one::<EventKind>(name, text)?),
            "since" => query.since = Some(read_one::<Timestamp>(name, text)?),
            "until" => query.until = Some(read_one::<Timestamp>(name, text)?),
            "spool_id" => query.spool_id = Some(read_one::<SpoolId>(name, text)?),
            "before" => query.before = Some(read_one::<EventId>(name, text)?),
            "limit" => query.limit = Some(read_one::<u32>(name, text)?),
            other => return Err(format!("the printer history takes no `{other}`")),
        }
    }
    Ok(query)
}

/// One page of the printer's own history, newest first, and the cursor for
/// the page after it when there is one.
///
/// The cursor is answered only when an older event exists, so a caller paging
/// by it stops at the last page rather than one empty page after it.
async fn printer_history(
    State(state): State<ApiState>,
    Query(asked): Query<Vec<(String, String)>>,
) -> Response {
    let query = match timeline_query(&asked) {
        Ok(query) => query,
        Err(refused) => return refusal(StatusCode::BAD_REQUEST, refused),
    };
    let limit = match query.resolved_limit() {
        Ok(limit) => limit,
        Err(error) => return refusal(store_status(&error), error),
    };
    let events = match state.supervisor.timeline(query.clone()).await {
        Ok(events) => events,
        Err(error) => return refusal(core_status(&error), error),
    };
    let full = u32::try_from(events.len()).is_ok_and(|read| read == limit);
    let next = match events.last() {
        Some(last) if full => {
            let older = TimelineQuery {
                before: Some(last.id),
                limit: Some(1),
                ..query
            };
            match state.supervisor.timeline(older).await {
                Ok(older) if older.is_empty() => None,
                Ok(_) => Some(last.id),
                Err(error) => return refusal(core_status(&error), error),
            }
        }
        _ => None,
    };
    answer(StatusCode::OK, &TimelineAnswer { events, next })
}

/// Whether the spools loaded hold enough for one file, the file was sliced
/// for their material and, when a sheet is given, that sheet suits it — read
/// now.
async fn preflight(
    State(state): State<ApiState>,
    Query(params): Query<PreflightParams>,
) -> Response {
    let Some(named) = params.file_name else {
        return refusal(
            StatusCode::BAD_REQUEST,
            "a filament check needs `file_name`, and this request carries none",
        );
    };
    let file_name = match FileName::new(&named) {
        Ok(file_name) => file_name,
        Err(error) => return refusal(StatusCode::BAD_REQUEST, error),
    };
    let sheet = match params.sheet.map(SheetId::try_from).transpose() {
        Ok(sheet) => sheet,
        Err(why) => return refusal(StatusCode::BAD_REQUEST, why),
    };
    match state.supervisor.preflight(&file_name, sheet.as_ref()).await {
        Ok(preflight) => answer(StatusCode::OK, &PreflightAnswer { preflight }),
        Err(error) => refusal(core_status(&error), error),
    }
}

/// List every print, and name the one the printer's job belongs to.
///
/// Reading this adopts that job when no open print carries its file name, which
/// is how a print started at the printer gets an identifier before anything has
/// reported on it. A printer that cannot be read still answers the stored
/// prints, with nothing active.
async fn list_and_adopt_prints(State(state): State<ApiState>) -> Response {
    match state.supervisor.list_and_adopt_prints().await {
        Ok(listing) => answer(
            StatusCode::OK,
            &PrintsAnswer {
                prints: listing.prints,
                active: listing.active,
            },
        ),
        Err(error) => refusal(core_status(&error), error),
    }
}

/// Read one print's status.
///
/// The print answered is the context's, read after the context read settled
/// the open prints against the printer's job — so a status that finds the job
/// over answers the print it closed rather than the one it found.
async fn status(
    State(state): State<ApiState>,
    Extension(caller): Extension<Caller>,
    PrintPath(print_id): PrintPath,
) -> Response {
    if let Some(refused) = scope_refused(&caller, print_id) {
        return refused;
    }
    match state.prints.print(print_id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return refusal(
                StatusCode::NOT_FOUND,
                format!("there is no print {print_id}"),
            );
        }
        Err(error) => return refusal(store_status(&error), error),
    }
    let context = match context_of(&state, print_id).await {
        Ok(context) => context,
        Err(refused) => return refused,
    };
    let session = match state.sessions.session(print_id).await {
        Ok(session) => session,
        Err(error) => return refusal(store_status(&error), error),
    };
    // The context read built the print's index when it answered a plan, so
    // this reads no file; a print it answered none for has none to answer.
    let planned_changes = if context.slicer.is_some() {
        match state
            .supervisor
            .planned_changes(&context.print, context.job.as_ref())
            .await
        {
            Ok(planned) => planned,
            Err(error) => return refusal(core_status(&error), error),
        }
    } else {
        None
    };
    answer(
        StatusCode::OK,
        &StatusAnswer {
            print: context.print,
            printer: context.printer,
            job: context.job,
            session,
            interventions: context.interventions,
            detector: context.detector,
            planned_changes,
            last_check_image: state
                .check_images
                .as_ref()
                .and_then(|images| images.last_check_image(print_id)),
        },
    )
}

/// One print's context, read off the request's own thread.
///
/// The first read of a print's context after it starts reads the print's
/// whole G-code to index it, through a printer port that blocks while it
/// reads, so it is taken on a blocking thread, as a look is: a request that
/// held an asynchronous worker for the length of a download would hold every
/// task queued behind it there too.
async fn context_of(
    state: &ApiState,
    print_id: PrintId,
) -> Result<printobserver_core::PrintContext, Response> {
    let supervisor = Arc::clone(&state.supervisor);
    let read = tokio::task::spawn_blocking(move || {
        printobserver_core::block_on(supervisor.context(print_id))
    })
    .await;
    match read {
        Ok(Ok(context)) => Ok(context),
        Ok(Err(error)) => Err(refusal(core_status(&error), error)),
        Err(error) => Err(refusal(StatusCode::INTERNAL_SERVER_ERROR, error)),
    }
}

/// Read everything a supervision turn is given about one print, with the
/// latest image materialized.
///
/// The path is looked up through the same store read the image operation
/// answers from, so the two operations cannot disagree about where an image
/// is. An image whose record is intact and whose file is gone answers no path,
/// which is what the caller's own missing-file failure is about.
async fn context(
    State(state): State<ApiState>,
    Extension(caller): Extension<Caller>,
    PrintPath(print_id): PrintPath,
    Query(params): Query<ContextParams>,
) -> Response {
    if let Some(refused) = scope_refused(&caller, print_id) {
        return refused;
    }
    // Off the request's own thread, for the reason `context_of` gives.
    let supervisor = Arc::clone(&state.supervisor);
    let since = params.since;
    let read = tokio::task::spawn_blocking(move || {
        printobserver_core::block_on(supervisor.agent_context(print_id, since))
    })
    .await;
    let context = match read {
        Ok(Ok(read)) => read,
        Ok(Err(error)) => return refusal(core_status(&error), error),
        Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
    };
    let mut image_path = None;
    if let Some(latest) = context.latest_image.as_ref() {
        match state.images.image(latest.id).await {
            Ok(lookup) => image_path = ImageAnswer::from(lookup).path,
            Err(error) => return refusal(store_status(&error), error),
        }
    }
    answer(
        StatusCode::OK,
        &ContextAnswer {
            context,
            image_path,
        },
    )
}

/// Take a fresh look at one print.
///
/// A wait longer than the supervisor allows is refused rather than shortened,
/// and a print nothing is held under is refused before any wait. The wait
/// itself runs on a blocking thread, exactly as a turn does, so that a minute
/// and a half of waiting holds no asynchronous worker the agent's own requests
/// are answered on.
async fn look(
    State(state): State<ApiState>,
    Extension(caller): Extension<Caller>,
    PrintPath(print_id): PrintPath,
    Query(params): Query<LookParams>,
) -> Response {
    if let Some(refused) = scope_refused(&caller, print_id) {
        return refused;
    }
    let wait_s = params.wait_s.unwrap_or(0);
    if wait_s > MAX_LOOK_WAIT_S {
        return refusal(
            StatusCode::BAD_REQUEST,
            format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
        );
    }
    match state.prints.print(print_id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return refusal(StatusCode::NOT_FOUND, CoreError::NoSuchPrint { print_id });
        }
        Err(error) => return refusal(store_status(&error), error),
    }
    // A look that was asked for counts whatever the camera then gives it: a
    // turn whose camera is down has still looked, and can say so.
    if let Caller::Turn(binding) = &caller {
        state.turns.note_look(binding);
    }
    let supervisor = Arc::clone(&state.supervisor);
    let taken = tokio::task::spawn_blocking(move || {
        let (arrived, waited) =
            supervisor.await_look_arrivals(print_id, Duration::from_secs(u64::from(wait_s)));
        printobserver_core::block_on(supervisor.take_look(print_id, waited, arrived))
    })
    .await;
    match taken {
        Ok(Ok(look)) => answer(StatusCode::OK, &look),
        Ok(Err(error)) => refusal(core_status(&error), error),
        Err(error) => refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
    }
}

/// Take a fresh look at the printer, with no print named.
///
/// The look and its frame belong to no print, and the wait is a plain wait:
/// nothing any print's agent is owed can end it or be taken by it. A turn's
/// credential reaches its own print alone, so this is the operator's; a wait
/// longer than the supervisor allows is refused rather than shortened.
async fn printer_look(
    State(state): State<ApiState>,
    Extension(caller): Extension<Caller>,
    Query(params): Query<LookParams>,
) -> Response {
    if let Some(refused) = printless_refused(&caller, "a look at the printer with no print named") {
        return refused;
    }
    let wait_s = params.wait_s.unwrap_or(0);
    if wait_s > MAX_LOOK_WAIT_S {
        return refusal(
            StatusCode::BAD_REQUEST,
            format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
        );
    }
    let waited = Duration::from_secs(u64::from(wait_s));
    tokio::time::sleep(waited).await;
    match state.supervisor.take_printer_look(waited).await {
        Ok(look) => answer(StatusCode::OK, &look),
        Err(error) => refusal(core_status(&error), error),
    }
}

/// Materialize one image: its record, and the absolute path its bytes are at.
///
/// An image belongs to one print, or to none when it is a frame taken of the
/// printer with no print named. A turn's credential reaches the images of its
/// own print alone, so a frame of no print is the operator's.
async fn image(
    State(state): State<ApiState>,
    Extension(caller): Extension<Caller>,
    Path(image_id): Path<ImageId>,
) -> Response {
    match state.images.image(image_id).await {
        Ok(lookup) => {
            let belongs_to = match &lookup {
                printobserver_core::ImageLookup::Found { record, .. }
                | printobserver_core::ImageLookup::FileMissing { record } => record.print_id,
            };
            let refused = match belongs_to {
                Some(print_id) => scope_refused(&caller, print_id),
                None => {
                    printless_refused(&caller, "a frame of the printer that belongs to no print")
                }
            };
            if let Some(refused) = refused {
                return refused;
            }
            answer(StatusCode::OK, &ImageAnswer::from(lookup))
        }
        Err(error) => refusal(store_status(&error), error),
    }
}

/// Read one print's events, newest first.
async fn history(
    State(state): State<ApiState>,
    Extension(caller): Extension<Caller>,
    PrintPath(print_id): PrintPath,
    Query(params): Query<HistoryParams>,
) -> Response {
    if let Some(refused) = scope_refused(&caller, print_id) {
        return refused;
    }
    let query = HistoryQuery {
        print_id,
        kinds: Vec::new(),
        since: None,
        until: None,
        limit: params.limit,
    };
    match state.events.history(query).await {
        Ok(events) => answer(StatusCode::OK, &HistoryAnswer { events }),
        Err(error) => refusal(store_status(&error), error),
    }
}

/// Read one print's manifest.
async fn manifest_get(
    State(state): State<ApiState>,
    Extension(caller): Extension<Caller>,
    PrintPath(print_id): PrintPath,
) -> Response {
    if let Some(refused) = scope_refused(&caller, print_id) {
        return refused;
    }
    let manifest = match state.prints.manifest(print_id).await {
        Ok(manifest) => manifest,
        Err(error) => return refusal(store_status(&error), error),
    };
    let narrowings = match state.prints.print(print_id).await {
        Ok(print) => print.map(|record| record.narrowings).unwrap_or_default(),
        Err(error) => return refusal(store_status(&error), error),
    };
    answer(
        StatusCode::OK,
        &ManifestAnswer {
            manifest,
            narrowings,
        },
    )
}

/// Write one print's manifest.
///
/// A manifest narrows what any actor may ask for, so replacing one is a change
/// to the bounds a print runs under and carries a reason like every other
/// change. The reason is ruled on **before** anything is written, so a request
/// without one leaves the stored manifest and the print's narrowings as they
/// were — and every range it asked wider than the envelope allows is recorded
/// on the print, exactly as it is when a start attaches one.
async fn manifest_set(
    State(state): State<ApiState>,
    Extension(caller): Extension<Caller>,
    PrintPath(print_id): PrintPath,
    body: Result<Json<ManifestBody>, JsonRejection>,
) -> Response {
    if let Some(refused) =
        operator_refused(&caller, &crate::operations::command_for("manifest_set"))
    {
        return refused;
    }
    let body = match body {
        Ok(Json(body)) => body,
        Err(rejected) => return rejected.into_response(),
    };
    if let Err(rejected) = body.reason() {
        return refusal(StatusCode::BAD_REQUEST, rejected);
    }
    let narrowed = effective_bounds(&state.supervisor.config().envelope, Some(&body.manifest));
    if let Err(error) = state
        .prints
        .put_manifest(print_id, body.manifest.clone())
        .await
    {
        return refusal(store_status(&error), error);
    }
    for narrowing in narrowed.narrowings.clone() {
        if let Err(error) = state.prints.record_narrowing(print_id, narrowing).await {
            return refusal(store_status(&error), error);
        }
    }
    answer(
        StatusCode::OK,
        &ManifestAnswer {
            manifest: Some(body.manifest),
            narrowings: narrowed.narrowings,
        },
    )
}

#[cfg(test)]
mod tests {
    use axum::http::StatusCode;
    use printobserver_core::CoreError;
    use printobserver_core::store::StoreError;

    use super::{core_status, store_status};

    /// Every refusal the store can make is answered under a status a caller can
    /// act on: what it asked for, what is not there, and what went wrong here.
    #[test]
    fn every_store_refusal_is_answered_under_a_status_a_caller_can_act_on() {
        for (error, expected) in [
            (
                StoreError::NotFound {
                    what: "print".to_owned(),
                },
                StatusCode::NOT_FOUND,
            ),
            (
                StoreError::LimitRefused {
                    limit: 1_000,
                    asked_for: 2_000,
                },
                StatusCode::BAD_REQUEST,
            ),
            (
                StoreError::ConstraintRefused {
                    constraint: "actions.decision".to_owned(),
                },
                StatusCode::BAD_REQUEST,
            ),
            (
                StoreError::Database {
                    detail: "the disk is full".to_owned(),
                },
                StatusCode::INTERNAL_SERVER_ERROR,
            ),
            (
                StoreError::Io {
                    detail: "the disk is full".to_owned(),
                },
                StatusCode::INTERNAL_SERVER_ERROR,
            ),
        ] {
            assert_eq!(store_status(&error), expected, "{error}");
        }
    }

    /// A print nothing holds is not found; a port that failed is this server's
    /// own failure rather than the caller's.
    #[test]
    fn a_print_nothing_holds_is_not_found_and_a_port_failure_is_this_servers_own() {
        assert_eq!(
            core_status(&CoreError::NoSuchPrint {
                print_id: printobserver_types::PrintId::new(),
            }),
            StatusCode::NOT_FOUND
        );
        assert_eq!(
            core_status(&CoreError::Store(StoreError::NotFound {
                what: "print".to_owned(),
            })),
            StatusCode::NOT_FOUND
        );
        assert_eq!(
            core_status(&CoreError::Unrepresentable {
                detail: "an instant".to_owned(),
            }),
            StatusCode::INTERNAL_SERVER_ERROR
        );
    }
}