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 fifteen 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 — and the operator's word that
15//! the bed is clear, 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            (name, _) => panic!("the operation `{name}` has no declared answer shape"),
556        };
557        schema.to_value()
558    }
559}
560
561/// The values declared beside an operation, at one place in the request.
562fn declared(entries: &'static [Declared], located: Located) -> impl Iterator<Item = Parameter> {
563    entries.iter().map(move |entry| Parameter {
564        name: entry.name.to_owned(),
565        required: entry.required,
566        located,
567        kind: entry.kind,
568        repeated: entry.repeated,
569    })
570}
571
572/// The shape one value declared beside an operation carries.
573///
574/// The contracts' own type where the declaration names one, and the kind's own
575/// scalar shape where it names none — a reason and a count are values this
576/// system mints no type for.
577fn declared_shape(entries: &'static [Declared], name: &str) -> Value {
578    let Some(entry) = entries.iter().find(|entry| entry.name == name) else {
579        return json!({ "type": "string" });
580    };
581    let one = if let Some(shape) = entry.shape {
582        json!({ "$ref": format!("#/$defs/{shape}") })
583    } else {
584        match entry.kind {
585            ValueKind::Text => json!({ "type": "string" }),
586            ValueKind::Number => json!({ "type": "number" }),
587            ValueKind::Integer => json!({ "type": "integer" }),
588            ValueKind::Boolean => json!({ "type": "boolean" }),
589            ValueKind::Structured => json!({ "type": "object" }),
590        }
591    };
592    // A value a request may carry more than once is a list of its kind, which
593    // is what a typed consumer sends it as.
594    if entry.repeated {
595        json!({ "type": "array", "items": one })
596    } else {
597        one
598    }
599}
600
601/// Which of the contracts' two closed vocabularies one mutating operation's
602/// body is a variant of.
603#[derive(Debug, Clone, Copy, PartialEq, Eq)]
604enum Vocabulary {
605    /// The print actions, tagged by `action`.
606    Actions,
607    /// The spool ledger's commands, tagged by `command`.
608    Commands,
609    /// The recovery actions, tagged by `action`, each carried beside the
610    /// actor and the reason every request carries.
611    Recovery,
612}
613
614impl Vocabulary {
615    /// The vocabulary one effect's body is read from, and the variant it names.
616    fn of(effect: Effect) -> Option<(Self, String)> {
617        let tag = |kind: ActionKind| {
618            printobserver_types::serde_json::to_value(kind)
619                .ok()
620                .and_then(|value| value.as_str().map(str::to_owned))
621                .unwrap_or_else(|| panic!("`{kind:?}` renders as the tag it is spelled by"))
622        };
623        match effect {
624            Effect::Mutating(kind) => Some((Self::Actions, tag(kind))),
625            Effect::Command(kind) => Some((Self::Commands, tag(kind.action_kind()))),
626            Effect::Recovery(kind) => Some((Self::Recovery, kind.as_str().to_owned())),
627            Effect::Read | Effect::Write => None,
628        }
629    }
630
631    /// The field the vocabulary's tag travels in.
632    const fn tag(self) -> &'static str {
633        match self {
634            Self::Actions | Self::Recovery => ACTION_TAG,
635            Self::Commands => COMMAND_TAG,
636        }
637    }
638
639    /// The vocabulary's own schema, as the contracts declare it.
640    ///
641    /// A recovery action names neither who asks nor why — those are the
642    /// request's, not the action's — so its request body is each variant of
643    /// the contracts' own `RecoveryAction` with the two beside it.
644    fn schema(self) -> Value {
645        use printobserver_types::schemars::schema_for;
646        match self {
647            Self::Actions => schema_for!(PrintAction).to_value(),
648            Self::Commands => schema_for!(SpoolCommand).to_value(),
649            Self::Recovery => recovery_request_schema(),
650        }
651    }
652}
653
654/// The contracts' own `RecoveryAction`, each variant carrying the actor and
655/// the reason a recovery request carries beside it.
656fn recovery_request_schema() -> Value {
657    use printobserver_types::schemars::schema_for;
658    let mut schema = schema_for!(RecoveryAction).to_value();
659    let actor = schema_for!(printobserver_core::Actor).to_value();
660    if let Some(variants) = schema.get_mut("oneOf").and_then(Value::as_array_mut) {
661        for variant in variants {
662            if let Some(properties) = variant.get_mut("properties").and_then(Value::as_object_mut) {
663                properties.insert(
664                    "actor".to_owned(),
665                    json!({ "$ref": "#/$defs/Actor", "description": "Who is asking." }),
666                );
667                properties.insert(
668                    "reason".to_owned(),
669                    json!({ "type": "string", "description": "Why the actor is asking for this." }),
670                );
671            }
672            if let Some(required) = variant.get_mut("required").and_then(Value::as_array_mut) {
673                required.push(json!("actor"));
674                required.push(json!("reason"));
675            }
676        }
677    }
678    let defs = schema
679        .as_object_mut()
680        .map(|top| top.entry("$defs").or_insert_with(|| json!({})));
681    if let Some(Value::Object(defs)) = defs {
682        if let Some(Value::Object(nested)) = actor.get("$defs") {
683            for (name, shape) in nested {
684                defs.insert(name.clone(), shape.clone());
685            }
686        }
687        let mut own = actor.clone();
688        if let Some(top) = own.as_object_mut() {
689            top.remove("$defs");
690            top.remove("$schema");
691        }
692        defs.insert("Actor".to_owned(), own);
693    }
694    schema
695}
696
697/// The shape of each field one action of the vocabulary takes.
698///
699/// Read out of the contracts' own `PrintAction` or `SpoolCommand` beside
700/// [`action_parameters`], which walks the same variant for the same fields —
701/// so a field that gains a shape here gains a parameter there, and neither can
702/// carry one the other does not.
703///
704/// # Panics
705///
706/// Panics when the contracts declare no variant tagged with this action.
707fn action_shapes(vocabulary: Vocabulary, kind: &str) -> Vec<(String, Value)> {
708    let schema = vocabulary.schema();
709    let variant = action_variant(&schema, vocabulary, kind);
710    variant
711        .get("properties")
712        .and_then(Value::as_object)
713        .unwrap_or_else(|| panic!("the action `{kind}` declares no properties"))
714        .iter()
715        .filter(|(name, _)| name.as_str() != vocabulary.tag())
716        .map(|(name, field)| (name.clone(), field.clone()))
717        .collect()
718}
719
720/// The variant of the contracts' own action vocabulary one action tags.
721///
722/// # Panics
723///
724/// Panics when the contracts declare no variant tagged with this action, which
725/// is this server's declared list and that closed type having come apart.
726fn action_variant(schema: &Value, vocabulary: Vocabulary, tag: &str) -> Value {
727    schema
728        .get("oneOf")
729        .and_then(Value::as_array)
730        .and_then(|variants| {
731            variants.iter().find(|variant| {
732                variant.pointer(&format!("/properties/{}/const", vocabulary.tag()))
733                    == Some(&json!(tag))
734            })
735        })
736        .cloned()
737        .unwrap_or_else(|| panic!("the contracts declare no action tagged `{tag}`"))
738}
739
740/// The values one path template takes, in the order it takes them.
741fn path_parameters(path: &str) -> Vec<Parameter> {
742    path.split('/')
743        .filter_map(|segment| segment.strip_prefix('{')?.strip_suffix('}'))
744        .map(|name| Parameter {
745            name: name.to_owned(),
746            // A route with a hole in its path is not a route: nothing reaches
747            // the handler without every segment of it.
748            required: true,
749            located: Located::Path,
750            // A path segment is text: what makes one an identifier is the type
751            // that minted it rather than anything a route can say.
752            kind: ValueKind::Text,
753            repeated: false,
754        })
755        .collect()
756}
757
758/// The body one action of the vocabulary takes, out of the contracts' own type.
759///
760/// # Panics
761///
762/// Panics when the contracts declare no variant tagged with this action, which
763/// is this server's declared list and that closed type having come apart.
764fn action_parameters(vocabulary: Vocabulary, kind: &str) -> Vec<Parameter> {
765    let schema = vocabulary.schema();
766    let variant = action_variant(&schema, vocabulary, kind);
767    let required: Vec<&str> = variant
768        .get("required")
769        .and_then(Value::as_array)
770        .map(|names| names.iter().filter_map(Value::as_str).collect())
771        .unwrap_or_default();
772    let properties = variant
773        .get("properties")
774        .and_then(Value::as_object)
775        .unwrap_or_else(|| panic!("the action `{kind}` declares no properties"));
776    properties
777        .iter()
778        .filter(|(name, _)| name.as_str() != vocabulary.tag())
779        .map(|(name, field)| Parameter {
780            name: name.clone(),
781            required: required.contains(&name.as_str()),
782            located: Located::Body,
783            kind: kind_of(&resolve(&schema, field)),
784            repeated: false,
785        })
786        .collect()
787}
788
789/// One field's own schema, following the one reference a contract field takes.
790fn resolve(schema: &Value, field: &Value) -> Value {
791    let Some(reference) = field.get("$ref").and_then(Value::as_str) else {
792        return field.clone();
793    };
794    reference
795        .strip_prefix("#/")
796        .and_then(|rest| schema.pointer(&format!("/{rest}")))
797        .cloned()
798        .unwrap_or_else(|| field.clone())
799}
800
801/// What kind of value one shape describes.
802///
803/// Read off the shape rather than off the field's name: a closed set of string
804/// constants is text however many of them there are, and an object is a
805/// document however few fields it has. A shape that says nothing this can
806/// decide is a document, which is the reading that still lets a caller supply
807/// it — as itself, or out of a file.
808fn kind_of(shape: &Value) -> ValueKind {
809    if let Some(declared) = shape.get("type") {
810        let named = |name: &str| match declared {
811            Value::String(one) => one == name,
812            Value::Array(many) => many.iter().any(|one| one == name),
813            _ => false,
814        };
815        if named("object") || named("array") {
816            return ValueKind::Structured;
817        }
818        if named("string") {
819            return ValueKind::Text;
820        }
821        if named("integer") {
822            return ValueKind::Integer;
823        }
824        if named("number") {
825            return ValueKind::Number;
826        }
827        if named("boolean") {
828            return ValueKind::Boolean;
829        }
830    }
831    match shape.get("oneOf").or_else(|| shape.get("anyOf")) {
832        Some(Value::Array(branches)) if !branches.is_empty() => {
833            let kinds: Vec<ValueKind> = branches
834                .iter()
835                .map(|branch| match branch.get("const") {
836                    Some(Value::String(_)) => ValueKind::Text,
837                    _ => kind_of(branch),
838                })
839                .collect();
840            let first = kinds[0];
841            if kinds.iter().all(|kind| *kind == first) {
842                first
843            } else {
844                ValueKind::Structured
845            }
846        }
847        _ => ValueKind::Structured,
848    }
849}
850
851/// One mutating operation, at the path its action is asked for under.
852const fn action(name: &'static str, path: &'static str, kind: ActionKind) -> Operation {
853    Operation {
854        name,
855        method: Method::Post,
856        path,
857        effect: Effect::Mutating(kind),
858        accepts: Some(MEDIA_TYPE),
859        answers: MEDIA_TYPE,
860        query: &[],
861        body: &[],
862        image_path_field: None,
863        printer_wide: None,
864        mints_print: false,
865    }
866}
867
868/// One spool command, at the path its command is asked for under.
869const fn command(name: &'static str, path: &'static str, kind: SpoolCommandKind) -> Operation {
870    Operation {
871        effect: Effect::Command(kind),
872        ..action(name, path, kind.action_kind())
873    }
874}
875
876/// One recovery action, at the path it is asked for under.
877const fn recovery(name: &'static str, path: &'static str, kind: RecoveryActionKind) -> Operation {
878    Operation {
879        name,
880        method: Method::Post,
881        path,
882        effect: Effect::Recovery(kind),
883        accepts: Some(MEDIA_TYPE),
884        answers: MEDIA_TYPE,
885        query: &[],
886        body: &[],
887        image_path_field: None,
888        printer_wide: None,
889        mints_print: false,
890    }
891}
892
893/// One read, which takes no body.
894const fn read(name: &'static str, path: &'static str) -> Operation {
895    Operation {
896        name,
897        method: Method::Get,
898        path,
899        effect: Effect::Read,
900        accepts: None,
901        answers: MEDIA_TYPE,
902        query: &[],
903        body: &[],
904        image_path_field: None,
905        printer_wide: None,
906        mints_print: false,
907    }
908}
909
910/// How one operation's name is spelled as a command of the `printobserver`
911/// program: each underscore a hyphen.
912///
913/// The one spelling both the command-line program's commands and the
914/// supervising agent's allowed commands are made from, so the command the agent
915/// is allowed to run is the command the program has.
916#[must_use]
917pub fn command_for(operation: &str) -> String {
918    operation.replace('_', "-")
919}
920
921/// Every public operation this server serves, and there is no other.
922pub const OPERATIONS: [Operation; 39] = [
923    // Takes nothing: it is how a caller finds the identifier every other
924    // print-specific operation takes.
925    // llmlint: ignore[names_match_behavior] suppressions.toml has the reason.
926    read("prints", "/prints"),
927    read("status", "/prints/{print_id}/status"),
928    // The print's context; asked `since` an event, its recent events are
929    // only those newer than that one.
930    Operation {
931        query: &[
932            // Read into an `EventId`, and refused when it names none.
933            Declared {
934                shape: Some("EventId"),
935                ..Declared::once("since", false, ValueKind::Text)
936            },
937        ],
938        image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
939        ..read("context", "/prints/{print_id}/context")
940    },
941    Operation {
942        image_path_field: Some(IMAGE_PATH_FIELD),
943        ..read("image", "/images/{image_id}")
944    },
945    Operation {
946        query: &[Declared::once("limit", false, ValueKind::Integer)],
947        ..read("history", "/prints/{print_id}/history")
948    },
949    // The event log in the order it was stored, after a cursor: one print's
950    // events and the printer's, or every event, filtered by kind, waiting up
951    // to `wait_s` seconds for one to pass. A read, so it takes no actor.
952    Operation {
953        query: &[
954            Declared::once("after", false, ValueKind::Text),
955            Declared::once("print_id", false, ValueKind::Text),
956            Declared {
957                repeated: true,
958                ..Declared::once("kinds", false, ValueKind::Text)
959            },
960            Declared {
961                repeated: true,
962                ..Declared::once("exclude_kinds", false, ValueKind::Text)
963            },
964            Declared::once("wait_s", false, ValueKind::Integer),
965            Declared::once("limit", false, ValueKind::Integer),
966        ],
967        ..read("events", "/events")
968    },
969    read("manifest_get", "/prints/{print_id}/manifest"),
970    // A fresh look: waits up to `wait_s` seconds for something to arrive for
971    // the print, returning the moment something does, then takes a frame and
972    // reads the printer as it is now. A read, so it takes no actor. Asked
973    // with no print named, it is the printer's look below.
974    Operation {
975        query: &[Declared::once("wait_s", false, ValueKind::Integer)],
976        image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
977        printer_wide: Some(&PRINTER_LOOK_OPERATION),
978        mints_print: false,
979        ..read("look", "/prints/{print_id}/look")
980    },
981    PRINTER_LOOK_OPERATION,
982    Operation {
983        name: "manifest_set",
984        method: Method::Put,
985        path: "/prints/{print_id}/manifest",
986        effect: Effect::Write,
987        accepts: Some(MEDIA_TYPE),
988        answers: MEDIA_TYPE,
989        query: &[],
990        body: &[
991            Declared::once("reason", true, ValueKind::Text),
992            Declared {
993                shape: Some("JobManifest"),
994                ..Declared::once("manifest", true, ValueKind::Structured)
995            },
996        ],
997        image_path_field: None,
998        printer_wide: None,
999        mints_print: false,
1000    },
1001    // Every spool, the retired ones only when asked for, each beside one line
1002    // saying what it holds — and the charges held for a tool after a filament
1003    // change nobody has confirmed.
1004    Operation {
1005        query: &[Declared::once("include_retired", false, ValueKind::Boolean)],
1006        ..read("spools", "/spools")
1007    },
1008    read("spool", "/spools/{spool_id}"),
1009    // The printer's own history: every print, charge and spool event, newest
1010    // first, a page at a time. Named for the printer rather than for a print,
1011    // because `history` is one print's.
1012    Operation {
1013        query: &[
1014            Declared {
1015                repeated: true,
1016                ..Declared::once("kinds", false, ValueKind::Text)
1017            },
1018            Declared::once("since", false, ValueKind::Text),
1019            Declared::once("until", false, ValueKind::Text),
1020            Declared::once("spool_id", false, ValueKind::Text),
1021            Declared::once("before", false, ValueKind::Text),
1022            Declared::once("limit", false, ValueKind::Integer),
1023        ],
1024        ..read("printer_history", "/history")
1025    },
1026    // Whether the spools loaded hold enough for one file, were it sliced for
1027    // their material, and — given a sheet — whether that sheet suits it, read
1028    // now: it records nothing and starts nothing.
1029    Operation {
1030        query: &[
1031            Declared::once("file_name", true, ValueKind::Text),
1032            // Read into a `SheetId`, and refused when blank.
1033            Declared {
1034                shape: Some("SheetId"),
1035                ..Declared::once("sheet", false, ValueKind::Text)
1036            },
1037        ],
1038        ..read("preflight", "/preflight")
1039    },
1040    action(
1041        "pause",
1042        "/prints/{print_id}/actions/pause",
1043        ActionKind::Pause,
1044    ),
1045    action(
1046        "resume",
1047        "/prints/{print_id}/actions/resume",
1048        ActionKind::Resume,
1049    ),
1050    action(
1051        "cancel",
1052        "/prints/{print_id}/actions/cancel",
1053        ActionKind::Cancel,
1054    ),
1055    // A first start has no print to name, so one is minted for it.
1056    Operation {
1057        mints_print: true,
1058        ..action(
1059            "start_print",
1060            "/prints/{print_id}/actions/start_print",
1061            ActionKind::StartPrint,
1062        )
1063    },
1064    action(
1065        "set_feedrate_factor",
1066        "/prints/{print_id}/actions/set_feedrate_factor",
1067        ActionKind::SetFeedrateFactor,
1068    ),
1069    action(
1070        "set_flowrate_factor",
1071        "/prints/{print_id}/actions/set_flowrate_factor",
1072        ActionKind::SetFlowrateFactor,
1073    ),
1074    action(
1075        "set_tool_target_c",
1076        "/prints/{print_id}/actions/set_tool_target_c",
1077        ActionKind::SetToolTargetC,
1078    ),
1079    action(
1080        "set_bed_target_c",
1081        "/prints/{print_id}/actions/set_bed_target_c",
1082        ActionKind::SetBedTargetC,
1083    ),
1084    action(
1085        "set_fan_percent",
1086        "/prints/{print_id}/actions/set_fan_percent",
1087        ActionKind::SetFanPercent,
1088    ),
1089    action(
1090        "acknowledge_failure",
1091        "/prints/{print_id}/actions/acknowledge_failure",
1092        ActionKind::AcknowledgeFailure,
1093    ),
1094    // Closes a record printobserver left open, asking nothing of the machine.
1095    action(
1096        "close_print",
1097        "/prints/{print_id}/actions/close_print",
1098        ActionKind::ClosePrint,
1099    ),
1100    command(
1101        "register_spool",
1102        "/spools/actions/register_spool",
1103        SpoolCommandKind::RegisterSpool,
1104    ),
1105    command(
1106        "load_spool",
1107        "/spools/{spool_id}/actions/load_spool",
1108        SpoolCommandKind::LoadSpool,
1109    ),
1110    command(
1111        "unload_spool",
1112        "/spools/{spool_id}/actions/unload_spool",
1113        SpoolCommandKind::UnloadSpool,
1114    ),
1115    command(
1116        "adjust_spool",
1117        "/spools/{spool_id}/actions/adjust_spool",
1118        SpoolCommandKind::AdjustSpool,
1119    ),
1120    command(
1121        "retire_spool",
1122        "/spools/{spool_id}/actions/retire_spool",
1123        SpoolCommandKind::RetireSpool,
1124    ),
1125    // What every recovery action is checked against now, and what each would
1126    // meet. The printer's rather than a print's, so it takes no print.
1127    read(RECOVERY_STATUS, "/printer/recovery"),
1128    recovery(
1129        "recover_lift",
1130        "/printer/recovery/recover_lift",
1131        RecoveryActionKind::RecoverLift,
1132    ),
1133    recovery(
1134        "recover_cool",
1135        "/printer/recovery/recover_cool",
1136        RecoveryActionKind::RecoverCool,
1137    ),
1138    recovery(
1139        "recover_fan",
1140        "/printer/recovery/recover_fan",
1141        RecoveryActionKind::RecoverFan,
1142    ),
1143    recovery(
1144        "recover_heat",
1145        "/printer/recovery/recover_heat",
1146        RecoveryActionKind::RecoverHeat,
1147    ),
1148    recovery(
1149        "recover_park",
1150        "/printer/recovery/recover_park",
1151        RecoveryActionKind::RecoverPark,
1152    ),
1153    recovery(
1154        "recover_home_xy",
1155        "/printer/recovery/recover_home_xy",
1156        RecoveryActionKind::RecoverHomeXy,
1157    ),
1158    recovery(
1159        "recover_home_z",
1160        "/printer/recovery/recover_home_z",
1161        RecoveryActionKind::RecoverHomeZ,
1162    ),
1163    // The operator's word that the bed is clear, which every recovery needing
1164    // the bed or the nozzle clear is decided on until the next print starts.
1165    // The printer's rather than a print's, and asks nothing of the machine.
1166    Operation {
1167        name: BED_CLEAR,
1168        method: Method::Post,
1169        path: "/printer/bed_clear",
1170        effect: Effect::Write,
1171        accepts: Some(MEDIA_TYPE),
1172        answers: MEDIA_TYPE,
1173        query: &[],
1174        body: &[
1175            Declared {
1176                shape: Some("Actor"),
1177                ..Declared::once("actor", true, ValueKind::Structured)
1178            },
1179            Declared::once("reason", true, ValueKind::Text),
1180        ],
1181        image_path_field: None,
1182        printer_wide: None,
1183        mints_print: false,
1184    },
1185];
1186
1187/// The operator's word that the bed is clear, recorded beside the recovery
1188/// vocabulary it is decided into.
1189pub const BED_CLEAR: &str = "bed_clear";
1190
1191/// The read beside the recovery vocabulary: what every recovery action is
1192/// checked against now, and what each would meet.
1193pub const RECOVERY_STATUS: &str = "recover_status";
1194
1195/// The fifteen operations this server serves beside the vocabularies.
1196///
1197/// Thirteen of them read, one writes a manifest and one records the operator's
1198/// word that the bed is clear, neither of which asks anything of the machine;
1199/// what they have in common is that none of them is an action, a spool command
1200/// or a recovery action the contracts declare. A look writes its own record into the
1201/// print's history — or the printer's, for a look at the printer — as every
1202/// read of the camera is kept, and asks nothing of the machine either; a
1203/// filament check records nothing at all.
1204pub const BESIDE_THE_ACTIONS: [&str; 15] = [
1205    "prints",
1206    "status",
1207    "context",
1208    "image",
1209    "history",
1210    "events",
1211    "manifest_get",
1212    "look",
1213    PRINTER_LOOK,
1214    "manifest_set",
1215    "spools",
1216    "spool",
1217    "printer_history",
1218    "preflight",
1219    BED_CLEAR,
1220];
1221
1222/// The look at the printer with no print named, which `look` is asked as when
1223/// it names none.
1224pub const PRINTER_LOOK: &str = "printer_look";
1225
1226/// A fresh look at the printer with no print named: waits `wait_s` seconds, on
1227/// nothing any print's agent is owed, then takes a frame, keeps it as the
1228/// printer's, and reads the printer as it is now. The operator's: a turn's
1229/// credential reaches its own print alone. Declared apart from [`OPERATIONS`],
1230/// which serves it, so the look's [`Operation::printer_wide`] can name it as
1231/// the operation itself rather than by a name that might name none.
1232const PRINTER_LOOK_OPERATION: Operation = Operation {
1233    query: &[Declared::once("wait_s", false, ValueKind::Integer)],
1234    image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
1235    ..read(PRINTER_LOOK, "/look")
1236};
1237
1238/// The operation whose command reaches this one, when this one is another's
1239/// [`Operation::printer_wide`] form and so has no command of its own.
1240#[must_use]
1241pub fn printer_wide_of(name: &str) -> Option<&'static Operation> {
1242    OPERATIONS
1243        .iter()
1244        .find(|declared| declared.printer_wide.is_some_and(|wide| wide.name == name))
1245}
1246
1247/// The operation of one name, when this server serves one.
1248#[must_use]
1249pub fn operation(name: &str) -> Option<&'static Operation> {
1250    OPERATIONS.iter().find(|declared| declared.name == name)
1251}
1252
1253#[cfg(test)]
1254mod tests {
1255    use printobserver_core::ActionKind;
1256
1257    use super::{Effect, MEDIA_TYPE, Method, OPERATIONS, VERSION_PREFIX, operation};
1258
1259    /// Every method is spelled the way the wire spells it.
1260    #[test]
1261    fn every_method_is_spelled_as_the_wire_spells_it() {
1262        for (method, spelling) in [
1263            (Method::Get, "GET"),
1264            (Method::Post, "POST"),
1265            (Method::Put, "PUT"),
1266        ] {
1267            assert_eq!(method.as_str(), spelling);
1268            assert_eq!(method.to_string(), spelling);
1269        }
1270    }
1271
1272    /// An operation's whole path carries the one versioned prefix.
1273    #[test]
1274    fn every_operation_sits_beneath_the_one_versioned_prefix() {
1275        for declared in OPERATIONS {
1276            let whole = declared.full_path();
1277            assert!(
1278                whole.starts_with(VERSION_PREFIX),
1279                "`{}` is served at {whole}",
1280                declared.name
1281            );
1282            assert_eq!(declared.answers, MEDIA_TYPE);
1283        }
1284    }
1285
1286    /// A mutating operation names the action it asks for, and a read names none.
1287    #[test]
1288    fn a_mutating_operation_names_its_action_and_a_read_names_none() {
1289        for declared in OPERATIONS {
1290            match declared.effect {
1291                Effect::Mutating(kind) => {
1292                    assert_eq!(declared.action_kind(), Some(kind));
1293                    assert_eq!(declared.command_kind(), None);
1294                    assert_eq!(declared.granted_as(), Some(kind));
1295                    assert!(declared.is_mutating());
1296                }
1297                Effect::Command(kind) => {
1298                    assert_eq!(declared.action_kind(), None);
1299                    assert_eq!(declared.command_kind(), Some(kind.action_kind()));
1300                    assert_eq!(declared.granted_as(), Some(kind.action_kind()));
1301                    assert!(declared.is_mutating());
1302                }
1303                Effect::Recovery(kind) => {
1304                    assert_eq!(declared.action_kind(), None);
1305                    assert_eq!(declared.granted_as(), None);
1306                    assert_eq!(declared.recovery_kind(), Some(kind));
1307                    assert!(declared.is_mutating());
1308                }
1309                Effect::Write => {
1310                    assert_eq!(declared.action_kind(), None);
1311                    assert!(
1312                        declared.is_mutating(),
1313                        "`{}` writes a record and is not held to the reason every \
1314                         change carries",
1315                        declared.name
1316                    );
1317                }
1318                Effect::Read => {
1319                    assert_eq!(declared.action_kind(), None);
1320                    assert!(!declared.is_mutating());
1321                }
1322            }
1323        }
1324    }
1325
1326    /// A mutating operation takes JSON and answers JSON; a read takes no body.
1327    ///
1328    /// The two constructors are the only way an entry of the declared list is
1329    /// made, so this is the shape every entry has by construction.
1330    #[test]
1331    fn a_mutating_operation_takes_a_body_and_a_read_takes_none() {
1332        let mutating = super::action(
1333            "pause",
1334            "/prints/{print_id}/actions/pause",
1335            ActionKind::Pause,
1336        );
1337        assert_eq!(mutating.method, Method::Post);
1338        assert_eq!(mutating.accepts, Some(MEDIA_TYPE));
1339        assert_eq!(mutating.answers, MEDIA_TYPE);
1340        assert_eq!(mutating.action_kind(), Some(ActionKind::Pause));
1341
1342        let reading = super::read("status", "/prints/{print_id}/status");
1343        assert_eq!(reading.method, Method::Get);
1344        assert_eq!(reading.accepts, None);
1345        assert_eq!(reading.answers, MEDIA_TYPE);
1346        assert_eq!(reading.effect, Effect::Read);
1347    }
1348
1349    /// A spool command's body is its command's own fields, less the tag and
1350    /// the spool its path already names.
1351    #[test]
1352    fn a_spool_commands_body_is_its_fields_less_the_tag_and_the_routed_spool() {
1353        let load = operation("load_spool").expect("the load is served");
1354        let names: Vec<(String, super::Located)> = load
1355            .request()
1356            .into_iter()
1357            .map(|parameter| (parameter.name, parameter.located))
1358            .collect();
1359        assert_eq!(
1360            names,
1361            vec![
1362                ("spool_id".to_owned(), super::Located::Path),
1363                ("actor".to_owned(), super::Located::Body),
1364                ("reason".to_owned(), super::Located::Body),
1365                ("tool".to_owned(), super::Located::Body),
1366            ]
1367        );
1368        let register = operation("register_spool").expect("the registration is served");
1369        assert!(
1370            register
1371                .request()
1372                .iter()
1373                .all(|parameter| parameter.name != super::COMMAND_TAG
1374                    && parameter.located == super::Located::Body)
1375        );
1376    }
1377
1378    /// The ledger's own kind names exactly the commands the contracts' own
1379    /// `SpoolCommand` declares, each by the tag it is spelled with, and every
1380    /// spool command operation is declared under one of them.
1381    #[test]
1382    fn the_ledgers_kinds_are_the_commands_the_contracts_declare() {
1383        let schema = super::Vocabulary::Commands.schema();
1384        let declared: Vec<String> = schema["oneOf"]
1385            .as_array()
1386            .expect("the spool vocabulary is a union")
1387            .iter()
1388            .filter_map(|variant| variant.pointer("/properties/command/const"))
1389            .filter_map(|tag| tag.as_str().map(str::to_owned))
1390            .collect();
1391        let kinds: Vec<String> = super::SpoolCommandKind::ALL
1392            .iter()
1393            .map(|kind| {
1394                printobserver_types::serde_json::to_value(kind.action_kind())
1395                    .ok()
1396                    .and_then(|tag| tag.as_str().map(str::to_owned))
1397                    .expect("an action kind renders as its tag")
1398            })
1399            .collect();
1400        assert_eq!(kinds, declared);
1401        let served: Vec<super::SpoolCommandKind> = OPERATIONS
1402            .iter()
1403            .filter_map(|operation| match operation.effect {
1404                Effect::Command(kind) => Some(kind),
1405                _ => None,
1406            })
1407            .collect();
1408        assert_eq!(served, super::SpoolCommandKind::ALL.to_vec());
1409    }
1410
1411    /// A value a request may carry more than once is described as a list.
1412    #[test]
1413    fn a_repeated_value_is_described_as_a_list_of_its_kind() {
1414        let history = operation("printer_history").expect("the printer history is served");
1415        let kinds = history
1416            .request_shapes()
1417            .into_iter()
1418            .find(|(parameter, _)| parameter.name == "kinds")
1419            .expect("the history takes kinds");
1420        assert!(kinds.0.repeated);
1421        assert_eq!(
1422            kinds.1,
1423            printobserver_types::serde_json::json!({"type": "array", "items": {"type": "string"}})
1424        );
1425    }
1426
1427    /// A recovery action's body is its own fields beside the actor and the
1428    /// reason, less the tag the operation names.
1429    #[test]
1430    fn a_recovery_actions_body_is_its_fields_beside_the_actor_and_the_reason() {
1431        let heat = operation("recover_heat").expect("the heat is served");
1432        let names: Vec<(String, bool, super::Located)> = heat
1433            .request()
1434            .into_iter()
1435            .map(|parameter| (parameter.name, parameter.required, parameter.located))
1436            .collect();
1437        assert_eq!(
1438            names,
1439            vec![
1440                ("actor".to_owned(), true, super::Located::Body),
1441                ("clearance_asserted".to_owned(), false, super::Located::Body),
1442                ("reason".to_owned(), true, super::Located::Body),
1443                ("target_c".to_owned(), true, super::Located::Body),
1444                ("tool".to_owned(), true, super::Located::Body),
1445            ]
1446        );
1447        let cool = operation("recover_cool").expect("the cool is served");
1448        let names: Vec<String> = cool
1449            .request()
1450            .into_iter()
1451            .map(|parameter| parameter.name)
1452            .collect();
1453        assert_eq!(names, vec!["actor".to_owned(), "reason".to_owned()]);
1454        let served: Vec<super::RecoveryActionKind> = OPERATIONS
1455            .iter()
1456            .filter_map(super::Operation::recovery_kind)
1457            .collect();
1458        assert_eq!(served, super::RecoveryActionKind::ALL.to_vec());
1459    }
1460
1461    /// A printer-wide form is an operation this server serves, takes the
1462    /// values its print's operation takes less the print, names no print of
1463    /// its own, and is the form of exactly one operation.
1464    #[test]
1465    fn a_printer_wide_form_takes_its_prints_values_less_the_print() {
1466        let mut forms = 0;
1467        for declared in OPERATIONS {
1468            let Some(wide) = declared.printer_wide else {
1469                continue;
1470            };
1471            forms += 1;
1472            assert_eq!(
1473                operation(wide.name),
1474                Some(wide),
1475                "the printer-wide form is not an operation this server serves"
1476            );
1477            assert_eq!(wide.method, declared.method, "`{}`", declared.name);
1478            assert_eq!(wide.effect, declared.effect, "`{}`", declared.name);
1479            assert_eq!(wide.image_path_field, declared.image_path_field);
1480            assert_eq!(
1481                wide.printer_wide, None,
1482                "a printer-wide form has none of its own"
1483            );
1484            assert!(!wide.path.contains("{print_id}"), "`{}`", wide.name);
1485            let taken: Vec<super::Parameter> = declared
1486                .request()
1487                .into_iter()
1488                .filter(|parameter| parameter.name != "print_id")
1489                .collect();
1490            assert_eq!(wide.request(), taken, "`{}`", wide.name);
1491            assert_eq!(
1492                super::printer_wide_of(wide.name).map(|found| found.name),
1493                Some(declared.name)
1494            );
1495        }
1496        assert_eq!(
1497            forms, 1,
1498            "the look is the one read with a printer-wide form"
1499        );
1500        assert!(super::printer_wide_of("look").is_none());
1501    }
1502
1503    /// An operation this server does not serve is answered as none.
1504    #[test]
1505    fn an_operation_this_server_does_not_serve_is_answered_as_none() {
1506        assert_eq!(operation("pause").map(|found| found.name), Some("pause"));
1507        assert!(operation("reboot").is_none());
1508    }
1509}