printobserver-server 0.15.5

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
//! The public operations this server serves, declared once.
//!
//! # One operation per public operation, and no more
//!
//! The list here is the whole API. It is exactly one operation per variant of
//! [`PrintAction`](printobserver_core::PrintAction), of
//! [`SpoolCommand`](printobserver_core::SpoolCommand) and of
//! [`RecoveryAction`](printobserver_core::RecoveryAction) the contracts
//! declare, and the recovery read beside the last ([`RECOVERY_STATUS`]),
//! plus fifteen operations beside them — the prints listing, status, context,
//! image materialization, history, the event log followed in the order it was
//! stored, a fresh look at a print and one at the printer, the manifest's read
//! and write, the four reads of the spool ledger: the spools, one spool, the
//! printer's own history and a filament check — and the operator's word that
//! the bed is clear, and nothing else. The router is built by folding
//! over this array rather than by writing routes out, so the set served and the
//! set declared are one thing; and this crate's own tier derives the required
//! set from the contracts' own `PrintAction` rather than from a list of its
//! own, so growing this array and the routes together cannot satisfy it.
//!
//! # A read of one print may have a form for the printer as a whole
//!
//! A fresh look is one print's, and there is one of the printer with no print
//! named — before a print, between prints, after one. The two are two
//! operations, because they are two routes and two answers recorded in two
//! places; and one command, because what a caller asks for is a look either
//! way. So the print's operation names the printer's as its
//! [`Operation::printer_wide`] form: the command made from it takes its print
//! as optional and asks the printer's operation when none is named, and the
//! printer's operation has no command of its own ([`printer_wide_of`]).
//!
//! The spool ledger's operations name no print: a spool is the printer's, not
//! one print's, so they sit beneath `/spools` and `/history` rather than
//! beneath a print, and a supervision turn's print binding constrains none of
//! them. Nor do the recovery operations, beneath `/printer/recovery`: what a
//! recovery moves is the printer, whatever the last print left on its bed.
//!
//! Every operation sits beneath [`VERSION_PREFIX`], takes JSON where it takes a
//! body at all, and answers JSON.
//!
//! # Each operation declares what it takes and what it answers
//!
//! [`Operation::request`] is the request schema of one route — every value a
//! caller supplies, where it travels and whether it is required — and
//! [`Operation::response_schema`] is the schema of each answer that route can
//! produce. Neither is written out for the fifteen mutating operations: their
//! body is derived from the contracts' own
//! [`PrintAction`](printobserver_core::PrintAction) or
//! [`SpoolCommand`](printobserver_core::SpoolCommand) at run time, so a
//! variant that gains a field gains it here the moment the type does. The
//! command-line program builds its own parser from these declarations rather
//! than from a list of its own, which is what stops the two surfaces drifting.
//!
//! # The ingress is not one of them
//!
//! [`INGRESS_PATH`] is the endpoint `Obico`'s webhook notification plugin posts
//! to. It is the producer's own ingress rather than an operation a client
//! calls — it is authenticated by a shared secret rather than by an actor, it
//! carries `Obico`'s body rather than this system's, and it answers before its
//! handling completes. So it is declared separately and served outside the
//! versioned prefix, where no client can mistake one surface for the other.

use printobserver_types::serde_json::{Value, json};

// The vocabulary the mutating operations are folded from, re-exported beside
// them: a client of this surface that derives its own commands from these
// operations — the command-line program — reads which action each is and what
// that action carries from here, without naming the supervision domain itself.
pub use printobserver_core::{
    ActionKind, PrintAction, RecoveryAction, RecoveryActionKind, SpoolCommand,
};

/// The one versioned prefix every public operation is served beneath.
pub const VERSION_PREFIX: &str = "/v1";

/// The media type every operation takes a body in and answers in.
pub const MEDIA_TYPE: &str = "application/json";

/// Where `Obico`'s webhook notification plugin posts, which is not a public
/// operation. See this module's own comment.
pub const INGRESS_PATH: &str = "/obico/webhook";

/// The field a context answer carries the latest image's own path in.
pub const CONTEXT_IMAGE_PATH_FIELD: &str = "image_path";

/// The field an image answer carries that image's own path in.
pub const IMAGE_PATH_FIELD: &str = "path";

/// The field of a request body the action vocabulary's tag travels in, which a
/// caller never supplies: the operation it sends to is what names the action.
const ACTION_TAG: &str = "action";

/// The field the spool ledger's vocabulary carries its tag in, which a caller
/// never supplies either.
pub const COMMAND_TAG: &str = "command";

/// The method one operation is reached by.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Method {
    /// A read.
    Get,
    /// A request that changes something.
    Post,
    /// A write that replaces what is there.
    Put,
}

impl Method {
    /// The method as it is spelled on the wire.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Get => "GET",
            Self::Post => "POST",
            Self::Put => "PUT",
        }
    }
}

impl core::fmt::Display for Method {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Where one value of a request travels.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Located {
    /// In the request target, as a segment of the path.
    Path,
    /// In the request target, after the question mark.
    Query,
    /// In the JSON body.
    Body,
}

/// What kind of value one parameter takes.
///
/// Declared rather than left to a consumer to rediscover from the schema,
/// because a consumer that has to read a value off a command line has to know
/// what to read it as: `1.15` is a number and `1.15` is also a perfectly good
/// reason to give.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ValueKind {
    /// Text, taken as it was given.
    Text,
    /// A number, whole or otherwise.
    Number,
    /// A whole number.
    Integer,
    /// True or false.
    Boolean,
    /// A document rather than a scalar.
    Structured,
}

impl ValueKind {
    /// Whether a value of this kind is a document rather than a scalar.
    #[must_use]
    pub const fn structured(self) -> bool {
        matches!(self, Self::Structured)
    }
}

/// One value declared beside an operation, at one place in its request.
///
/// Only the operations whose body is not one action of the vocabulary declare
/// their values this way; a mutating operation's are the fields the contracts'
/// own `PrintAction` declares for the variant it names.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Declared {
    /// What it is called, spelled as the wire spells it.
    pub name: &'static str,
    /// Whether a request without it is refused.
    pub required: bool,
    /// What kind of value it takes.
    pub kind: ValueKind,
    /// The contracts' own type it is a value of, when it is one of theirs.
    ///
    /// A consumer generating a typed client needs the type rather than the
    /// kind: [`ValueKind::Structured`] says a manifest is a document, and not
    /// that it is a `JobManifest`. A value this system mints no type for — a
    /// count, a reason — declares none.
    pub shape: Option<&'static str>,
    /// Whether a request may carry it more than once, each a value of its
    /// own: only a query value can be, and it is then a list of its kind.
    pub repeated: bool,
}

