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