printobserver-server 0.13.0

The printobserver server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
//! The JSON a caller sends and the JSON this server answers with.
//!
//! Nothing here restates a contract type. A request carries the values one
//! [`PrintAction`] variant needs and this module assembles the action; an
//! answer carries the contract's own records as they are. In particular **no
//! answer carries image bytes**: [`ImageAnswer`] carries the record and the
//! absolute path its bytes are at, because the server, the command-line program
//! and the agent all run on the one host and image transport is a filesystem
//! path.

use std::path::PathBuf;

use printobserver_core::store::ImageLookup;
use printobserver_core::{
    AcknowledgementDisposition, ActionKind, ActionRecord, Actor, ImageRecord, Intervention,
    JobManifest, ManifestNarrowing, PendingCharge, PolicyDecision, Preflight, PrintOutcome,
    PrintRecord, RecoveryAction, RecoveryActionKind, RecoveryDecision, SpoolCommand, SpoolId,
    SpoolRecord, SpoolTrust,
};
use printobserver_core::{AgentContext, DetectorHealth};
use printobserver_printer_api::{JobSnapshot, PrinterSnapshot};
use printobserver_supervisor_api::SupervisionSession;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use printobserver_types::serde_json::{Map, Value};
use printobserver_types::{EventId, EventRecord, FileName, PrintId, Timestamp};

/// Why a request could not be turned into one action of the vocabulary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BodyRefusal {
    /// What is missing or wrong, named so the caller can send it.
    pub detail: String,
}

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

/// One request for one action of the vocabulary.
///
/// Every mutating operation takes this shape: the reason it carries, who is
/// asking, the optional duration a bounded change stands for, and whichever of
/// the values the asked-for action needs. A field the action does not need is
/// ignored; a field it needs and the request omits is refused naming it, and
/// **a request carrying no reason is refused before anything reaches the
/// printer or the record**.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
pub struct ActionBody {
    /// Why the actor is asking for this.
    #[serde(default)]
    pub reason: Option<String>,
    /// Who is asking.
    pub actor: Actor,
    /// How long the change stands for, in whole seconds.
    #[serde(default)]
    pub duration_s: Option<i64>,
    /// The multiplier a feedrate or flowrate adjustment asks for.
    #[serde(default)]
    pub factor: Option<f64>,
    /// The temperature a heater adjustment asks for.
    #[serde(default)]
    pub target_c: Option<f64>,
    /// The percentage a fan adjustment asks for.
    #[serde(default)]
    pub percent: Option<f64>,
    /// The tool a tool adjustment is about.
    #[serde(default)]
    pub tool: Option<i64>,
    /// The file a start asks for.
    #[serde(default)]
    pub file_name: Option<FileName>,
    /// The manifest a start is bounded by.
    #[serde(default)]
    pub manifest: Option<JobManifest>,
    /// Whether a start goes ahead despite the filament check; absent, it does
    /// not.
    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
    #[serde(default)]
    pub override_filament_check: bool,
    /// Whether a start goes ahead despite the material check; absent, it does
    /// not.
    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
    #[serde(default)]
    pub override_material_check: bool,
    /// Whether a start goes ahead despite the sheet check; absent, it does
    /// not.
    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
    #[serde(default)]
    pub override_sheet_check: bool,
    /// The event an acknowledgement is about.
    #[serde(default)]
    pub event_id: Option<EventId>,
    /// What an acknowledgement asks for next.
    #[serde(default)]
    pub disposition: Option<AcknowledgementDisposition>,
    /// How a closed print ended, in the operator's judgement.
    #[serde(default)]
    pub outcome: Option<PrintOutcome>,
}

/// One value a request had to carry and did not.
fn missing<T>(named: &str) -> Result<T, BodyRefusal> {
    Err(BodyRefusal {
        detail: format!("this operation needs `{named}`, and the request carries none"),
    })
}

/// One value a request has to carry, refused naming it when it carries none.
fn needed<T>(value: Option<T>, named: &str) -> Result<T, BodyRefusal> {
    value.map_or_else(|| missing(named), Ok)
}

