1use std::net::SocketAddr;
104use std::path::{Path, PathBuf};
105
106use printobserver_core::{
107 ActionKind, ActorClass, AwayFromBed, DEFAULT_CLEARANCE_MARGIN_MM, DEFAULT_MAX_LIFT_MM,
108 PreflightMode, RecoveryActionKind, RecoveryConfig, RecoveryGrants, SafetyEnvelope, SpoolPolicy,
109};
110use printobserver_obico::{
111 AccessToken, BlankFrameBound, MAX_BLANK_FRAME_MAX_STDDEV, MIN_BLANK_FRAME_MAX_STDDEV, ObicoApi,
112};
113use printobserver_octoprint::{FanSupport, OctoPrintConfig};
114use printobserver_oneharness::{HarnessIdentity, ModelName};
115use printobserver_types::schemars::JsonSchema;
116use printobserver_types::serde::{Deserialize, Serialize};
117use printobserver_vision_api::WebAddress;
118
119pub const DEFAULT_INGRESS_ANSWER_BOUND_MS: u64 = 1_000;
126
127pub const DEFAULT_OBSERVATION_INTERVAL_S: u64 =
130 printobserver_core::DEFAULT_OBSERVATION_INTERVAL.as_secs();
131
132pub const DEFAULT_PRINTER_POLL_S: u64 = printobserver_core::DEFAULT_PRINTER_POLL.as_secs();
135
136pub const PRINTER_POLL_RANGE_S: (u64, u64) = (5, 300);
138
139pub const DEFAULT_UNATTENDED_WINDOW_S: u64 =
142 printobserver_core::DEFAULT_UNATTENDED_WINDOW.as_secs();
143
144pub const UNATTENDED_WINDOW_RANGE_S: (u64, u64) = (60, 86_400);
146
147pub const OBICO_POSTING_TIMEOUT_MS: u64 = 5_000;
156
157pub const ASSETS_DIRECTORY: &str = "assets";
162
163pub const SKILL_INSTALL: &str = "the skill is installed with `gh skill install \
170 nickderobertis/printobserver printobserver --dir <dir>`, and \
171 `supervisor.skill_path` names the installed `SKILL.md`, \
172 `<dir>/printobserver/SKILL.md`";
173
174#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
180pub enum ConfigField {
181 StateDir,
183 Listen,
185 OctoprintUrl,
187 OctoprintApiKey,
189 OctoprintFan,
191 SafetyEnvelope,
193 Harness,
195 Model,
197 SkillPath,
199 PromptTemplatePath,
201 ObservationIntervalS,
203 PrinterPollS,
205 UnattendedWindowS,
208 IngressAnswerBoundMs,
210 IngressSharedSecret,
212 ApiCredential,
215 ApiCredentialVerifier,
217 CameraSnapshotUrl,
220 ObicoUrl,
222 ObicoAccessToken,
224 ObicoMlApiUrl,
226 VisionBlankFrameMaxStddev,
228 SpoolsPreflight,
230 SpoolsBufferPercent,
232 SpoolsBufferMinG,
234 SpoolsAnalysisWaitSeconds,
236 RecoveryAwayFromBed,
238 RecoveryMaxZMm,
240 RecoveryMaxLiftMm,
242 RecoveryClearanceMarginMm,
244 RecoveryParkXy,
246 RecoveryZHomeXy,
248 RecoveryZHomeSweepsBed,
250 PolicyRecoveryOperator,
252 PolicyRecoveryAgent,
254 PolicyRecoveryAsserting,
256}
257
258impl ConfigField {
259 pub const ALL: [Self; 36] = [
261 Self::StateDir,
262 Self::Listen,
263 Self::OctoprintUrl,
264 Self::OctoprintApiKey,
265 Self::OctoprintFan,
266 Self::SafetyEnvelope,
267 Self::Harness,
268 Self::Model,
269 Self::SkillPath,
270 Self::PromptTemplatePath,
271 Self::ObservationIntervalS,
272 Self::PrinterPollS,
273 Self::UnattendedWindowS,
274 Self::IngressAnswerBoundMs,
275 Self::IngressSharedSecret,
276 Self::ApiCredential,
277 Self::ApiCredentialVerifier,
278 Self::CameraSnapshotUrl,
279 Self::ObicoUrl,
280 Self::ObicoAccessToken,
281 Self::ObicoMlApiUrl,
282 Self::VisionBlankFrameMaxStddev,
283 Self::SpoolsPreflight,
284 Self::SpoolsBufferPercent,
285 Self::SpoolsBufferMinG,
286 Self::SpoolsAnalysisWaitSeconds,
287 Self::RecoveryAwayFromBed,
288 Self::RecoveryMaxZMm,
289 Self::RecoveryMaxLiftMm,
290 Self::RecoveryClearanceMarginMm,
291 Self::RecoveryParkXy,
292 Self::RecoveryZHomeXy,
293 Self::RecoveryZHomeSweepsBed,
294 Self::PolicyRecoveryOperator,
295 Self::PolicyRecoveryAgent,
296 Self::PolicyRecoveryAsserting,
297 ];
298
299 #[must_use]
301 pub const fn key(self) -> &'static str {
302 match self {
303 Self::StateDir => "state_dir",
304 Self::Listen => "listen",
305 Self::OctoprintUrl => "octoprint.url",
306 Self::OctoprintApiKey => "octoprint.api_key",
307 Self::OctoprintFan => "octoprint.fan",
308 Self::SafetyEnvelope => "safety",
309 Self::Harness => "supervisor.harness",
310 Self::Model => "supervisor.model",
311 Self::SkillPath => "supervisor.skill_path",
312 Self::PromptTemplatePath => "supervisor.prompt_template_path",
313 Self::ObservationIntervalS => "supervisor.observation_interval_s",
314 Self::PrinterPollS => "supervisor.printer_poll_s",
315 Self::UnattendedWindowS => "supervisor.unattended_window_s",
316 Self::IngressAnswerBoundMs => "ingress.answer_bound_ms",
317 Self::IngressSharedSecret => "ingress.shared_secret",
318 Self::ApiCredential => "api.credential",
319 Self::ApiCredentialVerifier => "api.credential_verifier",
320 Self::CameraSnapshotUrl => "camera.snapshot_url",
321 Self::ObicoUrl => "obico.url",
322 Self::ObicoAccessToken => "obico.access_token",
323 Self::ObicoMlApiUrl => "obico.ml_api_url",
324 Self::VisionBlankFrameMaxStddev => "vision.blank_frame_max_stddev",
325 Self::SpoolsPreflight => "spools.preflight",
326 Self::SpoolsBufferPercent => "spools.buffer_percent",
327 Self::SpoolsBufferMinG => "spools.buffer_min_g",
328 Self::SpoolsAnalysisWaitSeconds => "spools.analysis_wait_seconds",
329 Self::RecoveryAwayFromBed => "recovery.away_from_bed",
330 Self::RecoveryMaxZMm => "recovery.max_z_mm",
331 Self::RecoveryMaxLiftMm => "recovery.max_lift_mm",
332 Self::RecoveryClearanceMarginMm => "recovery.clearance_margin_mm",
333 Self::RecoveryParkXy => "recovery.park_xy",
334 Self::RecoveryZHomeXy => "recovery.z_home_xy",
335 Self::RecoveryZHomeSweepsBed => "recovery.z_home_sweeps_bed",
336 Self::PolicyRecoveryOperator => "policy.recovery.operator",
337 Self::PolicyRecoveryAgent => "policy.recovery.agent",
338 Self::PolicyRecoveryAsserting => "policy.recovery.asserting",
339 }
340 }
341}
342
343impl core::fmt::Display for ConfigField {
344 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
345 formatter.write_str(self.key())
346 }
347}
348
349#[derive(Debug, Clone, PartialEq, Eq)]
354pub enum ConfigError {
355 Unreadable {
357 path: PathBuf,
359 detail: String,
361 },
362 Unparsable {
364 path: PathBuf,
366 detail: String,
368 },
369 Field {
371 field: ConfigField,
373 detail: String,
375 },
376}
377
378impl ConfigError {
379 #[must_use]
381 pub const fn field(&self) -> Option<ConfigField> {
382 match self {
383 Self::Field { field, .. } => Some(*field),
384 _ => None,
385 }
386 }
387
388 pub(crate) fn about(field: ConfigField, detail: impl Into<String>) -> Self {
390 Self::Field {
391 field,
392 detail: detail.into(),
393 }
394 }
395}
396
397impl core::fmt::Display for ConfigError {
398 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
399 match self {
400 Self::Unreadable { path, detail } => write!(
401 formatter,
402 "the configuration file {} could not be read: {detail}",
403 path.display()
404 ),
405 Self::Unparsable { path, detail } => write!(
406 formatter,
407 "the configuration file {} could not be read as this program's \
408 configuration: {detail}",
409 path.display()
410 ),
411 Self::Field { field, detail } => write!(
412 formatter,
413 "the configuration field `{field}` cannot be accepted: {detail}"
414 ),
415 }
416 }
417}
418
419impl core::error::Error for ConfigError {}
420
421#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
423#[serde(
424 crate = "printobserver_types::serde",
425 deny_unknown_fields,
426 rename_all = "snake_case"
427)]
428#[schemars(crate = "printobserver_types::schemars")]
429pub struct OctoprintSection {
430 #[serde(default, skip_serializing_if = "Option::is_none")]
432 pub url: Option<String>,
433 #[serde(default, skip_serializing_if = "Option::is_none")]
435 pub api_key: Option<String>,
436 #[serde(default = "commandable")]
438 pub fan: String,
439}
440
441pub const FAN_VOCABULARY: [(&str, FanSupport); 2] = [
444 ("commandable", FanSupport::Commandable),
445 ("absent", FanSupport::Absent),
446];
447
448fn commandable() -> String {
450 FAN_VOCABULARY[0].0.to_owned()
451}
452
453impl Default for OctoprintSection {
454 fn default() -> Self {
455 Self {
456 url: None,
457 api_key: None,
458 fan: commandable(),
459 }
460 }
461}
462
463#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
465#[serde(
466 crate = "printobserver_types::serde",
467 deny_unknown_fields,
468 rename_all = "snake_case"
469)]
470#[schemars(crate = "printobserver_types::schemars")]
471pub struct SupervisorSection {
472 #[serde(default, skip_serializing_if = "Option::is_none")]
474 pub harness: Option<String>,
475 #[serde(default, skip_serializing_if = "Option::is_none")]
477 pub model: Option<String>,
478 #[serde(default, skip_serializing_if = "Option::is_none")]
482 pub skill_path: Option<PathBuf>,
483 #[serde(default, skip_serializing_if = "Option::is_none")]
486 pub prompt_template_path: Option<PathBuf>,
487 #[serde(default = "default_observation_interval_s")]
490 pub observation_interval_s: u64,
491 #[serde(default = "default_printer_poll_s")]
494 pub printer_poll_s: u64,
495 #[serde(default = "default_unattended_window_s")]
499 pub unattended_window_s: u64,
500}
501
502const fn default_printer_poll_s() -> u64 {
504 DEFAULT_PRINTER_POLL_S
505}
506
507const fn default_unattended_window_s() -> u64 {
509 DEFAULT_UNATTENDED_WINDOW_S
510}
511
512const fn default_observation_interval_s() -> u64 {
514 DEFAULT_OBSERVATION_INTERVAL_S
515}
516
517impl Default for SupervisorSection {
518 fn default() -> Self {
519 Self {
520 harness: None,
521 model: None,
522 skill_path: None,
523 prompt_template_path: None,
524 observation_interval_s: DEFAULT_OBSERVATION_INTERVAL_S,
525 printer_poll_s: DEFAULT_PRINTER_POLL_S,
526 unattended_window_s: DEFAULT_UNATTENDED_WINDOW_S,
527 }
528 }
529}
530
531#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
533#[serde(
534 crate = "printobserver_types::serde",
535 deny_unknown_fields,
536 rename_all = "snake_case"
537)]
538#[schemars(crate = "printobserver_types::schemars")]
539pub struct IngressSection {
540 #[serde(default, skip_serializing_if = "Option::is_none")]
542 pub shared_secret: Option<String>,
543 #[serde(default = "default_answer_bound_ms")]
545 pub answer_bound_ms: u64,
546}
547
548const fn default_answer_bound_ms() -> u64 {
550 DEFAULT_INGRESS_ANSWER_BOUND_MS
551}
552
553impl Default for IngressSection {
554 fn default() -> Self {
555 Self {
556 shared_secret: None,
557 answer_bound_ms: DEFAULT_INGRESS_ANSWER_BOUND_MS,
558 }
559 }
560}
561
562#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
564#[serde(
565 crate = "printobserver_types::serde",
566 deny_unknown_fields,
567 rename_all = "snake_case"
568)]
569#[schemars(crate = "printobserver_types::schemars")]
570pub struct ApiSection {
571 #[serde(default, skip_serializing_if = "Option::is_none")]
575 pub credential: Option<String>,
576 #[serde(default, skip_serializing_if = "Option::is_none")]
582 pub credential_verifier: Option<String>,
583}
584
585#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
587#[serde(
588 crate = "printobserver_types::serde",
589 deny_unknown_fields,
590 rename_all = "snake_case"
591)]
592#[schemars(crate = "printobserver_types::schemars")]
593pub struct CameraSection {
594 #[serde(default, skip_serializing_if = "Option::is_none")]
597 pub snapshot_url: Option<String>,
598}
599
600#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
604#[serde(
605 crate = "printobserver_types::serde",
606 deny_unknown_fields,
607 rename_all = "snake_case"
608)]
609#[schemars(crate = "printobserver_types::schemars")]
610pub struct ObicoSection {
611 #[serde(default, skip_serializing_if = "Option::is_none")]
614 pub url: Option<String>,
615 #[serde(default, skip_serializing_if = "Option::is_none")]
619 pub access_token: Option<String>,
620 #[serde(default, skip_serializing_if = "Option::is_none")]
625 pub ml_api_url: Option<String>,
626}
627
628#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
630#[serde(
631 crate = "printobserver_types::serde",
632 deny_unknown_fields,
633 rename_all = "snake_case"
634)]
635#[schemars(crate = "printobserver_types::schemars")]
636pub struct VisionSection {
637 #[serde(default, skip_serializing_if = "Option::is_none")]
640 pub blank_frame_max_stddev: Option<f64>,
641}
642
643impl core::fmt::Debug for ObicoSection {
644 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
645 formatter
646 .debug_struct("ObicoSection")
647 .field("url", &self.url)
648 .field(
649 "access_token",
650 &self.access_token.as_ref().map(|_| REDACTED),
651 )
652 .field("ml_api_url", &self.ml_api_url)
653 .finish()
654 }
655}
656
657#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
664#[serde(
665 crate = "printobserver_types::serde",
666 deny_unknown_fields,
667 rename_all = "snake_case"
668)]
669#[schemars(crate = "printobserver_types::schemars")]
670pub struct SpoolsSection {
671 #[serde(default, skip_serializing_if = "Option::is_none")]
674 pub preflight: Option<String>,
675 #[serde(default, skip_serializing_if = "Option::is_none")]
677 pub buffer_percent: Option<f64>,
678 #[serde(default, skip_serializing_if = "Option::is_none")]
680 pub buffer_min_g: Option<f64>,
681 #[serde(default, skip_serializing_if = "Option::is_none")]
684 pub analysis_wait_seconds: Option<i64>,
685}
686
687#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
694#[serde(
695 crate = "printobserver_types::serde",
696 deny_unknown_fields,
697 rename_all = "snake_case"
698)]
699#[schemars(crate = "printobserver_types::schemars")]
700pub struct RecoverySection {
701 #[serde(default, skip_serializing_if = "Option::is_none")]
704 pub away_from_bed: Option<String>,
706 #[serde(default, skip_serializing_if = "Option::is_none")]
708 pub max_z_mm: Option<f64>,
709 #[serde(default, skip_serializing_if = "Option::is_none")]
712 pub max_lift_mm: Option<f64>,
713 #[serde(default, skip_serializing_if = "Option::is_none")]
716 pub clearance_margin_mm: Option<f64>,
717 #[serde(default, skip_serializing_if = "Option::is_none")]
719 pub park_xy: Option<Vec<f64>>,
720 #[serde(default, skip_serializing_if = "Option::is_none")]
722 pub z_home_xy: Option<Vec<f64>>,
723 #[serde(default, skip_serializing_if = "Option::is_none")]
726 pub z_home_sweeps_bed: Option<bool>,
727}
728
729#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
733#[serde(
734 crate = "printobserver_types::serde",
735 deny_unknown_fields,
736 rename_all = "snake_case"
737)]
738#[schemars(crate = "printobserver_types::schemars")]
739pub struct RecoveryPolicySection {
740 #[serde(default, skip_serializing_if = "Option::is_none")]
742 pub operator: Option<Vec<String>>,
744 #[serde(default, skip_serializing_if = "Option::is_none")]
747 pub agent: Option<Vec<String>>,
749 #[serde(default, skip_serializing_if = "Option::is_none")]
752 pub asserting: Option<Vec<String>>,
754}
755
756#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
758#[serde(
759 crate = "printobserver_types::serde",
760 deny_unknown_fields,
761 rename_all = "snake_case"
762)]
763#[schemars(crate = "printobserver_types::schemars")]
764pub struct PolicySection {
765 #[serde(default)]
767 pub recovery: RecoveryPolicySection,
768}
769
770#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
776#[serde(
777 crate = "printobserver_types::serde",
778 deny_unknown_fields,
779 rename_all = "snake_case"
780)]
781#[schemars(crate = "printobserver_types::schemars")]
782pub struct ConfigFile {
783 #[serde(default, skip_serializing_if = "Option::is_none")]
785 pub state_dir: Option<PathBuf>,
786 #[serde(default, skip_serializing_if = "Option::is_none")]
788 pub listen: Option<String>,
789 #[serde(default)]
791 pub octoprint: OctoprintSection,
792 #[serde(default, skip_serializing_if = "Option::is_none")]
794 pub safety: Option<SafetyEnvelope>,
795 #[serde(default)]
797 pub supervisor: SupervisorSection,
798 #[serde(default)]
800 pub ingress: IngressSection,
801 #[serde(default)]
803 pub api: ApiSection,
804 #[serde(default)]
806 pub camera: CameraSection,
807 #[serde(default)]
809 pub obico: ObicoSection,
810 #[serde(default)]
812 pub vision: VisionSection,
813 #[serde(default)]
815 pub spools: SpoolsSection,
816 #[serde(default)]
818 pub recovery: RecoverySection,
819 #[serde(default)]
821 pub policy: PolicySection,
822}
823
824#[derive(Clone, PartialEq, Eq)]
831pub struct SharedSecret(String);
832
833pub const REDACTED: &str = "<redacted>";
835
836impl SharedSecret {
837 pub fn new(value: &str) -> Result<Self, ConfigError> {
845 if value.trim().is_empty() {
846 return Err(ConfigError::about(
847 ConfigField::IngressSharedSecret,
848 "it is empty, and anything that can post to the ingress can pause a printer",
849 ));
850 }
851 Ok(Self(value.to_owned()))
852 }
853
854 #[must_use]
861 pub fn matches(&self, offered: Option<&str>) -> bool {
862 let Some(offered) = offered else {
863 return false;
864 };
865 let expected = self.0.as_bytes();
866 let mut difference = expected.len() ^ offered.len();
867 for (index, byte) in offered.bytes().enumerate() {
868 let against = expected[index % expected.len().max(1)];
869 difference |= usize::from(byte ^ against);
870 }
871 difference == 0
872 }
873}
874
875impl core::fmt::Display for SharedSecret {
876 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
877 formatter.write_str(REDACTED)
878 }
879}
880
881impl core::fmt::Debug for SharedSecret {
882 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
883 write!(formatter, "SharedSecret({REDACTED})")
884 }
885}
886
887pub const GENERATED_CREDENTIAL_BYTES: usize = 32;
889
890#[derive(Clone)]
900pub struct ApiCredential(String);
901
902impl ApiCredential {
903 pub fn new(value: &str) -> Result<Self, &'static str> {
912 if value.trim().is_empty() {
913 return Err(
914 "it is empty, and anything that can reach this server's API can command a printer",
915 );
916 }
917 if !value.bytes().all(|byte| (b' '..=b'~').contains(&byte)) {
918 return Err(
919 "it carries a control character or a character outside printable ASCII, which \
920 no `Authorization` header carries intact",
921 );
922 }
923 if value.starts_with(' ') || value.ends_with(' ') {
924 return Err(
925 "it begins or ends with a space, which an `Authorization` header does not carry",
926 );
927 }
928 Ok(Self(value.to_owned()))
930 }
931
932 pub fn generate() -> Result<Self, getrandom::Error> {
942 use base64::Engine as _;
943
944 let mut drawn = [0_u8; GENERATED_CREDENTIAL_BYTES];
945 getrandom::fill(&mut drawn)?;
946 Ok(Self(
947 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(drawn),
948 ))
949 }
950
951 #[must_use]
957 pub fn admits(&self, presented: &[u8]) -> bool {
958 use subtle::ConstantTimeEq as _;
959
960 let expected = self.0.as_bytes();
961 expected.len() == presented.len() && bool::from(expected.ct_eq(presented))
962 }
963
964 #[must_use]
967 pub fn written(&self) -> &str {
968 &self.0
969 }
970
971 #[must_use]
973 pub fn verifier(&self) -> CredentialVerifier {
974 CredentialVerifier::of(&self.0)
975 }
976}
977
978impl PartialEq for ApiCredential {
979 fn eq(&self, other: &Self) -> bool {
980 self.admits(other.0.as_bytes())
981 }
982}
983
984impl Eq for ApiCredential {}
985
986impl core::fmt::Display for ApiCredential {
987 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
988 formatter.write_str(REDACTED)
989 }
990}
991
992impl core::fmt::Debug for ApiCredential {
993 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
994 write!(formatter, "ApiCredential({REDACTED})")
995 }
996}
997
998pub const VERIFIER_PREFIX: &str = "sha256:";
1000
1001const VERIFIER_DIGITS: usize = 64;
1003
1004#[derive(Clone, PartialEq, Eq)]
1015pub struct CredentialVerifier([u8; 32]);
1016
1017impl CredentialVerifier {
1018 #[must_use]
1020 pub fn of(credential: &str) -> Self {
1021 use sha2::Digest as _;
1022
1023 Self(sha2::Sha256::digest(credential.as_bytes()).into())
1024 }
1025
1026 pub fn parse(text: &str) -> Result<Self, &'static str> {
1033 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";
1034 let digits = text.strip_prefix(VERIFIER_PREFIX).ok_or(SHAPE)?;
1035 if digits.len() != VERIFIER_DIGITS
1036 || !digits
1037 .bytes()
1038 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1039 {
1040 return Err(SHAPE);
1041 }
1042 let mut digest = [0_u8; 32];
1043 for (index, pair) in digits.as_bytes().chunks(2).enumerate() {
1044 let high = hex_value(pair[0]);
1045 let low = hex_value(pair[1]);
1046 digest[index] = (high << 4) | low;
1047 }
1048 Ok(Self(digest))
1049 }
1050
1051 #[must_use]
1057 pub fn admits(&self, presented: &[u8]) -> bool {
1058 use sha2::Digest as _;
1059 use subtle::ConstantTimeEq as _;
1060
1061 let offered: [u8; 32] = sha2::Sha256::digest(presented).into();
1062 bool::from(self.0.ct_eq(&offered))
1063 }
1064}
1065
1066const fn hex_value(digit: u8) -> u8 {
1068 if digit.is_ascii_digit() {
1069 digit - b'0'
1070 } else {
1071 digit - b'a' + 10
1072 }
1073}
1074
1075impl core::fmt::Display for CredentialVerifier {
1076 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1077 formatter.write_str(VERIFIER_PREFIX)?;
1078 for byte in self.0 {
1079 write!(formatter, "{byte:02x}")?;
1080 }
1081 Ok(())
1082 }
1083}
1084
1085impl core::fmt::Debug for CredentialVerifier {
1086 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1087 write!(formatter, "CredentialVerifier({self})")
1088 }
1089}
1090
1091#[derive(Debug, Clone, PartialEq)]
1100pub struct ServerConfig {
1101 pub state_dir: PathBuf,
1103 pub listen: SocketAddr,
1105 pub octoprint: OctoPrintConfig,
1107 pub safety: SafetyEnvelope,
1109 pub harness: HarnessIdentity,
1111 pub model: Option<ModelName>,
1113 pub skill_path: PathBuf,
1117 pub prompt_template_path: Option<PathBuf>,
1119 pub observation_interval: core::time::Duration,
1121 pub printer_poll: core::time::Duration,
1123 pub unattended_window: core::time::Duration,
1126 pub blank_frame_max_stddev: BlankFrameBound,
1128 pub obico_ml_api_url: Option<WebAddress>,
1131 pub ingress_answer_bound: core::time::Duration,
1133 pub ingress_shared_secret: SharedSecret,
1135 pub api_credential: Option<ApiCredential>,
1139 pub api_credential_verifier: Option<CredentialVerifier>,
1143 pub camera_snapshot_url: Option<WebAddress>,
1145 pub obico_api: Option<ObicoApi>,
1147 pub spools: SpoolPolicy,
1149 pub recovery: Option<RecoveryConfig>,
1151 pub recovery_grants: RecoveryGrants,
1153}
1154
1155impl ServerConfig {
1156 pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
1167 let path = path.as_ref();
1168 Self::parse(&read(path)?, path)
1169 }
1170
1171 pub fn parse(text: &str, path: &Path) -> Result<Self, ConfigError> {
1177 let file: ConfigFile = toml::from_str(text).map_err(|error| ConfigError::Unparsable {
1178 path: path.to_path_buf(),
1179 detail: error.to_string(),
1180 })?;
1181 Self::validate(file)
1182 }
1183
1184 fn validate(file: ConfigFile) -> Result<Self, ConfigError> {
1191 let state_dir =
1192 state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?;
1193 let listen = listen_address(&required(ConfigField::Listen, file.listen)?)?;
1194 let octoprint = octoprint(&file.octoprint)?;
1195 let safety = required(ConfigField::SafetyEnvelope, file.safety)?;
1196 check_envelope(&safety)?;
1197 let harness = harness_identity(file.supervisor.harness)?;
1198 let model = match file.supervisor.model {
1199 None => None,
1200 Some(name) => Some(
1201 ModelName::new(&named(ConfigField::Model, Some(name))?)
1202 .map_err(|error| ConfigError::about(ConfigField::Model, error.to_string()))?,
1203 ),
1204 };
1205 let skill_path = skill(file.supervisor.skill_path.as_deref())?;
1206 let prompt_template_path = readable(
1207 ConfigField::PromptTemplatePath,
1208 file.supervisor.prompt_template_path.as_deref(),
1209 )?;
1210 let observation_interval = observation_interval(file.supervisor.observation_interval_s)?;
1211 let printer_poll = seconds_within(
1212 ConfigField::PrinterPollS,
1213 file.supervisor.printer_poll_s,
1214 PRINTER_POLL_RANGE_S,
1215 )?;
1216 let unattended_window = seconds_within(
1217 ConfigField::UnattendedWindowS,
1218 file.supervisor.unattended_window_s,
1219 UNATTENDED_WINDOW_RANGE_S,
1220 )?;
1221 let blank_frame_max_stddev = blank_frame_bound(file.vision.blank_frame_max_stddev)?;
1222 let obico_ml_api_url = file
1223 .obico
1224 .ml_api_url
1225 .as_deref()
1226 .map(|url| web_address(ConfigField::ObicoMlApiUrl, url))
1227 .transpose()?;
1228 let ingress_answer_bound = answer_bound(file.ingress.answer_bound_ms)?;
1229 let ingress_shared_secret = SharedSecret::new(&required(
1230 ConfigField::IngressSharedSecret,
1231 file.ingress.shared_secret,
1232 )?)?;
1233 let api_credential = file
1234 .api
1235 .credential
1236 .as_deref()
1237 .map(|value| {
1238 ApiCredential::new(value)
1239 .map_err(|why| ConfigError::about(ConfigField::ApiCredential, why))
1240 })
1241 .transpose()?;
1242 let api_credential_verifier = file
1243 .api
1244 .credential_verifier
1245 .as_deref()
1246 .map(|value| {
1247 CredentialVerifier::parse(value.trim())
1248 .map_err(|why| ConfigError::about(ConfigField::ApiCredentialVerifier, why))
1249 })
1250 .transpose()?;
1251 let camera_snapshot_url = file
1252 .camera
1253 .snapshot_url
1254 .map(|url| web_address(ConfigField::CameraSnapshotUrl, &url))
1255 .transpose()?;
1256 let obico_api = obico_api(file.obico)?;
1257 let spools = spool_policy(&file.spools)?;
1258 let recovery = recovery_facts(&file.recovery)?;
1259 let recovery_grants = recovery_grants(&file.policy.recovery)?;
1260 Ok(Self {
1261 state_dir,
1262 listen,
1263 octoprint,
1264 safety,
1265 harness,
1266 model,
1267 skill_path,
1268 prompt_template_path,
1269 observation_interval,
1270 printer_poll,
1271 unattended_window,
1272 blank_frame_max_stddev,
1273 obico_ml_api_url,
1274 ingress_answer_bound,
1275 ingress_shared_secret,
1276 api_credential,
1277 api_credential_verifier,
1278 camera_snapshot_url,
1279 obico_api,
1280 spools,
1281 recovery,
1282 recovery_grants,
1283 })
1284 }
1285
1286 #[must_use]
1290 pub fn assets_dir(&self) -> PathBuf {
1291 self.state_dir.join(ASSETS_DIRECTORY)
1292 }
1293}
1294
1295fn web_address(field: ConfigField, url: &str) -> Result<WebAddress, ConfigError> {
1298 WebAddress::new(url).map_err(|why| ConfigError::about(field, why))
1299}
1300
1301fn obico_api(section: ObicoSection) -> Result<Option<ObicoApi>, ConfigError> {
1307 match (section.url, section.access_token) {
1308 (None, None) => Ok(None),
1309 (Some(_), None) => Err(ConfigError::about(
1310 ConfigField::ObicoAccessToken,
1311 "it is required when obico.url is given",
1312 )),
1313 (None, Some(_)) => Err(ConfigError::about(
1314 ConfigField::ObicoUrl,
1315 "it is required when obico.access_token is given",
1316 )),
1317 (Some(url), Some(access_token)) => {
1318 let url = web_address(ConfigField::ObicoUrl, &url)?;
1319 let access_token = AccessToken::new(&access_token)
1320 .map_err(|why| ConfigError::about(ConfigField::ObicoAccessToken, why))?;
1321 Ok(Some(ObicoApi::new(url, access_token)))
1322 }
1323 }
1324}
1325
1326#[derive(Debug, Clone, PartialEq, Eq)]
1334pub struct SignInConfig {
1335 pub state_dir: PathBuf,
1337 pub harness: HarnessIdentity,
1339}
1340
1341impl SignInConfig {
1342 pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
1352 let path = path.as_ref();
1353 let file: SignInFile =
1354 toml::from_str(&read(path)?).map_err(|error| ConfigError::Unparsable {
1355 path: path.to_path_buf(),
1356 detail: error.to_string(),
1357 })?;
1358 Ok(Self {
1359 state_dir: state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?,
1360 harness: harness_identity(file.supervisor.harness)?,
1361 })
1362 }
1363}
1364
1365#[derive(Deserialize)]
1370#[serde(crate = "printobserver_types::serde")]
1371struct SignInFile {
1372 #[serde(default)]
1374 state_dir: Option<PathBuf>,
1375 #[serde(default)]
1377 supervisor: SignInSupervisor,
1378}
1379
1380#[derive(Default, Deserialize)]
1382#[serde(crate = "printobserver_types::serde")]
1383struct SignInSupervisor {
1384 #[serde(default)]
1386 harness: Option<String>,
1387}
1388
1389fn read(path: &Path) -> Result<String, ConfigError> {
1391 std::fs::read_to_string(path).map_err(|error| ConfigError::Unreadable {
1392 path: path.to_path_buf(),
1393 detail: error.to_string(),
1394 })
1395}
1396
1397fn harness_identity(value: Option<String>) -> Result<HarnessIdentity, ConfigError> {
1399 HarnessIdentity::new(&named(ConfigField::Harness, value)?)
1400 .map_err(|error| ConfigError::about(ConfigField::Harness, error.to_string()))
1401}
1402
1403fn required<T>(field: ConfigField, value: Option<T>) -> Result<T, ConfigError> {
1405 value.ok_or_else(|| ConfigError::about(field, "the configuration file carries no value for it"))
1406}
1407
1408fn named(field: ConfigField, value: Option<String>) -> Result<String, ConfigError> {
1410 let value = required(field, value)?;
1411 if value.trim().is_empty() {
1412 return Err(ConfigError::about(
1413 field,
1414 "it is empty, and an empty value names nothing",
1415 ));
1416 }
1417 Ok(value.trim().to_owned())
1418}
1419
1420fn state_directory(named: &Path) -> Result<PathBuf, ConfigError> {
1422 if named.as_os_str().is_empty() {
1423 return Err(ConfigError::about(
1424 ConfigField::StateDir,
1425 "it names no directory, and this server's whole state lives in one",
1426 ));
1427 }
1428 std::fs::create_dir_all(named).map_err(|error| {
1429 ConfigError::about(
1430 ConfigField::StateDir,
1431 format!("{} cannot be created: {error}", named.display()),
1432 )
1433 })?;
1434 named.canonicalize().map(plainly_written).map_err(|error| {
1435 ConfigError::about(
1436 ConfigField::StateDir,
1437 format!("{} cannot be resolved: {error}", named.display()),
1438 )
1439 })
1440}
1441
1442#[must_use]
1451pub fn plainly_written(path: PathBuf) -> PathBuf {
1452 const VERBATIM: &str = r"\\?\";
1453 let drive = path
1454 .to_str()
1455 .and_then(|text| text.strip_prefix(VERBATIM))
1456 .filter(|rest| {
1457 let bytes = rest.as_bytes();
1458 bytes.len() >= 3
1459 && bytes[0].is_ascii_alphabetic()
1460 && bytes[1] == b':'
1461 && bytes[2] == b'\\'
1462 })
1463 .map(PathBuf::from);
1464 drive.unwrap_or(path)
1465}
1466
1467fn listen_address(named: &str) -> Result<SocketAddr, ConfigError> {
1469 named.trim().parse().map_err(|error| {
1470 ConfigError::about(
1471 ConfigField::Listen,
1472 format!("{named:?} is no address to listen on: {error}"),
1473 )
1474 })
1475}
1476
1477fn octoprint(section: &OctoprintSection) -> Result<OctoPrintConfig, ConfigError> {
1480 let fan = fan_support(§ion.fan)?;
1481 let url = named(ConfigField::OctoprintUrl, section.url.clone())?;
1482 let key = named(ConfigField::OctoprintApiKey, section.api_key.clone())?;
1483 OctoPrintConfig::new(&url, key)
1484 .map(|configured| configured.with_fan(fan))
1485 .map_err(|error| {
1486 let field = match error {
1487 printobserver_octoprint::ConfigError::EmptyApiKey => ConfigField::OctoprintApiKey,
1488 _ => ConfigField::OctoprintUrl,
1489 };
1490 ConfigError::about(field, error.to_string())
1491 })
1492}
1493
1494fn fan_support(named: &str) -> Result<FanSupport, ConfigError> {
1496 FAN_VOCABULARY
1497 .iter()
1498 .find(|(spelling, _)| *spelling == named.trim())
1499 .map(|(_, support)| *support)
1500 .ok_or_else(|| {
1501 let vocabulary: Vec<&str> = FAN_VOCABULARY.iter().map(|(word, _)| *word).collect();
1502 ConfigError::about(
1503 ConfigField::OctoprintFan,
1504 format!("{named:?} is not one of {}", vocabulary.join(" or ")),
1505 )
1506 })
1507}
1508
1509fn check_envelope(envelope: &SafetyEnvelope) -> Result<(), ConfigError> {
1511 if envelope.allowed.is_empty() {
1512 return Err(ConfigError::about(
1513 ConfigField::SafetyEnvelope,
1514 "it allows no adjustable at all, so no adjustment could ever be accepted",
1515 ));
1516 }
1517 for (adjustable, range) in &envelope.allowed {
1518 if !range.min.is_finite() || !range.max.is_finite() || range.min > range.max {
1519 return Err(ConfigError::about(
1520 ConfigField::SafetyEnvelope,
1521 format!(
1522 "the range allowed for {adjustable} runs from {} to {}, which admits \
1523 no value",
1524 range.min, range.max
1525 ),
1526 ));
1527 }
1528 }
1529 if envelope
1532 .actions
1533 .get(&ActorClass::Agent)
1534 .is_some_and(|granted| granted.contains(&ActionKind::ClosePrint))
1535 {
1536 return Err(ConfigError::about(
1537 ConfigField::SafetyEnvelope,
1538 "it grants `close_print` to the agent, and closing a print record is the \
1539 operator's judgement that the print is over",
1540 ));
1541 }
1542 if envelope.agent_min_interval_s < 0 {
1543 return Err(ConfigError::about(
1544 ConfigField::SafetyEnvelope,
1545 format!(
1546 "the agent's minimum interval is {}s, and an interval is a count of seconds",
1547 envelope.agent_min_interval_s
1548 ),
1549 ));
1550 }
1551 Ok(())
1552}
1553
1554fn readable(field: ConfigField, named: Option<&Path>) -> Result<Option<PathBuf>, ConfigError> {
1557 let Some(path) = named else {
1558 return Ok(None);
1559 };
1560 std::fs::read_to_string(path)
1561 .map(|_| Some(path.to_path_buf()))
1562 .map_err(|error| {
1563 ConfigError::about(field, format!("{} cannot be read: {error}", path.display()))
1564 })
1565}
1566
1567fn skill(named: Option<&Path>) -> Result<PathBuf, ConfigError> {
1570 let Some(path) = named else {
1571 return Err(ConfigError::about(
1572 ConfigField::SkillPath,
1573 format!(
1574 "the configuration file carries no value for it, and this program carries \
1575 no skill of its own: {SKILL_INSTALL}"
1576 ),
1577 ));
1578 };
1579 std::fs::read_to_string(path)
1580 .map(|_| path.to_path_buf())
1581 .map_err(|error| {
1582 ConfigError::about(
1583 ConfigField::SkillPath,
1584 format!(
1585 "{} cannot be read: {error}. {SKILL_INSTALL}",
1586 path.display()
1587 ),
1588 )
1589 })
1590}
1591
1592fn spool_policy(section: &SpoolsSection) -> Result<SpoolPolicy, ConfigError> {
1594 let defaults = SpoolPolicy::default();
1595 let preflight = match section.preflight.as_deref() {
1596 None => defaults.preflight,
1597 Some("refuse") => PreflightMode::Refuse,
1598 Some("warn") => PreflightMode::Warn,
1599 Some("off") => PreflightMode::Off,
1600 Some(_) => {
1601 return Err(ConfigError::about(
1602 ConfigField::SpoolsPreflight,
1603 "the spool check is one of `refuse`, `warn` or `off`",
1604 ));
1605 }
1606 };
1607 let margin = |field: ConfigField, value: Option<f64>, default: f64| match value {
1608 None => Ok(default),
1609 Some(value) if value.is_finite() && value >= 0.0 => Ok(value),
1610 Some(_) => Err(ConfigError::about(
1611 field,
1612 "a margin is a figure at or above zero; a negative one asks a spool for less \
1613 than the print needs",
1614 )),
1615 };
1616 let buffer_percent = margin(
1617 ConfigField::SpoolsBufferPercent,
1618 section.buffer_percent,
1619 defaults.buffer_percent,
1620 )?;
1621 let buffer_min_g = margin(
1622 ConfigField::SpoolsBufferMinG,
1623 section.buffer_min_g,
1624 defaults.buffer_min_g,
1625 )?;
1626 let analysis_wait_s = match section.analysis_wait_seconds {
1627 None => defaults.analysis_wait_s,
1628 Some(seconds) => u64::try_from(seconds).map_err(|_| {
1629 ConfigError::about(
1630 ConfigField::SpoolsAnalysisWaitSeconds,
1631 "a wait is a number of seconds at or above zero",
1632 )
1633 })?,
1634 };
1635 Ok(SpoolPolicy {
1636 preflight,
1637 buffer_percent,
1638 buffer_min_g,
1639 analysis_wait_s,
1640 })
1641}
1642
1643fn recovery_facts(section: &RecoverySection) -> Result<Option<RecoveryConfig>, ConfigError> {
1645 if *section == RecoverySection::default() {
1646 return Ok(None);
1647 }
1648 let absent = |field: ConfigField| {
1649 ConfigError::about(
1650 field,
1651 "`[recovery]` states this printer's facts, and this one is one of them",
1652 )
1653 };
1654 let away_from_bed = match section.away_from_bed.as_deref() {
1655 None => return Err(absent(ConfigField::RecoveryAwayFromBed)),
1656 Some("z_plus") => AwayFromBed::ZPlus,
1657 Some("z_minus") => AwayFromBed::ZMinus,
1658 Some(other) => {
1659 return Err(ConfigError::about(
1660 ConfigField::RecoveryAwayFromBed,
1661 format!("{other:?} is neither `z_plus` nor `z_minus`"),
1662 ));
1663 }
1664 };
1665 let max_z_mm = section
1666 .max_z_mm
1667 .ok_or_else(|| absent(ConfigField::RecoveryMaxZMm))?;
1668 if !(max_z_mm.is_finite() && max_z_mm > 0.0) {
1669 return Err(ConfigError::about(
1670 ConfigField::RecoveryMaxZMm,
1671 format!("{max_z_mm} mm is no height a machine reaches; it is a figure above zero"),
1672 ));
1673 }
1674 let max_lift_mm = section
1675 .max_lift_mm
1676 .unwrap_or_else(|| DEFAULT_MAX_LIFT_MM.min(max_z_mm));
1677 if !(max_lift_mm.is_finite() && max_lift_mm > 0.0 && max_lift_mm <= max_z_mm) {
1678 return Err(ConfigError::about(
1679 ConfigField::RecoveryMaxLiftMm,
1680 format!(
1681 "{max_lift_mm} mm is outside the lifts a machine of {max_z_mm} mm makes: above \
1682 zero, and at most `recovery.max_z_mm`"
1683 ),
1684 ));
1685 }
1686 let clearance_margin_mm = section
1687 .clearance_margin_mm
1688 .unwrap_or(DEFAULT_CLEARANCE_MARGIN_MM);
1689 if !(clearance_margin_mm.is_finite()
1690 && clearance_margin_mm >= 0.0
1691 && clearance_margin_mm < max_z_mm)
1692 {
1693 return Err(ConfigError::about(
1694 ConfigField::RecoveryClearanceMarginMm,
1695 format!(
1696 "{clearance_margin_mm} mm is outside the margins a machine of {max_z_mm} mm \
1697 admits: at or above zero, and below `recovery.max_z_mm`"
1698 ),
1699 ));
1700 }
1701 let place = |field: ConfigField, written: Option<&Vec<f64>>| match written.map(Vec::as_slice) {
1702 None => Err(absent(field)),
1703 Some([x, y]) if x.is_finite() && y.is_finite() && *x >= 0.0 && *y >= 0.0 => Ok([*x, *y]),
1704 Some(_) => Err(ConfigError::about(
1705 field,
1706 "a place is `[x, y]`, two figures in millimetres at or above zero",
1707 )),
1708 };
1709 let park_xy = place(ConfigField::RecoveryParkXy, section.park_xy.as_ref())?;
1710 let z_home_xy = place(ConfigField::RecoveryZHomeXy, section.z_home_xy.as_ref())?;
1711 let z_home_sweeps_bed = section
1712 .z_home_sweeps_bed
1713 .ok_or_else(|| absent(ConfigField::RecoveryZHomeSweepsBed))?;
1714 Ok(Some(RecoveryConfig {
1715 away_from_bed,
1716 max_z_mm,
1717 max_lift_mm,
1718 clearance_margin_mm,
1719 park_xy,
1720 z_home_xy,
1721 z_home_sweeps_bed,
1722 }))
1723}
1724
1725fn recovery_grants(section: &RecoveryPolicySection) -> Result<RecoveryGrants, ConfigError> {
1728 let defaults = RecoveryGrants::default();
1729 let actions = |field: ConfigField, written: Option<&Vec<String>>, default: Vec<_>| {
1730 let Some(written) = written else {
1731 return Ok(default);
1732 };
1733 written
1734 .iter()
1735 .map(|name| {
1736 RecoveryActionKind::ALL
1737 .iter()
1738 .find(|kind| kind.as_str() == name.trim())
1739 .copied()
1740 .ok_or_else(|| {
1741 ConfigError::about(
1742 field,
1743 format!("{name:?} is not a recovery action of this program"),
1744 )
1745 })
1746 })
1747 .collect::<Result<Vec<_>, _>>()
1748 };
1749 let operator = actions(
1750 ConfigField::PolicyRecoveryOperator,
1751 section.operator.as_ref(),
1752 defaults.operator,
1753 )?;
1754 let agent = actions(
1755 ConfigField::PolicyRecoveryAgent,
1756 section.agent.as_ref(),
1757 defaults.agent,
1758 )?;
1759 if agent.contains(&RecoveryActionKind::RecoverHomeZ) {
1762 return Err(ConfigError::about(
1763 ConfigField::PolicyRecoveryAgent,
1764 "it grants `recover_home_z` to the agent, and only a person at the machine can \
1765 say the bed is clear for Z to be homed",
1766 ));
1767 }
1768 let asserting = match section.asserting.as_ref() {
1769 None => defaults.asserting,
1770 Some(written) => written
1771 .iter()
1772 .map(|class| match class.trim() {
1773 "operator" => Ok(ActorClass::Operator),
1774 "agent" => Err(ConfigError::about(
1777 ConfigField::PolicyRecoveryAsserting,
1778 "it lets the agent assert clearance, and an assertion is a person's word \
1779 for what they can see at the machine",
1780 )),
1781 other => Err(ConfigError::about(
1782 ConfigField::PolicyRecoveryAsserting,
1783 format!("{other:?} is not an actor whose word can count; only `operator` is"),
1784 )),
1785 })
1786 .collect::<Result<Vec<_>, _>>()?,
1787 };
1788 Ok(RecoveryGrants {
1789 operator,
1790 agent,
1791 asserting,
1792 })
1793}
1794
1795fn observation_interval(seconds: u64) -> Result<core::time::Duration, ConfigError> {
1797 if seconds == 0 {
1798 return Err(ConfigError::about(
1799 ConfigField::ObservationIntervalS,
1800 "an interval of zero seconds observes a print again the moment its last turn \
1801 returns, which is a turn that never ends",
1802 ));
1803 }
1804 Ok(core::time::Duration::from_secs(seconds))
1805}
1806
1807fn seconds_within(
1809 field: ConfigField,
1810 seconds: u64,
1811 range: (u64, u64),
1812) -> Result<core::time::Duration, ConfigError> {
1813 let (least, most) = range;
1814 if !(least..=most).contains(&seconds) {
1815 return Err(ConfigError::about(
1816 field,
1817 format!("{seconds} seconds is outside the {least} to {most} seconds it admits"),
1818 ));
1819 }
1820 Ok(core::time::Duration::from_secs(seconds))
1821}
1822
1823fn blank_frame_bound(written: Option<f64>) -> Result<BlankFrameBound, ConfigError> {
1825 written.map_or(Ok(BlankFrameBound::DEFAULT), |bound| {
1826 BlankFrameBound::new(bound).map_err(|refused| {
1827 ConfigError::about(
1828 ConfigField::VisionBlankFrameMaxStddev,
1829 format!(
1830 "{refused} is outside the {MIN_BLANK_FRAME_MAX_STDDEV} to \
1831 {MAX_BLANK_FRAME_MAX_STDDEV} grey levels it admits"
1832 ),
1833 )
1834 })
1835 })
1836}
1837
1838fn answer_bound(milliseconds: u64) -> Result<core::time::Duration, ConfigError> {
1840 if milliseconds == 0 {
1841 return Err(ConfigError::about(
1842 ConfigField::IngressAnswerBoundMs,
1843 "a bound of zero is an ingress that has run out of time before it starts",
1844 ));
1845 }
1846 if milliseconds >= OBICO_POSTING_TIMEOUT_MS {
1847 return Err(ConfigError::about(
1848 ConfigField::IngressAnswerBoundMs,
1849 format!(
1850 "{milliseconds}ms is not below the {OBICO_POSTING_TIMEOUT_MS}ms Obico posts \
1851 under, so an alert answered at that bound is one Obico has already \
1852 abandoned — and its posting does not retry"
1853 ),
1854 ));
1855 }
1856 Ok(core::time::Duration::from_millis(milliseconds))
1857}
1858
1859#[cfg(test)]
1860mod tests {
1861 use super::CredentialVerifier;
1862
1863 const ABC: &str = "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
1865
1866 #[test]
1869 fn a_verifier_is_the_credentials_sha256_and_admits_only_it() {
1870 let verifier = CredentialVerifier::of("abc");
1871
1872 assert_eq!(verifier.to_string(), ABC);
1873 assert_eq!(CredentialVerifier::parse(ABC), Ok(verifier.clone()));
1874 assert!(verifier.admits(b"abc"));
1875 assert!(!verifier.admits(b"abd"));
1876 assert!(!verifier.admits(b""));
1877 }
1878
1879 #[test]
1881 fn a_verifier_in_any_other_spelling_is_refused() {
1882 for refused in [
1883 "",
1884 "sha256:",
1885 &ABC[..ABC.len() - 1],
1886 &format!("{ABC}0"),
1887 &ABC.to_uppercase(),
1888 &ABC.replace("sha256:", "sha512:"),
1889 &ABC.replace("sha256:", ""),
1890 &ABC.replace('a', "g"),
1891 ] {
1892 assert!(
1893 CredentialVerifier::parse(refused).is_err(),
1894 "{refused:?} was accepted"
1895 );
1896 }
1897 }
1898}