1use std::time::Duration;
52
53use printobserver_printer_api::{
54 BoxFuture, PrinterErrorReason, PrinterPush, PrinterSnapshot, PrinterState,
55};
56use printobserver_types::contract::Sample;
57use printobserver_types::schemars::JsonSchema;
58use printobserver_types::serde::{Deserialize, Serialize};
59use printobserver_types::{EventKind, EventPayload as _, EventRecord, PrintId, Timestamp};
60
61use crate::error::CoreError;
62use crate::events::PendingTurn;
63use crate::inbox::Arrival;
64use crate::kinds::{
65 DetectorHealthChangedPayload, DetectorStatus, HeatedTool, PortFailureSite, PrintEndedPayload,
66 PrinterConnectionChangedPayload, PrinterResetPayload, UnattendedPrinterActivityPayload,
67 system_source,
68};
69use crate::listing::ObservedJob;
70use crate::records::{PrintOutcome, PrintRecord};
71use crate::store::HistoryQuery;
72use crate::supervisor::Supervisor;
73
74pub const DEFAULT_PRINTER_POLL: Duration = Duration::from_secs(15);
76
77pub const DEFAULT_UNATTENDED_WINDOW: Duration = Duration::from_secs(3600);
80
81pub const RESET_GRACE: Duration = Duration::from_secs(1);
89
90pub const PUSH_CHANNEL_DOWN: &str =
92 "the printer's push channel was down, so this was read from its state alone";
93
94pub const PRINTER_WATCH_KINDS: [&str; 4] = [
97 PrinterConnectionChangedPayload::KIND,
98 PrinterResetPayload::KIND,
99 UnattendedPrinterActivityPayload::KIND,
100 DetectorHealthChangedPayload::KIND,
101];
102
103#[derive(Debug, Clone, Copy, PartialEq)]
105pub struct HeadPosition {
106 pub x: f64,
108 pub y: f64,
110 pub z: f64,
112}
113
114pub trait PositionProbe: Send + Sync {
119 fn read_position(&self) -> BoxFuture<'_, Option<HeadPosition>>;
121}
122
123pub trait DetectorProbe: Send + Sync {
125 fn check(&self) -> BoxFuture<'_, Result<String, String>>;
128}
129
130#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
132#[serde(
133 crate = "printobserver_types::serde",
134 rename_all = "snake_case",
135 deny_unknown_fields
136)]
137#[schemars(crate = "printobserver_types::schemars")]
138pub enum DetectorHealthStatus {
139 ScoringNothingFlagged,
142 ScoringFlagged,
145 Available,
148 Unavailable,
151 #[default]
154 Unchecked,
155}
156
157#[derive(Debug, Clone, PartialEq, Eq)]
171pub enum DetectorHealth {
172 Unchecked {
175 scoring_unread: Option<String>,
177 },
178 Available {
181 since: Timestamp,
183 scoring_unread: Option<String>,
185 },
186 Unavailable {
189 since: Timestamp,
191 scoring_unread: Option<String>,
193 },
194 Scoring {
196 since: Timestamp,
198 verdict: ScoringVerdict,
200 probe_failure: Option<String>,
203 },
204}
205
206#[derive(Debug, Clone, Copy, PartialEq, Eq)]
208pub enum ScoringVerdict {
209 NothingFlagged,
211 Flagged,
213}
214
215impl Default for DetectorHealth {
216 fn default() -> Self {
217 Self::Unchecked {
218 scoring_unread: None,
219 }
220 }
221}
222
223impl DetectorHealth {
224 #[must_use]
226 pub const fn status(&self) -> DetectorHealthStatus {
227 match self {
228 Self::Unchecked { .. } => DetectorHealthStatus::Unchecked,
229 Self::Available { .. } => DetectorHealthStatus::Available,
230 Self::Unavailable { .. } => DetectorHealthStatus::Unavailable,
231 Self::Scoring {
232 verdict: ScoringVerdict::NothingFlagged,
233 ..
234 } => DetectorHealthStatus::ScoringNothingFlagged,
235 Self::Scoring {
236 verdict: ScoringVerdict::Flagged,
237 ..
238 } => DetectorHealthStatus::ScoringFlagged,
239 }
240 }
241}
242
243#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
245#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
246struct DetectorHealthWire {
247 status: DetectorHealthStatus,
249 #[serde(deserialize_with = "present")]
252 since: Option<Timestamp>,
253 #[serde(default, skip_serializing_if = "Option::is_none")]
255 probe_failure: Option<String>,
256 #[serde(default, skip_serializing_if = "Option::is_none")]
258 scoring_unread: Option<String>,
259}
260
261fn present<'de, D: printobserver_types::serde::Deserializer<'de>>(
264 deserializer: D,
265) -> Result<Option<Timestamp>, D::Error> {
266 Option::deserialize(deserializer)
267}
268
269impl From<DetectorHealth> for DetectorHealthWire {
270 fn from(health: DetectorHealth) -> Self {
271 let status = health.status();
272 let (since, probe_failure, scoring_unread) = match health {
273 DetectorHealth::Unchecked { scoring_unread } => (None, None, scoring_unread),
274 DetectorHealth::Available {
275 since,
276 scoring_unread,
277 }
278 | DetectorHealth::Unavailable {
279 since,
280 scoring_unread,
281 } => (Some(since), None, scoring_unread),
282 DetectorHealth::Scoring {
283 since,
284 probe_failure,
285 ..
286 } => (Some(since), probe_failure, None),
287 };
288 Self {
289 status,
290 since,
291 probe_failure,
292 scoring_unread,
293 }
294 }
295}
296
297impl TryFrom<DetectorHealthWire> for DetectorHealth {
298 type Error = &'static str;
299
300 fn try_from(wire: DetectorHealthWire) -> Result<Self, Self::Error> {
301 let DetectorHealthWire {
302 status,
303 since,
304 probe_failure,
305 scoring_unread,
306 } = wire;
307 let scoring = matches!(
308 status,
309 DetectorHealthStatus::ScoringNothingFlagged | DetectorHealthStatus::ScoringFlagged
310 );
311 if scoring && scoring_unread.is_some() {
312 return Err("a scoring detector's scoring is being read");
313 }
314 if !scoring && probe_failure.is_some() {
315 return Err("only a scoring detector names its failing health check beside it");
316 }
317 match (status, since) {
318 (DetectorHealthStatus::Unchecked, None) => Ok(Self::Unchecked { scoring_unread }),
319 (DetectorHealthStatus::Available, Some(since)) => Ok(Self::Available {
320 since,
321 scoring_unread,
322 }),
323 (DetectorHealthStatus::Unavailable, Some(since)) => Ok(Self::Unavailable {
324 since,
325 scoring_unread,
326 }),
327 (DetectorHealthStatus::ScoringNothingFlagged, Some(since)) => Ok(Self::Scoring {
328 since,
329 verdict: ScoringVerdict::NothingFlagged,
330 probe_failure,
331 }),
332 (DetectorHealthStatus::ScoringFlagged, Some(since)) => Ok(Self::Scoring {
333 since,
334 verdict: ScoringVerdict::Flagged,
335 probe_failure,
336 }),
337 (DetectorHealthStatus::Unchecked, Some(_)) => {
338 Err("an unchecked detector has no instant it became so")
339 }
340 (_, None) => Err("a checked detector carries the instant it became so"),
341 }
342 }
343}
344
345impl Serialize for DetectorHealth {
346 fn serialize<S: printobserver_types::serde::Serializer>(
347 &self,
348 serializer: S,
349 ) -> Result<S::Ok, S::Error> {
350 DetectorHealthWire::from(self.clone()).serialize(serializer)
351 }
352}
353
354impl<'de> Deserialize<'de> for DetectorHealth {
355 fn deserialize<D: printobserver_types::serde::Deserializer<'de>>(
356 deserializer: D,
357 ) -> Result<Self, D::Error> {
358 let wire = DetectorHealthWire::deserialize(deserializer)?;
359 Self::try_from(wire).map_err(printobserver_types::serde::de::Error::custom)
360 }
361}
362
363fn health_arm(
366 status: &str,
367 doc: &str,
368 since: &printobserver_types::serde_json::Value,
369 beside: (&str, &str),
370) -> printobserver_types::serde_json::Value {
371 let (field, field_doc) = beside;
372 let mut properties = printobserver_types::serde_json::Map::new();
373 properties.insert(
374 "status".to_owned(),
375 printobserver_types::serde_json::json!({ "type": "string", "const": status }),
376 );
377 properties.insert("since".to_owned(), since.clone());
378 properties.insert(
379 field.to_owned(),
380 printobserver_types::serde_json::json!({ "type": "string", "description": field_doc }),
381 );
382 printobserver_types::serde_json::json!({
383 "type": "object",
384 "description": doc,
385 "properties": properties,
386 "required": ["status", "since"],
387 "additionalProperties": false,
388 })
389}
390
391const SCORING_UNREAD_DOC: &str = "Why the detector's scoring of the print is not being read, \
393 when it is not: no Obico API is configured, no Obico printer is known yet, or the last read \
394 failed.";
395
396const PROBE_FAILURE_DOC: &str = "What the detector's health check answered, when it is \
398 failing while the detector scores the print.";
399
400impl JsonSchema for DetectorHealth {
403 fn schema_name() -> std::borrow::Cow<'static, str> {
404 std::borrow::Cow::Borrowed("DetectorHealth")
405 }
406
407 fn json_schema(
408 generator: &mut printobserver_types::schemars::SchemaGenerator,
409 ) -> printobserver_types::schemars::Schema {
410 let timestamp =
411 printobserver_types::serde_json::to_value(generator.subschema_for::<Timestamp>())
412 .unwrap_or_default();
413 let unread = ("scoring_unread", SCORING_UNREAD_DOC);
414 let failing = ("probe_failure", PROBE_FAILURE_DOC);
415 let schema = printobserver_types::serde_json::json!({
416 "title": "DetectorHealth",
417 "description": "The failure detector's status, and since when it has been so: \
418 `since` is `null` exactly while the status is `unchecked`. Evidence that the \
419 detector is scoring the print comes before its health check.",
420 "oneOf": [
421 health_arm(
422 "scoring_nothing_flagged",
423 "The detector is scoring the print, from `since` on, and no failure alert \
424 of its own has arrived for it.",
425 ×tamp,
426 failing,
427 ),
428 health_arm(
429 "scoring_flagged",
430 "The detector is scoring the print, from `since` on, and a failure alert \
431 of its own has arrived for it.",
432 ×tamp,
433 failing,
434 ),
435 health_arm(
436 "available",
437 "No evidence that the detector is scoring the print, and it answered its \
438 health check, from `since` on: available, with no scores yet.",
439 ×tamp,
440 unread,
441 ),
442 health_arm(
443 "unavailable",
444 "No evidence that the detector is scoring the print, and it did not answer \
445 its health check, from `since` on.",
446 ×tamp,
447 unread,
448 ),
449 health_arm(
450 "unchecked",
451 "No evidence of any kind: no detector health address is configured, or no \
452 check has been made yet, and nothing shows the detector scoring.",
453 &printobserver_types::serde_json::json!({
454 "type": "null",
455 "description": "Nothing: an unchecked detector has no instant it became so.",
456 }),
457 unread,
458 ),
459 ],
460 });
461 printobserver_types::schemars::Schema::try_from(schema).unwrap_or_default()
462 }
463}
464
465impl Sample for DetectorHealth {
466 fn sample_full() -> Self {
467 Self::Scoring {
468 since: Timestamp::sample_full(),
469 verdict: ScoringVerdict::NothingFlagged,
470 probe_failure: Some("the detector's health check answered 503".to_owned()),
471 }
472 }
473
474 fn sample_minimal() -> Self {
475 Self::Unchecked {
476 scoring_unread: None,
477 }
478 }
479
480 fn sample_alternates() -> Vec<Self> {
481 vec![
482 Self::Scoring {
483 since: Timestamp::sample_full(),
484 verdict: ScoringVerdict::Flagged,
485 probe_failure: None,
486 },
487 Self::Available {
488 since: Timestamp::sample_full(),
489 scoring_unread: Some(
490 "no Obico printer is known yet: no [obico] printer_id is configured and Obico \
491 has posted nothing naming one since this server started"
492 .to_owned(),
493 ),
494 },
495 Self::Unavailable {
496 since: Timestamp::sample_full(),
497 scoring_unread: None,
498 },
499 Self::Unchecked {
500 scoring_unread: Some(
501 "no [obico] url and access_token are configured, so Obico's record of the \
502 print is not read"
503 .to_owned(),
504 ),
505 },
506 ]
507 }
508}
509
510#[derive(Debug, Clone, Default, PartialEq, Eq)]
512pub(crate) enum ProbeHealth {
513 #[default]
515 Unchecked,
516 Available {
518 since: Timestamp,
520 },
521 Unavailable {
523 since: Timestamp,
525 detail: String,
527 },
528}
529
530impl ProbeHealth {
531 const fn status(&self) -> DetectorHealthStatus {
533 match self {
534 Self::Unchecked => DetectorHealthStatus::Unchecked,
535 Self::Available { .. } => DetectorHealthStatus::Available,
536 Self::Unavailable { .. } => DetectorHealthStatus::Unavailable,
537 }
538 }
539}
540
541#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
545pub(crate) struct PushFacts {
546 pub(crate) reset: bool,
548 pub(crate) firmware_error: bool,
550 pub(crate) gap: bool,
553}
554
555#[derive(Debug, Clone, PartialEq)]
557struct Activity {
558 tools: Vec<HeatedTool>,
560 bed: Option<f64>,
562 moved: Option<bool>,
564}
565
566impl Activity {
567 fn is_active(&self) -> bool {
569 !self.tools.is_empty() || self.bed.is_some() || self.moved == Some(true)
570 }
571}
572
573#[derive(Debug, Clone)]
575struct Unattended {
576 print_id: PrintId,
578 began: Duration,
580 recorded: Option<Activity>,
582 position: Option<HeadPosition>,
584 turned_at: Option<Duration>,
587}
588
589#[derive(Debug, Default)]
591pub(crate) struct WatchState {
592 last_state: Option<PrinterState>,
594 pushes: PushFacts,
596 channel: Channel,
598 unattended: Option<Unattended>,
600 pub(crate) probe: ProbeHealth,
602 pub(crate) scoring: crate::scoring::ScoringState,
604 pending_turns: Vec<PendingTurn>,
606 pending_resets: Vec<PrinterResetPayload>,
608 pending_ends: Vec<PrintId>,
611 pending_claims: Vec<(PrintId, EventRecord)>,
614}
615
616impl WatchState {
617 const fn channel_is_down(&self) -> bool {
619 !matches!(self.channel, Channel::Open)
620 }
621}
622
623#[derive(Debug, Clone, Default, PartialEq, Eq)]
625enum Channel {
626 #[default]
628 Unknown,
629 Open,
631 Down(String),
633}
634
635#[derive(Debug, Default)]
637pub struct Watched {
638 pub turns: Vec<PendingTurn>,
641 pub active: Option<ActiveJob>,
644}
645
646#[derive(Debug, Clone, Copy, PartialEq, Eq)]
649pub struct ActiveJob {
650 pub print_id: PrintId,
652 pub file_position_bytes: Option<i64>,
654}
655
656const fn is_down(state: &PrinterState) -> bool {
658 matches!(state, PrinterState::Offline | PrinterState::Error)
659}
660
661const fn job_runs(state: &PrinterState) -> bool {
663 matches!(
664 state,
665 PrinterState::Printing | PrinterState::Paused | PrinterState::Cancelling
666 )
667}
668
669fn heated(snapshot: &PrinterSnapshot) -> (Vec<HeatedTool>, Option<f64>) {
671 let tools = snapshot
672 .tools
673 .iter()
674 .enumerate()
675 .filter_map(|(index, heater)| {
676 let target = heater.target_c.as_ref()?.value();
677 (target > 0.0).then(|| HeatedTool {
678 tool: i64::try_from(index).unwrap_or(i64::MAX),
679 target_c: target,
680 })
681 })
682 .collect();
683 let bed = snapshot
684 .bed
685 .as_ref()
686 .and_then(|bed| bed.target_c.as_ref())
687 .map(printobserver_types::Reported::value)
688 .filter(|target| *target > 0.0);
689 (tools, bed)
690}
691
692fn activity_detail(activity: &Activity, channel_down: bool) -> String {
694 let mut parts: Vec<String> = activity
695 .tools
696 .iter()
697 .map(|tool| format!("tool {} is heating to {} °C", tool.tool, tool.target_c))
698 .collect();
699 if let Some(bed) = activity.bed {
700 parts.push(format!("the bed is heating to {bed} °C"));
701 }
702 match activity.moved {
703 Some(true) => parts.push("the print head moved".to_owned()),
704 Some(false) => {}
705 None => parts.push("the print head's position could not be read".to_owned()),
706 }
707 let mut detail = format!("with no job running, {}", parts.join(", "));
708 if channel_down {
709 detail.push_str("; ");
710 detail.push_str(PUSH_CHANNEL_DOWN);
711 }
712 detail
713}
714
715impl Supervisor {
716 pub(crate) fn watch_state(&self) -> std::sync::MutexGuard<'_, WatchState> {
718 self.watch
719 .lock()
720 .unwrap_or_else(std::sync::PoisonError::into_inner)
721 }
722
723 pub(crate) fn push_facts(&self) -> PushFacts {
725 let state = self.watch_state();
726 let mut facts = state.pushes;
727 facts.gap |= state.channel_is_down();
728 facts
729 }
730
731 pub(crate) async fn pushes_after_a_reset_could_arrive(&self) -> PushFacts {
735 let started = std::time::Instant::now();
738 loop {
739 let facts = self.push_facts();
740 if facts.reset
741 || self.watch_state().channel_is_down()
742 || started.elapsed() >= RESET_GRACE
743 || crate::delay::Delay::new(Duration::from_millis(50))
744 .await
745 .is_err()
746 {
747 return facts;
748 }
749 }
750 }
751
752 pub(crate) fn note_job_running(&self) {
754 self.watch_state().unattended = None;
755 }
756
757 pub(crate) fn forget_pushes(&self) {
760 let mut state = self.watch_state();
761 let gap = state.channel_is_down();
762 state.pushes = PushFacts {
763 gap,
764 ..PushFacts::default()
765 };
766 }
767
768 #[must_use]
773 pub fn detector_health(&self) -> DetectorHealth {
774 self.detector_health_of(None)
775 }
776
777 #[must_use]
780 pub fn detector_health_for(&self, print_id: PrintId) -> DetectorHealth {
781 self.detector_health_of(Some(print_id))
782 }
783
784 fn detector_health_of(&self, print_id: Option<PrintId>) -> DetectorHealth {
787 let window = self
788 .config()
789 .observation_interval
790 .saturating_mul(crate::scoring::EVIDENCE_INTERVALS);
791 let now = self.clock().elapsed();
792 let held = self.watch_state();
793 if let Some(scoring) = held.scoring.scoring(print_id, now, window) {
794 return DetectorHealth::Scoring {
795 since: scoring.since,
796 verdict: scoring.verdict,
797 probe_failure: match &held.probe {
798 ProbeHealth::Unavailable { detail, .. } => Some(detail.clone()),
799 ProbeHealth::Unchecked | ProbeHealth::Available { .. } => None,
800 },
801 };
802 }
803 let scoring_unread = held.scoring.unread().map(str::to_owned);
804 match &held.probe {
805 ProbeHealth::Unchecked => DetectorHealth::Unchecked { scoring_unread },
806 ProbeHealth::Available { since } => DetectorHealth::Available {
807 since: *since,
808 scoring_unread,
809 },
810 ProbeHealth::Unavailable { since, .. } => DetectorHealth::Unavailable {
811 since: *since,
812 scoring_unread,
813 },
814 }
815 }
816
817 pub fn note_push_channel(&self, open: Result<(), String>) {
822 let mut state = self.watch_state();
823 match open {
824 Ok(()) => state.channel = Channel::Open,
825 Err(detail) => {
826 state.channel = Channel::Down(detail);
827 state.pushes.gap = true;
828 }
829 }
830 }
831
832 pub async fn note_push(&self, push: PrinterPush) -> Result<(), CoreError> {
843 match push {
844 PrinterPush::Reset => {
845 self.distrust_z("the printer pushed a reset, and a reset forgets where Z is");
847 let running = self.running_print().await;
854 self.watch_state().pushes.reset = true;
855 let (during_print, detail) = match running {
858 Ok(Some(print)) => (
859 Some(print.id),
860 format!("the printer pushed a reset during print {}", print.id),
861 ),
862 Ok(None) => (
863 None,
864 "the printer pushed a reset while no print was running".to_owned(),
865 ),
866 Err(error) => (
867 None,
868 format!(
869 "the printer pushed a reset; which print was running could not be \
870 read: {error}"
871 ),
872 ),
873 };
874 let payload = PrinterResetPayload {
875 during_print,
876 detail,
877 };
878 if let Err(error) = self.write_reset(&payload).await {
879 self.watch_state().pending_resets.push(payload);
882 return Err(error);
883 }
884 Ok(())
885 }
886 PrinterPush::Error {
887 reason: PrinterErrorReason::Firmware,
888 } => {
889 self.watch_state().pushes.firmware_error = true;
890 Ok(())
891 }
892 PrinterPush::Error {
893 reason: PrinterErrorReason::Other(_),
894 }
895 | PrinterPush::Log { .. } => Ok(()),
896 }
897 }
898
899 async fn write_reset(&self, payload: &PrinterResetPayload) -> Result<(), CoreError> {
901 let draft = self.draft_of(None, system_source(), payload)?;
902 self.stores().events.append_event(draft).await?;
903 Ok(())
904 }
905
906 async fn catch_up(&self) {
910 let resets = std::mem::take(&mut self.watch_state().pending_resets);
911 for payload in resets {
912 if self.write_reset(&payload).await.is_err() {
913 self.watch_state().pending_resets.push(payload);
914 }
915 }
916 let ends = std::mem::take(&mut self.watch_state().pending_ends);
917 for print_id in ends {
918 if self.after_close_out(print_id).await.is_err() {
919 self.watch_state().pending_ends.push(print_id);
920 }
921 }
922 let claims = std::mem::take(&mut self.watch_state().pending_claims);
923 for (print_id, event) in claims {
924 self.claim_activity_turn(print_id, event).await;
925 }
926 }
927
928 pub(crate) async fn follow_up_end(&self, print_id: PrintId) {
931 if self.after_close_out(print_id).await.is_err() {
932 self.watch_state().pending_ends.push(print_id);
933 }
934 }
935
936 async fn running_print(&self) -> Result<Option<PrintRecord>, CoreError> {
938 Ok(self
939 .stores()
940 .prints
941 .open_prints()
942 .await?
943 .into_iter()
944 .find(|print| self.was_seen_running(print.id)))
945 }
946
947 pub async fn watch_printer(&self, probe: &dyn PositionProbe) -> Result<Watched, CoreError> {
957 self.catch_up().await;
958 let resolving = self.resolving().await;
959 let observed = self.observe_job().await;
960 let mut active = None;
961 if let Some(observed) = &observed {
962 self.note_connection(
963 &observed.job.state,
964 observed.job.error.as_ref().map(|error| error.text.as_str()),
965 )
966 .await?;
967 active = self
968 .settle_and_adopt(observed)
969 .await?
970 .map(|print_id| ActiveJob {
971 print_id,
972 file_position_bytes: observed.job.file_position_bytes,
973 });
974 }
975 drop(resolving);
976 if let Some(observed) = &observed {
977 self.watch_unattended(observed, probe).await?;
978 if let Some(active) = &active
979 && let Some(print) = self.stores().prints.print(active.print_id).await?
980 {
981 if let Some(turn) = self
982 .follow_planned_changes(&print, &observed.job, true)
983 .await?
984 {
985 self.watch_state().pending_turns.push(turn);
986 }
987 if let Some(turn) = self.follow_pauses(&print, &observed.job).await? {
988 self.watch_state().pending_turns.push(turn);
989 }
990 }
991 }
992 Ok(Watched {
993 turns: std::mem::take(&mut self.watch_state().pending_turns),
994 active,
995 })
996 }
997
998 async fn note_connection(
1001 &self,
1002 state: &PrinterState,
1003 error: Option<&str>,
1004 ) -> Result<(), CoreError> {
1005 let (previous, channel_down) = {
1006 let held = self.watch_state();
1007 (held.last_state.clone(), held.channel_is_down())
1008 };
1009 if is_down(state) && previous.as_ref() != Some(state) {
1010 self.distrust_z(format!(
1013 "the printer went {state:?}, and Z may have moved since"
1014 ));
1015 }
1016 let changed = previous
1017 .as_ref()
1018 .filter(|previous| *previous != state && (is_down(previous) || is_down(state)));
1019 if let Some(previous) = changed {
1020 let reporting = error
1021 .filter(|error| !error.trim().is_empty())
1022 .map(|error| format!(", reporting {error:?}"))
1023 .unwrap_or_default();
1024 let mut detail = format!("the printer went from {previous:?} to {state:?}{reporting}");
1025 if channel_down {
1026 detail.push_str("; ");
1027 detail.push_str(PUSH_CHANNEL_DOWN);
1028 }
1029 let draft = self.draft_of(
1030 None,
1031 system_source(),
1032 &PrinterConnectionChangedPayload {
1033 from: previous.clone(),
1034 to: state.clone(),
1035 detail,
1036 },
1037 )?;
1038 self.stores().events.append_event(draft).await?;
1041 }
1042 self.watch_state().last_state = Some(state.clone());
1043 Ok(())
1044 }
1045
1046 async fn after_close_out(&self, print_id: PrintId) -> Result<(), CoreError> {
1050 self.forget_pushes();
1051 let Some(ended) = self
1052 .stores()
1053 .events
1054 .history(HistoryQuery {
1055 print_id,
1056 kinds: vec![PrintEndedPayload::kind()],
1057 since: None,
1058 until: None,
1059 limit: Some(1),
1060 })
1061 .await?
1062 .into_iter()
1063 .next()
1064 else {
1065 return Ok(());
1066 };
1067 let Some(Ok(payload)) = ended.payload_as::<PrintEndedPayload>() else {
1068 return Ok(());
1069 };
1070 if !matches!(
1071 payload.outcome,
1072 PrintOutcome::Interrupted | PrintOutcome::Failed
1073 ) {
1074 self.watch_state().unattended = None;
1075 return Ok(());
1076 }
1077 self.distrust_z(format!(
1078 "print {print_id} ended {}, and where it left Z is unknown",
1079 if payload.outcome == PrintOutcome::Failed {
1080 "failed"
1081 } else {
1082 "interrupted"
1083 }
1084 ));
1085 self.watch_state().unattended = Some(Unattended {
1086 print_id,
1087 began: self.clock().elapsed(),
1088 recorded: None,
1089 position: None,
1090 turned_at: None,
1091 });
1092 self.claim_after_end(print_id, ended).await
1093 }
1094
1095 async fn claim_after_end(
1098 &self,
1099 print_id: PrintId,
1100 event: EventRecord,
1101 ) -> Result<(), CoreError> {
1102 let Some(print) = self.stores().prints.print(print_id).await? else {
1103 return Ok(());
1104 };
1105 let arrival = Arrival {
1106 frame_captured_at: None,
1107 event,
1108 detection: None,
1109 camera_frame: crate::inbox::AlertCameraFrame::NotAsked,
1110 };
1111 if self.inboxes().claim_or_hand_over(print_id, arrival.clone()) {
1112 self.watch_state()
1113 .pending_turns
1114 .push(PendingTurn::new(print, arrival, Vec::new()));
1115 }
1116 Ok(())
1117 }
1118
1119 async fn watch_unattended(
1122 &self,
1123 observed: &ObservedJob,
1124 probe: &dyn PositionProbe,
1125 ) -> Result<(), CoreError> {
1126 let window = self.config().unattended_window;
1127 let now = self.clock().elapsed();
1128 let (print_id, last_position, channel_down) = {
1129 let mut held = self.watch_state();
1130 let Some(open) = &held.unattended else {
1131 return Ok(());
1132 };
1133 if now.saturating_sub(open.began) > window {
1134 held.unattended = None;
1135 return Ok(());
1136 }
1137 (open.print_id, open.position, held.channel_is_down())
1138 };
1139 if job_runs(&observed.job.state) || is_down(&observed.job.state) {
1140 return Ok(());
1141 }
1142 let Ok(snapshot) = self.read_snapshot().await else {
1143 return Ok(());
1144 };
1145 if job_runs(&snapshot.connection) || is_down(&snapshot.connection) {
1146 return Ok(());
1147 }
1148 let (tools, bed) = heated(&snapshot);
1149 let position = probe.read_position().await;
1150 let moved = match (last_position, position) {
1151 (_, None) => None,
1152 (None, Some(_)) => Some(false),
1153 (Some(before), Some(after)) => Some(before != after),
1154 };
1155 let activity = Activity { tools, bed, moved };
1156 let unchanged = {
1157 let mut held = self.watch_state();
1158 let Some(open) = held
1159 .unattended
1160 .as_mut()
1161 .filter(|open| open.print_id == print_id)
1162 else {
1163 return Ok(());
1164 };
1165 if position.is_some() {
1166 open.position = position;
1167 }
1168 if !activity.is_active() {
1169 open.recorded = None;
1170 return Ok(());
1171 }
1172 open.recorded.as_ref() == Some(&activity)
1173 };
1174 if unchanged {
1175 return Ok(());
1176 }
1177 let draft = self.draft_of(
1178 None,
1179 system_source(),
1180 &UnattendedPrinterActivityPayload {
1181 last_print_id: print_id,
1182 tools: activity.tools.clone(),
1183 bed_target_c: activity.bed,
1184 moved: activity.moved,
1185 detail: activity_detail(&activity, channel_down),
1186 },
1187 )?;
1188 let event = self.stores().events.append_event(draft).await?;
1189 let interval = self.config().observation_interval;
1190 let turn_due = {
1191 let mut held = self.watch_state();
1192 let Some(open) = held.unattended.as_mut() else {
1193 return Ok(());
1194 };
1195 open.recorded = Some(activity.clone());
1198 open.turned_at
1199 .is_none_or(|turned| now.saturating_sub(turned) >= interval)
1200 };
1201 if turn_due {
1202 self.claim_activity_turn(print_id, event).await;
1203 }
1204 Ok(())
1205 }
1206
1207 async fn claim_activity_turn(&self, print_id: PrintId, event: EventRecord) {
1211 if self.claim_after_end(print_id, event.clone()).await.is_err() {
1212 self.watch_state().pending_claims.push((print_id, event));
1213 return;
1214 }
1215 let now = self.clock().elapsed();
1216 if let Some(open) = self
1217 .watch_state()
1218 .unattended
1219 .as_mut()
1220 .filter(|open| open.print_id == print_id)
1221 {
1222 open.turned_at = Some(now);
1223 }
1224 }
1225
1226 pub async fn check_detector(
1239 &self,
1240 probe: &dyn DetectorProbe,
1241 ) -> Result<Option<PendingTurn>, CoreError> {
1242 let Some(print) = self.stores().prints.open_prints().await?.into_iter().next() else {
1243 return Ok(None);
1244 };
1245 let (status, detail) = match probe.check().await {
1246 Ok(detail) => (DetectorStatus::Available, detail),
1247 Err(detail) => (DetectorStatus::Unavailable, detail),
1248 };
1249 let health = match status {
1250 DetectorStatus::Available => DetectorHealthStatus::Available,
1251 DetectorStatus::Unavailable => DetectorHealthStatus::Unavailable,
1252 };
1253 let previous = self.watch_state().probe.status();
1254 if previous == health {
1255 if let ProbeHealth::Unavailable { detail: held, .. } = &mut self.watch_state().probe {
1258 held.clone_from(&detail);
1259 }
1260 return Ok(None);
1261 }
1262 let since = self.clock().now();
1263 let found = match status {
1264 DetectorStatus::Available => ProbeHealth::Available { since },
1265 DetectorStatus::Unavailable => ProbeHealth::Unavailable {
1266 since,
1267 detail: detail.clone(),
1268 },
1269 };
1270 if previous == DetectorHealthStatus::Unchecked && health == DetectorHealthStatus::Available
1273 {
1274 self.watch_state().probe = found;
1275 return Ok(None);
1276 }
1277 let draft = self.draft_of(
1278 None,
1279 system_source(),
1280 &DetectorHealthChangedPayload {
1281 status,
1282 detail: detail.clone(),
1283 },
1284 )?;
1285 let event = self.stores().events.append_event(draft).await?;
1286 self.watch_state().probe = found;
1289 if status != DetectorStatus::Unavailable {
1290 return Ok(None);
1291 }
1292 if matches!(
1293 self.detector_health_for(print.id),
1294 DetectorHealth::Scoring { .. }
1295 ) {
1296 self.record_port_failure_to(
1299 None,
1300 event.id,
1301 PortFailureSite::DetectorHealthCheck,
1302 detail,
1303 )
1304 .await;
1305 return Ok(None);
1306 }
1307 if !self.turns_allowed(print.id).await? {
1308 return Ok(None);
1309 }
1310 let arrival = Arrival {
1311 frame_captured_at: None,
1312 event,
1313 detection: None,
1314 camera_frame: crate::inbox::AlertCameraFrame::NotAsked,
1315 };
1316 Ok(self
1317 .inboxes()
1318 .claim_or_hand_over(print.id, arrival.clone())
1319 .then(|| PendingTurn::new(print, arrival, Vec::new())))
1320 }
1321}
1322
1323pub(crate) fn concerns_its_end(kind: &EventKind) -> bool {
1326 [
1327 PrintEndedPayload::KIND,
1328 UnattendedPrinterActivityPayload::KIND,
1329 ]
1330 .contains(&kind.as_str())
1331}
1332
1333fn resumed_noticed(resumed: &crate::kinds::FilamentChangePlannedResumedPayload) -> String {
1337 let named = |colour: Option<&str>| {
1338 colour.map_or_else(
1339 || "a colour the file does not name".to_owned(),
1340 str::to_owned,
1341 )
1342 };
1343 let change = &resumed.change;
1344 let what = match change.kind {
1345 crate::gcode_index::PlannedChangeKind::ColorChange => "colour change",
1346 crate::gcode_index::PlannedChangeKind::Pause => "pause",
1347 };
1348 format!(
1349 "{}: the print carried on from planned {what} {} after waiting {} s; the expected colour \
1350 is {} from layer {} (Z {} mm) up, and the colour before it was {}",
1351 crate::kinds::FilamentChangePlannedResumedPayload::KIND,
1352 change.index.saturating_add(1),
1353 resumed.waited_s,
1354 named(change.color.as_deref()),
1355 change.layer,
1356 change.z_mm,
1357 named(resumed.previous_color.as_deref()),
1358 )
1359}
1360
1361pub(crate) fn noticed_of(event: &EventRecord) -> Option<String> {
1364 if let Some(Ok(ended)) = event.payload_as::<PrintEndedPayload>() {
1365 let outcome = match ended.outcome {
1366 PrintOutcome::Interrupted => "interrupted",
1367 PrintOutcome::Failed => "failed",
1368 PrintOutcome::Completed | PrintOutcome::Cancelled => return None,
1369 };
1370 return Some(format!(
1371 "{}: the print ended {outcome}, the printer reporting {:?} ({})",
1372 PrintEndedPayload::KIND,
1373 ended.state,
1374 ended.reason
1375 ));
1376 }
1377 if let Some(Ok(activity)) = event.payload_as::<UnattendedPrinterActivityPayload>() {
1378 return Some(format!(
1379 "{}: after print {} ended, {}",
1380 UnattendedPrinterActivityPayload::KIND,
1381 activity.last_print_id,
1382 activity.detail
1383 ));
1384 }
1385 if let Some(Ok(degraded)) = event.payload_as::<crate::kinds::CameraDegradedPayload>() {
1386 return Some(format!(
1387 "{}: the camera gave no usable frame in {} attempts, so there is no frame to look \
1388 at: {}",
1389 crate::kinds::CameraDegradedPayload::KIND,
1390 degraded.attempts,
1391 degraded.detail
1392 ));
1393 }
1394 if let Some(Ok(resumed)) =
1395 event.payload_as::<crate::kinds::FilamentChangePlannedResumedPayload>()
1396 {
1397 return Some(resumed_noticed(&resumed));
1398 }
1399 if let Some(Ok(health)) = event.payload_as::<DetectorHealthChangedPayload>() {
1400 return Some(format!(
1401 "{}: the failure detector is {:?}, so nothing is watching the print for failures: {}",
1402 DetectorHealthChangedPayload::KIND,
1403 health.status,
1404 health.detail
1405 ));
1406 }
1407 None
1408}