/// The reason a mutating request carries, refused when it carries none.
///
/// One rule for every mutating operation, whether it asks something of the
/// machine or writes a record: a change nobody gave a reason for is one the
/// history cannot account for afterwards, and the answer to it is the same
/// refusal whichever operation it arrived at.
///
/// # Errors
///
/// Returns [`BodyRefusal`] when the reason is absent or is nothing but
/// whitespace.
pub fn reason_of(reason: Option<&str>) -> Result<String, BodyRefusal> {
    match reason.map(str::trim) {
        Some(reason) if !reason.is_empty() => Ok(reason.to_owned()),
        _ => Err(BodyRefusal {
            detail: "every mutating request carries a `reason`, and this one carries none"
                .to_owned(),
        }),
    }
}

/// One request to replace a print's manifest.
///
/// It carries a reason for the same reason every action does: a manifest
/// narrows what any actor may ask for, so replacing one is a change to the
/// bounds a print runs under rather than a note about it.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
pub struct ManifestBody {
    /// Why the manifest is being replaced.
    #[serde(default)]
    pub reason: Option<String>,
    /// The manifest to write.
    pub manifest: JobManifest,
}

impl ManifestBody {
    /// The reason this request carries, refused when it carries none.
    ///
    /// # Errors
    ///
    /// Returns [`BodyRefusal`] when the reason is absent or is nothing but
    /// whitespace. It is checked **before** the manifest is written, so a
    /// request without one leaves the stored manifest and the print's
    /// narrowings exactly as they were.
    pub fn reason(&self) -> Result<String, BodyRefusal> {
        reason_of(self.reason.as_deref())
    }
}

impl ActionBody {
    /// The reason this request carries, refused when it carries none.
    ///
    /// # Errors
    ///
    /// Returns [`BodyRefusal`] when the reason is absent or is nothing but
    /// whitespace. Every mutating operation carries a reason, and this is
    /// checked before the action is assembled, so a request without one reaches
    /// neither the policy, the printer nor the record.
    pub fn reason(&self) -> Result<String, BodyRefusal> {
        reason_of(self.reason.as_deref())
    }

    /// The action this request asks for.
    ///
    /// # Errors
    ///
    /// Returns [`BodyRefusal`] naming the value the asked-for action needs and
    /// the request does not carry, and naming the absent reason before
    /// anything else.
    pub fn into_action(
        self,
        kind: ActionKind,
    ) -> Result<printobserver_core::PrintAction, BodyRefusal> {
        use printobserver_core::PrintAction as Action;

        let reason = self.reason()?;
        let actor = self.actor.clone();
        let duration_s = self.duration_s;
        Ok(match kind {
            ActionKind::Pause => Action::Pause { reason, actor },
            ActionKind::Resume => Action::Resume { reason, actor },
            ActionKind::Cancel => Action::Cancel { reason, actor },
            ActionKind::StartPrint => Action::StartPrint {
                file_name: needed(self.file_name, "file_name")?,
                manifest: needed(self.manifest, "manifest")?,
                override_filament_check: self.override_filament_check,
                override_material_check: self.override_material_check,
                override_sheet_check: self.override_sheet_check,
                reason,
                actor,
            },
            ActionKind::SetFeedrateFactor => Action::SetFeedrateFactor {
                factor: needed(self.factor, "factor")?,
                duration_s,
                reason,
                actor,
            },
            ActionKind::SetFlowrateFactor => Action::SetFlowrateFactor {
                factor: needed(self.factor, "factor")?,
                duration_s,
                reason,
                actor,
            },
            ActionKind::SetToolTargetC => Action::SetToolTargetC {
                tool: needed(self.tool, "tool")?,
                target_c: needed(self.target_c, "target_c")?,
                duration_s,
                reason,
                actor,
            },
            ActionKind::SetBedTargetC => Action::SetBedTargetC {
                target_c: needed(self.target_c, "target_c")?,
                duration_s,
                reason,
                actor,
            },
            ActionKind::SetFanPercent => Action::SetFanPercent {
                percent: needed(self.percent, "percent")?,
                duration_s,
                reason,
                actor,
            },
            ActionKind::AcknowledgeFailure => Action::AcknowledgeFailure {
                event_id: needed(self.event_id, "event_id")?,
                disposition: needed(self.disposition, "disposition")?,
                reason,
                actor,
            },
            ActionKind::ClosePrint => Action::ClosePrint {
                outcome: needed(self.outcome, "outcome")?,
                reason,
                actor,
            },
            ActionKind::RegisterSpool
            | ActionKind::LoadSpool
            | ActionKind::UnloadSpool
            | ActionKind::AdjustSpool
            | ActionKind::RetireSpool => {
                return Err(BodyRefusal {
                    detail: format!(
                        "{kind:?} is a spool command, and no print-action operation carries one"
                    ),
                });
            }
        })
    }
}

