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