impl Declared {
    /// One value carried at most once, of a kind and of no named type.
    #[must_use]
    pub const fn once(name: &'static str, required: bool, kind: ValueKind) -> Self {
        Self {
            name,
            required,
            kind,
            shape: None,
            repeated: false,
        }
    }
}

/// One value a request to an operation carries.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Parameter {
    /// What it is called, spelled as the wire spells it.
    pub name: String,
    /// Whether a request without it is refused.
    pub required: bool,
    /// Where it travels.
    pub located: Located,
    /// What kind of value it takes.
    pub kind: ValueKind,
    /// Whether a request may carry it more than once, each a value of its own.
    pub repeated: bool,
}

/// One answer a route can produce.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Answer {
    /// The operation was carried out, or the read was answered.
    Success,
    /// The policy rejected the action, and the rejection is the answer.
    Rejected,
}

impl Answer {
    /// Its own name, for a report that walks the answers of a route.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Success => "success",
            Self::Rejected => "rejected",
        }
    }
}

impl core::fmt::Display for Answer {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// What one operation does to the machine or the record.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Effect {
    /// It reads, and changes nothing.
    Read,
    /// It changes something, so it carries a reason and passes the policy.
    Mutating(ActionKind),
    /// It asks the spool ledger for one command, so it carries a reason and
    /// passes the grants every action passes — and asks nothing of the
    /// machine. Its kind is one of the ledger's five and no print action.
    Command(SpoolCommandKind),
    /// It asks the printer for one recovery action, so it carries a reason
    /// and passes the recovery grants — and names no print: what it moves is
    /// the printer, whatever the last print left on its bed.
    Recovery(RecoveryActionKind),
    /// It writes a record without asking anything of the machine.
    Write,
}

/// One command of the spool ledger's vocabulary, and nothing else.
///
/// A kind of its own rather than the whole [`ActionKind`], so that an
/// operation declared as a spool command cannot name a print action: the
/// grants rule on the [`ActionKind`] it answers, and the body is read from the
/// `SpoolCommand` variant that kind tags.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SpoolCommandKind {
    /// Register a spool.
    RegisterSpool,
    /// Load a spool onto a tool.
    LoadSpool,
    /// Unload a spool from its tool.
    UnloadSpool,
    /// Correct a spool's figure.
    AdjustSpool,
    /// Retire a spool.
    RetireSpool,
}

impl SpoolCommandKind {
    /// Every command of the ledger, in the order the contracts declare them.
    pub const ALL: [Self; 5] = [
        Self::RegisterSpool,
        Self::LoadSpool,
        Self::UnloadSpool,
        Self::AdjustSpool,
        Self::RetireSpool,
    ];

    /// The action kind the envelope grants this command under.
    #[must_use]
    pub const fn action_kind(self) -> ActionKind {
        match self {
            Self::RegisterSpool => ActionKind::RegisterSpool,
            Self::LoadSpool => ActionKind::LoadSpool,
            Self::UnloadSpool => ActionKind::UnloadSpool,
            Self::AdjustSpool => ActionKind::AdjustSpool,
            Self::RetireSpool => ActionKind::RetireSpool,
        }
    }
}

/// One public operation: what it is called, how it is reached, and what it does.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Operation {
    /// The operation's own name. For a mutating operation this is the spelling
    /// the contracts' own `PrintAction` tags that variant with.
    pub name: &'static str,
    /// The method it is reached by.
    pub method: Method,
    /// Its path beneath [`VERSION_PREFIX`].
    pub path: &'static str,
    /// What it does.
    pub effect: Effect,
    /// The media type it takes a body in, when it takes one.
    pub accepts: Option<&'static str>,
    /// The media type it answers in.
    pub answers: &'static str,
    /// The values it takes after the question mark.
    pub query: &'static [Declared],
    /// The values it takes in its body, for an operation whose body is not one
    /// action of the vocabulary. A mutating operation declares none here: its
    /// body is the `PrintAction` or `SpoolCommand` variant it names, read from
    /// the contracts themselves by [`Operation::request`].
    pub body: &'static [Declared],
    /// The field of its answer carrying an absolute path to a materialized
    /// image, when its answer carries one.
    ///
    /// Every image answer this server gives is a path on **this server's own
    /// filesystem** and no route of it answers image bytes, so a consumer
    /// reading this field is reading which of its values names a file it may
    /// not be able to open. Declared here rather than discovered, because what
    /// a consumer owes such a field is a failure of its own.
    pub image_path_field: Option<&'static str>,
    /// The operation a request to this one is made to instead when it names
    /// no print, for a read of one print that has a form for the printer as a
    /// whole.
    ///
    /// The command made from this operation takes its print as optional, and
    /// the operation named here has no command of its own: it is reached
    /// through this one's. It takes no value this operation does not, less
    /// the print.
    pub printer_wide: Option<&'static Operation>,
    /// Whether a call may name no print, and is then made under a print
    /// identifier the calling program mints.
    ///
    /// For the one operation that opens a print of its own when none is open:
    /// a caller starting a first print has no print to name, and an
    /// identifier it had to make up is one it gets wrong. What the answer
    /// names is the print the operation ran under.
    pub mints_print: bool,
}

impl Operation {
    /// Its whole path, including the versioned prefix.
    #[must_use]
    pub fn full_path(&self) -> String {
        format!("{VERSION_PREFIX}{}", self.path)
    }

    /// Which print action this operation asks for, when it asks for one.
    #[must_use]
    pub const fn action_kind(&self) -> Option<ActionKind> {
        match self.effect {
            Effect::Mutating(kind) => Some(kind),
            _ => None,
        }
    }

    /// Which spool command this operation asks for, when it asks for one.
    #[must_use]
    pub const fn command_kind(&self) -> Option<ActionKind> {
        match self.effect {
            Effect::Command(kind) => Some(kind.action_kind()),
            _ => None,
        }
    }

    /// Which action of either vocabulary this operation asks for, when it asks
    /// for one: the kind the envelope grants it under.
    #[must_use]
    pub const fn granted_as(&self) -> Option<ActionKind> {
        match self.effect {
            Effect::Mutating(kind) => Some(kind),
            Effect::Command(kind) => Some(kind.action_kind()),
            Effect::Read | Effect::Write | Effect::Recovery(_) => None,
        }
    }

