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