printobserver-server 0.2.0

The printobserver server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
//! The one configuration file a running supervisor reads, and its validation.
//!
//! # Every field this program takes is declared once, here
//!
//! [`ConfigField`] is that declaration: one variant per configured value, each
//! carrying the dotted key it is spelled under. Two things read it rather than
//! restating it — the refusal a bad value produces names its field through it,
//! and this crate's own tier walks it, driving a server against a configuration
//! in which each field in turn is unacceptable. A field added to the shapes
//! below and not to [`ConfigField::ALL`] fails that tier's own coverage check,
//! so the walk cannot fall behind the type.
//!
//! # Validation happens at startup, and names the field
//!
//! A value that cannot work is refused where it is configured rather than at
//! the first request that needs it, and the refusal carries the field's own key
//! so an operator editing the file knows which line to change. That includes
//! the two values only the machine can rule on: an `OctoPrint` address nothing
//! answers at and a key that instance refuses are both configuration mistakes,
//! and [`crate::Server::start`] refuses them naming
//! [`ConfigField::OctoprintUrl`] and [`ConfigField::OctoprintApiKey`].
//!
//! # The ingress answer bound
//!
//! `Obico`'s webhook notification plugin posts best-effort with a short timeout
//! and does not retry, so this server answers its ingress before the handling
//! completes and inside a bound it declares here. The shipped default is
//! [`DEFAULT_INGRESS_ANSWER_BOUND_MS`] and the timeout it must stay below is
//! [`OBICO_POSTING_TIMEOUT_MS`]; `AGENTS.md`'s "The Obico ingress answer bound"
//! records that number, where it was read and why the default is where it is,
//! and `just check-repo` refuses a tree in which the two disagree.

use std::net::SocketAddr;
use std::path::{Path, PathBuf};

use printobserver_octoprint::{FanSupport, OctoPrintConfig};
use printobserver_oneharness::{HarnessIdentity, ModelName};
use printobserver_types::SafetyEnvelope;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};

/// The answer bound this repository ships, in milliseconds.
///
/// A fifth of [`OBICO_POSTING_TIMEOUT_MS`]. The margin is deliberate: the
/// supported host is a small ARM board beside the printer, and a bound set just
/// under the producer's timeout would be exceeded by the first slow moment on
/// it — after which `Obico` drops the alert, because its posting does not retry.
pub const DEFAULT_INGRESS_ANSWER_BOUND_MS: u64 = 1_000;

/// The timeout `Obico`'s own webhook notification plugin posts under.
///
/// Read from the `Obico` release the `obico-fixture` node stands up — revision
/// `49c0bc7001a3fd8d56297fc3032ba287bfe1d50b`,
/// `backend/notifications/plugins/webhook/__init__.py`, whose `execute_webhook`
/// takes `timeout: float = 5.0` and calls `raise_for_status` with no retry.
/// This repository's claim about an external producer; what reconciles it
/// against a live `Obico` is the scheduled `Obico` tier.
pub const OBICO_POSTING_TIMEOUT_MS: u64 = 5_000;

/// The directory under the state directory this server materializes the
/// supervising agent's own committed assets into.
pub const ASSETS_DIRECTORY: &str = "assets";

/// Every value this program is configured with, and the key it is spelled under.
///
/// The walk in this crate's tier is over this array, and the array is compared
/// against the configuration shapes' own declared properties, so neither can
/// grow a field the other does not know about.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ConfigField {
    /// Where the store, the images and the sessions live.
    StateDir,
    /// The address the API and the ingress are served on.
    Listen,
    /// Where the `OctoPrint` instance answers.
    OctoprintUrl,
    /// The key that instance authenticates every request by.
    OctoprintApiKey,
    /// Whether the machine has a part-cooling fan this server may command.
    OctoprintFan,
    /// The operator's safety envelope.
    SafetyEnvelope,
    /// The harness identity supervision turns run on.
    Harness,
    /// The model turns are pinned to, when one is pinned.
    Model,
    /// The `PrintObserver` skill sent as every turn's system prompt.
    SkillPath,
    /// The prompt template one turn fills.
    PromptTemplatePath,
    /// How long the ingress may take to answer, in milliseconds.
    IngressAnswerBoundMs,
    /// The shared secret the ingress requires of every post.
    IngressSharedSecret,
}

