Skip to main content

printobserver_server/
config.rs

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