    /// Which recovery action this operation asks for, when it asks for one:
    /// the kind the recovery grants rule on.
    #[must_use]
    pub const fn recovery_kind(&self) -> Option<RecoveryActionKind> {
        match self.effect {
            Effect::Recovery(kind) => Some(kind),
            _ => None,
        }
    }

    /// Whether this operation changes something.
    ///
    /// Asking the machine for an action and replacing the manifest a print runs
    /// under are both changes, and both carry a reason. What separates them is
    /// whether the policy has anything to rule on — not whether the caller has
    /// to say why.
    #[must_use]
    pub const fn is_mutating(&self) -> bool {
        matches!(
            self.effect,
            Effect::Mutating(_) | Effect::Command(_) | Effect::Recovery(_) | Effect::Write
        )
    }

    /// Every value a request to this operation carries, and where it carries it.
    ///
    /// The body of a mutating operation is not written out anywhere: it is the
    /// fields the contracts' own `PrintAction` or `SpoolCommand` declares for
    /// the variant this operation names, read from that type's own schema,
    /// less the tag and any value the path already carries. A variant that
    /// gains a field gains it here without this file changing, which is what
    /// stops a consumer building a request surface from drifting from the
    /// vocabulary.
    ///
    /// # Panics
    ///
    /// Panics when the contracts declare no variant this operation names, which
    /// is a declared list and a closed type that have come apart.
    #[must_use]
    pub fn request(&self) -> Vec<Parameter> {
        let mut found = path_parameters(self.path);
        found.extend(declared(self.query, Located::Query));
        match Vocabulary::of(self.effect) {
            Some((vocabulary, kind)) => {
                let routed: Vec<String> = found.iter().map(|path| path.name.clone()).collect();
                found.extend(
                    action_parameters(vocabulary, &kind)
                        .into_iter()
                        .filter(|field| !routed.contains(&field.name)),
                );
            }
            None => found.extend(declared(self.body, Located::Body)),
        }
        found
    }

    /// Every value a request to this operation carries, with its own shape.
    ///
    /// [`Operation::request`] answers what a command line needs — a name, a
    /// place and a kind. This answers what a **typed** consumer needs beside
    /// that: the shape of each value, as a schema referring to the contracts'
    /// own types by name where the value is one of theirs. `structured` says a
    /// manifest is a document; `{"$ref": "#/$defs/JobManifest"}` says which
    /// document, which is the difference between a generated client that types
    /// it and one that takes anything.
    ///
    /// The order is [`Operation::request`]'s own, so the two can be read side
    /// by side.
    ///
    /// # Panics
    ///
    /// Panics when the contracts declare no variant this operation names, which
    /// is a declared list and a closed type that have come apart.
    #[must_use]
    pub fn request_shapes(&self) -> Vec<(Parameter, Value)> {
        let action = match Vocabulary::of(self.effect) {
            Some((vocabulary, kind)) => action_shapes(vocabulary, &kind),
            None => Vec::new(),
        };
        self.request()
            .into_iter()
            .map(|parameter| {
                let shape = match parameter.located {
                    // What makes a path segment an identifier is the type that
                    // minted it, and a route mints nothing: it is a string.
                    Located::Path => json!({ "type": "string" }),
                    Located::Query => declared_shape(self.query, &parameter.name),
                    Located::Body if action.is_empty() => {
                        declared_shape(self.body, &parameter.name)
                    }
                    Located::Body => action
                        .iter()
                        .find(|(name, _)| *name == parameter.name)
                        .map_or_else(
                            || {
                                panic!(
                                    "`{}` takes `{}` in its body, and the action it names \
                                     declares no such field",
                                    self.name, parameter.name
                                )
                            },
                            |(_, shape)| shape.clone(),
                        ),
                };
                (parameter, shape)
            })
            .collect()
    }

    /// Every answer this operation can produce.
    ///
    /// A read answers what it read. An operation asking for an action answers
    /// that as well as the policy's own rejection, which is an answer rather
    /// than a transport failure: it carries the reason, the value asked for and
    /// the range allowed.
    #[must_use]
    pub const fn answers_with(&self) -> &'static [Answer] {
        match self.effect {
            Effect::Mutating(_) | Effect::Command(_) | Effect::Recovery(_) => {
                &[Answer::Success, Answer::Rejected]
            }
            Effect::Read | Effect::Write => &[Answer::Success],
        }
    }

    /// The schema of one answer this operation produces.
    ///
    /// A rejection is the same shape as an acceptance and deliberately so: the
    /// answer to a rejected action is the action record carrying the policy's
    /// own decision, rather than a second document a caller has to know about.
    ///
    /// # Panics
    ///
    /// Panics when this operation is not one this server serves an answer
    /// shape for, which is a declared list and a router that have come apart.
    #[must_use]
    pub fn response_schema(&self, answer: Answer) -> Value {
        use printobserver_types::schemars::schema_for;
        debug_assert!(
            self.answers_with().contains(&answer),
            "`{}` produces no {answer} answer",
            self.name
        );
        let schema = match (self.name, self.effect) {
            (_, Effect::Mutating(_)) => schema_for!(crate::wire::ActionAnswer),
            (_, Effect::Command(_)) => schema_for!(crate::wire::SpoolCommandAnswer),
            (_, Effect::Recovery(_)) => schema_for!(crate::wire::RecoveryAnswer),
            (RECOVERY_STATUS, _) => schema_for!(crate::wire::RecoveryStatusAnswer),
            ("spools", _) => schema_for!(crate::wire::SpoolsAnswer),
            ("spool", _) => schema_for!(crate::wire::SpoolAnswer),
            ("printer_history", _) => schema_for!(crate::wire::TimelineAnswer),
            ("preflight", _) => schema_for!(crate::wire::PreflightAnswer),
            ("prints", _) => schema_for!(crate::wire::PrintsAnswer),
            ("status", _) => schema_for!(crate::wire::StatusAnswer),
            ("context", _) => schema_for!(crate::wire::ContextAnswer),
            ("image", _) => schema_for!(crate::wire::ImageAnswer),
            ("history", _) => schema_for!(crate::wire::HistoryAnswer),
            ("events", _) => schema_for!(crate::wire::EventsAnswer),
            ("look" | "printer_look", _) => schema_for!(crate::wire::LookAnswer),
            ("manifest_get" | "manifest_set", _) => schema_for!(crate::wire::ManifestAnswer),
            (BED_CLEAR, _) => schema_for!(crate::wire::BedClearAnswer),
            (name, _) => panic!("the operation `{name}` has no declared answer shape"),
        };
        schema.to_value()
    }
}

