printobserver-sdk 0.7.1

Rust client for 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
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
//! Generated by `contract-codegen` from the checked-in contract schemas.
//!
//! This file is the Rust client's request and response types.
//!
//! Do not edit by hand: change the contracts, regenerate with `just
//! generate-clients`, and commit what that writes.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use crate::{Client, ClientError};

/// The version of the server contract these types were generated from: the
/// version of the workspace this crate is compiled from. A published crate
/// reports the release version it was built at, and a crate compiled from a
/// checkout reports that checkout's workspace version.
pub const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Every operation this client exposes a method for, which is every operation
/// the server declares and no other.
pub const OPERATION_NAMES: [&str; 28] = [
    "prints",
    "status",
    "context",
    "image",
    "history",
    "events",
    "manifest_get",
    "look",
    "manifest_set",
    "spools",
    "spool",
    "printer_history",
    "preflight",
    "pause",
    "resume",
    "cancel",
    "start_print",
    "set_feedrate_factor",
    "set_flowrate_factor",
    "set_tool_target_c",
    "set_bed_target_c",
    "set_fan_percent",
    "acknowledge_failure",
    "register_spool",
    "load_spool",
    "unload_spool",
    "adjust_spool",
    "retire_spool",
];

/// A field that was sent, null included, as what was sent.
fn present<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
    D: serde::Deserializer<'de>,
    T: Deserialize<'de>,
{
    T::deserialize(deserializer).map(Some)
}

/// What an operator's acknowledgement of a failure event asks for next.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AcknowledgementDisposition {
    /// Carry on printing.
    #[serde(rename = "continue")]
    Continue,
    /// Carry on printing, watched more closely.
    #[serde(rename = "watch")]
    Watch,
    /// The print should stop. Recorded for whoever may cancel it: the
    /// acknowledgement itself asks nothing of the machine.
    #[serde(rename = "stop")]
    Stop,
}

/// What one mutating request left behind it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ActionAnswer {
    /// The bounded intervention it opened, when it opened one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub intervention: Option<Intervention>,
    /// What the printer said, when the request reached it and it refused.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub printer_refusal: Option<String>,
    /// The record of the request and the decision taken on it. A rejected
    /// request's rejection is here, carrying its reason, the value asked for
    /// and the range allowed, so a caller can ask again inside the range.
    pub record: ActionRecord,
}

/// An accepted action reached the printer.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ActionExecutedPayload {
    /// The action's identifier.
    pub action_id: ActionId,
    /// The bounded intervention it opened, when it opened one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub intervention_id: Option<InterventionId>,
}

/// A lowercase hyphenated version 7 UUID identifying one requested action.
pub type ActionId = String;

/// One action of the closed vocabulary, named without its payload.
///
/// This is what a safety envelope grants and what a policy rejection names;
/// the
/// payload lives on `PrintAction` itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ActionKind {
    /// Pause the print.
    #[serde(rename = "pause")]
    Pause,
    /// Resume the print.
    #[serde(rename = "resume")]
    Resume,
    /// Cancel the print.
    #[serde(rename = "cancel")]
    Cancel,
    /// Start a print of a named file.
    #[serde(rename = "start_print")]
    StartPrint,
    /// Set the feedrate factor.
    #[serde(rename = "set_feedrate_factor")]
    SetFeedrateFactor,
    /// Set the flowrate factor.
    #[serde(rename = "set_flowrate_factor")]
    SetFlowrateFactor,
    /// Set a tool's target temperature.
    #[serde(rename = "set_tool_target_c")]
    SetToolTargetC,
    /// Set the bed's target temperature.
    #[serde(rename = "set_bed_target_c")]
    SetBedTargetC,
    /// Set the fan percentage.
    #[serde(rename = "set_fan_percent")]
    SetFanPercent,
    /// Acknowledge a failure event.
    #[serde(rename = "acknowledge_failure")]
    AcknowledgeFailure,
    /// Register a spool.
    #[serde(rename = "register_spool")]
    RegisterSpool,
    /// Load a spool onto a tool.
    #[serde(rename = "load_spool")]
    LoadSpool,
    /// Unload a spool from its tool.
    #[serde(rename = "unload_spool")]
    UnloadSpool,
    /// Correct a spool's remaining figure.
    #[serde(rename = "adjust_spool")]
    AdjustSpool,
    /// Retire a spool.
    #[serde(rename = "retire_spool")]
    RetireSpool,
}

/// One request, the decision taken on it, and what became of it.
///
/// `executed_at` and `outcome` are both optional and are absent together: a
/// record is written when the decision is taken, which is before — and, for a
/// rejected request, instead of — anything reaching the printer.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ActionRecord {
    /// The decision policy took on it.
    pub decision: PolicyDecision,
    /// When it reached the printer, if it did.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub executed_at: Option<Timestamp>,
    /// This record's identifier, minted by the store.
    pub id: ActionId,
    /// What the printer made of it, if it reached the printer.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub outcome: Option<ExecutionOutcome>,
    /// The print this request was made against.
    pub print_id: PrintId,
    /// The request itself.
    pub request: ActionRequest,
}

/// Policy refused an action.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ActionRejectedPayload {
    /// The action's identifier.
    pub action_id: ActionId,
    /// The whole decision, carrying which rejection it was.
    pub decision: PolicyDecision,
}

/// One request an actor made, at the instant it made it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ActionRequest {
    /// What was asked for.
    pub action: PrintAction,
    /// Who asked.
    pub actor: Actor,
    /// When they asked.
    pub requested_at: Timestamp,
}

/// An actor asked for an action.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ActionRequestedPayload {
    /// What was asked for.
    pub action: PrintAction,
    /// The action's identifier.
    pub action_id: ActionId,
    /// Who asked.
    pub actor: Actor,
}

/// Who asked for something.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Actor {
    /// The supervising agent, naming its session.
    #[serde(rename = "agent")]
    Agent {
        /// The supervision session the agent is acting in.
        session_name: String,
    },
    /// A person.
    #[serde(rename = "operator")]
    Operator,
    /// The supervisor itself.
    #[serde(rename = "system")]
    System,
}

/// An actor class, which is what a safety envelope grants actions to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ActorClass {
    /// The supervising agent.
    #[serde(rename = "agent")]
    Agent,
    /// A person.
    #[serde(rename = "operator")]
    Operator,
    /// The supervisor itself.
    #[serde(rename = "system")]
    System,
}

/// One thing an adjustment may change.
pub type Adjustable = String;

/// The agent's written record of one supervision turn.
///
/// This is deliberately not how the agent acts: acting is a
/// `PrintAction` that policy rules on.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AgentAssessment {
    /// How sure the agent is.
    pub confidence: Confidence,
    /// What the agent did.
    pub did: String,
    /// Whether the agent is escalating to a person.
    pub escalating: bool,
    /// Whether the print should carry on.
    pub should_continue: bool,
    /// One line saying what is happening.
    pub summary: String,
    /// Why it did it.
    pub why: String,
}

/// The agent wrote down what it made of a turn.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AgentAssessmentPayload {
    /// What the agent answered with.
    pub assessment: AgentAssessment,
    /// The session the turn ran in.
    pub session_name: String,
}

/// Somebody took a fresh look at the print.
///
/// Written down before the camera is asked for a frame, so that a frame the
/// camera would not give is recorded against a look that is already in the
/// history; the frame itself, when there is one, is this event's image.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CameraLookPayload {
    /// The events for the print that arrived while it waited, and that it
    /// handed to whoever looked, oldest first.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub delivered: Option<Vec<EventId>>,
    /// How long the look waited for something to happen before it was taken,
    /// in whole seconds.
    pub waited_s: i64,
}

/// The durable identity of one debit, so that a replay can never debit twice.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "key")]
pub enum ChargeKey {
    /// One segment of a print this system watched, on one tool.
    #[serde(rename = "print")]
    Print {
        /// The print.
        print_id: PrintId,
        /// Which segment: zero from the print's start, and one more each time
        /// a mid-print swap or a filament-change signal closes the current
        /// one.
        segment: i64,
        /// The tool, in the printer's own numbering.
        tool: i64,
    },
    /// One print this system never saw, on one tool.
    #[serde(rename = "unobserved")]
    Unobserved {
        /// The file that was printed.
        file_name: String,
        /// The file's tally generation, which advances each time the
        /// printer's
        /// tally for the file is reset.
        generation: i64,
        /// Where the file lives, in the printer's own vocabulary.
        origin: String,
        /// The print's ordinal in the file's tally — completed and failed
        /// prints counted up to and including this one — within that
        /// generation.
        print_number: i64,
        /// The tool, in the printer's own numbering.
        tool: i64,
    },
}

/// How the length a charge debits was worked out.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ChargeMethod {
    /// A completed print: the length the file's analysis gives.
    #[serde(rename = "slicer_estimate")]
    SlicerEstimate,
    /// The extrusion the file's own moves add up to, up to a position in it.
    #[serde(rename = "gcode_extrusion")]
    GcodeExtrusion,
    /// The analysed length scaled by how far into the file the print got; the
    /// fallback used only when the file itself could not be read.
    #[serde(rename = "file_fraction")]
    FileFraction,
    /// A completed print this system never saw: the file's analysed length.
    #[serde(rename = "unobserved_estimate")]
    UnobservedEstimate,
}

/// Filament a tool fed after an unconfirmed filament change was held for the
/// next spool loaded onto that tool, or confirmed on it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ChargePendedPayload {
    /// What was held.
    pub pending: PendingCharge,
}

/// What a charge took from a spool, and the whole calculation behind it.
///
/// Present or absent as one: a debit names its spool exactly when it carries
/// the grams, the figures they were worked out with, and the spool's figure
/// either side of them.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ChargedFilament {
    /// The density the grams were worked out with, in grams per cubic
    /// centimetre.
    pub density_g_cm3: f64,
    /// The diameter the grams were worked out with, in millimetres.
    pub diameter_mm: f64,
    /// What the length weighs, in grams; what is subtracted from the spool.
    pub grams: f64,
    /// The spool's figure after it, in grams.
    pub remaining_after_g: f64,
    /// The spool's figure before the charge, in grams.
    pub remaining_before_g: f64,
    /// The spool charged.
    pub spool_id: SpoolId,
}

/// One mark a spool command cleared, and the spool it was cleared from.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ClearedMark {
    /// The reason that no longer stands.
    pub reason: UnverifiedReason,
    /// The spool the mark was cleared from.
    pub spool_id: SpoolId,
}

/// How sure the agent is.
///
/// A closed vocabulary rather than a number, because a number invites a
/// precision the agent does not have.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Confidence {
    /// Not sure.
    #[serde(rename = "low")]
    Low,
    /// Fairly sure.
    #[serde(rename = "medium")]
    Medium,
    /// Sure.
    #[serde(rename = "high")]
    High,
}

/// What a context read answers.
///
/// The latest image is **materialized** here rather than left as the handle
/// `PrintContext` carries: the one thing a supervision turn does with an
/// image is look at it, and a handle is not something anything can open. The
/// path is absolute on this server's own filesystem, exactly as
/// `ImageAnswer`'s is, and is absent when there is no image or when the
/// record is intact and the file is not.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ContextAnswer {
    /// Everything a supervision turn is given about the print.
    pub context: PrintContext,
    /// Where the latest image's bytes are, absolute on this host.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub image_path: Option<String>,
}

/// The envelope intersected with the print's manifest.
///
/// This is what context reports, so that the agent can see its own limits
/// before it asks. Computing one is the supervision core's; this crate
/// declares
/// the shape and nothing that produces it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EffectiveBounds {
    /// The range each adjustable may be set to, inclusive.
    pub allowed: BTreeMap<String, Range>,
}

/// What this server answers when it will not do what it was asked.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ErrorAnswer {
    /// One line saying why, in the words of whatever refused it.
    pub error: String,
}

/// A lowercase hyphenated version 7 UUID identifying one event.
pub type EventId = String;

/// The name one kind of event is written down under: lowercase `snake_case`,
/// declared by the domain that owns the event.
pub type EventKind = String;

