Skip to main content

printobserver_server/
config.rs

1//! The one configuration file a running supervisor reads, and its validation.
2//!
3//! # Every field this program takes is declared once, here
4//!
5//! [`ConfigField`] is that declaration: one variant per configured value, each
6//! carrying the dotted key it is spelled under. Two things read it rather than
7//! restating it — the refusal a bad value produces names its field through it,
8//! and this crate's own tier walks it, driving a server against a configuration
9//! in which each field in turn is unacceptable. A field added to the shapes
10//! below and not to [`ConfigField::ALL`] fails that tier's own coverage check,
11//! so the walk cannot fall behind the type.
12//!
13//! # Validation happens at startup, and names the field
14//!
15//! A value that cannot work is refused where it is configured rather than at
16//! the first request that needs it, and the refusal carries the field's own key
17//! so an operator editing the file knows which line to change. That includes
18//! the two values only the machine can rule on: an `OctoPrint` address nothing
19//! answers at and a key that instance refuses are both configuration mistakes,
20//! and [`crate::Server::start`] refuses them naming
21//! [`ConfigField::OctoprintUrl`] and [`ConfigField::OctoprintApiKey`].
22//!
23//! # The ingress answer bound
24//!
25//! `Obico`'s webhook notification plugin posts best-effort with a short timeout
26//! and does not retry, so this server answers its ingress before the handling
27//! completes and inside a bound it declares here. The shipped default is
28//! [`DEFAULT_INGRESS_ANSWER_BOUND_MS`] and the timeout it must stay below is
29//! [`OBICO_POSTING_TIMEOUT_MS`]; `AGENTS.md`'s "The Obico ingress answer bound"
30//! records that number, where it was read and why the default is where it is,
31//! and `just check-repo` refuses a tree in which the two disagree.
32//!
33//! # The operator's credential, by its verifier
34//!
35//! Every request beneath the versioned prefix carries one credential. The
36//! operator's is checked against a [`CredentialVerifier`] — the SHA-256 of the
37//! credential, written `sha256:<64 lowercase hex>` — which `api.credential_verifier`
38//! names, so the server holds nothing a supervision turn reading its files
39//! could authenticate with. The plaintext lives with the operator, in the
40//! client configuration `printobserver credential issue` writes.
41//!
42//! `api.credential`, a plaintext credential, is still read for an installation
43//! that wrote one, and admitted until it is replaced; the composition root warns
44//! on every start that it is there. Either way a credential is held in a type
45//! neither rendering of which shows it, and is compared in constant time.
46//!
47//! # The periodic observation
48//!
49//! `supervisor.observation_interval_s` is how often every active print is given
50//! a periodic observation and its agent a turn on it, whether or not the
51//! detector has alerted. Left out it is
52//! [`DEFAULT_OBSERVATION_INTERVAL_S`] — two minutes — and zero is refused,
53//! because an interval of nothing is a turn started the moment the last one
54//! returns.
55//!
56//! # The printer watch
57//!
58//! `supervisor.printer_poll_s` is how often the printer watch reads the machine
59//! — from 5 to 300 seconds, fifteen when left out — whether or not a print is
60//! active, and `supervisor.unattended_window_s` how long after a print ends
61//! `interrupted` or `failed` the printer heating or moving on its own is
62//! recorded — from 60 to 86400 seconds, an hour when left out. A value outside
63//! either range is refused naming its key.
64//!
65//! # The camera and `Obico`'s own API
66//!
67//! Both are optional. `camera.snapshot_url` is where a look fetches a fresh
68//! frame; without it a look carries the printer's state and no frame.
69//! `obico.url` and `obico.access_token` are given together or not at all: they
70//! are how a print the detector paused and the agent adjusted is acknowledged
71//! to `Obico`, which re-arms its detection. Each address must be an `http` or
72//! `https` URL, and the token is held in a type whose debug form never shows
73//! it, so no refusal or log line this program writes can carry it.
74//! `obico.ml_api_url` is the failure detector's own service, whose
75//! unauthenticated health check is asked during every print; without it the
76//! detector's health reads `unchecked`. `vision.blank_frame_max_stddev` is the
77//! grey-level spread at or below which a frame is blank — from 1 to 128, 36.5
78//! when left out.
79//!
80//! # Recovery
81//!
82//! `[recovery]` states the printer's own facts a recovery action is checked
83//! against — `away_from_bed` (`z_plus` or `z_minus`), `max_z_mm`,
84//! `max_lift_mm` (50 when left out), `clearance_margin_mm` (5 when left out),
85//! `park_xy`, `z_home_xy` and `z_home_sweeps_bed`. Left out, every recovery
86//! action is refused as not configured; written, every key without a default
87//! is required. `[policy.recovery]` says who may ask for which: `operator`,
88//! `agent` and `asserting`, by default every action, none, and the operator
89//! alone. Granting `recover_home_z` to the agent, or letting the agent's word
90//! count as clearance, is refused naming the key, and so is every value
91//! outside the range its key admits.
92//!
93//! # The spool check
94//!
95//! `[spools]` is optional, and so is every key in it: `preflight` is what a
96//! start does when the loaded spool is short, unverified or the file has no
97//! analysis — `refuse`, `warn` or `off` — `buffer_percent` and `buffer_min_g`
98//! the margin asked beyond what a print needs, and `analysis_wait_seconds` how
99//! long a start waits for `OctoPrint`'s analysis of a file that has none yet.
100//! Each left out takes the supervision core's own default, and a negative
101//! figure or a mode outside the three is refused naming its key.
102
103use std::net::SocketAddr;
104use std::path::{Path, PathBuf};
105
106use printobserver_core::{
107    ActionKind, ActorClass, AwayFromBed, DEFAULT_CLEARANCE_MARGIN_MM, DEFAULT_MAX_LIFT_MM,
108    PreflightMode, RecoveryActionKind, RecoveryConfig, RecoveryGrants, SafetyEnvelope, SpoolPolicy,
109};
110use printobserver_obico::{
111    AccessToken, BlankFrameBound, MAX_BLANK_FRAME_MAX_STDDEV, MIN_BLANK_FRAME_MAX_STDDEV, ObicoApi,
112};
113use printobserver_octoprint::{FanSupport, OctoPrintConfig};
114use printobserver_oneharness::{HarnessIdentity, ModelName};
115use printobserver_types::schemars::JsonSchema;
116use printobserver_types::serde::{Deserialize, Serialize};
117use printobserver_vision_api::WebAddress;
118
119/// The answer bound this repository ships, in milliseconds.
120///
121/// A fifth of [`OBICO_POSTING_TIMEOUT_MS`]. The margin is deliberate: the
122/// supported host is a small ARM board beside the printer, and a bound set just
123/// under the producer's timeout would be exceeded by the first slow moment on
124/// it — after which `Obico` drops the alert, because its posting does not retry.
125pub const DEFAULT_INGRESS_ANSWER_BOUND_MS: u64 = 1_000;
126
127/// How often every active print is observed, in seconds, when the
128/// configuration names no interval: the core's own default.
129pub const DEFAULT_OBSERVATION_INTERVAL_S: u64 =
130    printobserver_core::DEFAULT_OBSERVATION_INTERVAL.as_secs();
131
132/// How often the printer watch reads the machine, in seconds, when the
133/// configuration names no poll: the core's own default.
134pub const DEFAULT_PRINTER_POLL_S: u64 = printobserver_core::DEFAULT_PRINTER_POLL.as_secs();
135
136/// The least and the most seconds `supervisor.printer_poll_s` admits.
137pub const PRINTER_POLL_RANGE_S: (u64, u64) = (5, 300);
138
139/// How long after an unfinished ending activity is recorded, in seconds, when
140/// the configuration names no window: the core's own default.
141pub const DEFAULT_UNATTENDED_WINDOW_S: u64 =
142    printobserver_core::DEFAULT_UNATTENDED_WINDOW.as_secs();
143
144/// The least and the most seconds `supervisor.unattended_window_s` admits.
145pub const UNATTENDED_WINDOW_RANGE_S: (u64, u64) = (60, 86_400);
146
147/// The timeout `Obico`'s own webhook notification plugin posts under.
148///
149/// Read from the `Obico` release the `obico-fixture` node stands up — revision
150/// `49c0bc7001a3fd8d56297fc3032ba287bfe1d50b`,
151/// `backend/notifications/plugins/webhook/__init__.py`, whose `execute_webhook`
152/// takes `timeout: float = 5.0` and calls `raise_for_status` with no retry.
153/// This repository's claim about an external producer; what reconciles it
154/// against a live `Obico` is the scheduled `Obico` tier.
155pub const OBICO_POSTING_TIMEOUT_MS: u64 = 5_000;
156
157/// The directory under the state directory this server materializes the
158/// supervising agent's prompt template and assessment schema into. The skill
159/// is not among them: it is installed with [`SKILL_INSTALL`] and configured by
160/// `supervisor.skill_path`.
161pub const ASSETS_DIRECTORY: &str = "assets";
162
163/// How the supervising agent's skill is installed, and what names it after.
164///
165/// This program carries no skill of its own: the skill is the Agent Skill this
166/// repository publishes, installed as any other is, and every refusal of
167/// `supervisor.skill_path` says so, because it is the one instruction an
168/// operator whose configuration predates that needs.
169pub const SKILL_INSTALL: &str = "the skill is installed with `gh skill install \
170     nickderobertis/printobserver printobserver --dir <dir>`, and \
171     `supervisor.skill_path` names the installed `SKILL.md`, \
172     `<dir>/printobserver/SKILL.md`";
173
174/// Every value this program is configured with, and the key it is spelled under.
175///
176/// The walk in this crate's tier is over this array, and the array is compared
177/// against the configuration shapes' own declared properties, so neither can
178/// grow a field the other does not know about.
179#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
180pub enum ConfigField {
181    /// Where the store, the images and the sessions live.
182    StateDir,
183    /// The address the API and the ingress are served on.
184    Listen,
185    /// Where the `OctoPrint` instance answers.
186    OctoprintUrl,
187    /// The key that instance authenticates every request by.
188    OctoprintApiKey,
189    /// Whether the machine has a part-cooling fan this server may command.
190    OctoprintFan,
191    /// The operator's safety envelope.
192    SafetyEnvelope,
193    /// The harness identity supervision turns run on.
194    Harness,
195    /// The model turns are pinned to, when one is pinned.
196    Model,
197    /// The `PrintObserver` skill sent as every turn's system prompt.
198    SkillPath,
199    /// The prompt template one turn fills.
200    PromptTemplatePath,
201    /// How often every active print is observed, in seconds.
202    ObservationIntervalS,
203    /// How often the printer watch reads the machine, in seconds.
204    PrinterPollS,
205    /// How long after an unfinished ending the printer acting on its own is
206    /// recorded, in seconds.
207    UnattendedWindowS,
208    /// How long the ingress may take to answer, in milliseconds.
209    IngressAnswerBoundMs,
210    /// The shared secret the ingress requires of every post.
211    IngressSharedSecret,
212    /// A plaintext operator credential, read for an installation that wrote
213    /// one until it is replaced by its verifier.
214    ApiCredential,
215    /// The verifier the operator's credential is checked against.
216    ApiCredentialVerifier,
217    /// Where a fresh frame of the print is fetched from, when a camera is
218    /// configured.
219    CameraSnapshotUrl,
220    /// Where `Obico`'s own API answers, when it is configured.
221    ObicoUrl,
222    /// The bearer token `Obico`'s API is reached with.
223    ObicoAccessToken,
224    /// Where the failure detector's own service answers its health check.
225    ObicoMlApiUrl,
226    /// The grey-level spread at or below which a camera frame is blank.
227    VisionBlankFrameMaxStddev,
228    /// What a start does when the spool check finds a problem.
229    SpoolsPreflight,
230    /// The margin asked beyond a print's requirement, as a percentage of it.
231    SpoolsBufferPercent,
232    /// The least margin asked, in grams.
233    SpoolsBufferMinG,
234    /// How long a start waits for a file's analysis, in seconds.
235    SpoolsAnalysisWaitSeconds,
236    /// Which way along Z moves the nozzle away from the bed.
237    RecoveryAwayFromBed,
238    /// The highest Z the machine reaches, in millimetres.
239    RecoveryMaxZMm,
240    /// The longest lift one recovery may ask for, in millimetres.
241    RecoveryMaxLiftMm,
242    /// How far above the tallest part the nozzle must be, in millimetres.
243    RecoveryClearanceMarginMm,
244    /// Where a park moves the head, in X and Y.
245    RecoveryParkXy,
246    /// Where the machine homes Z, in X and Y.
247    RecoveryZHomeXy,
248    /// Whether homing Z brings a gantry down over the whole bed.
249    RecoveryZHomeSweepsBed,
250    /// The recovery actions the operator may ask for.
251    PolicyRecoveryOperator,
252    /// The recovery actions the agent may ask for.
253    PolicyRecoveryAgent,
254    /// The actor classes whose clearance assertions count.
255    PolicyRecoveryAsserting,
256}
257
258impl ConfigField {
259    /// Every field this program takes, and there is no other.
260    pub const ALL: [Self; 36] = [
261        Self::StateDir,
262        Self::Listen,
263        Self::OctoprintUrl,
264        Self::OctoprintApiKey,
265        Self::OctoprintFan,
266        Self::SafetyEnvelope,
267        Self::Harness,
268        Self::Model,
269        Self::SkillPath,
270        Self::PromptTemplatePath,
271        Self::ObservationIntervalS,
272        Self::PrinterPollS,
273        Self::UnattendedWindowS,
274        Self::IngressAnswerBoundMs,
275        Self::IngressSharedSecret,
276        Self::ApiCredential,
277        Self::ApiCredentialVerifier,
278        Self::CameraSnapshotUrl,
279        Self::ObicoUrl,
280        Self::ObicoAccessToken,
281        Self::ObicoMlApiUrl,
282        Self::VisionBlankFrameMaxStddev,
283        Self::SpoolsPreflight,
284        Self::SpoolsBufferPercent,
285        Self::SpoolsBufferMinG,
286        Self::SpoolsAnalysisWaitSeconds,
287        Self::RecoveryAwayFromBed,
288        Self::RecoveryMaxZMm,
289        Self::RecoveryMaxLiftMm,
290        Self::RecoveryClearanceMarginMm,
291        Self::RecoveryParkXy,
292        Self::RecoveryZHomeXy,
293        Self::RecoveryZHomeSweepsBed,
294        Self::PolicyRecoveryOperator,
295        Self::PolicyRecoveryAgent,
296        Self::PolicyRecoveryAsserting,
297    ];
298
299    /// The dotted key this field is spelled under in the configuration file.
300    #[must_use]
301    pub const fn key(self) -> &'static str {
302        match self {
303            Self::StateDir => "state_dir",
304            Self::Listen => "listen",
305            Self::OctoprintUrl => "octoprint.url",
306            Self::OctoprintApiKey => "octoprint.api_key",
307            Self::OctoprintFan => "octoprint.fan",
308            Self::SafetyEnvelope => "safety",
309            Self::Harness => "supervisor.harness",
310            Self::Model => "supervisor.model",
311            Self::SkillPath => "supervisor.skill_path",
312            Self::PromptTemplatePath => "supervisor.prompt_template_path",
313            Self::ObservationIntervalS => "supervisor.observation_interval_s",
314            Self::PrinterPollS => "supervisor.printer_poll_s",
315            Self::UnattendedWindowS => "supervisor.unattended_window_s",
316            Self::IngressAnswerBoundMs => "ingress.answer_bound_ms",
317            Self::IngressSharedSecret => "ingress.shared_secret",
318            Self::ApiCredential => "api.credential",
319            Self::ApiCredentialVerifier => "api.credential_verifier",
320            Self::CameraSnapshotUrl => "camera.snapshot_url",
321            Self::ObicoUrl => "obico.url",
322            Self::ObicoAccessToken => "obico.access_token",
323            Self::ObicoMlApiUrl => "obico.ml_api_url",
324            Self::VisionBlankFrameMaxStddev => "vision.blank_frame_max_stddev",
325            Self::SpoolsPreflight => "spools.preflight",
326            Self::SpoolsBufferPercent => "spools.buffer_percent",
327            Self::SpoolsBufferMinG => "spools.buffer_min_g",
328            Self::SpoolsAnalysisWaitSeconds => "spools.analysis_wait_seconds",
329            Self::RecoveryAwayFromBed => "recovery.away_from_bed",
330            Self::RecoveryMaxZMm => "recovery.max_z_mm",
331            Self::RecoveryMaxLiftMm => "recovery.max_lift_mm",
332            Self::RecoveryClearanceMarginMm => "recovery.clearance_margin_mm",
333            Self::RecoveryParkXy => "recovery.park_xy",
334            Self::RecoveryZHomeXy => "recovery.z_home_xy",
335            Self::RecoveryZHomeSweepsBed => "recovery.z_home_sweeps_bed",
336            Self::PolicyRecoveryOperator => "policy.recovery.operator",
337            Self::PolicyRecoveryAgent => "policy.recovery.agent",
338            Self::PolicyRecoveryAsserting => "policy.recovery.asserting",
339        }
340    }
341}
342
343impl core::fmt::Display for ConfigField {
344    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
345        formatter.write_str(self.key())
346    }
347}
348
349/// Why this server will not start under the configuration it was given.
350///
351/// Every variant names the field it is about, because the answer an operator
352/// needs is which line of the file to change.
353#[derive(Debug, Clone, PartialEq, Eq)]
354pub enum ConfigError {
355    /// The file could not be read at all.
356    Unreadable {
357        /// The path that was named.
358        path: PathBuf,
359        /// What went wrong reading it.
360        detail: String,
361    },
362    /// The file is not the document this program takes.
363    Unparsable {
364        /// The path that was named.
365        path: PathBuf,
366        /// What could not be parsed, in the parser's own words.
367        detail: String,
368    },
369    /// One field carries a value this program cannot accept.
370    Field {
371        /// The field it is about.
372        field: ConfigField,
373        /// Why the value cannot be accepted.
374        detail: String,
375    },
376}
377
378impl ConfigError {
379    /// The field this refusal is about, when it is about one.
380    #[must_use]
381    pub const fn field(&self) -> Option<ConfigField> {
382        match self {
383            Self::Field { field, .. } => Some(*field),
384            _ => None,
385        }
386    }
387
388    /// One field's refusal, in its own words.
389    pub(crate) fn about(field: ConfigField, detail: impl Into<String>) -> Self {
390        Self::Field {
391            field,
392            detail: detail.into(),
393        }
394    }
395}
396
397impl core::fmt::Display for ConfigError {
398    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
399        match self {
400            Self::Unreadable { path, detail } => write!(
401                formatter,
402                "the configuration file {} could not be read: {detail}",
403                path.display()
404            ),
405            Self::Unparsable { path, detail } => write!(
406                formatter,
407                "the configuration file {} could not be read as this program's \
408                 configuration: {detail}",
409                path.display()
410            ),
411            Self::Field { field, detail } => write!(
412                formatter,
413                "the configuration field `{field}` cannot be accepted: {detail}"
414            ),
415        }
416    }
417}
418
419impl core::error::Error for ConfigError {}
420
421/// Where the `OctoPrint` instance is and what it is like, as written down.
422#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
423#[serde(
424    crate = "printobserver_types::serde",
425    deny_unknown_fields,
426    rename_all = "snake_case"
427)]
428#[schemars(crate = "printobserver_types::schemars")]
429pub struct OctoprintSection {
430    /// The base URL the instance answers on.
431    #[serde(default, skip_serializing_if = "Option::is_none")]
432    pub url: Option<String>,
433    /// The key it authenticates every request by.
434    #[serde(default, skip_serializing_if = "Option::is_none")]
435    pub api_key: Option<String>,
436    /// Whether the machine has a part-cooling fan this server may command.
437    #[serde(default = "commandable")]
438    pub fan: String,
439}
440
441/// The vocabulary [`OctoprintSection::fan`] takes, spelled as the operator
442/// writes it.
443pub const FAN_VOCABULARY: [(&str, FanSupport); 2] = [
444    ("commandable", FanSupport::Commandable),
445    ("absent", FanSupport::Absent),
446];
447
448/// The fan setting a configuration naming none takes.
449fn commandable() -> String {
450    FAN_VOCABULARY[0].0.to_owned()
451}
452
453impl Default for OctoprintSection {
454    fn default() -> Self {
455        Self {
456            url: None,
457            api_key: None,
458            fan: commandable(),
459        }
460    }
461}
462
463/// How the supervising agent is reached, as written down.
464#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
465#[serde(
466    crate = "printobserver_types::serde",
467    deny_unknown_fields,
468    rename_all = "snake_case"
469)]
470#[schemars(crate = "printobserver_types::schemars")]
471pub struct SupervisorSection {
472    /// The harness identity turns run on.
473    #[serde(default, skip_serializing_if = "Option::is_none")]
474    pub harness: Option<String>,
475    /// The model turns are pinned to, when one is pinned.
476    #[serde(default, skip_serializing_if = "Option::is_none")]
477    pub model: Option<String>,
478    /// The installed skill's `SKILL.md`, whose prose is sent as every turn's
479    /// system prompt; the agent runs from the directory holding it. Required:
480    /// this program carries no skill, and an absent one refuses the start.
481    #[serde(default, skip_serializing_if = "Option::is_none")]
482    pub skill_path: Option<PathBuf>,
483    /// The prompt template one turn fills, when the operator supplies one
484    /// instead of the committed template this program carries.
485    #[serde(default, skip_serializing_if = "Option::is_none")]
486    pub prompt_template_path: Option<PathBuf>,
487    /// How often every active print is given a periodic observation, and its
488    /// agent a turn on it, in seconds. Left out, two minutes.
489    #[serde(default = "default_observation_interval_s")]
490    pub observation_interval_s: u64,
491    /// How often the printer watch reads the machine, whether or not a print
492    /// is active, in seconds: from 5 to 300. Left out, fifteen seconds.
493    #[serde(default = "default_printer_poll_s")]
494    pub printer_poll_s: u64,
495    /// How long after a print ends `interrupted` or `failed` the printer
496    /// heating or moving on its own is recorded, in seconds: from 60 to
497    /// 86400. Left out, an hour.
498    #[serde(default = "default_unattended_window_s")]
499    pub unattended_window_s: u64,
500}
501
502/// The printer poll a configuration naming none takes.
503const fn default_printer_poll_s() -> u64 {
504    DEFAULT_PRINTER_POLL_S
505}
506
507/// The unattended window a configuration naming none takes.
508const fn default_unattended_window_s() -> u64 {
509    DEFAULT_UNATTENDED_WINDOW_S
510}
511
512/// The observation interval a configuration naming none takes.
513const fn default_observation_interval_s() -> u64 {
514    DEFAULT_OBSERVATION_INTERVAL_S
515}
516
517impl Default for SupervisorSection {
518    fn default() -> Self {
519        Self {
520            harness: None,
521            model: None,
522            skill_path: None,
523            prompt_template_path: None,
524            observation_interval_s: DEFAULT_OBSERVATION_INTERVAL_S,
525            printer_poll_s: DEFAULT_PRINTER_POLL_S,
526            unattended_window_s: DEFAULT_UNATTENDED_WINDOW_S,
527        }
528    }
529}
530
531/// What the `Obico` ingress requires and how fast it answers, as written down.
532#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
533#[serde(
534    crate = "printobserver_types::serde",
535    deny_unknown_fields,
536    rename_all = "snake_case"
537)]
538#[schemars(crate = "printobserver_types::schemars")]
539pub struct IngressSection {
540    /// The shared secret every post must carry.
541    #[serde(default, skip_serializing_if = "Option::is_none")]
542    pub shared_secret: Option<String>,
543    /// How long the ingress may take to answer, in milliseconds.
544    #[serde(default = "default_answer_bound_ms")]
545    pub answer_bound_ms: u64,
546}
547
548/// The answer bound a configuration naming none takes.
549const fn default_answer_bound_ms() -> u64 {
550    DEFAULT_INGRESS_ANSWER_BOUND_MS
551}
552
553impl Default for IngressSection {
554    fn default() -> Self {
555        Self {
556            shared_secret: None,
557            answer_bound_ms: DEFAULT_INGRESS_ANSWER_BOUND_MS,
558        }
559    }
560}
561
562/// What a caller of the versioned API authenticates with, as written down.
563#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
564#[serde(
565    crate = "printobserver_types::serde",
566    deny_unknown_fields,
567    rename_all = "snake_case"
568)]
569#[schemars(crate = "printobserver_types::schemars")]
570pub struct ApiSection {
571    /// A plaintext operator credential. Superseded by `credential_verifier`:
572    /// still admitted until it is replaced, with a warning on every start,
573    /// because a supervision turn can read the file it is written in.
574    #[serde(default, skip_serializing_if = "Option::is_none")]
575    pub credential: Option<String>,
576    /// The verifier the operator's credential is checked against:
577    /// `sha256:` and the 64 lowercase hexadecimal digits of the SHA-256 of the
578    /// credential's UTF-8 bytes, as `printobserver credential issue` prints it.
579    /// Left out, the server reads `api-credential.verifier` in its state
580    /// directory, and admits no operator at all when that is absent too.
581    #[serde(default, skip_serializing_if = "Option::is_none")]
582    pub credential_verifier: Option<String>,
583}
584
585/// Where a fresh frame of the print is fetched from, as written down.
586#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
587#[serde(
588    crate = "printobserver_types::serde",
589    deny_unknown_fields,
590    rename_all = "snake_case"
591)]
592#[schemars(crate = "printobserver_types::schemars")]
593pub struct CameraSection {
594    /// An `http` or `https` URL answering one still image of the print, such
595    /// as a `go2rtc` `frame.jpeg` address. Left out, a look carries no frame.
596    #[serde(default, skip_serializing_if = "Option::is_none")]
597    pub snapshot_url: Option<String>,
598}
599
600/// Where `Obico`'s own API answers, as written down.
601///
602/// Its debug form never shows the token.
603#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
604#[serde(
605    crate = "printobserver_types::serde",
606    deny_unknown_fields,
607    rename_all = "snake_case"
608)]
609#[schemars(crate = "printobserver_types::schemars")]
610pub struct ObicoSection {
611    /// The server's own `http` or `https` address, such as
612    /// `http://127.0.0.1:3334`. Given with `access_token` or not at all.
613    #[serde(default, skip_serializing_if = "Option::is_none")]
614    pub url: Option<String>,
615    /// A bearer token for its API, issued by the instance's own OAuth
616    /// administration. Left out with the address, a print the detector paused
617    /// and the supervisor resumed is not acknowledged to `Obico`.
618    #[serde(default, skip_serializing_if = "Option::is_none")]
619    pub access_token: Option<String>,
620    /// The failure detector's own service — `Obico`'s `ml_api` — as an `http`
621    /// or `https` address, whose unauthenticated `/hc/` is asked during every
622    /// print whether detection is up. Left out, nothing checks it and its
623    /// health reads `unchecked`.
624    #[serde(default, skip_serializing_if = "Option::is_none")]
625    pub ml_api_url: Option<String>,
626}
627
628/// How a camera frame is judged, as written down.
629#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
630#[serde(
631    crate = "printobserver_types::serde",
632    deny_unknown_fields,
633    rename_all = "snake_case"
634)]
635#[schemars(crate = "printobserver_types::schemars")]
636pub struct VisionSection {
637    /// The grey-level standard deviation at or below which a frame is blank
638    /// and is fetched again: from 1 to 128. Left out, 36.5.
639    #[serde(default, skip_serializing_if = "Option::is_none")]
640    pub blank_frame_max_stddev: Option<f64>,
641}
642
643impl core::fmt::Debug for ObicoSection {
644    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
645        formatter
646            .debug_struct("ObicoSection")
647            .field("url", &self.url)
648            .field(
649                "access_token",
650                &self.access_token.as_ref().map(|_| REDACTED),
651            )
652            .field("ml_api_url", &self.ml_api_url)
653            .finish()
654    }
655}
656
657/// How spools are checked before a print, as written down.
658///
659/// Every key is optional, and one left out takes the supervision core's own
660/// default. The mode is read as text rather than as the core's own type so
661/// that a mode outside the three is refused naming its key rather than by the
662/// parser in words of its own.
663#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
664#[serde(
665    crate = "printobserver_types::serde",
666    deny_unknown_fields,
667    rename_all = "snake_case"
668)]
669#[schemars(crate = "printobserver_types::schemars")]
670pub struct SpoolsSection {
671    /// What a start does when the loaded spool is short, unverified, or the
672    /// file has no analysis: `refuse`, `warn` or `off`. Left out, `refuse`.
673    #[serde(default, skip_serializing_if = "Option::is_none")]
674    pub preflight: Option<String>,
675    /// The margin asked beyond what a print needs, as a percentage of it.
676    #[serde(default, skip_serializing_if = "Option::is_none")]
677    pub buffer_percent: Option<f64>,
678    /// The least margin asked, in grams, however small the print.
679    #[serde(default, skip_serializing_if = "Option::is_none")]
680    pub buffer_min_g: Option<f64>,
681    /// How long a start waits for `OctoPrint`'s analysis of a file that has
682    /// none yet, in whole seconds; zero waits not at all.
683    #[serde(default, skip_serializing_if = "Option::is_none")]
684    pub analysis_wait_seconds: Option<i64>,
685}
686
687/// The printer's own facts a recovery is checked against, as written down.
688///
689/// Left out altogether, or written with no key, no recovery action can be
690/// checked and every one is refused as not configured. Written with any key,
691/// every key without a default is required. Each is read as written so that a
692/// value that cannot work is refused naming its key.
693#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
694#[serde(
695    crate = "printobserver_types::serde",
696    deny_unknown_fields,
697    rename_all = "snake_case"
698)]
699#[schemars(crate = "printobserver_types::schemars")]
700pub struct RecoverySection {
701    /// Which way along Z moves the nozzle away from the bed: `z_plus` or
702    /// `z_minus`.
703    #[serde(default, skip_serializing_if = "Option::is_none")]
704    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
705    pub away_from_bed: Option<String>,
706    /// The highest Z the machine reaches, in millimetres.
707    #[serde(default, skip_serializing_if = "Option::is_none")]
708    pub max_z_mm: Option<f64>,
709    /// The longest lift one recovery may ask for, in millimetres; 50 when
710    /// left out.
711    #[serde(default, skip_serializing_if = "Option::is_none")]
712    pub max_lift_mm: Option<f64>,
713    /// How far above the tallest part the nozzle must be, in millimetres; 5
714    /// when left out.
715    #[serde(default, skip_serializing_if = "Option::is_none")]
716    pub clearance_margin_mm: Option<f64>,
717    /// Where a park moves the head, as `[x, y]` in millimetres.
718    #[serde(default, skip_serializing_if = "Option::is_none")]
719    pub park_xy: Option<Vec<f64>>,
720    /// Where the machine homes Z, as `[x, y]` in millimetres.
721    #[serde(default, skip_serializing_if = "Option::is_none")]
722    pub z_home_xy: Option<Vec<f64>>,
723    /// Whether homing Z brings a gantry down over the whole bed.
724    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
725    #[serde(default, skip_serializing_if = "Option::is_none")]
726    pub z_home_sweeps_bed: Option<bool>,
727}
728
729/// Who may ask for which recovery action, as written down under
730/// `[policy.recovery]`. Each list left out takes its default: the operator
731/// every action, the agent none, and only the operator's assertions counting.
732#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
733#[serde(
734    crate = "printobserver_types::serde",
735    deny_unknown_fields,
736    rename_all = "snake_case"
737)]
738#[schemars(crate = "printobserver_types::schemars")]
739pub struct RecoveryPolicySection {
740    /// The recovery actions the operator may ask for, by name.
741    #[serde(default, skip_serializing_if = "Option::is_none")]
742    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
743    pub operator: Option<Vec<String>>,
744    /// The recovery actions the agent may ask for, by name. `recover_home_z`
745    /// is refused here.
746    #[serde(default, skip_serializing_if = "Option::is_none")]
747    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
748    pub agent: Option<Vec<String>>,
749    /// The actor classes whose word that the nozzle or the bed is clear
750    /// counts. `agent` is refused here.
751    #[serde(default, skip_serializing_if = "Option::is_none")]
752    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
753    pub asserting: Option<Vec<String>>,
754}
755
756/// The policies this program is configured with beside the safety envelope.
757#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
758#[serde(
759    crate = "printobserver_types::serde",
760    deny_unknown_fields,
761    rename_all = "snake_case"
762)]
763#[schemars(crate = "printobserver_types::schemars")]
764pub struct PolicySection {
765    /// Who may ask for which recovery action.
766    #[serde(default)]
767    pub recovery: RecoveryPolicySection,
768}
769
770/// The whole configuration file, exactly as it is written down.
771///
772/// This is the parsed document rather than the validated configuration:
773/// [`ServerConfig::load`] is what turns one into the other, and every value a
774/// later step could find wrong is ruled on there.
775#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
776#[serde(
777    crate = "printobserver_types::serde",
778    deny_unknown_fields,
779    rename_all = "snake_case"
780)]
781#[schemars(crate = "printobserver_types::schemars")]
782pub struct ConfigFile {
783    /// Where the store, the images and the sessions live.
784    #[serde(default, skip_serializing_if = "Option::is_none")]
785    pub state_dir: Option<PathBuf>,
786    /// The address the API and the ingress are served on.
787    #[serde(default, skip_serializing_if = "Option::is_none")]
788    pub listen: Option<String>,
789    /// Where the `OctoPrint` instance is.
790    #[serde(default)]
791    pub octoprint: OctoprintSection,
792    /// The operator's safety envelope.
793    #[serde(default, skip_serializing_if = "Option::is_none")]
794    pub safety: Option<SafetyEnvelope>,
795    /// How the supervising agent is reached.
796    #[serde(default)]
797    pub supervisor: SupervisorSection,
798    /// What the `Obico` ingress requires.
799    #[serde(default)]
800    pub ingress: IngressSection,
801    /// What a caller of the versioned API authenticates with.
802    #[serde(default)]
803    pub api: ApiSection,
804    /// Where a fresh frame of the print is fetched from.
805    #[serde(default)]
806    pub camera: CameraSection,
807    /// Where `Obico`'s own API answers.
808    #[serde(default)]
809    pub obico: ObicoSection,
810    /// How a camera frame is judged.
811    #[serde(default)]
812    pub vision: VisionSection,
813    /// How spools are checked before a print.
814    #[serde(default)]
815    pub spools: SpoolsSection,
816    /// The printer's own facts a recovery is checked against.
817    #[serde(default)]
818    pub recovery: RecoverySection,
819    /// The policies beside the safety envelope.
820    #[serde(default)]
821    pub policy: PolicySection,
822}
823
824/// The shared secret the ingress requires of every post.
825///
826/// Neither rendering of this type shows the value, so it cannot reach a log
827/// record, a panic message or an error's own text by being formatted — and the
828/// comparison that admits a post lives here rather than at the endpoint, so
829/// there is no way to read the secret out in order to compare it.
830#[derive(Clone, PartialEq, Eq)]
831pub struct SharedSecret(String);
832
833/// What a secret renders as, wherever a value carrying one is rendered.
834pub const REDACTED: &str = "<redacted>";
835
836impl SharedSecret {
837    /// The secret this text names.
838    ///
839    /// # Errors
840    ///
841    /// Returns [`ConfigError`] when the text is empty or is nothing but
842    /// whitespace: anything that can post to the ingress can pause a printer,
843    /// and a secret nothing has to carry is no secret.
844    pub fn new(value: &str) -> Result<Self, ConfigError> {
845        if value.trim().is_empty() {
846            return Err(ConfigError::about(
847                ConfigField::IngressSharedSecret,
848                "it is empty, and anything that can post to the ingress can pause a printer",
849            ));
850        }
851        Ok(Self(value.to_owned()))
852    }
853
854    /// Whether a post carried this secret.
855    ///
856    /// Compared over the whole of both values with the two lengths mixed in,
857    /// rather than by returning at the first difference or at a length
858    /// mismatch, so that how long this takes says nothing about how much of the
859    /// secret a caller guessed.
860    #[must_use]
861    pub fn matches(&self, offered: Option<&str>) -> bool {
862        let Some(offered) = offered else {
863            return false;
864        };
865        let expected = self.0.as_bytes();
866        let mut difference = expected.len() ^ offered.len();
867        for (index, byte) in offered.bytes().enumerate() {
868            let against = expected[index % expected.len().max(1)];
869            difference |= usize::from(byte ^ against);
870        }
871        difference == 0
872    }
873}
874
875impl core::fmt::Display for SharedSecret {
876    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
877        formatter.write_str(REDACTED)
878    }
879}
880
881impl core::fmt::Debug for SharedSecret {
882    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
883        write!(formatter, "SharedSecret({REDACTED})")
884    }
885}
886
887/// How many random bytes a credential this server generates is drawn from.
888pub const GENERATED_CREDENTIAL_BYTES: usize = 32;
889
890/// One credential in plaintext: a legacy `api.credential`, the legacy file a
891/// server generated into its state directory, or one `printobserver credential
892/// issue` draws for the operator's own configuration.
893///
894/// Neither rendering of this type shows the value. Its text is read in exactly
895/// one place — [`Self::written`], for the operator's own client configuration,
896/// which exists to carry it, and for the verifier computed from it — and the
897/// one comparison a presented credential is admitted by is [`Self::admits`], so
898/// there is no second comparison anywhere that could return early.
899#[derive(Clone)]
900pub struct ApiCredential(String);
901
902impl ApiCredential {
903    /// The credential this text names.
904    ///
905    /// # Errors
906    ///
907    /// Answers why the text cannot be a credential, in words that never quote
908    /// it: empty or nothing but whitespace, or carrying a control character or
909    /// a character outside printable ASCII, or beginning or ending with a space
910    /// — none of which an `Authorization` header carries intact.
911    pub fn new(value: &str) -> Result<Self, &'static str> {
912        if value.trim().is_empty() {
913            return Err(
914                "it is empty, and anything that can reach this server's API can command a printer",
915            );
916        }
917        if !value.bytes().all(|byte| (b' '..=b'~').contains(&byte)) {
918            return Err(
919                "it carries a control character or a character outside printable ASCII, which \
920                 no `Authorization` header carries intact",
921            );
922        }
923        if value.starts_with(' ') || value.ends_with(' ') {
924            return Err(
925                "it begins or ends with a space, which an `Authorization` header does not carry",
926            );
927        }
928        // llmlint: ignore[boundary_inputs_validated] The refusal set above is exactly the contract this server's API credential is planned against, shared with the nodes that build on it: empty or whitespace, a control or non-printable-ASCII byte, a leading or trailing space. A length floor would refuse operator credentials that contract admits, so it is recorded as a follow-up rather than added here; the default an operator gets without configuring one is the generated 32 random bytes.
929        Ok(Self(value.to_owned()))
930    }
931
932    /// A fresh credential, drawn from the operating system's own
933    /// cryptographically secure random source.
934    ///
935    /// [`GENERATED_CREDENTIAL_BYTES`] bytes, written as unpadded URL-safe
936    /// base64 so an operator can copy it and a header can carry it as it is.
937    ///
938    /// # Errors
939    ///
940    /// Answers the random source's own refusal, when it has none to give.
941    pub fn generate() -> Result<Self, getrandom::Error> {
942        use base64::Engine as _;
943
944        let mut drawn = [0_u8; GENERATED_CREDENTIAL_BYTES];
945        getrandom::fill(&mut drawn)?;
946        Ok(Self(
947            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(drawn),
948        ))
949    }
950
951    /// Whether a presented credential is this one.
952    ///
953    /// The lengths are compared first, which says how long the credential is and
954    /// nothing else; the bytes are then compared in constant time, so how long
955    /// this takes says nothing about how much of it a caller guessed.
956    #[must_use]
957    pub fn admits(&self, presented: &[u8]) -> bool {
958        use subtle::ConstantTimeEq as _;
959
960        let expected = self.0.as_bytes();
961        expected.len() == presented.len() && bool::from(expected.ct_eq(presented))
962    }
963
964    /// The text, for the one file whose purpose is to carry it — the
965    /// operator's own client configuration — and nothing else.
966    #[must_use]
967    pub fn written(&self) -> &str {
968        &self.0
969    }
970
971    /// The verifier this credential is checked by.
972    #[must_use]
973    pub fn verifier(&self) -> CredentialVerifier {
974        CredentialVerifier::of(&self.0)
975    }
976}
977
978impl PartialEq for ApiCredential {
979    fn eq(&self, other: &Self) -> bool {
980        self.admits(other.0.as_bytes())
981    }
982}
983
984impl Eq for ApiCredential {}
985
986impl core::fmt::Display for ApiCredential {
987    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
988        formatter.write_str(REDACTED)
989    }
990}
991
992impl core::fmt::Debug for ApiCredential {
993    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
994        write!(formatter, "ApiCredential({REDACTED})")
995    }
996}
997
998/// What a credential verifier is written with before its digest.
999pub const VERIFIER_PREFIX: &str = "sha256:";
1000
1001/// How many hexadecimal digits a verifier's digest is written in.
1002const VERIFIER_DIGITS: usize = 64;
1003
1004/// What one operator credential is checked against: the SHA-256 of its UTF-8
1005/// bytes.
1006///
1007/// It is not a secret, so its rendering shows it — written as
1008/// [`VERIFIER_PREFIX`] and the digest in lowercase hexadecimal, which is the
1009/// one spelling [`Self::parse`] accepts. It is still printed by nothing but the
1010/// two commands that exist to print it, and logged by nothing. A verifier of a
1011/// short or guessable credential can be searched offline, which is why the
1012/// credential it verifies is drawn from 32 random bytes when this program
1013/// draws it.
1014#[derive(Clone, PartialEq, Eq)]
1015pub struct CredentialVerifier([u8; 32]);
1016
1017impl CredentialVerifier {
1018    /// The verifier of one credential.
1019    #[must_use]
1020    pub fn of(credential: &str) -> Self {
1021        use sha2::Digest as _;
1022
1023        Self(sha2::Sha256::digest(credential.as_bytes()).into())
1024    }
1025
1026    /// The verifier this text writes down.
1027    ///
1028    /// # Errors
1029    ///
1030    /// Answers why the text is not one: anything but [`VERIFIER_PREFIX`]
1031    /// followed by exactly 64 lowercase hexadecimal digits.
1032    pub fn parse(text: &str) -> Result<Self, &'static str> {
1033        const SHAPE: &str = "it is not `sha256:` followed by the 64 lowercase hexadecimal digits                              of a SHA-256 digest, which is what `printobserver credential issue`                              and `printobserver credential verifier` print";
1034        let digits = text.strip_prefix(VERIFIER_PREFIX).ok_or(SHAPE)?;
1035        if digits.len() != VERIFIER_DIGITS
1036            || !digits
1037                .bytes()
1038                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1039        {
1040            return Err(SHAPE);
1041        }
1042        let mut digest = [0_u8; 32];
1043        for (index, pair) in digits.as_bytes().chunks(2).enumerate() {
1044            let high = hex_value(pair[0]);
1045            let low = hex_value(pair[1]);
1046            digest[index] = (high << 4) | low;
1047        }
1048        Ok(Self(digest))
1049    }
1050
1051    /// Whether a presented credential is the one this verifies.
1052    ///
1053    /// The presented bytes are digested and the two digests compared in
1054    /// constant time, so how long this takes says nothing about how much of
1055    /// the credential a caller guessed.
1056    #[must_use]
1057    pub fn admits(&self, presented: &[u8]) -> bool {
1058        use sha2::Digest as _;
1059        use subtle::ConstantTimeEq as _;
1060
1061        let offered: [u8; 32] = sha2::Sha256::digest(presented).into();
1062        bool::from(self.0.ct_eq(&offered))
1063    }
1064}
1065
1066/// One lowercase hexadecimal digit's value, for a digit already checked.
1067const fn hex_value(digit: u8) -> u8 {
1068    if digit.is_ascii_digit() {
1069        digit - b'0'
1070    } else {
1071        digit - b'a' + 10
1072    }
1073}
1074
1075impl core::fmt::Display for CredentialVerifier {
1076    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1077        formatter.write_str(VERIFIER_PREFIX)?;
1078        for byte in self.0 {
1079            write!(formatter, "{byte:02x}")?;
1080        }
1081        Ok(())
1082    }
1083}
1084
1085impl core::fmt::Debug for CredentialVerifier {
1086    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1087        write!(formatter, "CredentialVerifier({self})")
1088    }
1089}
1090
1091/// One running server's validated configuration.
1092///
1093/// Every value here is one no later step has to re-examine, and where a
1094/// validated type for one already exists it is that type rather than the text
1095/// it was written as: the `OctoPrint` instance is the adapter's own
1096/// configuration, which redacts the key it carries; the harness and the model
1097/// are the supervisor adapter's own names; and the ingress secret is a value
1098/// neither rendering of which shows.
1099#[derive(Debug, Clone, PartialEq)]
1100pub struct ServerConfig {
1101    /// Where the store, the images and the sessions live.
1102    pub state_dir: PathBuf,
1103    /// The address the API and the ingress are served on.
1104    pub listen: SocketAddr,
1105    /// Everything the printer adapter needs to reach the instance.
1106    pub octoprint: OctoPrintConfig,
1107    /// The operator's safety envelope.
1108    pub safety: SafetyEnvelope,
1109    /// The harness identity turns run on.
1110    pub harness: HarnessIdentity,
1111    /// The model turns are pinned to, when one is pinned.
1112    pub model: Option<ModelName>,
1113    /// The installed skill's `SKILL.md`, whose prose is sent as every turn's
1114    /// system prompt. The agent runs from the directory holding it, which is
1115    /// where the skill's own `reference/` documents sit.
1116    pub skill_path: PathBuf,
1117    /// The prompt template one turn fills, when the operator supplied one.
1118    pub prompt_template_path: Option<PathBuf>,
1119    /// How often every active print is given a periodic observation.
1120    pub observation_interval: core::time::Duration,
1121    /// How often the printer watch reads the machine.
1122    pub printer_poll: core::time::Duration,
1123    /// How long after an unfinished ending the printer acting on its own is
1124    /// recorded.
1125    pub unattended_window: core::time::Duration,
1126    /// The grey-level spread at or below which a camera frame is blank.
1127    pub blank_frame_max_stddev: BlankFrameBound,
1128    /// Where the failure detector's own service answers its health check,
1129    /// when configured.
1130    pub obico_ml_api_url: Option<WebAddress>,
1131    /// How long the ingress may take to answer.
1132    pub ingress_answer_bound: core::time::Duration,
1133    /// The shared secret every post to the ingress must carry.
1134    pub ingress_shared_secret: SharedSecret,
1135    /// A plaintext operator credential the configuration still carries, which
1136    /// is admitted — with a warning on every start — until it is replaced by
1137    /// its verifier.
1138    pub api_credential: Option<ApiCredential>,
1139    /// The verifier the operator's credential is checked against, when the
1140    /// configuration names one. Absent, the composition root reads the one in
1141    /// the state directory.
1142    pub api_credential_verifier: Option<CredentialVerifier>,
1143    /// Where a fresh frame of the print is fetched from, when configured.
1144    pub camera_snapshot_url: Option<WebAddress>,
1145    /// `Obico`'s own API, when configured; its debug form omits the token.
1146    pub obico_api: Option<ObicoApi>,
1147    /// How spools are checked before a print, and the margin asked for.
1148    pub spools: SpoolPolicy,
1149    /// The printer's own facts a recovery is checked against, when stated.
1150    pub recovery: Option<RecoveryConfig>,
1151    /// Who may ask for which recovery action.
1152    pub recovery_grants: RecoveryGrants,
1153}
1154
1155impl ServerConfig {
1156    /// Read and validate the one configuration file this program takes.
1157    ///
1158    /// # Errors
1159    ///
1160    /// Returns [`ConfigError::Unreadable`] when the file is not there,
1161    /// [`ConfigError::Unparsable`] when it is not this program's configuration,
1162    /// and [`ConfigError::Field`] naming the one field whose value cannot be
1163    /// accepted. The two values only the machine can rule on — the `OctoPrint`
1164    /// address and key — are ruled on by [`crate::Server::start`], which is
1165    /// where a printer exists to ask.
1166    pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
1167        let path = path.as_ref();
1168        Self::parse(&read(path)?, path)
1169    }
1170
1171    /// The same, over a document already read.
1172    ///
1173    /// # Errors
1174    ///
1175    /// The same as [`ServerConfig::load`], less the unreadable file.
1176    pub fn parse(text: &str, path: &Path) -> Result<Self, ConfigError> {
1177        let file: ConfigFile = toml::from_str(text).map_err(|error| ConfigError::Unparsable {
1178            path: path.to_path_buf(),
1179            detail: error.to_string(),
1180        })?;
1181        Self::validate(file)
1182    }
1183
1184    /// Rule on every value the document carries.
1185    ///
1186    /// Absence is ruled on here rather than by the parser, because a parser's
1187    /// own "missing field" says which key it wanted and not which field of this
1188    /// program that is. Every refusal below names the dotted key an operator
1189    /// would edit.
1190    fn validate(file: ConfigFile) -> Result<Self, ConfigError> {
1191        let state_dir =
1192            state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?;
1193        let listen = listen_address(&required(ConfigField::Listen, file.listen)?)?;
1194        let octoprint = octoprint(&file.octoprint)?;
1195        let safety = required(ConfigField::SafetyEnvelope, file.safety)?;
1196        check_envelope(&safety)?;
1197        let harness = harness_identity(file.supervisor.harness)?;
1198        let model = match file.supervisor.model {
1199            None => None,
1200            Some(name) => Some(
1201                ModelName::new(&named(ConfigField::Model, Some(name))?)
1202                    .map_err(|error| ConfigError::about(ConfigField::Model, error.to_string()))?,
1203            ),
1204        };
1205        let skill_path = skill(file.supervisor.skill_path.as_deref())?;
1206        let prompt_template_path = readable(
1207            ConfigField::PromptTemplatePath,
1208            file.supervisor.prompt_template_path.as_deref(),
1209        )?;
1210        let observation_interval = observation_interval(file.supervisor.observation_interval_s)?;
1211        let printer_poll = seconds_within(
1212            ConfigField::PrinterPollS,
1213            file.supervisor.printer_poll_s,
1214            PRINTER_POLL_RANGE_S,
1215        )?;
1216        let unattended_window = seconds_within(
1217            ConfigField::UnattendedWindowS,
1218            file.supervisor.unattended_window_s,
1219            UNATTENDED_WINDOW_RANGE_S,
1220        )?;
1221        let blank_frame_max_stddev = blank_frame_bound(file.vision.blank_frame_max_stddev)?;
1222        let obico_ml_api_url = file
1223            .obico
1224            .ml_api_url
1225            .as_deref()
1226            .map(|url| web_address(ConfigField::ObicoMlApiUrl, url))
1227            .transpose()?;
1228        let ingress_answer_bound = answer_bound(file.ingress.answer_bound_ms)?;
1229        let ingress_shared_secret = SharedSecret::new(&required(
1230            ConfigField::IngressSharedSecret,
1231            file.ingress.shared_secret,
1232        )?)?;
1233        let api_credential = file
1234            .api
1235            .credential
1236            .as_deref()
1237            .map(|value| {
1238                ApiCredential::new(value)
1239                    .map_err(|why| ConfigError::about(ConfigField::ApiCredential, why))
1240            })
1241            .transpose()?;
1242        let api_credential_verifier = file
1243            .api
1244            .credential_verifier
1245            .as_deref()
1246            .map(|value| {
1247                CredentialVerifier::parse(value.trim())
1248                    .map_err(|why| ConfigError::about(ConfigField::ApiCredentialVerifier, why))
1249            })
1250            .transpose()?;
1251        let camera_snapshot_url = file
1252            .camera
1253            .snapshot_url
1254            .map(|url| web_address(ConfigField::CameraSnapshotUrl, &url))
1255            .transpose()?;
1256        let obico_api = obico_api(file.obico)?;
1257        let spools = spool_policy(&file.spools)?;
1258        let recovery = recovery_facts(&file.recovery)?;
1259        let recovery_grants = recovery_grants(&file.policy.recovery)?;
1260        Ok(Self {
1261            state_dir,
1262            listen,
1263            octoprint,
1264            safety,
1265            harness,
1266            model,
1267            skill_path,
1268            prompt_template_path,
1269            observation_interval,
1270            printer_poll,
1271            unattended_window,
1272            blank_frame_max_stddev,
1273            obico_ml_api_url,
1274            ingress_answer_bound,
1275            ingress_shared_secret,
1276            api_credential,
1277            api_credential_verifier,
1278            camera_snapshot_url,
1279            obico_api,
1280            spools,
1281            recovery,
1282            recovery_grants,
1283        })
1284    }
1285
1286    /// Where this server materializes the agent's prompt template and
1287    /// assessment schema. The skill is not among them: it is the installed one
1288    /// `skill_path` names.
1289    #[must_use]
1290    pub fn assets_dir(&self) -> PathBuf {
1291        self.state_dir.join(ASSETS_DIRECTORY)
1292    }
1293}
1294
1295/// One address a field names, refused unless it is an `http` or `https` URL
1296/// naming a host, by the field's own key and without quoting the value.
1297fn web_address(field: ConfigField, url: &str) -> Result<WebAddress, ConfigError> {
1298    WebAddress::new(url).map_err(|why| ConfigError::about(field, why))
1299}
1300
1301/// `Obico`'s API, when both its address and its token are written down.
1302///
1303/// One without the other is refused naming the one that is missing: an address
1304/// with no token is a request `Obico` refuses, and a token with no address is a
1305/// secret written down for nothing.
1306fn obico_api(section: ObicoSection) -> Result<Option<ObicoApi>, ConfigError> {
1307    match (section.url, section.access_token) {
1308        (None, None) => Ok(None),
1309        (Some(_), None) => Err(ConfigError::about(
1310            ConfigField::ObicoAccessToken,
1311            "it is required when obico.url is given",
1312        )),
1313        (None, Some(_)) => Err(ConfigError::about(
1314            ConfigField::ObicoUrl,
1315            "it is required when obico.access_token is given",
1316        )),
1317        (Some(url), Some(access_token)) => {
1318            let url = web_address(ConfigField::ObicoUrl, &url)?;
1319            let access_token = AccessToken::new(&access_token)
1320                .map_err(|why| ConfigError::about(ConfigField::ObicoAccessToken, why))?;
1321            Ok(Some(ObicoApi::new(url, access_token)))
1322        }
1323    }
1324}
1325
1326/// The two values signing a harness in reads, and nothing else.
1327///
1328/// An operator signs the agent in before or after filling in the machine and
1329/// the failure detector, so `printobserver sign-in` reads the state directory
1330/// and the harness identity out of the server's own file and nothing beside
1331/// them: every other value the file carries, present or not and valid or not,
1332/// is one it never looks at.
1333#[derive(Debug, Clone, PartialEq, Eq)]
1334pub struct SignInConfig {
1335    /// Where the state lives, and so where the harness keeps its sign-in.
1336    pub state_dir: PathBuf,
1337    /// The harness identity supervision turns run on.
1338    pub harness: HarnessIdentity,
1339}
1340
1341impl SignInConfig {
1342    /// Read those two values out of one configuration file.
1343    ///
1344    /// # Errors
1345    ///
1346    /// Returns [`ConfigError::Unreadable`] when the file is not there,
1347    /// [`ConfigError::Unparsable`] when it is not a document carrying either
1348    /// value in the shape this program reads it in, and [`ConfigError::Field`]
1349    /// naming `state_dir` or `supervisor.harness` when that value cannot be
1350    /// accepted.
1351    pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
1352        let path = path.as_ref();
1353        let file: SignInFile =
1354            toml::from_str(&read(path)?).map_err(|error| ConfigError::Unparsable {
1355                path: path.to_path_buf(),
1356                detail: error.to_string(),
1357            })?;
1358        Ok(Self {
1359            state_dir: state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?,
1360            harness: harness_identity(file.supervisor.harness)?,
1361        })
1362    }
1363}
1364
1365/// The configuration file, read for the two values signing in takes.
1366///
1367/// Unlike [`ConfigFile`] it refuses no key it does not know, because every key
1368/// but these two is one signing in does not read.
1369#[derive(Deserialize)]
1370#[serde(crate = "printobserver_types::serde")]
1371struct SignInFile {
1372    /// Where the state lives.
1373    #[serde(default)]
1374    state_dir: Option<PathBuf>,
1375    /// The supervisor's section, for its harness alone.
1376    #[serde(default)]
1377    supervisor: SignInSupervisor,
1378}
1379
1380/// The supervisor's section, read for the harness alone.
1381#[derive(Default, Deserialize)]
1382#[serde(crate = "printobserver_types::serde")]
1383struct SignInSupervisor {
1384    /// The harness identity turns run on.
1385    #[serde(default)]
1386    harness: Option<String>,
1387}
1388
1389/// One configuration file's text.
1390fn read(path: &Path) -> Result<String, ConfigError> {
1391    std::fs::read_to_string(path).map_err(|error| ConfigError::Unreadable {
1392        path: path.to_path_buf(),
1393        detail: error.to_string(),
1394    })
1395}
1396
1397/// The harness identity, refused by its own key when it names nothing.
1398fn harness_identity(value: Option<String>) -> Result<HarnessIdentity, ConfigError> {
1399    HarnessIdentity::new(&named(ConfigField::Harness, value)?)
1400        .map_err(|error| ConfigError::about(ConfigField::Harness, error.to_string()))
1401}
1402
1403/// One field the file has to carry, refused by its own key when it does not.
1404fn required<T>(field: ConfigField, value: Option<T>) -> Result<T, ConfigError> {
1405    value.ok_or_else(|| ConfigError::about(field, "the configuration file carries no value for it"))
1406}
1407
1408/// One field that has to carry a name rather than nothing at all.
1409fn named(field: ConfigField, value: Option<String>) -> Result<String, ConfigError> {
1410    let value = required(field, value)?;
1411    if value.trim().is_empty() {
1412        return Err(ConfigError::about(
1413            field,
1414            "it is empty, and an empty value names nothing",
1415        ));
1416    }
1417    Ok(value.trim().to_owned())
1418}
1419
1420/// The state directory, created where it is not there.
1421fn state_directory(named: &Path) -> Result<PathBuf, ConfigError> {
1422    if named.as_os_str().is_empty() {
1423        return Err(ConfigError::about(
1424            ConfigField::StateDir,
1425            "it names no directory, and this server's whole state lives in one",
1426        ));
1427    }
1428    std::fs::create_dir_all(named).map_err(|error| {
1429        ConfigError::about(
1430            ConfigField::StateDir,
1431            format!("{} cannot be created: {error}", named.display()),
1432        )
1433    })?;
1434    named.canonicalize().map(plainly_written).map_err(|error| {
1435        ConfigError::about(
1436            ConfigField::StateDir,
1437            format!("{} cannot be resolved: {error}", named.display()),
1438        )
1439    })
1440}
1441
1442/// A resolved path, written the way its own platform's tools write it.
1443///
1444/// Resolving a path on Windows answers it in its verbatim form, `\\?\C:\…`:
1445/// one this program opens as readily as any other, and one no operator types and
1446/// some of the programs a supervision turn runs refuse — and every image path
1447/// this server answers is written under it. Where that form names an ordinary
1448/// drive path it is written as that path. Any other path, which on every other
1449/// platform is every path, is answered as it is.
1450#[must_use]
1451pub fn plainly_written(path: PathBuf) -> PathBuf {
1452    const VERBATIM: &str = r"\\?\";
1453    let drive = path
1454        .to_str()
1455        .and_then(|text| text.strip_prefix(VERBATIM))
1456        .filter(|rest| {
1457            let bytes = rest.as_bytes();
1458            bytes.len() >= 3
1459                && bytes[0].is_ascii_alphabetic()
1460                && bytes[1] == b':'
1461                && bytes[2] == b'\\'
1462        })
1463        .map(PathBuf::from);
1464    drive.unwrap_or(path)
1465}
1466
1467/// The address to serve on, as an address rather than as text.
1468fn listen_address(named: &str) -> Result<SocketAddr, ConfigError> {
1469    named.trim().parse().map_err(|error| {
1470        ConfigError::about(
1471            ConfigField::Listen,
1472            format!("{named:?} is no address to listen on: {error}"),
1473        )
1474    })
1475}
1476
1477/// Everything the printer adapter needs to reach the instance, refused by the
1478/// field whose value it could not take.
1479fn octoprint(section: &OctoprintSection) -> Result<OctoPrintConfig, ConfigError> {
1480    let fan = fan_support(&section.fan)?;
1481    let url = named(ConfigField::OctoprintUrl, section.url.clone())?;
1482    let key = named(ConfigField::OctoprintApiKey, section.api_key.clone())?;
1483    OctoPrintConfig::new(&url, key)
1484        .map(|configured| configured.with_fan(fan))
1485        .map_err(|error| {
1486            let field = match error {
1487                printobserver_octoprint::ConfigError::EmptyApiKey => ConfigField::OctoprintApiKey,
1488                _ => ConfigField::OctoprintUrl,
1489            };
1490            ConfigError::about(field, error.to_string())
1491        })
1492}
1493
1494/// The fan setting one word of the vocabulary names.
1495fn fan_support(named: &str) -> Result<FanSupport, ConfigError> {
1496    FAN_VOCABULARY
1497        .iter()
1498        .find(|(spelling, _)| *spelling == named.trim())
1499        .map(|(_, support)| *support)
1500        .ok_or_else(|| {
1501            let vocabulary: Vec<&str> = FAN_VOCABULARY.iter().map(|(word, _)| *word).collect();
1502            ConfigError::about(
1503                ConfigField::OctoprintFan,
1504                format!("{named:?} is not one of {}", vocabulary.join(" or ")),
1505            )
1506        })
1507}
1508
1509/// The envelope, refused when a range it declares admits nothing.
1510fn check_envelope(envelope: &SafetyEnvelope) -> Result<(), ConfigError> {
1511    if envelope.allowed.is_empty() {
1512        return Err(ConfigError::about(
1513            ConfigField::SafetyEnvelope,
1514            "it allows no adjustable at all, so no adjustment could ever be accepted",
1515        ));
1516    }
1517    for (adjustable, range) in &envelope.allowed {
1518        if !range.min.is_finite() || !range.max.is_finite() || range.min > range.max {
1519            return Err(ConfigError::about(
1520                ConfigField::SafetyEnvelope,
1521                format!(
1522                    "the range allowed for {adjustable} runs from {} to {}, which admits \
1523                     no value",
1524                    range.min, range.max
1525                ),
1526            ));
1527        }
1528    }
1529    // Closing a print record is the operator's judgement that the print is
1530    // over, so no configuration may hand it to the agent watching the print.
1531    if envelope
1532        .actions
1533        .get(&ActorClass::Agent)
1534        .is_some_and(|granted| granted.contains(&ActionKind::ClosePrint))
1535    {
1536        return Err(ConfigError::about(
1537            ConfigField::SafetyEnvelope,
1538            "it grants `close_print` to the agent, and closing a print record is the \
1539             operator's judgement that the print is over",
1540        ));
1541    }
1542    if envelope.agent_min_interval_s < 0 {
1543        return Err(ConfigError::about(
1544            ConfigField::SafetyEnvelope,
1545            format!(
1546                "the agent's minimum interval is {}s, and an interval is a count of seconds",
1547                envelope.agent_min_interval_s
1548            ),
1549        ));
1550    }
1551    Ok(())
1552}
1553
1554/// One optional path, read where it was named so that a path naming nothing is
1555/// refused here rather than hours later.
1556fn readable(field: ConfigField, named: Option<&Path>) -> Result<Option<PathBuf>, ConfigError> {
1557    let Some(path) = named else {
1558        return Ok(None);
1559    };
1560    std::fs::read_to_string(path)
1561        .map(|_| Some(path.to_path_buf()))
1562        .map_err(|error| {
1563            ConfigError::about(field, format!("{} cannot be read: {error}", path.display()))
1564        })
1565}
1566
1567/// The installed skill, refused naming how to install one when it is absent or
1568/// cannot be read.
1569fn skill(named: Option<&Path>) -> Result<PathBuf, ConfigError> {
1570    let Some(path) = named else {
1571        return Err(ConfigError::about(
1572            ConfigField::SkillPath,
1573            format!(
1574                "the configuration file carries no value for it, and this program carries \
1575                 no skill of its own: {SKILL_INSTALL}"
1576            ),
1577        ));
1578    };
1579    std::fs::read_to_string(path)
1580        .map(|_| path.to_path_buf())
1581        .map_err(|error| {
1582            ConfigError::about(
1583                ConfigField::SkillPath,
1584                format!(
1585                    "{} cannot be read: {error}. {SKILL_INSTALL}",
1586                    path.display()
1587                ),
1588            )
1589        })
1590}
1591
1592/// How spools are checked, each key left out taking the core's own default.
1593fn spool_policy(section: &SpoolsSection) -> Result<SpoolPolicy, ConfigError> {
1594    let defaults = SpoolPolicy::default();
1595    let preflight = match section.preflight.as_deref() {
1596        None => defaults.preflight,
1597        Some("refuse") => PreflightMode::Refuse,
1598        Some("warn") => PreflightMode::Warn,
1599        Some("off") => PreflightMode::Off,
1600        Some(_) => {
1601            return Err(ConfigError::about(
1602                ConfigField::SpoolsPreflight,
1603                "the spool check is one of `refuse`, `warn` or `off`",
1604            ));
1605        }
1606    };
1607    let margin = |field: ConfigField, value: Option<f64>, default: f64| match value {
1608        None => Ok(default),
1609        Some(value) if value.is_finite() && value >= 0.0 => Ok(value),
1610        Some(_) => Err(ConfigError::about(
1611            field,
1612            "a margin is a figure at or above zero; a negative one asks a spool for less \
1613             than the print needs",
1614        )),
1615    };
1616    let buffer_percent = margin(
1617        ConfigField::SpoolsBufferPercent,
1618        section.buffer_percent,
1619        defaults.buffer_percent,
1620    )?;
1621    let buffer_min_g = margin(
1622        ConfigField::SpoolsBufferMinG,
1623        section.buffer_min_g,
1624        defaults.buffer_min_g,
1625    )?;
1626    let analysis_wait_s = match section.analysis_wait_seconds {
1627        None => defaults.analysis_wait_s,
1628        Some(seconds) => u64::try_from(seconds).map_err(|_| {
1629            ConfigError::about(
1630                ConfigField::SpoolsAnalysisWaitSeconds,
1631                "a wait is a number of seconds at or above zero",
1632            )
1633        })?,
1634    };
1635    Ok(SpoolPolicy {
1636        preflight,
1637        buffer_percent,
1638        buffer_min_g,
1639        analysis_wait_s,
1640    })
1641}
1642
1643/// The printer's recovery facts, absent when the section states none.
1644fn recovery_facts(section: &RecoverySection) -> Result<Option<RecoveryConfig>, ConfigError> {
1645    if *section == RecoverySection::default() {
1646        return Ok(None);
1647    }
1648    let absent = |field: ConfigField| {
1649        ConfigError::about(
1650            field,
1651            "`[recovery]` states this printer's facts, and this one is one of them",
1652        )
1653    };
1654    let away_from_bed = match section.away_from_bed.as_deref() {
1655        None => return Err(absent(ConfigField::RecoveryAwayFromBed)),
1656        Some("z_plus") => AwayFromBed::ZPlus,
1657        Some("z_minus") => AwayFromBed::ZMinus,
1658        Some(other) => {
1659            return Err(ConfigError::about(
1660                ConfigField::RecoveryAwayFromBed,
1661                format!("{other:?} is neither `z_plus` nor `z_minus`"),
1662            ));
1663        }
1664    };
1665    let max_z_mm = section
1666        .max_z_mm
1667        .ok_or_else(|| absent(ConfigField::RecoveryMaxZMm))?;
1668    if !(max_z_mm.is_finite() && max_z_mm > 0.0) {
1669        return Err(ConfigError::about(
1670            ConfigField::RecoveryMaxZMm,
1671            format!("{max_z_mm} mm is no height a machine reaches; it is a figure above zero"),
1672        ));
1673    }
1674    let max_lift_mm = section
1675        .max_lift_mm
1676        .unwrap_or_else(|| DEFAULT_MAX_LIFT_MM.min(max_z_mm));
1677    if !(max_lift_mm.is_finite() && max_lift_mm > 0.0 && max_lift_mm <= max_z_mm) {
1678        return Err(ConfigError::about(
1679            ConfigField::RecoveryMaxLiftMm,
1680            format!(
1681                "{max_lift_mm} mm is outside the lifts a machine of {max_z_mm} mm makes: above \
1682                 zero, and at most `recovery.max_z_mm`"
1683            ),
1684        ));
1685    }
1686    let clearance_margin_mm = section
1687        .clearance_margin_mm
1688        .unwrap_or(DEFAULT_CLEARANCE_MARGIN_MM);
1689    if !(clearance_margin_mm.is_finite()
1690        && clearance_margin_mm >= 0.0
1691        && clearance_margin_mm < max_z_mm)
1692    {
1693        return Err(ConfigError::about(
1694            ConfigField::RecoveryClearanceMarginMm,
1695            format!(
1696                "{clearance_margin_mm} mm is outside the margins a machine of {max_z_mm} mm \
1697                 admits: at or above zero, and below `recovery.max_z_mm`"
1698            ),
1699        ));
1700    }
1701    let place = |field: ConfigField, written: Option<&Vec<f64>>| match written.map(Vec::as_slice) {
1702        None => Err(absent(field)),
1703        Some([x, y]) if x.is_finite() && y.is_finite() && *x >= 0.0 && *y >= 0.0 => Ok([*x, *y]),
1704        Some(_) => Err(ConfigError::about(
1705            field,
1706            "a place is `[x, y]`, two figures in millimetres at or above zero",
1707        )),
1708    };
1709    let park_xy = place(ConfigField::RecoveryParkXy, section.park_xy.as_ref())?;
1710    let z_home_xy = place(ConfigField::RecoveryZHomeXy, section.z_home_xy.as_ref())?;
1711    let z_home_sweeps_bed = section
1712        .z_home_sweeps_bed
1713        .ok_or_else(|| absent(ConfigField::RecoveryZHomeSweepsBed))?;
1714    Ok(Some(RecoveryConfig {
1715        away_from_bed,
1716        max_z_mm,
1717        max_lift_mm,
1718        clearance_margin_mm,
1719        park_xy,
1720        z_home_xy,
1721        z_home_sweeps_bed,
1722    }))
1723}
1724
1725/// Who may ask for which recovery action, each list left out taking its
1726/// default, and the two grants no configuration may make refused.
1727fn recovery_grants(section: &RecoveryPolicySection) -> Result<RecoveryGrants, ConfigError> {
1728    let defaults = RecoveryGrants::default();
1729    let actions = |field: ConfigField, written: Option<&Vec<String>>, default: Vec<_>| {
1730        let Some(written) = written else {
1731            return Ok(default);
1732        };
1733        written
1734            .iter()
1735            .map(|name| {
1736                RecoveryActionKind::ALL
1737                    .iter()
1738                    .find(|kind| kind.as_str() == name.trim())
1739                    .copied()
1740                    .ok_or_else(|| {
1741                        ConfigError::about(
1742                            field,
1743                            format!("{name:?} is not a recovery action of this program"),
1744                        )
1745                    })
1746            })
1747            .collect::<Result<Vec<_>, _>>()
1748    };
1749    let operator = actions(
1750        ConfigField::PolicyRecoveryOperator,
1751        section.operator.as_ref(),
1752        defaults.operator,
1753    )?;
1754    let agent = actions(
1755        ConfigField::PolicyRecoveryAgent,
1756        section.agent.as_ref(),
1757        defaults.agent,
1758    )?;
1759    // Homing Z drives the nozzle or a gantry down onto whatever is on the bed,
1760    // and only a person standing at the machine can say nothing is.
1761    if agent.contains(&RecoveryActionKind::RecoverHomeZ) {
1762        return Err(ConfigError::about(
1763            ConfigField::PolicyRecoveryAgent,
1764            "it grants `recover_home_z` to the agent, and only a person at the machine can \
1765             say the bed is clear for Z to be homed",
1766        ));
1767    }
1768    let asserting = match section.asserting.as_ref() {
1769        None => defaults.asserting,
1770        Some(written) => written
1771            .iter()
1772            .map(|class| match class.trim() {
1773                "operator" => Ok(ActorClass::Operator),
1774                // An assertion is a person's word for what they can see, and
1775                // an agent's word for clearance is no measurement of it.
1776                "agent" => Err(ConfigError::about(
1777                    ConfigField::PolicyRecoveryAsserting,
1778                    "it lets the agent assert clearance, and an assertion is a person's word \
1779                     for what they can see at the machine",
1780                )),
1781                other => Err(ConfigError::about(
1782                    ConfigField::PolicyRecoveryAsserting,
1783                    format!("{other:?} is not an actor whose word can count; only `operator` is"),
1784                )),
1785            })
1786            .collect::<Result<Vec<_>, _>>()?,
1787    };
1788    Ok(RecoveryGrants {
1789        operator,
1790        agent,
1791        asserting,
1792    })
1793}
1794
1795/// The observation interval, refused at zero.
1796fn observation_interval(seconds: u64) -> Result<core::time::Duration, ConfigError> {
1797    if seconds == 0 {
1798        return Err(ConfigError::about(
1799            ConfigField::ObservationIntervalS,
1800            "an interval of zero seconds observes a print again the moment its last turn \
1801             returns, which is a turn that never ends",
1802        ));
1803    }
1804    Ok(core::time::Duration::from_secs(seconds))
1805}
1806
1807/// A number of seconds, refused outside the range its field admits.
1808fn seconds_within(
1809    field: ConfigField,
1810    seconds: u64,
1811    range: (u64, u64),
1812) -> Result<core::time::Duration, ConfigError> {
1813    let (least, most) = range;
1814    if !(least..=most).contains(&seconds) {
1815        return Err(ConfigError::about(
1816            field,
1817            format!("{seconds} seconds is outside the {least} to {most} seconds it admits"),
1818        ));
1819    }
1820    Ok(core::time::Duration::from_secs(seconds))
1821}
1822
1823/// The blank-frame bound, refused outside the range it admits.
1824fn blank_frame_bound(written: Option<f64>) -> Result<BlankFrameBound, ConfigError> {
1825    written.map_or(Ok(BlankFrameBound::DEFAULT), |bound| {
1826        BlankFrameBound::new(bound).map_err(|refused| {
1827            ConfigError::about(
1828                ConfigField::VisionBlankFrameMaxStddev,
1829                format!(
1830                    "{refused} is outside the {MIN_BLANK_FRAME_MAX_STDDEV} to \
1831                     {MAX_BLANK_FRAME_MAX_STDDEV} grey levels it admits"
1832                ),
1833            )
1834        })
1835    })
1836}
1837
1838/// The answer bound, refused when it is not one this program admits.
1839fn answer_bound(milliseconds: u64) -> Result<core::time::Duration, ConfigError> {
1840    if milliseconds == 0 {
1841        return Err(ConfigError::about(
1842            ConfigField::IngressAnswerBoundMs,
1843            "a bound of zero is an ingress that has run out of time before it starts",
1844        ));
1845    }
1846    if milliseconds >= OBICO_POSTING_TIMEOUT_MS {
1847        return Err(ConfigError::about(
1848            ConfigField::IngressAnswerBoundMs,
1849            format!(
1850                "{milliseconds}ms is not below the {OBICO_POSTING_TIMEOUT_MS}ms Obico posts \
1851                 under, so an alert answered at that bound is one Obico has already \
1852                 abandoned — and its posting does not retry"
1853            ),
1854        ));
1855    }
1856    Ok(core::time::Duration::from_millis(milliseconds))
1857}
1858
1859#[cfg(test)]
1860mod tests {
1861    use super::CredentialVerifier;
1862
1863    /// The SHA-256 of `abc`, as FIPS 180-2 gives it.
1864    const ABC: &str = "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
1865
1866    /// A verifier is the SHA-256 of the credential's UTF-8 bytes, written and
1867    /// read back in one spelling, and it admits that credential and no other.
1868    #[test]
1869    fn a_verifier_is_the_credentials_sha256_and_admits_only_it() {
1870        let verifier = CredentialVerifier::of("abc");
1871
1872        assert_eq!(verifier.to_string(), ABC);
1873        assert_eq!(CredentialVerifier::parse(ABC), Ok(verifier.clone()));
1874        assert!(verifier.admits(b"abc"));
1875        assert!(!verifier.admits(b"abd"));
1876        assert!(!verifier.admits(b""));
1877    }
1878
1879    /// Anything but `sha256:` and 64 lowercase hexadecimal digits is refused.
1880    #[test]
1881    fn a_verifier_in_any_other_spelling_is_refused() {
1882        for refused in [
1883            "",
1884            "sha256:",
1885            &ABC[..ABC.len() - 1],
1886            &format!("{ABC}0"),
1887            &ABC.to_uppercase(),
1888            &ABC.replace("sha256:", "sha512:"),
1889            &ABC.replace("sha256:", ""),
1890            &ABC.replace('a', "g"),
1891        ] {
1892            assert!(
1893                CredentialVerifier::parse(refused).is_err(),
1894                "{refused:?} was accepted"
1895            );
1896        }
1897    }
1898}