/// What one mutating request left behind it.
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct ActionAnswer {
    /// 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,
    /// The bounded intervention it opened, when it opened one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub intervention: Option<Intervention>,
    /// What the printer said, when the request reached it and it refused.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub printer_refusal: Option<String>,
}

/// The spool command one request asks for, assembled from its body.
///
/// The body is the command's own fields, less the two a caller never supplies:
/// the tag, which the operation it was sent to names, and — for a command about
/// one spool — the spool, which its path names. Everything else is read by the
/// contracts' own type, so a field it refuses is refused in its own words and
/// a field it gains is one this reads with nothing written here. The reason is
/// ruled on first and travels trimmed, exactly as a print action's does.
///
/// # Errors
///
/// Returns [`BodyRefusal`] when the body is not a document, carries no reason,
/// names the tag or the spool itself, or is not the command's own fields.
pub fn spool_command_of(
    kind: ActionKind,
    spool_id: Option<SpoolId>,
    body: Value,
) -> Result<SpoolCommand, BodyRefusal> {
    let Value::Object(mut fields) = body else {
        return Err(BodyRefusal {
            detail: "a spool command's body is a document of its fields".to_owned(),
        });
    };
    let reason = reason_of(fields.get("reason").and_then(Value::as_str))?;
    fields.insert("reason".to_owned(), Value::String(reason));
    let tag = crate::operations::COMMAND_TAG;
    for routed in [tag, "spool_id"] {
        if fields.contains_key(routed) {
            return Err(BodyRefusal {
                detail: format!(
                    "a spool command's body does not carry `{routed}`: the operation it is \
                     sent to names it"
                ),
            });
        }
    }
    let named = printobserver_types::serde_json::to_value(kind).map_err(|error| BodyRefusal {
        detail: error.to_string(),
    })?;
    fields.insert(tag.to_owned(), named);
    if let Some(spool_id) = spool_id {
        fields.insert("spool_id".to_owned(), Value::String(spool_id.to_string()));
    }
    let command: SpoolCommand = printobserver_types::serde_json::from_value(Value::Object(fields))
        .map_err(|error| BodyRefusal {
            detail: format!("this is not a `{}` body: {error}", spool_command_name(kind)),
        })?;
    if command.kind() == kind {
        Ok(command)
    } else {
        Err(BodyRefusal {
            detail: format!("this body is not a `{}`", spool_command_name(kind)),
        })
    }
}

/// One command's own name, as the wire spells it.
fn spool_command_name(kind: ActionKind) -> String {
    printobserver_types::serde_json::to_value(kind)
        .ok()
        .and_then(|value| value.as_str().map(str::to_owned))
        .unwrap_or_else(|| format!("{kind:?}"))
}

/// The actor a spool command's body claims, read before anything else of it,
/// so the claim is held to the caller before the body is ruled on.
///
/// # Errors
///
/// Returns [`BodyRefusal`] when the body names no actor this system has.
pub fn claimed_actor(body: &Map<String, Value>) -> Result<Actor, BodyRefusal> {
    let Some(actor) = body.get("actor") else {
        return missing("actor");
    };
    printobserver_types::serde_json::from_value(actor.clone()).map_err(|error| BodyRefusal {
        detail: format!("`actor` is not an actor this system has: {error}"),
    })
}

/// The recovery action one request asks for, assembled from its body.
///
/// The body is the action's own fields beside the actor and the reason, less
/// the tag a caller never supplies: the operation it was sent to names the
/// action. A field no variant of the vocabulary carries — raw G-code among
/// them — is refused, and so is a reason that is absent or nothing but
/// whitespace, before anything is decided or recorded.
///
/// # Errors
///
/// Returns [`BodyRefusal`] when the body is not a document, carries the tag,
/// gives no reason or no actor, or is not that action's body.
pub fn recovery_of(
    kind: RecoveryActionKind,
    body: Value,
) -> Result<(RecoveryAction, Actor, String), BodyRefusal> {
    let Value::Object(mut fields) = body else {
        return Err(BodyRefusal {
            detail: "a recovery action's body is a document of its fields".to_owned(),
        });
    };
    let reason = reason_of(fields.get("reason").and_then(Value::as_str))?;
    let actor = claimed_actor(&fields)?;
    fields.remove("reason");
    fields.remove("actor");
    if fields.contains_key("action") {
        return Err(BodyRefusal {
            detail: "a recovery action's body does not carry `action`: the operation it is \
                     sent to names it"
                .to_owned(),
        });
    }
    fields.insert("action".to_owned(), Value::String(kind.as_str().to_owned()));
    let action: RecoveryAction = printobserver_types::serde_json::from_value(Value::Object(fields))
        .map_err(|error| BodyRefusal {
            detail: format!("this is not a `{kind}` body: {error}"),
        })?;
    if action.kind() == kind {
        Ok((action, actor, reason))
    } else {
        Err(BodyRefusal {
            detail: format!("this body is not a `{kind}`"),
        })
    }
}

