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