/// The values declared beside an operation, at one place in the request.
fn declared(entries: &'static [Declared], located: Located) -> impl Iterator<Item = Parameter> {
    entries.iter().map(move |entry| Parameter {
        name: entry.name.to_owned(),
        required: entry.required,
        located,
        kind: entry.kind,
        repeated: entry.repeated,
    })
}

/// The shape one value declared beside an operation carries.
///
/// The contracts' own type where the declaration names one, and the kind's own
/// scalar shape where it names none — a reason and a count are values this
/// system mints no type for.
fn declared_shape(entries: &'static [Declared], name: &str) -> Value {
    let Some(entry) = entries.iter().find(|entry| entry.name == name) else {
        return json!({ "type": "string" });
    };
    let one = if let Some(shape) = entry.shape {
        json!({ "$ref": format!("#/$defs/{shape}") })
    } else {
        match entry.kind {
            ValueKind::Text => json!({ "type": "string" }),
            ValueKind::Number => json!({ "type": "number" }),
            ValueKind::Integer => json!({ "type": "integer" }),
            ValueKind::Boolean => json!({ "type": "boolean" }),
            ValueKind::Structured => json!({ "type": "object" }),
        }
    };
    // A value a request may carry more than once is a list of its kind, which
    // is what a typed consumer sends it as.
    if entry.repeated {
        json!({ "type": "array", "items": one })
    } else {
        one
    }
}

/// Which of the contracts' two closed vocabularies one mutating operation's
/// body is a variant of.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Vocabulary {
    /// The print actions, tagged by `action`.
    Actions,
    /// The spool ledger's commands, tagged by `command`.
    Commands,
    /// The recovery actions, tagged by `action`, each carried beside the
    /// actor and the reason every request carries.
    Recovery,
}

impl Vocabulary {
    /// The vocabulary one effect's body is read from, and the variant it names.
    fn of(effect: Effect) -> Option<(Self, String)> {
        let tag = |kind: ActionKind| {
            printobserver_types::serde_json::to_value(kind)
                .ok()
                .and_then(|value| value.as_str().map(str::to_owned))
                .unwrap_or_else(|| panic!("`{kind:?}` renders as the tag it is spelled by"))
        };
        match effect {
            Effect::Mutating(kind) => Some((Self::Actions, tag(kind))),
            Effect::Command(kind) => Some((Self::Commands, tag(kind.action_kind()))),
            Effect::Recovery(kind) => Some((Self::Recovery, kind.as_str().to_owned())),
            Effect::Read | Effect::Write => None,
        }
    }

    /// The field the vocabulary's tag travels in.
    const fn tag(self) -> &'static str {
        match self {
            Self::Actions | Self::Recovery => ACTION_TAG,
            Self::Commands => COMMAND_TAG,
        }
    }

    /// The vocabulary's own schema, as the contracts declare it.
    ///
    /// A recovery action names neither who asks nor why — those are the
    /// request's, not the action's — so its request body is each variant of
    /// the contracts' own `RecoveryAction` with the two beside it.
    fn schema(self) -> Value {
        use printobserver_types::schemars::schema_for;
        match self {
            Self::Actions => schema_for!(PrintAction).to_value(),
            Self::Commands => schema_for!(SpoolCommand).to_value(),
            Self::Recovery => recovery_request_schema(),
        }
    }
}

/// The contracts' own `RecoveryAction`, each variant carrying the actor and
/// the reason a recovery request carries beside it.
fn recovery_request_schema() -> Value {
    use printobserver_types::schemars::schema_for;
    let mut schema = schema_for!(RecoveryAction).to_value();
    let actor = schema_for!(printobserver_core::Actor).to_value();
    if let Some(variants) = schema.get_mut("oneOf").and_then(Value::as_array_mut) {
        for variant in variants {
            if let Some(properties) = variant.get_mut("properties").and_then(Value::as_object_mut) {
                properties.insert(
                    "actor".to_owned(),
                    json!({ "$ref": "#/$defs/Actor", "description": "Who is asking." }),
                );
                properties.insert(
                    "reason".to_owned(),
                    json!({ "type": "string", "description": "Why the actor is asking for this." }),
                );
            }
            if let Some(required) = variant.get_mut("required").and_then(Value::as_array_mut) {
                required.push(json!("actor"));
                required.push(json!("reason"));
            }
        }
    }
    let defs = schema
        .as_object_mut()
        .map(|top| top.entry("$defs").or_insert_with(|| json!({})));
    if let Some(Value::Object(defs)) = defs {
        if let Some(Value::Object(nested)) = actor.get("$defs") {
            for (name, shape) in nested {
                defs.insert(name.clone(), shape.clone());
            }
        }
        let mut own = actor.clone();
        if let Some(top) = own.as_object_mut() {
            top.remove("$defs");
            top.remove("$schema");
        }
        defs.insert("Actor".to_owned(), own);
    }
    schema
}

/// The shape of each field one action of the vocabulary takes.
///
/// Read out of the contracts' own `PrintAction` or `SpoolCommand` beside
/// [`action_parameters`], which walks the same variant for the same fields —
/// so a field that gains a shape here gains a parameter there, and neither can
/// carry one the other does not.
///
/// # Panics
///
/// Panics when the contracts declare no variant tagged with this action.
fn action_shapes(vocabulary: Vocabulary, kind: &str) -> Vec<(String, Value)> {
    let schema = vocabulary.schema();
    let variant = action_variant(&schema, vocabulary, kind);
    variant
        .get("properties")
        .and_then(Value::as_object)
        .unwrap_or_else(|| panic!("the action `{kind}` declares no properties"))
        .iter()
        .filter(|(name, _)| name.as_str() != vocabulary.tag())
        .map(|(name, field)| (name.clone(), field.clone()))
        .collect()
}

/// The variant of the contracts' own action vocabulary one action tags.
///
/// # Panics
///
/// Panics when the contracts declare no variant tagged with this action, which
/// is this server's declared list and that closed type having come apart.
fn action_variant(schema: &Value, vocabulary: Vocabulary, tag: &str) -> Value {
    schema
        .get("oneOf")
        .and_then(Value::as_array)
        .and_then(|variants| {
            variants.iter().find(|variant| {
                variant.pointer(&format!("/properties/{}/const", vocabulary.tag()))
                    == Some(&json!(tag))
            })
        })
        .cloned()
        .unwrap_or_else(|| panic!("the contracts declare no action tagged `{tag}`"))
}

