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