/// One event, as the store holds it and the server serves it.
///
/// `raw` holds the bytes exactly as received for an externally sourced event
/// and is absent for an internally raised one — it is what makes the history
/// auditable when a normalization turns out to be wrong. `print_id` is
/// optional, because an externally sourced event may name no print this
/// system
/// knows.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EventRecord {
    /// This event's identifier, minted by the store.
    pub id: EventId,
    /// The image it arrived with, when it arrived with one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub image: Option<ImageRef>,
    /// Which event this is.
    pub kind: EventKind,
    /// What it carries, in the form its kind declares.
    pub payload: serde_json::Value,
    /// The print it belongs to, when it belongs to one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub print_id: Option<PrintId>,
    /// The bytes exactly as received, for an externally sourced event.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub raw: Option<RawBytes>,
    /// When it was received.
    pub received_at: Timestamp,
    /// Where it came from.
    pub source: EventSource,
}

/// Where an event came from, as the bare string the domain that raised it
/// declares for itself.
pub type EventSource = String;

/// What an events read answers: the events stored after its cursor that pass
/// its filters, oldest first, and where the next read picks up.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EventsAnswer {
    /// The last event this read examined, whether or not it passed the
    /// filters, given as `after` to read on from it; null when the log held
    /// nothing to start after. Always sent, as null when it is that.
    pub cursor: Option<EventId>,
    /// The events, oldest first in the order they were stored, each exactly
    /// as
    /// a history read serves it.
    pub events: Vec<EventRecord>,
    /// The watched print's end as stored, whatever the filters said, and null
    /// while it is open. Absent from a read that names no print.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "present"
    )]
    pub print_ended: Option<Option<PrintEnded>>,
}

/// What happened when an accepted action reached the printer.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ExecutionOutcome {
    /// The printer took it.
    #[serde(rename = "succeeded")]
    Succeeded,
    /// The printer did not, for this reason.
    #[serde(rename = "failed")]
    Failed {
        /// Why it failed.
        reason: String,
    },
}

/// A filament change was signalled during a print.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FilamentChangeSignalledPayload {
    /// The position the spool was charged up to, and how fresh it is, when
    /// one
    /// was known; absent, there is no position and so no claim about one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub position: Option<SignalPosition>,
    /// The kind of the alert that carried the signal.
    pub source_kind: EventKind,
    /// The spool that was on it, when one was tracked.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub spool_id: Option<SpoolId>,
    /// The tool the change was signalled for, when it is known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool: Option<i64>,
}

/// Filament was charged against a spool, or recorded uncharged.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FilamentConsumedPayload {
    /// The file's analysed length for the tool, in millimetres, when it had
    /// one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub analysed_length_mm: Option<f64>,
    /// The durable identity of this debit.
    pub charge_key: ChargeKey,
    /// The spool charged and the whole calculation of what it was charged;
    /// absent when nothing was tracked on the tool, and the filament was
    /// recorded uncharged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub charged: Option<ChargedFilament>,
    /// How much was fed, in millimetres.
    pub length_mm: f64,
    /// How the length was worked out.
    pub method: ChargeMethod,
    /// Anything a reader needs to make sense of the figure.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    /// How far into the file the charge runs, when that was read.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub position: Option<FilePosition>,
    /// The tool that fed it, as its key names it.
    pub tool: i64,
}

/// A file name a printer's own file API can be asked for: no path separator,
/// no NUL byte, no `.` or `..` segment, no drive prefix, and not empty.
pub type FileName = String;

/// How far into its file a print had got, and when that was read.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FilePosition {
    /// The byte the printer had read the file up to.
    pub bytes: i64,
    /// When the position was read.
    pub observed_at: Timestamp,
    /// The file's size in bytes, when it was known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub size_bytes: Option<i64>,
}

/// The printer's tally for a file went down — the file was deleted and
/// uploaded again — so the file's tally generation advanced, and the new
/// count
/// is that generation's growth from zero.
///
/// The rebaseline itself marks no spool; only an `unverified` disposition
/// does.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FileTallyRebaselinedPayload {
    /// What became of the prints the new generation counts.
    pub disposition: RebaselineDisposition,
    /// The file whose tally went down.
    pub file_name: String,
    /// The failed prints the new tally counts.
    pub new_failures: i64,
    /// The generation it is in now.
    pub new_generation: i64,
    /// The completed prints the new tally counts.
    pub new_successes: i64,
    /// The failed prints the old tally counted.
    pub old_failures: i64,
    /// The generation the tally was in.
    pub old_generation: i64,
    /// The completed prints the old tally counted.
    pub old_successes: i64,
    /// Where it lives, in the printer's own vocabulary.
    pub origin: String,
}

/// One heater, as a source reported it.
///
/// Every field is optional, because a source that reports no heater at all
/// reports none of these; each is a plausibility-ranged reported value in
/// degrees Celsius.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HeaterSnapshot {
    /// The temperature the heater is at.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub actual_c: Option<Reported>,
    /// The offset applied to this heater's target.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub offset_c: Option<Reported>,
    /// The temperature the heater is driving towards.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_c: Option<Reported>,
}

/// What a history read answers.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HistoryAnswer {
    /// The print's events, newest first.
    pub events: Vec<EventRecord>,
}

/// What an image read answers.
///
/// The path is absolute on this server's own filesystem, and is the whole of
/// the answer about the bytes: nothing here renders them, encodes them or
/// serves them. It is absent when the record is intact and the file is not,
/// which is a different answer from there being no such image.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ImageAnswer {
    /// Where its bytes are, absolute on this host.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    /// The record.
    pub record: ImageRecord,
}

/// A lowercase hyphenated version 7 UUID identifying one image.
pub type ImageId = String;

/// One image, stored beside the event it arrived with.
///
/// `relative_path` is relative to the configured state directory, so that the
/// store stays portable. Materializing an image resolves that to an absolute
/// path; nothing in this system renders image bytes into JSON.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ImageRecord {
    /// How many bytes it is.
    pub byte_len: i64,
    /// The content type it was served as.
    pub content_type: String,
    /// The event it arrived with.
    pub event_id: EventId,
    /// When it was fetched.
    pub fetched_at: Timestamp,
    /// This image's identifier, minted by the store.
    pub id: ImageId,
    /// The print it belongs to.
    pub print_id: PrintId,
    /// Where it lives, relative to the configured state directory.
    pub relative_path: String,
    /// The SHA-256 of its bytes, lowercase hexadecimal.
    pub sha256: String,
    /// Where it was fetched from, when it was fetched from somewhere.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_url: Option<String>,
}

/// The handle an image travels in context under.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ImageRef {
    /// The image's identifier.
    pub id: ImageId,
    /// The SHA-256 of its bytes, lowercase hexadecimal.
    pub sha256: String,
}

/// One adjustment made for a bounded time.
///
/// `prior_value` is read from the printer snapshot taken before the change,
/// and
/// is absent when the printer reported none — in which case expiry restores
/// nothing and the outcome says so rather than guessing a default.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Intervention {
    /// The action that asked for it.
    pub action_id: ActionId,
    /// What it changed.
    pub adjustable: Adjustable,
    /// When it was applied.
    pub applied_at: Timestamp,
    /// What it was changed to.
    pub applied_value: f64,
    /// When it stops standing.
    pub expires_at: Timestamp,
    /// This intervention's identifier, minted by the store.
    pub id: InterventionId,
    /// What became of it.
    pub outcome: InterventionOutcome,
    /// The print it was made against.
    pub print_id: PrintId,
    /// What the printer reported before the change, if it reported anything.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prior_value: Option<f64>,
    /// When the prior value was put back, if it was.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub restored_at: Option<Timestamp>,
}

/// A bounded intervention expired.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InterventionExpiredPayload {
    /// What it had changed.
    pub adjustable: Adjustable,
    /// The intervention's identifier.
    pub intervention_id: InterventionId,
    /// What became of it.
    pub outcome: InterventionOutcome,
}

/// A lowercase hyphenated version 7 UUID identifying one bounded
/// intervention.
pub type InterventionId = String;

/// What became of a bounded change.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum InterventionOutcome {
    /// It is still in force.
    #[serde(rename = "still_active")]
    StillActive,
    /// The prior value was put back.
    #[serde(rename = "restored")]
    Restored,
    /// There was no prior value to put back.
    #[serde(rename = "restore_unavailable")]
    RestoreUnavailable,
    /// Putting the prior value back failed.
    #[serde(rename = "restore_failed")]
    RestoreFailed {
        /// Why it failed.
        reason: String,
    },
    /// Another intervention replaced it before it expired.
    #[serde(rename = "superseded")]
    Superseded {
        /// The intervention that replaced it.
        by: InterventionId,
    },
}

/// What a sliced job declares about itself and about what may be adjusted.
///
/// An adjustable the manifest does not name takes the envelope's own range; a
/// manifest range wider than the envelope's is narrowed to the envelope's and
/// the narrowing is recorded on the print. A manifest may only narrow.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JobManifest {
    /// The range each named adjustable may take, inclusive.
    pub allowed: BTreeMap<String, Range>,
    /// The file this manifest is about, as the slicer named it.
    pub file_name: String,
    /// The material the job is sliced for.
    pub material: String,
    /// Whatever else the slicer recorded.
    pub metadata: BTreeMap<String, String>,
    /// The nozzle the job is sliced for, in millimetres.
    pub nozzle_diameter_mm: f64,
    /// The slicer profile the job was sliced with.
    pub slicer_profile: String,
}

/// The job a printer reports it is running.
///
/// Every field but `state` is optional: an absent one means the source did
/// not
/// report it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JobSnapshot {
    /// How far through the print is, as a fraction from zero to one.
    ///
    /// Normalized to a fraction here regardless of how the source expresses
    /// it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub completion: Option<Reported>,
    /// The error the source reports, when it reports one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// The whole print's estimated duration, in whole seconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub estimated_print_time_s: Option<i64>,
    /// The filament the source's analysis of the file says each tool uses;
    /// empty when the source reported none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub filament: Option<Vec<ToolFilament>>,
    /// The name of the file being printed, as the source reported it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file_name: Option<String>,
    /// Where the file lives, in the source's own vocabulary.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file_origin: Option<String>,
    /// How far into the file the printer has read, in bytes, when the source
    /// reported it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file_position_bytes: Option<i64>,
    /// How long the print has left, in whole seconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub print_time_left_s: Option<i64>,
    /// How long the print has been running, in whole seconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub print_time_s: Option<i64>,
    /// The file's size in bytes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub size_bytes: Option<i64>,
    /// The state the source reports the job to be in.
    pub state: PrinterState,
}

/// One spool loaded on one tool, as a print started.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LoadedSpool {
    /// The spool loaded on it.
    pub spool_id: SpoolId,
    /// The tool, in the printer's own numbering.
    pub tool: i64,
}

/// One fresh look at a print.
///
/// An answer rather than a record, so it admits fields beside its own the way
/// every answer of the server does: a client that could not open the frame's
/// path says so in a field of its own beside the rest of the answer.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Look {
    /// The events for this print that arrived while the look waited, oldest
    /// first; the look returned early when there were any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub arrived: Option<Vec<EventRecord>>,
    /// Whether the print is paused and the pause is the detector's, which is
    /// what an adjustment asked for now would be applied under.
    pub detector_paused: bool,
    /// The look itself, as it was written into the print's history, carrying
    /// the frame as its image when there is one.
    pub event: EventRecord,
    /// The frame the camera gave, absent when no camera is configured or it
    /// gave none — which the history records as a port failure.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub frame: Option<ImageRef>,
    /// The absolute path the frame's bytes are at, on the supervisor's host.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub image_path: Option<String>,
    /// The job the printer reports now, absent when it could not be read.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub job: Option<JobSnapshot>,
    /// The printer's state now, absent when it could not be read.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub printer: Option<PrinterSnapshot>,
}

/// An external body arrived that could not be read.
///
/// This kind always carries its `raw` bytes, and it exists so that an alert
/// this system cannot read is written down rather than dropped.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MalformedExternalEventPayload {
    /// One line saying why the body could not be read.
    pub detail: String,
}

/// What a manifest read or write answers.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ManifestAnswer {
    /// The manifest, when the print has one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub manifest: Option<JobManifest>,
    /// Every range this manifest asked wider than the envelope allows,
    /// narrowed
    /// to the envelope's — recorded on the print, so nobody has to wonder
    /// later
    /// which bound applied.
    pub narrowings: Vec<ManifestNarrowing>,
}

/// One adjustable whose manifest range was wider than the envelope's.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ManifestNarrowing {
    /// The adjustable that was narrowed.
    pub adjustable: Adjustable,
    /// The range that stands.
    pub applied: Range,
    /// The range the manifest asked for.
    pub requested: Range,
}