impl ConfigField {
    /// Every field this program takes, and there is no other.
    pub const ALL: [Self; 12] = [
        Self::StateDir,
        Self::Listen,
        Self::OctoprintUrl,
        Self::OctoprintApiKey,
        Self::OctoprintFan,
        Self::SafetyEnvelope,
        Self::Harness,
        Self::Model,
        Self::SkillPath,
        Self::PromptTemplatePath,
        Self::IngressAnswerBoundMs,
        Self::IngressSharedSecret,
    ];

    /// The dotted key this field is spelled under in the configuration file.
    #[must_use]
    pub const fn key(self) -> &'static str {
        match self {
            Self::StateDir => "state_dir",
            Self::Listen => "listen",
            Self::OctoprintUrl => "octoprint.url",
            Self::OctoprintApiKey => "octoprint.api_key",
            Self::OctoprintFan => "octoprint.fan",
            Self::SafetyEnvelope => "safety",
            Self::Harness => "supervisor.harness",
            Self::Model => "supervisor.model",
            Self::SkillPath => "supervisor.skill_path",
            Self::PromptTemplatePath => "supervisor.prompt_template_path",
            Self::IngressAnswerBoundMs => "ingress.answer_bound_ms",
            Self::IngressSharedSecret => "ingress.shared_secret",
        }
    }
}

impl core::fmt::Display for ConfigField {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter.write_str(self.key())
    }
}

/// Why this server will not start under the configuration it was given.
///
/// Every variant names the field it is about, because the answer an operator
/// needs is which line of the file to change.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigError {
    /// The file could not be read at all.
    Unreadable {
        /// The path that was named.
        path: PathBuf,
        /// What went wrong reading it.
        detail: String,
    },
    /// The file is not the document this program takes.
    Unparsable {
        /// The path that was named.
        path: PathBuf,
        /// What could not be parsed, in the parser's own words.
        detail: String,
    },
    /// One field carries a value this program cannot accept.
    Field {
        /// The field it is about.
        field: ConfigField,
        /// Why the value cannot be accepted.
        detail: String,
    },
}

impl ConfigError {
    /// The field this refusal is about, when it is about one.
    #[must_use]
    pub const fn field(&self) -> Option<ConfigField> {
        match self {
            Self::Field { field, .. } => Some(*field),
            _ => None,
        }
    }

    /// One field's refusal, in its own words.
    pub(crate) fn about(field: ConfigField, detail: impl Into<String>) -> Self {
        Self::Field {
            field,
            detail: detail.into(),
        }
    }
}

impl core::fmt::Display for ConfigError {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Unreadable { path, detail } => write!(
                formatter,
                "the configuration file {} could not be read: {detail}",
                path.display()
            ),
            Self::Unparsable { path, detail } => write!(
                formatter,
                "the configuration file {} could not be read as this program's \
                 configuration: {detail}",
                path.display()
            ),
            Self::Field { field, detail } => write!(
                formatter,
                "the configuration field `{field}` cannot be accepted: {detail}"
            ),
        }
    }
}

impl core::error::Error for ConfigError {}

/// Where the `OctoPrint` instance is and what it is like, as written down.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(
    crate = "printobserver_types::serde",
    deny_unknown_fields,
    rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct OctoprintSection {
    /// The base URL the instance answers on.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// The key it authenticates every request by.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_key: Option<String>,
    /// Whether the machine has a part-cooling fan this server may command.
    #[serde(default = "commandable")]
    pub fan: String,
}

/// The vocabulary [`OctoprintSection::fan`] takes, spelled as the operator
/// writes it.
pub const FAN_VOCABULARY: [(&str, FanSupport); 2] = [
    ("commandable", FanSupport::Commandable),
    ("absent", FanSupport::Absent),
];

/// The fan setting a configuration naming none takes.
fn commandable() -> String {
    FAN_VOCABULARY[0].0.to_owned()
}

impl Default for OctoprintSection {
    fn default() -> Self {
        Self {
            url: None,
            api_key: None,
            fan: commandable(),
        }
    }
}

/// How the supervising agent is reached, as written down.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(
    crate = "printobserver_types::serde",
    deny_unknown_fields,
    rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
#[derive(Default)]
pub struct SupervisorSection {
    /// The harness identity turns run on.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub harness: Option<String>,
    /// The model turns are pinned to, when one is pinned.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// The skill to send as every turn's system prompt, when the operator
    /// supplies one instead of the committed skill this program carries.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub skill_path: Option<PathBuf>,
    /// The prompt template one turn fills, when the operator supplies one
    /// instead of the committed template this program carries.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prompt_template_path: Option<PathBuf>,
}

