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
33use std::net::SocketAddr;
34use std::path::{Path, PathBuf};
35
36use printobserver_octoprint::{FanSupport, OctoPrintConfig};
37use printobserver_oneharness::{HarnessIdentity, ModelName};
38use printobserver_types::SafetyEnvelope;
39use printobserver_types::schemars::JsonSchema;
40use printobserver_types::serde::{Deserialize, Serialize};
41
42/// The answer bound this repository ships, in milliseconds.
43///
44/// A fifth of [`OBICO_POSTING_TIMEOUT_MS`]. The margin is deliberate: the
45/// supported host is a small ARM board beside the printer, and a bound set just
46/// under the producer's timeout would be exceeded by the first slow moment on
47/// it — after which `Obico` drops the alert, because its posting does not retry.
48pub const DEFAULT_INGRESS_ANSWER_BOUND_MS: u64 = 1_000;
49
50/// The timeout `Obico`'s own webhook notification plugin posts under.
51///
52/// Read from the `Obico` release the `obico-fixture` node stands up — revision
53/// `49c0bc7001a3fd8d56297fc3032ba287bfe1d50b`,
54/// `backend/notifications/plugins/webhook/__init__.py`, whose `execute_webhook`
55/// takes `timeout: float = 5.0` and calls `raise_for_status` with no retry.
56/// This repository's claim about an external producer; what reconciles it
57/// against a live `Obico` is the scheduled `Obico` tier.
58pub const OBICO_POSTING_TIMEOUT_MS: u64 = 5_000;
59
60/// The directory under the state directory this server materializes the
61/// supervising agent's own committed assets into.
62pub const ASSETS_DIRECTORY: &str = "assets";
63
64/// Every value this program is configured with, and the key it is spelled under.
65///
66/// The walk in this crate's tier is over this array, and the array is compared
67/// against the configuration shapes' own declared properties, so neither can
68/// grow a field the other does not know about.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
70pub enum ConfigField {
71    /// Where the store, the images and the sessions live.
72    StateDir,
73    /// The address the API and the ingress are served on.
74    Listen,
75    /// Where the `OctoPrint` instance answers.
76    OctoprintUrl,
77    /// The key that instance authenticates every request by.
78    OctoprintApiKey,
79    /// Whether the machine has a part-cooling fan this server may command.
80    OctoprintFan,
81    /// The operator's safety envelope.
82    SafetyEnvelope,
83    /// The harness identity supervision turns run on.
84    Harness,
85    /// The model turns are pinned to, when one is pinned.
86    Model,
87    /// The `PrintObserver` skill sent as every turn's system prompt.
88    SkillPath,
89    /// The prompt template one turn fills.
90    PromptTemplatePath,
91    /// How long the ingress may take to answer, in milliseconds.
92    IngressAnswerBoundMs,
93    /// The shared secret the ingress requires of every post.
94    IngressSharedSecret,
95}
96
97impl ConfigField {
98    /// Every field this program takes, and there is no other.
99    pub const ALL: [Self; 12] = [
100        Self::StateDir,
101        Self::Listen,
102        Self::OctoprintUrl,
103        Self::OctoprintApiKey,
104        Self::OctoprintFan,
105        Self::SafetyEnvelope,
106        Self::Harness,
107        Self::Model,
108        Self::SkillPath,
109        Self::PromptTemplatePath,
110        Self::IngressAnswerBoundMs,
111        Self::IngressSharedSecret,
112    ];
113
114    /// The dotted key this field is spelled under in the configuration file.
115    #[must_use]
116    pub const fn key(self) -> &'static str {
117        match self {
118            Self::StateDir => "state_dir",
119            Self::Listen => "listen",
120            Self::OctoprintUrl => "octoprint.url",
121            Self::OctoprintApiKey => "octoprint.api_key",
122            Self::OctoprintFan => "octoprint.fan",
123            Self::SafetyEnvelope => "safety",
124            Self::Harness => "supervisor.harness",
125            Self::Model => "supervisor.model",
126            Self::SkillPath => "supervisor.skill_path",
127            Self::PromptTemplatePath => "supervisor.prompt_template_path",
128            Self::IngressAnswerBoundMs => "ingress.answer_bound_ms",
129            Self::IngressSharedSecret => "ingress.shared_secret",
130        }
131    }
132}
133
134impl core::fmt::Display for ConfigField {
135    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
136        formatter.write_str(self.key())
137    }
138}
139
140/// Why this server will not start under the configuration it was given.
141///
142/// Every variant names the field it is about, because the answer an operator
143/// needs is which line of the file to change.
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub enum ConfigError {
146    /// The file could not be read at all.
147    Unreadable {
148        /// The path that was named.
149        path: PathBuf,
150        /// What went wrong reading it.
151        detail: String,
152    },
153    /// The file is not the document this program takes.
154    Unparsable {
155        /// The path that was named.
156        path: PathBuf,
157        /// What could not be parsed, in the parser's own words.
158        detail: String,
159    },
160    /// One field carries a value this program cannot accept.
161    Field {
162        /// The field it is about.
163        field: ConfigField,
164        /// Why the value cannot be accepted.
165        detail: String,
166    },
167}
168
169impl ConfigError {
170    /// The field this refusal is about, when it is about one.
171    #[must_use]
172    pub const fn field(&self) -> Option<ConfigField> {
173        match self {
174            Self::Field { field, .. } => Some(*field),
175            _ => None,
176        }
177    }
178
179    /// One field's refusal, in its own words.
180    pub(crate) fn about(field: ConfigField, detail: impl Into<String>) -> Self {
181        Self::Field {
182            field,
183            detail: detail.into(),
184        }
185    }
186}
187
188impl core::fmt::Display for ConfigError {
189    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
190        match self {
191            Self::Unreadable { path, detail } => write!(
192                formatter,
193                "the configuration file {} could not be read: {detail}",
194                path.display()
195            ),
196            Self::Unparsable { path, detail } => write!(
197                formatter,
198                "the configuration file {} could not be read as this program's \
199                 configuration: {detail}",
200                path.display()
201            ),
202            Self::Field { field, detail } => write!(
203                formatter,
204                "the configuration field `{field}` cannot be accepted: {detail}"
205            ),
206        }
207    }
208}
209
210impl core::error::Error for ConfigError {}
211
212/// Where the `OctoPrint` instance is and what it is like, as written down.
213#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
214#[serde(
215    crate = "printobserver_types::serde",
216    deny_unknown_fields,
217    rename_all = "snake_case"
218)]
219#[schemars(crate = "printobserver_types::schemars")]
220pub struct OctoprintSection {
221    /// The base URL the instance answers on.
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub url: Option<String>,
224    /// The key it authenticates every request by.
225    #[serde(default, skip_serializing_if = "Option::is_none")]
226    pub api_key: Option<String>,
227    /// Whether the machine has a part-cooling fan this server may command.
228    #[serde(default = "commandable")]
229    pub fan: String,
230}
231
232/// The vocabulary [`OctoprintSection::fan`] takes, spelled as the operator
233/// writes it.
234pub const FAN_VOCABULARY: [(&str, FanSupport); 2] = [
235    ("commandable", FanSupport::Commandable),
236    ("absent", FanSupport::Absent),
237];
238
239/// The fan setting a configuration naming none takes.
240fn commandable() -> String {
241    FAN_VOCABULARY[0].0.to_owned()
242}
243
244impl Default for OctoprintSection {
245    fn default() -> Self {
246        Self {
247            url: None,
248            api_key: None,
249            fan: commandable(),
250        }
251    }
252}
253
254/// How the supervising agent is reached, as written down.
255#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
256#[serde(
257    crate = "printobserver_types::serde",
258    deny_unknown_fields,
259    rename_all = "snake_case"
260)]
261#[schemars(crate = "printobserver_types::schemars")]
262#[derive(Default)]
263pub struct SupervisorSection {
264    /// The harness identity turns run on.
265    #[serde(default, skip_serializing_if = "Option::is_none")]
266    pub harness: Option<String>,
267    /// The model turns are pinned to, when one is pinned.
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub model: Option<String>,
270    /// The skill to send as every turn's system prompt, when the operator
271    /// supplies one instead of the committed skill this program carries.
272    #[serde(default, skip_serializing_if = "Option::is_none")]
273    pub skill_path: Option<PathBuf>,
274    /// The prompt template one turn fills, when the operator supplies one
275    /// instead of the committed template this program carries.
276    #[serde(default, skip_serializing_if = "Option::is_none")]
277    pub prompt_template_path: Option<PathBuf>,
278}
279
280/// What the `Obico` ingress requires and how fast it answers, as written down.
281#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
282#[serde(
283    crate = "printobserver_types::serde",
284    deny_unknown_fields,
285    rename_all = "snake_case"
286)]
287#[schemars(crate = "printobserver_types::schemars")]
288pub struct IngressSection {
289    /// The shared secret every post must carry.
290    #[serde(default, skip_serializing_if = "Option::is_none")]
291    pub shared_secret: Option<String>,
292    /// How long the ingress may take to answer, in milliseconds.
293    #[serde(default = "default_answer_bound_ms")]
294    pub answer_bound_ms: u64,
295}
296
297/// The answer bound a configuration naming none takes.
298const fn default_answer_bound_ms() -> u64 {
299    DEFAULT_INGRESS_ANSWER_BOUND_MS
300}
301
302impl Default for IngressSection {
303    fn default() -> Self {
304        Self {
305            shared_secret: None,
306            answer_bound_ms: DEFAULT_INGRESS_ANSWER_BOUND_MS,
307        }
308    }
309}
310
311/// The whole configuration file, exactly as it is written down.
312///
313/// This is the parsed document rather than the validated configuration:
314/// [`ServerConfig::load`] is what turns one into the other, and every value a
315/// later step could find wrong is ruled on there.
316#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
317#[serde(
318    crate = "printobserver_types::serde",
319    deny_unknown_fields,
320    rename_all = "snake_case"
321)]
322#[schemars(crate = "printobserver_types::schemars")]
323pub struct ConfigFile {
324    /// Where the store, the images and the sessions live.
325    #[serde(default, skip_serializing_if = "Option::is_none")]
326    pub state_dir: Option<PathBuf>,
327    /// The address the API and the ingress are served on.
328    #[serde(default, skip_serializing_if = "Option::is_none")]
329    pub listen: Option<String>,
330    /// Where the `OctoPrint` instance is.
331    #[serde(default)]
332    pub octoprint: OctoprintSection,
333    /// The operator's safety envelope.
334    #[serde(default, skip_serializing_if = "Option::is_none")]
335    pub safety: Option<SafetyEnvelope>,
336    /// How the supervising agent is reached.
337    #[serde(default)]
338    pub supervisor: SupervisorSection,
339    /// What the `Obico` ingress requires.
340    #[serde(default)]
341    pub ingress: IngressSection,
342}
343
344/// The shared secret the ingress requires of every post.
345///
346/// Neither rendering of this type shows the value, so it cannot reach a log
347/// record, a panic message or an error's own text by being formatted — and the
348/// comparison that admits a post lives here rather than at the endpoint, so
349/// there is no way to read the secret out in order to compare it.
350#[derive(Clone, PartialEq, Eq)]
351pub struct SharedSecret(String);
352
353/// What a secret renders as, wherever a value carrying one is rendered.
354pub const REDACTED: &str = "<redacted>";
355
356impl SharedSecret {
357    /// The secret this text names.
358    ///
359    /// # Errors
360    ///
361    /// Returns [`ConfigError`] when the text is empty or is nothing but
362    /// whitespace: anything that can post to the ingress can pause a printer,
363    /// and a secret nothing has to carry is no secret.
364    pub fn new(value: &str) -> Result<Self, ConfigError> {
365        if value.trim().is_empty() {
366            return Err(ConfigError::about(
367                ConfigField::IngressSharedSecret,
368                "it is empty, and anything that can post to the ingress can pause a printer",
369            ));
370        }
371        Ok(Self(value.to_owned()))
372    }
373
374    /// Whether a post carried this secret.
375    ///
376    /// Compared over the whole of both values with the two lengths mixed in,
377    /// rather than by returning at the first difference or at a length
378    /// mismatch, so that how long this takes says nothing about how much of the
379    /// secret a caller guessed.
380    #[must_use]
381    pub fn matches(&self, offered: Option<&str>) -> bool {
382        let Some(offered) = offered else {
383            return false;
384        };
385        let expected = self.0.as_bytes();
386        let mut difference = expected.len() ^ offered.len();
387        for (index, byte) in offered.bytes().enumerate() {
388            let against = expected[index % expected.len().max(1)];
389            difference |= usize::from(byte ^ against);
390        }
391        difference == 0
392    }
393}
394
395impl core::fmt::Display for SharedSecret {
396    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
397        formatter.write_str(REDACTED)
398    }
399}
400
401impl core::fmt::Debug for SharedSecret {
402    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
403        write!(formatter, "SharedSecret({REDACTED})")
404    }
405}
406
407/// One running server's validated configuration.
408///
409/// Every value here is one no later step has to re-examine, and where a
410/// validated type for one already exists it is that type rather than the text
411/// it was written as: the `OctoPrint` instance is the adapter's own
412/// configuration, which redacts the key it carries; the harness and the model
413/// are the supervisor adapter's own names; and the ingress secret is a value
414/// neither rendering of which shows.
415#[derive(Debug, Clone, PartialEq)]
416pub struct ServerConfig {
417    /// Where the store, the images and the sessions live.
418    pub state_dir: PathBuf,
419    /// The address the API and the ingress are served on.
420    pub listen: SocketAddr,
421    /// Everything the printer adapter needs to reach the instance.
422    pub octoprint: OctoPrintConfig,
423    /// The operator's safety envelope.
424    pub safety: SafetyEnvelope,
425    /// The harness identity turns run on.
426    pub harness: HarnessIdentity,
427    /// The model turns are pinned to, when one is pinned.
428    pub model: Option<ModelName>,
429    /// The skill to send as every turn's system prompt, when the operator
430    /// supplied one.
431    pub skill_path: Option<PathBuf>,
432    /// The prompt template one turn fills, when the operator supplied one.
433    pub prompt_template_path: Option<PathBuf>,
434    /// How long the ingress may take to answer.
435    pub ingress_answer_bound: core::time::Duration,
436    /// The shared secret every post to the ingress must carry.
437    pub ingress_shared_secret: SharedSecret,
438}
439
440impl ServerConfig {
441    /// Read and validate the one configuration file this program takes.
442    ///
443    /// # Errors
444    ///
445    /// Returns [`ConfigError::Unreadable`] when the file is not there,
446    /// [`ConfigError::Unparsable`] when it is not this program's configuration,
447    /// and [`ConfigError::Field`] naming the one field whose value cannot be
448    /// accepted. The two values only the machine can rule on — the `OctoPrint`
449    /// address and key — are ruled on by [`crate::Server::start`], which is
450    /// where a printer exists to ask.
451    pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
452        let path = path.as_ref();
453        let text = std::fs::read_to_string(path).map_err(|error| ConfigError::Unreadable {
454            path: path.to_path_buf(),
455            detail: error.to_string(),
456        })?;
457        Self::parse(&text, path)
458    }
459
460    /// The same, over a document already read.
461    ///
462    /// # Errors
463    ///
464    /// The same as [`ServerConfig::load`], less the unreadable file.
465    pub fn parse(text: &str, path: &Path) -> Result<Self, ConfigError> {
466        let file: ConfigFile = toml::from_str(text).map_err(|error| ConfigError::Unparsable {
467            path: path.to_path_buf(),
468            detail: error.to_string(),
469        })?;
470        Self::validate(file)
471    }
472
473    /// Rule on every value the document carries.
474    ///
475    /// Absence is ruled on here rather than by the parser, because a parser's
476    /// own "missing field" says which key it wanted and not which field of this
477    /// program that is. Every refusal below names the dotted key an operator
478    /// would edit.
479    fn validate(file: ConfigFile) -> Result<Self, ConfigError> {
480        let state_dir =
481            state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?;
482        let listen = listen_address(&required(ConfigField::Listen, file.listen)?)?;
483        let octoprint = octoprint(&file.octoprint)?;
484        let safety = required(ConfigField::SafetyEnvelope, file.safety)?;
485        check_envelope(&safety)?;
486        let harness = HarnessIdentity::new(&named(ConfigField::Harness, file.supervisor.harness)?)
487            .map_err(|error| ConfigError::about(ConfigField::Harness, error.to_string()))?;
488        let model = match file.supervisor.model {
489            None => None,
490            Some(name) => Some(
491                ModelName::new(&named(ConfigField::Model, Some(name))?)
492                    .map_err(|error| ConfigError::about(ConfigField::Model, error.to_string()))?,
493            ),
494        };
495        let skill_path = readable(
496            ConfigField::SkillPath,
497            file.supervisor.skill_path.as_deref(),
498        )?;
499        let prompt_template_path = readable(
500            ConfigField::PromptTemplatePath,
501            file.supervisor.prompt_template_path.as_deref(),
502        )?;
503        let ingress_answer_bound = answer_bound(file.ingress.answer_bound_ms)?;
504        let ingress_shared_secret = SharedSecret::new(&required(
505            ConfigField::IngressSharedSecret,
506            file.ingress.shared_secret,
507        )?)?;
508        Ok(Self {
509            state_dir,
510            listen,
511            octoprint,
512            safety,
513            harness,
514            model,
515            skill_path,
516            prompt_template_path,
517            ingress_answer_bound,
518            ingress_shared_secret,
519        })
520    }
521
522    /// Where this server materializes the agent's committed assets.
523    #[must_use]
524    pub fn assets_dir(&self) -> PathBuf {
525        self.state_dir.join(ASSETS_DIRECTORY)
526    }
527}
528
529/// One field the file has to carry, refused by its own key when it does not.
530fn required<T>(field: ConfigField, value: Option<T>) -> Result<T, ConfigError> {
531    value.ok_or_else(|| ConfigError::about(field, "the configuration file carries no value for it"))
532}
533
534/// One field that has to carry a name rather than nothing at all.
535fn named(field: ConfigField, value: Option<String>) -> Result<String, ConfigError> {
536    let value = required(field, value)?;
537    if value.trim().is_empty() {
538        return Err(ConfigError::about(
539            field,
540            "it is empty, and an empty value names nothing",
541        ));
542    }
543    Ok(value.trim().to_owned())
544}
545
546/// The state directory, created where it is not there.
547fn state_directory(named: &Path) -> Result<PathBuf, ConfigError> {
548    if named.as_os_str().is_empty() {
549        return Err(ConfigError::about(
550            ConfigField::StateDir,
551            "it names no directory, and this server's whole state lives in one",
552        ));
553    }
554    std::fs::create_dir_all(named).map_err(|error| {
555        ConfigError::about(
556            ConfigField::StateDir,
557            format!("{} cannot be created: {error}", named.display()),
558        )
559    })?;
560    named.canonicalize().map_err(|error| {
561        ConfigError::about(
562            ConfigField::StateDir,
563            format!("{} cannot be resolved: {error}", named.display()),
564        )
565    })
566}
567
568/// The address to serve on, as an address rather than as text.
569fn listen_address(named: &str) -> Result<SocketAddr, ConfigError> {
570    named.trim().parse().map_err(|error| {
571        ConfigError::about(
572            ConfigField::Listen,
573            format!("{named:?} is no address to listen on: {error}"),
574        )
575    })
576}
577
578/// Everything the printer adapter needs to reach the instance, refused by the
579/// field whose value it could not take.
580fn octoprint(section: &OctoprintSection) -> Result<OctoPrintConfig, ConfigError> {
581    let fan = fan_support(&section.fan)?;
582    let url = named(ConfigField::OctoprintUrl, section.url.clone())?;
583    let key = named(ConfigField::OctoprintApiKey, section.api_key.clone())?;
584    OctoPrintConfig::new(&url, key)
585        .map(|configured| configured.with_fan(fan))
586        .map_err(|error| {
587            let field = match error {
588                printobserver_octoprint::ConfigError::EmptyApiKey => ConfigField::OctoprintApiKey,
589                _ => ConfigField::OctoprintUrl,
590            };
591            ConfigError::about(field, error.to_string())
592        })
593}
594
595/// The fan setting one word of the vocabulary names.
596fn fan_support(named: &str) -> Result<FanSupport, ConfigError> {
597    FAN_VOCABULARY
598        .iter()
599        .find(|(spelling, _)| *spelling == named.trim())
600        .map(|(_, support)| *support)
601        .ok_or_else(|| {
602            let vocabulary: Vec<&str> = FAN_VOCABULARY.iter().map(|(word, _)| *word).collect();
603            ConfigError::about(
604                ConfigField::OctoprintFan,
605                format!("{named:?} is not one of {}", vocabulary.join(" or ")),
606            )
607        })
608}
609
610/// The envelope, refused when a range it declares admits nothing.
611fn check_envelope(envelope: &SafetyEnvelope) -> Result<(), ConfigError> {
612    if envelope.allowed.is_empty() {
613        return Err(ConfigError::about(
614            ConfigField::SafetyEnvelope,
615            "it allows no adjustable at all, so no adjustment could ever be accepted",
616        ));
617    }
618    for (adjustable, range) in &envelope.allowed {
619        if !range.min.is_finite() || !range.max.is_finite() || range.min > range.max {
620            return Err(ConfigError::about(
621                ConfigField::SafetyEnvelope,
622                format!(
623                    "the range allowed for {adjustable} runs from {} to {}, which admits \
624                     no value",
625                    range.min, range.max
626                ),
627            ));
628        }
629    }
630    if envelope.agent_min_interval_s < 0 {
631        return Err(ConfigError::about(
632            ConfigField::SafetyEnvelope,
633            format!(
634                "the agent's minimum interval is {}s, and an interval is a count of seconds",
635                envelope.agent_min_interval_s
636            ),
637        ));
638    }
639    Ok(())
640}
641
642/// One optional path, read where it was named so that a path naming nothing is
643/// refused here rather than hours later.
644fn readable(field: ConfigField, named: Option<&Path>) -> Result<Option<PathBuf>, ConfigError> {
645    let Some(path) = named else {
646        return Ok(None);
647    };
648    std::fs::read_to_string(path)
649        .map(|_| Some(path.to_path_buf()))
650        .map_err(|error| {
651            ConfigError::about(field, format!("{} cannot be read: {error}", path.display()))
652        })
653}
654
655/// The answer bound, refused when it is not one this program admits.
656fn answer_bound(milliseconds: u64) -> Result<core::time::Duration, ConfigError> {
657    if milliseconds == 0 {
658        return Err(ConfigError::about(
659            ConfigField::IngressAnswerBoundMs,
660            "a bound of zero is an ingress that has run out of time before it starts",
661        ));
662    }
663    if milliseconds >= OBICO_POSTING_TIMEOUT_MS {
664        return Err(ConfigError::about(
665            ConfigField::IngressAnswerBoundMs,
666            format!(
667                "{milliseconds}ms is not below the {OBICO_POSTING_TIMEOUT_MS}ms Obico posts \
668                 under, so an alert answered at that bound is one Obico has already \
669                 abandoned — and its posting does not retry"
670            ),
671        ));
672    }
673    Ok(core::time::Duration::from_millis(milliseconds))
674}