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