1use std::net::SocketAddr;
91use std::path::{Path, PathBuf};
92
93use printobserver_core::{ActionKind, ActorClass, PreflightMode, SafetyEnvelope, SpoolPolicy};
94use printobserver_obico::{
95 AccessToken, BlankFrameBound, MAX_BLANK_FRAME_MAX_STDDEV, MIN_BLANK_FRAME_MAX_STDDEV, ObicoApi,
96};
97use printobserver_octoprint::{FanSupport, OctoPrintConfig};
98use printobserver_oneharness::{HarnessIdentity, ModelName};
99use printobserver_types::schemars::JsonSchema;
100use printobserver_types::serde::{Deserialize, Serialize};
101use printobserver_vision_api::WebAddress;
102
103pub const DEFAULT_INGRESS_ANSWER_BOUND_MS: u64 = 1_000;
110
111pub const DEFAULT_OBSERVATION_INTERVAL_S: u64 =
114 printobserver_core::DEFAULT_OBSERVATION_INTERVAL.as_secs();
115
116pub const DEFAULT_PRINTER_POLL_S: u64 = printobserver_core::DEFAULT_PRINTER_POLL.as_secs();
119
120pub const PRINTER_POLL_RANGE_S: (u64, u64) = (5, 300);
122
123pub const DEFAULT_UNATTENDED_WINDOW_S: u64 =
126 printobserver_core::DEFAULT_UNATTENDED_WINDOW.as_secs();
127
128pub const UNATTENDED_WINDOW_RANGE_S: (u64, u64) = (60, 86_400);
130
131pub const OBICO_POSTING_TIMEOUT_MS: u64 = 5_000;
140
141pub const ASSETS_DIRECTORY: &str = "assets";
146
147pub const SKILL_INSTALL: &str = "the skill is installed with `gh skill install \
154 nickderobertis/printobserver printobserver --dir <dir>`, and \
155 `supervisor.skill_path` names the installed `SKILL.md`, \
156 `<dir>/printobserver/SKILL.md`";
157
158#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
164pub enum ConfigField {
165 StateDir,
167 Listen,
169 OctoprintUrl,
171 OctoprintApiKey,
173 OctoprintFan,
175 SafetyEnvelope,
177 Harness,
179 Model,
181 SkillPath,
183 PromptTemplatePath,
185 ObservationIntervalS,
187 PrinterPollS,
189 UnattendedWindowS,
192 IngressAnswerBoundMs,
194 IngressSharedSecret,
196 ApiCredential,
199 ApiCredentialVerifier,
201 CameraSnapshotUrl,
204 ObicoUrl,
206 ObicoAccessToken,
208 ObicoMlApiUrl,
210 VisionBlankFrameMaxStddev,
212 SpoolsPreflight,
214 SpoolsBufferPercent,
216 SpoolsBufferMinG,
218 SpoolsAnalysisWaitSeconds,
220}
221
222impl ConfigField {
223 pub const ALL: [Self; 26] = [
225 Self::StateDir,
226 Self::Listen,
227 Self::OctoprintUrl,
228 Self::OctoprintApiKey,
229 Self::OctoprintFan,
230 Self::SafetyEnvelope,
231 Self::Harness,
232 Self::Model,
233 Self::SkillPath,
234 Self::PromptTemplatePath,
235 Self::ObservationIntervalS,
236 Self::PrinterPollS,
237 Self::UnattendedWindowS,
238 Self::IngressAnswerBoundMs,
239 Self::IngressSharedSecret,
240 Self::ApiCredential,
241 Self::ApiCredentialVerifier,
242 Self::CameraSnapshotUrl,
243 Self::ObicoUrl,
244 Self::ObicoAccessToken,
245 Self::ObicoMlApiUrl,
246 Self::VisionBlankFrameMaxStddev,
247 Self::SpoolsPreflight,
248 Self::SpoolsBufferPercent,
249 Self::SpoolsBufferMinG,
250 Self::SpoolsAnalysisWaitSeconds,
251 ];
252
253 #[must_use]
255 pub const fn key(self) -> &'static str {
256 match self {
257 Self::StateDir => "state_dir",
258 Self::Listen => "listen",
259 Self::OctoprintUrl => "octoprint.url",
260 Self::OctoprintApiKey => "octoprint.api_key",
261 Self::OctoprintFan => "octoprint.fan",
262 Self::SafetyEnvelope => "safety",
263 Self::Harness => "supervisor.harness",
264 Self::Model => "supervisor.model",
265 Self::SkillPath => "supervisor.skill_path",
266 Self::PromptTemplatePath => "supervisor.prompt_template_path",
267 Self::ObservationIntervalS => "supervisor.observation_interval_s",
268 Self::PrinterPollS => "supervisor.printer_poll_s",
269 Self::UnattendedWindowS => "supervisor.unattended_window_s",
270 Self::IngressAnswerBoundMs => "ingress.answer_bound_ms",
271 Self::IngressSharedSecret => "ingress.shared_secret",
272 Self::ApiCredential => "api.credential",
273 Self::ApiCredentialVerifier => "api.credential_verifier",
274 Self::CameraSnapshotUrl => "camera.snapshot_url",
275 Self::ObicoUrl => "obico.url",
276 Self::ObicoAccessToken => "obico.access_token",
277 Self::ObicoMlApiUrl => "obico.ml_api_url",
278 Self::VisionBlankFrameMaxStddev => "vision.blank_frame_max_stddev",
279 Self::SpoolsPreflight => "spools.preflight",
280 Self::SpoolsBufferPercent => "spools.buffer_percent",
281 Self::SpoolsBufferMinG => "spools.buffer_min_g",
282 Self::SpoolsAnalysisWaitSeconds => "spools.analysis_wait_seconds",
283 }
284 }
285}
286
287impl core::fmt::Display for ConfigField {
288 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
289 formatter.write_str(self.key())
290 }
291}
292
293#[derive(Debug, Clone, PartialEq, Eq)]
298pub enum ConfigError {
299 Unreadable {
301 path: PathBuf,
303 detail: String,
305 },
306 Unparsable {
308 path: PathBuf,
310 detail: String,
312 },
313 Field {
315 field: ConfigField,
317 detail: String,
319 },
320}
321
322impl ConfigError {
323 #[must_use]
325 pub const fn field(&self) -> Option<ConfigField> {
326 match self {
327 Self::Field { field, .. } => Some(*field),
328 _ => None,
329 }
330 }
331
332 pub(crate) fn about(field: ConfigField, detail: impl Into<String>) -> Self {
334 Self::Field {
335 field,
336 detail: detail.into(),
337 }
338 }
339}
340
341impl core::fmt::Display for ConfigError {
342 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
343 match self {
344 Self::Unreadable { path, detail } => write!(
345 formatter,
346 "the configuration file {} could not be read: {detail}",
347 path.display()
348 ),
349 Self::Unparsable { path, detail } => write!(
350 formatter,
351 "the configuration file {} could not be read as this program's \
352 configuration: {detail}",
353 path.display()
354 ),
355 Self::Field { field, detail } => write!(
356 formatter,
357 "the configuration field `{field}` cannot be accepted: {detail}"
358 ),
359 }
360 }
361}
362
363impl core::error::Error for ConfigError {}
364
365#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
367#[serde(
368 crate = "printobserver_types::serde",
369 deny_unknown_fields,
370 rename_all = "snake_case"
371)]
372#[schemars(crate = "printobserver_types::schemars")]
373pub struct OctoprintSection {
374 #[serde(default, skip_serializing_if = "Option::is_none")]
376 pub url: Option<String>,
377 #[serde(default, skip_serializing_if = "Option::is_none")]
379 pub api_key: Option<String>,
380 #[serde(default = "commandable")]
382 pub fan: String,
383}
384
385pub const FAN_VOCABULARY: [(&str, FanSupport); 2] = [
388 ("commandable", FanSupport::Commandable),
389 ("absent", FanSupport::Absent),
390];
391
392fn commandable() -> String {
394 FAN_VOCABULARY[0].0.to_owned()
395}
396
397impl Default for OctoprintSection {
398 fn default() -> Self {
399 Self {
400 url: None,
401 api_key: None,
402 fan: commandable(),
403 }
404 }
405}
406
407#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
409#[serde(
410 crate = "printobserver_types::serde",
411 deny_unknown_fields,
412 rename_all = "snake_case"
413)]
414#[schemars(crate = "printobserver_types::schemars")]
415pub struct SupervisorSection {
416 #[serde(default, skip_serializing_if = "Option::is_none")]
418 pub harness: Option<String>,
419 #[serde(default, skip_serializing_if = "Option::is_none")]
421 pub model: Option<String>,
422 #[serde(default, skip_serializing_if = "Option::is_none")]
426 pub skill_path: Option<PathBuf>,
427 #[serde(default, skip_serializing_if = "Option::is_none")]
430 pub prompt_template_path: Option<PathBuf>,
431 #[serde(default = "default_observation_interval_s")]
434 pub observation_interval_s: u64,
435 #[serde(default = "default_printer_poll_s")]
438 pub printer_poll_s: u64,
439 #[serde(default = "default_unattended_window_s")]
443 pub unattended_window_s: u64,
444}
445
446const fn default_printer_poll_s() -> u64 {
448 DEFAULT_PRINTER_POLL_S
449}
450
451const fn default_unattended_window_s() -> u64 {
453 DEFAULT_UNATTENDED_WINDOW_S
454}
455
456const fn default_observation_interval_s() -> u64 {
458 DEFAULT_OBSERVATION_INTERVAL_S
459}
460
461impl Default for SupervisorSection {
462 fn default() -> Self {
463 Self {
464 harness: None,
465 model: None,
466 skill_path: None,
467 prompt_template_path: None,
468 observation_interval_s: DEFAULT_OBSERVATION_INTERVAL_S,
469 printer_poll_s: DEFAULT_PRINTER_POLL_S,
470 unattended_window_s: DEFAULT_UNATTENDED_WINDOW_S,
471 }
472 }
473}
474
475#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
477#[serde(
478 crate = "printobserver_types::serde",
479 deny_unknown_fields,
480 rename_all = "snake_case"
481)]
482#[schemars(crate = "printobserver_types::schemars")]
483pub struct IngressSection {
484 #[serde(default, skip_serializing_if = "Option::is_none")]
486 pub shared_secret: Option<String>,
487 #[serde(default = "default_answer_bound_ms")]
489 pub answer_bound_ms: u64,
490}
491
492const fn default_answer_bound_ms() -> u64 {
494 DEFAULT_INGRESS_ANSWER_BOUND_MS
495}
496
497impl Default for IngressSection {
498 fn default() -> Self {
499 Self {
500 shared_secret: None,
501 answer_bound_ms: DEFAULT_INGRESS_ANSWER_BOUND_MS,
502 }
503 }
504}
505
506#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
508#[serde(
509 crate = "printobserver_types::serde",
510 deny_unknown_fields,
511 rename_all = "snake_case"
512)]
513#[schemars(crate = "printobserver_types::schemars")]
514pub struct ApiSection {
515 #[serde(default, skip_serializing_if = "Option::is_none")]
519 pub credential: Option<String>,
520 #[serde(default, skip_serializing_if = "Option::is_none")]
526 pub credential_verifier: Option<String>,
527}
528
529#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
531#[serde(
532 crate = "printobserver_types::serde",
533 deny_unknown_fields,
534 rename_all = "snake_case"
535)]
536#[schemars(crate = "printobserver_types::schemars")]
537pub struct CameraSection {
538 #[serde(default, skip_serializing_if = "Option::is_none")]
541 pub snapshot_url: Option<String>,
542}
543
544#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
548#[serde(
549 crate = "printobserver_types::serde",
550 deny_unknown_fields,
551 rename_all = "snake_case"
552)]
553#[schemars(crate = "printobserver_types::schemars")]
554pub struct ObicoSection {
555 #[serde(default, skip_serializing_if = "Option::is_none")]
558 pub url: Option<String>,
559 #[serde(default, skip_serializing_if = "Option::is_none")]
563 pub access_token: Option<String>,
564 #[serde(default, skip_serializing_if = "Option::is_none")]
569 pub ml_api_url: Option<String>,
570}
571
572#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
574#[serde(
575 crate = "printobserver_types::serde",
576 deny_unknown_fields,
577 rename_all = "snake_case"
578)]
579#[schemars(crate = "printobserver_types::schemars")]
580pub struct VisionSection {
581 #[serde(default, skip_serializing_if = "Option::is_none")]
584 pub blank_frame_max_stddev: Option<f64>,
585}
586
587impl core::fmt::Debug for ObicoSection {
588 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
589 formatter
590 .debug_struct("ObicoSection")
591 .field("url", &self.url)
592 .field(
593 "access_token",
594 &self.access_token.as_ref().map(|_| REDACTED),
595 )
596 .field("ml_api_url", &self.ml_api_url)
597 .finish()
598 }
599}
600
601#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
608#[serde(
609 crate = "printobserver_types::serde",
610 deny_unknown_fields,
611 rename_all = "snake_case"
612)]
613#[schemars(crate = "printobserver_types::schemars")]
614pub struct SpoolsSection {
615 #[serde(default, skip_serializing_if = "Option::is_none")]
618 pub preflight: Option<String>,
619 #[serde(default, skip_serializing_if = "Option::is_none")]
621 pub buffer_percent: Option<f64>,
622 #[serde(default, skip_serializing_if = "Option::is_none")]
624 pub buffer_min_g: Option<f64>,
625 #[serde(default, skip_serializing_if = "Option::is_none")]
628 pub analysis_wait_seconds: Option<i64>,
629}
630
631#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
637#[serde(
638 crate = "printobserver_types::serde",
639 deny_unknown_fields,
640 rename_all = "snake_case"
641)]
642#[schemars(crate = "printobserver_types::schemars")]
643pub struct ConfigFile {
644 #[serde(default, skip_serializing_if = "Option::is_none")]
646 pub state_dir: Option<PathBuf>,
647 #[serde(default, skip_serializing_if = "Option::is_none")]
649 pub listen: Option<String>,
650 #[serde(default)]
652 pub octoprint: OctoprintSection,
653 #[serde(default, skip_serializing_if = "Option::is_none")]
655 pub safety: Option<SafetyEnvelope>,
656 #[serde(default)]
658 pub supervisor: SupervisorSection,
659 #[serde(default)]
661 pub ingress: IngressSection,
662 #[serde(default)]
664 pub api: ApiSection,
665 #[serde(default)]
667 pub camera: CameraSection,
668 #[serde(default)]
670 pub obico: ObicoSection,
671 #[serde(default)]
673 pub vision: VisionSection,
674 #[serde(default)]
676 pub spools: SpoolsSection,
677}
678
679#[derive(Clone, PartialEq, Eq)]
686pub struct SharedSecret(String);
687
688pub const REDACTED: &str = "<redacted>";
690
691impl SharedSecret {
692 pub fn new(value: &str) -> Result<Self, ConfigError> {
700 if value.trim().is_empty() {
701 return Err(ConfigError::about(
702 ConfigField::IngressSharedSecret,
703 "it is empty, and anything that can post to the ingress can pause a printer",
704 ));
705 }
706 Ok(Self(value.to_owned()))
707 }
708
709 #[must_use]
716 pub fn matches(&self, offered: Option<&str>) -> bool {
717 let Some(offered) = offered else {
718 return false;
719 };
720 let expected = self.0.as_bytes();
721 let mut difference = expected.len() ^ offered.len();
722 for (index, byte) in offered.bytes().enumerate() {
723 let against = expected[index % expected.len().max(1)];
724 difference |= usize::from(byte ^ against);
725 }
726 difference == 0
727 }
728}
729
730impl core::fmt::Display for SharedSecret {
731 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
732 formatter.write_str(REDACTED)
733 }
734}
735
736impl core::fmt::Debug for SharedSecret {
737 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
738 write!(formatter, "SharedSecret({REDACTED})")
739 }
740}
741
742pub const GENERATED_CREDENTIAL_BYTES: usize = 32;
744
745#[derive(Clone)]
755pub struct ApiCredential(String);
756
757impl ApiCredential {
758 pub fn new(value: &str) -> Result<Self, &'static str> {
767 if value.trim().is_empty() {
768 return Err(
769 "it is empty, and anything that can reach this server's API can command a printer",
770 );
771 }
772 if !value.bytes().all(|byte| (b' '..=b'~').contains(&byte)) {
773 return Err(
774 "it carries a control character or a character outside printable ASCII, which \
775 no `Authorization` header carries intact",
776 );
777 }
778 if value.starts_with(' ') || value.ends_with(' ') {
779 return Err(
780 "it begins or ends with a space, which an `Authorization` header does not carry",
781 );
782 }
783 Ok(Self(value.to_owned()))
785 }
786
787 pub fn generate() -> Result<Self, getrandom::Error> {
797 use base64::Engine as _;
798
799 let mut drawn = [0_u8; GENERATED_CREDENTIAL_BYTES];
800 getrandom::fill(&mut drawn)?;
801 Ok(Self(
802 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(drawn),
803 ))
804 }
805
806 #[must_use]
812 pub fn admits(&self, presented: &[u8]) -> bool {
813 use subtle::ConstantTimeEq as _;
814
815 let expected = self.0.as_bytes();
816 expected.len() == presented.len() && bool::from(expected.ct_eq(presented))
817 }
818
819 #[must_use]
822 pub fn written(&self) -> &str {
823 &self.0
824 }
825
826 #[must_use]
828 pub fn verifier(&self) -> CredentialVerifier {
829 CredentialVerifier::of(&self.0)
830 }
831}
832
833impl PartialEq for ApiCredential {
834 fn eq(&self, other: &Self) -> bool {
835 self.admits(other.0.as_bytes())
836 }
837}
838
839impl Eq for ApiCredential {}
840
841impl core::fmt::Display for ApiCredential {
842 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
843 formatter.write_str(REDACTED)
844 }
845}
846
847impl core::fmt::Debug for ApiCredential {
848 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
849 write!(formatter, "ApiCredential({REDACTED})")
850 }
851}
852
853pub const VERIFIER_PREFIX: &str = "sha256:";
855
856const VERIFIER_DIGITS: usize = 64;
858
859#[derive(Clone, PartialEq, Eq)]
870pub struct CredentialVerifier([u8; 32]);
871
872impl CredentialVerifier {
873 #[must_use]
875 pub fn of(credential: &str) -> Self {
876 use sha2::Digest as _;
877
878 Self(sha2::Sha256::digest(credential.as_bytes()).into())
879 }
880
881 pub fn parse(text: &str) -> Result<Self, &'static str> {
888 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";
889 let digits = text.strip_prefix(VERIFIER_PREFIX).ok_or(SHAPE)?;
890 if digits.len() != VERIFIER_DIGITS
891 || !digits
892 .bytes()
893 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
894 {
895 return Err(SHAPE);
896 }
897 let mut digest = [0_u8; 32];
898 for (index, pair) in digits.as_bytes().chunks(2).enumerate() {
899 let high = hex_value(pair[0]);
900 let low = hex_value(pair[1]);
901 digest[index] = (high << 4) | low;
902 }
903 Ok(Self(digest))
904 }
905
906 #[must_use]
912 pub fn admits(&self, presented: &[u8]) -> bool {
913 use sha2::Digest as _;
914 use subtle::ConstantTimeEq as _;
915
916 let offered: [u8; 32] = sha2::Sha256::digest(presented).into();
917 bool::from(self.0.ct_eq(&offered))
918 }
919}
920
921const fn hex_value(digit: u8) -> u8 {
923 if digit.is_ascii_digit() {
924 digit - b'0'
925 } else {
926 digit - b'a' + 10
927 }
928}
929
930impl core::fmt::Display for CredentialVerifier {
931 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
932 formatter.write_str(VERIFIER_PREFIX)?;
933 for byte in self.0 {
934 write!(formatter, "{byte:02x}")?;
935 }
936 Ok(())
937 }
938}
939
940impl core::fmt::Debug for CredentialVerifier {
941 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
942 write!(formatter, "CredentialVerifier({self})")
943 }
944}
945
946#[derive(Debug, Clone, PartialEq)]
955pub struct ServerConfig {
956 pub state_dir: PathBuf,
958 pub listen: SocketAddr,
960 pub octoprint: OctoPrintConfig,
962 pub safety: SafetyEnvelope,
964 pub harness: HarnessIdentity,
966 pub model: Option<ModelName>,
968 pub skill_path: PathBuf,
972 pub prompt_template_path: Option<PathBuf>,
974 pub observation_interval: core::time::Duration,
976 pub printer_poll: core::time::Duration,
978 pub unattended_window: core::time::Duration,
981 pub blank_frame_max_stddev: BlankFrameBound,
983 pub obico_ml_api_url: Option<WebAddress>,
986 pub ingress_answer_bound: core::time::Duration,
988 pub ingress_shared_secret: SharedSecret,
990 pub api_credential: Option<ApiCredential>,
994 pub api_credential_verifier: Option<CredentialVerifier>,
998 pub camera_snapshot_url: Option<WebAddress>,
1000 pub obico_api: Option<ObicoApi>,
1002 pub spools: SpoolPolicy,
1004}
1005
1006impl ServerConfig {
1007 pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
1018 let path = path.as_ref();
1019 Self::parse(&read(path)?, path)
1020 }
1021
1022 pub fn parse(text: &str, path: &Path) -> Result<Self, ConfigError> {
1028 let file: ConfigFile = toml::from_str(text).map_err(|error| ConfigError::Unparsable {
1029 path: path.to_path_buf(),
1030 detail: error.to_string(),
1031 })?;
1032 Self::validate(file)
1033 }
1034
1035 fn validate(file: ConfigFile) -> Result<Self, ConfigError> {
1042 let state_dir =
1043 state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?;
1044 let listen = listen_address(&required(ConfigField::Listen, file.listen)?)?;
1045 let octoprint = octoprint(&file.octoprint)?;
1046 let safety = required(ConfigField::SafetyEnvelope, file.safety)?;
1047 check_envelope(&safety)?;
1048 let harness = harness_identity(file.supervisor.harness)?;
1049 let model = match file.supervisor.model {
1050 None => None,
1051 Some(name) => Some(
1052 ModelName::new(&named(ConfigField::Model, Some(name))?)
1053 .map_err(|error| ConfigError::about(ConfigField::Model, error.to_string()))?,
1054 ),
1055 };
1056 let skill_path = skill(file.supervisor.skill_path.as_deref())?;
1057 let prompt_template_path = readable(
1058 ConfigField::PromptTemplatePath,
1059 file.supervisor.prompt_template_path.as_deref(),
1060 )?;
1061 let observation_interval = observation_interval(file.supervisor.observation_interval_s)?;
1062 let printer_poll = seconds_within(
1063 ConfigField::PrinterPollS,
1064 file.supervisor.printer_poll_s,
1065 PRINTER_POLL_RANGE_S,
1066 )?;
1067 let unattended_window = seconds_within(
1068 ConfigField::UnattendedWindowS,
1069 file.supervisor.unattended_window_s,
1070 UNATTENDED_WINDOW_RANGE_S,
1071 )?;
1072 let blank_frame_max_stddev = blank_frame_bound(file.vision.blank_frame_max_stddev)?;
1073 let obico_ml_api_url = file
1074 .obico
1075 .ml_api_url
1076 .as_deref()
1077 .map(|url| web_address(ConfigField::ObicoMlApiUrl, url))
1078 .transpose()?;
1079 let ingress_answer_bound = answer_bound(file.ingress.answer_bound_ms)?;
1080 let ingress_shared_secret = SharedSecret::new(&required(
1081 ConfigField::IngressSharedSecret,
1082 file.ingress.shared_secret,
1083 )?)?;
1084 let api_credential = file
1085 .api
1086 .credential
1087 .as_deref()
1088 .map(|value| {
1089 ApiCredential::new(value)
1090 .map_err(|why| ConfigError::about(ConfigField::ApiCredential, why))
1091 })
1092 .transpose()?;
1093 let api_credential_verifier = file
1094 .api
1095 .credential_verifier
1096 .as_deref()
1097 .map(|value| {
1098 CredentialVerifier::parse(value.trim())
1099 .map_err(|why| ConfigError::about(ConfigField::ApiCredentialVerifier, why))
1100 })
1101 .transpose()?;
1102 let camera_snapshot_url = file
1103 .camera
1104 .snapshot_url
1105 .map(|url| web_address(ConfigField::CameraSnapshotUrl, &url))
1106 .transpose()?;
1107 let obico_api = obico_api(file.obico)?;
1108 let spools = spool_policy(&file.spools)?;
1109 Ok(Self {
1110 state_dir,
1111 listen,
1112 octoprint,
1113 safety,
1114 harness,
1115 model,
1116 skill_path,
1117 prompt_template_path,
1118 observation_interval,
1119 printer_poll,
1120 unattended_window,
1121 blank_frame_max_stddev,
1122 obico_ml_api_url,
1123 ingress_answer_bound,
1124 ingress_shared_secret,
1125 api_credential,
1126 api_credential_verifier,
1127 camera_snapshot_url,
1128 obico_api,
1129 spools,
1130 })
1131 }
1132
1133 #[must_use]
1137 pub fn assets_dir(&self) -> PathBuf {
1138 self.state_dir.join(ASSETS_DIRECTORY)
1139 }
1140}
1141
1142fn web_address(field: ConfigField, url: &str) -> Result<WebAddress, ConfigError> {
1145 WebAddress::new(url).map_err(|why| ConfigError::about(field, why))
1146}
1147
1148fn obico_api(section: ObicoSection) -> Result<Option<ObicoApi>, ConfigError> {
1154 match (section.url, section.access_token) {
1155 (None, None) => Ok(None),
1156 (Some(_), None) => Err(ConfigError::about(
1157 ConfigField::ObicoAccessToken,
1158 "it is required when obico.url is given",
1159 )),
1160 (None, Some(_)) => Err(ConfigError::about(
1161 ConfigField::ObicoUrl,
1162 "it is required when obico.access_token is given",
1163 )),
1164 (Some(url), Some(access_token)) => {
1165 let url = web_address(ConfigField::ObicoUrl, &url)?;
1166 let access_token = AccessToken::new(&access_token)
1167 .map_err(|why| ConfigError::about(ConfigField::ObicoAccessToken, why))?;
1168 Ok(Some(ObicoApi::new(url, access_token)))
1169 }
1170 }
1171}
1172
1173#[derive(Debug, Clone, PartialEq, Eq)]
1181pub struct SignInConfig {
1182 pub state_dir: PathBuf,
1184 pub harness: HarnessIdentity,
1186}
1187
1188impl SignInConfig {
1189 pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
1199 let path = path.as_ref();
1200 let file: SignInFile =
1201 toml::from_str(&read(path)?).map_err(|error| ConfigError::Unparsable {
1202 path: path.to_path_buf(),
1203 detail: error.to_string(),
1204 })?;
1205 Ok(Self {
1206 state_dir: state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?,
1207 harness: harness_identity(file.supervisor.harness)?,
1208 })
1209 }
1210}
1211
1212#[derive(Deserialize)]
1217#[serde(crate = "printobserver_types::serde")]
1218struct SignInFile {
1219 #[serde(default)]
1221 state_dir: Option<PathBuf>,
1222 #[serde(default)]
1224 supervisor: SignInSupervisor,
1225}
1226
1227#[derive(Default, Deserialize)]
1229#[serde(crate = "printobserver_types::serde")]
1230struct SignInSupervisor {
1231 #[serde(default)]
1233 harness: Option<String>,
1234}
1235
1236fn read(path: &Path) -> Result<String, ConfigError> {
1238 std::fs::read_to_string(path).map_err(|error| ConfigError::Unreadable {
1239 path: path.to_path_buf(),
1240 detail: error.to_string(),
1241 })
1242}
1243
1244fn harness_identity(value: Option<String>) -> Result<HarnessIdentity, ConfigError> {
1246 HarnessIdentity::new(&named(ConfigField::Harness, value)?)
1247 .map_err(|error| ConfigError::about(ConfigField::Harness, error.to_string()))
1248}
1249
1250fn required<T>(field: ConfigField, value: Option<T>) -> Result<T, ConfigError> {
1252 value.ok_or_else(|| ConfigError::about(field, "the configuration file carries no value for it"))
1253}
1254
1255fn named(field: ConfigField, value: Option<String>) -> Result<String, ConfigError> {
1257 let value = required(field, value)?;
1258 if value.trim().is_empty() {
1259 return Err(ConfigError::about(
1260 field,
1261 "it is empty, and an empty value names nothing",
1262 ));
1263 }
1264 Ok(value.trim().to_owned())
1265}
1266
1267fn state_directory(named: &Path) -> Result<PathBuf, ConfigError> {
1269 if named.as_os_str().is_empty() {
1270 return Err(ConfigError::about(
1271 ConfigField::StateDir,
1272 "it names no directory, and this server's whole state lives in one",
1273 ));
1274 }
1275 std::fs::create_dir_all(named).map_err(|error| {
1276 ConfigError::about(
1277 ConfigField::StateDir,
1278 format!("{} cannot be created: {error}", named.display()),
1279 )
1280 })?;
1281 named.canonicalize().map(plainly_written).map_err(|error| {
1282 ConfigError::about(
1283 ConfigField::StateDir,
1284 format!("{} cannot be resolved: {error}", named.display()),
1285 )
1286 })
1287}
1288
1289#[must_use]
1298pub fn plainly_written(path: PathBuf) -> PathBuf {
1299 const VERBATIM: &str = r"\\?\";
1300 let drive = path
1301 .to_str()
1302 .and_then(|text| text.strip_prefix(VERBATIM))
1303 .filter(|rest| {
1304 let bytes = rest.as_bytes();
1305 bytes.len() >= 3
1306 && bytes[0].is_ascii_alphabetic()
1307 && bytes[1] == b':'
1308 && bytes[2] == b'\\'
1309 })
1310 .map(PathBuf::from);
1311 drive.unwrap_or(path)
1312}
1313
1314fn listen_address(named: &str) -> Result<SocketAddr, ConfigError> {
1316 named.trim().parse().map_err(|error| {
1317 ConfigError::about(
1318 ConfigField::Listen,
1319 format!("{named:?} is no address to listen on: {error}"),
1320 )
1321 })
1322}
1323
1324fn octoprint(section: &OctoprintSection) -> Result<OctoPrintConfig, ConfigError> {
1327 let fan = fan_support(§ion.fan)?;
1328 let url = named(ConfigField::OctoprintUrl, section.url.clone())?;
1329 let key = named(ConfigField::OctoprintApiKey, section.api_key.clone())?;
1330 OctoPrintConfig::new(&url, key)
1331 .map(|configured| configured.with_fan(fan))
1332 .map_err(|error| {
1333 let field = match error {
1334 printobserver_octoprint::ConfigError::EmptyApiKey => ConfigField::OctoprintApiKey,
1335 _ => ConfigField::OctoprintUrl,
1336 };
1337 ConfigError::about(field, error.to_string())
1338 })
1339}
1340
1341fn fan_support(named: &str) -> Result<FanSupport, ConfigError> {
1343 FAN_VOCABULARY
1344 .iter()
1345 .find(|(spelling, _)| *spelling == named.trim())
1346 .map(|(_, support)| *support)
1347 .ok_or_else(|| {
1348 let vocabulary: Vec<&str> = FAN_VOCABULARY.iter().map(|(word, _)| *word).collect();
1349 ConfigError::about(
1350 ConfigField::OctoprintFan,
1351 format!("{named:?} is not one of {}", vocabulary.join(" or ")),
1352 )
1353 })
1354}
1355
1356fn check_envelope(envelope: &SafetyEnvelope) -> Result<(), ConfigError> {
1358 if envelope.allowed.is_empty() {
1359 return Err(ConfigError::about(
1360 ConfigField::SafetyEnvelope,
1361 "it allows no adjustable at all, so no adjustment could ever be accepted",
1362 ));
1363 }
1364 for (adjustable, range) in &envelope.allowed {
1365 if !range.min.is_finite() || !range.max.is_finite() || range.min > range.max {
1366 return Err(ConfigError::about(
1367 ConfigField::SafetyEnvelope,
1368 format!(
1369 "the range allowed for {adjustable} runs from {} to {}, which admits \
1370 no value",
1371 range.min, range.max
1372 ),
1373 ));
1374 }
1375 }
1376 if envelope
1379 .actions
1380 .get(&ActorClass::Agent)
1381 .is_some_and(|granted| granted.contains(&ActionKind::ClosePrint))
1382 {
1383 return Err(ConfigError::about(
1384 ConfigField::SafetyEnvelope,
1385 "it grants `close_print` to the agent, and closing a print record is the \
1386 operator's judgement that the print is over",
1387 ));
1388 }
1389 if envelope.agent_min_interval_s < 0 {
1390 return Err(ConfigError::about(
1391 ConfigField::SafetyEnvelope,
1392 format!(
1393 "the agent's minimum interval is {}s, and an interval is a count of seconds",
1394 envelope.agent_min_interval_s
1395 ),
1396 ));
1397 }
1398 Ok(())
1399}
1400
1401fn readable(field: ConfigField, named: Option<&Path>) -> Result<Option<PathBuf>, ConfigError> {
1404 let Some(path) = named else {
1405 return Ok(None);
1406 };
1407 std::fs::read_to_string(path)
1408 .map(|_| Some(path.to_path_buf()))
1409 .map_err(|error| {
1410 ConfigError::about(field, format!("{} cannot be read: {error}", path.display()))
1411 })
1412}
1413
1414fn skill(named: Option<&Path>) -> Result<PathBuf, ConfigError> {
1417 let Some(path) = named else {
1418 return Err(ConfigError::about(
1419 ConfigField::SkillPath,
1420 format!(
1421 "the configuration file carries no value for it, and this program carries \
1422 no skill of its own: {SKILL_INSTALL}"
1423 ),
1424 ));
1425 };
1426 std::fs::read_to_string(path)
1427 .map(|_| path.to_path_buf())
1428 .map_err(|error| {
1429 ConfigError::about(
1430 ConfigField::SkillPath,
1431 format!(
1432 "{} cannot be read: {error}. {SKILL_INSTALL}",
1433 path.display()
1434 ),
1435 )
1436 })
1437}
1438
1439fn spool_policy(section: &SpoolsSection) -> Result<SpoolPolicy, ConfigError> {
1441 let defaults = SpoolPolicy::default();
1442 let preflight = match section.preflight.as_deref() {
1443 None => defaults.preflight,
1444 Some("refuse") => PreflightMode::Refuse,
1445 Some("warn") => PreflightMode::Warn,
1446 Some("off") => PreflightMode::Off,
1447 Some(_) => {
1448 return Err(ConfigError::about(
1449 ConfigField::SpoolsPreflight,
1450 "the spool check is one of `refuse`, `warn` or `off`",
1451 ));
1452 }
1453 };
1454 let margin = |field: ConfigField, value: Option<f64>, default: f64| match value {
1455 None => Ok(default),
1456 Some(value) if value.is_finite() && value >= 0.0 => Ok(value),
1457 Some(_) => Err(ConfigError::about(
1458 field,
1459 "a margin is a figure at or above zero; a negative one asks a spool for less \
1460 than the print needs",
1461 )),
1462 };
1463 let buffer_percent = margin(
1464 ConfigField::SpoolsBufferPercent,
1465 section.buffer_percent,
1466 defaults.buffer_percent,
1467 )?;
1468 let buffer_min_g = margin(
1469 ConfigField::SpoolsBufferMinG,
1470 section.buffer_min_g,
1471 defaults.buffer_min_g,
1472 )?;
1473 let analysis_wait_s = match section.analysis_wait_seconds {
1474 None => defaults.analysis_wait_s,
1475 Some(seconds) => u64::try_from(seconds).map_err(|_| {
1476 ConfigError::about(
1477 ConfigField::SpoolsAnalysisWaitSeconds,
1478 "a wait is a number of seconds at or above zero",
1479 )
1480 })?,
1481 };
1482 Ok(SpoolPolicy {
1483 preflight,
1484 buffer_percent,
1485 buffer_min_g,
1486 analysis_wait_s,
1487 })
1488}
1489
1490fn observation_interval(seconds: u64) -> Result<core::time::Duration, ConfigError> {
1492 if seconds == 0 {
1493 return Err(ConfigError::about(
1494 ConfigField::ObservationIntervalS,
1495 "an interval of zero seconds observes a print again the moment its last turn \
1496 returns, which is a turn that never ends",
1497 ));
1498 }
1499 Ok(core::time::Duration::from_secs(seconds))
1500}
1501
1502fn seconds_within(
1504 field: ConfigField,
1505 seconds: u64,
1506 range: (u64, u64),
1507) -> Result<core::time::Duration, ConfigError> {
1508 let (least, most) = range;
1509 if !(least..=most).contains(&seconds) {
1510 return Err(ConfigError::about(
1511 field,
1512 format!("{seconds} seconds is outside the {least} to {most} seconds it admits"),
1513 ));
1514 }
1515 Ok(core::time::Duration::from_secs(seconds))
1516}
1517
1518fn blank_frame_bound(written: Option<f64>) -> Result<BlankFrameBound, ConfigError> {
1520 written.map_or(Ok(BlankFrameBound::DEFAULT), |bound| {
1521 BlankFrameBound::new(bound).map_err(|refused| {
1522 ConfigError::about(
1523 ConfigField::VisionBlankFrameMaxStddev,
1524 format!(
1525 "{refused} is outside the {MIN_BLANK_FRAME_MAX_STDDEV} to \
1526 {MAX_BLANK_FRAME_MAX_STDDEV} grey levels it admits"
1527 ),
1528 )
1529 })
1530 })
1531}
1532
1533fn answer_bound(milliseconds: u64) -> Result<core::time::Duration, ConfigError> {
1535 if milliseconds == 0 {
1536 return Err(ConfigError::about(
1537 ConfigField::IngressAnswerBoundMs,
1538 "a bound of zero is an ingress that has run out of time before it starts",
1539 ));
1540 }
1541 if milliseconds >= OBICO_POSTING_TIMEOUT_MS {
1542 return Err(ConfigError::about(
1543 ConfigField::IngressAnswerBoundMs,
1544 format!(
1545 "{milliseconds}ms is not below the {OBICO_POSTING_TIMEOUT_MS}ms Obico posts \
1546 under, so an alert answered at that bound is one Obico has already \
1547 abandoned — and its posting does not retry"
1548 ),
1549 ));
1550 }
1551 Ok(core::time::Duration::from_millis(milliseconds))
1552}
1553
1554#[cfg(test)]
1555mod tests {
1556 use super::CredentialVerifier;
1557
1558 const ABC: &str = "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
1560
1561 #[test]
1564 fn a_verifier_is_the_credentials_sha256_and_admits_only_it() {
1565 let verifier = CredentialVerifier::of("abc");
1566
1567 assert_eq!(verifier.to_string(), ABC);
1568 assert_eq!(CredentialVerifier::parse(ABC), Ok(verifier.clone()));
1569 assert!(verifier.admits(b"abc"));
1570 assert!(!verifier.admits(b"abd"));
1571 assert!(!verifier.admits(b""));
1572 }
1573
1574 #[test]
1576 fn a_verifier_in_any_other_spelling_is_refused() {
1577 for refused in [
1578 "",
1579 "sha256:",
1580 &ABC[..ABC.len() - 1],
1581 &format!("{ABC}0"),
1582 &ABC.to_uppercase(),
1583 &ABC.replace("sha256:", "sha512:"),
1584 &ABC.replace("sha256:", ""),
1585 &ABC.replace('a', "g"),
1586 ] {
1587 assert!(
1588 CredentialVerifier::parse(refused).is_err(),
1589 "{refused:?} was accepted"
1590 );
1591 }
1592 }
1593}