1use 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
42pub const DEFAULT_INGRESS_ANSWER_BOUND_MS: u64 = 1_000;
49
50pub const OBICO_POSTING_TIMEOUT_MS: u64 = 5_000;
59
60pub const ASSETS_DIRECTORY: &str = "assets";
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
70pub enum ConfigField {
71 StateDir,
73 Listen,
75 OctoprintUrl,
77 OctoprintApiKey,
79 OctoprintFan,
81 SafetyEnvelope,
83 Harness,
85 Model,
87 SkillPath,
89 PromptTemplatePath,
91 IngressAnswerBoundMs,
93 IngressSharedSecret,
95}
96
97impl ConfigField {
98 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 #[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#[derive(Debug, Clone, PartialEq, Eq)]
145pub enum ConfigError {
146 Unreadable {
148 path: PathBuf,
150 detail: String,
152 },
153 Unparsable {
155 path: PathBuf,
157 detail: String,
159 },
160 Field {
162 field: ConfigField,
164 detail: String,
166 },
167}
168
169impl ConfigError {
170 #[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 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#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
223 pub url: Option<String>,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
226 pub api_key: Option<String>,
227 #[serde(default = "commandable")]
229 pub fan: String,
230}
231
232pub const FAN_VOCABULARY: [(&str, FanSupport); 2] = [
235 ("commandable", FanSupport::Commandable),
236 ("absent", FanSupport::Absent),
237];
238
239fn 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#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
266 pub harness: Option<String>,
267 #[serde(default, skip_serializing_if = "Option::is_none")]
269 pub model: Option<String>,
270 #[serde(default, skip_serializing_if = "Option::is_none")]
273 pub skill_path: Option<PathBuf>,
274 #[serde(default, skip_serializing_if = "Option::is_none")]
277 pub prompt_template_path: Option<PathBuf>,
278}
279
280#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
291 pub shared_secret: Option<String>,
292 #[serde(default = "default_answer_bound_ms")]
294 pub answer_bound_ms: u64,
295}
296
297const 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#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
326 pub state_dir: Option<PathBuf>,
327 #[serde(default, skip_serializing_if = "Option::is_none")]
329 pub listen: Option<String>,
330 #[serde(default)]
332 pub octoprint: OctoprintSection,
333 #[serde(default, skip_serializing_if = "Option::is_none")]
335 pub safety: Option<SafetyEnvelope>,
336 #[serde(default)]
338 pub supervisor: SupervisorSection,
339 #[serde(default)]
341 pub ingress: IngressSection,
342}
343
344#[derive(Clone, PartialEq, Eq)]
351pub struct SharedSecret(String);
352
353pub const REDACTED: &str = "<redacted>";
355
356impl SharedSecret {
357 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 #[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#[derive(Debug, Clone, PartialEq)]
416pub struct ServerConfig {
417 pub state_dir: PathBuf,
419 pub listen: SocketAddr,
421 pub octoprint: OctoPrintConfig,
423 pub safety: SafetyEnvelope,
425 pub harness: HarnessIdentity,
427 pub model: Option<ModelName>,
429 pub skill_path: Option<PathBuf>,
432 pub prompt_template_path: Option<PathBuf>,
434 pub ingress_answer_bound: core::time::Duration,
436 pub ingress_shared_secret: SharedSecret,
438}
439
440impl ServerConfig {
441 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 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 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 #[must_use]
524 pub fn assets_dir(&self) -> PathBuf {
525 self.state_dir.join(ASSETS_DIRECTORY)
526 }
527}
528
529fn 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
534fn 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
546fn 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
568fn 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
578fn octoprint(section: &OctoprintSection) -> Result<OctoPrintConfig, ConfigError> {
581 let fan = fan_support(§ion.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
595fn 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
610fn 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
642fn 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
655fn 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}