1use core::num::NonZeroU64;
136use std::net::SocketAddr;
137use std::path::{Path, PathBuf};
138
139use printobserver_core::{
140 ActionKind, ActorClass, AwayFromBed, DEFAULT_CLEARANCE_MARGIN_MM, DEFAULT_MAX_LIFT_MM,
141 PreflightMode, RecoveryActionKind, RecoveryConfig, RecoveryGrants, SafetyEnvelope, SheetTable,
142 SpoolPolicy,
143};
144use printobserver_obico::{
145 AccessToken, BlankFrameBound, MAX_BLANK_FRAME_MAX_STDDEV, MIN_BLANK_FRAME_MAX_STDDEV, ObicoApi,
146 ObicoPrinterId,
147};
148use printobserver_octoprint::{FanSupport, OctoPrintConfig};
149use printobserver_oneharness::{HarnessIdentity, ModelName};
150use printobserver_types::schemars::JsonSchema;
151use printobserver_types::serde::{Deserialize, Serialize};
152use printobserver_vision_api::WebAddress;
153
154pub const DEFAULT_INGRESS_ANSWER_BOUND_MS: u64 = 1_000;
161
162pub const DEFAULT_OBSERVATION_INTERVAL_S: u64 =
165 printobserver_core::DEFAULT_OBSERVATION_INTERVAL.as_secs();
166
167pub const DEFAULT_PRINTER_POLL_S: u64 = printobserver_core::DEFAULT_PRINTER_POLL.as_secs();
170
171pub const PRINTER_POLL_RANGE_S: (u64, u64) = (5, 300);
173
174pub const DEFAULT_UNATTENDED_WINDOW_S: u64 =
177 printobserver_core::DEFAULT_UNATTENDED_WINDOW.as_secs();
178
179pub const UNATTENDED_WINDOW_RANGE_S: (u64, u64) = (60, 86_400);
181
182pub const DEFAULT_CHECK_TURN_TIMEOUT_S: u64 = 120;
187
188pub const CHECK_TURN_TIMEOUT_RANGE_S: (u64, u64) = (1, 900);
191
192pub const OBICO_POSTING_TIMEOUT_MS: u64 = 5_000;
201
202pub const ASSETS_DIRECTORY: &str = "assets";
207
208pub const SKILL_INSTALL: &str = "the skill is installed with `gh skill install \
215 nickderobertis/printobserver printobserver --dir <dir>`, and \
216 `supervisor.skill_path` names the installed `SKILL.md`, \
217 `<dir>/printobserver/SKILL.md`";
218
219#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
225pub enum ConfigField {
226 StateDir,
228 Listen,
230 OctoprintUrl,
232 OctoprintApiKey,
234 OctoprintFan,
236 SafetyEnvelope,
238 Harness,
240 Model,
242 SkillPath,
244 PromptTemplatePath,
246 ObservationIntervalS,
248 PrinterPollS,
250 UnattendedWindowS,
253 AutoCompactTokens,
256 IdleCompactTokens,
259 CheckTurnTimeoutS,
261 IngressAnswerBoundMs,
263 IngressSharedSecret,
265 ApiCredential,
268 ApiCredentialVerifier,
270 CameraSnapshotUrl,
273 CameraCalibration,
275 ObicoUrl,
277 ObicoAccessToken,
279 ObicoMlApiUrl,
281 ObicoPrinterId,
283 VisionBlankFrameMaxStddev,
285 SpoolsPreflight,
287 SpoolsBufferPercent,
289 SpoolsBufferMinG,
291 SpoolsAnalysisWaitSeconds,
293 SheetsAllowed,
295 RecoveryAwayFromBed,
297 RecoveryMaxZMm,
299 RecoveryMaxLiftMm,
301 RecoveryClearanceMarginMm,
303 RecoveryParkXy,
305 RecoveryZHomeXy,
307 RecoveryZHomeSweepsBed,
309 PolicyRecoveryOperator,
311 PolicyRecoveryAgent,
313 PolicyRecoveryAsserting,
315}
316
317impl ConfigField {
318 pub const ALL: [Self; 42] = [
320 Self::StateDir,
321 Self::Listen,
322 Self::OctoprintUrl,
323 Self::OctoprintApiKey,
324 Self::OctoprintFan,
325 Self::SafetyEnvelope,
326 Self::Harness,
327 Self::Model,
328 Self::SkillPath,
329 Self::PromptTemplatePath,
330 Self::ObservationIntervalS,
331 Self::PrinterPollS,
332 Self::UnattendedWindowS,
333 Self::AutoCompactTokens,
334 Self::IdleCompactTokens,
335 Self::CheckTurnTimeoutS,
336 Self::IngressAnswerBoundMs,
337 Self::IngressSharedSecret,
338 Self::ApiCredential,
339 Self::ApiCredentialVerifier,
340 Self::CameraSnapshotUrl,
341 Self::CameraCalibration,
342 Self::ObicoUrl,
343 Self::ObicoAccessToken,
344 Self::ObicoMlApiUrl,
345 Self::ObicoPrinterId,
346 Self::VisionBlankFrameMaxStddev,
347 Self::SpoolsPreflight,
348 Self::SpoolsBufferPercent,
349 Self::SpoolsBufferMinG,
350 Self::SpoolsAnalysisWaitSeconds,
351 Self::SheetsAllowed,
352 Self::RecoveryAwayFromBed,
353 Self::RecoveryMaxZMm,
354 Self::RecoveryMaxLiftMm,
355 Self::RecoveryClearanceMarginMm,
356 Self::RecoveryParkXy,
357 Self::RecoveryZHomeXy,
358 Self::RecoveryZHomeSweepsBed,
359 Self::PolicyRecoveryOperator,
360 Self::PolicyRecoveryAgent,
361 Self::PolicyRecoveryAsserting,
362 ];
363
364 #[must_use]
366 pub const fn key(self) -> &'static str {
367 match self {
368 Self::StateDir => "state_dir",
369 Self::Listen => "listen",
370 Self::OctoprintUrl => "octoprint.url",
371 Self::OctoprintApiKey => "octoprint.api_key",
372 Self::OctoprintFan => "octoprint.fan",
373 Self::SafetyEnvelope => "safety",
374 Self::Harness => "supervisor.harness",
375 Self::Model => "supervisor.model",
376 Self::SkillPath => "supervisor.skill_path",
377 Self::PromptTemplatePath => "supervisor.prompt_template_path",
378 Self::ObservationIntervalS => "supervisor.observation_interval_s",
379 Self::PrinterPollS => "supervisor.printer_poll_s",
380 Self::UnattendedWindowS => "supervisor.unattended_window_s",
381 Self::AutoCompactTokens => "supervisor.auto_compact_tokens",
382 Self::IdleCompactTokens => "supervisor.idle_compact_tokens",
383 Self::CheckTurnTimeoutS => "supervisor.check_turn_timeout_s",
384 Self::IngressAnswerBoundMs => "ingress.answer_bound_ms",
385 Self::IngressSharedSecret => "ingress.shared_secret",
386 Self::ApiCredential => "api.credential",
387 Self::ApiCredentialVerifier => "api.credential_verifier",
388 Self::CameraSnapshotUrl => "camera.snapshot_url",
389 Self::CameraCalibration => "camera.calibration",
390 Self::ObicoUrl => "obico.url",
391 Self::ObicoAccessToken => "obico.access_token",
392 Self::ObicoMlApiUrl => "obico.ml_api_url",
393 Self::ObicoPrinterId => "obico.printer_id",
394 Self::VisionBlankFrameMaxStddev => "vision.blank_frame_max_stddev",
395 Self::SpoolsPreflight => "spools.preflight",
396 Self::SpoolsBufferPercent => "spools.buffer_percent",
397 Self::SpoolsBufferMinG => "spools.buffer_min_g",
398 Self::SpoolsAnalysisWaitSeconds => "spools.analysis_wait_seconds",
399 Self::SheetsAllowed => "sheets.allowed",
400 Self::RecoveryAwayFromBed => "recovery.away_from_bed",
401 Self::RecoveryMaxZMm => "recovery.max_z_mm",
402 Self::RecoveryMaxLiftMm => "recovery.max_lift_mm",
403 Self::RecoveryClearanceMarginMm => "recovery.clearance_margin_mm",
404 Self::RecoveryParkXy => "recovery.park_xy",
405 Self::RecoveryZHomeXy => "recovery.z_home_xy",
406 Self::RecoveryZHomeSweepsBed => "recovery.z_home_sweeps_bed",
407 Self::PolicyRecoveryOperator => "policy.recovery.operator",
408 Self::PolicyRecoveryAgent => "policy.recovery.agent",
409 Self::PolicyRecoveryAsserting => "policy.recovery.asserting",
410 }
411 }
412}
413
414impl core::fmt::Display for ConfigField {
415 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
416 formatter.write_str(self.key())
417 }
418}
419
420#[derive(Debug, Clone, PartialEq, Eq)]
425pub enum ConfigError {
426 Unreadable {
428 path: PathBuf,
430 detail: String,
432 },
433 Unparsable {
435 path: PathBuf,
437 detail: String,
439 },
440 Field {
442 field: ConfigField,
444 detail: String,
446 },
447}
448
449impl ConfigError {
450 #[must_use]
452 pub const fn field(&self) -> Option<ConfigField> {
453 match self {
454 Self::Field { field, .. } => Some(*field),
455 _ => None,
456 }
457 }
458
459 pub(crate) fn about(field: ConfigField, detail: impl Into<String>) -> Self {
461 Self::Field {
462 field,
463 detail: detail.into(),
464 }
465 }
466}
467
468impl core::fmt::Display for ConfigError {
469 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
470 match self {
471 Self::Unreadable { path, detail } => write!(
472 formatter,
473 "the configuration file {} could not be read: {detail}",
474 path.display()
475 ),
476 Self::Unparsable { path, detail } => write!(
477 formatter,
478 "the configuration file {} could not be read as this program's \
479 configuration: {detail}",
480 path.display()
481 ),
482 Self::Field { field, detail } => write!(
483 formatter,
484 "the configuration field `{field}` cannot be accepted: {detail}"
485 ),
486 }
487 }
488}
489
490impl core::error::Error for ConfigError {}
491
492#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
494#[serde(
495 crate = "printobserver_types::serde",
496 deny_unknown_fields,
497 rename_all = "snake_case"
498)]
499#[schemars(crate = "printobserver_types::schemars")]
500pub struct OctoprintSection {
501 #[serde(default, skip_serializing_if = "Option::is_none")]
503 pub url: Option<String>,
504 #[serde(default, skip_serializing_if = "Option::is_none")]
506 pub api_key: Option<String>,
507 #[serde(default = "commandable")]
509 pub fan: String,
510}
511
512pub const FAN_VOCABULARY: [(&str, FanSupport); 2] = [
515 ("commandable", FanSupport::Commandable),
516 ("absent", FanSupport::Absent),
517];
518
519fn commandable() -> String {
521 FAN_VOCABULARY[0].0.to_owned()
522}
523
524impl Default for OctoprintSection {
525 fn default() -> Self {
526 Self {
527 url: None,
528 api_key: None,
529 fan: commandable(),
530 }
531 }
532}
533
534#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
536#[serde(
537 crate = "printobserver_types::serde",
538 deny_unknown_fields,
539 rename_all = "snake_case"
540)]
541#[schemars(crate = "printobserver_types::schemars")]
542pub struct SupervisorSection {
543 #[serde(default, skip_serializing_if = "Option::is_none")]
545 pub harness: Option<String>,
546 #[serde(default, skip_serializing_if = "Option::is_none")]
548 pub model: Option<String>,
549 #[serde(default, skip_serializing_if = "Option::is_none")]
553 pub skill_path: Option<PathBuf>,
554 #[serde(default, skip_serializing_if = "Option::is_none")]
557 pub prompt_template_path: Option<PathBuf>,
558 #[serde(default = "default_observation_interval_s")]
561 pub observation_interval_s: u64,
562 #[serde(default = "default_printer_poll_s")]
565 pub printer_poll_s: u64,
566 #[serde(default = "default_unattended_window_s")]
570 pub unattended_window_s: u64,
571 #[serde(default, skip_serializing_if = "Option::is_none")]
574 pub auto_compact_tokens: Option<i64>,
575 #[serde(default, skip_serializing_if = "Option::is_none")]
578 pub idle_compact_tokens: Option<i64>,
579 #[serde(default = "default_check_turn_timeout_s")]
582 pub check_turn_timeout_s: u64,
583}
584
585const fn default_check_turn_timeout_s() -> u64 {
587 DEFAULT_CHECK_TURN_TIMEOUT_S
588}
589
590const fn default_printer_poll_s() -> u64 {
592 DEFAULT_PRINTER_POLL_S
593}
594
595const fn default_unattended_window_s() -> u64 {
597 DEFAULT_UNATTENDED_WINDOW_S
598}
599
600const fn default_observation_interval_s() -> u64 {
602 DEFAULT_OBSERVATION_INTERVAL_S
603}
604
605impl Default for SupervisorSection {
606 fn default() -> Self {
607 Self {
608 harness: None,
609 model: None,
610 skill_path: None,
611 prompt_template_path: None,
612 observation_interval_s: DEFAULT_OBSERVATION_INTERVAL_S,
613 printer_poll_s: DEFAULT_PRINTER_POLL_S,
614 unattended_window_s: DEFAULT_UNATTENDED_WINDOW_S,
615 auto_compact_tokens: None,
616 idle_compact_tokens: None,
617 check_turn_timeout_s: DEFAULT_CHECK_TURN_TIMEOUT_S,
618 }
619 }
620}
621
622#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
624#[serde(
625 crate = "printobserver_types::serde",
626 deny_unknown_fields,
627 rename_all = "snake_case"
628)]
629#[schemars(crate = "printobserver_types::schemars")]
630pub struct IngressSection {
631 #[serde(default, skip_serializing_if = "Option::is_none")]
633 pub shared_secret: Option<String>,
634 #[serde(default = "default_answer_bound_ms")]
636 pub answer_bound_ms: u64,
637}
638
639const fn default_answer_bound_ms() -> u64 {
641 DEFAULT_INGRESS_ANSWER_BOUND_MS
642}
643
644impl Default for IngressSection {
645 fn default() -> Self {
646 Self {
647 shared_secret: None,
648 answer_bound_ms: DEFAULT_INGRESS_ANSWER_BOUND_MS,
649 }
650 }
651}
652
653#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
655#[serde(
656 crate = "printobserver_types::serde",
657 deny_unknown_fields,
658 rename_all = "snake_case"
659)]
660#[schemars(crate = "printobserver_types::schemars")]
661pub struct ApiSection {
662 #[serde(default, skip_serializing_if = "Option::is_none")]
666 pub credential: Option<String>,
667 #[serde(default, skip_serializing_if = "Option::is_none")]
673 pub credential_verifier: Option<String>,
674}
675
676#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
678#[serde(
679 crate = "printobserver_types::serde",
680 deny_unknown_fields,
681 rename_all = "snake_case"
682)]
683#[schemars(crate = "printobserver_types::schemars")]
684pub struct CameraSection {
685 #[serde(default, skip_serializing_if = "Option::is_none")]
688 pub snapshot_url: Option<String>,
689 #[serde(default, skip_serializing_if = "Option::is_none")]
695 pub calibration: Option<PathBuf>,
696}
697
698#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
702#[serde(
703 crate = "printobserver_types::serde",
704 deny_unknown_fields,
705 rename_all = "snake_case"
706)]
707#[schemars(crate = "printobserver_types::schemars")]
708pub struct ObicoSection {
709 #[serde(default, skip_serializing_if = "Option::is_none")]
712 pub url: Option<String>,
713 #[serde(default, skip_serializing_if = "Option::is_none")]
717 pub access_token: Option<String>,
718 #[serde(default, skip_serializing_if = "Option::is_none")]
723 pub ml_api_url: Option<String>,
724 #[serde(default, skip_serializing_if = "Option::is_none")]
730 pub printer_id: Option<i64>,
731}
732
733#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
735#[serde(
736 crate = "printobserver_types::serde",
737 deny_unknown_fields,
738 rename_all = "snake_case"
739)]
740#[schemars(crate = "printobserver_types::schemars")]
741pub struct VisionSection {
742 #[serde(default, skip_serializing_if = "Option::is_none")]
745 pub blank_frame_max_stddev: Option<f64>,
746}
747
748impl core::fmt::Debug for ObicoSection {
749 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
750 formatter
751 .debug_struct("ObicoSection")
752 .field("url", &self.url)
753 .field(
754 "access_token",
755 &self.access_token.as_ref().map(|_| REDACTED),
756 )
757 .field("ml_api_url", &self.ml_api_url)
758 .field("printer_id", &self.printer_id)
759 .finish()
760 }
761}
762
763#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
770#[serde(
771 crate = "printobserver_types::serde",
772 deny_unknown_fields,
773 rename_all = "snake_case"
774)]
775#[schemars(crate = "printobserver_types::schemars")]
776pub struct SpoolsSection {
777 #[serde(default, skip_serializing_if = "Option::is_none")]
780 pub preflight: Option<String>,
781 #[serde(default, skip_serializing_if = "Option::is_none")]
783 pub buffer_percent: Option<f64>,
784 #[serde(default, skip_serializing_if = "Option::is_none")]
786 pub buffer_min_g: Option<f64>,
787 #[serde(default, skip_serializing_if = "Option::is_none")]
790 pub analysis_wait_seconds: Option<i64>,
791}
792
793#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
798#[serde(
799 crate = "printobserver_types::serde",
800 deny_unknown_fields,
801 rename_all = "snake_case"
802)]
803#[schemars(crate = "printobserver_types::schemars")]
804pub struct SheetsSection {
805 #[serde(default, skip_serializing_if = "Option::is_none")]
809 pub allowed: Option<std::collections::BTreeMap<String, Vec<String>>>,
810}
811
812#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
819#[serde(
820 crate = "printobserver_types::serde",
821 deny_unknown_fields,
822 rename_all = "snake_case"
823)]
824#[schemars(crate = "printobserver_types::schemars")]
825pub struct RecoverySection {
826 #[serde(default, skip_serializing_if = "Option::is_none")]
829 pub away_from_bed: Option<String>,
831 #[serde(default, skip_serializing_if = "Option::is_none")]
833 pub max_z_mm: Option<f64>,
834 #[serde(default, skip_serializing_if = "Option::is_none")]
837 pub max_lift_mm: Option<f64>,
838 #[serde(default, skip_serializing_if = "Option::is_none")]
841 pub clearance_margin_mm: Option<f64>,
842 #[serde(default, skip_serializing_if = "Option::is_none")]
844 pub park_xy: Option<Vec<f64>>,
845 #[serde(default, skip_serializing_if = "Option::is_none")]
847 pub z_home_xy: Option<Vec<f64>>,
848 #[serde(default, skip_serializing_if = "Option::is_none")]
851 pub z_home_sweeps_bed: Option<bool>,
852}
853
854#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
858#[serde(
859 crate = "printobserver_types::serde",
860 deny_unknown_fields,
861 rename_all = "snake_case"
862)]
863#[schemars(crate = "printobserver_types::schemars")]
864pub struct RecoveryPolicySection {
865 #[serde(default, skip_serializing_if = "Option::is_none")]
867 pub operator: Option<Vec<String>>,
869 #[serde(default, skip_serializing_if = "Option::is_none")]
872 pub agent: Option<Vec<String>>,
874 #[serde(default, skip_serializing_if = "Option::is_none")]
877 pub asserting: Option<Vec<String>>,
879}
880
881#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
883#[serde(
884 crate = "printobserver_types::serde",
885 deny_unknown_fields,
886 rename_all = "snake_case"
887)]
888#[schemars(crate = "printobserver_types::schemars")]
889pub struct PolicySection {
890 #[serde(default)]
892 pub recovery: RecoveryPolicySection,
893}
894
895#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
901#[serde(
902 crate = "printobserver_types::serde",
903 deny_unknown_fields,
904 rename_all = "snake_case"
905)]
906#[schemars(crate = "printobserver_types::schemars")]
907pub struct ConfigFile {
908 #[serde(default, skip_serializing_if = "Option::is_none")]
910 pub state_dir: Option<PathBuf>,
911 #[serde(default, skip_serializing_if = "Option::is_none")]
913 pub listen: Option<String>,
914 #[serde(default)]
916 pub octoprint: OctoprintSection,
917 #[serde(default, skip_serializing_if = "Option::is_none")]
919 pub safety: Option<SafetyEnvelope>,
920 #[serde(default)]
922 pub supervisor: SupervisorSection,
923 #[serde(default)]
925 pub ingress: IngressSection,
926 #[serde(default)]
928 pub api: ApiSection,
929 #[serde(default)]
931 pub camera: CameraSection,
932 #[serde(default)]
934 pub obico: ObicoSection,
935 #[serde(default)]
937 pub vision: VisionSection,
938 #[serde(default)]
940 pub spools: SpoolsSection,
941 #[serde(default)]
943 pub sheets: SheetsSection,
944 #[serde(default)]
946 pub recovery: RecoverySection,
947 #[serde(default)]
949 pub policy: PolicySection,
950}
951
952#[derive(Clone, PartialEq, Eq)]
959pub struct SharedSecret(String);
960
961pub const REDACTED: &str = "<redacted>";
963
964impl SharedSecret {
965 pub fn new(value: &str) -> Result<Self, ConfigError> {
973 if value.trim().is_empty() {
974 return Err(ConfigError::about(
975 ConfigField::IngressSharedSecret,
976 "it is empty, and anything that can post to the ingress can pause a printer",
977 ));
978 }
979 Ok(Self(value.to_owned()))
980 }
981
982 #[must_use]
989 pub fn matches(&self, offered: Option<&str>) -> bool {
990 let Some(offered) = offered else {
991 return false;
992 };
993 let expected = self.0.as_bytes();
994 let mut difference = expected.len() ^ offered.len();
995 for (index, byte) in offered.bytes().enumerate() {
996 let against = expected[index % expected.len().max(1)];
997 difference |= usize::from(byte ^ against);
998 }
999 difference == 0
1000 }
1001}
1002
1003impl core::fmt::Display for SharedSecret {
1004 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1005 formatter.write_str(REDACTED)
1006 }
1007}
1008
1009impl core::fmt::Debug for SharedSecret {
1010 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1011 write!(formatter, "SharedSecret({REDACTED})")
1012 }
1013}
1014
1015pub const GENERATED_CREDENTIAL_BYTES: usize = 32;
1017
1018#[derive(Clone)]
1028pub struct ApiCredential(String);
1029
1030impl ApiCredential {
1031 pub fn new(value: &str) -> Result<Self, &'static str> {
1040 if value.trim().is_empty() {
1041 return Err(
1042 "it is empty, and anything that can reach this server's API can command a printer",
1043 );
1044 }
1045 if !value.bytes().all(|byte| (b' '..=b'~').contains(&byte)) {
1046 return Err(
1047 "it carries a control character or a character outside printable ASCII, which \
1048 no `Authorization` header carries intact",
1049 );
1050 }
1051 if value.starts_with(' ') || value.ends_with(' ') {
1052 return Err(
1053 "it begins or ends with a space, which an `Authorization` header does not carry",
1054 );
1055 }
1056 Ok(Self(value.to_owned()))
1058 }
1059
1060 pub fn generate() -> Result<Self, getrandom::Error> {
1070 use base64::Engine as _;
1071
1072 let mut drawn = [0_u8; GENERATED_CREDENTIAL_BYTES];
1073 getrandom::fill(&mut drawn)?;
1074 Ok(Self(
1075 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(drawn),
1076 ))
1077 }
1078
1079 #[must_use]
1085 pub fn admits(&self, presented: &[u8]) -> bool {
1086 use subtle::ConstantTimeEq as _;
1087
1088 let expected = self.0.as_bytes();
1089 expected.len() == presented.len() && bool::from(expected.ct_eq(presented))
1090 }
1091
1092 #[must_use]
1095 pub fn written(&self) -> &str {
1096 &self.0
1097 }
1098
1099 #[must_use]
1101 pub fn verifier(&self) -> CredentialVerifier {
1102 CredentialVerifier::of(&self.0)
1103 }
1104}
1105
1106impl PartialEq for ApiCredential {
1107 fn eq(&self, other: &Self) -> bool {
1108 self.admits(other.0.as_bytes())
1109 }
1110}
1111
1112impl Eq for ApiCredential {}
1113
1114impl core::fmt::Display for ApiCredential {
1115 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1116 formatter.write_str(REDACTED)
1117 }
1118}
1119
1120impl core::fmt::Debug for ApiCredential {
1121 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1122 write!(formatter, "ApiCredential({REDACTED})")
1123 }
1124}
1125
1126pub const VERIFIER_PREFIX: &str = "sha256:";
1128
1129const VERIFIER_DIGITS: usize = 64;
1131
1132#[derive(Clone, PartialEq, Eq)]
1143pub struct CredentialVerifier([u8; 32]);
1144
1145impl CredentialVerifier {
1146 #[must_use]
1148 pub fn of(credential: &str) -> Self {
1149 use sha2::Digest as _;
1150
1151 Self(sha2::Sha256::digest(credential.as_bytes()).into())
1152 }
1153
1154 pub fn parse(text: &str) -> Result<Self, &'static str> {
1161 const SHAPE: &str = "it is not `sha256:` followed by the 64 lowercase hexadecimal digits of a SHA-256 digest, which is what `printobserver credential issue` and `printobserver credential verifier` print";
1162 let digits = text.strip_prefix(VERIFIER_PREFIX).ok_or(SHAPE)?;
1163 if digits.len() != VERIFIER_DIGITS
1164 || !digits
1165 .bytes()
1166 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1167 {
1168 return Err(SHAPE);
1169 }
1170 let mut digest = [0_u8; 32];
1171 for (index, pair) in digits.as_bytes().chunks(2).enumerate() {
1172 let high = hex_value(pair[0]);
1173 let low = hex_value(pair[1]);
1174 digest[index] = (high << 4) | low;
1175 }
1176 Ok(Self(digest))
1177 }
1178
1179 #[must_use]
1185 pub fn admits(&self, presented: &[u8]) -> bool {
1186 use sha2::Digest as _;
1187 use subtle::ConstantTimeEq as _;
1188
1189 let offered: [u8; 32] = sha2::Sha256::digest(presented).into();
1190 bool::from(self.0.ct_eq(&offered))
1191 }
1192}
1193
1194const fn hex_value(digit: u8) -> u8 {
1196 if digit.is_ascii_digit() {
1197 digit - b'0'
1198 } else {
1199 digit - b'a' + 10
1200 }
1201}
1202
1203impl core::fmt::Display for CredentialVerifier {
1204 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1205 formatter.write_str(VERIFIER_PREFIX)?;
1206 for byte in self.0 {
1207 write!(formatter, "{byte:02x}")?;
1208 }
1209 Ok(())
1210 }
1211}
1212
1213impl core::fmt::Debug for CredentialVerifier {
1214 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1215 write!(formatter, "CredentialVerifier({self})")
1216 }
1217}
1218
1219#[derive(Debug, Clone, PartialEq)]
1228pub struct ServerConfig {
1229 pub state_dir: PathBuf,
1231 pub listen: SocketAddr,
1233 pub octoprint: OctoPrintConfig,
1235 pub safety: SafetyEnvelope,
1237 pub harness: HarnessIdentity,
1239 pub model: Option<ModelName>,
1241 pub skill_path: PathBuf,
1245 pub prompt_template_path: Option<PathBuf>,
1247 pub observation_interval: core::time::Duration,
1249 pub printer_poll: core::time::Duration,
1251 pub unattended_window: core::time::Duration,
1254 pub auto_compact_tokens: Option<NonZeroU64>,
1257 pub idle_compact_tokens: Option<NonZeroU64>,
1260 pub check_turn_timeout: core::time::Duration,
1262 pub blank_frame_max_stddev: BlankFrameBound,
1264 pub obico_ml_api_url: Option<WebAddress>,
1267 pub obico_printer_id: Option<ObicoPrinterId>,
1270 pub ingress_answer_bound: core::time::Duration,
1272 pub ingress_shared_secret: SharedSecret,
1274 pub api_credential: Option<ApiCredential>,
1278 pub api_credential_verifier: Option<CredentialVerifier>,
1282 pub camera_snapshot_url: Option<WebAddress>,
1284 pub camera_calibration: Option<std::sync::Arc<printobserver_panels::CameraCalibration>>,
1287 pub obico_api: Option<ObicoApi>,
1289 pub spools: SpoolPolicy,
1291 pub sheets: SheetTable,
1293 pub recovery: Option<RecoveryConfig>,
1295 pub recovery_grants: RecoveryGrants,
1297}
1298
1299impl ServerConfig {
1300 pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
1311 let path = path.as_ref();
1312 Self::parse(&read(path)?, path)
1313 }
1314
1315 pub fn parse(text: &str, path: &Path) -> Result<Self, ConfigError> {
1321 let file: ConfigFile = toml::from_str(text).map_err(|error| ConfigError::Unparsable {
1322 path: path.to_path_buf(),
1323 detail: error.to_string(),
1324 })?;
1325 Self::validate(file)
1326 }
1327
1328 fn validate(file: ConfigFile) -> Result<Self, ConfigError> {
1335 let state_dir =
1336 state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?;
1337 let listen = listen_address(&required(ConfigField::Listen, file.listen)?)?;
1338 let octoprint = octoprint(&file.octoprint)?;
1339 let safety = required(ConfigField::SafetyEnvelope, file.safety)?;
1340 check_envelope(&safety)?;
1341 let harness = harness_identity(file.supervisor.harness)?;
1342 let model = match file.supervisor.model {
1343 None => None,
1344 Some(name) => Some(
1345 ModelName::new(&named(ConfigField::Model, Some(name))?)
1346 .map_err(|error| ConfigError::about(ConfigField::Model, error.to_string()))?,
1347 ),
1348 };
1349 let skill_path = skill(file.supervisor.skill_path.as_deref())?;
1350 let prompt_template_path = readable(
1351 ConfigField::PromptTemplatePath,
1352 file.supervisor.prompt_template_path.as_deref(),
1353 )?;
1354 let observation_interval = observation_interval(file.supervisor.observation_interval_s)?;
1355 let printer_poll = seconds_within(
1356 ConfigField::PrinterPollS,
1357 file.supervisor.printer_poll_s,
1358 PRINTER_POLL_RANGE_S,
1359 )?;
1360 let unattended_window = seconds_within(
1361 ConfigField::UnattendedWindowS,
1362 file.supervisor.unattended_window_s,
1363 UNATTENDED_WINDOW_RANGE_S,
1364 )?;
1365 let (auto_compact_tokens, idle_compact_tokens) = compaction(
1366 file.supervisor.auto_compact_tokens,
1367 file.supervisor.idle_compact_tokens,
1368 )?;
1369 let blank_frame_max_stddev = blank_frame_bound(file.vision.blank_frame_max_stddev)?;
1370 let (obico_ml_api_url, obico_printer_id) = detector_reads(&file.obico)?;
1371 let ingress_answer_bound = answer_bound(file.ingress.answer_bound_ms)?;
1372 let ingress_shared_secret = SharedSecret::new(&required(
1373 ConfigField::IngressSharedSecret,
1374 file.ingress.shared_secret,
1375 )?)?;
1376 let api_credential = file
1377 .api
1378 .credential
1379 .as_deref()
1380 .map(|value| {
1381 ApiCredential::new(value)
1382 .map_err(|why| ConfigError::about(ConfigField::ApiCredential, why))
1383 })
1384 .transpose()?;
1385 let api_credential_verifier = file
1386 .api
1387 .credential_verifier
1388 .as_deref()
1389 .map(|value| {
1390 CredentialVerifier::parse(value.trim())
1391 .map_err(|why| ConfigError::about(ConfigField::ApiCredentialVerifier, why))
1392 })
1393 .transpose()?;
1394 let (camera_snapshot_url, camera_calibration) = camera(file.camera)?;
1395 let obico_api = obico_api(file.obico)?;
1396 let spools = spool_policy(&file.spools)?;
1397 let sheets = match file.sheets.allowed {
1398 None => SheetTable::default(),
1399 Some(entries) => SheetTable::new(entries)
1400 .map_err(|why| ConfigError::about(ConfigField::SheetsAllowed, why))?,
1401 };
1402 let recovery = recovery_facts(&file.recovery)?;
1403 let recovery_grants = recovery_grants(&file.policy.recovery)?;
1404 Ok(Self {
1405 state_dir,
1406 listen,
1407 octoprint,
1408 safety,
1409 harness,
1410 model,
1411 skill_path,
1412 prompt_template_path,
1413 observation_interval,
1414 printer_poll,
1415 unattended_window,
1416 auto_compact_tokens,
1417 idle_compact_tokens,
1418 check_turn_timeout: check_turn_timeout(file.supervisor.check_turn_timeout_s)?,
1419 blank_frame_max_stddev,
1420 obico_ml_api_url,
1421 obico_printer_id,
1422 ingress_answer_bound,
1423 ingress_shared_secret,
1424 api_credential,
1425 api_credential_verifier,
1426 camera_snapshot_url,
1427 camera_calibration,
1428 obico_api,
1429 spools,
1430 sheets,
1431 recovery,
1432 recovery_grants,
1433 })
1434 }
1435
1436 #[must_use]
1440 pub fn assets_dir(&self) -> PathBuf {
1441 self.state_dir.join(ASSETS_DIRECTORY)
1442 }
1443}
1444
1445fn web_address(field: ConfigField, url: &str) -> Result<WebAddress, ConfigError> {
1448 WebAddress::new(url).map_err(|why| ConfigError::about(field, why))
1449}
1450
1451fn detector_reads(
1455 section: &ObicoSection,
1456) -> Result<(Option<WebAddress>, Option<ObicoPrinterId>), ConfigError> {
1457 let ml_api_url = section
1458 .ml_api_url
1459 .as_deref()
1460 .map(|url| web_address(ConfigField::ObicoMlApiUrl, url))
1461 .transpose()?;
1462 let printer_id = section
1463 .printer_id
1464 .map(|id| {
1465 ObicoPrinterId::new(id)
1466 .map_err(|why| ConfigError::about(ConfigField::ObicoPrinterId, why))
1467 })
1468 .transpose()?;
1469 Ok((ml_api_url, printer_id))
1470}
1471
1472fn obico_api(section: ObicoSection) -> Result<Option<ObicoApi>, ConfigError> {
1478 match (section.url, section.access_token) {
1479 (None, None) => Ok(None),
1480 (Some(_), None) => Err(ConfigError::about(
1481 ConfigField::ObicoAccessToken,
1482 "it is required when obico.url is given",
1483 )),
1484 (None, Some(_)) => Err(ConfigError::about(
1485 ConfigField::ObicoUrl,
1486 "it is required when obico.access_token is given",
1487 )),
1488 (Some(url), Some(access_token)) => {
1489 let url = web_address(ConfigField::ObicoUrl, &url)?;
1490 let access_token = AccessToken::new(&access_token)
1491 .map_err(|why| ConfigError::about(ConfigField::ObicoAccessToken, why))?;
1492 Ok(Some(ObicoApi::new(url, access_token)))
1493 }
1494 }
1495}
1496
1497#[derive(Debug, Clone, PartialEq, Eq)]
1505pub struct SignInConfig {
1506 pub state_dir: PathBuf,
1508 pub harness: HarnessIdentity,
1510}
1511
1512impl SignInConfig {
1513 pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
1523 let path = path.as_ref();
1524 let file: SignInFile =
1525 toml::from_str(&read(path)?).map_err(|error| ConfigError::Unparsable {
1526 path: path.to_path_buf(),
1527 detail: error.to_string(),
1528 })?;
1529 Ok(Self {
1530 state_dir: state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?,
1531 harness: harness_identity(file.supervisor.harness)?,
1532 })
1533 }
1534}
1535
1536#[derive(Deserialize)]
1541#[serde(crate = "printobserver_types::serde")]
1542struct SignInFile {
1543 #[serde(default)]
1545 state_dir: Option<PathBuf>,
1546 #[serde(default)]
1548 supervisor: SignInSupervisor,
1549}
1550
1551#[derive(Default, Deserialize)]
1553#[serde(crate = "printobserver_types::serde")]
1554struct SignInSupervisor {
1555 #[serde(default)]
1557 harness: Option<String>,
1558}
1559
1560fn read(path: &Path) -> Result<String, ConfigError> {
1562 std::fs::read_to_string(path).map_err(|error| ConfigError::Unreadable {
1563 path: path.to_path_buf(),
1564 detail: error.to_string(),
1565 })
1566}
1567
1568fn harness_identity(value: Option<String>) -> Result<HarnessIdentity, ConfigError> {
1570 HarnessIdentity::new(&named(ConfigField::Harness, value)?)
1571 .map_err(|error| ConfigError::about(ConfigField::Harness, error.to_string()))
1572}
1573
1574fn required<T>(field: ConfigField, value: Option<T>) -> Result<T, ConfigError> {
1576 value.ok_or_else(|| ConfigError::about(field, "the configuration file carries no value for it"))
1577}
1578
1579fn named(field: ConfigField, value: Option<String>) -> Result<String, ConfigError> {
1581 let value = required(field, value)?;
1582 if value.trim().is_empty() {
1583 return Err(ConfigError::about(
1584 field,
1585 "it is empty, and an empty value names nothing",
1586 ));
1587 }
1588 Ok(value.trim().to_owned())
1589}
1590
1591fn state_directory(named: &Path) -> Result<PathBuf, ConfigError> {
1593 if named.as_os_str().is_empty() {
1594 return Err(ConfigError::about(
1595 ConfigField::StateDir,
1596 "it names no directory, and this server's whole state lives in one",
1597 ));
1598 }
1599 std::fs::create_dir_all(named).map_err(|error| {
1600 ConfigError::about(
1601 ConfigField::StateDir,
1602 format!("{} cannot be created: {error}", named.display()),
1603 )
1604 })?;
1605 named.canonicalize().map(plainly_written).map_err(|error| {
1606 ConfigError::about(
1607 ConfigField::StateDir,
1608 format!("{} cannot be resolved: {error}", named.display()),
1609 )
1610 })
1611}
1612
1613#[must_use]
1622pub fn plainly_written(path: PathBuf) -> PathBuf {
1623 const VERBATIM: &str = r"\\?\";
1624 let drive = path
1625 .to_str()
1626 .and_then(|text| text.strip_prefix(VERBATIM))
1627 .filter(|rest| {
1628 let bytes = rest.as_bytes();
1629 bytes.len() >= 3
1630 && bytes[0].is_ascii_alphabetic()
1631 && bytes[1] == b':'
1632 && bytes[2] == b'\\'
1633 })
1634 .map(PathBuf::from);
1635 drive.unwrap_or(path)
1636}
1637
1638fn listen_address(named: &str) -> Result<SocketAddr, ConfigError> {
1640 named.trim().parse().map_err(|error| {
1641 ConfigError::about(
1642 ConfigField::Listen,
1643 format!("{named:?} is no address to listen on: {error}"),
1644 )
1645 })
1646}
1647
1648fn octoprint(section: &OctoprintSection) -> Result<OctoPrintConfig, ConfigError> {
1651 let fan = fan_support(§ion.fan)?;
1652 let url = named(ConfigField::OctoprintUrl, section.url.clone())?;
1653 let key = named(ConfigField::OctoprintApiKey, section.api_key.clone())?;
1654 OctoPrintConfig::new(&url, key)
1655 .map(|configured| configured.with_fan(fan))
1656 .map_err(|error| {
1657 let field = match error {
1658 printobserver_octoprint::ConfigError::EmptyApiKey => ConfigField::OctoprintApiKey,
1659 _ => ConfigField::OctoprintUrl,
1660 };
1661 ConfigError::about(field, error.to_string())
1662 })
1663}
1664
1665fn fan_support(named: &str) -> Result<FanSupport, ConfigError> {
1667 FAN_VOCABULARY
1668 .iter()
1669 .find(|(spelling, _)| *spelling == named.trim())
1670 .map(|(_, support)| *support)
1671 .ok_or_else(|| {
1672 let vocabulary: Vec<&str> = FAN_VOCABULARY.iter().map(|(word, _)| *word).collect();
1673 ConfigError::about(
1674 ConfigField::OctoprintFan,
1675 format!("{named:?} is not one of {}", vocabulary.join(" or ")),
1676 )
1677 })
1678}
1679
1680fn check_envelope(envelope: &SafetyEnvelope) -> Result<(), ConfigError> {
1682 if envelope.allowed.is_empty() {
1683 return Err(ConfigError::about(
1684 ConfigField::SafetyEnvelope,
1685 "it allows no adjustable at all, so no adjustment could ever be accepted",
1686 ));
1687 }
1688 for (adjustable, range) in &envelope.allowed {
1689 if !range.min.is_finite() || !range.max.is_finite() || range.min > range.max {
1690 return Err(ConfigError::about(
1691 ConfigField::SafetyEnvelope,
1692 format!(
1693 "the range allowed for {adjustable} runs from {} to {}, which admits \
1694 no value",
1695 range.min, range.max
1696 ),
1697 ));
1698 }
1699 }
1700 if envelope
1703 .actions
1704 .get(&ActorClass::Agent)
1705 .is_some_and(|granted| granted.contains(&ActionKind::ClosePrint))
1706 {
1707 return Err(ConfigError::about(
1708 ConfigField::SafetyEnvelope,
1709 "it grants `close_print` to the agent, and closing a print record is the \
1710 operator's judgement that the print is over",
1711 ));
1712 }
1713 if envelope.agent_min_interval_s < 0 {
1714 return Err(ConfigError::about(
1715 ConfigField::SafetyEnvelope,
1716 format!(
1717 "the agent's minimum interval is {}s, and an interval is a count of seconds",
1718 envelope.agent_min_interval_s
1719 ),
1720 ));
1721 }
1722 Ok(())
1723}
1724
1725fn readable(field: ConfigField, named: Option<&Path>) -> Result<Option<PathBuf>, ConfigError> {
1728 let Some(path) = named else {
1729 return Ok(None);
1730 };
1731 std::fs::read_to_string(path)
1732 .map(|_| Some(path.to_path_buf()))
1733 .map_err(|error| {
1734 ConfigError::about(field, format!("{} cannot be read: {error}", path.display()))
1735 })
1736}
1737
1738fn camera(
1740 section: CameraSection,
1741) -> Result<
1742 (
1743 Option<WebAddress>,
1744 Option<std::sync::Arc<printobserver_panels::CameraCalibration>>,
1745 ),
1746 ConfigError,
1747> {
1748 let snapshot_url = section
1749 .snapshot_url
1750 .map(|url| web_address(ConfigField::CameraSnapshotUrl, &url))
1751 .transpose()?;
1752 let calibration = section
1753 .calibration
1754 .as_deref()
1755 .map(calibration)
1756 .transpose()?
1757 .map(std::sync::Arc::new);
1758 Ok((snapshot_url, calibration))
1759}
1760
1761fn calibration(path: &Path) -> Result<printobserver_panels::CameraCalibration, ConfigError> {
1764 let bytes = std::fs::read(path).map_err(|error| {
1765 ConfigError::about(
1766 ConfigField::CameraCalibration,
1767 format!("{} cannot be read: {error}", path.display()),
1768 )
1769 })?;
1770 printobserver_panels::CameraCalibration::from_json(&bytes).map_err(|error| {
1771 ConfigError::about(
1772 ConfigField::CameraCalibration,
1773 format!("{} is not a camera calibration: {error}", path.display()),
1774 )
1775 })
1776}
1777
1778fn skill(named: Option<&Path>) -> Result<PathBuf, ConfigError> {
1781 let Some(path) = named else {
1782 return Err(ConfigError::about(
1783 ConfigField::SkillPath,
1784 format!(
1785 "the configuration file carries no value for it, and this program carries \
1786 no skill of its own: {SKILL_INSTALL}"
1787 ),
1788 ));
1789 };
1790 std::fs::read_to_string(path)
1791 .map(|_| path.to_path_buf())
1792 .map_err(|error| {
1793 ConfigError::about(
1794 ConfigField::SkillPath,
1795 format!(
1796 "{} cannot be read: {error}. {SKILL_INSTALL}",
1797 path.display()
1798 ),
1799 )
1800 })
1801}
1802
1803fn spool_policy(section: &SpoolsSection) -> Result<SpoolPolicy, ConfigError> {
1805 let defaults = SpoolPolicy::default();
1806 let preflight = match section.preflight.as_deref() {
1807 None => defaults.preflight,
1808 Some("refuse") => PreflightMode::Refuse,
1809 Some("warn") => PreflightMode::Warn,
1810 Some("off") => PreflightMode::Off,
1811 Some(_) => {
1812 return Err(ConfigError::about(
1813 ConfigField::SpoolsPreflight,
1814 "the spool check is one of `refuse`, `warn` or `off`",
1815 ));
1816 }
1817 };
1818 let margin = |field: ConfigField, value: Option<f64>, default: f64| match value {
1819 None => Ok(default),
1820 Some(value) if value.is_finite() && value >= 0.0 => Ok(value),
1821 Some(_) => Err(ConfigError::about(
1822 field,
1823 "a margin is a figure at or above zero; a negative one asks a spool for less \
1824 than the print needs",
1825 )),
1826 };
1827 let buffer_percent = margin(
1828 ConfigField::SpoolsBufferPercent,
1829 section.buffer_percent,
1830 defaults.buffer_percent,
1831 )?;
1832 let buffer_min_g = margin(
1833 ConfigField::SpoolsBufferMinG,
1834 section.buffer_min_g,
1835 defaults.buffer_min_g,
1836 )?;
1837 let analysis_wait_s = match section.analysis_wait_seconds {
1838 None => defaults.analysis_wait_s,
1839 Some(seconds) => u64::try_from(seconds).map_err(|_| {
1840 ConfigError::about(
1841 ConfigField::SpoolsAnalysisWaitSeconds,
1842 "a wait is a number of seconds at or above zero",
1843 )
1844 })?,
1845 };
1846 Ok(SpoolPolicy {
1847 preflight,
1848 buffer_percent,
1849 buffer_min_g,
1850 analysis_wait_s,
1851 })
1852}
1853
1854fn recovery_facts(section: &RecoverySection) -> Result<Option<RecoveryConfig>, ConfigError> {
1856 if *section == RecoverySection::default() {
1857 return Ok(None);
1858 }
1859 let absent = |field: ConfigField| {
1860 ConfigError::about(
1861 field,
1862 "`[recovery]` states this printer's facts, and this one is one of them",
1863 )
1864 };
1865 let away_from_bed = match section.away_from_bed.as_deref() {
1866 None => return Err(absent(ConfigField::RecoveryAwayFromBed)),
1867 Some("z_plus") => AwayFromBed::ZPlus,
1868 Some("z_minus") => AwayFromBed::ZMinus,
1869 Some(other) => {
1870 return Err(ConfigError::about(
1871 ConfigField::RecoveryAwayFromBed,
1872 format!("{other:?} is neither `z_plus` nor `z_minus`"),
1873 ));
1874 }
1875 };
1876 let max_z_mm = section
1877 .max_z_mm
1878 .ok_or_else(|| absent(ConfigField::RecoveryMaxZMm))?;
1879 if !(max_z_mm.is_finite() && max_z_mm > 0.0) {
1880 return Err(ConfigError::about(
1881 ConfigField::RecoveryMaxZMm,
1882 format!("{max_z_mm} mm is no height a machine reaches; it is a figure above zero"),
1883 ));
1884 }
1885 let max_lift_mm = section
1886 .max_lift_mm
1887 .unwrap_or_else(|| DEFAULT_MAX_LIFT_MM.min(max_z_mm));
1888 if !(max_lift_mm.is_finite() && max_lift_mm > 0.0 && max_lift_mm <= max_z_mm) {
1889 return Err(ConfigError::about(
1890 ConfigField::RecoveryMaxLiftMm,
1891 format!(
1892 "{max_lift_mm} mm is outside the lifts a machine of {max_z_mm} mm makes: above \
1893 zero, and at most `recovery.max_z_mm`"
1894 ),
1895 ));
1896 }
1897 let clearance_margin_mm = section
1898 .clearance_margin_mm
1899 .unwrap_or(DEFAULT_CLEARANCE_MARGIN_MM);
1900 if !(clearance_margin_mm.is_finite()
1901 && clearance_margin_mm >= 0.0
1902 && clearance_margin_mm < max_z_mm)
1903 {
1904 return Err(ConfigError::about(
1905 ConfigField::RecoveryClearanceMarginMm,
1906 format!(
1907 "{clearance_margin_mm} mm is outside the margins a machine of {max_z_mm} mm \
1908 admits: at or above zero, and below `recovery.max_z_mm`"
1909 ),
1910 ));
1911 }
1912 let place = |field: ConfigField, written: Option<&Vec<f64>>| match written.map(Vec::as_slice) {
1913 None => Err(absent(field)),
1914 Some([x, y]) if x.is_finite() && y.is_finite() && *x >= 0.0 && *y >= 0.0 => Ok([*x, *y]),
1915 Some(_) => Err(ConfigError::about(
1916 field,
1917 "a place is `[x, y]`, two figures in millimetres at or above zero",
1918 )),
1919 };
1920 let park_xy = place(ConfigField::RecoveryParkXy, section.park_xy.as_ref())?;
1921 let z_home_xy = place(ConfigField::RecoveryZHomeXy, section.z_home_xy.as_ref())?;
1922 let z_home_sweeps_bed = section
1923 .z_home_sweeps_bed
1924 .ok_or_else(|| absent(ConfigField::RecoveryZHomeSweepsBed))?;
1925 Ok(Some(RecoveryConfig {
1926 away_from_bed,
1927 max_z_mm,
1928 max_lift_mm,
1929 clearance_margin_mm,
1930 park_xy,
1931 z_home_xy,
1932 z_home_sweeps_bed,
1933 }))
1934}
1935
1936fn recovery_grants(section: &RecoveryPolicySection) -> Result<RecoveryGrants, ConfigError> {
1939 let defaults = RecoveryGrants::default();
1940 let actions = |field: ConfigField, written: Option<&Vec<String>>, default: Vec<_>| {
1941 let Some(written) = written else {
1942 return Ok(default);
1943 };
1944 written
1945 .iter()
1946 .map(|name| {
1947 RecoveryActionKind::ALL
1948 .iter()
1949 .find(|kind| kind.as_str() == name.trim())
1950 .copied()
1951 .ok_or_else(|| {
1952 ConfigError::about(
1953 field,
1954 format!("{name:?} is not a recovery action of this program"),
1955 )
1956 })
1957 })
1958 .collect::<Result<Vec<_>, _>>()
1959 };
1960 let operator = actions(
1961 ConfigField::PolicyRecoveryOperator,
1962 section.operator.as_ref(),
1963 defaults.operator,
1964 )?;
1965 let agent = actions(
1966 ConfigField::PolicyRecoveryAgent,
1967 section.agent.as_ref(),
1968 defaults.agent,
1969 )?;
1970 if agent.contains(&RecoveryActionKind::RecoverHomeZ) {
1973 return Err(ConfigError::about(
1974 ConfigField::PolicyRecoveryAgent,
1975 "it grants `recover_home_z` to the agent, and only a person at the machine can \
1976 say the bed is clear for Z to be homed",
1977 ));
1978 }
1979 let asserting = match section.asserting.as_ref() {
1980 None => defaults.asserting,
1981 Some(written) => written
1982 .iter()
1983 .map(|class| match class.trim() {
1984 "operator" => Ok(ActorClass::Operator),
1985 "agent" => Err(ConfigError::about(
1988 ConfigField::PolicyRecoveryAsserting,
1989 "it lets the agent assert clearance, and an assertion is a person's word \
1990 for what they can see at the machine",
1991 )),
1992 other => Err(ConfigError::about(
1993 ConfigField::PolicyRecoveryAsserting,
1994 format!("{other:?} is not an actor whose word can count; only `operator` is"),
1995 )),
1996 })
1997 .collect::<Result<Vec<_>, _>>()?,
1998 };
1999 Ok(RecoveryGrants {
2000 operator,
2001 agent,
2002 asserting,
2003 })
2004}
2005
2006fn observation_interval(seconds: u64) -> Result<core::time::Duration, ConfigError> {
2008 if seconds == 0 {
2009 return Err(ConfigError::about(
2010 ConfigField::ObservationIntervalS,
2011 "an interval of zero seconds observes a print again the moment its last turn \
2012 returns, which is a turn that never ends",
2013 ));
2014 }
2015 Ok(core::time::Duration::from_secs(seconds))
2016}
2017
2018fn compaction(
2021 auto: Option<i64>,
2022 idle: Option<i64>,
2023) -> Result<(Option<NonZeroU64>, Option<NonZeroU64>), ConfigError> {
2024 Ok((
2025 tokens(ConfigField::AutoCompactTokens, auto)?,
2026 tokens(ConfigField::IdleCompactTokens, idle)?,
2027 ))
2028}
2029
2030fn tokens(field: ConfigField, count: Option<i64>) -> Result<Option<NonZeroU64>, ConfigError> {
2034 count
2035 .map(|count| {
2036 u64::try_from(count)
2037 .ok()
2038 .and_then(NonZeroU64::new)
2039 .ok_or_else(|| {
2040 ConfigError::about(
2041 field,
2042 format!(
2043 "{count} tokens is no conversation size: it is a whole number from 1"
2044 ),
2045 )
2046 })
2047 })
2048 .transpose()
2049}
2050
2051fn check_turn_timeout(seconds: u64) -> Result<core::time::Duration, ConfigError> {
2054 seconds_within(
2055 ConfigField::CheckTurnTimeoutS,
2056 seconds,
2057 CHECK_TURN_TIMEOUT_RANGE_S,
2058 )
2059}
2060
2061fn seconds_within(
2063 field: ConfigField,
2064 seconds: u64,
2065 range: (u64, u64),
2066) -> Result<core::time::Duration, ConfigError> {
2067 let (least, most) = range;
2068 if !(least..=most).contains(&seconds) {
2069 return Err(ConfigError::about(
2070 field,
2071 format!("{seconds} seconds is outside the {least} to {most} seconds it admits"),
2072 ));
2073 }
2074 Ok(core::time::Duration::from_secs(seconds))
2075}
2076
2077fn blank_frame_bound(written: Option<f64>) -> Result<BlankFrameBound, ConfigError> {
2079 written.map_or(Ok(BlankFrameBound::DEFAULT), |bound| {
2080 BlankFrameBound::new(bound).map_err(|refused| {
2081 ConfigError::about(
2082 ConfigField::VisionBlankFrameMaxStddev,
2083 format!(
2084 "{refused} is outside the {MIN_BLANK_FRAME_MAX_STDDEV} to \
2085 {MAX_BLANK_FRAME_MAX_STDDEV} grey levels it admits"
2086 ),
2087 )
2088 })
2089 })
2090}
2091
2092fn answer_bound(milliseconds: u64) -> Result<core::time::Duration, ConfigError> {
2094 if milliseconds == 0 {
2095 return Err(ConfigError::about(
2096 ConfigField::IngressAnswerBoundMs,
2097 "a bound of zero is an ingress that has run out of time before it starts",
2098 ));
2099 }
2100 if milliseconds >= OBICO_POSTING_TIMEOUT_MS {
2101 return Err(ConfigError::about(
2102 ConfigField::IngressAnswerBoundMs,
2103 format!(
2104 "{milliseconds}ms is not below the {OBICO_POSTING_TIMEOUT_MS}ms Obico posts \
2105 under, so an alert answered at that bound is one Obico has already \
2106 abandoned — and its posting does not retry"
2107 ),
2108 ));
2109 }
2110 Ok(core::time::Duration::from_millis(milliseconds))
2111}
2112
2113#[cfg(test)]
2114mod tests {
2115 use super::CredentialVerifier;
2116
2117 const ABC: &str = "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
2119
2120 #[test]
2123 fn a_verifier_is_the_credentials_sha256_and_admits_only_it() {
2124 let verifier = CredentialVerifier::of("abc");
2125
2126 assert_eq!(verifier.to_string(), ABC);
2127 assert_eq!(CredentialVerifier::parse(ABC), Ok(verifier.clone()));
2128 assert!(verifier.admits(b"abc"));
2129 assert!(!verifier.admits(b"abd"));
2130 assert!(!verifier.admits(b""));
2131 }
2132
2133 #[test]
2135 fn a_verifier_in_any_other_spelling_is_refused() {
2136 for refused in [
2137 "",
2138 "sha256:",
2139 &ABC[..ABC.len() - 1],
2140 &format!("{ABC}0"),
2141 &ABC.to_uppercase(),
2142 &ABC.replace("sha256:", "sha512:"),
2143 &ABC.replace("sha256:", ""),
2144 &ABC.replace('a', "g"),
2145 ] {
2146 assert!(
2147 CredentialVerifier::parse(refused).is_err(),
2148 "{refused:?} was accepted"
2149 );
2150 }
2151 }
2152}