/// Obico reported a print failure.
///
/// The two instants are optional because Obico's own field for each is a Unix
/// timestamp number, an empty string, or absent, and the last two both mean
/// the
/// producer reported no instant. An absent field here is that, never an epoch
/// date standing in for it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ObicoFailureAlertPayload {
    /// When the print ended, when Obico reported an instant for it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ended_at: Option<Timestamp>,
    /// The file being printed, when Obico named one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file_name: Option<String>,
    /// Whether Obico called it a warning rather than a failure.
    pub is_warning: bool,
    /// Obico's own identifier for the print, when it named one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub obico_print_id: Option<i64>,
    /// Whether Obico paused the print itself.
    pub print_paused: bool,
    /// When the print started, when Obico reported an instant for it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub started_at: Option<Timestamp>,
}

/// The kind of printer notification Obico sent, normalized.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ObicoNotificationType {
    /// A print started.
    #[serde(rename = "started")]
    Started,
    /// A print finished.
    #[serde(rename = "done")]
    Done,
    /// A print was cancelled.
    #[serde(rename = "cancelled")]
    Cancelled,
    /// A print was paused.
    #[serde(rename = "paused")]
    Paused,
    /// A print was resumed.
    #[serde(rename = "resumed")]
    Resumed,
    /// The printer is waiting for a filament change.
    #[serde(rename = "filament_change")]
    FilamentChange,
    /// A heater cooled down.
    #[serde(rename = "heater_cooled")]
    HeaterCooled,
    /// A heater reached its target.
    #[serde(rename = "heater_target")]
    HeaterTarget,
}

/// Obico sent a printer notification.
///
/// The two instants are optional for the same reason
/// `ObicoFailureAlertPayload`'s are, and are absent along with the rest of
/// the print's fields when the notification is about no print at all.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ObicoPrinterNotificationPayload {
    /// When the print ended, when Obico reported an instant for it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ended_at: Option<Timestamp>,
    /// The file being printed, when the notification is about one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file_name: Option<String>,
    /// Which notification it is.
    pub notification_type: ObicoNotificationType,
    /// Obico's own identifier for the print, when the notification is about
    /// one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub obico_print_id: Option<i64>,
    /// When the print started, when Obico reported an instant for it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub started_at: Option<Timestamp>,
}

/// An operator acknowledged an event.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OperatorAcknowledgementPayload {
    /// The event being acknowledged.
    pub acknowledged_event_id: EventId,
    /// What the operator asked for next.
    pub disposition: AcknowledgementDisposition,
}

/// Filament a tool fed after a filament change nobody has confirmed, held
/// until
/// somebody says which spool fed it.
///
/// A length rather than grams, because the grams follow the spool that takes
/// it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PendingCharge {
    /// The file's analysed length for the tool, in millimetres, when it had
    /// one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub analysed_length_mm: Option<f64>,
    /// The print segment the filament was fed in, which names the print and
    /// the tool that fed it.
    pub charge_key: PrintSegmentKey,
    /// How much was fed, in millimetres.
    pub length_mm: f64,
    /// How that length was worked out.
    pub method: ChargeMethod,
    /// Anything a reader needs to make sense of the figure.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    /// When it was held.
    pub pended_at: Timestamp,
    /// How far into the file the segment ran, when that was read.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub position: Option<FilePosition>,
}

/// One pending charge a spool command took.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PendingTaken {
    /// The key it is charged under.
    pub charge_key: ChargeKey,
    /// The print it was fed in.
    pub print_id: PrintId,
}

/// The supervisor looked in on an active print on its own schedule, with no
/// detector having said anything about it.
///
/// What a failure detector never alerts on — a progress that stopped moving,
/// a
/// heater whose target fell to nothing mid-print, a fan cut at a bridge, a
/// wall
/// going thin — is still on the machine and in the camera's frame, so every
/// active print is given one of these each interval and a turn on it. It
/// carries what the printer reported as it was taken; the frame the camera
/// gave
/// at the same moment, untagged by any detector, is this event's image.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PeriodicObservationPayload {
    /// How often these are taken, in whole seconds.
    pub interval_s: i64,
    /// The job the printer reported as the observation was taken, absent when
    /// it could not be read.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub job: Option<JobSnapshot>,
    /// The printer's state as the observation was taken, absent when it could
    /// not be read — which the history records as a port failure.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub printer: Option<PrinterSnapshot>,
}

/// The decision policy took on one request.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum PolicyDecision {
    /// The request may proceed.
    #[serde(rename = "accepted")]
    Accepted,
    /// The request may not, for this reason.
    #[serde(rename = "rejected")]
    Rejected(RejectionReason),
}

/// A port failed while one event was being handled.
///
/// The event is named rather than implied, so that a reader holding an
/// event's
/// identifier reaches every failure recorded while that event was being
/// handled. A failure recorded here is one the handling survived: the event
/// is
/// already in the history by the time any of these sites is reached, and the
/// loop goes on to handle the next event.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PortFailurePayload {
    /// What the port said about it, in the port's own words.
    pub detail: String,
    /// The event whose handling reached the failing call.
    pub event_id: EventId,
    /// Where it failed.
    pub site: PortFailureSite,
}

/// Where a port failed while an event was being handled.
///
/// A closed set of exactly the sites at which a failure has nowhere else to
/// be
/// recorded. The printer's action methods record theirs on the
/// `ActionRecord` the request minted, and a restoring
/// call records its own on the `Intervention` it was
/// expiring; those are not sites here, because a second record of them would
/// be
/// a second version of one fact.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PortFailureSite {
    /// Reading the printer's own state.
    #[serde(rename = "printer_snapshot")]
    PrinterSnapshot,
    /// Reading the job the printer reports it is running.
    #[serde(rename = "printer_job")]
    PrinterJob,
    /// Writing the image the event arrived with.
    #[serde(rename = "image_write")]
    ImageWrite,
    /// Running the supervision turn the event prompted.
    #[serde(rename = "supervision_turn")]
    SupervisionTurn,
    /// Taking a fresh frame from the camera, for a look at the print or for a
    /// periodic observation of it.
    #[serde(rename = "camera_look")]
    CameraLook,
    /// Telling the detector that paused the print its detection was handled.
    #[serde(rename = "detector_acknowledgement")]
    DetectorAcknowledgement,
}

/// How fresh the position a filament change charged up to is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PositionFreshness {
    /// Read from the job as the signal was handled: where the spool stopped.
    #[serde(rename = "read_at_signal")]
    ReadAtSignal,
    /// The last position recorded before the signal, the job reporting none
    /// as it was handled: the spool may have fed past it.
    #[serde(rename = "last_recorded")]
    LastRecorded,
}

/// What a filament check found for one print.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Preflight {
    /// When the check was made.
    pub checked_at: Timestamp,
    /// The file the print is of.
    pub file_name: String,
    /// What it found for each tool.
    pub tools: Vec<PreflightTool>,
    /// The worst of the tools' verdicts, in the order insufficient,
    /// unverified spool, no analysis, warned, overridden, unchecked, passed.
    pub verdict: PreflightVerdict,
}

/// What a filament check answers.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PreflightAnswer {
    /// What the check found, read now.
    pub preflight: Preflight,
}

/// The filament check before a start was made.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PreflightCheckedPayload {
    /// The start it was made for, when it was made for one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub action_id: Option<ActionId>,
    /// What the check found.
    pub preflight: Preflight,
}

/// What a print needs from one spool, in grams: both figures a comparison
/// with what the spool holds uses, or neither.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PreflightNeed {
    /// The margin asked for beyond that.
    pub buffer_g: f64,
    /// What the print needs from the spool, by the file's analysis and the
    /// spool's own diameter and density.
    pub required_g: f64,
}

/// What a check that refuses a start found for one tool.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "verdict")]
pub enum PreflightObjection {
    /// The spool holds less than the print needs and its buffer.
    #[serde(rename = "insufficient")]
    Insufficient {
        /// The spool's marks at the check, oldest first, so a spool both
        /// short
        /// and unverified says both.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        marks: Option<Vec<UnverifiedMark>>,
        /// What the print needs from it.
        need: PreflightNeed,
        /// What the spool holds, in grams.
        remaining_g: f64,
        /// The spool.
        spool: PreflightSpool,
    },
    /// The spool's figure is in doubt.
    #[serde(rename = "unverified_spool")]
    UnverifiedSpool {
        /// Every reason the spool's figure is in doubt, oldest first; never
        /// empty.
        // llmlint: ignore[invalid_states_unrepresentable] See suppressions.toml.
        marks: Vec<UnverifiedMark>,
        /// What the print needs from it, when the file's analysis says.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        need: Option<PreflightNeed>,
        /// What the spool holds, in grams.
        remaining_g: f64,
        /// The spool.
        spool: PreflightSpool,
    },
    /// The file has no analysis, so what the spool must hold is unknown.
    #[serde(rename = "no_analysis")]
    NoAnalysis {
        /// What the spool holds, in grams.
        remaining_g: f64,
        /// The spool.
        spool: PreflightSpool,
    },
}

/// The spool a check judged, named beside its identifier so a reader need
/// not look it up.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PreflightSpool {
    /// The spool's identifier.
    pub id: SpoolId,
    /// The spool's name.
    pub name: String,
}

/// What a filament check found for one tool.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PreflightTool {
    /// What the check found for it, with the evidence that finding rests on.
    pub result: PreflightToolResult,
    /// The tool, in the printer's own numbering.
    pub tool: i64,
}

/// What a filament check found for one tool, tagged by its verdict, each
/// verdict carrying exactly the evidence it rests on.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "verdict")]
pub enum PreflightToolResult {
    /// The spool holds what the print needs and its buffer, and its figure is
    /// not in doubt.
    #[serde(rename = "passed")]
    Passed {
        /// What the print needs from it.
        need: PreflightNeed,
        /// What the spool holds, in grams.
        remaining_g: f64,
        /// The spool.
        spool: PreflightSpool,
    },
    /// No tracked spool is loaded on the tool, so nothing was checked.
    #[serde(rename = "unchecked")]
    Unchecked,
    /// The spool holds less than the print needs and its buffer.
    #[serde(rename = "insufficient")]
    Insufficient {
        /// The spool's marks at the check, oldest first, so a spool both
        /// short
        /// and unverified says both.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        marks: Option<Vec<UnverifiedMark>>,
        /// What the print needs from it.
        need: PreflightNeed,
        /// What the spool holds, in grams.
        remaining_g: f64,
        /// The spool.
        spool: PreflightSpool,
    },
    /// The spool's figure is in doubt.
    #[serde(rename = "unverified_spool")]
    UnverifiedSpool {
        /// Every reason the spool's figure is in doubt, oldest first; never
        /// empty.
        // llmlint: ignore[invalid_states_unrepresentable] See suppressions.toml.
        marks: Vec<UnverifiedMark>,
        /// What the print needs from it, when the file's analysis says.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        need: Option<PreflightNeed>,
        /// What the spool holds, in grams.
        remaining_g: f64,
        /// The spool.
        spool: PreflightSpool,
    },
    /// `OctoPrint`'s analysis of the file had not appeared, so what the spool
    /// must hold is unknown.
    #[serde(rename = "no_analysis")]
    NoAnalysis {
        /// What the spool holds, in grams.
        remaining_g: f64,
        /// The spool.
        spool: PreflightSpool,
    },
    /// The start went ahead despite this objection, because an operator said
    /// so.
    #[serde(rename = "overridden")]
    Overridden {
        /// What the check objected to.
        objection: PreflightObjection,
    },
    /// The check is set to warn, and let the start go ahead despite this
    /// objection.
    #[serde(rename = "warned")]
    Warned {
        /// What the check objected to.
        objection: PreflightObjection,
    },
}

/// What a filament check found, for one tool or for a whole print.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PreflightVerdict {
    /// The spool holds what the print needs and its buffer.
    #[serde(rename = "passed")]
    Passed,
    /// No tracked spool is loaded on the tool, so nothing was checked.
    #[serde(rename = "unchecked")]
    Unchecked,
    /// The spool holds less than the print needs and its buffer.
    #[serde(rename = "insufficient")]
    Insufficient,
    /// The spool's figure is in doubt.
    #[serde(rename = "unverified_spool")]
    UnverifiedSpool,
    /// `OctoPrint`'s analysis of the file had still not appeared when the
    /// start's wait for it elapsed, or has not appeared yet when the check is
    /// only read.
    #[serde(rename = "no_analysis")]
    NoAnalysis,
    /// The start went ahead despite the check, because the actor said so.
    #[serde(rename = "overridden")]
    Overridden,
    /// The check is set to warn, and let an insufficient, unverified or
    /// unanalysed start go ahead.
    #[serde(rename = "warned")]
    Warned,
}

