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) the contracts declare,
7//! plus seven operations beside them — the prints listing, status, context,
8//! image materialization, history, and the manifest's read and write — and
9//! nothing else. The router is built by folding
10//! over this array rather than by writing routes out, so the set served and the
11//! set declared are one thing; and this crate's own tier derives the required
12//! set from the contracts' own `PrintAction` rather than from a list of its
13//! own, so growing this array and the routes together cannot satisfy it.
14//!
15//! Every operation sits beneath [`VERSION_PREFIX`], takes JSON where it takes a
16//! body at all, and answers JSON.
17//!
18//! # Each operation declares what it takes and what it answers
19//!
20//! [`Operation::request`] is the request schema of one route — every value a
21//! caller supplies, where it travels and whether it is required — and
22//! [`Operation::response_schema`] is the schema of each answer that route can
23//! produce. Neither is written out for the ten mutating operations: their body
24//! is derived from the contracts' own
25//! [`PrintAction`](printobserver_core::PrintAction) at run time, so a variant
26//! that gains a field gains it here the moment the type does. The
27//! command-line program builds its own parser from these declarations rather
28//! than from a list of its own, which is what stops the two surfaces drifting.
29//!
30//! # The ingress is not one of them
31//!
32//! [`INGRESS_PATH`] is the endpoint `Obico`'s webhook notification plugin posts
33//! to. It is the producer's own ingress rather than an operation a client
34//! calls — it is authenticated by a shared secret rather than by an actor, it
35//! carries `Obico`'s body rather than this system's, and it answers before its
36//! handling completes. So it is declared separately and served outside the
37//! versioned prefix, where no client can mistake one surface for the other.
38
39use printobserver_types::serde_json::{Value, json};
40
41// The vocabulary the mutating operations are folded from, re-exported beside
42// them: a client of this surface that derives its own commands from these
43// operations — the command-line program — reads which action each is and what
44// that action carries from here, without naming the supervision domain itself.
45pub use printobserver_core::{ActionKind, PrintAction};
46
47/// The one versioned prefix every public operation is served beneath.
48pub const VERSION_PREFIX: &str = "/v1";
49
50/// The media type every operation takes a body in and answers in.
51pub const MEDIA_TYPE: &str = "application/json";
52
53/// Where `Obico`'s webhook notification plugin posts, which is not a public
54/// operation. See this module's own comment.
55pub const INGRESS_PATH: &str = "/obico/webhook";
56
57/// The field a context answer carries the latest image's own path in.
58pub const CONTEXT_IMAGE_PATH_FIELD: &str = "image_path";
59
60/// The field an image answer carries that image's own path in.
61pub const IMAGE_PATH_FIELD: &str = "path";
62
63/// The field of a request body the action vocabulary's tag travels in, which a
64/// caller never supplies: the operation it sends to is what names the action.
65const ACTION_TAG: &str = "action";
66
67/// The method one operation is reached by.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
69pub enum Method {
70    /// A read.
71    Get,
72    /// A request that changes something.
73    Post,
74    /// A write that replaces what is there.
75    Put,
76}
77
78impl Method {
79    /// The method as it is spelled on the wire.
80    #[must_use]
81    pub const fn as_str(self) -> &'static str {
82        match self {
83            Self::Get => "GET",
84            Self::Post => "POST",
85            Self::Put => "PUT",
86        }
87    }
88}
89
90impl core::fmt::Display for Method {
91    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
92        formatter.write_str(self.as_str())
93    }
94}
95
96/// Where one value of a request travels.
97#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
98pub enum Located {
99    /// In the request target, as a segment of the path.
100    Path,
101    /// In the request target, after the question mark.
102    Query,
103    /// In the JSON body.
104    Body,
105}
106
107/// What kind of value one parameter takes.
108///
109/// Declared rather than left to a consumer to rediscover from the schema,
110/// because a consumer that has to read a value off a command line has to know
111/// what to read it as: `1.15` is a number and `1.15` is also a perfectly good
112/// reason to give.
113#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
114pub enum ValueKind {
115    /// Text, taken as it was given.
116    Text,
117    /// A number, whole or otherwise.
118    Number,
119    /// A whole number.
120    Integer,
121    /// True or false.
122    Boolean,
123    /// A document rather than a scalar.
124    Structured,
125}
126
127impl ValueKind {
128    /// Whether a value of this kind is a document rather than a scalar.
129    #[must_use]
130    pub const fn structured(self) -> bool {
131        matches!(self, Self::Structured)
132    }
133}
134
135/// One value declared beside an operation, at one place in its request.
136///
137/// Only the operations whose body is not one action of the vocabulary declare
138/// their values this way; a mutating operation's are the fields the contracts'
139/// own `PrintAction` declares for the variant it names.
140#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
141pub struct Declared {
142    /// What it is called, spelled as the wire spells it.
143    pub name: &'static str,
144    /// Whether a request without it is refused.
145    pub required: bool,
146    /// What kind of value it takes.
147    pub kind: ValueKind,
148    /// The contracts' own type it is a value of, when it is one of theirs.
149    ///
150    /// A consumer generating a typed client needs the type rather than the
151    /// kind: [`ValueKind::Structured`] says a manifest is a document, and not
152    /// that it is a `JobManifest`. A value this system mints no type for — a
153    /// count, a reason — declares none.
154    pub shape: Option<&'static str>,
155}
156
157/// One value a request to an operation carries.
158#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
159pub struct Parameter {
160    /// What it is called, spelled as the wire spells it.
161    pub name: String,
162    /// Whether a request without it is refused.
163    pub required: bool,
164    /// Where it travels.
165    pub located: Located,
166    /// What kind of value it takes.
167    pub kind: ValueKind,
168}
169
170/// One answer a route can produce.
171#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
172pub enum Answer {
173    /// The operation was carried out, or the read was answered.
174    Success,
175    /// The policy rejected the action, and the rejection is the answer.
176    Rejected,
177}
178
179impl Answer {
180    /// Its own name, for a report that walks the answers of a route.
181    #[must_use]
182    pub const fn as_str(self) -> &'static str {
183        match self {
184            Self::Success => "success",
185            Self::Rejected => "rejected",
186        }
187    }
188}
189
190impl core::fmt::Display for Answer {
191    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
192        formatter.write_str(self.as_str())
193    }
194}
195
196/// What one operation does to the machine or the record.
197#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
198pub enum Effect {
199    /// It reads, and changes nothing.
200    Read,
201    /// It changes something, so it carries a reason and passes the policy.
202    Mutating(ActionKind),
203    /// It writes a record without asking anything of the machine.
204    Write,
205}
206
207/// One public operation: what it is called, how it is reached, and what it does.
208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
209pub struct Operation {
210    /// The operation's own name. For a mutating operation this is the spelling
211    /// the contracts' own `PrintAction` tags that variant with.
212    pub name: &'static str,
213    /// The method it is reached by.
214    pub method: Method,
215    /// Its path beneath [`VERSION_PREFIX`].
216    pub path: &'static str,
217    /// What it does.
218    pub effect: Effect,
219    /// The media type it takes a body in, when it takes one.
220    pub accepts: Option<&'static str>,
221    /// The media type it answers in.
222    pub answers: &'static str,
223    /// The values it takes after the question mark.
224    pub query: &'static [Declared],
225    /// The values it takes in its body, for an operation whose body is not one
226    /// action of the vocabulary. A mutating operation declares none here: its
227    /// body is the `PrintAction` variant it names, read from the contracts
228    /// themselves by [`Operation::request`].
229    pub body: &'static [Declared],
230    /// The field of its answer carrying an absolute path to a materialized
231    /// image, when its answer carries one.
232    ///
233    /// Every image answer this server gives is a path on **this server's own
234    /// filesystem** and no route of it answers image bytes, so a consumer
235    /// reading this field is reading which of its values names a file it may
236    /// not be able to open. Declared here rather than discovered, because what
237    /// a consumer owes such a field is a failure of its own.
238    pub image_path_field: Option<&'static str>,
239}
240
241impl Operation {
242    /// Its whole path, including the versioned prefix.
243    #[must_use]
244    pub fn full_path(&self) -> String {
245        format!("{VERSION_PREFIX}{}", self.path)
246    }
247
248    /// Which action this operation asks for, when it asks for one.
249    #[must_use]
250    pub const fn action_kind(&self) -> Option<ActionKind> {
251        match self.effect {
252            Effect::Mutating(kind) => Some(kind),
253            _ => None,
254        }
255    }
256
257    /// Whether this operation changes something.
258    ///
259    /// Asking the machine for an action and replacing the manifest a print runs
260    /// under are both changes, and both carry a reason. What separates them is
261    /// whether the policy has anything to rule on — not whether the caller has
262    /// to say why.
263    #[must_use]
264    pub const fn is_mutating(&self) -> bool {
265        matches!(self.effect, Effect::Mutating(_) | Effect::Write)
266    }
267
268    /// Every value a request to this operation carries, and where it carries it.
269    ///
270    /// The body of a mutating operation is not written out anywhere: it is the
271    /// fields the contracts' own `PrintAction` declares for the variant this
272    /// operation names, read from that type's own schema. A variant that gains
273    /// a field gains it here without this file changing, which is what stops a
274    /// consumer building a request surface from drifting from the vocabulary.
275    ///
276    /// # Panics
277    ///
278    /// Panics when the contracts declare no variant this operation names, which
279    /// is a declared list and a closed type that have come apart.
280    #[must_use]
281    pub fn request(&self) -> Vec<Parameter> {
282        let mut found = path_parameters(self.path);
283        found.extend(declared(self.query, Located::Query));
284        match self.effect {
285            Effect::Mutating(kind) => found.extend(action_parameters(kind)),
286            Effect::Read | Effect::Write => found.extend(declared(self.body, Located::Body)),
287        }
288        found
289    }
290
291    /// Every value a request to this operation carries, with its own shape.
292    ///
293    /// [`Operation::request`] answers what a command line needs — a name, a
294    /// place and a kind. This answers what a **typed** consumer needs beside
295    /// that: the shape of each value, as a schema referring to the contracts'
296    /// own types by name where the value is one of theirs. `structured` says a
297    /// manifest is a document; `{"$ref": "#/$defs/JobManifest"}` says which
298    /// document, which is the difference between a generated client that types
299    /// it and one that takes anything.
300    ///
301    /// The order is [`Operation::request`]'s own, so the two can be read side
302    /// by side.
303    ///
304    /// # Panics
305    ///
306    /// Panics when the contracts declare no variant this operation names, which
307    /// is a declared list and a closed type that have come apart.
308    #[must_use]
309    pub fn request_shapes(&self) -> Vec<(Parameter, Value)> {
310        let action = match self.effect {
311            Effect::Mutating(kind) => action_shapes(kind),
312            Effect::Read | Effect::Write => Vec::new(),
313        };
314        self.request()
315            .into_iter()
316            .map(|parameter| {
317                let shape = match parameter.located {
318                    // What makes a path segment an identifier is the type that
319                    // minted it, and a route mints nothing: it is a string.
320                    Located::Path => json!({ "type": "string" }),
321                    Located::Query => declared_shape(self.query, &parameter.name),
322                    Located::Body if action.is_empty() => {
323                        declared_shape(self.body, &parameter.name)
324                    }
325                    Located::Body => action
326                        .iter()
327                        .find(|(name, _)| *name == parameter.name)
328                        .map_or_else(
329                            || {
330                                panic!(
331                                    "`{}` takes `{}` in its body, and the action it names \
332                                     declares no such field",
333                                    self.name, parameter.name
334                                )
335                            },
336                            |(_, shape)| shape.clone(),
337                        ),
338                };
339                (parameter, shape)
340            })
341            .collect()
342    }
343
344    /// Every answer this operation can produce.
345    ///
346    /// A read answers what it read. An operation asking for an action answers
347    /// that as well as the policy's own rejection, which is an answer rather
348    /// than a transport failure: it carries the reason, the value asked for and
349    /// the range allowed.
350    #[must_use]
351    pub const fn answers_with(&self) -> &'static [Answer] {
352        match self.effect {
353            Effect::Mutating(_) => &[Answer::Success, Answer::Rejected],
354            Effect::Read | Effect::Write => &[Answer::Success],
355        }
356    }
357
358    /// The schema of one answer this operation produces.
359    ///
360    /// A rejection is the same shape as an acceptance and deliberately so: the
361    /// answer to a rejected action is the action record carrying the policy's
362    /// own decision, rather than a second document a caller has to know about.
363    ///
364    /// # Panics
365    ///
366    /// Panics when this operation is not one this server serves an answer
367    /// shape for, which is a declared list and a router that have come apart.
368    #[must_use]
369    pub fn response_schema(&self, answer: Answer) -> Value {
370        use printobserver_types::schemars::schema_for;
371        debug_assert!(
372            self.answers_with().contains(&answer),
373            "`{}` produces no {answer} answer",
374            self.name
375        );
376        let schema = match (self.name, self.effect) {
377            (_, Effect::Mutating(_)) => schema_for!(crate::wire::ActionAnswer),
378            ("prints", _) => schema_for!(crate::wire::PrintsAnswer),
379            ("status", _) => schema_for!(crate::wire::StatusAnswer),
380            ("context", _) => schema_for!(crate::wire::ContextAnswer),
381            ("image", _) => schema_for!(crate::wire::ImageAnswer),
382            ("history", _) => schema_for!(crate::wire::HistoryAnswer),
383            ("manifest_get" | "manifest_set", _) => schema_for!(crate::wire::ManifestAnswer),
384            (name, _) => panic!("the operation `{name}` has no declared answer shape"),
385        };
386        schema.to_value()
387    }
388}
389
390/// The values declared beside an operation, at one place in the request.
391fn declared(entries: &'static [Declared], located: Located) -> impl Iterator<Item = Parameter> {
392    entries.iter().map(move |entry| Parameter {
393        name: entry.name.to_owned(),
394        required: entry.required,
395        located,
396        kind: entry.kind,
397    })
398}
399
400/// The shape one value declared beside an operation carries.
401///
402/// The contracts' own type where the declaration names one, and the kind's own
403/// scalar shape where it names none — a reason and a count are values this
404/// system mints no type for.
405fn declared_shape(entries: &'static [Declared], name: &str) -> Value {
406    let Some(entry) = entries.iter().find(|entry| entry.name == name) else {
407        return json!({ "type": "string" });
408    };
409    if let Some(shape) = entry.shape {
410        return json!({ "$ref": format!("#/$defs/{shape}") });
411    }
412    match entry.kind {
413        ValueKind::Text => json!({ "type": "string" }),
414        ValueKind::Number => json!({ "type": "number" }),
415        ValueKind::Integer => json!({ "type": "integer" }),
416        ValueKind::Boolean => json!({ "type": "boolean" }),
417        ValueKind::Structured => json!({ "type": "object" }),
418    }
419}
420
421/// The shape of each field one action of the vocabulary takes.
422///
423/// Read out of the contracts' own `PrintAction` beside
424/// [`action_parameters`], which walks the same variant for the same fields —
425/// so a field that gains a shape here gains a parameter there, and neither can
426/// carry one the other does not.
427///
428/// # Panics
429///
430/// Panics when the contracts declare no variant tagged with this action.
431fn action_shapes(kind: ActionKind) -> Vec<(String, Value)> {
432    let schema = printobserver_types::schemars::schema_for!(PrintAction).to_value();
433    let variant = action_variant(&schema, kind);
434    variant
435        .get("properties")
436        .and_then(Value::as_object)
437        .unwrap_or_else(|| panic!("the action `{kind:?}` declares no properties"))
438        .iter()
439        .filter(|(name, _)| name.as_str() != ACTION_TAG)
440        .map(|(name, field)| (name.clone(), field.clone()))
441        .collect()
442}
443
444/// The variant of the contracts' own action vocabulary one action tags.
445///
446/// # Panics
447///
448/// Panics when the contracts declare no variant tagged with this action, which
449/// is this server's declared list and that closed type having come apart.
450fn action_variant(schema: &Value, kind: ActionKind) -> Value {
451    let tag = printobserver_types::serde_json::to_value(kind)
452        .ok()
453        .and_then(|value| value.as_str().map(str::to_owned))
454        .unwrap_or_else(|| panic!("`{kind:?}` renders as the tag it is spelled by"));
455    schema
456        .get("oneOf")
457        .and_then(Value::as_array)
458        .and_then(|variants| {
459            variants.iter().find(|variant| {
460                variant.pointer(&format!("/properties/{ACTION_TAG}/const"))
461                    == Some(&json!(tag.clone()))
462            })
463        })
464        .cloned()
465        .unwrap_or_else(|| panic!("the contracts declare no action tagged `{tag}`"))
466}
467
468/// The values one path template takes, in the order it takes them.
469fn path_parameters(path: &str) -> Vec<Parameter> {
470    path.split('/')
471        .filter_map(|segment| segment.strip_prefix('{')?.strip_suffix('}'))
472        .map(|name| Parameter {
473            name: name.to_owned(),
474            // A route with a hole in its path is not a route: nothing reaches
475            // the handler without every segment of it.
476            required: true,
477            located: Located::Path,
478            // A path segment is text: what makes one an identifier is the type
479            // that minted it rather than anything a route can say.
480            kind: ValueKind::Text,
481        })
482        .collect()
483}
484
485/// The body one action of the vocabulary takes, out of the contracts' own type.
486///
487/// # Panics
488///
489/// Panics when the contracts declare no variant tagged with this action, which
490/// is this server's declared list and that closed type having come apart.
491fn action_parameters(kind: ActionKind) -> Vec<Parameter> {
492    let schema = printobserver_types::schemars::schema_for!(PrintAction).to_value();
493    let variant = action_variant(&schema, kind);
494    let required: Vec<&str> = variant
495        .get("required")
496        .and_then(Value::as_array)
497        .map(|names| names.iter().filter_map(Value::as_str).collect())
498        .unwrap_or_default();
499    let properties = variant
500        .get("properties")
501        .and_then(Value::as_object)
502        .unwrap_or_else(|| panic!("the action `{kind:?}` declares no properties"));
503    properties
504        .iter()
505        .filter(|(name, _)| name.as_str() != ACTION_TAG)
506        .map(|(name, field)| Parameter {
507            name: name.clone(),
508            required: required.contains(&name.as_str()),
509            located: Located::Body,
510            kind: kind_of(&resolve(&schema, field)),
511        })
512        .collect()
513}
514
515/// One field's own schema, following the one reference a contract field takes.
516fn resolve(schema: &Value, field: &Value) -> Value {
517    let Some(reference) = field.get("$ref").and_then(Value::as_str) else {
518        return field.clone();
519    };
520    reference
521        .strip_prefix("#/")
522        .and_then(|rest| schema.pointer(&format!("/{rest}")))
523        .cloned()
524        .unwrap_or_else(|| field.clone())
525}
526
527/// What kind of value one shape describes.
528///
529/// Read off the shape rather than off the field's name: a closed set of string
530/// constants is text however many of them there are, and an object is a
531/// document however few fields it has. A shape that says nothing this can
532/// decide is a document, which is the reading that still lets a caller supply
533/// it — as itself, or out of a file.
534fn kind_of(shape: &Value) -> ValueKind {
535    if let Some(declared) = shape.get("type") {
536        let named = |name: &str| match declared {
537            Value::String(one) => one == name,
538            Value::Array(many) => many.iter().any(|one| one == name),
539            _ => false,
540        };
541        if named("object") || named("array") {
542            return ValueKind::Structured;
543        }
544        if named("string") {
545            return ValueKind::Text;
546        }
547        if named("integer") {
548            return ValueKind::Integer;
549        }
550        if named("number") {
551            return ValueKind::Number;
552        }
553        if named("boolean") {
554            return ValueKind::Boolean;
555        }
556    }
557    match shape.get("oneOf").or_else(|| shape.get("anyOf")) {
558        Some(Value::Array(branches)) if !branches.is_empty() => {
559            let kinds: Vec<ValueKind> = branches
560                .iter()
561                .map(|branch| match branch.get("const") {
562                    Some(Value::String(_)) => ValueKind::Text,
563                    _ => kind_of(branch),
564                })
565                .collect();
566            let first = kinds[0];
567            if kinds.iter().all(|kind| *kind == first) {
568                first
569            } else {
570                ValueKind::Structured
571            }
572        }
573        _ => ValueKind::Structured,
574    }
575}
576
577/// One mutating operation, at the path its action is asked for under.
578const fn action(name: &'static str, path: &'static str, kind: ActionKind) -> Operation {
579    Operation {
580        name,
581        method: Method::Post,
582        path,
583        effect: Effect::Mutating(kind),
584        accepts: Some(MEDIA_TYPE),
585        answers: MEDIA_TYPE,
586        query: &[],
587        body: &[],
588        image_path_field: None,
589    }
590}
591
592/// One read, which takes no body.
593const fn read(name: &'static str, path: &'static str) -> Operation {
594    Operation {
595        name,
596        method: Method::Get,
597        path,
598        effect: Effect::Read,
599        accepts: None,
600        answers: MEDIA_TYPE,
601        query: &[],
602        body: &[],
603        image_path_field: None,
604    }
605}
606
607/// Every public operation this server serves, and there is no other.
608pub const OPERATIONS: [Operation; 17] = [
609    // Takes nothing: it is how a caller finds the identifier every other
610    // print-specific operation takes.
611    // llmlint: ignore[names_match_behavior] suppressions.toml has the reason.
612    read("prints", "/prints"),
613    read("status", "/prints/{print_id}/status"),
614    Operation {
615        image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
616        ..read("context", "/prints/{print_id}/context")
617    },
618    Operation {
619        image_path_field: Some(IMAGE_PATH_FIELD),
620        ..read("image", "/images/{image_id}")
621    },
622    Operation {
623        query: &[Declared {
624            name: "limit",
625            required: false,
626            kind: ValueKind::Integer,
627            shape: None,
628        }],
629        ..read("history", "/prints/{print_id}/history")
630    },
631    read("manifest_get", "/prints/{print_id}/manifest"),
632    Operation {
633        name: "manifest_set",
634        method: Method::Put,
635        path: "/prints/{print_id}/manifest",
636        effect: Effect::Write,
637        accepts: Some(MEDIA_TYPE),
638        answers: MEDIA_TYPE,
639        query: &[],
640        body: &[
641            Declared {
642                name: "reason",
643                required: true,
644                kind: ValueKind::Text,
645                shape: None,
646            },
647            Declared {
648                name: "manifest",
649                required: true,
650                kind: ValueKind::Structured,
651                shape: Some("JobManifest"),
652            },
653        ],
654        image_path_field: None,
655    },
656    action(
657        "pause",
658        "/prints/{print_id}/actions/pause",
659        ActionKind::Pause,
660    ),
661    action(
662        "resume",
663        "/prints/{print_id}/actions/resume",
664        ActionKind::Resume,
665    ),
666    action(
667        "cancel",
668        "/prints/{print_id}/actions/cancel",
669        ActionKind::Cancel,
670    ),
671    action(
672        "start_print",
673        "/prints/{print_id}/actions/start_print",
674        ActionKind::StartPrint,
675    ),
676    action(
677        "set_feedrate_factor",
678        "/prints/{print_id}/actions/set_feedrate_factor",
679        ActionKind::SetFeedrateFactor,
680    ),
681    action(
682        "set_flowrate_factor",
683        "/prints/{print_id}/actions/set_flowrate_factor",
684        ActionKind::SetFlowrateFactor,
685    ),
686    action(
687        "set_tool_target_c",
688        "/prints/{print_id}/actions/set_tool_target_c",
689        ActionKind::SetToolTargetC,
690    ),
691    action(
692        "set_bed_target_c",
693        "/prints/{print_id}/actions/set_bed_target_c",
694        ActionKind::SetBedTargetC,
695    ),
696    action(
697        "set_fan_percent",
698        "/prints/{print_id}/actions/set_fan_percent",
699        ActionKind::SetFanPercent,
700    ),
701    action(
702        "acknowledge_failure",
703        "/prints/{print_id}/actions/acknowledge_failure",
704        ActionKind::AcknowledgeFailure,
705    ),
706];
707
708/// The seven operations this server serves beside the action vocabulary.
709///
710/// Six of them read and the seventh writes a manifest, which asks nothing of
711/// the machine; what they have in common is that none of them is an action of
712/// the vocabulary the contracts declare.
713pub const BESIDE_THE_ACTIONS: [&str; 7] = [
714    "prints",
715    "status",
716    "context",
717    "image",
718    "history",
719    "manifest_get",
720    "manifest_set",
721];
722
723/// The operation of one name, when this server serves one.
724#[must_use]
725pub fn operation(name: &str) -> Option<&'static Operation> {
726    OPERATIONS.iter().find(|declared| declared.name == name)
727}
728
729#[cfg(test)]
730mod tests {
731    use printobserver_core::ActionKind;
732
733    use super::{Effect, MEDIA_TYPE, Method, OPERATIONS, VERSION_PREFIX, operation};
734
735    /// Every method is spelled the way the wire spells it.
736    #[test]
737    fn every_method_is_spelled_as_the_wire_spells_it() {
738        for (method, spelling) in [
739            (Method::Get, "GET"),
740            (Method::Post, "POST"),
741            (Method::Put, "PUT"),
742        ] {
743            assert_eq!(method.as_str(), spelling);
744            assert_eq!(method.to_string(), spelling);
745        }
746    }
747
748    /// An operation's whole path carries the one versioned prefix.
749    #[test]
750    fn every_operation_sits_beneath_the_one_versioned_prefix() {
751        for declared in OPERATIONS {
752            let whole = declared.full_path();
753            assert!(
754                whole.starts_with(VERSION_PREFIX),
755                "`{}` is served at {whole}",
756                declared.name
757            );
758            assert_eq!(declared.answers, MEDIA_TYPE);
759        }
760    }
761
762    /// A mutating operation names the action it asks for, and a read names none.
763    #[test]
764    fn a_mutating_operation_names_its_action_and_a_read_names_none() {
765        for declared in OPERATIONS {
766            match declared.effect {
767                Effect::Mutating(kind) => {
768                    assert_eq!(declared.action_kind(), Some(kind));
769                    assert!(declared.is_mutating());
770                }
771                Effect::Write => {
772                    assert_eq!(declared.action_kind(), None);
773                    assert!(
774                        declared.is_mutating(),
775                        "`{}` writes a record and is not held to the reason every \
776                         change carries",
777                        declared.name
778                    );
779                }
780                Effect::Read => {
781                    assert_eq!(declared.action_kind(), None);
782                    assert!(!declared.is_mutating());
783                }
784            }
785        }
786    }
787
788    /// A mutating operation takes JSON and answers JSON; a read takes no body.
789    ///
790    /// The two constructors are the only way an entry of the declared list is
791    /// made, so this is the shape every entry has by construction.
792    #[test]
793    fn a_mutating_operation_takes_a_body_and_a_read_takes_none() {
794        let mutating = super::action(
795            "pause",
796            "/prints/{print_id}/actions/pause",
797            ActionKind::Pause,
798        );
799        assert_eq!(mutating.method, Method::Post);
800        assert_eq!(mutating.accepts, Some(MEDIA_TYPE));
801        assert_eq!(mutating.answers, MEDIA_TYPE);
802        assert_eq!(mutating.action_kind(), Some(ActionKind::Pause));
803
804        let reading = super::read("status", "/prints/{print_id}/status");
805        assert_eq!(reading.method, Method::Get);
806        assert_eq!(reading.accepts, None);
807        assert_eq!(reading.answers, MEDIA_TYPE);
808        assert_eq!(reading.effect, Effect::Read);
809    }
810
811    /// An operation this server does not serve is answered as none.
812    #[test]
813    fn an_operation_this_server_does_not_serve_is_answered_as_none() {
814        assert_eq!(operation("pause").map(|found| found.name), Some("pause"));
815        assert!(operation("reboot").is_none());
816    }
817}