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 API credential
34//!
35//! Every request beneath the versioned prefix carries one credential, and
36//! [`ApiCredential`] is it. `api.credential` names it outright; left out, the
37//! composition root generates one into the state directory the first time it
38//! starts and reuses it after. Either way it is held in a type neither
39//! rendering of which shows it, and the one comparison a presented credential
40//! is admitted by is [`ApiCredential::admits`].
41
42use std::net::SocketAddr;
43use std::path::{Path, PathBuf};
44
45use printobserver_core::SafetyEnvelope;
46use printobserver_octoprint::{FanSupport, OctoPrintConfig};
47use printobserver_oneharness::{HarnessIdentity, ModelName};
48use printobserver_types::schemars::JsonSchema;
49use printobserver_types::serde::{Deserialize, Serialize};
50
51/// The answer bound this repository ships, in milliseconds.
52///
53/// A fifth of [`OBICO_POSTING_TIMEOUT_MS`]. The margin is deliberate: the
54/// supported host is a small ARM board beside the printer, and a bound set just
55/// under the producer's timeout would be exceeded by the first slow moment on
56/// it — after which `Obico` drops the alert, because its posting does not retry.
57pub const DEFAULT_INGRESS_ANSWER_BOUND_MS: u64 = 1_000;
58
59/// The timeout `Obico`'s own webhook notification plugin posts under.
60///
61/// Read from the `Obico` release the `obico-fixture` node stands up — revision
62/// `49c0bc7001a3fd8d56297fc3032ba287bfe1d50b`,
63/// `backend/notifications/plugins/webhook/__init__.py`, whose `execute_webhook`
64/// takes `timeout: float = 5.0` and calls `raise_for_status` with no retry.
65/// This repository's claim about an external producer; what reconciles it
66/// against a live `Obico` is the scheduled `Obico` tier.
67pub const OBICO_POSTING_TIMEOUT_MS: u64 = 5_000;
68
69/// The directory under the state directory this server materializes the
70/// supervising agent's prompt template and assessment schema into. The skill
71/// is not among them: it is installed with [`SKILL_INSTALL`] and configured by
72/// `supervisor.skill_path`.
73pub const ASSETS_DIRECTORY: &str = "assets";
74
75/// How the supervising agent's skill is installed, and what names it after.
76///
77/// This program carries no skill of its own: the skill is the Agent Skill this
78/// repository publishes, installed as any other is, and every refusal of
79/// `supervisor.skill_path` says so, because it is the one instruction an
80/// operator whose configuration predates that needs.
81pub const SKILL_INSTALL: &str = "the skill is installed with `gh skill install \
82 nickderobertis/printobserver printobserver --dir <dir>`, and \
83 `supervisor.skill_path` names the installed `SKILL.md`, \
84 `<dir>/printobserver/SKILL.md`";
85
86/// Every value this program is configured with, and the key it is spelled under.
87///
88/// The walk in this crate's tier is over this array, and the array is compared
89/// against the configuration shapes' own declared properties, so neither can
90/// grow a field the other does not know about.
91#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
92pub enum ConfigField {
93 /// Where the store, the images and the sessions live.
94 StateDir,
95 /// The address the API and the ingress are served on.
96 Listen,
97 /// Where the `OctoPrint` instance answers.
98 OctoprintUrl,
99 /// The key that instance authenticates every request by.
100 OctoprintApiKey,
101 /// Whether the machine has a part-cooling fan this server may command.
102 OctoprintFan,
103 /// The operator's safety envelope.
104 SafetyEnvelope,
105 /// The harness identity supervision turns run on.
106 Harness,
107 /// The model turns are pinned to, when one is pinned.
108 Model,
109 /// The `PrintObserver` skill sent as every turn's system prompt.
110 SkillPath,
111 /// The prompt template one turn fills.
112 PromptTemplatePath,
113 /// How long the ingress may take to answer, in milliseconds.
114 IngressAnswerBoundMs,
115 /// The shared secret the ingress requires of every post.
116 IngressSharedSecret,
117 /// The credential every request to a versioned operation must carry, when
118 /// the operator chose one rather than letting the server generate it.
119 ApiCredential,
120}
121
122impl ConfigField {
123 /// Every field this program takes, and there is no other.
124 pub const ALL: [Self; 13] = [
125 Self::StateDir,
126 Self::Listen,
127 Self::OctoprintUrl,
128 Self::OctoprintApiKey,
129 Self::OctoprintFan,
130 Self::SafetyEnvelope,
131 Self::Harness,
132 Self::Model,
133 Self::SkillPath,
134 Self::PromptTemplatePath,
135 Self::IngressAnswerBoundMs,
136 Self::IngressSharedSecret,
137 Self::ApiCredential,
138 ];
139
140 /// The dotted key this field is spelled under in the configuration file.
141 #[must_use]
142 pub const fn key(self) -> &'static str {
143 match self {
144 Self::StateDir => "state_dir",
145 Self::Listen => "listen",
146 Self::OctoprintUrl => "octoprint.url",
147 Self::OctoprintApiKey => "octoprint.api_key",
148 Self::OctoprintFan => "octoprint.fan",
149 Self::SafetyEnvelope => "safety",
150 Self::Harness => "supervisor.harness",
151 Self::Model => "supervisor.model",
152 Self::SkillPath => "supervisor.skill_path",
153 Self::PromptTemplatePath => "supervisor.prompt_template_path",
154 Self::IngressAnswerBoundMs => "ingress.answer_bound_ms",
155 Self::IngressSharedSecret => "ingress.shared_secret",
156 Self::ApiCredential => "api.credential",
157 }
158 }
159}
160
161impl core::fmt::Display for ConfigField {
162 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
163 formatter.write_str(self.key())
164 }
165}
166
167/// Why this server will not start under the configuration it was given.
168///
169/// Every variant names the field it is about, because the answer an operator
170/// needs is which line of the file to change.
171#[derive(Debug, Clone, PartialEq, Eq)]
172pub enum ConfigError {
173 /// The file could not be read at all.
174 Unreadable {
175 /// The path that was named.
176 path: PathBuf,
177 /// What went wrong reading it.
178 detail: String,
179 },
180 /// The file is not the document this program takes.
181 Unparsable {
182 /// The path that was named.
183 path: PathBuf,
184 /// What could not be parsed, in the parser's own words.
185 detail: String,
186 },
187 /// One field carries a value this program cannot accept.
188 Field {
189 /// The field it is about.
190 field: ConfigField,
191 /// Why the value cannot be accepted.
192 detail: String,
193 },
194}
195
196impl ConfigError {
197 /// The field this refusal is about, when it is about one.
198 #[must_use]
199 pub const fn field(&self) -> Option<ConfigField> {
200 match self {
201 Self::Field { field, .. } => Some(*field),
202 _ => None,
203 }
204 }
205
206 /// One field's refusal, in its own words.
207 pub(crate) fn about(field: ConfigField, detail: impl Into<String>) -> Self {
208 Self::Field {
209 field,
210 detail: detail.into(),
211 }
212 }
213}
214
215impl core::fmt::Display for ConfigError {
216 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
217 match self {
218 Self::Unreadable { path, detail } => write!(
219 formatter,
220 "the configuration file {} could not be read: {detail}",
221 path.display()
222 ),
223 Self::Unparsable { path, detail } => write!(
224 formatter,
225 "the configuration file {} could not be read as this program's \
226 configuration: {detail}",
227 path.display()
228 ),
229 Self::Field { field, detail } => write!(
230 formatter,
231 "the configuration field `{field}` cannot be accepted: {detail}"
232 ),
233 }
234 }
235}
236
237impl core::error::Error for ConfigError {}
238
239/// Where the `OctoPrint` instance is and what it is like, as written down.
240#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
241#[serde(
242 crate = "printobserver_types::serde",
243 deny_unknown_fields,
244 rename_all = "snake_case"
245)]
246#[schemars(crate = "printobserver_types::schemars")]
247pub struct OctoprintSection {
248 /// The base URL the instance answers on.
249 #[serde(default, skip_serializing_if = "Option::is_none")]
250 pub url: Option<String>,
251 /// The key it authenticates every request by.
252 #[serde(default, skip_serializing_if = "Option::is_none")]
253 pub api_key: Option<String>,
254 /// Whether the machine has a part-cooling fan this server may command.
255 #[serde(default = "commandable")]
256 pub fan: String,
257}
258
259/// The vocabulary [`OctoprintSection::fan`] takes, spelled as the operator
260/// writes it.
261pub const FAN_VOCABULARY: [(&str, FanSupport); 2] = [
262 ("commandable", FanSupport::Commandable),
263 ("absent", FanSupport::Absent),
264];
265
266/// The fan setting a configuration naming none takes.
267fn commandable() -> String {
268 FAN_VOCABULARY[0].0.to_owned()
269}
270
271impl Default for OctoprintSection {
272 fn default() -> Self {
273 Self {
274 url: None,
275 api_key: None,
276 fan: commandable(),
277 }
278 }
279}
280
281/// How the supervising agent is reached, as written down.
282#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
283#[serde(
284 crate = "printobserver_types::serde",
285 deny_unknown_fields,
286 rename_all = "snake_case"
287)]
288#[schemars(crate = "printobserver_types::schemars")]
289#[derive(Default)]
290pub struct SupervisorSection {
291 /// The harness identity turns run on.
292 #[serde(default, skip_serializing_if = "Option::is_none")]
293 pub harness: Option<String>,
294 /// The model turns are pinned to, when one is pinned.
295 #[serde(default, skip_serializing_if = "Option::is_none")]
296 pub model: Option<String>,
297 /// The installed skill's `SKILL.md`, whose prose is sent as every turn's
298 /// system prompt; the agent runs from the directory holding it. Required:
299 /// this program carries no skill, and an absent one refuses the start.
300 #[serde(default, skip_serializing_if = "Option::is_none")]
301 pub skill_path: Option<PathBuf>,
302 /// The prompt template one turn fills, when the operator supplies one
303 /// instead of the committed template this program carries.
304 #[serde(default, skip_serializing_if = "Option::is_none")]
305 pub prompt_template_path: Option<PathBuf>,
306}
307
308/// What the `Obico` ingress requires and how fast it answers, as written down.
309#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
310#[serde(
311 crate = "printobserver_types::serde",
312 deny_unknown_fields,
313 rename_all = "snake_case"
314)]
315#[schemars(crate = "printobserver_types::schemars")]
316pub struct IngressSection {
317 /// The shared secret every post must carry.
318 #[serde(default, skip_serializing_if = "Option::is_none")]
319 pub shared_secret: Option<String>,
320 /// How long the ingress may take to answer, in milliseconds.
321 #[serde(default = "default_answer_bound_ms")]
322 pub answer_bound_ms: u64,
323}
324
325/// The answer bound a configuration naming none takes.
326const fn default_answer_bound_ms() -> u64 {
327 DEFAULT_INGRESS_ANSWER_BOUND_MS
328}
329
330impl Default for IngressSection {
331 fn default() -> Self {
332 Self {
333 shared_secret: None,
334 answer_bound_ms: DEFAULT_INGRESS_ANSWER_BOUND_MS,
335 }
336 }
337}
338
339/// What a caller of the versioned API authenticates with, as written down.
340#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
341#[serde(
342 crate = "printobserver_types::serde",
343 deny_unknown_fields,
344 rename_all = "snake_case"
345)]
346#[schemars(crate = "printobserver_types::schemars")]
347pub struct ApiSection {
348 /// The credential every request must carry. Left out, the server generates
349 /// one into its state directory and reuses it on every later start.
350 #[serde(default, skip_serializing_if = "Option::is_none")]
351 pub credential: Option<String>,
352}
353
354/// The whole configuration file, exactly as it is written down.
355///
356/// This is the parsed document rather than the validated configuration:
357/// [`ServerConfig::load`] is what turns one into the other, and every value a
358/// later step could find wrong is ruled on there.
359#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
360#[serde(
361 crate = "printobserver_types::serde",
362 deny_unknown_fields,
363 rename_all = "snake_case"
364)]
365#[schemars(crate = "printobserver_types::schemars")]
366pub struct ConfigFile {
367 /// Where the store, the images and the sessions live.
368 #[serde(default, skip_serializing_if = "Option::is_none")]
369 pub state_dir: Option<PathBuf>,
370 /// The address the API and the ingress are served on.
371 #[serde(default, skip_serializing_if = "Option::is_none")]
372 pub listen: Option<String>,
373 /// Where the `OctoPrint` instance is.
374 #[serde(default)]
375 pub octoprint: OctoprintSection,
376 /// The operator's safety envelope.
377 #[serde(default, skip_serializing_if = "Option::is_none")]
378 pub safety: Option<SafetyEnvelope>,
379 /// How the supervising agent is reached.
380 #[serde(default)]
381 pub supervisor: SupervisorSection,
382 /// What the `Obico` ingress requires.
383 #[serde(default)]
384 pub ingress: IngressSection,
385 /// What a caller of the versioned API authenticates with.
386 #[serde(default)]
387 pub api: ApiSection,
388}
389
390/// The shared secret the ingress requires of every post.
391///
392/// Neither rendering of this type shows the value, so it cannot reach a log
393/// record, a panic message or an error's own text by being formatted — and the
394/// comparison that admits a post lives here rather than at the endpoint, so
395/// there is no way to read the secret out in order to compare it.
396#[derive(Clone, PartialEq, Eq)]
397pub struct SharedSecret(String);
398
399/// What a secret renders as, wherever a value carrying one is rendered.
400pub const REDACTED: &str = "<redacted>";
401
402impl SharedSecret {
403 /// The secret this text names.
404 ///
405 /// # Errors
406 ///
407 /// Returns [`ConfigError`] when the text is empty or is nothing but
408 /// whitespace: anything that can post to the ingress can pause a printer,
409 /// and a secret nothing has to carry is no secret.
410 pub fn new(value: &str) -> Result<Self, ConfigError> {
411 if value.trim().is_empty() {
412 return Err(ConfigError::about(
413 ConfigField::IngressSharedSecret,
414 "it is empty, and anything that can post to the ingress can pause a printer",
415 ));
416 }
417 Ok(Self(value.to_owned()))
418 }
419
420 /// Whether a post carried this secret.
421 ///
422 /// Compared over the whole of both values with the two lengths mixed in,
423 /// rather than by returning at the first difference or at a length
424 /// mismatch, so that how long this takes says nothing about how much of the
425 /// secret a caller guessed.
426 #[must_use]
427 pub fn matches(&self, offered: Option<&str>) -> bool {
428 let Some(offered) = offered else {
429 return false;
430 };
431 let expected = self.0.as_bytes();
432 let mut difference = expected.len() ^ offered.len();
433 for (index, byte) in offered.bytes().enumerate() {
434 let against = expected[index % expected.len().max(1)];
435 difference |= usize::from(byte ^ against);
436 }
437 difference == 0
438 }
439}
440
441impl core::fmt::Display for SharedSecret {
442 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
443 formatter.write_str(REDACTED)
444 }
445}
446
447impl core::fmt::Debug for SharedSecret {
448 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
449 write!(formatter, "SharedSecret({REDACTED})")
450 }
451}
452
453/// How many random bytes a credential this server generates is drawn from.
454pub const GENERATED_CREDENTIAL_BYTES: usize = 32;
455
456/// The credential every request to a versioned operation must carry.
457///
458/// Neither rendering of this type shows the value. Its text is read in exactly
459/// one place outside this file — the client configuration the composition root
460/// writes, which exists to carry it — and the one comparison a presented
461/// credential is admitted by is [`Self::admits`], so there is no second
462/// comparison anywhere that could return early.
463#[derive(Clone)]
464pub struct ApiCredential(String);
465
466impl ApiCredential {
467 /// The credential this text names.
468 ///
469 /// # Errors
470 ///
471 /// Answers why the text cannot be a credential, in words that never quote
472 /// it: empty or nothing but whitespace, or carrying a control character or
473 /// a character outside printable ASCII, or beginning or ending with a space
474 /// — none of which an `Authorization` header carries intact.
475 pub fn new(value: &str) -> Result<Self, &'static str> {
476 if value.trim().is_empty() {
477 return Err(
478 "it is empty, and anything that can reach this server's API can command a printer",
479 );
480 }
481 if !value.bytes().all(|byte| (b' '..=b'~').contains(&byte)) {
482 return Err(
483 "it carries a control character or a character outside printable ASCII, which \
484 no `Authorization` header carries intact",
485 );
486 }
487 if value.starts_with(' ') || value.ends_with(' ') {
488 return Err(
489 "it begins or ends with a space, which an `Authorization` header does not carry",
490 );
491 }
492 // 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.
493 Ok(Self(value.to_owned()))
494 }
495
496 /// A fresh credential, drawn from the operating system's own
497 /// cryptographically secure random source.
498 ///
499 /// [`GENERATED_CREDENTIAL_BYTES`] bytes, written as unpadded URL-safe
500 /// base64 so an operator can copy it and a header can carry it as it is.
501 ///
502 /// # Errors
503 ///
504 /// Answers the random source's own refusal, when it has none to give.
505 pub fn generate() -> Result<Self, getrandom::Error> {
506 use base64::Engine as _;
507
508 let mut drawn = [0_u8; GENERATED_CREDENTIAL_BYTES];
509 getrandom::fill(&mut drawn)?;
510 Ok(Self(
511 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(drawn),
512 ))
513 }
514
515 /// Whether a presented credential is this one.
516 ///
517 /// The lengths are compared first, which says how long the credential is and
518 /// nothing else; the bytes are then compared in constant time, so how long
519 /// this takes says nothing about how much of it a caller guessed.
520 #[must_use]
521 pub fn admits(&self, presented: &[u8]) -> bool {
522 use subtle::ConstantTimeEq as _;
523
524 let expected = self.0.as_bytes();
525 expected.len() == presented.len() && bool::from(expected.ct_eq(presented))
526 }
527
528 /// The text, for the one file whose purpose is to carry it.
529 pub(crate) fn written(&self) -> &str {
530 &self.0
531 }
532}
533
534impl PartialEq for ApiCredential {
535 fn eq(&self, other: &Self) -> bool {
536 self.admits(other.0.as_bytes())
537 }
538}
539
540impl Eq for ApiCredential {}
541
542impl core::fmt::Display for ApiCredential {
543 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
544 formatter.write_str(REDACTED)
545 }
546}
547
548impl core::fmt::Debug for ApiCredential {
549 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
550 write!(formatter, "ApiCredential({REDACTED})")
551 }
552}
553
554/// One running server's validated configuration.
555///
556/// Every value here is one no later step has to re-examine, and where a
557/// validated type for one already exists it is that type rather than the text
558/// it was written as: the `OctoPrint` instance is the adapter's own
559/// configuration, which redacts the key it carries; the harness and the model
560/// are the supervisor adapter's own names; and the ingress secret is a value
561/// neither rendering of which shows.
562#[derive(Debug, Clone, PartialEq)]
563pub struct ServerConfig {
564 /// Where the store, the images and the sessions live.
565 pub state_dir: PathBuf,
566 /// The address the API and the ingress are served on.
567 pub listen: SocketAddr,
568 /// Everything the printer adapter needs to reach the instance.
569 pub octoprint: OctoPrintConfig,
570 /// The operator's safety envelope.
571 pub safety: SafetyEnvelope,
572 /// The harness identity turns run on.
573 pub harness: HarnessIdentity,
574 /// The model turns are pinned to, when one is pinned.
575 pub model: Option<ModelName>,
576 /// The installed skill's `SKILL.md`, whose prose is sent as every turn's
577 /// system prompt. The agent runs from the directory holding it, which is
578 /// where the skill's own `reference/` documents sit.
579 pub skill_path: PathBuf,
580 /// The prompt template one turn fills, when the operator supplied one.
581 pub prompt_template_path: Option<PathBuf>,
582 /// How long the ingress may take to answer.
583 pub ingress_answer_bound: core::time::Duration,
584 /// The shared secret every post to the ingress must carry.
585 pub ingress_shared_secret: SharedSecret,
586 /// The API credential the operator configured, when they configured one.
587 /// Absent, the composition root takes the one in the state directory.
588 pub api_credential: Option<ApiCredential>,
589}
590
591impl ServerConfig {
592 /// Read and validate the one configuration file this program takes.
593 ///
594 /// # Errors
595 ///
596 /// Returns [`ConfigError::Unreadable`] when the file is not there,
597 /// [`ConfigError::Unparsable`] when it is not this program's configuration,
598 /// and [`ConfigError::Field`] naming the one field whose value cannot be
599 /// accepted. The two values only the machine can rule on — the `OctoPrint`
600 /// address and key — are ruled on by [`crate::Server::start`], which is
601 /// where a printer exists to ask.
602 pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
603 let path = path.as_ref();
604 Self::parse(&read(path)?, path)
605 }
606
607 /// The same, over a document already read.
608 ///
609 /// # Errors
610 ///
611 /// The same as [`ServerConfig::load`], less the unreadable file.
612 pub fn parse(text: &str, path: &Path) -> Result<Self, ConfigError> {
613 let file: ConfigFile = toml::from_str(text).map_err(|error| ConfigError::Unparsable {
614 path: path.to_path_buf(),
615 detail: error.to_string(),
616 })?;
617 Self::validate(file)
618 }
619
620 /// Rule on every value the document carries.
621 ///
622 /// Absence is ruled on here rather than by the parser, because a parser's
623 /// own "missing field" says which key it wanted and not which field of this
624 /// program that is. Every refusal below names the dotted key an operator
625 /// would edit.
626 fn validate(file: ConfigFile) -> Result<Self, ConfigError> {
627 let state_dir =
628 state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?;
629 let listen = listen_address(&required(ConfigField::Listen, file.listen)?)?;
630 let octoprint = octoprint(&file.octoprint)?;
631 let safety = required(ConfigField::SafetyEnvelope, file.safety)?;
632 check_envelope(&safety)?;
633 let harness = harness_identity(file.supervisor.harness)?;
634 let model = match file.supervisor.model {
635 None => None,
636 Some(name) => Some(
637 ModelName::new(&named(ConfigField::Model, Some(name))?)
638 .map_err(|error| ConfigError::about(ConfigField::Model, error.to_string()))?,
639 ),
640 };
641 let skill_path = skill(file.supervisor.skill_path.as_deref())?;
642 let prompt_template_path = readable(
643 ConfigField::PromptTemplatePath,
644 file.supervisor.prompt_template_path.as_deref(),
645 )?;
646 let ingress_answer_bound = answer_bound(file.ingress.answer_bound_ms)?;
647 let ingress_shared_secret = SharedSecret::new(&required(
648 ConfigField::IngressSharedSecret,
649 file.ingress.shared_secret,
650 )?)?;
651 let api_credential = file
652 .api
653 .credential
654 .as_deref()
655 .map(|value| {
656 ApiCredential::new(value)
657 .map_err(|why| ConfigError::about(ConfigField::ApiCredential, why))
658 })
659 .transpose()?;
660 Ok(Self {
661 state_dir,
662 listen,
663 octoprint,
664 safety,
665 harness,
666 model,
667 skill_path,
668 prompt_template_path,
669 ingress_answer_bound,
670 ingress_shared_secret,
671 api_credential,
672 })
673 }
674
675 /// Where this server materializes the agent's prompt template and
676 /// assessment schema. The skill is not among them: it is the installed one
677 /// `skill_path` names.
678 #[must_use]
679 pub fn assets_dir(&self) -> PathBuf {
680 self.state_dir.join(ASSETS_DIRECTORY)
681 }
682}
683
684/// The two values signing a harness in reads, and nothing else.
685///
686/// An operator signs the agent in before or after filling in the machine and
687/// the failure detector, so `printobserver sign-in` reads the state directory
688/// and the harness identity out of the server's own file and nothing beside
689/// them: every other value the file carries, present or not and valid or not,
690/// is one it never looks at.
691#[derive(Debug, Clone, PartialEq, Eq)]
692pub struct SignInConfig {
693 /// Where the state lives, and so where the harness keeps its sign-in.
694 pub state_dir: PathBuf,
695 /// The harness identity supervision turns run on.
696 pub harness: HarnessIdentity,
697}
698
699impl SignInConfig {
700 /// Read those two values out of one configuration file.
701 ///
702 /// # Errors
703 ///
704 /// Returns [`ConfigError::Unreadable`] when the file is not there,
705 /// [`ConfigError::Unparsable`] when it is not a document carrying either
706 /// value in the shape this program reads it in, and [`ConfigError::Field`]
707 /// naming `state_dir` or `supervisor.harness` when that value cannot be
708 /// accepted.
709 pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
710 let path = path.as_ref();
711 let file: SignInFile =
712 toml::from_str(&read(path)?).map_err(|error| ConfigError::Unparsable {
713 path: path.to_path_buf(),
714 detail: error.to_string(),
715 })?;
716 Ok(Self {
717 state_dir: state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?,
718 harness: harness_identity(file.supervisor.harness)?,
719 })
720 }
721}
722
723/// The configuration file, read for the two values signing in takes.
724///
725/// Unlike [`ConfigFile`] it refuses no key it does not know, because every key
726/// but these two is one signing in does not read.
727#[derive(Deserialize)]
728#[serde(crate = "printobserver_types::serde")]
729struct SignInFile {
730 /// Where the state lives.
731 #[serde(default)]
732 state_dir: Option<PathBuf>,
733 /// The supervisor's section, for its harness alone.
734 #[serde(default)]
735 supervisor: SignInSupervisor,
736}
737
738/// The supervisor's section, read for the harness alone.
739#[derive(Default, Deserialize)]
740#[serde(crate = "printobserver_types::serde")]
741struct SignInSupervisor {
742 /// The harness identity turns run on.
743 #[serde(default)]
744 harness: Option<String>,
745}
746
747/// One configuration file's text.
748fn read(path: &Path) -> Result<String, ConfigError> {
749 std::fs::read_to_string(path).map_err(|error| ConfigError::Unreadable {
750 path: path.to_path_buf(),
751 detail: error.to_string(),
752 })
753}
754
755/// The harness identity, refused by its own key when it names nothing.
756fn harness_identity(value: Option<String>) -> Result<HarnessIdentity, ConfigError> {
757 HarnessIdentity::new(&named(ConfigField::Harness, value)?)
758 .map_err(|error| ConfigError::about(ConfigField::Harness, error.to_string()))
759}
760
761/// One field the file has to carry, refused by its own key when it does not.
762fn required<T>(field: ConfigField, value: Option<T>) -> Result<T, ConfigError> {
763 value.ok_or_else(|| ConfigError::about(field, "the configuration file carries no value for it"))
764}
765
766/// One field that has to carry a name rather than nothing at all.
767fn named(field: ConfigField, value: Option<String>) -> Result<String, ConfigError> {
768 let value = required(field, value)?;
769 if value.trim().is_empty() {
770 return Err(ConfigError::about(
771 field,
772 "it is empty, and an empty value names nothing",
773 ));
774 }
775 Ok(value.trim().to_owned())
776}
777
778/// The state directory, created where it is not there.
779fn state_directory(named: &Path) -> Result<PathBuf, ConfigError> {
780 if named.as_os_str().is_empty() {
781 return Err(ConfigError::about(
782 ConfigField::StateDir,
783 "it names no directory, and this server's whole state lives in one",
784 ));
785 }
786 std::fs::create_dir_all(named).map_err(|error| {
787 ConfigError::about(
788 ConfigField::StateDir,
789 format!("{} cannot be created: {error}", named.display()),
790 )
791 })?;
792 named.canonicalize().map(plainly_written).map_err(|error| {
793 ConfigError::about(
794 ConfigField::StateDir,
795 format!("{} cannot be resolved: {error}", named.display()),
796 )
797 })
798}
799
800/// A resolved path, written the way its own platform's tools write it.
801///
802/// Resolving a path on Windows answers it in its verbatim form, `\\?\C:\…`:
803/// one this program opens as readily as any other, and one no operator types and
804/// some of the programs a supervision turn runs refuse — and every image path
805/// this server answers is written under it. Where that form names an ordinary
806/// drive path it is written as that path. Any other path, which on every other
807/// platform is every path, is answered as it is.
808#[must_use]
809pub fn plainly_written(path: PathBuf) -> PathBuf {
810 const VERBATIM: &str = r"\\?\";
811 let drive = path
812 .to_str()
813 .and_then(|text| text.strip_prefix(VERBATIM))
814 .filter(|rest| {
815 let bytes = rest.as_bytes();
816 bytes.len() >= 3
817 && bytes[0].is_ascii_alphabetic()
818 && bytes[1] == b':'
819 && bytes[2] == b'\\'
820 })
821 .map(PathBuf::from);
822 drive.unwrap_or(path)
823}
824
825/// The address to serve on, as an address rather than as text.
826fn listen_address(named: &str) -> Result<SocketAddr, ConfigError> {
827 named.trim().parse().map_err(|error| {
828 ConfigError::about(
829 ConfigField::Listen,
830 format!("{named:?} is no address to listen on: {error}"),
831 )
832 })
833}
834
835/// Everything the printer adapter needs to reach the instance, refused by the
836/// field whose value it could not take.
837fn octoprint(section: &OctoprintSection) -> Result<OctoPrintConfig, ConfigError> {
838 let fan = fan_support(§ion.fan)?;
839 let url = named(ConfigField::OctoprintUrl, section.url.clone())?;
840 let key = named(ConfigField::OctoprintApiKey, section.api_key.clone())?;
841 OctoPrintConfig::new(&url, key)
842 .map(|configured| configured.with_fan(fan))
843 .map_err(|error| {
844 let field = match error {
845 printobserver_octoprint::ConfigError::EmptyApiKey => ConfigField::OctoprintApiKey,
846 _ => ConfigField::OctoprintUrl,
847 };
848 ConfigError::about(field, error.to_string())
849 })
850}
851
852/// The fan setting one word of the vocabulary names.
853fn fan_support(named: &str) -> Result<FanSupport, ConfigError> {
854 FAN_VOCABULARY
855 .iter()
856 .find(|(spelling, _)| *spelling == named.trim())
857 .map(|(_, support)| *support)
858 .ok_or_else(|| {
859 let vocabulary: Vec<&str> = FAN_VOCABULARY.iter().map(|(word, _)| *word).collect();
860 ConfigError::about(
861 ConfigField::OctoprintFan,
862 format!("{named:?} is not one of {}", vocabulary.join(" or ")),
863 )
864 })
865}
866
867/// The envelope, refused when a range it declares admits nothing.
868fn check_envelope(envelope: &SafetyEnvelope) -> Result<(), ConfigError> {
869 if envelope.allowed.is_empty() {
870 return Err(ConfigError::about(
871 ConfigField::SafetyEnvelope,
872 "it allows no adjustable at all, so no adjustment could ever be accepted",
873 ));
874 }
875 for (adjustable, range) in &envelope.allowed {
876 if !range.min.is_finite() || !range.max.is_finite() || range.min > range.max {
877 return Err(ConfigError::about(
878 ConfigField::SafetyEnvelope,
879 format!(
880 "the range allowed for {adjustable} runs from {} to {}, which admits \
881 no value",
882 range.min, range.max
883 ),
884 ));
885 }
886 }
887 if envelope.agent_min_interval_s < 0 {
888 return Err(ConfigError::about(
889 ConfigField::SafetyEnvelope,
890 format!(
891 "the agent's minimum interval is {}s, and an interval is a count of seconds",
892 envelope.agent_min_interval_s
893 ),
894 ));
895 }
896 Ok(())
897}
898
899/// One optional path, read where it was named so that a path naming nothing is
900/// refused here rather than hours later.
901fn readable(field: ConfigField, named: Option<&Path>) -> Result<Option<PathBuf>, ConfigError> {
902 let Some(path) = named else {
903 return Ok(None);
904 };
905 std::fs::read_to_string(path)
906 .map(|_| Some(path.to_path_buf()))
907 .map_err(|error| {
908 ConfigError::about(field, format!("{} cannot be read: {error}", path.display()))
909 })
910}
911
912/// The installed skill, refused naming how to install one when it is absent or
913/// cannot be read.
914fn skill(named: Option<&Path>) -> Result<PathBuf, ConfigError> {
915 let Some(path) = named else {
916 return Err(ConfigError::about(
917 ConfigField::SkillPath,
918 format!(
919 "the configuration file carries no value for it, and this program carries \
920 no skill of its own: {SKILL_INSTALL}"
921 ),
922 ));
923 };
924 std::fs::read_to_string(path)
925 .map(|_| path.to_path_buf())
926 .map_err(|error| {
927 ConfigError::about(
928 ConfigField::SkillPath,
929 format!(
930 "{} cannot be read: {error}. {SKILL_INSTALL}",
931 path.display()
932 ),
933 )
934 })
935}
936
937/// The answer bound, refused when it is not one this program admits.
938fn answer_bound(milliseconds: u64) -> Result<core::time::Duration, ConfigError> {
939 if milliseconds == 0 {
940 return Err(ConfigError::about(
941 ConfigField::IngressAnswerBoundMs,
942 "a bound of zero is an ingress that has run out of time before it starts",
943 ));
944 }
945 if milliseconds >= OBICO_POSTING_TIMEOUT_MS {
946 return Err(ConfigError::about(
947 ConfigField::IngressAnswerBoundMs,
948 format!(
949 "{milliseconds}ms is not below the {OBICO_POSTING_TIMEOUT_MS}ms Obico posts \
950 under, so an alert answered at that bound is one Obico has already \
951 abandoned — and its posting does not retry"
952 ),
953 ));
954 }
955 Ok(core::time::Duration::from_millis(milliseconds))
956}