/// The whole vocabulary an actor may ask for, and there is no other.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "action")]
pub enum PrintAction {
    /// Pause the print.
    #[serde(rename = "pause")]
    Pause {
        /// Who is asking.
        actor: Actor,
        /// Why the actor is asking for this.
        reason: String,
    },
    /// Resume the print.
    #[serde(rename = "resume")]
    Resume {
        /// Who is asking.
        actor: Actor,
        /// Why the actor is asking for this.
        reason: String,
    },
    /// Cancel the print.
    #[serde(rename = "cancel")]
    Cancel {
        /// Who is asking.
        actor: Actor,
        /// Why the actor is asking for this.
        reason: String,
    },
    /// Start a print of a named file, with a manifest.
    #[serde(rename = "start_print")]
    StartPrint {
        /// Who is asking.
        actor: Actor,
        /// The file to print, validated as a name a file API can be asked
        /// for.
        file_name: FileName,
        /// The manifest this print is bounded by.
        manifest: JobManifest,
        /// Start despite an insufficient or unverified spool, or a file
        /// `OctoPrint` has not analysed; the start's own reason is the
        /// override's reason.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        override_filament_check: Option<bool>,
        /// Why the actor is asking for this.
        reason: String,
    },
    /// Set the feedrate factor, where one means one hundred percent.
    #[serde(rename = "set_feedrate_factor")]
    SetFeedrateFactor {
        /// Who is asking.
        actor: Actor,
        /// How long the change stands for, in whole seconds.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        duration_s: Option<i64>,
        /// The multiplier asked for.
        factor: f64,
        /// Why the actor is asking for this.
        reason: String,
    },
    /// Set the flowrate factor, where one means one hundred percent.
    #[serde(rename = "set_flowrate_factor")]
    SetFlowrateFactor {
        /// Who is asking.
        actor: Actor,
        /// How long the change stands for, in whole seconds.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        duration_s: Option<i64>,
        /// The multiplier asked for.
        factor: f64,
        /// Why the actor is asking for this.
        reason: String,
    },
    /// Set one tool's target temperature.
    #[serde(rename = "set_tool_target_c")]
    SetToolTargetC {
        /// Who is asking.
        actor: Actor,
        /// How long the change stands for, in whole seconds.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        duration_s: Option<i64>,
        /// Why the actor is asking for this.
        reason: String,
        /// The target temperature asked for, in degrees Celsius.
        target_c: f64,
        /// The tool, in the printer's own numbering.
        tool: i64,
    },
    /// Set the bed's target temperature.
    #[serde(rename = "set_bed_target_c")]
    SetBedTargetC {
        /// Who is asking.
        actor: Actor,
        /// How long the change stands for, in whole seconds.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        duration_s: Option<i64>,
        /// Why the actor is asking for this.
        reason: String,
        /// The target temperature asked for, in degrees Celsius.
        target_c: f64,
    },
    /// Set the part-cooling fan percentage.
    #[serde(rename = "set_fan_percent")]
    SetFanPercent {
        /// Who is asking.
        actor: Actor,
        /// How long the change stands for, in whole seconds.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        duration_s: Option<i64>,
        /// The percentage asked for.
        percent: f64,
        /// Why the actor is asking for this.
        reason: String,
    },
    /// Acknowledge a failure event, with a disposition.
    #[serde(rename = "acknowledge_failure")]
    AcknowledgeFailure {
        /// Who is asking.
        actor: Actor,
        /// What to do next.
        disposition: AcknowledgementDisposition,
        /// The event being acknowledged.
        event_id: EventId,
        /// Why the actor is asking for this.
        reason: String,
    },
}

/// Everything a supervision turn is given about one print.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PrintContext {
    /// The limits in force, so that the agent can see them before it asks.
    pub bounds: EffectiveBounds,
    /// The interventions still active.
    pub interventions: Vec<Intervention>,
    /// The job, when a snapshot could be taken.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub job: Option<JobSnapshot>,
    /// The most recent image, when there is one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub latest_image: Option<ImageRef>,
    /// The manifest, when the print has one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub manifest: Option<JobManifest>,
    /// The print itself.
    pub print: PrintRecord,
    /// The printer, when a snapshot could be taken.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub printer: Option<PrinterSnapshot>,
    /// A bounded list of this print's events, newest first.
    pub recent_events: Vec<EventRecord>,
}

/// One print's end, as its `print_ended` event stored it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PrintEnded {
    /// The `print_ended` event.
    pub event_id: EventId,
    /// How the print ended.
    pub outcome: PrintOutcome,
    /// When that event was received.
    pub received_at: Timestamp,
}

/// A print ended.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PrintEndedPayload {
    /// How far into its file it last read, when that was read.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_position: Option<FilePosition>,
    /// How it ended.
    pub outcome: PrintOutcome,
    /// Why it ended, in the words the end was recorded with.
    pub reason: String,
    /// The state the printer was in as it ended.
    pub state: PrinterState,
}

/// A lowercase hyphenated version 7 UUID identifying one print.
pub type PrintId = String;

/// How a print ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PrintOutcome {
    /// It ran to its end.
    #[serde(rename = "completed")]
    Completed,
    /// Somebody cancelled it.
    #[serde(rename = "cancelled")]
    Cancelled,
    /// It stopped on an error.
    #[serde(rename = "failed")]
    Failed,
}

/// One print, and the record supervision keys from.
///
/// The provider's own print id is carried beside this record's identifier
/// rather than as it, because a print may be observed before the provider
/// that reports it has one.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PrintRecord {
    /// Why it ended, if it has.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end_reason: Option<String>,
    /// When it ended, if it has.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ended_at: Option<Timestamp>,
    /// The file being printed, as the source reported it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file_name: Option<String>,
    /// This print's identifier, minted by the store.
    pub id: PrintId,
    /// The longest running time, in whole seconds, the printer reported for
    /// this print's job at a read that found it printing rather than paused.
    ///
    /// The time a job has spent printing only grows, pause or no pause, so a
    /// job of this print's file reporting less — by more than
    /// `listing::JOB_IDENTITY_TOLERANCE_S` — is a later job. Absent until a
    /// read finds the job printing.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub job_print_time_s: Option<i64>,
    /// When the printer's job this print records began, as the printer's own
    /// running time put it at the latest read that found the job running or
    /// paused: the instant of that read, less the running time it reported.
    ///
    /// `OctoPrint` counts a pause into the running time until the job resumes
    /// and then takes the pause back out, so a pause moves this later: a read
    /// putting it further than `listing::JOB_IDENTITY_TOLERANCE_S` from the
    /// one
    /// recorded resets it, rather than it being fixed once. Absent when no
    /// read has
    /// found this print's job reporting a running time — a print opened by an
    /// alert or a start before any read, and every print recorded before this
    /// was.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub job_started_at: Option<Timestamp>,
    /// Every manifest range this print narrowed to the envelope's.
    pub narrowings: Vec<ManifestNarrowing>,
    /// When the print was opened.
    pub opened_at: Timestamp,
    /// The provider's own identifier for the print, whichever provider
    /// reported it, when one has.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider_print_id: Option<i64>,
    /// The state the print is in.
    pub state: PrinterState,
}

/// One segment of a print this system watched, on one tool: the key of a
/// `ChargeKey::Print` debit, and the only key filament held pending can be
/// under.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PrintSegmentKey {
    /// The print.
    pub print_id: PrintId,
    /// Which segment, numbered as `ChargeKey::Print` numbers it.
    pub segment: i64,
    /// The tool, in the printer's own numbering.
    pub tool: i64,
}

/// A print started.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PrintStartedPayload {
    /// The file being printed, when it is known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file_name: Option<String>,
    /// The spool loaded on each tool as it started.
    pub loaded: Vec<LoadedSpool>,
    /// The filament check made before it started, when one was.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preflight: Option<Preflight>,
    /// The action that started it; absent when the print was observed rather
    /// than started through this system.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub started_by: Option<ActionId>,
}

/// A print that was already open when spool tracking was installed: it is
/// never charged, and this says why it carries no charge.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PrintUntrackedPayload {
    /// Why the print carries no charge.
    pub reason: String,
}

/// A printer, as a source reported it at one instant.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PrinterSnapshot {
    /// The bed heater, when the printer reports one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bed: Option<HeaterSnapshot>,
    /// The chamber heater, when the printer reports one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chamber: Option<HeaterSnapshot>,
    /// The state the printer is in.
    pub connection: PrinterState,
    /// The part-cooling fan, in percent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fan_percent: Option<Reported>,
    /// The feedrate multiplier, where one means one hundred percent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub feedrate_factor: Option<Reported>,
    /// The flowrate multiplier, where one means one hundred percent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub flowrate_factor: Option<Reported>,
    /// The instant this observation was taken.
    pub observed_at: Timestamp,
    /// The tool heaters, indexed by tool number.
    pub tools: Vec<HeaterSnapshot>,
}

/// The state a source reports a printer or a print to be in.
///
/// The `unknown` arm exists so that a state nobody anticipated is recorded
/// carrying the source's own word for it rather than lost.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum PrinterState {
    /// Connected and idle.
    #[serde(rename = "operational")]
    Operational,
    /// Printing, but paused.
    #[serde(rename = "paused")]
    Paused,
    /// Printing.
    #[serde(rename = "printing")]
    Printing,
    /// Cancelling a print.
    #[serde(rename = "cancelling")]
    Cancelling,
    /// In an error state.
    #[serde(rename = "error")]
    Error,
    /// Not reachable.
    #[serde(rename = "offline")]
    Offline,
    /// A state this vocabulary does not name, in the source's own word for
    /// it.
    #[serde(rename = "unknown")]
    Unknown(String),
}

/// What the prints read answers: every print, and the one the printer is
/// running.
///
/// An open print's recorded `state` is the state it was opened in, which is
/// `printing` whether or not the machine is paused now; what the machine is
/// doing is the status read's answer.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PrintsAnswer {
    /// The print the printer's current job belongs to, present exactly when
    /// the
    /// printer reports a job it is printing or has paused. Absent when the
    /// printer could not be read.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub active: Option<PrintId>,
    /// Every print this server holds, ended or not, most recently opened
    /// first.
    pub prints: Vec<PrintRecord>,
}

/// An inclusive pair of 64-bit floats.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Range {
    /// The highest value the range admits, inclusive.
    pub max: f64,
    /// The lowest value the range admits, inclusive.
    pub min: f64,
}

/// Bytes exactly as received, base64-encoded.
pub type RawBytes = String;

/// What became of the prints a file's new tally generation counts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum RebaselineDisposition {
    /// They were accounted as prints this system never saw.
    #[serde(rename = "accounted")]
    Accounted,
    /// It could not be told which of them this system already settled, so the
    /// loaded spool was marked unverified rather than charged on a guess.
    #[serde(rename = "unverified")]
    Unverified,
}

