1use core::num::NonZeroU64;
129use std::net::SocketAddr;
130use std::path::{Path, PathBuf};
131
132use printobserver_core::{
133 ActionKind, ActorClass, AwayFromBed, DEFAULT_CLEARANCE_MARGIN_MM, DEFAULT_MAX_LIFT_MM,
134 PreflightMode, RecoveryActionKind, RecoveryConfig, RecoveryGrants, SafetyEnvelope, SheetTable,
135 SpoolPolicy,
136};
137use printobserver_obico::{
138 AccessToken, BlankFrameBound, MAX_BLANK_FRAME_MAX_STDDEV, MIN_BLANK_FRAME_MAX_STDDEV, ObicoApi,
139 ObicoPrinterId,
140};
141use printobserver_octoprint::{FanSupport, OctoPrintConfig};
142use printobserver_oneharness::{HarnessIdentity, ModelName};
143use printobserver_types::schemars::JsonSchema;
144use printobserver_types::serde::{Deserialize, Serialize};
145use printobserver_vision_api::WebAddress;
146
147pub const DEFAULT_INGRESS_ANSWER_BOUND_MS: u64 = 1_000;
154
155pub const DEFAULT_OBSERVATION_INTERVAL_S: u64 =
158 printobserver_core::DEFAULT_OBSERVATION_INTERVAL.as_secs();
159
160pub const DEFAULT_PRINTER_POLL_S: u64 = printobserver_core::DEFAULT_PRINTER_POLL.as_secs();
163
164pub const PRINTER_POLL_RANGE_S: (u64, u64) = (5, 300);
166
167pub const DEFAULT_UNATTENDED_WINDOW_S: u64 =
170 printobserver_core::DEFAULT_UNATTENDED_WINDOW.as_secs();
171
172pub const UNATTENDED_WINDOW_RANGE_S: (u64, u64) = (60, 86_400);
174
175pub const OBICO_POSTING_TIMEOUT_MS: u64 = 5_000;
184
185pub const ASSETS_DIRECTORY: &str = "assets";
190
191pub const SKILL_INSTALL: &str = "the skill is installed with `gh skill install \
198 nickderobertis/printobserver printobserver --dir <dir>`, and \
199 `supervisor.skill_path` names the installed `SKILL.md`, \
200 `<dir>/printobserver/SKILL.md`";
201
202#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
208pub enum ConfigField {
209 StateDir,
211 Listen,
213 OctoprintUrl,
215 OctoprintApiKey,
217 OctoprintFan,
219 SafetyEnvelope,
221 Harness,
223 Model,
225 SkillPath,
227 PromptTemplatePath,
229 ObservationIntervalS,
231 PrinterPollS,
233 UnattendedWindowS,
236 AutoCompactTokens,
239 IdleCompactTokens,
242 IngressAnswerBoundMs,
244 IngressSharedSecret,
246 ApiCredential,
249 ApiCredentialVerifier,
251 CameraSnapshotUrl,
254 CameraCalibration,
256 ObicoUrl,
258 ObicoAccessToken,
260 ObicoMlApiUrl,
262 ObicoPrinterId,
264 VisionBlankFrameMaxStddev,
266 SpoolsPreflight,
268 SpoolsBufferPercent,
270 SpoolsBufferMinG,
272 SpoolsAnalysisWaitSeconds,
274 SheetsAllowed,
276 RecoveryAwayFromBed,
278 RecoveryMaxZMm,
280 RecoveryMaxLiftMm,
282 RecoveryClearanceMarginMm,
284 RecoveryParkXy,
286 RecoveryZHomeXy,
288 RecoveryZHomeSweepsBed,
290 PolicyRecoveryOperator,
292 PolicyRecoveryAgent,
294 PolicyRecoveryAsserting,
296}
297
298impl ConfigField {
299 pub const ALL: [Self; 41] = [
301 Self::StateDir,
302 Self::Listen,
303 Self::OctoprintUrl,
304 Self::OctoprintApiKey,
305 Self::OctoprintFan,
306 Self::SafetyEnvelope,
307 Self::Harness,
308 Self::Model,
309 Self::SkillPath,
310 Self::PromptTemplatePath,
311 Self::ObservationIntervalS,
312 Self::PrinterPollS,
313 Self::UnattendedWindowS,
314 Self::AutoCompactTokens,
315 Self::IdleCompactTokens,
316 Self::IngressAnswerBoundMs,
317 Self::IngressSharedSecret,
318 Self::ApiCredential,
319 Self::ApiCredentialVerifier,
320 Self::CameraSnapshotUrl,
321 Self::CameraCalibration,
322 Self::ObicoUrl,
323 Self::ObicoAccessToken,
324 Self::ObicoMlApiUrl,
325 Self::ObicoPrinterId,
326 Self::VisionBlankFrameMaxStddev,
327 Self::SpoolsPreflight,
328 Self::SpoolsBufferPercent,
329 Self::SpoolsBufferMinG,
330 Self::SpoolsAnalysisWaitSeconds,
331 Self::SheetsAllowed,
332 Self::RecoveryAwayFromBed,
333 Self::RecoveryMaxZMm,
334 Self::RecoveryMaxLiftMm,
335 Self::RecoveryClearanceMarginMm,
336 Self::RecoveryParkXy,
337 Self::RecoveryZHomeXy,
338 Self::RecoveryZHomeSweepsBed,
339 Self::PolicyRecoveryOperator,
340 Self::PolicyRecoveryAgent,
341 Self::PolicyRecoveryAsserting,
342 ];
343
344 #[must_use]
346 pub const fn key(self) -> &'static str {
347 match self {
348 Self::StateDir => "state_dir",
349 Self::Listen => "listen",
350 Self::OctoprintUrl => "octoprint.url",
351 Self::OctoprintApiKey => "octoprint.api_key",
352 Self::OctoprintFan => "octoprint.fan",
353 Self::SafetyEnvelope => "safety",
354 Self::Harness => "supervisor.harness",
355 Self::Model => "supervisor.model",
356 Self::SkillPath => "supervisor.skill_path",
357 Self::PromptTemplatePath => "supervisor.prompt_template_path",
358 Self::ObservationIntervalS => "supervisor.observation_interval_s",
359 Self::PrinterPollS => "supervisor.printer_poll_s",
360 Self::UnattendedWindowS => "supervisor.unattended_window_s",
361 Self::AutoCompactTokens => "supervisor.auto_compact_tokens",
362 Self::IdleCompactTokens => "supervisor.idle_compact_tokens",
363 Self::IngressAnswerBoundMs => "ingress.answer_bound_ms",
364 Self::IngressSharedSecret => "ingress.shared_secret",
365 Self::ApiCredential => "api.credential",
366 Self::ApiCredentialVerifier => "api.credential_verifier",
367 Self::CameraSnapshotUrl => "camera.snapshot_url",
368 Self::CameraCalibration => "camera.calibration",
369 Self::ObicoUrl => "obico.url",
370 Self::ObicoAccessToken => "obico.access_token",
371 Self::ObicoMlApiUrl => "obico.ml_api_url",
372 Self::ObicoPrinterId => "obico.printer_id",
373 Self::VisionBlankFrameMaxStddev => "vision.blank_frame_max_stddev",
374 Self::SpoolsPreflight => "spools.preflight",
375 Self::SpoolsBufferPercent => "spools.buffer_percent",
376 Self::SpoolsBufferMinG => "spools.buffer_min_g",
377 Self::SpoolsAnalysisWaitSeconds => "spools.analysis_wait_seconds",
378 Self::SheetsAllowed => "sheets.allowed",
379 Self::RecoveryAwayFromBed => "recovery.away_from_bed",
380 Self::RecoveryMaxZMm => "recovery.max_z_mm",
381 Self::RecoveryMaxLiftMm => "recovery.max_lift_mm",
382 Self::RecoveryClearanceMarginMm => "recovery.clearance_margin_mm",
383 Self::RecoveryParkXy => "recovery.park_xy",
384 Self::RecoveryZHomeXy => "recovery.z_home_xy",
385 Self::RecoveryZHomeSweepsBed => "recovery.z_home_sweeps_bed",
386 Self::PolicyRecoveryOperator => "policy.recovery.operator",
387 Self::PolicyRecoveryAgent => "policy.recovery.agent",
388 Self::PolicyRecoveryAsserting => "policy.recovery.asserting",
389 }
390 }
391}
392
393impl core::fmt::Display for ConfigField {
394 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
395 formatter.write_str(self.key())
396 }
397}
398
399#[derive(Debug, Clone, PartialEq, Eq)]
404pub enum ConfigError {
405 Unreadable {
407 path: PathBuf,
409 detail: String,
411 },
412 Unparsable {
414 path: PathBuf,
416 detail: String,
418 },
419 Field {
421 field: ConfigField,
423 detail: String,
425 },
426}
427
428impl ConfigError {
429 #[must_use]
431 pub const fn field(&self) -> Option<ConfigField> {
432 match self {
433 Self::Field { field, .. } => Some(*field),
434 _ => None,
435 }
436 }
437
438 pub(crate) fn about(field: ConfigField, detail: impl Into<String>) -> Self {
440 Self::Field {
441 field,
442 detail: detail.into(),
443 }
444 }
445}
446
447impl core::fmt::Display for ConfigError {
448 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
449 match self {
450 Self::Unreadable { path, detail } => write!(
451 formatter,
452 "the configuration file {} could not be read: {detail}",
453 path.display()
454 ),
455 Self::Unparsable { path, detail } => write!(
456 formatter,
457 "the configuration file {} could not be read as this program's \
458 configuration: {detail}",
459 path.display()
460 ),
461 Self::Field { field, detail } => write!(
462 formatter,
463 "the configuration field `{field}` cannot be accepted: {detail}"
464 ),
465 }
466 }
467}
468
469impl core::error::Error for ConfigError {}
470
471#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
473#[serde(
474 crate = "printobserver_types::serde",
475 deny_unknown_fields,
476 rename_all = "snake_case"
477)]
478#[schemars(crate = "printobserver_types::schemars")]
479pub struct OctoprintSection {
480 #[serde(default, skip_serializing_if = "Option::is_none")]
482 pub url: Option<String>,
483 #[serde(default, skip_serializing_if = "Option::is_none")]
485 pub api_key: Option<String>,
486 #[serde(default = "commandable")]
488 pub fan: String,
489}
490
491pub const FAN_VOCABULARY: [(&str, FanSupport); 2] = [
494 ("commandable", FanSupport::Commandable),
495 ("absent", FanSupport::Absent),
496];
497
498fn commandable() -> String {
500 FAN_VOCABULARY[0].0.to_owned()
501}
502
503impl Default for OctoprintSection {
504 fn default() -> Self {
505 Self {
506 url: None,
507 api_key: None,
508 fan: commandable(),
509 }
510 }
511}
512
513#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
515#[serde(
516 crate = "printobserver_types::serde",
517 deny_unknown_fields,
518 rename_all = "snake_case"
519)]
520#[schemars(crate = "printobserver_types::schemars")]
521pub struct SupervisorSection {
522 #[serde(default, skip_serializing_if = "Option::is_none")]
524 pub harness: Option<String>,
525 #[serde(default, skip_serializing_if = "Option::is_none")]
527 pub model: Option<String>,
528 #[serde(default, skip_serializing_if = "Option::is_none")]
532 pub skill_path: Option<PathBuf>,
533 #[serde(default, skip_serializing_if = "Option::is_none")]
536 pub prompt_template_path: Option<PathBuf>,
537 #[serde(default = "default_observation_interval_s")]
540 pub observation_interval_s: u64,
541 #[serde(default = "default_printer_poll_s")]
544 pub printer_poll_s: u64,
545 #[serde(default = "default_unattended_window_s")]
549 pub unattended_window_s: u64,
550 #[serde(default, skip_serializing_if = "Option::is_none")]
553 pub auto_compact_tokens: Option<i64>,
554 #[serde(default, skip_serializing_if = "Option::is_none")]
557 pub idle_compact_tokens: Option<i64>,
558}
559
560const fn default_printer_poll_s() -> u64 {
562 DEFAULT_PRINTER_POLL_S
563}
564
565const fn default_unattended_window_s() -> u64 {
567 DEFAULT_UNATTENDED_WINDOW_S
568}
569
570const fn default_observation_interval_s() -> u64 {
572 DEFAULT_OBSERVATION_INTERVAL_S
573}
574
575impl Default for SupervisorSection {
576 fn default() -> Self {
577 Self {
578 harness: None,
579 model: None,
580 skill_path: None,
581 prompt_template_path: None,
582 observation_interval_s: DEFAULT_OBSERVATION_INTERVAL_S,
583 printer_poll_s: DEFAULT_PRINTER_POLL_S,
584 unattended_window_s: DEFAULT_UNATTENDED_WINDOW_S,
585 auto_compact_tokens: None,
586 idle_compact_tokens: None,
587 }
588 }
589}
590
591#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
593#[serde(
594 crate = "printobserver_types::serde",
595 deny_unknown_fields,
596 rename_all = "snake_case"
597)]
598#[schemars(crate = "printobserver_types::schemars")]
599pub struct IngressSection {
600 #[serde(default, skip_serializing_if = "Option::is_none")]
602 pub shared_secret: Option<String>,
603 #[serde(default = "default_answer_bound_ms")]
605 pub answer_bound_ms: u64,
606}
607
608const fn default_answer_bound_ms() -> u64 {
610 DEFAULT_INGRESS_ANSWER_BOUND_MS
611}
612
613impl Default for IngressSection {
614 fn default() -> Self {
615 Self {
616 shared_secret: None,
617 answer_bound_ms: DEFAULT_INGRESS_ANSWER_BOUND_MS,
618 }
619 }
620}
621
622#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
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 ApiSection {
631 #[serde(default, skip_serializing_if = "Option::is_none")]
635 pub credential: Option<String>,
636 #[serde(default, skip_serializing_if = "Option::is_none")]
642 pub credential_verifier: Option<String>,
643}
644
645#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
647#[serde(
648 crate = "printobserver_types::serde",
649 deny_unknown_fields,
650 rename_all = "snake_case"
651)]
652#[schemars(crate = "printobserver_types::schemars")]
653pub struct CameraSection {
654 #[serde(default, skip_serializing_if = "Option::is_none")]
657 pub snapshot_url: Option<String>,
658 #[serde(default, skip_serializing_if = "Option::is_none")]
664 pub calibration: Option<PathBuf>,
665}
666
667#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
671#[serde(
672 crate = "printobserver_types::serde",
673 deny_unknown_fields,
674 rename_all = "snake_case"
675)]
676#[schemars(crate = "printobserver_types::schemars")]
677pub struct ObicoSection {
678 #[serde(default, skip_serializing_if = "Option::is_none")]
681 pub url: Option<String>,
682 #[serde(default, skip_serializing_if = "Option::is_none")]
686 pub access_token: Option<String>,
687 #[serde(default, skip_serializing_if = "Option::is_none")]
692 pub ml_api_url: Option<String>,
693 #[serde(default, skip_serializing_if = "Option::is_none")]
699 pub printer_id: Option<i64>,
700}
701
702#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
704#[serde(
705 crate = "printobserver_types::serde",
706 deny_unknown_fields,
707 rename_all = "snake_case"
708)]
709#[schemars(crate = "printobserver_types::schemars")]
710pub struct VisionSection {
711 #[serde(default, skip_serializing_if = "Option::is_none")]
714 pub blank_frame_max_stddev: Option<f64>,
715}
716
717impl core::fmt::Debug for ObicoSection {
718 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
719 formatter
720 .debug_struct("ObicoSection")
721 .field("url", &self.url)
722 .field(
723 "access_token",
724 &self.access_token.as_ref().map(|_| REDACTED),
725 )
726 .field("ml_api_url", &self.ml_api_url)
727 .field("printer_id", &self.printer_id)
728 .finish()
729 }
730}
731
732#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
739#[serde(
740 crate = "printobserver_types::serde",
741 deny_unknown_fields,
742 rename_all = "snake_case"
743)]
744#[schemars(crate = "printobserver_types::schemars")]
745pub struct SpoolsSection {
746 #[serde(default, skip_serializing_if = "Option::is_none")]
749 pub preflight: Option<String>,
750 #[serde(default, skip_serializing_if = "Option::is_none")]
752 pub buffer_percent: Option<f64>,
753 #[serde(default, skip_serializing_if = "Option::is_none")]
755 pub buffer_min_g: Option<f64>,
756 #[serde(default, skip_serializing_if = "Option::is_none")]
759 pub analysis_wait_seconds: Option<i64>,
760}
761
762#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
767#[serde(
768 crate = "printobserver_types::serde",
769 deny_unknown_fields,
770 rename_all = "snake_case"
771)]
772#[schemars(crate = "printobserver_types::schemars")]
773pub struct SheetsSection {
774 #[serde(default, skip_serializing_if = "Option::is_none")]
778 pub allowed: Option<std::collections::BTreeMap<String, Vec<String>>>,
779}
780
781#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
788#[serde(
789 crate = "printobserver_types::serde",
790 deny_unknown_fields,
791 rename_all = "snake_case"
792)]
793#[schemars(crate = "printobserver_types::schemars")]
794pub struct RecoverySection {
795 #[serde(default, skip_serializing_if = "Option::is_none")]
798 pub away_from_bed: Option<String>,
800 #[serde(default, skip_serializing_if = "Option::is_none")]
802 pub max_z_mm: Option<f64>,
803 #[serde(default, skip_serializing_if = "Option::is_none")]
806 pub max_lift_mm: Option<f64>,
807 #[serde(default, skip_serializing_if = "Option::is_none")]
810 pub clearance_margin_mm: Option<f64>,
811 #[serde(default, skip_serializing_if = "Option::is_none")]
813 pub park_xy: Option<Vec<f64>>,
814 #[serde(default, skip_serializing_if = "Option::is_none")]
816 pub z_home_xy: Option<Vec<f64>>,
817 #[serde(default, skip_serializing_if = "Option::is_none")]
820 pub z_home_sweeps_bed: Option<bool>,
821}
822
823#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
827#[serde(
828 crate = "printobserver_types::serde",
829 deny_unknown_fields,
830 rename_all = "snake_case"
831)]
832#[schemars(crate = "printobserver_types::schemars")]
833pub struct RecoveryPolicySection {
834 #[serde(default, skip_serializing_if = "Option::is_none")]
836 pub operator: Option<Vec<String>>,
838 #[serde(default, skip_serializing_if = "Option::is_none")]
841 pub agent: Option<Vec<String>>,
843 #[serde(default, skip_serializing_if = "Option::is_none")]
846 pub asserting: Option<Vec<String>>,
848}
849
850#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
852#[serde(
853 crate = "printobserver_types::serde",
854 deny_unknown_fields,
855 rename_all = "snake_case"
856)]
857#[schemars(crate = "printobserver_types::schemars")]
858pub struct PolicySection {
859 #[serde(default)]
861 pub recovery: RecoveryPolicySection,
862}
863
864#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
870#[serde(
871 crate = "printobserver_types::serde",
872 deny_unknown_fields,
873 rename_all = "snake_case"
874)]
875#[schemars(crate = "printobserver_types::schemars")]
876pub struct ConfigFile {
877 #[serde(default, skip_serializing_if = "Option::is_none")]
879 pub state_dir: Option<PathBuf>,
880 #[serde(default, skip_serializing_if = "Option::is_none")]
882 pub listen: Option<String>,
883 #[serde(default)]
885 pub octoprint: OctoprintSection,
886 #[serde(default, skip_serializing_if = "Option::is_none")]
888 pub safety: Option<SafetyEnvelope>,
889 #[serde(default)]
891 pub supervisor: SupervisorSection,
892 #[serde(default)]
894 pub ingress: IngressSection,
895 #[serde(default)]
897 pub api: ApiSection,
898 #[serde(default)]
900 pub camera: CameraSection,
901 #[serde(default)]
903 pub obico: ObicoSection,
904 #[serde(default)]
906 pub vision: VisionSection,
907 #[serde(default)]
909 pub spools: SpoolsSection,
910 #[serde(default)]
912 pub sheets: SheetsSection,
913 #[serde(default)]
915 pub recovery: RecoverySection,
916 #[serde(default)]
918 pub policy: PolicySection,
919}
920
921#[derive(Clone, PartialEq, Eq)]
928pub struct SharedSecret(String);
929
930pub const REDACTED: &str = "<redacted>";
932
933impl SharedSecret {
934 pub fn new(value: &str) -> Result<Self, ConfigError> {
942 if value.trim().is_empty() {
943 return Err(ConfigError::about(
944 ConfigField::IngressSharedSecret,
945 "it is empty, and anything that can post to the ingress can pause a printer",
946 ));
947 }
948 Ok(Self(value.to_owned()))
949 }
950
951 #[must_use]
958 pub fn matches(&self, offered: Option<&str>) -> bool {
959 let Some(offered) = offered else {
960 return false;
961 };
962 let expected = self.0.as_bytes();
963 let mut difference = expected.len() ^ offered.len();
964 for (index, byte) in offered.bytes().enumerate() {
965 let against = expected[index % expected.len().max(1)];
966 difference |= usize::from(byte ^ against);
967 }
968 difference == 0
969 }
970}
971
972impl core::fmt::Display for SharedSecret {
973 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
974 formatter.write_str(REDACTED)
975 }
976}
977
978impl core::fmt::Debug for SharedSecret {
979 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
980 write!(formatter, "SharedSecret({REDACTED})")
981 }
982}
983
984pub const GENERATED_CREDENTIAL_BYTES: usize = 32;
986
987#[derive(Clone)]
997pub struct ApiCredential(String);
998
999impl ApiCredential {
1000 pub fn new(value: &str) -> Result<Self, &'static str> {
1009 if value.trim().is_empty() {
1010 return Err(
1011 "it is empty, and anything that can reach this server's API can command a printer",
1012 );
1013 }
1014 if !value.bytes().all(|byte| (b' '..=b'~').contains(&byte)) {
1015 return Err(
1016 "it carries a control character or a character outside printable ASCII, which \
1017 no `Authorization` header carries intact",
1018 );
1019 }
1020 if value.starts_with(' ') || value.ends_with(' ') {
1021 return Err(
1022 "it begins or ends with a space, which an `Authorization` header does not carry",
1023 );
1024 }
1025 Ok(Self(value.to_owned()))
1027 }
1028
1029 pub fn generate() -> Result<Self, getrandom::Error> {
1039 use base64::Engine as _;
1040
1041 let mut drawn = [0_u8; GENERATED_CREDENTIAL_BYTES];
1042 getrandom::fill(&mut drawn)?;
1043 Ok(Self(
1044 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(drawn),
1045 ))
1046 }
1047
1048 #[must_use]
1054 pub fn admits(&self, presented: &[u8]) -> bool {
1055 use subtle::ConstantTimeEq as _;
1056
1057 let expected = self.0.as_bytes();
1058 expected.len() == presented.len() && bool::from(expected.ct_eq(presented))
1059 }
1060
1061 #[must_use]
1064 pub fn written(&self) -> &str {
1065 &self.0
1066 }
1067
1068 #[must_use]
1070 pub fn verifier(&self) -> CredentialVerifier {
1071 CredentialVerifier::of(&self.0)
1072 }
1073}
1074
1075impl PartialEq for ApiCredential {
1076 fn eq(&self, other: &Self) -> bool {
1077 self.admits(other.0.as_bytes())
1078 }
1079}
1080
1081impl Eq for ApiCredential {}
1082
1083impl core::fmt::Display for ApiCredential {
1084 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1085 formatter.write_str(REDACTED)
1086 }
1087}
1088
1089impl core::fmt::Debug for ApiCredential {
1090 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1091 write!(formatter, "ApiCredential({REDACTED})")
1092 }
1093}
1094
1095pub const VERIFIER_PREFIX: &str = "sha256:";
1097
1098const VERIFIER_DIGITS: usize = 64;
1100
1101#[derive(Clone, PartialEq, Eq)]
1112pub struct CredentialVerifier([u8; 32]);
1113
1114impl CredentialVerifier {
1115 #[must_use]
1117 pub fn of(credential: &str) -> Self {
1118 use sha2::Digest as _;
1119
1120 Self(sha2::Sha256::digest(credential.as_bytes()).into())
1121 }
1122
1123 pub fn parse(text: &str) -> Result<Self, &'static str> {
1130 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";
1131 let digits = text.strip_prefix(VERIFIER_PREFIX).ok_or(SHAPE)?;
1132 if digits.len() != VERIFIER_DIGITS
1133 || !digits
1134 .bytes()
1135 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1136 {
1137 return Err(SHAPE);
1138 }
1139 let mut digest = [0_u8; 32];
1140 for (index, pair) in digits.as_bytes().chunks(2).enumerate() {
1141 let high = hex_value(pair[0]);
1142 let low = hex_value(pair[1]);
1143 digest[index] = (high << 4) | low;
1144 }
1145 Ok(Self(digest))
1146 }
1147
1148 #[must_use]
1154 pub fn admits(&self, presented: &[u8]) -> bool {
1155 use sha2::Digest as _;
1156 use subtle::ConstantTimeEq as _;
1157
1158 let offered: [u8; 32] = sha2::Sha256::digest(presented).into();
1159 bool::from(self.0.ct_eq(&offered))
1160 }
1161}
1162
1163const fn hex_value(digit: u8) -> u8 {
1165 if digit.is_ascii_digit() {
1166 digit - b'0'
1167 } else {
1168 digit - b'a' + 10
1169 }
1170}
1171
1172impl core::fmt::Display for CredentialVerifier {
1173 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1174 formatter.write_str(VERIFIER_PREFIX)?;
1175 for byte in self.0 {
1176 write!(formatter, "{byte:02x}")?;
1177 }
1178 Ok(())
1179 }
1180}
1181
1182impl core::fmt::Debug for CredentialVerifier {
1183 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1184 write!(formatter, "CredentialVerifier({self})")
1185 }
1186}
1187
1188#[derive(Debug, Clone, PartialEq)]
1197pub struct ServerConfig {
1198 pub state_dir: PathBuf,
1200 pub listen: SocketAddr,
1202 pub octoprint: OctoPrintConfig,
1204 pub safety: SafetyEnvelope,
1206 pub harness: HarnessIdentity,
1208 pub model: Option<ModelName>,
1210 pub skill_path: PathBuf,
1214 pub prompt_template_path: Option<PathBuf>,
1216 pub observation_interval: core::time::Duration,
1218 pub printer_poll: core::time::Duration,
1220 pub unattended_window: core::time::Duration,
1223 pub auto_compact_tokens: Option<NonZeroU64>,
1226 pub idle_compact_tokens: Option<NonZeroU64>,
1229 pub blank_frame_max_stddev: BlankFrameBound,
1231 pub obico_ml_api_url: Option<WebAddress>,
1234 pub obico_printer_id: Option<ObicoPrinterId>,
1237 pub ingress_answer_bound: core::time::Duration,
1239 pub ingress_shared_secret: SharedSecret,
1241 pub api_credential: Option<ApiCredential>,
1245 pub api_credential_verifier: Option<CredentialVerifier>,
1249 pub camera_snapshot_url: Option<WebAddress>,
1251 pub camera_calibration: Option<std::sync::Arc<printobserver_panels::CameraCalibration>>,
1254 pub obico_api: Option<ObicoApi>,
1256 pub spools: SpoolPolicy,
1258 pub sheets: SheetTable,
1260 pub recovery: Option<RecoveryConfig>,
1262 pub recovery_grants: RecoveryGrants,
1264}
1265
1266impl ServerConfig {
1267 pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
1278 let path = path.as_ref();
1279 Self::parse(&read(path)?, path)
1280 }
1281
1282 pub fn parse(text: &str, path: &Path) -> Result<Self, ConfigError> {
1288 let file: ConfigFile = toml::from_str(text).map_err(|error| ConfigError::Unparsable {
1289 path: path.to_path_buf(),
1290 detail: error.to_string(),
1291 })?;
1292 Self::validate(file)
1293 }
1294
1295 fn validate(file: ConfigFile) -> Result<Self, ConfigError> {
1302 let state_dir =
1303 state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?;
1304 let listen = listen_address(&required(ConfigField::Listen, file.listen)?)?;
1305 let octoprint = octoprint(&file.octoprint)?;
1306 let safety = required(ConfigField::SafetyEnvelope, file.safety)?;
1307 check_envelope(&safety)?;
1308 let harness = harness_identity(file.supervisor.harness)?;
1309 let model = match file.supervisor.model {
1310 None => None,
1311 Some(name) => Some(
1312 ModelName::new(&named(ConfigField::Model, Some(name))?)
1313 .map_err(|error| ConfigError::about(ConfigField::Model, error.to_string()))?,
1314 ),
1315 };
1316 let skill_path = skill(file.supervisor.skill_path.as_deref())?;
1317 let prompt_template_path = readable(
1318 ConfigField::PromptTemplatePath,
1319 file.supervisor.prompt_template_path.as_deref(),
1320 )?;
1321 let observation_interval = observation_interval(file.supervisor.observation_interval_s)?;
1322 let printer_poll = seconds_within(
1323 ConfigField::PrinterPollS,
1324 file.supervisor.printer_poll_s,
1325 PRINTER_POLL_RANGE_S,
1326 )?;
1327 let unattended_window = seconds_within(
1328 ConfigField::UnattendedWindowS,
1329 file.supervisor.unattended_window_s,
1330 UNATTENDED_WINDOW_RANGE_S,
1331 )?;
1332 let (auto_compact_tokens, idle_compact_tokens) = compaction(
1333 file.supervisor.auto_compact_tokens,
1334 file.supervisor.idle_compact_tokens,
1335 )?;
1336 let blank_frame_max_stddev = blank_frame_bound(file.vision.blank_frame_max_stddev)?;
1337 let (obico_ml_api_url, obico_printer_id) = detector_reads(&file.obico)?;
1338 let ingress_answer_bound = answer_bound(file.ingress.answer_bound_ms)?;
1339 let ingress_shared_secret = SharedSecret::new(&required(
1340 ConfigField::IngressSharedSecret,
1341 file.ingress.shared_secret,
1342 )?)?;
1343 let api_credential = file
1344 .api
1345 .credential
1346 .as_deref()
1347 .map(|value| {
1348 ApiCredential::new(value)
1349 .map_err(|why| ConfigError::about(ConfigField::ApiCredential, why))
1350 })
1351 .transpose()?;
1352 let api_credential_verifier = file
1353 .api
1354 .credential_verifier
1355 .as_deref()
1356 .map(|value| {
1357 CredentialVerifier::parse(value.trim())
1358 .map_err(|why| ConfigError::about(ConfigField::ApiCredentialVerifier, why))
1359 })
1360 .transpose()?;
1361 let (camera_snapshot_url, camera_calibration) = camera(file.camera)?;
1362 let obico_api = obico_api(file.obico)?;
1363 let spools = spool_policy(&file.spools)?;
1364 let sheets = match file.sheets.allowed {
1365 None => SheetTable::default(),
1366 Some(entries) => SheetTable::new(entries)
1367 .map_err(|why| ConfigError::about(ConfigField::SheetsAllowed, why))?,
1368 };
1369 let recovery = recovery_facts(&file.recovery)?;
1370 let recovery_grants = recovery_grants(&file.policy.recovery)?;
1371 Ok(Self {
1372 state_dir,
1373 listen,
1374 octoprint,
1375 safety,
1376 harness,
1377 model,
1378 skill_path,
1379 prompt_template_path,
1380 observation_interval,
1381 printer_poll,
1382 unattended_window,
1383 auto_compact_tokens,
1384 idle_compact_tokens,
1385 blank_frame_max_stddev,
1386 obico_ml_api_url,
1387 obico_printer_id,
1388 ingress_answer_bound,
1389 ingress_shared_secret,
1390 api_credential,
1391 api_credential_verifier,
1392 camera_snapshot_url,
1393 camera_calibration,
1394 obico_api,
1395 spools,
1396 sheets,
1397 recovery,
1398 recovery_grants,
1399 })
1400 }
1401
1402 #[must_use]
1406 pub fn assets_dir(&self) -> PathBuf {
1407 self.state_dir.join(ASSETS_DIRECTORY)
1408 }
1409}
1410
1411fn web_address(field: ConfigField, url: &str) -> Result<WebAddress, ConfigError> {
1414 WebAddress::new(url).map_err(|why| ConfigError::about(field, why))
1415}
1416
1417fn detector_reads(
1421 section: &ObicoSection,
1422) -> Result<(Option<WebAddress>, Option<ObicoPrinterId>), ConfigError> {
1423 let ml_api_url = section
1424 .ml_api_url
1425 .as_deref()
1426 .map(|url| web_address(ConfigField::ObicoMlApiUrl, url))
1427 .transpose()?;
1428 let printer_id = section
1429 .printer_id
1430 .map(|id| {
1431 ObicoPrinterId::new(id)
1432 .map_err(|why| ConfigError::about(ConfigField::ObicoPrinterId, why))
1433 })
1434 .transpose()?;
1435 Ok((ml_api_url, printer_id))
1436}
1437
1438fn obico_api(section: ObicoSection) -> Result<Option<ObicoApi>, ConfigError> {
1444 match (section.url, section.access_token) {
1445 (None, None) => Ok(None),
1446 (Some(_), None) => Err(ConfigError::about(
1447 ConfigField::ObicoAccessToken,
1448 "it is required when obico.url is given",
1449 )),
1450 (None, Some(_)) => Err(ConfigError::about(
1451 ConfigField::ObicoUrl,
1452 "it is required when obico.access_token is given",
1453 )),
1454 (Some(url), Some(access_token)) => {
1455 let url = web_address(ConfigField::ObicoUrl, &url)?;
1456 let access_token = AccessToken::new(&access_token)
1457 .map_err(|why| ConfigError::about(ConfigField::ObicoAccessToken, why))?;
1458 Ok(Some(ObicoApi::new(url, access_token)))
1459 }
1460 }
1461}
1462
1463#[derive(Debug, Clone, PartialEq, Eq)]
1471pub struct SignInConfig {
1472 pub state_dir: PathBuf,
1474 pub harness: HarnessIdentity,
1476}
1477
1478impl SignInConfig {
1479 pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
1489 let path = path.as_ref();
1490 let file: SignInFile =
1491 toml::from_str(&read(path)?).map_err(|error| ConfigError::Unparsable {
1492 path: path.to_path_buf(),
1493 detail: error.to_string(),
1494 })?;
1495 Ok(Self {
1496 state_dir: state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?,
1497 harness: harness_identity(file.supervisor.harness)?,
1498 })
1499 }
1500}
1501
1502#[derive(Deserialize)]
1507#[serde(crate = "printobserver_types::serde")]
1508struct SignInFile {
1509 #[serde(default)]
1511 state_dir: Option<PathBuf>,
1512 #[serde(default)]
1514 supervisor: SignInSupervisor,
1515}
1516
1517#[derive(Default, Deserialize)]
1519#[serde(crate = "printobserver_types::serde")]
1520struct SignInSupervisor {
1521 #[serde(default)]
1523 harness: Option<String>,
1524}
1525
1526fn read(path: &Path) -> Result<String, ConfigError> {
1528 std::fs::read_to_string(path).map_err(|error| ConfigError::Unreadable {
1529 path: path.to_path_buf(),
1530 detail: error.to_string(),
1531 })
1532}
1533
1534fn harness_identity(value: Option<String>) -> Result<HarnessIdentity, ConfigError> {
1536 HarnessIdentity::new(&named(ConfigField::Harness, value)?)
1537 .map_err(|error| ConfigError::about(ConfigField::Harness, error.to_string()))
1538}
1539
1540fn required<T>(field: ConfigField, value: Option<T>) -> Result<T, ConfigError> {
1542 value.ok_or_else(|| ConfigError::about(field, "the configuration file carries no value for it"))
1543}
1544
1545fn named(field: ConfigField, value: Option<String>) -> Result<String, ConfigError> {
1547 let value = required(field, value)?;
1548 if value.trim().is_empty() {
1549 return Err(ConfigError::about(
1550 field,
1551 "it is empty, and an empty value names nothing",
1552 ));
1553 }
1554 Ok(value.trim().to_owned())
1555}
1556
1557fn state_directory(named: &Path) -> Result<PathBuf, ConfigError> {
1559 if named.as_os_str().is_empty() {
1560 return Err(ConfigError::about(
1561 ConfigField::StateDir,
1562 "it names no directory, and this server's whole state lives in one",
1563 ));
1564 }
1565 std::fs::create_dir_all(named).map_err(|error| {
1566 ConfigError::about(
1567 ConfigField::StateDir,
1568 format!("{} cannot be created: {error}", named.display()),
1569 )
1570 })?;
1571 named.canonicalize().map(plainly_written).map_err(|error| {
1572 ConfigError::about(
1573 ConfigField::StateDir,
1574 format!("{} cannot be resolved: {error}", named.display()),
1575 )
1576 })
1577}
1578
1579#[must_use]
1588pub fn plainly_written(path: PathBuf) -> PathBuf {
1589 const VERBATIM: &str = r"\\?\";
1590 let drive = path
1591 .to_str()
1592 .and_then(|text| text.strip_prefix(VERBATIM))
1593 .filter(|rest| {
1594 let bytes = rest.as_bytes();
1595 bytes.len() >= 3
1596 && bytes[0].is_ascii_alphabetic()
1597 && bytes[1] == b':'
1598 && bytes[2] == b'\\'
1599 })
1600 .map(PathBuf::from);
1601 drive.unwrap_or(path)
1602}
1603
1604fn listen_address(named: &str) -> Result<SocketAddr, ConfigError> {
1606 named.trim().parse().map_err(|error| {
1607 ConfigError::about(
1608 ConfigField::Listen,
1609 format!("{named:?} is no address to listen on: {error}"),
1610 )
1611 })
1612}
1613
1614fn octoprint(section: &OctoprintSection) -> Result<OctoPrintConfig, ConfigError> {
1617 let fan = fan_support(§ion.fan)?;
1618 let url = named(ConfigField::OctoprintUrl, section.url.clone())?;
1619 let key = named(ConfigField::OctoprintApiKey, section.api_key.clone())?;
1620 OctoPrintConfig::new(&url, key)
1621 .map(|configured| configured.with_fan(fan))
1622 .map_err(|error| {
1623 let field = match error {
1624 printobserver_octoprint::ConfigError::EmptyApiKey => ConfigField::OctoprintApiKey,
1625 _ => ConfigField::OctoprintUrl,
1626 };
1627 ConfigError::about(field, error.to_string())
1628 })
1629}
1630
1631fn fan_support(named: &str) -> Result<FanSupport, ConfigError> {
1633 FAN_VOCABULARY
1634 .iter()
1635 .find(|(spelling, _)| *spelling == named.trim())
1636 .map(|(_, support)| *support)
1637 .ok_or_else(|| {
1638 let vocabulary: Vec<&str> = FAN_VOCABULARY.iter().map(|(word, _)| *word).collect();
1639 ConfigError::about(
1640 ConfigField::OctoprintFan,
1641 format!("{named:?} is not one of {}", vocabulary.join(" or ")),
1642 )
1643 })
1644}
1645
1646fn check_envelope(envelope: &SafetyEnvelope) -> Result<(), ConfigError> {
1648 if envelope.allowed.is_empty() {
1649 return Err(ConfigError::about(
1650 ConfigField::SafetyEnvelope,
1651 "it allows no adjustable at all, so no adjustment could ever be accepted",
1652 ));
1653 }
1654 for (adjustable, range) in &envelope.allowed {
1655 if !range.min.is_finite() || !range.max.is_finite() || range.min > range.max {
1656 return Err(ConfigError::about(
1657 ConfigField::SafetyEnvelope,
1658 format!(
1659 "the range allowed for {adjustable} runs from {} to {}, which admits \
1660 no value",
1661 range.min, range.max
1662 ),
1663 ));
1664 }
1665 }
1666 if envelope
1669 .actions
1670 .get(&ActorClass::Agent)
1671 .is_some_and(|granted| granted.contains(&ActionKind::ClosePrint))
1672 {
1673 return Err(ConfigError::about(
1674 ConfigField::SafetyEnvelope,
1675 "it grants `close_print` to the agent, and closing a print record is the \
1676 operator's judgement that the print is over",
1677 ));
1678 }
1679 if envelope.agent_min_interval_s < 0 {
1680 return Err(ConfigError::about(
1681 ConfigField::SafetyEnvelope,
1682 format!(
1683 "the agent's minimum interval is {}s, and an interval is a count of seconds",
1684 envelope.agent_min_interval_s
1685 ),
1686 ));
1687 }
1688 Ok(())
1689}
1690
1691fn readable(field: ConfigField, named: Option<&Path>) -> Result<Option<PathBuf>, ConfigError> {
1694 let Some(path) = named else {
1695 return Ok(None);
1696 };
1697 std::fs::read_to_string(path)
1698 .map(|_| Some(path.to_path_buf()))
1699 .map_err(|error| {
1700 ConfigError::about(field, format!("{} cannot be read: {error}", path.display()))
1701 })
1702}
1703
1704fn camera(
1706 section: CameraSection,
1707) -> Result<
1708 (
1709 Option<WebAddress>,
1710 Option<std::sync::Arc<printobserver_panels::CameraCalibration>>,
1711 ),
1712 ConfigError,
1713> {
1714 let snapshot_url = section
1715 .snapshot_url
1716 .map(|url| web_address(ConfigField::CameraSnapshotUrl, &url))
1717 .transpose()?;
1718 let calibration = section
1719 .calibration
1720 .as_deref()
1721 .map(calibration)
1722 .transpose()?
1723 .map(std::sync::Arc::new);
1724 Ok((snapshot_url, calibration))
1725}
1726
1727fn calibration(path: &Path) -> Result<printobserver_panels::CameraCalibration, ConfigError> {
1730 let bytes = std::fs::read(path).map_err(|error| {
1731 ConfigError::about(
1732 ConfigField::CameraCalibration,
1733 format!("{} cannot be read: {error}", path.display()),
1734 )
1735 })?;
1736 printobserver_panels::CameraCalibration::from_json(&bytes).map_err(|error| {
1737 ConfigError::about(
1738 ConfigField::CameraCalibration,
1739 format!("{} is not a camera calibration: {error}", path.display()),
1740 )
1741 })
1742}
1743
1744fn skill(named: Option<&Path>) -> Result<PathBuf, ConfigError> {
1747 let Some(path) = named else {
1748 return Err(ConfigError::about(
1749 ConfigField::SkillPath,
1750 format!(
1751 "the configuration file carries no value for it, and this program carries \
1752 no skill of its own: {SKILL_INSTALL}"
1753 ),
1754 ));
1755 };
1756 std::fs::read_to_string(path)
1757 .map(|_| path.to_path_buf())
1758 .map_err(|error| {
1759 ConfigError::about(
1760 ConfigField::SkillPath,
1761 format!(
1762 "{} cannot be read: {error}. {SKILL_INSTALL}",
1763 path.display()
1764 ),
1765 )
1766 })
1767}
1768
1769fn spool_policy(section: &SpoolsSection) -> Result<SpoolPolicy, ConfigError> {
1771 let defaults = SpoolPolicy::default();
1772 let preflight = match section.preflight.as_deref() {
1773 None => defaults.preflight,
1774 Some("refuse") => PreflightMode::Refuse,
1775 Some("warn") => PreflightMode::Warn,
1776 Some("off") => PreflightMode::Off,
1777 Some(_) => {
1778 return Err(ConfigError::about(
1779 ConfigField::SpoolsPreflight,
1780 "the spool check is one of `refuse`, `warn` or `off`",
1781 ));
1782 }
1783 };
1784 let margin = |field: ConfigField, value: Option<f64>, default: f64| match value {
1785 None => Ok(default),
1786 Some(value) if value.is_finite() && value >= 0.0 => Ok(value),
1787 Some(_) => Err(ConfigError::about(
1788 field,
1789 "a margin is a figure at or above zero; a negative one asks a spool for less \
1790 than the print needs",
1791 )),
1792 };
1793 let buffer_percent = margin(
1794 ConfigField::SpoolsBufferPercent,
1795 section.buffer_percent,
1796 defaults.buffer_percent,
1797 )?;
1798 let buffer_min_g = margin(
1799 ConfigField::SpoolsBufferMinG,
1800 section.buffer_min_g,
1801 defaults.buffer_min_g,
1802 )?;
1803 let analysis_wait_s = match section.analysis_wait_seconds {
1804 None => defaults.analysis_wait_s,
1805 Some(seconds) => u64::try_from(seconds).map_err(|_| {
1806 ConfigError::about(
1807 ConfigField::SpoolsAnalysisWaitSeconds,
1808 "a wait is a number of seconds at or above zero",
1809 )
1810 })?,
1811 };
1812 Ok(SpoolPolicy {
1813 preflight,
1814 buffer_percent,
1815 buffer_min_g,
1816 analysis_wait_s,
1817 })
1818}
1819
1820fn recovery_facts(section: &RecoverySection) -> Result<Option<RecoveryConfig>, ConfigError> {
1822 if *section == RecoverySection::default() {
1823 return Ok(None);
1824 }
1825 let absent = |field: ConfigField| {
1826 ConfigError::about(
1827 field,
1828 "`[recovery]` states this printer's facts, and this one is one of them",
1829 )
1830 };
1831 let away_from_bed = match section.away_from_bed.as_deref() {
1832 None => return Err(absent(ConfigField::RecoveryAwayFromBed)),
1833 Some("z_plus") => AwayFromBed::ZPlus,
1834 Some("z_minus") => AwayFromBed::ZMinus,
1835 Some(other) => {
1836 return Err(ConfigError::about(
1837 ConfigField::RecoveryAwayFromBed,
1838 format!("{other:?} is neither `z_plus` nor `z_minus`"),
1839 ));
1840 }
1841 };
1842 let max_z_mm = section
1843 .max_z_mm
1844 .ok_or_else(|| absent(ConfigField::RecoveryMaxZMm))?;
1845 if !(max_z_mm.is_finite() && max_z_mm > 0.0) {
1846 return Err(ConfigError::about(
1847 ConfigField::RecoveryMaxZMm,
1848 format!("{max_z_mm} mm is no height a machine reaches; it is a figure above zero"),
1849 ));
1850 }
1851 let max_lift_mm = section
1852 .max_lift_mm
1853 .unwrap_or_else(|| DEFAULT_MAX_LIFT_MM.min(max_z_mm));
1854 if !(max_lift_mm.is_finite() && max_lift_mm > 0.0 && max_lift_mm <= max_z_mm) {
1855 return Err(ConfigError::about(
1856 ConfigField::RecoveryMaxLiftMm,
1857 format!(
1858 "{max_lift_mm} mm is outside the lifts a machine of {max_z_mm} mm makes: above \
1859 zero, and at most `recovery.max_z_mm`"
1860 ),
1861 ));
1862 }
1863 let clearance_margin_mm = section
1864 .clearance_margin_mm
1865 .unwrap_or(DEFAULT_CLEARANCE_MARGIN_MM);
1866 if !(clearance_margin_mm.is_finite()
1867 && clearance_margin_mm >= 0.0
1868 && clearance_margin_mm < max_z_mm)
1869 {
1870 return Err(ConfigError::about(
1871 ConfigField::RecoveryClearanceMarginMm,
1872 format!(
1873 "{clearance_margin_mm} mm is outside the margins a machine of {max_z_mm} mm \
1874 admits: at or above zero, and below `recovery.max_z_mm`"
1875 ),
1876 ));
1877 }
1878 let place = |field: ConfigField, written: Option<&Vec<f64>>| match written.map(Vec::as_slice) {
1879 None => Err(absent(field)),
1880 Some([x, y]) if x.is_finite() && y.is_finite() && *x >= 0.0 && *y >= 0.0 => Ok([*x, *y]),
1881 Some(_) => Err(ConfigError::about(
1882 field,
1883 "a place is `[x, y]`, two figures in millimetres at or above zero",
1884 )),
1885 };
1886 let park_xy = place(ConfigField::RecoveryParkXy, section.park_xy.as_ref())?;
1887 let z_home_xy = place(ConfigField::RecoveryZHomeXy, section.z_home_xy.as_ref())?;
1888 let z_home_sweeps_bed = section
1889 .z_home_sweeps_bed
1890 .ok_or_else(|| absent(ConfigField::RecoveryZHomeSweepsBed))?;
1891 Ok(Some(RecoveryConfig {
1892 away_from_bed,
1893 max_z_mm,
1894 max_lift_mm,
1895 clearance_margin_mm,
1896 park_xy,
1897 z_home_xy,
1898 z_home_sweeps_bed,
1899 }))
1900}
1901
1902fn recovery_grants(section: &RecoveryPolicySection) -> Result<RecoveryGrants, ConfigError> {
1905 let defaults = RecoveryGrants::default();
1906 let actions = |field: ConfigField, written: Option<&Vec<String>>, default: Vec<_>| {
1907 let Some(written) = written else {
1908 return Ok(default);
1909 };
1910 written
1911 .iter()
1912 .map(|name| {
1913 RecoveryActionKind::ALL
1914 .iter()
1915 .find(|kind| kind.as_str() == name.trim())
1916 .copied()
1917 .ok_or_else(|| {
1918 ConfigError::about(
1919 field,
1920 format!("{name:?} is not a recovery action of this program"),
1921 )
1922 })
1923 })
1924 .collect::<Result<Vec<_>, _>>()
1925 };
1926 let operator = actions(
1927 ConfigField::PolicyRecoveryOperator,
1928 section.operator.as_ref(),
1929 defaults.operator,
1930 )?;
1931 let agent = actions(
1932 ConfigField::PolicyRecoveryAgent,
1933 section.agent.as_ref(),
1934 defaults.agent,
1935 )?;
1936 if agent.contains(&RecoveryActionKind::RecoverHomeZ) {
1939 return Err(ConfigError::about(
1940 ConfigField::PolicyRecoveryAgent,
1941 "it grants `recover_home_z` to the agent, and only a person at the machine can \
1942 say the bed is clear for Z to be homed",
1943 ));
1944 }
1945 let asserting = match section.asserting.as_ref() {
1946 None => defaults.asserting,
1947 Some(written) => written
1948 .iter()
1949 .map(|class| match class.trim() {
1950 "operator" => Ok(ActorClass::Operator),
1951 "agent" => Err(ConfigError::about(
1954 ConfigField::PolicyRecoveryAsserting,
1955 "it lets the agent assert clearance, and an assertion is a person's word \
1956 for what they can see at the machine",
1957 )),
1958 other => Err(ConfigError::about(
1959 ConfigField::PolicyRecoveryAsserting,
1960 format!("{other:?} is not an actor whose word can count; only `operator` is"),
1961 )),
1962 })
1963 .collect::<Result<Vec<_>, _>>()?,
1964 };
1965 Ok(RecoveryGrants {
1966 operator,
1967 agent,
1968 asserting,
1969 })
1970}
1971
1972fn observation_interval(seconds: u64) -> Result<core::time::Duration, ConfigError> {
1974 if seconds == 0 {
1975 return Err(ConfigError::about(
1976 ConfigField::ObservationIntervalS,
1977 "an interval of zero seconds observes a print again the moment its last turn \
1978 returns, which is a turn that never ends",
1979 ));
1980 }
1981 Ok(core::time::Duration::from_secs(seconds))
1982}
1983
1984fn compaction(
1987 auto: Option<i64>,
1988 idle: Option<i64>,
1989) -> Result<(Option<NonZeroU64>, Option<NonZeroU64>), ConfigError> {
1990 Ok((
1991 tokens(ConfigField::AutoCompactTokens, auto)?,
1992 tokens(ConfigField::IdleCompactTokens, idle)?,
1993 ))
1994}
1995
1996fn tokens(field: ConfigField, count: Option<i64>) -> Result<Option<NonZeroU64>, ConfigError> {
2000 count
2001 .map(|count| {
2002 u64::try_from(count)
2003 .ok()
2004 .and_then(NonZeroU64::new)
2005 .ok_or_else(|| {
2006 ConfigError::about(
2007 field,
2008 format!(
2009 "{count} tokens is no conversation size: it is a whole number from 1"
2010 ),
2011 )
2012 })
2013 })
2014 .transpose()
2015}
2016
2017fn seconds_within(
2019 field: ConfigField,
2020 seconds: u64,
2021 range: (u64, u64),
2022) -> Result<core::time::Duration, ConfigError> {
2023 let (least, most) = range;
2024 if !(least..=most).contains(&seconds) {
2025 return Err(ConfigError::about(
2026 field,
2027 format!("{seconds} seconds is outside the {least} to {most} seconds it admits"),
2028 ));
2029 }
2030 Ok(core::time::Duration::from_secs(seconds))
2031}
2032
2033fn blank_frame_bound(written: Option<f64>) -> Result<BlankFrameBound, ConfigError> {
2035 written.map_or(Ok(BlankFrameBound::DEFAULT), |bound| {
2036 BlankFrameBound::new(bound).map_err(|refused| {
2037 ConfigError::about(
2038 ConfigField::VisionBlankFrameMaxStddev,
2039 format!(
2040 "{refused} is outside the {MIN_BLANK_FRAME_MAX_STDDEV} to \
2041 {MAX_BLANK_FRAME_MAX_STDDEV} grey levels it admits"
2042 ),
2043 )
2044 })
2045 })
2046}
2047
2048fn answer_bound(milliseconds: u64) -> Result<core::time::Duration, ConfigError> {
2050 if milliseconds == 0 {
2051 return Err(ConfigError::about(
2052 ConfigField::IngressAnswerBoundMs,
2053 "a bound of zero is an ingress that has run out of time before it starts",
2054 ));
2055 }
2056 if milliseconds >= OBICO_POSTING_TIMEOUT_MS {
2057 return Err(ConfigError::about(
2058 ConfigField::IngressAnswerBoundMs,
2059 format!(
2060 "{milliseconds}ms is not below the {OBICO_POSTING_TIMEOUT_MS}ms Obico posts \
2061 under, so an alert answered at that bound is one Obico has already \
2062 abandoned — and its posting does not retry"
2063 ),
2064 ));
2065 }
2066 Ok(core::time::Duration::from_millis(milliseconds))
2067}
2068
2069#[cfg(test)]
2070mod tests {
2071 use super::CredentialVerifier;
2072
2073 const ABC: &str = "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
2075
2076 #[test]
2079 fn a_verifier_is_the_credentials_sha256_and_admits_only_it() {
2080 let verifier = CredentialVerifier::of("abc");
2081
2082 assert_eq!(verifier.to_string(), ABC);
2083 assert_eq!(CredentialVerifier::parse(ABC), Ok(verifier.clone()));
2084 assert!(verifier.admits(b"abc"));
2085 assert!(!verifier.admits(b"abd"));
2086 assert!(!verifier.admits(b""));
2087 }
2088
2089 #[test]
2091 fn a_verifier_in_any_other_spelling_is_refused() {
2092 for refused in [
2093 "",
2094 "sha256:",
2095 &ABC[..ABC.len() - 1],
2096 &format!("{ABC}0"),
2097 &ABC.to_uppercase(),
2098 &ABC.replace("sha256:", "sha512:"),
2099 &ABC.replace("sha256:", ""),
2100 &ABC.replace('a', "g"),
2101 ] {
2102 assert!(
2103 CredentialVerifier::parse(refused).is_err(),
2104 "{refused:?} was accepted"
2105 );
2106 }
2107 }
2108}