/// What the `Obico` ingress requires and how fast it answers, as written down.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(
    crate = "printobserver_types::serde",
    deny_unknown_fields,
    rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct IngressSection {
    /// The shared secret every post must carry.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shared_secret: Option<String>,
    /// How long the ingress may take to answer, in milliseconds.
    #[serde(default = "default_answer_bound_ms")]
    pub answer_bound_ms: u64,
}

/// The answer bound a configuration naming none takes.
const fn default_answer_bound_ms() -> u64 {
    DEFAULT_INGRESS_ANSWER_BOUND_MS
}

impl Default for IngressSection {
    fn default() -> Self {
        Self {
            shared_secret: None,
            answer_bound_ms: DEFAULT_INGRESS_ANSWER_BOUND_MS,
        }
    }
}

/// The whole configuration file, exactly as it is written down.
///
/// This is the parsed document rather than the validated configuration:
/// [`ServerConfig::load`] is what turns one into the other, and every value a
/// later step could find wrong is ruled on there.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(
    crate = "printobserver_types::serde",
    deny_unknown_fields,
    rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct ConfigFile {
    /// Where the store, the images and the sessions live.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub state_dir: Option<PathBuf>,
    /// The address the API and the ingress are served on.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub listen: Option<String>,
    /// Where the `OctoPrint` instance is.
    #[serde(default)]
    pub octoprint: OctoprintSection,
    /// The operator's safety envelope.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub safety: Option<SafetyEnvelope>,
    /// How the supervising agent is reached.
    #[serde(default)]
    pub supervisor: SupervisorSection,
    /// What the `Obico` ingress requires.
    #[serde(default)]
    pub ingress: IngressSection,
}

/// The shared secret the ingress requires of every post.
///
/// Neither rendering of this type shows the value, so it cannot reach a log
/// record, a panic message or an error's own text by being formatted — and the
/// comparison that admits a post lives here rather than at the endpoint, so
/// there is no way to read the secret out in order to compare it.
#[derive(Clone, PartialEq, Eq)]
pub struct SharedSecret(String);

/// What a secret renders as, wherever a value carrying one is rendered.
pub const REDACTED: &str = "<redacted>";

impl SharedSecret {
    /// The secret this text names.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError`] when the text is empty or is nothing but
    /// whitespace: anything that can post to the ingress can pause a printer,
    /// and a secret nothing has to carry is no secret.
    pub fn new(value: &str) -> Result<Self, ConfigError> {
        if value.trim().is_empty() {
            return Err(ConfigError::about(
                ConfigField::IngressSharedSecret,
                "it is empty, and anything that can post to the ingress can pause a printer",
            ));
        }
        Ok(Self(value.to_owned()))
    }

    /// Whether a post carried this secret.
    ///
    /// Compared over the whole of both values with the two lengths mixed in,
    /// rather than by returning at the first difference or at a length
    /// mismatch, so that how long this takes says nothing about how much of the
    /// secret a caller guessed.
    #[must_use]
    pub fn matches(&self, offered: Option<&str>) -> bool {
        let Some(offered) = offered else {
            return false;
        };
        let expected = self.0.as_bytes();
        let mut difference = expected.len() ^ offered.len();
        for (index, byte) in offered.bytes().enumerate() {
            let against = expected[index % expected.len().max(1)];
            difference |= usize::from(byte ^ against);
        }
        difference == 0
    }
}

impl core::fmt::Display for SharedSecret {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter.write_str(REDACTED)
    }
}

impl core::fmt::Debug for SharedSecret {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(formatter, "SharedSecret({REDACTED})")
    }
}

/// One running server's validated configuration.
///
/// Every value here is one no later step has to re-examine, and where a
/// validated type for one already exists it is that type rather than the text
/// it was written as: the `OctoPrint` instance is the adapter's own
/// configuration, which redacts the key it carries; the harness and the model
/// are the supervisor adapter's own names; and the ingress secret is a value
/// neither rendering of which shows.
#[derive(Debug, Clone, PartialEq)]
pub struct ServerConfig {
    /// Where the store, the images and the sessions live.
    pub state_dir: PathBuf,
    /// The address the API and the ingress are served on.
    pub listen: SocketAddr,
    /// Everything the printer adapter needs to reach the instance.
    pub octoprint: OctoPrintConfig,
    /// The operator's safety envelope.
    pub safety: SafetyEnvelope,
    /// The harness identity turns run on.
    pub harness: HarnessIdentity,
    /// The model turns are pinned to, when one is pinned.
    pub model: Option<ModelName>,
    /// The skill to send as every turn's system prompt, when the operator
    /// supplied one.
    pub skill_path: Option<PathBuf>,
    /// The prompt template one turn fills, when the operator supplied one.
    pub prompt_template_path: Option<PathBuf>,
    /// How long the ingress may take to answer.
    pub ingress_answer_bound: core::time::Duration,
    /// The shared secret every post to the ingress must carry.
    pub ingress_shared_secret: SharedSecret,
}