/// Why a request was refused.
///
/// Each rejection is a distinct variant, so a consumer distinguishes them by
/// matching rather than by reading a message.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum RejectionReason {
    /// The value asked for is outside the range allowed for that adjustable.
    #[serde(rename = "out_of_bounds")]
    OutOfBounds {
        /// The adjustable that was asked for.
        adjustable: Adjustable,
        /// The range that was allowed.
        allowed: Range,
        /// The value that was asked for.
        requested: f64,
    },
    /// This actor class may not request this action at all.
    #[serde(rename = "actor_may_not_request")]
    ActorMayNotRequest {
        /// The action they asked for.
        action: ActionKind,
        /// The class of the actor that asked.
        actor_class: ActorClass,
    },
    /// There is no active print to act on.
    #[serde(rename = "no_active_print")]
    NoActivePrint,
    /// The printer is not in a state this action is valid from.
    #[serde(rename = "invalid_from_state")]
    InvalidFromState {
        /// The state the printer is in.
        state: PrinterState,
    },
    /// The agent's minimum interval has not elapsed.
    #[serde(rename = "min_interval_not_elapsed")]
    MinIntervalNotElapsed {
        /// The minimum interval, in whole seconds.
        interval_s: i64,
        /// How long it has been since the last agent action, in whole
        /// seconds.
        since_last_s: i64,
    },
    /// The adjustable is not one this printer has.
    #[serde(rename = "unsupported_adjustable")]
    UnsupportedAdjustable {
        /// The adjustable this printer cannot express.
        adjustable: Adjustable,
    },
    /// A start was refused because the spool on one tool holds less than the
    /// print needs and its buffer.
    #[serde(rename = "insufficient_filament")]
    InsufficientFilament {
        /// The margin asked for beyond that, in grams.
        buffer_g: f64,
        /// What the spool holds, in grams.
        remaining_g: f64,
        /// What the print needs from it, in grams.
        required_g: f64,
        /// The spool loaded on it.
        spool_id: SpoolId,
        /// That spool's name.
        spool_name: String,
        /// The tool whose spool is short.
        tool: i64,
        /// The spool's oldest mark, when the short spool is also unverified.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        unverified: Option<UnverifiedReason>,
    },
    /// A start was refused because the spool on one tool is unverified.
    #[serde(rename = "unverified_spool")]
    UnverifiedSpool {
        /// The spool's oldest mark.
        reason: UnverifiedReason,
        /// The spool loaded on it.
        spool_id: SpoolId,
        /// That spool's name.
        spool_name: String,
        /// The tool whose spool is unverified.
        tool: i64,
    },
    /// A start was refused because `OctoPrint`'s analysis of the file had not
    /// appeared when the start's wait for it elapsed.
    #[serde(rename = "analysis_unavailable")]
    AnalysisUnavailable {
        /// The file that has no analysis.
        file_name: String,
        /// How long the start waited for one, in whole seconds.
        waited_s: i64,
    },
    /// A spool command could not be carried out.
    #[serde(rename = "spool_refused")]
    SpoolRefused {
        /// Why, in a form a client acts on without reading `message`.
        cause: SpoolRefusalCause,
        /// Why, in a sentence naming what to do instead, for a person.
        message: String,
    },
}

/// A value as a source reported it, flagged when it is outside the
/// plausibility range this crate declares for its field.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Reported {
    /// One shape of the contracts, which say nothing more about it.
    pub out_of_range: bool,
    /// One shape of the contracts, which say nothing more about it.
    pub value: f64,
}

/// The position a filament change charged up to, and how fresh it is.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SignalPosition {
    /// Whether it was read when the signal was handled, or is the last one
    /// recorded before it.
    pub freshness: PositionFreshness,
    /// The position.
    pub position: FilePosition,
}

/// A spool's remaining figure was corrected.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SpoolAdjustedPayload {
    /// Who corrected it.
    pub actor: Actor,
    /// Every mark the correction cleared.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cleared_marks: Option<Vec<ClearedMark>>,
    /// The scale reading the figure was worked out from, when it was given as
    /// one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub gross_g: Option<f64>,
    /// Why.
    pub reason: String,
    /// Its figure after, in grams.
    pub remaining_after_g: f64,
    /// Its figure before, in grams, after any pending charge it took.
    pub remaining_before_g: f64,
    /// The spool corrected.
    pub spool_id: SpoolId,
    /// The pending charges the correction took first, each also its own
    /// `filament_consumed` event under its key.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub took_pending: Option<Vec<PendingTaken>>,
}

/// What one spool's read answers: the spool, and the newest of the printer's
/// own events that name it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SpoolAnswer {
    /// The newest timeline events naming it, newest first.
    pub recent: Vec<EventRecord>,
    /// The spool, retired or not.
    pub spool: SpoolRecord,
}

/// The whole vocabulary of the spool ledger, and there is no other.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "command")]
pub enum SpoolCommand {
    /// Register a spool.
    #[serde(rename = "register_spool")]
    RegisterSpool {
        /// Who is asking.
        actor: Actor,
        /// The filament's colour.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        color: Option<String>,
        /// The material's density, in grams per cubic centimetre; the known
        /// density of the material when absent, and a material with none
        /// known
        /// is refused.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        density_g_cm3: Option<f64>,
        /// The filament's diameter, in millimetres; 1.75 when absent.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        diameter_mm: Option<f64>,
        /// The net filament on the spool when full, in grams.
        initial_g: f64,
        /// The material, such as `PLA`.
        material: String,
        /// The operator's own label for it.
        name: String,
        /// Why the actor is asking for this.
        reason: String,
        /// The filament on it now, in grams; the full figure when absent.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        remaining_g: Option<f64>,
        /// The empty spool's own weight, in grams.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        tare_g: Option<f64>,
    },
    /// Load a spool onto a tool.
    ///
    /// Onto an occupied tool it is a swap, and the spool there is unloaded in
    /// the same write. Naming the spool already on the tool confirms it was
    /// never swapped, which is accepted only while that tool holds a pending
    /// charge or that spool holds a filament-change mark.
    #[serde(rename = "load_spool")]
    LoadSpool {
        /// Who is asking.
        actor: Actor,
        /// Why the actor is asking for this.
        reason: String,
        /// The spool to load.
        spool_id: SpoolId,
        /// The tool, in the printer's own numbering.
        tool: i64,
    },
    /// Unload a spool from its tool.
    #[serde(rename = "unload_spool")]
    UnloadSpool {
        /// Who is asking.
        actor: Actor,
        /// Why the actor is asking for this.
        reason: String,
        /// The spool to unload.
        spool_id: SpoolId,
    },
    /// Correct a spool's remaining figure, from exactly one of the two; a
    /// command naming both or neither is refused as `spool_refused`.
    #[serde(rename = "adjust_spool")]
    AdjustSpool {
        /// Who is asking.
        actor: Actor,
        /// A scale reading of the spool, in grams, which needs its tare.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        gross_g: Option<f64>,
        /// Why the actor is asking for this.
        reason: String,
        /// The filament left, in grams.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        remaining_g: Option<f64>,
        /// The spool to correct.
        spool_id: SpoolId,
    },
    /// Retire a spool, after which it refuses every command.
    #[serde(rename = "retire_spool")]
    RetireSpool {
        /// Who is asking.
        actor: Actor,
        /// Why the actor is asking for this.
        reason: String,
        /// The spool to retire.
        spool_id: SpoolId,
    },
}

/// What a spool command answers, accepted or refused.
///
/// A refusal is the same shape and deliberately so: the decision carries the
/// grant or the ledger's own reason, and the events are the record the
/// refusal
/// wrote.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SpoolCommandAnswer {
    /// The decision taken on the command.
    pub decision: PolicyDecision,
    /// Every event it wrote, in the order they were written.
    pub events: Vec<EventRecord>,
    /// The spool it was about, as the command left it, when there is one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub spool: Option<SpoolRecord>,
}

/// A spool command was refused.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SpoolCommandRejectedPayload {
    /// The command, as it was asked for.
    pub command: SpoolCommand,
    /// The whole decision, carrying which refusal it was.
    pub decision: PolicyDecision,
}

/// One field of a spool command, as the command names it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SpoolField {
    /// The operator's own label for the spool.
    #[serde(rename = "name")]
    Name,
    /// The material, such as `PLA`.
    #[serde(rename = "material")]
    Material,
    /// The filament's diameter, in millimetres.
    #[serde(rename = "diameter_mm")]
    DiameterMm,
    /// The material's density, in grams per cubic centimetre.
    #[serde(rename = "density_g_cm3")]
    DensityGCm3,
    /// The net filament on the spool when full, in grams.
    #[serde(rename = "initial_g")]
    InitialG,
    /// The filament on the spool now, in grams.
    #[serde(rename = "remaining_g")]
    RemainingG,
    /// The empty spool's own weight, in grams.
    #[serde(rename = "tare_g")]
    TareG,
    /// A scale reading of the spool, in grams.
    #[serde(rename = "gross_g")]
    GrossG,
}

/// A lowercase hyphenated version 7 UUID identifying one registered spool.
pub type SpoolId = String;

/// Where a spool is in its life.
///
/// One state rather than a loaded tool beside a retirement instant, because a
/// retired spool is on no tool: retiring a loaded spool takes it off.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "state")]
pub enum SpoolLifecycle {
    /// Registered, and loaded on no tool.
    #[serde(rename = "shelved")]
    Shelved,
    /// Loaded on one tool.
    #[serde(rename = "loaded")]
    Loaded {
        /// The tool, in the printer's own numbering.
        tool: i64,
    },
    /// Retired: it takes no further command, and is on no tool.
    #[serde(rename = "retired")]
    Retired {
        /// When it was retired.
        at: Timestamp,
    },
}

/// A spool was loaded onto a tool, or confirmed as never having left it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SpoolLoadedPayload {
    /// Who loaded it.
    pub actor: Actor,
    /// Every mark the load cleared, on either spool.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cleared_marks: Option<Vec<ClearedMark>>,
    /// Why.
    pub reason: String,
    /// The spool the load swapped off the tool, when it was occupied.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub replaced: Option<SpoolId>,
    /// The spool loaded.
    pub spool_id: SpoolId,
    /// The pending charges the load took, each also its own
    /// `filament_consumed` event under its key.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub took_pending: Option<Vec<PendingTaken>>,
    /// The tool, in the printer's own numbering.
    pub tool: i64,
}

/// One spool the operator registered, and what is known of it now.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SpoolRecord {
    /// The filament's colour, when the operator gave one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub color: Option<String>,
    /// The material's density, in grams per cubic centimetre; above zero.
    pub density_g_cm3: f64,
    /// The filament's diameter, in millimetres; above zero.
    pub diameter_mm: f64,
    /// This spool's identifier, minted when it was registered.
    pub id: SpoolId,
    /// The net filament on the spool when it was full, in grams; above zero.
    pub initial_g: f64,
    /// Where the spool is in its life: on the shelf, loaded on a tool, or
    /// retired — and never both of the last two.
    pub lifecycle: SpoolLifecycle,
    /// The material, as given and trimmed, such as `PLA`; never empty.
    pub material: String,
    /// The operator's own label for the spool; never empty.
    pub name: String,
    /// When the spool was registered.
    pub registered_at: Timestamp,
    /// The filament left, in grams.
    ///
    /// Always the initial figure less every charge plus every correction. A
    /// charge is never refused or clamped, so this may go below zero.
    pub remaining_g: f64,
    /// The empty spool's own weight, in grams, when the operator gave it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tare_g: Option<f64>,
    /// How far the remaining figure can be trusted.
    pub trust: SpoolTrust,
    /// When anything about the spool last changed.
    pub updated_at: Timestamp,
}

/// Why the spool ledger refused a command, each cause carrying what a client
/// needs to choose the next valid request.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "cause")]
pub enum SpoolRefusalCause {
    /// No spool was ever registered under this identifier.
    #[serde(rename = "unknown_spool")]
    UnknownSpool {
        /// The identifier the command named.
        spool_id: SpoolId,
    },
    /// The spool is retired, and takes no further command.
    #[serde(rename = "retired_spool")]
    RetiredSpool {
        /// The retired spool.
        spool_id: SpoolId,
    },
    /// The spool named is already on the tool, and nothing is pending there
    /// or
    /// marked on it for a load to confirm.
    #[serde(rename = "nothing_to_confirm")]
    NothingToConfirm {
        /// The tool the spool is already on.
        tool: i64,
    },
    /// A figure the command gave is not one the field can hold: not a number,
    /// or out of the field's range.
    #[serde(rename = "invalid_adjustment_figure")]
    InvalidAdjustmentFigure {
        /// The field the figure was given for.
        field: SpoolField,
        /// The figure given; always a number, because a figure JSON cannot
        /// carry is refused as it would be written rather than written as
        /// `null`.
        value: f64,
    },
    /// A scale reading was given for a spool with no tare, so it cannot be
    /// turned into a figure.
    #[serde(rename = "tare_required")]
    TareRequired {
        /// The spool with no tare.
        spool_id: SpoolId,
    },
    /// The material has no known density, so the command needs one.
    #[serde(rename = "density_required")]
    DensityRequired {
        /// The material, as given and trimmed.
        material: String,
        /// The spool, when the command was about one that exists; absent for
        /// a registration.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        spool_id: Option<SpoolId>,
    },
    /// A field the command needs was empty or absent.
    #[serde(rename = "missing_field")]
    MissingField {
        /// The field; for a correction naming neither figure, `remaining_g`,
        /// which `gross_g` may stand in for.
        field: SpoolField,
    },
    /// The command gave fields only one of which it may carry.
    #[serde(rename = "conflicting_fields")]
    ConflictingFields {
        /// Every field given that conflicts, in the command's own order.
        fields: Vec<SpoolField>,
    },
    /// The command named a tool the printer cannot have.
    #[serde(rename = "unknown_tool")]
    UnknownTool {
        /// The tool named.
        tool: i64,
    },
    /// The spool is loaded on no tool, so there is nothing to unload.
    #[serde(rename = "not_loaded")]
    NotLoaded {
        /// The spool.
        spool_id: SpoolId,
    },
    /// The ledger refused the write the command made, because the spools
    /// changed under it; reading them again shows how.
    #[serde(rename = "ledger_refused")]
    LedgerRefused,
}