/// The values one path template takes, in the order it takes them.
fn path_parameters(path: &str) -> Vec<Parameter> {
    path.split('/')
        .filter_map(|segment| segment.strip_prefix('{')?.strip_suffix('}'))
        .map(|name| Parameter {
            name: name.to_owned(),
            // A route with a hole in its path is not a route: nothing reaches
            // the handler without every segment of it.
            required: true,
            located: Located::Path,
            // A path segment is text: what makes one an identifier is the type
            // that minted it rather than anything a route can say.
            kind: ValueKind::Text,
            repeated: false,
        })
        .collect()
}

/// The body one action of the vocabulary takes, out of the contracts' own type.
///
/// # Panics
///
/// Panics when the contracts declare no variant tagged with this action, which
/// is this server's declared list and that closed type having come apart.
fn action_parameters(vocabulary: Vocabulary, kind: &str) -> Vec<Parameter> {
    let schema = vocabulary.schema();
    let variant = action_variant(&schema, vocabulary, kind);
    let required: Vec<&str> = variant
        .get("required")
        .and_then(Value::as_array)
        .map(|names| names.iter().filter_map(Value::as_str).collect())
        .unwrap_or_default();
    let properties = variant
        .get("properties")
        .and_then(Value::as_object)
        .unwrap_or_else(|| panic!("the action `{kind}` declares no properties"));
    properties
        .iter()
        .filter(|(name, _)| name.as_str() != vocabulary.tag())
        .map(|(name, field)| Parameter {
            name: name.clone(),
            required: required.contains(&name.as_str()),
            located: Located::Body,
            kind: kind_of(&resolve(&schema, field)),
            repeated: false,
        })
        .collect()
}

/// One field's own schema, following the one reference a contract field takes.
fn resolve(schema: &Value, field: &Value) -> Value {
    let Some(reference) = field.get("$ref").and_then(Value::as_str) else {
        return field.clone();
    };
    reference
        .strip_prefix("#/")
        .and_then(|rest| schema.pointer(&format!("/{rest}")))
        .cloned()
        .unwrap_or_else(|| field.clone())
}

/// What kind of value one shape describes.
///
/// Read off the shape rather than off the field's name: a closed set of string
/// constants is text however many of them there are, and an object is a
/// document however few fields it has. A shape that says nothing this can
/// decide is a document, which is the reading that still lets a caller supply
/// it — as itself, or out of a file.
fn kind_of(shape: &Value) -> ValueKind {
    if let Some(declared) = shape.get("type") {
        let named = |name: &str| match declared {
            Value::String(one) => one == name,
            Value::Array(many) => many.iter().any(|one| one == name),
            _ => false,
        };
        if named("object") || named("array") {
            return ValueKind::Structured;
        }
        if named("string") {
            return ValueKind::Text;
        }
        if named("integer") {
            return ValueKind::Integer;
        }
        if named("number") {
            return ValueKind::Number;
        }
        if named("boolean") {
            return ValueKind::Boolean;
        }
    }
    match shape.get("oneOf").or_else(|| shape.get("anyOf")) {
        Some(Value::Array(branches)) if !branches.is_empty() => {
            let kinds: Vec<ValueKind> = branches
                .iter()
                .map(|branch| match branch.get("const") {
                    Some(Value::String(_)) => ValueKind::Text,
                    _ => kind_of(branch),
                })
                .collect();
            let first = kinds[0];
            if kinds.iter().all(|kind| *kind == first) {
                first
            } else {
                ValueKind::Structured
            }
        }
        _ => ValueKind::Structured,
    }
}

/// One mutating operation, at the path its action is asked for under.
const fn action(name: &'static str, path: &'static str, kind: ActionKind) -> Operation {
    Operation {
        name,
        method: Method::Post,
        path,
        effect: Effect::Mutating(kind),
        accepts: Some(MEDIA_TYPE),
        answers: MEDIA_TYPE,
        query: &[],
        body: &[],
        image_path_field: None,
        printer_wide: None,
        mints_print: false,
    }
}

/// One spool command, at the path its command is asked for under.
const fn command(name: &'static str, path: &'static str, kind: SpoolCommandKind) -> Operation {
    Operation {
        effect: Effect::Command(kind),
        ..action(name, path, kind.action_kind())
    }
}

/// One recovery action, at the path it is asked for under.
const fn recovery(name: &'static str, path: &'static str, kind: RecoveryActionKind) -> Operation {
    Operation {
        name,
        method: Method::Post,
        path,
        effect: Effect::Recovery(kind),
        accepts: Some(MEDIA_TYPE),
        answers: MEDIA_TYPE,
        query: &[],
        body: &[],
        image_path_field: None,
        printer_wide: None,
        mints_print: false,
    }
}

/// One read, which takes no body.
const fn read(name: &'static str, path: &'static str) -> Operation {
    Operation {
        name,
        method: Method::Get,
        path,
        effect: Effect::Read,
        accepts: None,
        answers: MEDIA_TYPE,
        query: &[],
        body: &[],
        image_path_field: None,
        printer_wide: None,
        mints_print: false,
    }
}

/// How one operation's name is spelled as a command of the `printobserver`
/// program: each underscore a hyphen.
///
/// The one spelling both the command-line program's commands and the
/// supervising agent's allowed commands are made from, so the command the agent
/// is allowed to run is the command the program has.
#[must_use]
pub fn command_for(operation: &str) -> String {
    operation.replace('_', "-")
}