/// What a recovery action answers, carried out or refused.
///
/// A refusal is the same shape and deliberately so: `decision` is either
/// `executed`, carrying what the printer made of it, or `rejected`, carrying
/// the reason, and the two events are what the request wrote.
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct RecoveryAnswer {
    /// What was asked for.
    pub action: RecoveryAction,
    /// What became of it.
    pub decision: RecoveryDecision,
    /// What became of it, in a sentence for a person: why it was refused and
    /// what would let it go ahead, or what it did.
    pub detail: String,
    /// The `recovery_requested` event, and the `recovery_executed` or
    /// `recovery_rejected` beside it.
    pub events: Vec<EventRecord>,
}

/// What the recovery read answers: everything a recovery is checked against
/// now, as the supervision core reads it.
pub type RecoveryStatusAnswer = printobserver_core::RecoveryStatus;

/// 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, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct SpoolCommandAnswer {
    /// The decision taken on the command.
    pub decision: PolicyDecision,
    /// The spool it was about, as the command left it, when there is one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub spool: Option<SpoolRecord>,
    /// Every event it wrote, in the order they were written.
    pub events: Vec<EventRecord>,
}

/// 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, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct SpoolsAnswer {
    /// One line per spool in `spools`, in the same order.
    pub at_a_glance: Vec<String>,
    /// Every spool, retired ones only when asked for, most recently registered
    /// first.
    pub spools: Vec<SpoolRecord>,
    /// 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>,
}

impl SpoolsAnswer {
    /// The answer for these spools and these held charges.
    #[must_use]
    pub fn of(spools: Vec<SpoolRecord>, pending: Vec<PendingCharge>) -> Self {
        Self {
            at_a_glance: spools.iter().map(at_a_glance).collect(),
            spools,
            pending,
        }
    }
}

/// One spool, in one line: its name, its material, what is left of what it
/// held, where it is, whether its figure can be trusted, and whether it is
/// retired.
///
/// `PLA white | PLA | 812.4 g of 1000.0 g left | on tool 0 | verified`, and
/// for a spool whose figure is in doubt the oldest reason, with how many more
/// it holds: `| unverified: uncharged_print (+1 more)`.
#[must_use]
pub fn at_a_glance(spool: &SpoolRecord) -> String {
    let place = spool
        .loaded_tool()
        .map_or_else(|| "not loaded".to_owned(), |tool| format!("on tool {tool}"));
    let trust = match &spool.trust {
        SpoolTrust::Verified => "verified".to_owned(),
        SpoolTrust::Unverified { marks } => {
            let oldest = marks.first().map_or_else(String::new, |mark| {
                printobserver_types::serde_json::to_value(mark.reason.kind())
                    .ok()
                    .and_then(|named| named.as_str().map(str::to_owned))
                    .unwrap_or_default()
            });
            let more = marks.len().saturating_sub(1);
            if more == 0 {
                format!("unverified: {oldest}")
            } else {
                format!("unverified: {oldest} (+{more} more)")
            }
        }
    };
    let retired = if spool.is_retired() { " | retired" } else { "" };
    format!(
        "{} | {} | {:.1} g of {:.1} g left | {place} | {trust}{retired}",
        spool.name, spool.material, spool.remaining_g, spool.initial_g
    )
}

/// 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, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct SpoolAnswer {
    /// The spool, retired or not.
    pub spool: SpoolRecord,
    /// The newest timeline events naming it, newest first.
    pub recent: Vec<EventRecord>,
}

/// What a printer history read answers: one page of the printer's own events.
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
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(skip_serializing_if = "Option::is_none")]
    pub next: Option<EventId>,
}

/// What a filament check answers.
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct PreflightAnswer {
    /// What the check found, read now.
    pub preflight: Preflight,
}

