Skip to main content

printobserver_server/
operations.rs

1//! The public operations this server serves, declared once.
2//!
3//! # One operation per public operation, and no more
4//!
5//! The list here is the whole API. It is exactly one operation per variant of
6//! [`PrintAction`](printobserver_core::PrintAction), of
7//! [`SpoolCommand`](printobserver_core::SpoolCommand) and of
8//! [`RecoveryAction`](printobserver_core::RecoveryAction) the contracts
9//! declare, and the recovery read beside the last ([`RECOVERY_STATUS`]),
10//! plus sixteen operations beside them — the prints listing, status, context,
11//! image materialization, history, the event log followed in the order it was
12//! stored, a fresh look at a print and one at the printer, the manifest's read
13//! and write, the four reads of the spool ledger: the spools, one spool, the
14//! printer's own history and a filament check — the operator's word that the
15//! bed is clear, and a recheck of a print's camera, and nothing else. The router is built by folding
16//! over this array rather than by writing routes out, so the set served and the
17//! set declared are one thing; and this crate's own tier derives the required
18//! set from the contracts' own `PrintAction` rather than from a list of its
19//! own, so growing this array and the routes together cannot satisfy it.
20//!
21//! # A read of one print may have a form for the printer as a whole
22//!
23//! A fresh look is one print's, and there is one of the printer with no print
24//! named — before a print, between prints, after one. The two are two
25//! operations, because they are two routes and two answers recorded in two
26//! places; and one command, because what a caller asks for is a look either
27//! way. So the print's operation names the printer's as its
28//! [`Operation::printer_wide`] form: the command made from it takes its print
29//! as optional and asks the printer's operation when none is named, and the
30//! printer's operation has no command of its own ([`printer_wide_of`]).
31//!
32//! The spool ledger's operations name no print: a spool is the printer's, not
33//! one print's, so they sit beneath `/spools` and `/history` rather than
34//! beneath a print, and a supervision turn's print binding constrains none of
35//! them. Nor do the recovery operations, beneath `/printer/recovery`: what a
36//! recovery moves is the printer, whatever the last print left on its bed.
37//!
38//! Every operation sits beneath [`VERSION_PREFIX`], takes JSON where it takes a
39//! body at all, and answers JSON.
40//!
41//! # Each operation declares what it takes and what it answers
42//!
43//! [`Operation::request`] is the request schema of one route — every value a
44//! caller supplies, where it travels and whether it is required — and
45//! [`Operation::response_schema`] is the schema of each answer that route can
46//! produce. Neither is written out for the fifteen mutating operations: their
47//! body is derived from the contracts' own
48//! [`PrintAction`](printobserver_core::PrintAction) or
49//! [`SpoolCommand`](printobserver_core::SpoolCommand) at run time, so a
50//! variant that gains a field gains it here the moment the type does. The
51//! command-line program builds its own parser from these declarations rather
52//! than from a list of its own, which is what stops the two surfaces drifting.
53//!
54//! # The ingress is not one of them
55//!
56//! [`INGRESS_PATH`] is the endpoint `Obico`'s webhook notification plugin posts
57//! to. It is the producer's own ingress rather than an operation a client
58//! calls — it is authenticated by a shared secret rather than by an actor, it
59//! carries `Obico`'s body rather than this system's, and it answers before its
60//! handling completes. So it is declared separately and served outside the
61//! versioned prefix, where no client can mistake one surface for the other.
62
63use printobserver_types::serde_json::{Value, json};
64
65// The vocabulary the mutating operations are folded from, re-exported beside
66// them: a client of this surface that derives its own commands from these
67// operations — the command-line program — reads which action each is and what
68// that action carries from here, without naming the supervision domain itself.
69pub use printobserver_core::{
70    ActionKind, PrintAction, RecoveryAction, RecoveryActionKind, SpoolCommand,
71};
72
73/// The one versioned prefix every public operation is served beneath.
74pub const VERSION_PREFIX: &str = "/v1";
75
76/// The media type every operation takes a body in and answers in.
77pub const MEDIA_TYPE: &str = "application/json";
78
79/// Where `Obico`'s webhook notification plugin posts, which is not a public
80/// operation. See this module's own comment.
81pub const INGRESS_PATH: &str = "/obico/webhook";
82
83/// The field a context answer carries the latest image's own path in.
84pub const CONTEXT_IMAGE_PATH_FIELD: &str = "image_path";
85
86/// The field an image answer carries that image's own path in.
87pub const IMAGE_PATH_FIELD: &str = "path";
88
89/// The field of a request body the action vocabulary's tag travels in, which a
90/// caller never supplies: the operation it sends to is what names the action.
91const ACTION_TAG: &str = "action";
92
93/// The field the spool ledger's vocabulary carries its tag in, which a caller
94/// never supplies either.
95pub const COMMAND_TAG: &str = "command";
96
97/// The method one operation is reached by.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
99pub enum Method {
100    /// A read.
101    Get,
102    /// A request that changes something.
103    Post,
104    /// A write that replaces what is there.
105    Put,
106}
107
108impl Method {
109    /// The method as it is spelled on the wire.
110    #[must_use]
111    pub const fn as_str(self) -> &'static str {
112        match self {
113            Self::Get => "GET",
114            Self::Post => "POST",
115            Self::Put => "PUT",
116        }
117    }
118}
119
120impl core::fmt::Display for Method {
121    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
122        formatter.write_str(self.as_str())
123    }
124}
125
126/// Where one value of a request travels.
127#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
128pub enum Located {
129    /// In the request target, as a segment of the path.
130    Path,
131    /// In the request target, after the question mark.
132    Query,
133    /// In the JSON body.
134    Body,
135}
136
137/// What kind of value one parameter takes.
138///
139/// Declared rather than left to a consumer to rediscover from the schema,
140/// because a consumer that has to read a value off a command line has to know
141/// what to read it as: `1.15` is a number and `1.15` is also a perfectly good
142/// reason to give.
143#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
144pub enum ValueKind {
145    /// Text, taken as it was given.
146    Text,
147    /// A number, whole or otherwise.
148    Number,
149    /// A whole number.
150    Integer,
151    /// True or false.
152    Boolean,
153    /// A document rather than a scalar.
154    Structured,
155}
156
157impl ValueKind {
158    /// Whether a value of this kind is a document rather than a scalar.
159    #[must_use]
160    pub const fn structured(self) -> bool {
161        matches!(self, Self::Structured)
162    }
163}
164
165/// One value declared beside an operation, at one place in its request.
166///
167/// Only the operations whose body is not one action of the vocabulary declare
168/// their values this way; a mutating operation's are the fields the contracts'
169/// own `PrintAction` declares for the variant it names.
170#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
171pub struct Declared {
172    /// What it is called, spelled as the wire spells it.
173    pub name: &'static str,
174    /// Whether a request without it is refused.
175    pub required: bool,
176    /// What kind of value it takes.
177    pub kind: ValueKind,
178    /// The contracts' own type it is a value of, when it is one of theirs.
179    ///
180    /// A consumer generating a typed client needs the type rather than the
181    /// kind: [`ValueKind::Structured`] says a manifest is a document, and not
182    /// that it is a `JobManifest`. A value this system mints no type for — a
183    /// count, a reason — declares none.
184    pub shape: Option<&'static str>,
185    /// Whether a request may carry it more than once, each a value of its
186    /// own: only a query value can be, and it is then a list of its kind.
187    pub repeated: bool,
188}
189
190impl Declared {
191    /// One value carried at most once, of a kind and of no named type.
192    #[must_use]
193    pub const fn once(name: &'static str, required: bool, kind: ValueKind) -> Self {
194        Self {
195            name,
196            required,
197            kind,
198            shape: None,
199            repeated: false,
200        }
201    }
202}
203
204/// One value a request to an operation carries.
205#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
206pub struct Parameter {
207    /// What it is called, spelled as the wire spells it.
208    pub name: String,
209    /// Whether a request without it is refused.
210    pub required: bool,
211    /// Where it travels.
212    pub located: Located,
213    /// What kind of value it takes.
214    pub kind: ValueKind,
215    /// Whether a request may carry it more than once, each a value of its own.
216    pub repeated: bool,
217}
218
219/// One answer a route can produce.
220#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
221pub enum Answer {
222    /// The operation was carried out, or the read was answered.
223    Success,
224    /// The policy rejected the action, and the rejection is the answer.
225    Rejected,
226}
227
228impl Answer {
229    /// Its own name, for a report that walks the answers of a route.
230    #[must_use]
231    pub const fn as_str(self) -> &'static str {
232        match self {
233            Self::Success => "success",
234            Self::Rejected => "rejected",
235        }
236    }
237}
238
239impl core::fmt::Display for Answer {
240    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
241        formatter.write_str(self.as_str())
242    }
243}
244
245/// What one operation does to the machine or the record.
246#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
247pub enum Effect {
248    /// It reads, and changes nothing.
249    Read,
250    /// It changes something, so it carries a reason and passes the policy.
251    Mutating(ActionKind),
252    /// It asks the spool ledger for one command, so it carries a reason and
253    /// passes the grants every action passes — and asks nothing of the
254    /// machine. Its kind is one of the ledger's five and no print action.
255    Command(SpoolCommandKind),
256    /// It asks the printer for one recovery action, so it carries a reason
257    /// and passes the recovery grants — and names no print: what it moves is
258    /// the printer, whatever the last print left on its bed.
259    Recovery(RecoveryActionKind),
260    /// It writes a record without asking anything of the machine.
261    Write,
262}
263
264/// One command of the spool ledger's vocabulary, and nothing else.
265///
266/// A kind of its own rather than the whole [`ActionKind`], so that an
267/// operation declared as a spool command cannot name a print action: the
268/// grants rule on the [`ActionKind`] it answers, and the body is read from the
269/// `SpoolCommand` variant that kind tags.
270#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
271pub enum SpoolCommandKind {
272    /// Register a spool.
273    RegisterSpool,
274    /// Load a spool onto a tool.
275    LoadSpool,
276    /// Unload a spool from its tool.
277    UnloadSpool,
278    /// Correct a spool's figure.
279    AdjustSpool,
280    /// Retire a spool.
281    RetireSpool,
282}
283
284impl SpoolCommandKind {
285    /// Every command of the ledger, in the order the contracts declare them.
286    pub const ALL: [Self; 5] = [
287        Self::RegisterSpool,
288        Self::LoadSpool,
289        Self::UnloadSpool,
290        Self::AdjustSpool,
291        Self::RetireSpool,
292    ];
293
294    /// The action kind the envelope grants this command under.
295    #[must_use]
296    pub const fn action_kind(self) -> ActionKind {
297        match self {
298            Self::RegisterSpool => ActionKind::RegisterSpool,
299            Self::LoadSpool => ActionKind::LoadSpool,
300            Self::UnloadSpool => ActionKind::UnloadSpool,
301            Self::AdjustSpool => ActionKind::AdjustSpool,
302            Self::RetireSpool => ActionKind::RetireSpool,
303        }
304    }
305}
306
307/// One public operation: what it is called, how it is reached, and what it does.
308#[derive(Debug, Clone, Copy, PartialEq, Eq)]
309pub struct Operation {
310    /// The operation's own name. For a mutating operation this is the spelling
311    /// the contracts' own `PrintAction` tags that variant with.
312    pub name: &'static str,
313    /// The method it is reached by.
314    pub method: Method,
315    /// Its path beneath [`VERSION_PREFIX`].
316    pub path: &'static str,
317    /// What it does.
318    pub effect: Effect,
319    /// The media type it takes a body in, when it takes one.
320    pub accepts: Option<&'static str>,
321    /// The media type it answers in.
322    pub answers: &'static str,
323    /// The values it takes after the question mark.
324    pub query: &'static [Declared],
325    /// The values it takes in its body, for an operation whose body is not one
326    /// action of the vocabulary. A mutating operation declares none here: its
327    /// body is the `PrintAction` or `SpoolCommand` variant it names, read from
328    /// the contracts themselves by [`Operation::request`].
329    pub body: &'static [Declared],
330    /// The field of its answer carrying an absolute path to a materialized
331    /// image, when its answer carries one.
332    ///
333    /// Every image answer this server gives is a path on **this server's own
334    /// filesystem** and no route of it answers image bytes, so a consumer
335    /// reading this field is reading which of its values names a file it may
336    /// not be able to open. Declared here rather than discovered, because what
337    /// a consumer owes such a field is a failure of its own.
338    pub image_path_field: Option<&'static str>,
339    /// The operation a request to this one is made to instead when it names
340    /// no print, for a read of one print that has a form for the printer as a
341    /// whole.
342    ///
343    /// The command made from this operation takes its print as optional, and
344    /// the operation named here has no command of its own: it is reached
345    /// through this one's. It takes no value this operation does not, less
346    /// the print.
347    pub printer_wide: Option<&'static Operation>,
348    /// Whether a call may name no print, and is then made under a print
349    /// identifier the calling program mints.
350    ///
351    /// For the one operation that opens a print of its own when none is open:
352    /// a caller starting a first print has no print to name, and an
353    /// identifier it had to make up is one it gets wrong. What the answer
354    /// names is the print the operation ran under.
355    pub mints_print: bool,
356}
357
358impl Operation {
359    /// Its whole path, including the versioned prefix.
360    #[must_use]
361    pub fn full_path(&self) -> String {
362        format!("{VERSION_PREFIX}{}", self.path)
363    }
364
365    /// Which print action this operation asks for, when it asks for one.
366    #[must_use]
367    pub const fn action_kind(&self) -> Option<ActionKind> {
368        match self.effect {
369            Effect::Mutating(kind) => Some(kind),
370            _ => None,
371        }
372    }
373
374    /// Which spool command this operation asks for, when it asks for one.
375    #[must_use]
376    pub const fn command_kind(&self) -> Option<ActionKind> {
377        match self.effect {
378            Effect::Command(kind) => Some(kind.action_kind()),
379            _ => None,
380        }
381    }
382
383    /// Which action of either vocabulary this operation asks for, when it asks
384    /// for one: the kind the envelope grants it under.
385    #[must_use]
386    pub const fn granted_as(&self) -> Option<ActionKind> {
387        match self.effect {
388            Effect::Mutating(kind) => Some(kind),
389            Effect::Command(kind) => Some(kind.action_kind()),
390            Effect::Read | Effect::Write | Effect::Recovery(_) => None,
391        }
392    }
393
394    /// Which recovery action this operation asks for, when it asks for one:
395    /// the kind the recovery grants rule on.
396    #[must_use]
397    pub const fn recovery_kind(&self) -> Option<RecoveryActionKind> {
398        match self.effect {
399            Effect::Recovery(kind) => Some(kind),
400            _ => None,
401        }
402    }
403
404    /// Whether this operation changes something.
405    ///
406    /// Asking the machine for an action and replacing the manifest a print runs
407    /// under are both changes, and both carry a reason. What separates them is
408    /// whether the policy has anything to rule on — not whether the caller has
409    /// to say why.
410    #[must_use]
411    pub const fn is_mutating(&self) -> bool {
412        matches!(
413            self.effect,
414            Effect::Mutating(_) | Effect::Command(_) | Effect::Recovery(_) | Effect::Write
415        )
416    }
417
418    /// Every value a request to this operation carries, and where it carries it.
419    ///
420    /// The body of a mutating operation is not written out anywhere: it is the
421    /// fields the contracts' own `PrintAction` or `SpoolCommand` declares for
422    /// the variant this operation names, read from that type's own schema,
423    /// less the tag and any value the path already carries. A variant that
424    /// gains a field gains it here without this file changing, which is what
425    /// stops a consumer building a request surface from drifting from the
426    /// vocabulary.
427    ///
428    /// # Panics
429    ///
430    /// Panics when the contracts declare no variant this operation names, which
431    /// is a declared list and a closed type that have come apart.
432    #[must_use]
433    pub fn request(&self) -> Vec<Parameter> {
434        let mut found = path_parameters(self.path);
435        found.extend(declared(self.query, Located::Query));
436        match Vocabulary::of(self.effect) {
437            Some((vocabulary, kind)) => {
438                let routed: Vec<String> = found.iter().map(|path| path.name.clone()).collect();
439                found.extend(
440                    action_parameters(vocabulary, &kind)
441                        .into_iter()
442                        .filter(|field| !routed.contains(&field.name)),
443                );
444            }
445            None => found.extend(declared(self.body, Located::Body)),
446        }
447        found
448    }
449
450    /// Every value a request to this operation carries, with its own shape.
451    ///
452    /// [`Operation::request`] answers what a command line needs — a name, a
453    /// place and a kind. This answers what a **typed** consumer needs beside
454    /// that: the shape of each value, as a schema referring to the contracts'
455    /// own types by name where the value is one of theirs. `structured` says a
456    /// manifest is a document; `{"$ref": "#/$defs/JobManifest"}` says which
457    /// document, which is the difference between a generated client that types
458    /// it and one that takes anything.
459    ///
460    /// The order is [`Operation::request`]'s own, so the two can be read side
461    /// by side.
462    ///
463    /// # Panics
464    ///
465    /// Panics when the contracts declare no variant this operation names, which
466    /// is a declared list and a closed type that have come apart.
467    #[must_use]
468    pub fn request_shapes(&self) -> Vec<(Parameter, Value)> {
469        let action = match Vocabulary::of(self.effect) {
470            Some((vocabulary, kind)) => action_shapes(vocabulary, &kind),
471            None => Vec::new(),
472        };
473        self.request()
474            .into_iter()
475            .map(|parameter| {
476                let shape = match parameter.located {
477                    // What makes a path segment an identifier is the type that
478                    // minted it, and a route mints nothing: it is a string.
479                    Located::Path => json!({ "type": "string" }),
480                    Located::Query => declared_shape(self.query, &parameter.name),
481                    Located::Body if action.is_empty() => {
482                        declared_shape(self.body, &parameter.name)
483                    }
484                    Located::Body => action
485                        .iter()
486                        .find(|(name, _)| *name == parameter.name)
487                        .map_or_else(
488                            || {
489                                panic!(
490                                    "`{}` takes `{}` in its body, and the action it names \
491                                     declares no such field",
492                                    self.name, parameter.name
493                                )
494                            },
495                            |(_, shape)| shape.clone(),
496                        ),
497                };
498                (parameter, shape)
499            })
500            .collect()
501    }
502
503    /// Every answer this operation can produce.
504    ///
505    /// A read answers what it read. An operation asking for an action answers
506    /// that as well as the policy's own rejection, which is an answer rather
507    /// than a transport failure: it carries the reason, the value asked for and
508    /// the range allowed.
509    #[must_use]
510    pub const fn answers_with(&self) -> &'static [Answer] {
511        match self.effect {
512            Effect::Mutating(_) | Effect::Command(_) | Effect::Recovery(_) => {
513                &[Answer::Success, Answer::Rejected]
514            }
515            Effect::Read | Effect::Write => &[Answer::Success],
516        }
517    }
518
519    /// The schema of one answer this operation produces.
520    ///
521    /// A rejection is the same shape as an acceptance and deliberately so: the
522    /// answer to a rejected action is the action record carrying the policy's
523    /// own decision, rather than a second document a caller has to know about.
524    ///
525    /// # Panics
526    ///
527    /// Panics when this operation is not one this server serves an answer
528    /// shape for, which is a declared list and a router that have come apart.
529    #[must_use]
530    pub fn response_schema(&self, answer: Answer) -> Value {
531        use printobserver_types::schemars::schema_for;
532        debug_assert!(
533            self.answers_with().contains(&answer),
534            "`{}` produces no {answer} answer",
535            self.name
536        );
537        let schema = match (self.name, self.effect) {
538            (_, Effect::Mutating(_)) => schema_for!(crate::wire::ActionAnswer),
539            (_, Effect::Command(_)) => schema_for!(crate::wire::SpoolCommandAnswer),
540            (_, Effect::Recovery(_)) => schema_for!(crate::wire::RecoveryAnswer),
541            (RECOVERY_STATUS, _) => schema_for!(crate::wire::RecoveryStatusAnswer),
542            ("spools", _) => schema_for!(crate::wire::SpoolsAnswer),
543            ("spool", _) => schema_for!(crate::wire::SpoolAnswer),
544            ("printer_history", _) => schema_for!(crate::wire::TimelineAnswer),
545            ("preflight", _) => schema_for!(crate::wire::PreflightAnswer),
546            ("prints", _) => schema_for!(crate::wire::PrintsAnswer),
547            ("status", _) => schema_for!(crate::wire::StatusAnswer),
548            ("context", _) => schema_for!(crate::wire::ContextAnswer),
549            ("image", _) => schema_for!(crate::wire::ImageAnswer),
550            ("history", _) => schema_for!(crate::wire::HistoryAnswer),
551            ("events", _) => schema_for!(crate::wire::EventsAnswer),
552            ("look" | "printer_look", _) => schema_for!(crate::wire::LookAnswer),
553            ("manifest_get" | "manifest_set", _) => schema_for!(crate::wire::ManifestAnswer),
554            (BED_CLEAR, _) => schema_for!(crate::wire::BedClearAnswer),
555            (RECHECK_CAMERA, _) => schema_for!(crate::wire::RecheckCameraAnswer),
556            (name, _) => panic!("the operation `{name}` has no declared answer shape"),
557        };
558        schema.to_value()
559    }
560}
561
562/// The values declared beside an operation, at one place in the request.
563fn declared(entries: &'static [Declared], located: Located) -> impl Iterator<Item = Parameter> {
564    entries.iter().map(move |entry| Parameter {
565        name: entry.name.to_owned(),
566        required: entry.required,
567        located,
568        kind: entry.kind,
569        repeated: entry.repeated,
570    })
571}
572
573/// The shape one value declared beside an operation carries.
574///
575/// The contracts' own type where the declaration names one, and the kind's own
576/// scalar shape where it names none — a reason and a count are values this
577/// system mints no type for.
578fn declared_shape(entries: &'static [Declared], name: &str) -> Value {
579    let Some(entry) = entries.iter().find(|entry| entry.name == name) else {
580        return json!({ "type": "string" });
581    };
582    let one = if let Some(shape) = entry.shape {
583        json!({ "$ref": format!("#/$defs/{shape}") })
584    } else {
585        match entry.kind {
586            ValueKind::Text => json!({ "type": "string" }),
587            ValueKind::Number => json!({ "type": "number" }),
588            ValueKind::Integer => json!({ "type": "integer" }),
589            ValueKind::Boolean => json!({ "type": "boolean" }),
590            ValueKind::Structured => json!({ "type": "object" }),
591        }
592    };
593    // A value a request may carry more than once is a list of its kind, which
594    // is what a typed consumer sends it as.
595    if entry.repeated {
596        json!({ "type": "array", "items": one })
597    } else {
598        one
599    }
600}
601
602/// Which of the contracts' two closed vocabularies one mutating operation's
603/// body is a variant of.
604#[derive(Debug, Clone, Copy, PartialEq, Eq)]
605enum Vocabulary {
606    /// The print actions, tagged by `action`.
607    Actions,
608    /// The spool ledger's commands, tagged by `command`.
609    Commands,
610    /// The recovery actions, tagged by `action`, each carried beside the
611    /// actor and the reason every request carries.
612    Recovery,
613}
614
615impl Vocabulary {
616    /// The vocabulary one effect's body is read from, and the variant it names.
617    fn of(effect: Effect) -> Option<(Self, String)> {
618        let tag = |kind: ActionKind| {
619            printobserver_types::serde_json::to_value(kind)
620                .ok()
621                .and_then(|value| value.as_str().map(str::to_owned))
622                .unwrap_or_else(|| panic!("`{kind:?}` renders as the tag it is spelled by"))
623        };
624        match effect {
625            Effect::Mutating(kind) => Some((Self::Actions, tag(kind))),
626            Effect::Command(kind) => Some((Self::Commands, tag(kind.action_kind()))),
627            Effect::Recovery(kind) => Some((Self::Recovery, kind.as_str().to_owned())),
628            Effect::Read | Effect::Write => None,
629        }
630    }
631
632    /// The field the vocabulary's tag travels in.
633    const fn tag(self) -> &'static str {
634        match self {
635            Self::Actions | Self::Recovery => ACTION_TAG,
636            Self::Commands => COMMAND_TAG,
637        }
638    }
639
640    /// The vocabulary's own schema, as the contracts declare it.
641    ///
642    /// A recovery action names neither who asks nor why — those are the
643    /// request's, not the action's — so its request body is each variant of
644    /// the contracts' own `RecoveryAction` with the two beside it.
645    fn schema(self) -> Value {
646        use printobserver_types::schemars::schema_for;
647        match self {
648            Self::Actions => schema_for!(PrintAction).to_value(),
649            Self::Commands => schema_for!(SpoolCommand).to_value(),
650            Self::Recovery => recovery_request_schema(),
651        }
652    }
653}
654
655/// The contracts' own `RecoveryAction`, each variant carrying the actor and
656/// the reason a recovery request carries beside it.
657fn recovery_request_schema() -> Value {
658    use printobserver_types::schemars::schema_for;
659    let mut schema = schema_for!(RecoveryAction).to_value();
660    let actor = schema_for!(printobserver_core::Actor).to_value();
661    if let Some(variants) = schema.get_mut("oneOf").and_then(Value::as_array_mut) {
662        for variant in variants {
663            if let Some(properties) = variant.get_mut("properties").and_then(Value::as_object_mut) {
664                properties.insert(
665                    "actor".to_owned(),
666                    json!({ "$ref": "#/$defs/Actor", "description": "Who is asking." }),
667                );
668                properties.insert(
669                    "reason".to_owned(),
670                    json!({ "type": "string", "description": "Why the actor is asking for this." }),
671                );
672            }
673            if let Some(required) = variant.get_mut("required").and_then(Value::as_array_mut) {
674                required.push(json!("actor"));
675                required.push(json!("reason"));
676            }
677        }
678    }
679    let defs = schema
680        .as_object_mut()
681        .map(|top| top.entry("$defs").or_insert_with(|| json!({})));
682    if let Some(Value::Object(defs)) = defs {
683        if let Some(Value::Object(nested)) = actor.get("$defs") {
684            for (name, shape) in nested {
685                defs.insert(name.clone(), shape.clone());
686            }
687        }
688        let mut own = actor.clone();
689        if let Some(top) = own.as_object_mut() {
690            top.remove("$defs");
691            top.remove("$schema");
692        }
693        defs.insert("Actor".to_owned(), own);
694    }
695    schema
696}
697
698/// The shape of each field one action of the vocabulary takes.
699///
700/// Read out of the contracts' own `PrintAction` or `SpoolCommand` beside
701/// [`action_parameters`], which walks the same variant for the same fields —
702/// so a field that gains a shape here gains a parameter there, and neither can
703/// carry one the other does not.
704///
705/// # Panics
706///
707/// Panics when the contracts declare no variant tagged with this action.
708fn action_shapes(vocabulary: Vocabulary, kind: &str) -> Vec<(String, Value)> {
709    let schema = vocabulary.schema();
710    let variant = action_variant(&schema, vocabulary, kind);
711    variant
712        .get("properties")
713        .and_then(Value::as_object)
714        .unwrap_or_else(|| panic!("the action `{kind}` declares no properties"))
715        .iter()
716        .filter(|(name, _)| name.as_str() != vocabulary.tag())
717        .map(|(name, field)| (name.clone(), field.clone()))
718        .collect()
719}
720
721/// The variant of the contracts' own action vocabulary one action tags.
722///
723/// # Panics
724///
725/// Panics when the contracts declare no variant tagged with this action, which
726/// is this server's declared list and that closed type having come apart.
727fn action_variant(schema: &Value, vocabulary: Vocabulary, tag: &str) -> Value {
728    schema
729        .get("oneOf")
730        .and_then(Value::as_array)
731        .and_then(|variants| {
732            variants.iter().find(|variant| {
733                variant.pointer(&format!("/properties/{}/const", vocabulary.tag()))
734                    == Some(&json!(tag))
735            })
736        })
737        .cloned()
738        .unwrap_or_else(|| panic!("the contracts declare no action tagged `{tag}`"))
739}
740
741/// The values one path template takes, in the order it takes them.
742fn path_parameters(path: &str) -> Vec<Parameter> {
743    path.split('/')
744        .filter_map(|segment| segment.strip_prefix('{')?.strip_suffix('}'))
745        .map(|name| Parameter {
746            name: name.to_owned(),
747            // A route with a hole in its path is not a route: nothing reaches
748            // the handler without every segment of it.
749            required: true,
750            located: Located::Path,
751            // A path segment is text: what makes one an identifier is the type
752            // that minted it rather than anything a route can say.
753            kind: ValueKind::Text,
754            repeated: false,
755        })
756        .collect()
757}
758
759/// The body one action of the vocabulary takes, out of the contracts' own type.
760///
761/// # Panics
762///
763/// Panics when the contracts declare no variant tagged with this action, which
764/// is this server's declared list and that closed type having come apart.
765fn action_parameters(vocabulary: Vocabulary, kind: &str) -> Vec<Parameter> {
766    let schema = vocabulary.schema();
767    let variant = action_variant(&schema, vocabulary, kind);
768    let required: Vec<&str> = variant
769        .get("required")
770        .and_then(Value::as_array)
771        .map(|names| names.iter().filter_map(Value::as_str).collect())
772        .unwrap_or_default();
773    let properties = variant
774        .get("properties")
775        .and_then(Value::as_object)
776        .unwrap_or_else(|| panic!("the action `{kind}` declares no properties"));
777    properties
778        .iter()
779        .filter(|(name, _)| name.as_str() != vocabulary.tag())
780        .map(|(name, field)| Parameter {
781            name: name.clone(),
782            required: required.contains(&name.as_str()),
783            located: Located::Body,
784            kind: kind_of(&resolve(&schema, field)),
785            repeated: false,
786        })
787        .collect()
788}
789
790/// One field's own schema, following the one reference a contract field takes.
791fn resolve(schema: &Value, field: &Value) -> Value {
792    let Some(reference) = field.get("$ref").and_then(Value::as_str) else {
793        return field.clone();
794    };
795    reference
796        .strip_prefix("#/")
797        .and_then(|rest| schema.pointer(&format!("/{rest}")))
798        .cloned()
799        .unwrap_or_else(|| field.clone())
800}
801
802/// What kind of value one shape describes.
803///
804/// Read off the shape rather than off the field's name: a closed set of string
805/// constants is text however many of them there are, and an object is a
806/// document however few fields it has. A shape that says nothing this can
807/// decide is a document, which is the reading that still lets a caller supply
808/// it — as itself, or out of a file.
809fn kind_of(shape: &Value) -> ValueKind {
810    if let Some(declared) = shape.get("type") {
811        let named = |name: &str| match declared {
812            Value::String(one) => one == name,
813            Value::Array(many) => many.iter().any(|one| one == name),
814            _ => false,
815        };
816        if named("object") || named("array") {
817            return ValueKind::Structured;
818        }
819        if named("string") {
820            return ValueKind::Text;
821        }
822        if named("integer") {
823            return ValueKind::Integer;
824        }
825        if named("number") {
826            return ValueKind::Number;
827        }
828        if named("boolean") {
829            return ValueKind::Boolean;
830        }
831    }
832    match shape.get("oneOf").or_else(|| shape.get("anyOf")) {
833        Some(Value::Array(branches)) if !branches.is_empty() => {
834            let kinds: Vec<ValueKind> = branches
835                .iter()
836                .map(|branch| match branch.get("const") {
837                    Some(Value::String(_)) => ValueKind::Text,
838                    _ => kind_of(branch),
839                })
840                .collect();
841            let first = kinds[0];
842            if kinds.iter().all(|kind| *kind == first) {
843                first
844            } else {
845                ValueKind::Structured
846            }
847        }
848        _ => ValueKind::Structured,
849    }
850}
851
852/// One mutating operation, at the path its action is asked for under.
853const fn action(name: &'static str, path: &'static str, kind: ActionKind) -> Operation {
854    Operation {
855        name,
856        method: Method::Post,
857        path,
858        effect: Effect::Mutating(kind),
859        accepts: Some(MEDIA_TYPE),
860        answers: MEDIA_TYPE,
861        query: &[],
862        body: &[],
863        image_path_field: None,
864        printer_wide: None,
865        mints_print: false,
866    }
867}
868
869/// One spool command, at the path its command is asked for under.
870const fn command(name: &'static str, path: &'static str, kind: SpoolCommandKind) -> Operation {
871    Operation {
872        effect: Effect::Command(kind),
873        ..action(name, path, kind.action_kind())
874    }
875}
876
877/// One recovery action, at the path it is asked for under.
878const fn recovery(name: &'static str, path: &'static str, kind: RecoveryActionKind) -> Operation {
879    Operation {
880        name,
881        method: Method::Post,
882        path,
883        effect: Effect::Recovery(kind),
884        accepts: Some(MEDIA_TYPE),
885        answers: MEDIA_TYPE,
886        query: &[],
887        body: &[],
888        image_path_field: None,
889        printer_wide: None,
890        mints_print: false,
891    }
892}
893
894/// One read, which takes no body.
895const fn read(name: &'static str, path: &'static str) -> Operation {
896    Operation {
897        name,
898        method: Method::Get,
899        path,
900        effect: Effect::Read,
901        accepts: None,
902        answers: MEDIA_TYPE,
903        query: &[],
904        body: &[],
905        image_path_field: None,
906        printer_wide: None,
907        mints_print: false,
908    }
909}
910
911/// How one operation's name is spelled as a command of the `printobserver`
912/// program: each underscore a hyphen.
913///
914/// The one spelling both the command-line program's commands and the
915/// supervising agent's allowed commands are made from, so the command the agent
916/// is allowed to run is the command the program has.
917#[must_use]
918pub fn command_for(operation: &str) -> String {
919    operation.replace('_', "-")
920}
921
922/// Every public operation this server serves, and there is no other.
923pub const OPERATIONS: [Operation; 40] = [
924    // Takes nothing: it is how a caller finds the identifier every other
925    // print-specific operation takes.
926    // llmlint: ignore[names_match_behavior] suppressions.toml has the reason.
927    read("prints", "/prints"),
928    read("status", "/prints/{print_id}/status"),
929    // The print's context; asked `since` an event, its recent events are
930    // only those newer than that one.
931    Operation {
932        query: &[
933            // Read into an `EventId`, and refused when it names none.
934            Declared {
935                shape: Some("EventId"),
936                ..Declared::once("since", false, ValueKind::Text)
937            },
938        ],
939        image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
940        ..read("context", "/prints/{print_id}/context")
941    },
942    Operation {
943        image_path_field: Some(IMAGE_PATH_FIELD),
944        ..read("image", "/images/{image_id}")
945    },
946    Operation {
947        query: &[Declared::once("limit", false, ValueKind::Integer)],
948        ..read("history", "/prints/{print_id}/history")
949    },
950    // The event log in the order it was stored, after a cursor: one print's
951    // events and the printer's, or every event, filtered by kind, waiting up
952    // to `wait_s` seconds for one to pass. A read, so it takes no actor.
953    Operation {
954        query: &[
955            Declared::once("after", false, ValueKind::Text),
956            Declared::once("print_id", false, ValueKind::Text),
957            Declared {
958                repeated: true,
959                ..Declared::once("kinds", false, ValueKind::Text)
960            },
961            Declared {
962                repeated: true,
963                ..Declared::once("exclude_kinds", false, ValueKind::Text)
964            },
965            Declared::once("wait_s", false, ValueKind::Integer),
966            Declared::once("limit", false, ValueKind::Integer),
967        ],
968        ..read("events", "/events")
969    },
970    read("manifest_get", "/prints/{print_id}/manifest"),
971    // A fresh look: waits up to `wait_s` seconds for something to arrive for
972    // the print, returning the moment something does, then takes a frame and
973    // reads the printer as it is now. A read, so it takes no actor. Asked
974    // with no print named, it is the printer's look below.
975    Operation {
976        query: &[Declared::once("wait_s", false, ValueKind::Integer)],
977        image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
978        printer_wide: Some(&PRINTER_LOOK_OPERATION),
979        mints_print: false,
980        ..read("look", "/prints/{print_id}/look")
981    },
982    PRINTER_LOOK_OPERATION,
983    Operation {
984        name: "manifest_set",
985        method: Method::Put,
986        path: "/prints/{print_id}/manifest",
987        effect: Effect::Write,
988        accepts: Some(MEDIA_TYPE),
989        answers: MEDIA_TYPE,
990        query: &[],
991        body: &[
992            Declared::once("reason", true, ValueKind::Text),
993            Declared {
994                shape: Some("JobManifest"),
995                ..Declared::once("manifest", true, ValueKind::Structured)
996            },
997        ],
998        image_path_field: None,
999        printer_wide: None,
1000        mints_print: false,
1001    },
1002    // Every spool, the retired ones only when asked for, each beside one line
1003    // saying what it holds — and the charges held for a tool after a filament
1004    // change nobody has confirmed.
1005    Operation {
1006        query: &[Declared::once("include_retired", false, ValueKind::Boolean)],
1007        ..read("spools", "/spools")
1008    },
1009    read("spool", "/spools/{spool_id}"),
1010    // The printer's own history: every print, charge and spool event, newest
1011    // first, a page at a time. Named for the printer rather than for a print,
1012    // because `history` is one print's.
1013    Operation {
1014        query: &[
1015            Declared {
1016                repeated: true,
1017                ..Declared::once("kinds", false, ValueKind::Text)
1018            },
1019            Declared::once("since", false, ValueKind::Text),
1020            Declared::once("until", false, ValueKind::Text),
1021            Declared::once("spool_id", false, ValueKind::Text),
1022            Declared::once("before", false, ValueKind::Text),
1023            Declared::once("limit", false, ValueKind::Integer),
1024        ],
1025        ..read("printer_history", "/history")
1026    },
1027    // Whether the spools loaded hold enough for one file, were it sliced for
1028    // their material, and — given a sheet — whether that sheet suits it, read
1029    // now: it records nothing and starts nothing.
1030    Operation {
1031        query: &[
1032            Declared::once("file_name", true, ValueKind::Text),
1033            // Read into a `SheetId`, and refused when blank.
1034            Declared {
1035                shape: Some("SheetId"),
1036                ..Declared::once("sheet", false, ValueKind::Text)
1037            },
1038        ],
1039        ..read("preflight", "/preflight")
1040    },
1041    action(
1042        "pause",
1043        "/prints/{print_id}/actions/pause",
1044        ActionKind::Pause,
1045    ),
1046    action(
1047        "resume",
1048        "/prints/{print_id}/actions/resume",
1049        ActionKind::Resume,
1050    ),
1051    action(
1052        "cancel",
1053        "/prints/{print_id}/actions/cancel",
1054        ActionKind::Cancel,
1055    ),
1056    // A first start has no print to name, so one is minted for it.
1057    Operation {
1058        mints_print: true,
1059        ..action(
1060            "start_print",
1061            "/prints/{print_id}/actions/start_print",
1062            ActionKind::StartPrint,
1063        )
1064    },
1065    action(
1066        "set_feedrate_factor",
1067        "/prints/{print_id}/actions/set_feedrate_factor",
1068        ActionKind::SetFeedrateFactor,
1069    ),
1070    action(
1071        "set_flowrate_factor",
1072        "/prints/{print_id}/actions/set_flowrate_factor",
1073        ActionKind::SetFlowrateFactor,
1074    ),
1075    action(
1076        "set_tool_target_c",
1077        "/prints/{print_id}/actions/set_tool_target_c",
1078        ActionKind::SetToolTargetC,
1079    ),
1080    action(
1081        "set_bed_target_c",
1082        "/prints/{print_id}/actions/set_bed_target_c",
1083        ActionKind::SetBedTargetC,
1084    ),
1085    action(
1086        "set_fan_percent",
1087        "/prints/{print_id}/actions/set_fan_percent",
1088        ActionKind::SetFanPercent,
1089    ),
1090    action(
1091        "acknowledge_failure",
1092        "/prints/{print_id}/actions/acknowledge_failure",
1093        ActionKind::AcknowledgeFailure,
1094    ),
1095    // Closes a record printobserver left open, asking nothing of the machine.
1096    action(
1097        "close_print",
1098        "/prints/{print_id}/actions/close_print",
1099        ActionKind::ClosePrint,
1100    ),
1101    command(
1102        "register_spool",
1103        "/spools/actions/register_spool",
1104        SpoolCommandKind::RegisterSpool,
1105    ),
1106    command(
1107        "load_spool",
1108        "/spools/{spool_id}/actions/load_spool",
1109        SpoolCommandKind::LoadSpool,
1110    ),
1111    command(
1112        "unload_spool",
1113        "/spools/{spool_id}/actions/unload_spool",
1114        SpoolCommandKind::UnloadSpool,
1115    ),
1116    command(
1117        "adjust_spool",
1118        "/spools/{spool_id}/actions/adjust_spool",
1119        SpoolCommandKind::AdjustSpool,
1120    ),
1121    command(
1122        "retire_spool",
1123        "/spools/{spool_id}/actions/retire_spool",
1124        SpoolCommandKind::RetireSpool,
1125    ),
1126    // What every recovery action is checked against now, and what each would
1127    // meet. The printer's rather than a print's, so it takes no print.
1128    read(RECOVERY_STATUS, "/printer/recovery"),
1129    recovery(
1130        "recover_lift",
1131        "/printer/recovery/recover_lift",
1132        RecoveryActionKind::RecoverLift,
1133    ),
1134    recovery(
1135        "recover_cool",
1136        "/printer/recovery/recover_cool",
1137        RecoveryActionKind::RecoverCool,
1138    ),
1139    recovery(
1140        "recover_fan",
1141        "/printer/recovery/recover_fan",
1142        RecoveryActionKind::RecoverFan,
1143    ),
1144    recovery(
1145        "recover_heat",
1146        "/printer/recovery/recover_heat",
1147        RecoveryActionKind::RecoverHeat,
1148    ),
1149    recovery(
1150        "recover_park",
1151        "/printer/recovery/recover_park",
1152        RecoveryActionKind::RecoverPark,
1153    ),
1154    recovery(
1155        "recover_home_xy",
1156        "/printer/recovery/recover_home_xy",
1157        RecoveryActionKind::RecoverHomeXy,
1158    ),
1159    recovery(
1160        "recover_home_z",
1161        "/printer/recovery/recover_home_z",
1162        RecoveryActionKind::RecoverHomeZ,
1163    ),
1164    // The operator's word that the bed is clear, which every recovery needing
1165    // the bed or the nozzle clear is decided on until the next print starts.
1166    // The printer's rather than a print's, and asks nothing of the machine.
1167    Operation {
1168        name: BED_CLEAR,
1169        method: Method::Post,
1170        path: "/printer/bed_clear",
1171        effect: Effect::Write,
1172        accepts: Some(MEDIA_TYPE),
1173        answers: MEDIA_TYPE,
1174        query: &[],
1175        body: &[
1176            Declared {
1177                shape: Some("Actor"),
1178                ..Declared::once("actor", true, ValueKind::Structured)
1179            },
1180            Declared::once("reason", true, ValueKind::Text),
1181        ],
1182        image_path_field: None,
1183        printer_wide: None,
1184        mints_print: false,
1185    },
1186    // Judges a print's camera again on a fresh frame — its view and its
1187    // first-layer alignment, a latched verdict included — and asks nothing of
1188    // the machine.
1189    Operation {
1190        name: RECHECK_CAMERA,
1191        method: Method::Post,
1192        path: "/prints/{print_id}/camera/recheck",
1193        effect: Effect::Write,
1194        accepts: Some(MEDIA_TYPE),
1195        answers: MEDIA_TYPE,
1196        query: &[],
1197        body: &[
1198            Declared {
1199                shape: Some("Actor"),
1200                ..Declared::once("actor", true, ValueKind::Structured)
1201            },
1202            Declared::once("reason", true, ValueKind::Text),
1203        ],
1204        image_path_field: Some(RECHECK_FRAME_PATH_FIELD),
1205        printer_wide: None,
1206        mints_print: false,
1207    },
1208];
1209
1210/// The operator's word that the bed is clear, recorded beside the recovery
1211/// vocabulary it is decided into.
1212pub const BED_CLEAR: &str = "bed_clear";
1213
1214/// A print's camera judged again on a fresh frame.
1215pub const RECHECK_CAMERA: &str = "recheck_camera";
1216
1217/// The field a recheck of the camera carries its fresh frame's own path in.
1218pub const RECHECK_FRAME_PATH_FIELD: &str = "frame_path";
1219
1220/// The read beside the recovery vocabulary: what every recovery action is
1221/// checked against now, and what each would meet.
1222pub const RECOVERY_STATUS: &str = "recover_status";
1223
1224/// The sixteen operations this server serves beside the vocabularies.
1225///
1226/// Thirteen of them read, one writes a manifest, one records the operator's
1227/// word that the bed is clear and one judges a print's camera again on a fresh
1228/// frame, none of which asks anything of the machine;
1229/// what they have in common is that none of them is an action, a spool command
1230/// or a recovery action the contracts declare. A look writes its own record into the
1231/// print's history — or the printer's, for a look at the printer — as every
1232/// read of the camera is kept, and asks nothing of the machine either; a
1233/// filament check records nothing at all.
1234pub const BESIDE_THE_ACTIONS: [&str; 16] = [
1235    "prints",
1236    "status",
1237    "context",
1238    "image",
1239    "history",
1240    "events",
1241    "manifest_get",
1242    "look",
1243    PRINTER_LOOK,
1244    "manifest_set",
1245    "spools",
1246    "spool",
1247    "printer_history",
1248    "preflight",
1249    BED_CLEAR,
1250    RECHECK_CAMERA,
1251];
1252
1253/// The look at the printer with no print named, which `look` is asked as when
1254/// it names none.
1255pub const PRINTER_LOOK: &str = "printer_look";
1256
1257/// A fresh look at the printer with no print named: waits `wait_s` seconds, on
1258/// nothing any print's agent is owed, then takes a frame, keeps it as the
1259/// printer's, and reads the printer as it is now. The operator's: a turn's
1260/// credential reaches its own print alone. Declared apart from [`OPERATIONS`],
1261/// which serves it, so the look's [`Operation::printer_wide`] can name it as
1262/// the operation itself rather than by a name that might name none.
1263const PRINTER_LOOK_OPERATION: Operation = Operation {
1264    query: &[Declared::once("wait_s", false, ValueKind::Integer)],
1265    image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
1266    ..read(PRINTER_LOOK, "/look")
1267};
1268
1269/// The operation whose command reaches this one, when this one is another's
1270/// [`Operation::printer_wide`] form and so has no command of its own.
1271#[must_use]
1272pub fn printer_wide_of(name: &str) -> Option<&'static Operation> {
1273    OPERATIONS
1274        .iter()
1275        .find(|declared| declared.printer_wide.is_some_and(|wide| wide.name == name))
1276}
1277
1278/// The operation of one name, when this server serves one.
1279#[must_use]
1280pub fn operation(name: &str) -> Option<&'static Operation> {
1281    OPERATIONS.iter().find(|declared| declared.name == name)
1282}
1283
1284#[cfg(test)]
1285mod tests {
1286    use printobserver_core::ActionKind;
1287
1288    use super::{Effect, MEDIA_TYPE, Method, OPERATIONS, VERSION_PREFIX, operation};
1289
1290    /// Every method is spelled the way the wire spells it.
1291    #[test]
1292    fn every_method_is_spelled_as_the_wire_spells_it() {
1293        for (method, spelling) in [
1294            (Method::Get, "GET"),
1295            (Method::Post, "POST"),
1296            (Method::Put, "PUT"),
1297        ] {
1298            assert_eq!(method.as_str(), spelling);
1299            assert_eq!(method.to_string(), spelling);
1300        }
1301    }
1302
1303    /// An operation's whole path carries the one versioned prefix.
1304    #[test]
1305    fn every_operation_sits_beneath_the_one_versioned_prefix() {
1306        for declared in OPERATIONS {
1307            let whole = declared.full_path();
1308            assert!(
1309                whole.starts_with(VERSION_PREFIX),
1310                "`{}` is served at {whole}",
1311                declared.name
1312            );
1313            assert_eq!(declared.answers, MEDIA_TYPE);
1314        }
1315    }
1316
1317    /// A mutating operation names the action it asks for, and a read names none.
1318    #[test]
1319    fn a_mutating_operation_names_its_action_and_a_read_names_none() {
1320        for declared in OPERATIONS {
1321            match declared.effect {
1322                Effect::Mutating(kind) => {
1323                    assert_eq!(declared.action_kind(), Some(kind));
1324                    assert_eq!(declared.command_kind(), None);
1325                    assert_eq!(declared.granted_as(), Some(kind));
1326                    assert!(declared.is_mutating());
1327                }
1328                Effect::Command(kind) => {
1329                    assert_eq!(declared.action_kind(), None);
1330                    assert_eq!(declared.command_kind(), Some(kind.action_kind()));
1331                    assert_eq!(declared.granted_as(), Some(kind.action_kind()));
1332                    assert!(declared.is_mutating());
1333                }
1334                Effect::Recovery(kind) => {
1335                    assert_eq!(declared.action_kind(), None);
1336                    assert_eq!(declared.granted_as(), None);
1337                    assert_eq!(declared.recovery_kind(), Some(kind));
1338                    assert!(declared.is_mutating());
1339                }
1340                Effect::Write => {
1341                    assert_eq!(declared.action_kind(), None);
1342                    assert!(
1343                        declared.is_mutating(),
1344                        "`{}` writes a record and is not held to the reason every \
1345                         change carries",
1346                        declared.name
1347                    );
1348                }
1349                Effect::Read => {
1350                    assert_eq!(declared.action_kind(), None);
1351                    assert!(!declared.is_mutating());
1352                }
1353            }
1354        }
1355    }
1356
1357    /// A mutating operation takes JSON and answers JSON; a read takes no body.
1358    ///
1359    /// The two constructors are the only way an entry of the declared list is
1360    /// made, so this is the shape every entry has by construction.
1361    #[test]
1362    fn a_mutating_operation_takes_a_body_and_a_read_takes_none() {
1363        let mutating = super::action(
1364            "pause",
1365            "/prints/{print_id}/actions/pause",
1366            ActionKind::Pause,
1367        );
1368        assert_eq!(mutating.method, Method::Post);
1369        assert_eq!(mutating.accepts, Some(MEDIA_TYPE));
1370        assert_eq!(mutating.answers, MEDIA_TYPE);
1371        assert_eq!(mutating.action_kind(), Some(ActionKind::Pause));
1372
1373        let reading = super::read("status", "/prints/{print_id}/status");
1374        assert_eq!(reading.method, Method::Get);
1375        assert_eq!(reading.accepts, None);
1376        assert_eq!(reading.answers, MEDIA_TYPE);
1377        assert_eq!(reading.effect, Effect::Read);
1378    }
1379
1380    /// A spool command's body is its command's own fields, less the tag and
1381    /// the spool its path already names.
1382    #[test]
1383    fn a_spool_commands_body_is_its_fields_less_the_tag_and_the_routed_spool() {
1384        let load = operation("load_spool").expect("the load is served");
1385        let names: Vec<(String, super::Located)> = load
1386            .request()
1387            .into_iter()
1388            .map(|parameter| (parameter.name, parameter.located))
1389            .collect();
1390        assert_eq!(
1391            names,
1392            vec![
1393                ("spool_id".to_owned(), super::Located::Path),
1394                ("actor".to_owned(), super::Located::Body),
1395                ("reason".to_owned(), super::Located::Body),
1396                ("tool".to_owned(), super::Located::Body),
1397            ]
1398        );
1399        let register = operation("register_spool").expect("the registration is served");
1400        assert!(
1401            register
1402                .request()
1403                .iter()
1404                .all(|parameter| parameter.name != super::COMMAND_TAG
1405                    && parameter.located == super::Located::Body)
1406        );
1407    }
1408
1409    /// The ledger's own kind names exactly the commands the contracts' own
1410    /// `SpoolCommand` declares, each by the tag it is spelled with, and every
1411    /// spool command operation is declared under one of them.
1412    #[test]
1413    fn the_ledgers_kinds_are_the_commands_the_contracts_declare() {
1414        let schema = super::Vocabulary::Commands.schema();
1415        let declared: Vec<String> = schema["oneOf"]
1416            .as_array()
1417            .expect("the spool vocabulary is a union")
1418            .iter()
1419            .filter_map(|variant| variant.pointer("/properties/command/const"))
1420            .filter_map(|tag| tag.as_str().map(str::to_owned))
1421            .collect();
1422        let kinds: Vec<String> = super::SpoolCommandKind::ALL
1423            .iter()
1424            .map(|kind| {
1425                printobserver_types::serde_json::to_value(kind.action_kind())
1426                    .ok()
1427                    .and_then(|tag| tag.as_str().map(str::to_owned))
1428                    .expect("an action kind renders as its tag")
1429            })
1430            .collect();
1431        assert_eq!(kinds, declared);
1432        let served: Vec<super::SpoolCommandKind> = OPERATIONS
1433            .iter()
1434            .filter_map(|operation| match operation.effect {
1435                Effect::Command(kind) => Some(kind),
1436                _ => None,
1437            })
1438            .collect();
1439        assert_eq!(served, super::SpoolCommandKind::ALL.to_vec());
1440    }
1441
1442    /// A value a request may carry more than once is described as a list.
1443    #[test]
1444    fn a_repeated_value_is_described_as_a_list_of_its_kind() {
1445        let history = operation("printer_history").expect("the printer history is served");
1446        let kinds = history
1447            .request_shapes()
1448            .into_iter()
1449            .find(|(parameter, _)| parameter.name == "kinds")
1450            .expect("the history takes kinds");
1451        assert!(kinds.0.repeated);
1452        assert_eq!(
1453            kinds.1,
1454            printobserver_types::serde_json::json!({"type": "array", "items": {"type": "string"}})
1455        );
1456    }
1457
1458    /// A recovery action's body is its own fields beside the actor and the
1459    /// reason, less the tag the operation names.
1460    #[test]
1461    fn a_recovery_actions_body_is_its_fields_beside_the_actor_and_the_reason() {
1462        let heat = operation("recover_heat").expect("the heat is served");
1463        let names: Vec<(String, bool, super::Located)> = heat
1464            .request()
1465            .into_iter()
1466            .map(|parameter| (parameter.name, parameter.required, parameter.located))
1467            .collect();
1468        assert_eq!(
1469            names,
1470            vec![
1471                ("actor".to_owned(), true, super::Located::Body),
1472                ("clearance_asserted".to_owned(), false, super::Located::Body),
1473                ("reason".to_owned(), true, super::Located::Body),
1474                ("target_c".to_owned(), true, super::Located::Body),
1475                ("tool".to_owned(), true, super::Located::Body),
1476            ]
1477        );
1478        let cool = operation("recover_cool").expect("the cool is served");
1479        let names: Vec<String> = cool
1480            .request()
1481            .into_iter()
1482            .map(|parameter| parameter.name)
1483            .collect();
1484        assert_eq!(names, vec!["actor".to_owned(), "reason".to_owned()]);
1485        let served: Vec<super::RecoveryActionKind> = OPERATIONS
1486            .iter()
1487            .filter_map(super::Operation::recovery_kind)
1488            .collect();
1489        assert_eq!(served, super::RecoveryActionKind::ALL.to_vec());
1490    }
1491
1492    /// A printer-wide form is an operation this server serves, takes the
1493    /// values its print's operation takes less the print, names no print of
1494    /// its own, and is the form of exactly one operation.
1495    #[test]
1496    fn a_printer_wide_form_takes_its_prints_values_less_the_print() {
1497        let mut forms = 0;
1498        for declared in OPERATIONS {
1499            let Some(wide) = declared.printer_wide else {
1500                continue;
1501            };
1502            forms += 1;
1503            assert_eq!(
1504                operation(wide.name),
1505                Some(wide),
1506                "the printer-wide form is not an operation this server serves"
1507            );
1508            assert_eq!(wide.method, declared.method, "`{}`", declared.name);
1509            assert_eq!(wide.effect, declared.effect, "`{}`", declared.name);
1510            assert_eq!(wide.image_path_field, declared.image_path_field);
1511            assert_eq!(
1512                wide.printer_wide, None,
1513                "a printer-wide form has none of its own"
1514            );
1515            assert!(!wide.path.contains("{print_id}"), "`{}`", wide.name);
1516            let taken: Vec<super::Parameter> = declared
1517                .request()
1518                .into_iter()
1519                .filter(|parameter| parameter.name != "print_id")
1520                .collect();
1521            assert_eq!(wide.request(), taken, "`{}`", wide.name);
1522            assert_eq!(
1523                super::printer_wide_of(wide.name).map(|found| found.name),
1524                Some(declared.name)
1525            );
1526        }
1527        assert_eq!(
1528            forms, 1,
1529            "the look is the one read with a printer-wide form"
1530        );
1531        assert!(super::printer_wide_of("look").is_none());
1532    }
1533
1534    /// An operation this server does not serve is answered as none.
1535    #[test]
1536    fn an_operation_this_server_does_not_serve_is_answered_as_none() {
1537        assert_eq!(operation("pause").map(|found| found.name), Some("pause"));
1538        assert!(operation("reboot").is_none());
1539    }
1540}