/// A spool was registered.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SpoolRegisteredPayload {
    /// Who registered it.
    pub actor: Actor,
    /// Why.
    pub reason: String,
    /// The spool, as it was registered.
    pub spool: SpoolRecord,
}

/// A spool was retired.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SpoolRetiredPayload {
    /// Who retired it.
    pub actor: Actor,
    /// Why.
    pub reason: String,
    /// Its figure as it was retired, in grams.
    pub remaining_g: f64,
    /// The spool retired.
    pub spool_id: SpoolId,
}

/// How far a spool's remaining figure can be trusted.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "state")]
pub enum SpoolTrust {
    /// Every charge against the spool was taken exactly.
    #[serde(rename = "verified")]
    Verified,
    /// At least one thing happened that could not be charged exactly.
    #[serde(rename = "unverified")]
    Unverified {
        /// Every reason the figure is in doubt, oldest first, at most one per
        /// distinct reason; never empty.
        // llmlint: ignore[invalid_states_unrepresentable] See suppressions.toml.
        marks: Vec<UnverifiedMark>,
    },
}

/// A spool was unloaded from its tool.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SpoolUnloadedPayload {
    /// Who unloaded it.
    pub actor: Actor,
    /// Why.
    pub reason: String,
    /// The spool unloaded.
    pub spool_id: SpoolId,
    /// The tool it left.
    pub tool: i64,
}

/// A spool was marked as one whose figure is in doubt.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SpoolUnverifiedPayload {
    /// Why its figure is in doubt.
    pub reason: UnverifiedReason,
    /// The spool marked.
    pub spool_id: SpoolId,
}

/// What the spools read answers.
///
/// `at_a_glance` is one line per spool, in the order `spools` lists them,
/// composed here so that what is left on each spool is the first thing a
/// reader of either rendering meets rather than a figure inside a whole
/// record. Its name is what puts it first: both renderings walk an answer's
/// fields in name order, ahead of `pending` and `spools`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SpoolsAnswer {
    /// One line per spool in `spools`, in the same order.
    pub at_a_glance: Vec<String>,
    /// Every charge held after a filament change nobody has confirmed, oldest
    /// first: what the next spool loaded on that tool is charged.
    pub pending: Vec<PendingCharge>,
    /// Every spool, retired ones only when asked for, most recently
    /// registered
    /// first.
    pub spools: Vec<SpoolRecord>,
}

/// What one restart put back the way it found it.
///
/// A supervisor that has been restarted adopts whatever the store holds
/// rather
/// than starting empty, and each of these is one of those adoptions. They are
/// recorded rather than merely done, because a print that carried on across a
/// restart and one that was started again look identical afterwards unless
/// the
/// history says which happened.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum StartupOutcome {
    /// A print left open was adopted as the print this supervisor is
    /// watching.
    #[serde(rename = "print_adopted")]
    PrintAdopted,
    /// A session left open was resumed rather than replaced.
    #[serde(rename = "session_resumed")]
    SessionResumed {
        /// The session's own name in the harness.
        session_name: String,
    },
    /// An intervention already past its expiry was expired on start.
    #[serde(rename = "intervention_expired")]
    InterventionExpired {
        /// What it had changed.
        adjustable: Adjustable,
        /// The intervention that had outlived its bound.
        intervention_id: InterventionId,
        /// What became of putting the prior value back.
        outcome: InterventionOutcome,
    },
}

/// A supervisor reconciled one thing the store held when it started.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StartupReconciliationPayload {
    /// What was reconciled.
    pub outcome: StartupOutcome,
    /// The print it is about.
    pub print_id: PrintId,
}

/// What a status read answers.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StatusAnswer {
    /// The bounded interventions still in force.
    pub interventions: Vec<Intervention>,
    /// The job, when a snapshot could be taken.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub job: Option<JobSnapshot>,
    /// The print.
    pub print: PrintRecord,
    /// The printer, when a snapshot could be taken.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub printer: Option<PrinterSnapshot>,
    /// The supervision session watching it, when one is.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session: Option<SupervisionSession>,
}

/// The supervision session keyed to one print.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SupervisionSession {
    /// Why it was closed, if it was.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub close_reason: Option<String>,
    /// When the session was closed, if it was.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub closed_at: Option<Timestamp>,
    /// When the session was opened.
    pub created_at: Timestamp,
    /// The identity the harness ran the session under.
    pub harness_identity: String,
    /// When the last turn ran.
    pub last_turn_at: Timestamp,
    /// The print this session watches.
    pub print_id: PrintId,
    /// The session's own name in the harness.
    pub session_name: String,
}

/// A supervision session was closed.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SupervisionSessionClosedPayload {
    /// Why it was closed.
    pub close_reason: String,
    /// The session's own name in the harness.
    pub session_name: String,
}

/// A supervision session was opened.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SupervisionSessionOpenedPayload {
    /// The identity the harness ran it under.
    pub harness_identity: String,
    /// The session's own name in the harness.
    pub session_name: String,
}

/// What a printer history read answers: one page of the printer's own events.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TimelineAnswer {
    /// The events, newest first.
    pub events: Vec<EventRecord>,
    /// The cursor for the following, older page, given as `before`; absent
    /// when there is none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next: Option<EventId>,
}

/// An instant in UTC, as an RFC 3339 string with a zero offset.
pub type Timestamp = String;

/// The filament one tool feeds, as a length and, when it is known, a volume.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolFilament {
    /// The length of filament fed, in millimetres.
    pub length_mm: f64,
    /// The tool, in the printer's own numbering.
    pub tool: i64,
    /// The volume of filament fed, in cubic centimetres, when the source
    /// reported one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub volume_cm3: Option<f64>,
}

/// A print this system never saw was found in the printer's own tally.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UnaccountedPrintPayload {
    /// Whether it was charged against a spool.
    pub charged: bool,
    /// The file that was printed.
    pub file_name: String,
    /// When it was printed, when the printer says.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub printed_at: Option<Timestamp>,
    /// Whether it completed.
    pub success: bool,
}

/// One reason a spool's figure is in doubt, and since when.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UnverifiedMark {
    /// Why the figure is in doubt.
    pub reason: UnverifiedReason,
    /// When the spool was marked for it.
    pub since: Timestamp,
}

/// Why a spool's figure is in doubt.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "reason")]
pub enum UnverifiedReason {
    /// A print ran on the spool's tool and nothing could be charged, because
    /// the file had no analysis — an SD-card file, for one.
    #[serde(rename = "uncharged_print")]
    UnchargedPrint {
        /// The print nothing could be charged for.
        print_id: PrintId,
    },
    /// A print this system never saw ran and did not complete.
    #[serde(rename = "unaccounted_print")]
    UnaccountedPrint {
        /// The file that was printed.
        file_name: String,
        /// When it was printed.
        printed_at: Timestamp,
    },
    /// A filament change was signalled and nobody has said which spool is now
    /// loaded. The spool was charged up to a position read when the signal
    /// was
    /// handled.
    #[serde(rename = "filament_change_unconfirmed")]
    FilamentChangeUnconfirmed {
        /// The print the change was signalled during.
        print_id: PrintId,
    },
    /// A filament change was signalled, nobody has said which spool is now
    /// loaded, and no fresh position could be read at the signal: the spool
    /// was
    /// charged only up to the last recorded position, so its figure may be
    /// overstated.
    #[serde(rename = "filament_change_unconfirmed_position")]
    FilamentChangeUnconfirmedPosition {
        /// The print the change was signalled during.
        print_id: PrintId,
    },
    /// A file's print tally was reset, and it cannot be told which of the
    /// prints since the re-upload were already settled.
    #[serde(rename = "tally_reset")]
    TallyReset {
        /// The file whose tally was reset.
        file_name: String,
        /// Where the file lives, in the printer's own vocabulary.
        origin: String,
    },
}

/// One payload type declared under a kind name, by the domain that owns it.
///
/// The table from kind name to payload type, as the server declares it: every
/// kind below has exactly one implementation here, and a kind this client
/// does not know flows through `EventRecord` untouched.
pub trait EventPayloadKind: serde::de::DeserializeOwned {
    /// The name this payload's events are written down under.
    const KIND: &'static str;
}

impl EventPayloadKind for ActionExecutedPayload {
    const KIND: &'static str = "action_executed";
}

impl EventPayloadKind for ActionRejectedPayload {
    const KIND: &'static str = "action_rejected";
}

impl EventPayloadKind for ActionRequestedPayload {
    const KIND: &'static str = "action_requested";
}

impl EventPayloadKind for AgentAssessmentPayload {
    const KIND: &'static str = "agent_assessment";
}

impl EventPayloadKind for CameraLookPayload {
    const KIND: &'static str = "camera_look";
}

impl EventPayloadKind for ChargePendedPayload {
    const KIND: &'static str = "charge_pended";
}

impl EventPayloadKind for FilamentChangeSignalledPayload {
    const KIND: &'static str = "filament_change_signalled";
}

impl EventPayloadKind for FilamentConsumedPayload {
    const KIND: &'static str = "filament_consumed";
}

impl EventPayloadKind for FileTallyRebaselinedPayload {
    const KIND: &'static str = "file_tally_rebaselined";
}

impl EventPayloadKind for InterventionExpiredPayload {
    const KIND: &'static str = "intervention_expired";
}

impl EventPayloadKind for MalformedExternalEventPayload {
    const KIND: &'static str = "malformed_external_event";
}

impl EventPayloadKind for ObicoFailureAlertPayload {
    const KIND: &'static str = "obico_failure_alert";
}

impl EventPayloadKind for ObicoPrinterNotificationPayload {
    const KIND: &'static str = "obico_printer_notification";
}

impl EventPayloadKind for OperatorAcknowledgementPayload {
    const KIND: &'static str = "operator_acknowledgement";
}

impl EventPayloadKind for PeriodicObservationPayload {
    const KIND: &'static str = "periodic_observation";
}

impl EventPayloadKind for PortFailurePayload {
    const KIND: &'static str = "port_failure";
}

impl EventPayloadKind for PreflightCheckedPayload {
    const KIND: &'static str = "preflight_checked";
}

impl EventPayloadKind for PrintEndedPayload {
    const KIND: &'static str = "print_ended";
}

impl EventPayloadKind for PrintStartedPayload {
    const KIND: &'static str = "print_started";
}

impl EventPayloadKind for PrintUntrackedPayload {
    const KIND: &'static str = "print_untracked";
}

impl EventPayloadKind for SpoolAdjustedPayload {
    const KIND: &'static str = "spool_adjusted";
}

impl EventPayloadKind for SpoolCommandRejectedPayload {
    const KIND: &'static str = "spool_command_rejected";
}

impl EventPayloadKind for SpoolLoadedPayload {
    const KIND: &'static str = "spool_loaded";
}

impl EventPayloadKind for SpoolRegisteredPayload {
    const KIND: &'static str = "spool_registered";
}

impl EventPayloadKind for SpoolRetiredPayload {
    const KIND: &'static str = "spool_retired";
}

impl EventPayloadKind for SpoolUnloadedPayload {
    const KIND: &'static str = "spool_unloaded";
}

impl EventPayloadKind for SpoolUnverifiedPayload {
    const KIND: &'static str = "spool_unverified";
}

impl EventPayloadKind for StartupReconciliationPayload {
    const KIND: &'static str = "startup_reconciliation";
}

impl EventPayloadKind for SupervisionSessionClosedPayload {
    const KIND: &'static str = "supervision_session_closed";
}

impl EventPayloadKind for SupervisionSessionOpenedPayload {
    const KIND: &'static str = "supervision_session_opened";
}

impl EventPayloadKind for UnaccountedPrintPayload {
    const KIND: &'static str = "unaccounted_print";
}