/// What a status read answers.
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct StatusAnswer {
    /// The print.
    pub print: PrintRecord,
    /// The printer, when a snapshot could be taken.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub printer: Option<PrinterSnapshot>,
    /// The job, when a snapshot could be taken.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub job: Option<JobSnapshot>,
    /// The supervision session watching it, when one is.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session: Option<SupervisionSession>,
    /// The bounded interventions still in force.
    pub interventions: Vec<Intervention>,
    /// The failure detector's health, and since when it has been so.
    pub detector: DetectorHealth,
}

/// What a context read answers.
///
/// The context is the agent's view of it ([`AgentContext`]): each fact once,
/// as it is now, and the events newer than the one asked `since`.
///
/// The latest image is **materialized** here rather than left as the handle
/// [`printobserver_core::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, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct ContextAnswer {
    /// Everything a supervision turn is given about the print.
    pub context: AgentContext,
    /// Where the latest image's bytes are, absolute on this host.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image_path: Option<PathBuf>,
}

/// What a fresh look answers: the look, as the supervision core took it.
///
/// Its `image_path` is absolute on this server's own filesystem, exactly as
/// [`ContextAnswer`]'s is.
pub type LookAnswer = printobserver_core::Look;

/// 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, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct ImageAnswer {
    /// The record.
    pub record: ImageRecord,
    /// Where its bytes are, absolute on this host.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<PathBuf>,
}

impl From<ImageLookup> for ImageAnswer {
    fn from(lookup: ImageLookup) -> Self {
        match lookup {
            ImageLookup::Found { record, path } => Self {
                record,
                path: Some(path),
            },
            ImageLookup::FileMissing { record } => Self { record, path: None },
        }
    }
}

/// 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, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct PrintsAnswer {
    /// Every print this server holds, ended or not, most recently opened first.
    pub prints: Vec<PrintRecord>,
    /// 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(skip_serializing_if = "Option::is_none")]
    pub active: Option<PrintId>,
}

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

/// 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, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
#[schemars(transform = cursor_is_always_sent)]
pub struct EventsAnswer {
    /// The events, oldest first in the order they were stored, each exactly as
    /// a history read serves it.
    pub events: Vec<EventRecord>,
    /// 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 watched print's end as stored, whatever the filters said, and null
    /// while it is open. Absent from a read that names no print.
    // Marked as a field whose null is sent and means something its absence
    // does not, so a generated client keeps the two apart.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(extend("x-null-is-sent" = true))]
    pub print_ended: Option<Option<PrintEnded>>,
}

/// Declare an events answer's `cursor` required, as the null it may be.
///
/// The derive reads an `Option` as a field that may be absent, and its own
/// `required` attribute drops the null with the absence; this keeps the null.
fn cursor_is_always_sent(schema: &mut printobserver_types::schemars::Schema) {
    if let Some(Value::Array(required)) = schema.get_mut("required") {
        required.push(Value::from("cursor"));
    }
}

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

/// What a manifest read or write answers.
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct ManifestAnswer {
    /// The manifest, when the print has one.
    #[serde(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>,
}

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

impl ErrorAnswer {
    /// One refusal, in its own words.
    pub fn saying(detail: impl core::fmt::Display) -> Self {
        Self {
            error: detail.to_string(),
        }
    }
}

/// What the ingress answers a post it accepted.
///
/// It carries no field, because the only thing it could carry is that the post
/// was accepted and this is the answer only an accepted post gets. It
/// serializes as `{"accepted": true}`, which is what a caller reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IngressAnswer;

impl Serialize for IngressAnswer {
    fn serialize<S: printobserver_types::serde::Serializer>(
        &self,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        use printobserver_types::serde::ser::SerializeStruct as _;
        let mut state = serializer.serialize_struct("IngressAnswer", 1)?;
        state.serialize_field("accepted", &true)?;
        state.end()
    }
}

#[cfg(test)]
mod tests {
    use printobserver_core::{ActionKind, Actor, ImageRecord};
    use printobserver_types::contract::Sample as _;

    use super::{ActionBody, ErrorAnswer, ImageAnswer, ImageLookup};

    /// A body carrying nothing but a reason and an actor.
    fn bare() -> ActionBody {
        ActionBody {
            reason: Some("a test is asking".to_owned()),
            actor: Actor::Operator,
            duration_s: None,
            factor: None,
            target_c: None,
            percent: None,
            tool: None,
            file_name: None,
            manifest: None,
            override_filament_check: false,
            override_material_check: false,
            override_sheet_check: false,
            event_id: None,
            disposition: None,
            outcome: None,
        }
    }