/// Every public operation this server serves, and there is no other.
pub const OPERATIONS: [Operation; 39] = [
    // Takes nothing: it is how a caller finds the identifier every other
    // print-specific operation takes.
    // llmlint: ignore[names_match_behavior] suppressions.toml has the reason.
    read("prints", "/prints"),
    read("status", "/prints/{print_id}/status"),
    // The print's context; asked `since` an event, its recent events are
    // only those newer than that one.
    Operation {
        query: &[
            // Read into an `EventId`, and refused when it names none.
            Declared {
                shape: Some("EventId"),
                ..Declared::once("since", false, ValueKind::Text)
            },
        ],
        image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
        ..read("context", "/prints/{print_id}/context")
    },
    Operation {
        image_path_field: Some(IMAGE_PATH_FIELD),
        ..read("image", "/images/{image_id}")
    },
    Operation {
        query: &[Declared::once("limit", false, ValueKind::Integer)],
        ..read("history", "/prints/{print_id}/history")
    },
    // The event log in the order it was stored, after a cursor: one print's
    // events and the printer's, or every event, filtered by kind, waiting up
    // to `wait_s` seconds for one to pass. A read, so it takes no actor.
    Operation {
        query: &[
            Declared::once("after", false, ValueKind::Text),
            Declared::once("print_id", false, ValueKind::Text),
            Declared {
                repeated: true,
                ..Declared::once("kinds", false, ValueKind::Text)
            },
            Declared {
                repeated: true,
                ..Declared::once("exclude_kinds", false, ValueKind::Text)
            },
            Declared::once("wait_s", false, ValueKind::Integer),
            Declared::once("limit", false, ValueKind::Integer),
        ],
        ..read("events", "/events")
    },
    read("manifest_get", "/prints/{print_id}/manifest"),
    // A fresh look: waits up to `wait_s` seconds for something to arrive for
    // the print, returning the moment something does, then takes a frame and
    // reads the printer as it is now. A read, so it takes no actor. Asked
    // with no print named, it is the printer's look below.
    Operation {
        query: &[Declared::once("wait_s", false, ValueKind::Integer)],
        image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
        printer_wide: Some(&PRINTER_LOOK_OPERATION),
        mints_print: false,
        ..read("look", "/prints/{print_id}/look")
    },
    PRINTER_LOOK_OPERATION,
    Operation {
        name: "manifest_set",
        method: Method::Put,
        path: "/prints/{print_id}/manifest",
        effect: Effect::Write,
        accepts: Some(MEDIA_TYPE),
        answers: MEDIA_TYPE,
        query: &[],
        body: &[
            Declared::once("reason", true, ValueKind::Text),
            Declared {
                shape: Some("JobManifest"),
                ..Declared::once("manifest", true, ValueKind::Structured)
            },
        ],
        image_path_field: None,
        printer_wide: None,
        mints_print: false,
    },
    // Every spool, the retired ones only when asked for, each beside one line
    // saying what it holds — and the charges held for a tool after a filament
    // change nobody has confirmed.
    Operation {
        query: &[Declared::once("include_retired", false, ValueKind::Boolean)],
        ..read("spools", "/spools")
    },
    read("spool", "/spools/{spool_id}"),
    // The printer's own history: every print, charge and spool event, newest
    // first, a page at a time. Named for the printer rather than for a print,
    // because `history` is one print's.
    Operation {
        query: &[
            Declared {
                repeated: true,
                ..Declared::once("kinds", false, ValueKind::Text)
            },
            Declared::once("since", false, ValueKind::Text),
            Declared::once("until", false, ValueKind::Text),
            Declared::once("spool_id", false, ValueKind::Text),
            Declared::once("before", false, ValueKind::Text),
            Declared::once("limit", false, ValueKind::Integer),
        ],
        ..read("printer_history", "/history")
    },
    // Whether the spools loaded hold enough for one file, were it sliced for
    // their material, and — given a sheet — whether that sheet suits it, read
    // now: it records nothing and starts nothing.
    Operation {
        query: &[
            Declared::once("file_name", true, ValueKind::Text),
            // Read into a `SheetId`, and refused when blank.
            Declared {
                shape: Some("SheetId"),
                ..Declared::once("sheet", false, ValueKind::Text)
            },
        ],
        ..read("preflight", "/preflight")
    },
    action(
        "pause",
        "/prints/{print_id}/actions/pause",
        ActionKind::Pause,
    ),
    action(
        "resume",
        "/prints/{print_id}/actions/resume",
        ActionKind::Resume,
    ),
    action(
        "cancel",
        "/prints/{print_id}/actions/cancel",
        ActionKind::Cancel,
    ),
    // A first start has no print to name, so one is minted for it.
    Operation {
        mints_print: true,
        ..action(
            "start_print",
            "/prints/{print_id}/actions/start_print",
            ActionKind::StartPrint,
        )
    },
    action(
        "set_feedrate_factor",
        "/prints/{print_id}/actions/set_feedrate_factor",
        ActionKind::SetFeedrateFactor,
    ),
    action(
        "set_flowrate_factor",
        "/prints/{print_id}/actions/set_flowrate_factor",
        ActionKind::SetFlowrateFactor,
    ),
    action(
        "set_tool_target_c",
        "/prints/{print_id}/actions/set_tool_target_c",
        ActionKind::SetToolTargetC,
    ),
    action(
        "set_bed_target_c",
        "/prints/{print_id}/actions/set_bed_target_c",
        ActionKind::SetBedTargetC,
    ),
    action(
        "set_fan_percent",
        "/prints/{print_id}/actions/set_fan_percent",
        ActionKind::SetFanPercent,
    ),
    action(
        "acknowledge_failure",
        "/prints/{print_id}/actions/acknowledge_failure",
        ActionKind::AcknowledgeFailure,
    ),
    // Closes a record printobserver left open, asking nothing of the machine.
    action(
        "close_print",
        "/prints/{print_id}/actions/close_print",
        ActionKind::ClosePrint,
    ),
    command(
        "register_spool",
        "/spools/actions/register_spool",
        SpoolCommandKind::RegisterSpool,
    ),
    command(
        "load_spool",
        "/spools/{spool_id}/actions/load_spool",
        SpoolCommandKind::LoadSpool,
    ),
    command(
        "unload_spool",
        "/spools/{spool_id}/actions/unload_spool",
        SpoolCommandKind::UnloadSpool,
    ),
    command(
        "adjust_spool",
        "/spools/{spool_id}/actions/adjust_spool",
        SpoolCommandKind::AdjustSpool,
    ),
    command(
        "retire_spool",
        "/spools/{spool_id}/actions/retire_spool",
        SpoolCommandKind::RetireSpool,
    ),
    // What every recovery action is checked against now, and what each would
    // meet. The printer's rather than a print's, so it takes no print.
    read(RECOVERY_STATUS, "/printer/recovery"),
    recovery(
        "recover_lift",
        "/printer/recovery/recover_lift",
        RecoveryActionKind::RecoverLift,
    ),
    recovery(
        "recover_cool",
        "/printer/recovery/recover_cool",
        RecoveryActionKind::RecoverCool,
    ),
    recovery(
        "recover_fan",
        "/printer/recovery/recover_fan",
        RecoveryActionKind::RecoverFan,
    ),
    recovery(
        "recover_heat",
        "/printer/recovery/recover_heat",
        RecoveryActionKind::RecoverHeat,
    ),
    recovery(
        "recover_park",
        "/printer/recovery/recover_park",
        RecoveryActionKind::RecoverPark,
    ),
    recovery(
        "recover_home_xy",
        "/printer/recovery/recover_home_xy",
        RecoveryActionKind::RecoverHomeXy,
    ),
    recovery(
        "recover_home_z",
        "/printer/recovery/recover_home_z",
        RecoveryActionKind::RecoverHomeZ,
    ),
    // The operator's word that the bed is clear, which every recovery needing
    // the bed or the nozzle clear is decided on until the next print starts.
    // The printer's rather than a print's, and asks nothing of the machine.
    Operation {
        name: BED_CLEAR,
        method: Method::Post,
        path: "/printer/bed_clear",
        effect: Effect::Write,
        accepts: Some(MEDIA_TYPE),
        answers: MEDIA_TYPE,
        query: &[],
        body: &[
            Declared {
                shape: Some("Actor"),
                ..Declared::once("actor", true, ValueKind::Structured)
            },
            Declared::once("reason", true, ValueKind::Text),
        ],
        image_path_field: None,
        printer_wide: None,
        mints_print: false,
    },
];

