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 if let Some(active) = &active
974 && let Some(print) = self.stores().prints.print(active.print_id).await?
975 && let Some(turn) = self
976 .follow_planned_changes(&print, &observed.job, true)
977 .await?
978 {
979 self.watch_state().pending_turns.push(turn);
980 }
981 }
982 Ok(Watched {
983 turns: std::mem::take(&mut self.watch_state().pending_turns),
984 active,
985 })
986 }
987
988 async fn note_connection(
991 &self,
992 state: &PrinterState,
993 error: Option<&str>,
994 ) -> Result<(), CoreError> {
995 let (previous, channel_down) = {
996 let held = self.watch_state();
997 (held.last_state.clone(), held.channel_is_down())
998 };
999 if is_down(state) && previous.as_ref() != Some(state) {
1000 self.distrust_z(format!(
1003 "the printer went {state:?}, and Z may have moved since"
1004 ));
1005 }
1006 let changed = previous
1007 .as_ref()
1008 .filter(|previous| *previous != state && (is_down(previous) || is_down(state)));
1009 if let Some(previous) = changed {
1010 let reporting = error
1011 .filter(|error| !error.trim().is_empty())
1012 .map(|error| format!(", reporting {error:?}"))
1013 .unwrap_or_default();
1014 let mut detail = format!("the printer went from {previous:?} to {state:?}{reporting}");
1015 if channel_down {
1016 detail.push_str("; ");
1017 detail.push_str(PUSH_CHANNEL_DOWN);
1018 }
1019 let draft = self.draft_of(
1020 None,
1021 system_source(),
1022 &PrinterConnectionChangedPayload {
1023 from: previous.clone(),
1024 to: state.clone(),
1025 detail,
1026 },
1027 )?;
1028 self.stores().events.append_event(draft).await?;
1031 }
1032 self.watch_state().last_state = Some(state.clone());
1033 Ok(())
1034 }
1035
1036 async fn after_close_out(&self, print_id: PrintId) -> Result<(), CoreError> {
1040 self.forget_pushes();
1041 let Some(ended) = self
1042 .stores()
1043 .events
1044 .history(HistoryQuery {
1045 print_id,
1046 kinds: vec![PrintEndedPayload::kind()],
1047 since: None,
1048 until: None,
1049 limit: Some(1),
1050 })
1051 .await?
1052 .into_iter()
1053 .next()
1054 else {
1055 return Ok(());
1056 };
1057 let Some(Ok(payload)) = ended.payload_as::<PrintEndedPayload>() else {
1058 return Ok(());
1059 };
1060 if !matches!(
1061 payload.outcome,
1062 PrintOutcome::Interrupted | PrintOutcome::Failed
1063 ) {
1064 self.watch_state().unattended = None;
1065 return Ok(());
1066 }
1067 self.distrust_z(format!(
1068 "print {print_id} ended {}, and where it left Z is unknown",
1069 if payload.outcome == PrintOutcome::Failed {
1070 "failed"
1071 } else {
1072 "interrupted"
1073 }
1074 ));
1075 self.watch_state().unattended = Some(Unattended {
1076 print_id,
1077 began: self.clock().elapsed(),
1078 recorded: None,
1079 position: None,
1080 turned_at: None,
1081 });
1082 self.claim_after_end(print_id, ended).await
1083 }
1084
1085 async fn claim_after_end(
1088 &self,
1089 print_id: PrintId,
1090 event: EventRecord,
1091 ) -> Result<(), CoreError> {
1092 let Some(print) = self.stores().prints.print(print_id).await? else {
1093 return Ok(());
1094 };
1095 let arrival = Arrival {
1096 frame_captured_at: None,
1097 event,
1098 detection: None,
1099 camera_frame: crate::inbox::AlertCameraFrame::NotAsked,
1100 };
1101 if self.inboxes().claim_or_hand_over(print_id, arrival.clone()) {
1102 self.watch_state()
1103 .pending_turns
1104 .push(PendingTurn::new(print, arrival, Vec::new()));
1105 }
1106 Ok(())
1107 }
1108
1109 async fn watch_unattended(
1112 &self,
1113 observed: &ObservedJob,
1114 probe: &dyn PositionProbe,
1115 ) -> Result<(), CoreError> {
1116 let window = self.config().unattended_window;
1117 let now = self.clock().elapsed();
1118 let (print_id, last_position, channel_down) = {
1119 let mut held = self.watch_state();
1120 let Some(open) = &held.unattended else {
1121 return Ok(());
1122 };
1123 if now.saturating_sub(open.began) > window {
1124 held.unattended = None;
1125 return Ok(());
1126 }
1127 (open.print_id, open.position, held.channel_is_down())
1128 };
1129 if job_runs(&observed.job.state) || is_down(&observed.job.state) {
1130 return Ok(());
1131 }
1132 let Ok(snapshot) = self.read_snapshot().await else {
1133 return Ok(());
1134 };
1135 if job_runs(&snapshot.connection) || is_down(&snapshot.connection) {
1136 return Ok(());
1137 }
1138 let (tools, bed) = heated(&snapshot);
1139 let position = probe.read_position().await;
1140 let moved = match (last_position, position) {
1141 (_, None) => None,
1142 (None, Some(_)) => Some(false),
1143 (Some(before), Some(after)) => Some(before != after),
1144 };
1145 let activity = Activity { tools, bed, moved };
1146 let unchanged = {
1147 let mut held = self.watch_state();
1148 let Some(open) = held
1149 .unattended
1150 .as_mut()
1151 .filter(|open| open.print_id == print_id)
1152 else {
1153 return Ok(());
1154 };
1155 if position.is_some() {
1156 open.position = position;
1157 }
1158 if !activity.is_active() {
1159 open.recorded = None;
1160 return Ok(());
1161 }
1162 open.recorded.as_ref() == Some(&activity)
1163 };
1164 if unchanged {
1165 return Ok(());
1166 }
1167 let draft = self.draft_of(
1168 None,
1169 system_source(),
1170 &UnattendedPrinterActivityPayload {
1171 last_print_id: print_id,
1172 tools: activity.tools.clone(),
1173 bed_target_c: activity.bed,
1174 moved: activity.moved,
1175 detail: activity_detail(&activity, channel_down),
1176 },
1177 )?;
1178 let event = self.stores().events.append_event(draft).await?;
1179 let interval = self.config().observation_interval;
1180 let turn_due = {
1181 let mut held = self.watch_state();
1182 let Some(open) = held.unattended.as_mut() else {
1183 return Ok(());
1184 };
1185 open.recorded = Some(activity.clone());
1188 open.turned_at
1189 .is_none_or(|turned| now.saturating_sub(turned) >= interval)
1190 };
1191 if turn_due {
1192 self.claim_activity_turn(print_id, event).await;
1193 }
1194 Ok(())
1195 }
1196
1197 async fn claim_activity_turn(&self, print_id: PrintId, event: EventRecord) {
1201 if self.claim_after_end(print_id, event.clone()).await.is_err() {
1202 self.watch_state().pending_claims.push((print_id, event));
1203 return;
1204 }
1205 let now = self.clock().elapsed();
1206 if let Some(open) = self
1207 .watch_state()
1208 .unattended
1209 .as_mut()
1210 .filter(|open| open.print_id == print_id)
1211 {
1212 open.turned_at = Some(now);
1213 }
1214 }
1215
1216 pub async fn check_detector(
1229 &self,
1230 probe: &dyn DetectorProbe,
1231 ) -> Result<Option<PendingTurn>, CoreError> {
1232 let Some(print) = self.stores().prints.open_prints().await?.into_iter().next() else {
1233 return Ok(None);
1234 };
1235 let (status, detail) = match probe.check().await {
1236 Ok(detail) => (DetectorStatus::Available, detail),
1237 Err(detail) => (DetectorStatus::Unavailable, detail),
1238 };
1239 let health = match status {
1240 DetectorStatus::Available => DetectorHealthStatus::Available,
1241 DetectorStatus::Unavailable => DetectorHealthStatus::Unavailable,
1242 };
1243 let previous = self.watch_state().probe.status();
1244 if previous == health {
1245 if let ProbeHealth::Unavailable { detail: held, .. } = &mut self.watch_state().probe {
1248 held.clone_from(&detail);
1249 }
1250 return Ok(None);
1251 }
1252 let since = self.clock().now();
1253 let found = match status {
1254 DetectorStatus::Available => ProbeHealth::Available { since },
1255 DetectorStatus::Unavailable => ProbeHealth::Unavailable {
1256 since,
1257 detail: detail.clone(),
1258 },
1259 };
1260 if previous == DetectorHealthStatus::Unchecked && health == DetectorHealthStatus::Available
1263 {
1264 self.watch_state().probe = found;
1265 return Ok(None);
1266 }
1267 let draft = self.draft_of(
1268 None,
1269 system_source(),
1270 &DetectorHealthChangedPayload {
1271 status,
1272 detail: detail.clone(),
1273 },
1274 )?;
1275 let event = self.stores().events.append_event(draft).await?;
1276 self.watch_state().probe = found;
1279 if status != DetectorStatus::Unavailable {
1280 return Ok(None);
1281 }
1282 if matches!(
1283 self.detector_health_for(print.id),
1284 DetectorHealth::Scoring { .. }
1285 ) {
1286 self.record_port_failure_to(
1289 None,
1290 event.id,
1291 PortFailureSite::DetectorHealthCheck,
1292 detail,
1293 )
1294 .await;
1295 return Ok(None);
1296 }
1297 if !self.turns_allowed(print.id).await? {
1298 return Ok(None);
1299 }
1300 let arrival = Arrival {
1301 frame_captured_at: None,
1302 event,
1303 detection: None,
1304 camera_frame: crate::inbox::AlertCameraFrame::NotAsked,
1305 };
1306 Ok(self
1307 .inboxes()
1308 .claim_or_hand_over(print.id, arrival.clone())
1309 .then(|| PendingTurn::new(print, arrival, Vec::new())))
1310 }
1311}
1312
1313pub(crate) fn concerns_its_end(kind: &EventKind) -> bool {
1316 [
1317 PrintEndedPayload::KIND,
1318 UnattendedPrinterActivityPayload::KIND,
1319 ]
1320 .contains(&kind.as_str())
1321}
1322
1323fn resumed_noticed(resumed: &crate::kinds::FilamentChangePlannedResumedPayload) -> String {
1326 let named = |colour: Option<&str>| {
1327 colour.map_or_else(
1328 || "a colour the file does not name".to_owned(),
1329 str::to_owned,
1330 )
1331 };
1332 let change = &resumed.change;
1333 let what = match change.kind {
1334 crate::gcode_index::PlannedChangeKind::ColorChange => "colour change",
1335 crate::gcode_index::PlannedChangeKind::Pause => "pause",
1336 };
1337 format!(
1338 "{}: the print carried on from planned {what} {} after waiting {} s; the expected colour \
1339 is {} from layer {} (Z {} mm) up, and the colour before it was {}",
1340 crate::kinds::FilamentChangePlannedResumedPayload::KIND,
1341 change.index,
1342 resumed.waited_s,
1343 named(change.color.as_deref()),
1344 change.layer,
1345 change.z_mm,
1346 named(resumed.previous_color.as_deref()),
1347 )
1348}
1349
1350pub(crate) fn noticed_of(event: &EventRecord) -> Option<String> {
1353 if let Some(Ok(ended)) = event.payload_as::<PrintEndedPayload>() {
1354 let outcome = match ended.outcome {
1355 PrintOutcome::Interrupted => "interrupted",
1356 PrintOutcome::Failed => "failed",
1357 PrintOutcome::Completed | PrintOutcome::Cancelled => return None,
1358 };
1359 return Some(format!(
1360 "{}: the print ended {outcome}, the printer reporting {:?} ({})",
1361 PrintEndedPayload::KIND,
1362 ended.state,
1363 ended.reason
1364 ));
1365 }
1366 if let Some(Ok(activity)) = event.payload_as::<UnattendedPrinterActivityPayload>() {
1367 return Some(format!(
1368 "{}: after print {} ended, {}",
1369 UnattendedPrinterActivityPayload::KIND,
1370 activity.last_print_id,
1371 activity.detail
1372 ));
1373 }
1374 if let Some(Ok(degraded)) = event.payload_as::<crate::kinds::CameraDegradedPayload>() {
1375 return Some(format!(
1376 "{}: the camera gave no usable frame in {} attempts, so there is no frame to look \
1377 at: {}",
1378 crate::kinds::CameraDegradedPayload::KIND,
1379 degraded.attempts,
1380 degraded.detail
1381 ));
1382 }
1383 if let Some(Ok(resumed)) =
1384 event.payload_as::<crate::kinds::FilamentChangePlannedResumedPayload>()
1385 {
1386 return Some(resumed_noticed(&resumed));
1387 }
1388 if let Some(Ok(health)) = event.payload_as::<DetectorHealthChangedPayload>() {
1389 return Some(format!(
1390 "{}: the failure detector is {:?}, so nothing is watching the print for failures: {}",
1391 DetectorHealthChangedPayload::KIND,
1392 health.status,
1393 health.detail
1394 ));
1395 }
1396 None
1397}