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