/// The operator's word that the bed is clear, recorded beside the recovery
/// vocabulary it is decided into.
pub const BED_CLEAR: &str = "bed_clear";

/// The read beside the recovery vocabulary: what every recovery action is
/// checked against now, and what each would meet.
pub const RECOVERY_STATUS: &str = "recover_status";

/// The fifteen operations this server serves beside the vocabularies.
///
/// Thirteen of them read, one writes a manifest and one records the operator's
/// word that the bed is clear, neither of which asks anything of the machine;
/// what they have in common is that none of them is an action, a spool command
/// or a recovery action the contracts declare. A look writes its own record into the
/// print's history — or the printer's, for a look at the printer — as every
/// read of the camera is kept, and asks nothing of the machine either; a
/// filament check records nothing at all.
pub const BESIDE_THE_ACTIONS: [&str; 15] = [
    "prints",
    "status",
    "context",
    "image",
    "history",
    "events",
    "manifest_get",
    "look",
    PRINTER_LOOK,
    "manifest_set",
    "spools",
    "spool",
    "printer_history",
    "preflight",
    BED_CLEAR,
];

/// The look at the printer with no print named, which `look` is asked as when
/// it names none.
pub const PRINTER_LOOK: &str = "printer_look";

/// A fresh look at the printer with no print named: waits `wait_s` seconds, on
/// nothing any print's agent is owed, then takes a frame, keeps it as the
/// printer's, and reads the printer as it is now. The operator's: a turn's
/// credential reaches its own print alone. Declared apart from [`OPERATIONS`],
/// which serves it, so the look's [`Operation::printer_wide`] can name it as
/// the operation itself rather than by a name that might name none.
const PRINTER_LOOK_OPERATION: Operation = Operation {
    query: &[Declared::once("wait_s", false, ValueKind::Integer)],
    image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
    ..read(PRINTER_LOOK, "/look")
};

/// The operation whose command reaches this one, when this one is another's
/// [`Operation::printer_wide`] form and so has no command of its own.
#[must_use]
pub fn printer_wide_of(name: &str) -> Option<&'static Operation> {
    OPERATIONS
        .iter()
        .find(|declared| declared.printer_wide.is_some_and(|wide| wide.name == name))
}

/// The operation of one name, when this server serves one.
#[must_use]
pub fn operation(name: &str) -> Option<&'static Operation> {
    OPERATIONS.iter().find(|declared| declared.name == name)
}

#[cfg(test)]
mod tests {
    use printobserver_core::ActionKind;

    use super::{Effect, MEDIA_TYPE, Method, OPERATIONS, VERSION_PREFIX, operation};

    /// Every method is spelled the way the wire spells it.
    #[test]
    fn every_method_is_spelled_as_the_wire_spells_it() {
        for (method, spelling) in [
            (Method::Get, "GET"),
            (Method::Post, "POST"),
            (Method::Put, "PUT"),
        ] {
            assert_eq!(method.as_str(), spelling);
            assert_eq!(method.to_string(), spelling);
        }
    }

    /// An operation's whole path carries the one versioned prefix.
    #[test]
    fn every_operation_sits_beneath_the_one_versioned_prefix() {
        for declared in OPERATIONS {
            let whole = declared.full_path();
            assert!(
                whole.starts_with(VERSION_PREFIX),
                "`{}` is served at {whole}",
                declared.name
            );
            assert_eq!(declared.answers, MEDIA_TYPE);
        }
    }

    /// A mutating operation names the action it asks for, and a read names none.
    #[test]
    fn a_mutating_operation_names_its_action_and_a_read_names_none() {
        for declared in OPERATIONS {
            match declared.effect {
                Effect::Mutating(kind) => {
                    assert_eq!(declared.action_kind(), Some(kind));
                    assert_eq!(declared.command_kind(), None);
                    assert_eq!(declared.granted_as(), Some(kind));
                    assert!(declared.is_mutating());
                }
                Effect::Command(kind) => {
                    assert_eq!(declared.action_kind(), None);
                    assert_eq!(declared.command_kind(), Some(kind.action_kind()));
                    assert_eq!(declared.granted_as(), Some(kind.action_kind()));
                    assert!(declared.is_mutating());
                }
                Effect::Recovery(kind) => {
                    assert_eq!(declared.action_kind(), None);
                    assert_eq!(declared.granted_as(), None);
                    assert_eq!(declared.recovery_kind(), Some(kind));
                    assert!(declared.is_mutating());
                }
                Effect::Write => {
                    assert_eq!(declared.action_kind(), None);
                    assert!(
                        declared.is_mutating(),
                        "`{}` writes a record and is not held to the reason every \
                         change carries",
                        declared.name
                    );
                }
                Effect::Read => {
                    assert_eq!(declared.action_kind(), None);
                    assert!(!declared.is_mutating());
                }
            }
        }
    }