    /// Every action that needs a value it was not given is refused naming it.
    ///
    /// The walk is over the whole vocabulary rather than a sample: an action
    /// that quietly defaulted a value nobody sent would be one this server
    /// carried to a printer on the caller's behalf.
    #[test]
    fn every_action_that_needs_a_value_it_was_not_given_is_refused_naming_it() {
        let needed = [
            (ActionKind::StartPrint, "file_name"),
            (ActionKind::SetFeedrateFactor, "factor"),
            (ActionKind::SetFlowrateFactor, "factor"),
            (ActionKind::SetToolTargetC, "tool"),
            (ActionKind::SetBedTargetC, "target_c"),
            (ActionKind::SetFanPercent, "percent"),
            (ActionKind::AcknowledgeFailure, "event_id"),
            (ActionKind::ClosePrint, "outcome"),
        ];
        for (kind, named) in needed {
            let refusal = bare()
                .into_action(kind)
                .expect_err("this action needs a value the body does not carry");
            assert!(
                refusal.to_string().contains(named),
                "{kind:?} was refused without naming `{named}`: {refusal}"
            );
        }
    }

    /// A spool command is no print action, so no print-action body is read as
    /// one, whatever it carries.
    #[test]
    fn a_spool_command_kind_is_refused_as_a_print_action() {
        for kind in [
            ActionKind::RegisterSpool,
            ActionKind::LoadSpool,
            ActionKind::UnloadSpool,
            ActionKind::AdjustSpool,
            ActionKind::RetireSpool,
        ] {
            let refusal = bare()
                .into_action(kind)
                .expect_err("a spool command is not a print action");
            assert!(
                refusal.to_string().contains("spool command"),
                "{kind:?} was refused without saying why: {refusal}"
            );
        }
    }

    /// The second value each two-valued action needs is named in its turn.
    #[test]
    fn the_second_value_a_two_valued_action_needs_is_named_in_its_turn() {
        let mut starting = bare();
        starting.file_name = Some(printobserver_types::FileName::new("a.gcode").expect("a name"));
        assert!(
            starting
                .into_action(ActionKind::StartPrint)
                .expect_err("a start needs a manifest")
                .to_string()
                .contains("manifest")
        );

        let mut tool = bare();
        tool.tool = Some(0);
        assert!(
            tool.into_action(ActionKind::SetToolTargetC)
                .expect_err("a tool target needs a temperature")
                .to_string()
                .contains("target_c")
        );

        let mut acknowledgement = bare();
        acknowledgement.event_id = Some(printobserver_types::EventId::new());
        assert!(
            acknowledgement
                .into_action(ActionKind::AcknowledgeFailure)
                .expect_err("an acknowledgement needs a disposition")
                .to_string()
                .contains("disposition")
        );
    }

    /// A reason that is nothing but whitespace is no reason.
    #[test]
    fn a_reason_that_is_nothing_but_whitespace_is_no_reason() {
        let mut blank = bare();
        blank.reason = Some("   ".to_owned());
        assert!(blank.reason().is_err());
        let mut absent = bare();
        absent.reason = None;
        assert!(absent.reason().is_err());
        assert_eq!(bare().reason().expect("a reason"), "a test is asking");
    }

    /// An image whose file is gone answers the record and no path.
    ///
    /// A different answer from there being no such image, which is what tells a
    /// caller the history is intact and the file is not.
    #[test]
    fn an_image_whose_file_is_gone_answers_the_record_and_no_path() {
        let record = ImageRecord::sample_full();
        let missing = ImageAnswer::from(ImageLookup::FileMissing {
            record: record.clone(),
        });
        assert_eq!(missing.record, record);
        assert_eq!(missing.path, None);

        let found = ImageAnswer::from(ImageLookup::Found {
            record: record.clone(),
            path: "/var/lib/printobserver/images/ab/cd".into(),
        });
        assert_eq!(
            found.path.as_deref(),
            Some(std::path::Path::new("/var/lib/printobserver/images/ab/cd"))
        );
    }

    /// A refusal answers in the words of whatever refused it.
    #[test]
    fn a_refusal_answers_in_the_words_of_whatever_refused_it() {
        assert_eq!(
            ErrorAnswer::saying("the disk is full").error,
            "the disk is full"
        );
    }
}