impl ServerConfig {
    /// Read and validate the one configuration file this program takes.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError::Unreadable`] when the file is not there,
    /// [`ConfigError::Unparsable`] when it is not this program's configuration,
    /// and [`ConfigError::Field`] naming the one field whose value cannot be
    /// accepted. The two values only the machine can rule on — the `OctoPrint`
    /// address and key — are ruled on by [`crate::Server::start`], which is
    /// where a printer exists to ask.
    pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
        let path = path.as_ref();
        let text = std::fs::read_to_string(path).map_err(|error| ConfigError::Unreadable {
            path: path.to_path_buf(),
            detail: error.to_string(),
        })?;
        Self::parse(&text, path)
    }

    /// The same, over a document already read.
    ///
    /// # Errors
    ///
    /// The same as [`ServerConfig::load`], less the unreadable file.
    pub fn parse(text: &str, path: &Path) -> Result<Self, ConfigError> {
        let file: ConfigFile = toml::from_str(text).map_err(|error| ConfigError::Unparsable {
            path: path.to_path_buf(),
            detail: error.to_string(),
        })?;
        Self::validate(file)
    }

    /// Rule on every value the document carries.
    ///
    /// Absence is ruled on here rather than by the parser, because a parser's
    /// own "missing field" says which key it wanted and not which field of this
    /// program that is. Every refusal below names the dotted key an operator
    /// would edit.
    fn validate(file: ConfigFile) -> Result<Self, ConfigError> {
        let state_dir =
            state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?;
        let listen = listen_address(&required(ConfigField::Listen, file.listen)?)?;
        let octoprint = octoprint(&file.octoprint)?;
        let safety = required(ConfigField::SafetyEnvelope, file.safety)?;
        check_envelope(&safety)?;
        let harness = HarnessIdentity::new(&named(ConfigField::Harness, file.supervisor.harness)?)
            .map_err(|error| ConfigError::about(ConfigField::Harness, error.to_string()))?;
        let model = match file.supervisor.model {
            None => None,
            Some(name) => Some(
                ModelName::new(&named(ConfigField::Model, Some(name))?)
                    .map_err(|error| ConfigError::about(ConfigField::Model, error.to_string()))?,
            ),
        };
        let skill_path = readable(
            ConfigField::SkillPath,
            file.supervisor.skill_path.as_deref(),
        )?;
        let prompt_template_path = readable(
            ConfigField::PromptTemplatePath,
            file.supervisor.prompt_template_path.as_deref(),
        )?;
        let ingress_answer_bound = answer_bound(file.ingress.answer_bound_ms)?;
        let ingress_shared_secret = SharedSecret::new(&required(
            ConfigField::IngressSharedSecret,
            file.ingress.shared_secret,
        )?)?;
        Ok(Self {
            state_dir,
            listen,
            octoprint,
            safety,
            harness,
            model,
            skill_path,
            prompt_template_path,
            ingress_answer_bound,
            ingress_shared_secret,
        })
    }

    /// Where this server materializes the agent's committed assets.
    #[must_use]
    pub fn assets_dir(&self) -> PathBuf {
        self.state_dir.join(ASSETS_DIRECTORY)
    }
}

/// One field the file has to carry, refused by its own key when it does not.
fn required<T>(field: ConfigField, value: Option<T>) -> Result<T, ConfigError> {
    value.ok_or_else(|| ConfigError::about(field, "the configuration file carries no value for it"))
}

/// One field that has to carry a name rather than nothing at all.
fn named(field: ConfigField, value: Option<String>) -> Result<String, ConfigError> {
    let value = required(field, value)?;
    if value.trim().is_empty() {
        return Err(ConfigError::about(
            field,
            "it is empty, and an empty value names nothing",
        ));
    }
    Ok(value.trim().to_owned())
}