/// Every kind the server declares a payload type for, in name order.
pub const EVENT_KINDS: [&str; 31] = [
    "action_executed",
    "action_rejected",
    "action_requested",
    "agent_assessment",
    "camera_look",
    "charge_pended",
    "filament_change_signalled",
    "filament_consumed",
    "file_tally_rebaselined",
    "intervention_expired",
    "malformed_external_event",
    "obico_failure_alert",
    "obico_printer_notification",
    "operator_acknowledgement",
    "periodic_observation",
    "port_failure",
    "preflight_checked",
    "print_ended",
    "print_started",
    "print_untracked",
    "spool_adjusted",
    "spool_command_rejected",
    "spool_loaded",
    "spool_registered",
    "spool_retired",
    "spool_unloaded",
    "spool_unverified",
    "startup_reconciliation",
    "supervision_session_closed",
    "supervision_session_opened",
    "unaccounted_print",
];

impl EventRecord {
    /// The payload as `P`, when this event is under the kind `P` declares.
    ///
    /// Answers `None` for an event of any other kind — one this client knows
    /// or one it does not — and the parse failure for an event under the
    /// right kind whose payload is not of the type.
    #[must_use]
    pub fn payload_as<P: EventPayloadKind>(&self) -> Option<Result<P, serde_json::Error>> {
        (self.kind == P::KIND).then(|| serde_json::from_value(self.payload.clone()))
    }
}

impl Client {
    /// Call `prints` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read.
    // llmlint: ignore[names_match_behavior] See suppressions.toml.
    pub fn prints(&self) -> Result<PrintsAnswer, ClientError> {
        let target = String::from("/v1/prints");
        let asked: Vec<(String, String)> = Vec::new();
        let sending: Option<serde_json::Value> = None;
        self.call("GET", &target, &asked, sending.as_ref())
    }

    /// Call `status` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read.
    pub fn status(&self, print_id: &str) -> Result<StatusAnswer, ClientError> {
        let target = format!("/v1/prints/{print_id}/status");
        let asked: Vec<(String, String)> = Vec::new();
        let sending: Option<serde_json::Value> = None;
        self.call("GET", &target, &asked, sending.as_ref())
    }

    /// Call `context` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read.
    pub fn context(&self, print_id: &str) -> Result<ContextAnswer, ClientError> {
        let target = format!("/v1/prints/{print_id}/context");
        let asked: Vec<(String, String)> = Vec::new();
        let sending: Option<serde_json::Value> = None;
        self.call("GET", &target, &asked, sending.as_ref())
    }

    /// Call `image` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read.
    pub fn image(&self, image_id: &str) -> Result<ImageAnswer, ClientError> {
        let target = format!("/v1/images/{image_id}");
        let asked: Vec<(String, String)> = Vec::new();
        let sending: Option<serde_json::Value> = None;
        self.call("GET", &target, &asked, sending.as_ref())
    }

    /// Call `history` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read.
    pub fn history(
        &self,
        print_id: &str,
        limit: Option<i64>,
    ) -> Result<HistoryAnswer, ClientError> {
        let target = format!("/v1/prints/{print_id}/history");
        let mut asked: Vec<(String, String)> = Vec::new();
        if let Some(value) = limit {
            asked.push(("limit".to_owned(), value.to_string()));
        }
        let sending: Option<serde_json::Value> = None;
        self.call("GET", &target, &asked, sending.as_ref())
    }

    /// Call `events` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read.
    pub fn events(
        &self,
        after: Option<String>,
        print_id: Option<String>,
        kinds: Option<Vec<String>>,
        exclude_kinds: Option<Vec<String>>,
        wait_s: Option<i64>,
        limit: Option<i64>,
    ) -> Result<EventsAnswer, ClientError> {
        let target = String::from("/v1/events");
        let mut asked: Vec<(String, String)> = Vec::new();
        if let Some(value) = after {
            asked.push(("after".to_owned(), value));
        }
        if let Some(value) = print_id {
            asked.push(("print_id".to_owned(), value));
        }
        for value in kinds.into_iter().flatten() {
            asked.push(("kinds".to_owned(), value));
        }
        for value in exclude_kinds.into_iter().flatten() {
            asked.push(("exclude_kinds".to_owned(), value));
        }
        if let Some(value) = wait_s {
            asked.push(("wait_s".to_owned(), value.to_string()));
        }
        if let Some(value) = limit {
            asked.push(("limit".to_owned(), value.to_string()));
        }
        let sending: Option<serde_json::Value> = None;
        self.call("GET", &target, &asked, sending.as_ref())
    }

    /// Call `manifest_get` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read.
    pub fn manifest_get(&self, print_id: &str) -> Result<ManifestAnswer, ClientError> {
        let target = format!("/v1/prints/{print_id}/manifest");
        let asked: Vec<(String, String)> = Vec::new();
        let sending: Option<serde_json::Value> = None;
        self.call("GET", &target, &asked, sending.as_ref())
    }

    /// Call `look` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read.
    pub fn look(&self, print_id: &str, wait_s: Option<i64>) -> Result<Look, ClientError> {
        let target = format!("/v1/prints/{print_id}/look");
        let mut asked: Vec<(String, String)> = Vec::new();
        if let Some(value) = wait_s {
            asked.push(("wait_s".to_owned(), value.to_string()));
        }
        let sending: Option<serde_json::Value> = None;
        self.call("GET", &target, &asked, sending.as_ref())
    }

    /// Call `manifest_set` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read, when this client
    /// refuses the call before making it because the reason is empty, and
    /// when the policy refused the action — which arrives as
    /// `ClientError::Rejected`, carrying the reason, the value asked for and
    /// the range allowed.
    pub fn manifest_set(
        &self,
        print_id: &str,
        reason: &str,
        manifest: &JobManifest,
    ) -> Result<ManifestAnswer, ClientError> {
        crate::reason_given(reason)?;
        let target = format!("/v1/prints/{print_id}/manifest");
        let asked: Vec<(String, String)> = Vec::new();
        let mut sending = serde_json::Map::new();
        sending.insert("reason".to_owned(), crate::as_value(&reason)?);
        sending.insert("manifest".to_owned(), crate::as_value(&manifest)?);
        let sending = Some(serde_json::Value::Object(sending));
        self.call("PUT", &target, &asked, sending.as_ref())
    }

    /// Call `spools` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read.
    pub fn spools(&self, include_retired: Option<bool>) -> Result<SpoolsAnswer, ClientError> {
        let target = String::from("/v1/spools");
        let mut asked: Vec<(String, String)> = Vec::new();
        if let Some(value) = include_retired {
            asked.push(("include_retired".to_owned(), value.to_string()));
        }
        let sending: Option<serde_json::Value> = None;
        self.call("GET", &target, &asked, sending.as_ref())
    }

    /// Call `spool` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read.
    pub fn spool(&self, spool_id: &str) -> Result<SpoolAnswer, ClientError> {
        let target = format!("/v1/spools/{spool_id}");
        let asked: Vec<(String, String)> = Vec::new();
        let sending: Option<serde_json::Value> = None;
        self.call("GET", &target, &asked, sending.as_ref())
    }

    /// Call `printer_history` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read.
    pub fn printer_history(
        &self,
        kinds: Option<Vec<String>>,
        since: Option<String>,
        until: Option<String>,
        spool_id: Option<String>,
        before: Option<String>,
        limit: Option<i64>,
    ) -> Result<TimelineAnswer, ClientError> {
        let target = String::from("/v1/history");
        let mut asked: Vec<(String, String)> = Vec::new();
        for value in kinds.into_iter().flatten() {
            asked.push(("kinds".to_owned(), value));
        }
        if let Some(value) = since {
            asked.push(("since".to_owned(), value));
        }
        if let Some(value) = until {
            asked.push(("until".to_owned(), value));
        }
        if let Some(value) = spool_id {
            asked.push(("spool_id".to_owned(), value));
        }
        if let Some(value) = before {
            asked.push(("before".to_owned(), value));
        }
        if let Some(value) = limit {
            asked.push(("limit".to_owned(), value.to_string()));
        }
        let sending: Option<serde_json::Value> = None;
        self.call("GET", &target, &asked, sending.as_ref())
    }

    /// Call `preflight` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read.
    pub fn preflight(&self, file_name: &str) -> Result<PreflightAnswer, ClientError> {
        let target = String::from("/v1/preflight");
        let asked: Vec<(String, String)> = vec![("file_name".to_owned(), file_name.to_owned())];
        let sending: Option<serde_json::Value> = None;
        self.call("GET", &target, &asked, sending.as_ref())
    }

    /// Call `pause` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read, when this client
    /// refuses the call before making it because the reason is empty, and
    /// when the policy refused the action — which arrives as
    /// `ClientError::Rejected`, carrying the reason, the value asked for and
    /// the range allowed.
    pub fn pause(&self, print_id: &str, reason: &str) -> Result<ActionAnswer, ClientError> {
        crate::reason_given(reason)?;
        let target = format!("/v1/prints/{print_id}/actions/pause");
        let asked: Vec<(String, String)> = Vec::new();
        let mut sending = serde_json::Map::new();
        sending.insert("actor".to_owned(), crate::as_value(&self.actor())?);
        sending.insert("reason".to_owned(), crate::as_value(&reason)?);
        let sending = Some(serde_json::Value::Object(sending));
        self.call("POST", &target, &asked, sending.as_ref())
    }

    /// Call `resume` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read, when this client
    /// refuses the call before making it because the reason is empty, and
    /// when the policy refused the action — which arrives as
    /// `ClientError::Rejected`, carrying the reason, the value asked for and
    /// the range allowed.
    pub fn resume(&self, print_id: &str, reason: &str) -> Result<ActionAnswer, ClientError> {
        crate::reason_given(reason)?;
        let target = format!("/v1/prints/{print_id}/actions/resume");
        let asked: Vec<(String, String)> = Vec::new();
        let mut sending = serde_json::Map::new();
        sending.insert("actor".to_owned(), crate::as_value(&self.actor())?);
        sending.insert("reason".to_owned(), crate::as_value(&reason)?);
        let sending = Some(serde_json::Value::Object(sending));
        self.call("POST", &target, &asked, sending.as_ref())
    }

    /// Call `cancel` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read, when this client
    /// refuses the call before making it because the reason is empty, and
    /// when the policy refused the action — which arrives as
    /// `ClientError::Rejected`, carrying the reason, the value asked for and
    /// the range allowed.
    pub fn cancel(&self, print_id: &str, reason: &str) -> Result<ActionAnswer, ClientError> {
        crate::reason_given(reason)?;
        let target = format!("/v1/prints/{print_id}/actions/cancel");
        let asked: Vec<(String, String)> = Vec::new();
        let mut sending = serde_json::Map::new();
        sending.insert("actor".to_owned(), crate::as_value(&self.actor())?);
        sending.insert("reason".to_owned(), crate::as_value(&reason)?);
        let sending = Some(serde_json::Value::Object(sending));
        self.call("POST", &target, &asked, sending.as_ref())
    }

    /// Call `start_print` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read, when this client
    /// refuses the call before making it because the reason is empty, and
    /// when the policy refused the action — which arrives as
    /// `ClientError::Rejected`, carrying the reason, the value asked for and
    /// the range allowed.
    pub fn start_print(
        &self,
        print_id: &str,
        file_name: &FileName,
        manifest: &JobManifest,
        reason: &str,
        override_filament_check: Option<bool>,
    ) -> Result<ActionAnswer, ClientError> {
        crate::reason_given(reason)?;
        let target = format!("/v1/prints/{print_id}/actions/start_print");
        let asked: Vec<(String, String)> = Vec::new();
        let mut sending = serde_json::Map::new();
        sending.insert("actor".to_owned(), crate::as_value(&self.actor())?);
        sending.insert("file_name".to_owned(), crate::as_value(&file_name)?);
        sending.insert("manifest".to_owned(), crate::as_value(&manifest)?);
        if let Some(value) = override_filament_check {
            sending.insert(
                "override_filament_check".to_owned(),
                crate::as_value(&value)?,
            );
        }
        sending.insert("reason".to_owned(), crate::as_value(&reason)?);
        let sending = Some(serde_json::Value::Object(sending));
        self.call("POST", &target, &asked, sending.as_ref())
    }

