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