    /// A mutating operation takes JSON and answers JSON; a read takes no body.
    ///
    /// The two constructors are the only way an entry of the declared list is
    /// made, so this is the shape every entry has by construction.
    #[test]
    fn a_mutating_operation_takes_a_body_and_a_read_takes_none() {
        let mutating = super::action(
            "pause",
            "/prints/{print_id}/actions/pause",
            ActionKind::Pause,
        );
        assert_eq!(mutating.method, Method::Post);
        assert_eq!(mutating.accepts, Some(MEDIA_TYPE));
        assert_eq!(mutating.answers, MEDIA_TYPE);
        assert_eq!(mutating.action_kind(), Some(ActionKind::Pause));

        let reading = super::read("status", "/prints/{print_id}/status");
        assert_eq!(reading.method, Method::Get);
        assert_eq!(reading.accepts, None);
        assert_eq!(reading.answers, MEDIA_TYPE);
        assert_eq!(reading.effect, Effect::Read);
    }

    /// A spool command's body is its command's own fields, less the tag and
    /// the spool its path already names.
    #[test]
    fn a_spool_commands_body_is_its_fields_less_the_tag_and_the_routed_spool() {
        let load = operation("load_spool").expect("the load is served");
        let names: Vec<(String, super::Located)> = load
            .request()
            .into_iter()
            .map(|parameter| (parameter.name, parameter.located))
            .collect();
        assert_eq!(
            names,
            vec![
                ("spool_id".to_owned(), super::Located::Path),
                ("actor".to_owned(), super::Located::Body),
                ("reason".to_owned(), super::Located::Body),
                ("tool".to_owned(), super::Located::Body),
            ]
        );
        let register = operation("register_spool").expect("the registration is served");
        assert!(
            register
                .request()
                .iter()
                .all(|parameter| parameter.name != super::COMMAND_TAG
                    && parameter.located == super::Located::Body)
        );
    }

    /// The ledger's own kind names exactly the commands the contracts' own
    /// `SpoolCommand` declares, each by the tag it is spelled with, and every
    /// spool command operation is declared under one of them.
    #[test]
    fn the_ledgers_kinds_are_the_commands_the_contracts_declare() {
        let schema = super::Vocabulary::Commands.schema();
        let declared: Vec<String> = schema["oneOf"]
            .as_array()
            .expect("the spool vocabulary is a union")
            .iter()
            .filter_map(|variant| variant.pointer("/properties/command/const"))
            .filter_map(|tag| tag.as_str().map(str::to_owned))
            .collect();
        let kinds: Vec<String> = super::SpoolCommandKind::ALL
            .iter()
            .map(|kind| {
                printobserver_types::serde_json::to_value(kind.action_kind())
                    .ok()
                    .and_then(|tag| tag.as_str().map(str::to_owned))
                    .expect("an action kind renders as its tag")
            })
            .collect();
        assert_eq!(kinds, declared);
        let served: Vec<super::SpoolCommandKind> = OPERATIONS
            .iter()
            .filter_map(|operation| match operation.effect {
                Effect::Command(kind) => Some(kind),
                _ => None,
            })
            .collect();
        assert_eq!(served, super::SpoolCommandKind::ALL.to_vec());
    }

    /// A value a request may carry more than once is described as a list.
    #[test]
    fn a_repeated_value_is_described_as_a_list_of_its_kind() {
        let history = operation("printer_history").expect("the printer history is served");
        let kinds = history
            .request_shapes()
            .into_iter()
            .find(|(parameter, _)| parameter.name == "kinds")
            .expect("the history takes kinds");
        assert!(kinds.0.repeated);
        assert_eq!(
            kinds.1,
            printobserver_types::serde_json::json!({"type": "array", "items": {"type": "string"}})
        );
    }

    /// A recovery action's body is its own fields beside the actor and the
    /// reason, less the tag the operation names.
    #[test]
    fn a_recovery_actions_body_is_its_fields_beside_the_actor_and_the_reason() {
        let heat = operation("recover_heat").expect("the heat is served");
        let names: Vec<(String, bool, super::Located)> = heat
            .request()
            .into_iter()
            .map(|parameter| (parameter.name, parameter.required, parameter.located))
            .collect();
        assert_eq!(
            names,
            vec![
                ("actor".to_owned(), true, super::Located::Body),
                ("clearance_asserted".to_owned(), false, super::Located::Body),
                ("reason".to_owned(), true, super::Located::Body),
                ("target_c".to_owned(), true, super::Located::Body),
                ("tool".to_owned(), true, super::Located::Body),
            ]
        );
        let cool = operation("recover_cool").expect("the cool is served");
        let names: Vec<String> = cool
            .request()
            .into_iter()
            .map(|parameter| parameter.name)
            .collect();
        assert_eq!(names, vec!["actor".to_owned(), "reason".to_owned()]);
        let served: Vec<super::RecoveryActionKind> = OPERATIONS
            .iter()
            .filter_map(super::Operation::recovery_kind)
            .collect();
        assert_eq!(served, super::RecoveryActionKind::ALL.to_vec());
    }

    /// A printer-wide form is an operation this server serves, takes the
    /// values its print's operation takes less the print, names no print of
    /// its own, and is the form of exactly one operation.
    #[test]
    fn a_printer_wide_form_takes_its_prints_values_less_the_print() {
        let mut forms = 0;
        for declared in OPERATIONS {
            let Some(wide) = declared.printer_wide else {
                continue;
            };
            forms += 1;
            assert_eq!(
                operation(wide.name),
                Some(wide),
                "the printer-wide form is not an operation this server serves"
            );
            assert_eq!(wide.method, declared.method, "`{}`", declared.name);
            assert_eq!(wide.effect, declared.effect, "`{}`", declared.name);
            assert_eq!(wide.image_path_field, declared.image_path_field);
            assert_eq!(
                wide.printer_wide, None,
                "a printer-wide form has none of its own"
            );
            assert!(!wide.path.contains("{print_id}"), "`{}`", wide.name);
            let taken: Vec<super::Parameter> = declared
                .request()
                .into_iter()
                .filter(|parameter| parameter.name != "print_id")
                .collect();
            assert_eq!(wide.request(), taken, "`{}`", wide.name);
            assert_eq!(
                super::printer_wide_of(wide.name).map(|found| found.name),
                Some(declared.name)
            );
        }
        assert_eq!(
            forms, 1,
            "the look is the one read with a printer-wide form"
        );
        assert!(super::printer_wide_of("look").is_none());
    }

    /// An operation this server does not serve is answered as none.
    #[test]
    fn an_operation_this_server_does_not_serve_is_answered_as_none() {
        assert_eq!(operation("pause").map(|found| found.name), Some("pause"));
        assert!(operation("reboot").is_none());
    }
}