/// The state directory, created where it is not there.
fn state_directory(named: &Path) -> Result<PathBuf, ConfigError> {
    if named.as_os_str().is_empty() {
        return Err(ConfigError::about(
            ConfigField::StateDir,
            "it names no directory, and this server's whole state lives in one",
        ));
    }
    std::fs::create_dir_all(named).map_err(|error| {
        ConfigError::about(
            ConfigField::StateDir,
            format!("{} cannot be created: {error}", named.display()),
        )
    })?;
    named.canonicalize().map_err(|error| {
        ConfigError::about(
            ConfigField::StateDir,
            format!("{} cannot be resolved: {error}", named.display()),
        )
    })
}

/// The address to serve on, as an address rather than as text.
fn listen_address(named: &str) -> Result<SocketAddr, ConfigError> {
    named.trim().parse().map_err(|error| {
        ConfigError::about(
            ConfigField::Listen,
            format!("{named:?} is no address to listen on: {error}"),
        )
    })
}

/// Everything the printer adapter needs to reach the instance, refused by the
/// field whose value it could not take.
fn octoprint(section: &OctoprintSection) -> Result<OctoPrintConfig, ConfigError> {
    let fan = fan_support(&section.fan)?;
    let url = named(ConfigField::OctoprintUrl, section.url.clone())?;
    let key = named(ConfigField::OctoprintApiKey, section.api_key.clone())?;
    OctoPrintConfig::new(&url, key)
        .map(|configured| configured.with_fan(fan))
        .map_err(|error| {
            let field = match error {
                printobserver_octoprint::ConfigError::EmptyApiKey => ConfigField::OctoprintApiKey,
                _ => ConfigField::OctoprintUrl,
            };
            ConfigError::about(field, error.to_string())
        })
}

/// The fan setting one word of the vocabulary names.
fn fan_support(named: &str) -> Result<FanSupport, ConfigError> {
    FAN_VOCABULARY
        .iter()
        .find(|(spelling, _)| *spelling == named.trim())
        .map(|(_, support)| *support)
        .ok_or_else(|| {
            let vocabulary: Vec<&str> = FAN_VOCABULARY.iter().map(|(word, _)| *word).collect();
            ConfigError::about(
                ConfigField::OctoprintFan,
                format!("{named:?} is not one of {}", vocabulary.join(" or ")),
            )
        })
}

/// The envelope, refused when a range it declares admits nothing.
fn check_envelope(envelope: &SafetyEnvelope) -> Result<(), ConfigError> {
    if envelope.allowed.is_empty() {
        return Err(ConfigError::about(
            ConfigField::SafetyEnvelope,
            "it allows no adjustable at all, so no adjustment could ever be accepted",
        ));
    }
    for (adjustable, range) in &envelope.allowed {
        if !range.min.is_finite() || !range.max.is_finite() || range.min > range.max {
            return Err(ConfigError::about(
                ConfigField::SafetyEnvelope,
                format!(
                    "the range allowed for {adjustable} runs from {} to {}, which admits \
                     no value",
                    range.min, range.max
                ),
            ));
        }
    }
    if envelope.agent_min_interval_s < 0 {
        return Err(ConfigError::about(
            ConfigField::SafetyEnvelope,
            format!(
                "the agent's minimum interval is {}s, and an interval is a count of seconds",
                envelope.agent_min_interval_s
            ),
        ));
    }
    Ok(())
}

/// One optional path, read where it was named so that a path naming nothing is
/// refused here rather than hours later.
fn readable(field: ConfigField, named: Option<&Path>) -> Result<Option<PathBuf>, ConfigError> {
    let Some(path) = named else {
        return Ok(None);
    };
    std::fs::read_to_string(path)
        .map(|_| Some(path.to_path_buf()))
        .map_err(|error| {
            ConfigError::about(field, format!("{} cannot be read: {error}", path.display()))
        })
}

/// The answer bound, refused when it is not one this program admits.
fn answer_bound(milliseconds: u64) -> Result<core::time::Duration, ConfigError> {
    if milliseconds == 0 {
        return Err(ConfigError::about(
            ConfigField::IngressAnswerBoundMs,
            "a bound of zero is an ingress that has run out of time before it starts",
        ));
    }
    if milliseconds >= OBICO_POSTING_TIMEOUT_MS {
        return Err(ConfigError::about(
            ConfigField::IngressAnswerBoundMs,
            format!(
                "{milliseconds}ms is not below the {OBICO_POSTING_TIMEOUT_MS}ms Obico posts \
                 under, so an alert answered at that bound is one Obico has already \
                 abandoned — and its posting does not retry"
            ),
        ));
    }
    Ok(core::time::Duration::from_millis(milliseconds))
}