    /// Call `set_feedrate_factor` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read, when this client
    /// refuses the call before making it because the reason is empty, and
    /// when the policy refused the action — which arrives as
    /// `ClientError::Rejected`, carrying the reason, the value asked for and
    /// the range allowed.
    pub fn set_feedrate_factor(
        &self,
        print_id: &str,
        factor: f64,
        reason: &str,
        duration_s: Option<i64>,
    ) -> Result<ActionAnswer, ClientError> {
        crate::reason_given(reason)?;
        let target = format!("/v1/prints/{print_id}/actions/set_feedrate_factor");
        let asked: Vec<(String, String)> = Vec::new();
        let mut sending = serde_json::Map::new();
        sending.insert("actor".to_owned(), crate::as_value(&self.actor())?);
        if let Some(value) = duration_s {
            sending.insert("duration_s".to_owned(), crate::as_value(&value)?);
        }
        sending.insert("factor".to_owned(), crate::as_value(&factor)?);
        sending.insert("reason".to_owned(), crate::as_value(&reason)?);
        let sending = Some(serde_json::Value::Object(sending));
        self.call("POST", &target, &asked, sending.as_ref())
    }

    /// Call `set_flowrate_factor` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read, when this client
    /// refuses the call before making it because the reason is empty, and
    /// when the policy refused the action — which arrives as
    /// `ClientError::Rejected`, carrying the reason, the value asked for and
    /// the range allowed.
    pub fn set_flowrate_factor(
        &self,
        print_id: &str,
        factor: f64,
        reason: &str,
        duration_s: Option<i64>,
    ) -> Result<ActionAnswer, ClientError> {
        crate::reason_given(reason)?;
        let target = format!("/v1/prints/{print_id}/actions/set_flowrate_factor");
        let asked: Vec<(String, String)> = Vec::new();
        let mut sending = serde_json::Map::new();
        sending.insert("actor".to_owned(), crate::as_value(&self.actor())?);
        if let Some(value) = duration_s {
            sending.insert("duration_s".to_owned(), crate::as_value(&value)?);
        }
        sending.insert("factor".to_owned(), crate::as_value(&factor)?);
        sending.insert("reason".to_owned(), crate::as_value(&reason)?);
        let sending = Some(serde_json::Value::Object(sending));
        self.call("POST", &target, &asked, sending.as_ref())
    }

    /// Call `set_tool_target_c` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read, when this client
    /// refuses the call before making it because the reason is empty, and
    /// when the policy refused the action — which arrives as
    /// `ClientError::Rejected`, carrying the reason, the value asked for and
    /// the range allowed.
    pub fn set_tool_target_c(
        &self,
        print_id: &str,
        reason: &str,
        target_c: f64,
        tool: i64,
        duration_s: Option<i64>,
    ) -> Result<ActionAnswer, ClientError> {
        crate::reason_given(reason)?;
        let target = format!("/v1/prints/{print_id}/actions/set_tool_target_c");
        let asked: Vec<(String, String)> = Vec::new();
        let mut sending = serde_json::Map::new();
        sending.insert("actor".to_owned(), crate::as_value(&self.actor())?);
        if let Some(value) = duration_s {
            sending.insert("duration_s".to_owned(), crate::as_value(&value)?);
        }
        sending.insert("reason".to_owned(), crate::as_value(&reason)?);
        sending.insert("target_c".to_owned(), crate::as_value(&target_c)?);
        sending.insert("tool".to_owned(), crate::as_value(&tool)?);
        let sending = Some(serde_json::Value::Object(sending));
        self.call("POST", &target, &asked, sending.as_ref())
    }

    /// Call `set_bed_target_c` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read, when this client
    /// refuses the call before making it because the reason is empty, and
    /// when the policy refused the action — which arrives as
    /// `ClientError::Rejected`, carrying the reason, the value asked for and
    /// the range allowed.
    pub fn set_bed_target_c(
        &self,
        print_id: &str,
        reason: &str,
        target_c: f64,
        duration_s: Option<i64>,
    ) -> Result<ActionAnswer, ClientError> {
        crate::reason_given(reason)?;
        let target = format!("/v1/prints/{print_id}/actions/set_bed_target_c");
        let asked: Vec<(String, String)> = Vec::new();
        let mut sending = serde_json::Map::new();
        sending.insert("actor".to_owned(), crate::as_value(&self.actor())?);
        if let Some(value) = duration_s {
            sending.insert("duration_s".to_owned(), crate::as_value(&value)?);
        }
        sending.insert("reason".to_owned(), crate::as_value(&reason)?);
        sending.insert("target_c".to_owned(), crate::as_value(&target_c)?);
        let sending = Some(serde_json::Value::Object(sending));
        self.call("POST", &target, &asked, sending.as_ref())
    }

    /// Call `set_fan_percent` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read, when this client
    /// refuses the call before making it because the reason is empty, and
    /// when the policy refused the action — which arrives as
    /// `ClientError::Rejected`, carrying the reason, the value asked for and
    /// the range allowed.
    pub fn set_fan_percent(
        &self,
        print_id: &str,
        percent: f64,
        reason: &str,
        duration_s: Option<i64>,
    ) -> Result<ActionAnswer, ClientError> {
        crate::reason_given(reason)?;
        let target = format!("/v1/prints/{print_id}/actions/set_fan_percent");
        let asked: Vec<(String, String)> = Vec::new();
        let mut sending = serde_json::Map::new();
        sending.insert("actor".to_owned(), crate::as_value(&self.actor())?);
        if let Some(value) = duration_s {
            sending.insert("duration_s".to_owned(), crate::as_value(&value)?);
        }
        sending.insert("percent".to_owned(), crate::as_value(&percent)?);
        sending.insert("reason".to_owned(), crate::as_value(&reason)?);
        let sending = Some(serde_json::Value::Object(sending));
        self.call("POST", &target, &asked, sending.as_ref())
    }

    /// Call `acknowledge_failure` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read, when this client
    /// refuses the call before making it because the reason is empty, and
    /// when the policy refused the action — which arrives as
    /// `ClientError::Rejected`, carrying the reason, the value asked for and
    /// the range allowed.
    pub fn acknowledge_failure(
        &self,
        print_id: &str,
        disposition: &AcknowledgementDisposition,
        event_id: &EventId,
        reason: &str,
    ) -> Result<ActionAnswer, ClientError> {
        crate::reason_given(reason)?;
        let target = format!("/v1/prints/{print_id}/actions/acknowledge_failure");
        let asked: Vec<(String, String)> = Vec::new();
        let mut sending = serde_json::Map::new();
        sending.insert("actor".to_owned(), crate::as_value(&self.actor())?);
        sending.insert("disposition".to_owned(), crate::as_value(&disposition)?);
        sending.insert("event_id".to_owned(), crate::as_value(&event_id)?);
        sending.insert("reason".to_owned(), crate::as_value(&reason)?);
        let sending = Some(serde_json::Value::Object(sending));
        self.call("POST", &target, &asked, sending.as_ref())
    }

    /// Call `register_spool` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read, when this client
    /// refuses the call before making it because the reason is empty, and
    /// when the policy refused the action — which arrives as
    /// `ClientError::Rejected`, carrying the reason, the value asked for and
    /// the range allowed.
    // One argument per value the operation declares, as every client takes them; suppressions.toml has the reason.
    #[expect(clippy::too_many_arguments)]
    pub fn register_spool(
        &self,
        initial_g: f64,
        material: &str,
        name: &str,
        reason: &str,
        color: Option<String>,
        density_g_cm3: Option<f64>,
        diameter_mm: Option<f64>,
        remaining_g: Option<f64>,
        tare_g: Option<f64>,
    ) -> Result<SpoolCommandAnswer, ClientError> {
        crate::reason_given(reason)?;
        let target = String::from("/v1/spools/actions/register_spool");
        let asked: Vec<(String, String)> = Vec::new();
        let mut sending = serde_json::Map::new();
        sending.insert("actor".to_owned(), crate::as_value(&self.actor())?);
        if let Some(value) = color {
            sending.insert("color".to_owned(), crate::as_value(&value)?);
        }
        if let Some(value) = density_g_cm3 {
            sending.insert("density_g_cm3".to_owned(), crate::as_value(&value)?);
        }
        if let Some(value) = diameter_mm {
            sending.insert("diameter_mm".to_owned(), crate::as_value(&value)?);
        }
        sending.insert("initial_g".to_owned(), crate::as_value(&initial_g)?);
        sending.insert("material".to_owned(), crate::as_value(&material)?);
        sending.insert("name".to_owned(), crate::as_value(&name)?);
        sending.insert("reason".to_owned(), crate::as_value(&reason)?);
        if let Some(value) = remaining_g {
            sending.insert("remaining_g".to_owned(), crate::as_value(&value)?);
        }
        if let Some(value) = tare_g {
            sending.insert("tare_g".to_owned(), crate::as_value(&value)?);
        }
        let sending = Some(serde_json::Value::Object(sending));
        self.call("POST", &target, &asked, sending.as_ref())
    }

    /// Call `load_spool` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read, when this client
    /// refuses the call before making it because the reason is empty, and
    /// when the policy refused the action — which arrives as
    /// `ClientError::Rejected`, carrying the reason, the value asked for and
    /// the range allowed.
    pub fn load_spool(
        &self,
        spool_id: &str,
        reason: &str,
        tool: i64,
    ) -> Result<SpoolCommandAnswer, ClientError> {
        crate::reason_given(reason)?;
        let target = format!("/v1/spools/{spool_id}/actions/load_spool");
        let asked: Vec<(String, String)> = Vec::new();
        let mut sending = serde_json::Map::new();
        sending.insert("actor".to_owned(), crate::as_value(&self.actor())?);
        sending.insert("reason".to_owned(), crate::as_value(&reason)?);
        sending.insert("tool".to_owned(), crate::as_value(&tool)?);
        let sending = Some(serde_json::Value::Object(sending));
        self.call("POST", &target, &asked, sending.as_ref())
    }

    /// Call `unload_spool` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read, when this client
    /// refuses the call before making it because the reason is empty, and
    /// when the policy refused the action — which arrives as
    /// `ClientError::Rejected`, carrying the reason, the value asked for and
    /// the range allowed.
    pub fn unload_spool(
        &self,
        spool_id: &str,
        reason: &str,
    ) -> Result<SpoolCommandAnswer, ClientError> {
        crate::reason_given(reason)?;
        let target = format!("/v1/spools/{spool_id}/actions/unload_spool");
        let asked: Vec<(String, String)> = Vec::new();
        let mut sending = serde_json::Map::new();
        sending.insert("actor".to_owned(), crate::as_value(&self.actor())?);
        sending.insert("reason".to_owned(), crate::as_value(&reason)?);
        let sending = Some(serde_json::Value::Object(sending));
        self.call("POST", &target, &asked, sending.as_ref())
    }

    /// Call `adjust_spool` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read, when this client
    /// refuses the call before making it because the reason is empty, and
    /// when the policy refused the action — which arrives as
    /// `ClientError::Rejected`, carrying the reason, the value asked for and
    /// the range allowed.
    pub fn adjust_spool(
        &self,
        spool_id: &str,
        reason: &str,
        gross_g: Option<f64>,
        remaining_g: Option<f64>,
    ) -> Result<SpoolCommandAnswer, ClientError> {
        crate::reason_given(reason)?;
        let target = format!("/v1/spools/{spool_id}/actions/adjust_spool");
        let asked: Vec<(String, String)> = Vec::new();
        let mut sending = serde_json::Map::new();
        sending.insert("actor".to_owned(), crate::as_value(&self.actor())?);
        if let Some(value) = gross_g {
            sending.insert("gross_g".to_owned(), crate::as_value(&value)?);
        }
        sending.insert("reason".to_owned(), crate::as_value(&reason)?);
        if let Some(value) = remaining_g {
            sending.insert("remaining_g".to_owned(), crate::as_value(&value)?);
        }
        let sending = Some(serde_json::Value::Object(sending));
        self.call("POST", &target, &asked, sending.as_ref())
    }

    /// Call `retire_spool` on the configured supervisor.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` when the supervisor could not be reached, when
    /// it answered something this client cannot read, when this client
    /// refuses the call before making it because the reason is empty, and
    /// when the policy refused the action — which arrives as
    /// `ClientError::Rejected`, carrying the reason, the value asked for and
    /// the range allowed.
    pub fn retire_spool(
        &self,
        spool_id: &str,
        reason: &str,
    ) -> Result<SpoolCommandAnswer, ClientError> {
        crate::reason_given(reason)?;
        let target = format!("/v1/spools/{spool_id}/actions/retire_spool");
        let asked: Vec<(String, String)> = Vec::new();
        let mut sending = serde_json::Map::new();
        sending.insert("actor".to_owned(), crate::as_value(&self.actor())?);
        sending.insert("reason".to_owned(), crate::as_value(&reason)?);
        let sending = Some(serde_json::Value::Object(sending));
        self.call("POST", &target, &asked, sending.as_ref())
    }
}