1use std::time::Duration;
47
48use printobserver_printer_api::{
49 BoxFuture, PrinterErrorReason, PrinterPush, PrinterSnapshot, PrinterState,
50};
51use printobserver_types::contract::Sample;
52use printobserver_types::schemars::JsonSchema;
53use printobserver_types::serde::{Deserialize, Serialize};
54use printobserver_types::{EventKind, EventPayload as _, EventRecord, PrintId, Timestamp};
55
56use crate::error::CoreError;
57use crate::events::PendingTurn;
58use crate::inbox::Arrival;
59use crate::kinds::{
60 DetectorHealthChangedPayload, DetectorStatus, HeatedTool, PortFailureSite, PrintEndedPayload,
61 PrinterConnectionChangedPayload, PrinterResetPayload, UnattendedPrinterActivityPayload,
62 system_source,
63};
64use crate::listing::ObservedJob;
65use crate::records::{PrintOutcome, PrintRecord};
66use crate::store::HistoryQuery;
67use crate::supervisor::Supervisor;
68
69pub const DEFAULT_PRINTER_POLL: Duration = Duration::from_secs(15);
71
72pub const DEFAULT_UNATTENDED_WINDOW: Duration = Duration::from_secs(3600);
75
76pub const RESET_GRACE: Duration = Duration::from_secs(1);
84
85pub const PUSH_CHANNEL_DOWN: &str =
87 "the printer's push channel was down, so this was read from its state alone";
88
89pub const PRINTER_WATCH_KINDS: [&str; 4] = [
92 PrinterConnectionChangedPayload::KIND,
93 PrinterResetPayload::KIND,
94 UnattendedPrinterActivityPayload::KIND,
95 DetectorHealthChangedPayload::KIND,
96];
97
98#[derive(Debug, Clone, Copy, PartialEq)]
100pub struct HeadPosition {
101 pub x: f64,
103 pub y: f64,
105 pub z: f64,
107}
108
109pub trait PositionProbe: Send + Sync {
114 fn read_position(&self) -> BoxFuture<'_, Option<HeadPosition>>;
116}
117
118pub trait DetectorProbe: Send + Sync {
120 fn check(&self) -> BoxFuture<'_, Result<String, String>>;
123}
124
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
127#[serde(
128 crate = "printobserver_types::serde",
129 rename_all = "snake_case",
130 deny_unknown_fields
131)]
132#[schemars(crate = "printobserver_types::schemars")]
133pub enum DetectorHealthStatus {
134 ScoringNothingFlagged,
137 ScoringFlagged,
140 Available,
143 Unavailable,
146 #[default]
149 Unchecked,
150}
151
152#[derive(Debug, Clone, PartialEq, Eq)]
166pub enum DetectorHealth {
167 Unchecked {
170 scoring_unread: Option<String>,
172 },
173 Available {
176 since: Timestamp,
178 scoring_unread: Option<String>,
180 },
181 Unavailable {
184 since: Timestamp,
186 scoring_unread: Option<String>,
188 },
189 Scoring {
191 since: Timestamp,
193 verdict: ScoringVerdict,
195 probe_failure: Option<String>,
198 },
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
203pub enum ScoringVerdict {
204 NothingFlagged,
206 Flagged,
208}
209
210impl Default for DetectorHealth {
211 fn default() -> Self {
212 Self::Unchecked {
213 scoring_unread: None,
214 }
215 }
216}
217
218impl DetectorHealth {
219 #[must_use]
221 pub const fn status(&self) -> DetectorHealthStatus {
222 match self {
223 Self::Unchecked { .. } => DetectorHealthStatus::Unchecked,
224 Self::Available { .. } => DetectorHealthStatus::Available,
225 Self::Unavailable { .. } => DetectorHealthStatus::Unavailable,
226 Self::Scoring {
227 verdict: ScoringVerdict::NothingFlagged,
228 ..
229 } => DetectorHealthStatus::ScoringNothingFlagged,
230 Self::Scoring {
231 verdict: ScoringVerdict::Flagged,
232 ..
233 } => DetectorHealthStatus::ScoringFlagged,
234 }
235 }
236}
237
238#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
240#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
241struct DetectorHealthWire {
242 status: DetectorHealthStatus,
244 #[serde(deserialize_with = "present")]
247 since: Option<Timestamp>,
248 #[serde(default, skip_serializing_if = "Option::is_none")]
250 probe_failure: Option<String>,
251 #[serde(default, skip_serializing_if = "Option::is_none")]
253 scoring_unread: Option<String>,
254}
255
256fn present<'de, D: printobserver_types::serde::Deserializer<'de>>(
259 deserializer: D,
260) -> Result<Option<Timestamp>, D::Error> {
261 Option::deserialize(deserializer)
262}
263
264impl From<DetectorHealth> for DetectorHealthWire {
265 fn from(health: DetectorHealth) -> Self {
266 let status = health.status();
267 let (since, probe_failure, scoring_unread) = match health {
268 DetectorHealth::Unchecked { scoring_unread } => (None, None, scoring_unread),
269 DetectorHealth::Available {
270 since,
271 scoring_unread,
272 }
273 | DetectorHealth::Unavailable {
274 since,
275 scoring_unread,
276 } => (Some(since), None, scoring_unread),
277 DetectorHealth::Scoring {
278 since,
279 probe_failure,
280 ..
281 } => (Some(since), probe_failure, None),
282 };
283 Self {
284 status,
285 since,
286 probe_failure,
287 scoring_unread,
288 }
289 }
290}
291
292impl TryFrom<DetectorHealthWire> for DetectorHealth {
293 type Error = &'static str;
294
295 fn try_from(wire: DetectorHealthWire) -> Result<Self, Self::Error> {
296 let DetectorHealthWire {
297 status,
298 since,
299 probe_failure,
300 scoring_unread,
301 } = wire;
302 let scoring = matches!(
303 status,
304 DetectorHealthStatus::ScoringNothingFlagged | DetectorHealthStatus::ScoringFlagged
305 );
306 if scoring && scoring_unread.is_some() {
307 return Err("a scoring detector's scoring is being read");
308 }
309 if !scoring && probe_failure.is_some() {
310 return Err("only a scoring detector names its failing health check beside it");
311 }
312 match (status, since) {
313 (DetectorHealthStatus::Unchecked, None) => Ok(Self::Unchecked { scoring_unread }),
314 (DetectorHealthStatus::Available, Some(since)) => Ok(Self::Available {
315 since,
316 scoring_unread,
317 }),
318 (DetectorHealthStatus::Unavailable, Some(since)) => Ok(Self::Unavailable {
319 since,
320 scoring_unread,
321 }),
322 (DetectorHealthStatus::ScoringNothingFlagged, Some(since)) => Ok(Self::Scoring {
323 since,
324 verdict: ScoringVerdict::NothingFlagged,
325 probe_failure,
326 }),
327 (DetectorHealthStatus::ScoringFlagged, Some(since)) => Ok(Self::Scoring {
328 since,
329 verdict: ScoringVerdict::Flagged,
330 probe_failure,
331 }),
332 (DetectorHealthStatus::Unchecked, Some(_)) => {
333 Err("an unchecked detector has no instant it became so")
334 }
335 (_, None) => Err("a checked detector carries the instant it became so"),
336 }
337 }
338}
339
340impl Serialize for DetectorHealth {
341 fn serialize<S: printobserver_types::serde::Serializer>(
342 &self,
343 serializer: S,
344 ) -> Result<S::Ok, S::Error> {
345 DetectorHealthWire::from(self.clone()).serialize(serializer)
346 }
347}
348
349impl<'de> Deserialize<'de> for DetectorHealth {
350 fn deserialize<D: printobserver_types::serde::Deserializer<'de>>(
351 deserializer: D,
352 ) -> Result<Self, D::Error> {
353 let wire = DetectorHealthWire::deserialize(deserializer)?;
354 Self::try_from(wire).map_err(printobserver_types::serde::de::Error::custom)
355 }
356}
357
358fn health_arm(
361 status: &str,
362 doc: &str,
363 since: &printobserver_types::serde_json::Value,
364 beside: (&str, &str),
365) -> printobserver_types::serde_json::Value {
366 let (field, field_doc) = beside;
367 let mut properties = printobserver_types::serde_json::Map::new();
368 properties.insert(
369 "status".to_owned(),
370 printobserver_types::serde_json::json!({ "type": "string", "const": status }),
371 );
372 properties.insert("since".to_owned(), since.clone());
373 properties.insert(
374 field.to_owned(),
375 printobserver_types::serde_json::json!({ "type": "string", "description": field_doc }),
376 );
377 printobserver_types::serde_json::json!({
378 "type": "object",
379 "description": doc,
380 "properties": properties,
381 "required": ["status", "since"],
382 "additionalProperties": false,
383 })
384}
385
386const SCORING_UNREAD_DOC: &str = "Why the detector's scoring of the print is not being read, \
388 when it is not: no Obico API is configured, no Obico printer is known yet, or the last read \
389 failed.";
390
391const PROBE_FAILURE_DOC: &str = "What the detector's health check answered, when it is \
393 failing while the detector scores the print.";
394
395impl JsonSchema for DetectorHealth {
398 fn schema_name() -> std::borrow::Cow<'static, str> {
399 std::borrow::Cow::Borrowed("DetectorHealth")
400 }
401
402 fn json_schema(
403 generator: &mut printobserver_types::schemars::SchemaGenerator,
404 ) -> printobserver_types::schemars::Schema {
405 let timestamp =
406 printobserver_types::serde_json::to_value(generator.subschema_for::<Timestamp>())
407 .unwrap_or_default();
408 let unread = ("scoring_unread", SCORING_UNREAD_DOC);
409 let failing = ("probe_failure", PROBE_FAILURE_DOC);
410 let schema = printobserver_types::serde_json::json!({
411 "title": "DetectorHealth",
412 "description": "The failure detector's status, and since when it has been so: \
413 `since` is `null` exactly while the status is `unchecked`. Evidence that the \
414 detector is scoring the print comes before its health check.",
415 "oneOf": [
416 health_arm(
417 "scoring_nothing_flagged",
418 "The detector is scoring the print, from `since` on, and no failure alert \
419 of its own has arrived for it.",
420 ×tamp,
421 failing,
422 ),
423 health_arm(
424 "scoring_flagged",
425 "The detector is scoring the print, from `since` on, and a failure alert \
426 of its own has arrived for it.",
427 ×tamp,
428 failing,
429 ),
430 health_arm(
431 "available",
432 "No evidence that the detector is scoring the print, and it answered its \
433 health check, from `since` on: available, with no scores yet.",
434 ×tamp,
435 unread,
436 ),
437 health_arm(
438 "unavailable",
439 "No evidence that the detector is scoring the print, and it did not answer \
440 its health check, from `since` on.",
441 ×tamp,
442 unread,
443 ),
444 health_arm(
445 "unchecked",
446 "No evidence of any kind: no detector health address is configured, or no \
447 check has been made yet, and nothing shows the detector scoring.",
448 &printobserver_types::serde_json::json!({
449 "type": "null",
450 "description": "Nothing: an unchecked detector has no instant it became so.",
451 }),
452 unread,
453 ),
454 ],
455 });
456 printobserver_types::schemars::Schema::try_from(schema).unwrap_or_default()
457 }
458}
459
460impl Sample for DetectorHealth {
461 fn sample_full() -> Self {
462 Self::Scoring {
463 since: Timestamp::sample_full(),
464 verdict: ScoringVerdict::NothingFlagged,
465 probe_failure: Some("the detector's health check answered 503".to_owned()),
466 }
467 }
468
469 fn sample_minimal() -> Self {
470 Self::Unchecked {
471 scoring_unread: None,
472 }
473 }
474
475 fn sample_alternates() -> Vec<Self> {
476 vec![
477 Self::Scoring {
478 since: Timestamp::sample_full(),
479 verdict: ScoringVerdict::Flagged,
480 probe_failure: None,
481 },
482 Self::Available {
483 since: Timestamp::sample_full(),
484 scoring_unread: Some(
485 "no Obico printer is known yet: no [obico] printer_id is configured and Obico \
486 has posted nothing naming one since this server started"
487 .to_owned(),
488 ),
489 },
490 Self::Unavailable {
491 since: Timestamp::sample_full(),
492 scoring_unread: None,
493 },
494 Self::Unchecked {
495 scoring_unread: Some(
496 "no [obico] url and access_token are configured, so Obico's record of the \
497 print is not read"
498 .to_owned(),
499 ),
500 },
501 ]
502 }
503}
504
505#[derive(Debug, Clone, Default, PartialEq, Eq)]
507pub(crate) enum ProbeHealth {
508 #[default]
510 Unchecked,
511 Available {
513 since: Timestamp,
515 },
516 Unavailable {
518 since: Timestamp,
520 detail: String,
522 },
523}
524
525impl ProbeHealth {
526 const fn status(&self) -> DetectorHealthStatus {
528 match self {
529 Self::Unchecked => DetectorHealthStatus::Unchecked,
530 Self::Available { .. } => DetectorHealthStatus::Available,
531 Self::Unavailable { .. } => DetectorHealthStatus::Unavailable,
532 }
533 }
534}
535
536#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
540pub(crate) struct PushFacts {
541 pub(crate) reset: bool,
543 pub(crate) firmware_error: bool,
545 pub(crate) gap: bool,
548}
549
550#[derive(Debug, Clone, PartialEq)]
552struct Activity {
553 tools: Vec<HeatedTool>,
555 bed: Option<f64>,
557 moved: Option<bool>,
559}
560
561impl Activity {
562 fn is_active(&self) -> bool {
564 !self.tools.is_empty() || self.bed.is_some() || self.moved == Some(true)
565 }
566}
567
568#[derive(Debug, Clone)]
570struct Unattended {
571 print_id: PrintId,
573 began: Duration,
575 recorded: Option<Activity>,
577 position: Option<HeadPosition>,
579 turned_at: Option<Duration>,
582}
583
584#[derive(Debug, Default)]
586pub(crate) struct WatchState {
587 last_state: Option<PrinterState>,
589 pushes: PushFacts,
591 channel: Channel,
593 unattended: Option<Unattended>,
595 pub(crate) probe: ProbeHealth,
597 pub(crate) scoring: crate::scoring::ScoringState,
599 pending_turns: Vec<PendingTurn>,
601 pending_resets: Vec<PrinterResetPayload>,
603 pending_ends: Vec<PrintId>,
606 pending_claims: Vec<(PrintId, EventRecord)>,
609}
610
611impl WatchState {
612 const fn channel_is_down(&self) -> bool {
614 !matches!(self.channel, Channel::Open)
615 }
616}
617
618#[derive(Debug, Clone, Default, PartialEq, Eq)]
620enum Channel {
621 #[default]
623 Unknown,
624 Open,
626 Down(String),
628}
629
630#[derive(Debug, Default)]
632pub struct Watched {
633 pub turns: Vec<PendingTurn>,
636 pub active: Option<ActiveJob>,
639}
640
641#[derive(Debug, Clone, Copy, PartialEq, Eq)]
644pub struct ActiveJob {
645 pub print_id: PrintId,
647 pub file_position_bytes: Option<i64>,
649}
650
651const fn is_down(state: &PrinterState) -> bool {
653 matches!(state, PrinterState::Offline | PrinterState::Error)
654}
655
656const fn job_runs(state: &PrinterState) -> bool {
658 matches!(
659 state,
660 PrinterState::Printing | PrinterState::Paused | PrinterState::Cancelling
661 )
662}
663
664fn heated(snapshot: &PrinterSnapshot) -> (Vec<HeatedTool>, Option<f64>) {
666 let tools = snapshot
667 .tools
668 .iter()
669 .enumerate()
670 .filter_map(|(index, heater)| {
671 let target = heater.target_c.as_ref()?.value();
672 (target > 0.0).then(|| HeatedTool {
673 tool: i64::try_from(index).unwrap_or(i64::MAX),
674 target_c: target,
675 })
676 })
677 .collect();
678 let bed = snapshot
679 .bed
680 .as_ref()
681 .and_then(|bed| bed.target_c.as_ref())
682 .map(printobserver_types::Reported::value)
683 .filter(|target| *target > 0.0);
684 (tools, bed)
685}
686
687fn activity_detail(activity: &Activity, channel_down: bool) -> String {
689 let mut parts: Vec<String> = activity
690 .tools
691 .iter()
692 .map(|tool| format!("tool {} is heating to {} °C", tool.tool, tool.target_c))
693 .collect();
694 if let Some(bed) = activity.bed {
695 parts.push(format!("the bed is heating to {bed} °C"));
696 }
697 match activity.moved {
698 Some(true) => parts.push("the print head moved".to_owned()),
699 Some(false) => {}
700 None => parts.push("the print head's position could not be read".to_owned()),
701 }
702 let mut detail = format!("with no job running, {}", parts.join(", "));
703 if channel_down {
704 detail.push_str("; ");
705 detail.push_str(PUSH_CHANNEL_DOWN);
706 }
707 detail
708}
709
710impl Supervisor {
711 pub(crate) fn watch_state(&self) -> std::sync::MutexGuard<'_, WatchState> {
713 self.watch
714 .lock()
715 .unwrap_or_else(std::sync::PoisonError::into_inner)
716 }
717
718 pub(crate) fn push_facts(&self) -> PushFacts {
720 let state = self.watch_state();
721 let mut facts = state.pushes;
722 facts.gap |= state.channel_is_down();
723 facts
724 }
725
726 pub(crate) async fn pushes_after_a_reset_could_arrive(&self) -> PushFacts {
730 let started = std::time::Instant::now();
733 loop {
734 let facts = self.push_facts();
735 if facts.reset
736 || self.watch_state().channel_is_down()
737 || started.elapsed() >= RESET_GRACE
738 || crate::delay::Delay::new(Duration::from_millis(50))
739 .await
740 .is_err()
741 {
742 return facts;
743 }
744 }
745 }
746
747 pub(crate) fn note_job_running(&self) {
749 self.watch_state().unattended = None;
750 }
751
752 pub(crate) fn forget_pushes(&self) {
755 let mut state = self.watch_state();
756 let gap = state.channel_is_down();
757 state.pushes = PushFacts {
758 gap,
759 ..PushFacts::default()
760 };
761 }
762
763 #[must_use]
768 pub fn detector_health(&self) -> DetectorHealth {
769 self.detector_health_of(None)
770 }
771
772 #[must_use]
775 pub fn detector_health_for(&self, print_id: PrintId) -> DetectorHealth {
776 self.detector_health_of(Some(print_id))
777 }
778
779 fn detector_health_of(&self, print_id: Option<PrintId>) -> DetectorHealth {
782 let window = self
783 .config()
784 .observation_interval
785 .saturating_mul(crate::scoring::EVIDENCE_INTERVALS);
786 let now = self.clock().elapsed();
787 let held = self.watch_state();
788 if let Some(scoring) = held.scoring.scoring(print_id, now, window) {
789 return DetectorHealth::Scoring {
790 since: scoring.since,
791 verdict: scoring.verdict,
792 probe_failure: match &held.probe {
793 ProbeHealth::Unavailable { detail, .. } => Some(detail.clone()),
794 ProbeHealth::Unchecked | ProbeHealth::Available { .. } => None,
795 },
796 };
797 }
798 let scoring_unread = held.scoring.unread().map(str::to_owned);
799 match &held.probe {
800 ProbeHealth::Unchecked => DetectorHealth::Unchecked { scoring_unread },
801 ProbeHealth::Available { since } => DetectorHealth::Available {
802 since: *since,
803 scoring_unread,
804 },
805 ProbeHealth::Unavailable { since, .. } => DetectorHealth::Unavailable {
806 since: *since,
807 scoring_unread,
808 },
809 }
810 }
811
812 pub fn note_push_channel(&self, open: Result<(), String>) {
817 let mut state = self.watch_state();
818 match open {
819 Ok(()) => state.channel = Channel::Open,
820 Err(detail) => {
821 state.channel = Channel::Down(detail);
822 state.pushes.gap = true;
823 }
824 }
825 }
826
827 pub async fn note_push(&self, push: PrinterPush) -> Result<(), CoreError> {
838 match push {
839 PrinterPush::Reset => {
840 self.distrust_z("the printer pushed a reset, and a reset forgets where Z is");
842 let running = self.running_print().await;
849 self.watch_state().pushes.reset = true;
850 let (during_print, detail) = match running {
853 Ok(Some(print)) => (
854 Some(print.id),
855 format!("the printer pushed a reset during print {}", print.id),
856 ),
857 Ok(None) => (
858 None,
859 "the printer pushed a reset while no print was running".to_owned(),
860 ),
861 Err(error) => (
862 None,
863 format!(
864 "the printer pushed a reset; which print was running could not be \
865 read: {error}"
866 ),
867 ),
868 };
869 let payload = PrinterResetPayload {
870 during_print,
871 detail,
872 };
873 if let Err(error) = self.write_reset(&payload).await {
874 self.watch_state().pending_resets.push(payload);
877 return Err(error);
878 }
879 Ok(())
880 }
881 PrinterPush::Error {
882 reason: PrinterErrorReason::Firmware,
883 } => {
884 self.watch_state().pushes.firmware_error = true;
885 Ok(())
886 }
887 PrinterPush::Error {
888 reason: PrinterErrorReason::Other(_),
889 }
890 | PrinterPush::Log { .. } => Ok(()),
891 }
892 }
893
894 async fn write_reset(&self, payload: &PrinterResetPayload) -> Result<(), CoreError> {
896 let draft = self.draft_of(None, system_source(), payload)?;
897 self.stores().events.append_event(draft).await?;
898 Ok(())
899 }
900
901 async fn catch_up(&self) {
905 let resets = std::mem::take(&mut self.watch_state().pending_resets);
906 for payload in resets {
907 if self.write_reset(&payload).await.is_err() {
908 self.watch_state().pending_resets.push(payload);
909 }
910 }
911 let ends = std::mem::take(&mut self.watch_state().pending_ends);
912 for print_id in ends {
913 if self.after_close_out(print_id).await.is_err() {
914 self.watch_state().pending_ends.push(print_id);
915 }
916 }
917 let claims = std::mem::take(&mut self.watch_state().pending_claims);
918 for (print_id, event) in claims {
919 self.claim_activity_turn(print_id, event).await;
920 }
921 }
922
923 pub(crate) async fn follow_up_end(&self, print_id: PrintId) {
926 if self.after_close_out(print_id).await.is_err() {
927 self.watch_state().pending_ends.push(print_id);
928 }
929 }
930
931 async fn running_print(&self) -> Result<Option<PrintRecord>, CoreError> {
933 Ok(self
934 .stores()
935 .prints
936 .open_prints()
937 .await?
938 .into_iter()
939 .find(|print| self.was_seen_running(print.id)))
940 }
941
942 pub async fn watch_printer(&self, probe: &dyn PositionProbe) -> Result<Watched, CoreError> {
952 self.catch_up().await;
953 let resolving = self.resolving().await;
954 let observed = self.observe_job().await;
955 let mut active = None;
956 if let Some(observed) = &observed {
957 self.note_connection(
958 &observed.job.state,
959 observed.job.error.as_ref().map(|error| error.text.as_str()),
960 )
961 .await?;
962 active = self
963 .settle_and_adopt(observed)
964 .await?
965 .map(|print_id| ActiveJob {
966 print_id,
967 file_position_bytes: observed.job.file_position_bytes,
968 });
969 }
970 drop(resolving);
971 if let Some(observed) = &observed {
972 self.watch_unattended(observed, probe).await?;
973 }
974 Ok(Watched {
975 turns: std::mem::take(&mut self.watch_state().pending_turns),
976 active,
977 })
978 }
979
980 async fn note_connection(
983 &self,
984 state: &PrinterState,
985 error: Option<&str>,
986 ) -> Result<(), CoreError> {
987 let (previous, channel_down) = {
988 let held = self.watch_state();
989 (held.last_state.clone(), held.channel_is_down())
990 };
991 if is_down(state) && previous.as_ref() != Some(state) {
992 self.distrust_z(format!(
995 "the printer went {state:?}, and Z may have moved since"
996 ));
997 }
998 let changed = previous
999 .as_ref()
1000 .filter(|previous| *previous != state && (is_down(previous) || is_down(state)));
1001 if let Some(previous) = changed {
1002 let reporting = error
1003 .filter(|error| !error.trim().is_empty())
1004 .map(|error| format!(", reporting {error:?}"))
1005 .unwrap_or_default();
1006 let mut detail = format!("the printer went from {previous:?} to {state:?}{reporting}");
1007 if channel_down {
1008 detail.push_str("; ");
1009 detail.push_str(PUSH_CHANNEL_DOWN);
1010 }
1011 let draft = self.draft_of(
1012 None,
1013 system_source(),
1014 &PrinterConnectionChangedPayload {
1015 from: previous.clone(),
1016 to: state.clone(),
1017 detail,
1018 },
1019 )?;
1020 self.stores().events.append_event(draft).await?;
1023 }
1024 self.watch_state().last_state = Some(state.clone());
1025 Ok(())
1026 }
1027
1028 async fn after_close_out(&self, print_id: PrintId) -> Result<(), CoreError> {
1032 self.forget_pushes();
1033 let Some(ended) = self
1034 .stores()
1035 .events
1036 .history(HistoryQuery {
1037 print_id,
1038 kinds: vec![PrintEndedPayload::kind()],
1039 since: None,
1040 until: None,
1041 limit: Some(1),
1042 })
1043 .await?
1044 .into_iter()
1045 .next()
1046 else {
1047 return Ok(());
1048 };
1049 let Some(Ok(payload)) = ended.payload_as::<PrintEndedPayload>() else {
1050 return Ok(());
1051 };
1052 if !matches!(
1053 payload.outcome,
1054 PrintOutcome::Interrupted | PrintOutcome::Failed
1055 ) {
1056 self.watch_state().unattended = None;
1057 return Ok(());
1058 }
1059 self.distrust_z(format!(
1060 "print {print_id} ended {}, and where it left Z is unknown",
1061 if payload.outcome == PrintOutcome::Failed {
1062 "failed"
1063 } else {
1064 "interrupted"
1065 }
1066 ));
1067 self.watch_state().unattended = Some(Unattended {
1068 print_id,
1069 began: self.clock().elapsed(),
1070 recorded: None,
1071 position: None,
1072 turned_at: None,
1073 });
1074 self.claim_after_end(print_id, ended).await
1075 }
1076
1077 async fn claim_after_end(
1080 &self,
1081 print_id: PrintId,
1082 event: EventRecord,
1083 ) -> Result<(), CoreError> {
1084 let Some(print) = self.stores().prints.print(print_id).await? else {
1085 return Ok(());
1086 };
1087 let arrival = Arrival {
1088 frame_captured_at: None,
1089 event,
1090 detection: None,
1091 camera_frame: crate::inbox::AlertCameraFrame::NotAsked,
1092 };
1093 if self.inboxes().claim_or_hand_over(print_id, arrival.clone()) {
1094 self.watch_state()
1095 .pending_turns
1096 .push(PendingTurn::new(print, arrival, Vec::new()));
1097 }
1098 Ok(())
1099 }
1100
1101 async fn watch_unattended(
1104 &self,
1105 observed: &ObservedJob,
1106 probe: &dyn PositionProbe,
1107 ) -> Result<(), CoreError> {
1108 let window = self.config().unattended_window;
1109 let now = self.clock().elapsed();
1110 let (print_id, last_position, channel_down) = {
1111 let mut held = self.watch_state();
1112 let Some(open) = &held.unattended else {
1113 return Ok(());
1114 };
1115 if now.saturating_sub(open.began) > window {
1116 held.unattended = None;
1117 return Ok(());
1118 }
1119 (open.print_id, open.position, held.channel_is_down())
1120 };
1121 if job_runs(&observed.job.state) || is_down(&observed.job.state) {
1122 return Ok(());
1123 }
1124 let Ok(snapshot) = self.read_snapshot().await else {
1125 return Ok(());
1126 };
1127 if job_runs(&snapshot.connection) || is_down(&snapshot.connection) {
1128 return Ok(());
1129 }
1130 let (tools, bed) = heated(&snapshot);
1131 let position = probe.read_position().await;
1132 let moved = match (last_position, position) {
1133 (_, None) => None,
1134 (None, Some(_)) => Some(false),
1135 (Some(before), Some(after)) => Some(before != after),
1136 };
1137 let activity = Activity { tools, bed, moved };
1138 let unchanged = {
1139 let mut held = self.watch_state();
1140 let Some(open) = held
1141 .unattended
1142 .as_mut()
1143 .filter(|open| open.print_id == print_id)
1144 else {
1145 return Ok(());
1146 };
1147 if position.is_some() {
1148 open.position = position;
1149 }
1150 if !activity.is_active() {
1151 open.recorded = None;
1152 return Ok(());
1153 }
1154 open.recorded.as_ref() == Some(&activity)
1155 };
1156 if unchanged {
1157 return Ok(());
1158 }
1159 let draft = self.draft_of(
1160 None,
1161 system_source(),
1162 &UnattendedPrinterActivityPayload {
1163 last_print_id: print_id,
1164 tools: activity.tools.clone(),
1165 bed_target_c: activity.bed,
1166 moved: activity.moved,
1167 detail: activity_detail(&activity, channel_down),
1168 },
1169 )?;
1170 let event = self.stores().events.append_event(draft).await?;
1171 let interval = self.config().observation_interval;
1172 let turn_due = {
1173 let mut held = self.watch_state();
1174 let Some(open) = held.unattended.as_mut() else {
1175 return Ok(());
1176 };
1177 open.recorded = Some(activity.clone());
1180 open.turned_at
1181 .is_none_or(|turned| now.saturating_sub(turned) >= interval)
1182 };
1183 if turn_due {
1184 self.claim_activity_turn(print_id, event).await;
1185 }
1186 Ok(())
1187 }
1188
1189 async fn claim_activity_turn(&self, print_id: PrintId, event: EventRecord) {
1193 if self.claim_after_end(print_id, event.clone()).await.is_err() {
1194 self.watch_state().pending_claims.push((print_id, event));
1195 return;
1196 }
1197 let now = self.clock().elapsed();
1198 if let Some(open) = self
1199 .watch_state()
1200 .unattended
1201 .as_mut()
1202 .filter(|open| open.print_id == print_id)
1203 {
1204 open.turned_at = Some(now);
1205 }
1206 }
1207
1208 pub async fn check_detector(
1221 &self,
1222 probe: &dyn DetectorProbe,
1223 ) -> Result<Option<PendingTurn>, CoreError> {
1224 let Some(print) = self.stores().prints.open_prints().await?.into_iter().next() else {
1225 return Ok(None);
1226 };
1227 let (status, detail) = match probe.check().await {
1228 Ok(detail) => (DetectorStatus::Available, detail),
1229 Err(detail) => (DetectorStatus::Unavailable, detail),
1230 };
1231 let health = match status {
1232 DetectorStatus::Available => DetectorHealthStatus::Available,
1233 DetectorStatus::Unavailable => DetectorHealthStatus::Unavailable,
1234 };
1235 let previous = self.watch_state().probe.status();
1236 if previous == health {
1237 if let ProbeHealth::Unavailable { detail: held, .. } = &mut self.watch_state().probe {
1240 held.clone_from(&detail);
1241 }
1242 return Ok(None);
1243 }
1244 let since = self.clock().now();
1245 let found = match status {
1246 DetectorStatus::Available => ProbeHealth::Available { since },
1247 DetectorStatus::Unavailable => ProbeHealth::Unavailable {
1248 since,
1249 detail: detail.clone(),
1250 },
1251 };
1252 if previous == DetectorHealthStatus::Unchecked && health == DetectorHealthStatus::Available
1255 {
1256 self.watch_state().probe = found;
1257 return Ok(None);
1258 }
1259 let draft = self.draft_of(
1260 None,
1261 system_source(),
1262 &DetectorHealthChangedPayload {
1263 status,
1264 detail: detail.clone(),
1265 },
1266 )?;
1267 let event = self.stores().events.append_event(draft).await?;
1268 self.watch_state().probe = found;
1271 if status != DetectorStatus::Unavailable {
1272 return Ok(None);
1273 }
1274 if matches!(
1275 self.detector_health_for(print.id),
1276 DetectorHealth::Scoring { .. }
1277 ) {
1278 self.record_port_failure_to(
1281 None,
1282 event.id,
1283 PortFailureSite::DetectorHealthCheck,
1284 detail,
1285 )
1286 .await;
1287 return Ok(None);
1288 }
1289 let arrival = Arrival {
1290 frame_captured_at: None,
1291 event,
1292 detection: None,
1293 camera_frame: crate::inbox::AlertCameraFrame::NotAsked,
1294 };
1295 Ok(self
1296 .inboxes()
1297 .claim_or_hand_over(print.id, arrival.clone())
1298 .then(|| PendingTurn::new(print, arrival, Vec::new())))
1299 }
1300}
1301
1302pub(crate) fn concerns_its_end(kind: &EventKind) -> bool {
1305 [
1306 PrintEndedPayload::KIND,
1307 UnattendedPrinterActivityPayload::KIND,
1308 ]
1309 .contains(&kind.as_str())
1310}
1311
1312pub(crate) fn noticed_of(event: &EventRecord) -> Option<String> {
1315 if let Some(Ok(ended)) = event.payload_as::<PrintEndedPayload>() {
1316 let outcome = match ended.outcome {
1317 PrintOutcome::Interrupted => "interrupted",
1318 PrintOutcome::Failed => "failed",
1319 PrintOutcome::Completed | PrintOutcome::Cancelled => return None,
1320 };
1321 return Some(format!(
1322 "{}: the print ended {outcome}, the printer reporting {:?} ({})",
1323 PrintEndedPayload::KIND,
1324 ended.state,
1325 ended.reason
1326 ));
1327 }
1328 if let Some(Ok(activity)) = event.payload_as::<UnattendedPrinterActivityPayload>() {
1329 return Some(format!(
1330 "{}: after print {} ended, {}",
1331 UnattendedPrinterActivityPayload::KIND,
1332 activity.last_print_id,
1333 activity.detail
1334 ));
1335 }
1336 if let Some(Ok(degraded)) = event.payload_as::<crate::kinds::CameraDegradedPayload>() {
1337 return Some(format!(
1338 "{}: the camera gave no usable frame in {} attempts, so there is no frame to look \
1339 at: {}",
1340 crate::kinds::CameraDegradedPayload::KIND,
1341 degraded.attempts,
1342 degraded.detail
1343 ));
1344 }
1345 if let Some(Ok(health)) = event.payload_as::<DetectorHealthChangedPayload>() {
1346 return Some(format!(
1347 "{}: the failure detector is {:?}, so nothing is watching the print for failures: {}",
1348 DetectorHealthChangedPayload::KIND,
1349 health.status,
1350 health.detail
1351 ));
1352 }
1353 None
1354}