printobserver-sdk 0.2.0

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
//! 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, which
/// is the version the type crate declares in the tree they came from.
pub const CONTRACT_VERSION: &str = "0.2.0";

/// Every operation this client exposes a method for, which is every operation
/// the server declares and no other.
pub const OPERATION_NAMES: [&str; 16] = [
    "status",
    "context",
    "image",
    "history",
    "manifest_get",
    "manifest_set",
    "pause",
    "resume",
    "cancel",
    "start_print",
    "set_feedrate_factor",
    "set_flowrate_factor",
    "set_tool_target_c",
    "set_bed_target_c",
    "set_fan_percent",
    "acknowledge_failure",
];

/// 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,
    /// Stop the print.
    #[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,
}

/// 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,
}

/// 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;

/// One event, as the store holds 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>,
    /// 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,
    /// Which arm this is, and what that arm carries. It travels flattened
    /// into this object, under `kind`.
    #[serde(flatten)]
    pub kind: EventRecordKind,
}

/// Which arm one `EventRecord` is, and what that arm carries.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind")]
pub enum EventRecordKind {
    /// Obico reported a print failure.
    #[serde(rename = "obico_failure_alert")]
    ObicoFailureAlert {
        /// One shape of the contracts, which say nothing more about it.
        payload: ObicoFailureAlertPayload,
    },
    /// Obico sent a printer notification.
    #[serde(rename = "obico_printer_notification")]
    ObicoPrinterNotification {
        /// One shape of the contracts, which say nothing more about it.
        payload: ObicoPrinterNotificationPayload,
    },
    /// An external body arrived that could not be read.
    #[serde(rename = "malformed_external_event")]
    MalformedExternalEvent {
        /// One shape of the contracts, which say nothing more about it.
        payload: MalformedExternalEventPayload,
    },
    /// An actor asked for an action.
    #[serde(rename = "action_requested")]
    ActionRequested {
        /// One shape of the contracts, which say nothing more about it.
        payload: ActionRequestedPayload,
    },
    /// An accepted action reached the printer.
    #[serde(rename = "action_executed")]
    ActionExecuted {
        /// One shape of the contracts, which say nothing more about it.
        payload: ActionExecutedPayload,
    },
    /// Policy refused an action.
    #[serde(rename = "action_rejected")]
    ActionRejected {
        /// One shape of the contracts, which say nothing more about it.
        payload: ActionRejectedPayload,
    },
    /// A bounded intervention expired.
    #[serde(rename = "intervention_expired")]
    InterventionExpired {
        /// One shape of the contracts, which say nothing more about it.
        payload: InterventionExpiredPayload,
    },
    /// A supervision session was opened.
    #[serde(rename = "supervision_session_opened")]
    SupervisionSessionOpened {
        /// One shape of the contracts, which say nothing more about it.
        payload: SupervisionSessionOpenedPayload,
    },
    /// A supervision session was closed.
    #[serde(rename = "supervision_session_closed")]
    SupervisionSessionClosed {
        /// One shape of the contracts, which say nothing more about it.
        payload: SupervisionSessionClosedPayload,
    },
    /// The agent wrote down what it made of a turn.
    #[serde(rename = "agent_assessment")]
    AgentAssessment {
        /// One shape of the contracts, which say nothing more about it.
        payload: AgentAssessmentPayload,
    },
    /// An operator acknowledged an event.
    #[serde(rename = "operator_acknowledgement")]
    OperatorAcknowledgement {
        /// One shape of the contracts, which say nothing more about it.
        payload: OperatorAcknowledgementPayload,
    },
    /// A port failed while an event was being handled.
    #[serde(rename = "port_failure")]
    PortFailure {
        /// One shape of the contracts, which say nothing more about it.
        payload: PortFailurePayload,
    },
    /// A supervisor reconciled one thing the store held when it started.
    #[serde(rename = "startup_reconciliation")]
    StartupReconciliation {
        /// One shape of the contracts, which say nothing more about it.
        payload: StartupReconciliationPayload,
    },
}

/// Where an event came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum EventSource {
    /// Obico, over its webhook.
    #[serde(rename = "obico")]
    Obico,
    /// A person.
    #[serde(rename = "operator")]
    Operator,
    /// The supervising agent.
    #[serde(rename = "agent")]
    Agent,
    /// The supervisor itself.
    #[serde(rename = "system")]
    System,
}

/// 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 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;

/// 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 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 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,
}

/// 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,
}

/// 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,
}

/// 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,
        /// 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>,
}

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

/// One print, and the record supervision keys from.
///
/// Obico's own print id is carried beside this record's identifier rather
/// than
/// as it, because a print may be observed before Obico 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,
    /// Every manifest range this print narrowed to the envelope's.
    pub narrowings: Vec<ManifestNarrowing>,
    /// Obico's own identifier for the print, when Obico has one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub obico_print_id: Option<i64>,
    /// When the print was opened.
    pub opened_at: Timestamp,
    /// The state the print is in.
    pub state: PrinterState,
}

/// 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),
}

/// 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;

/// 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 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,
}

/// 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,
}

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

impl Client {
    /// 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 `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 `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 `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,
    ) -> 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)?);
        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())
    }
}