printobserver_core/supervisor.rs
1//! The supervisor, and the one call site every action passes through.
2//!
3//! # This module is the chokepoint
4//!
5//! Every action this crate takes at the printer port is issued from
6//! [`Supervisor::issue_decided_action`] and from nowhere else, and that
7//! function records the policy decision for the request **before** it issues
8//! the call. That is structural rather than a convention, and two properties of
9//! this module are what make it so:
10//!
11//! 1. **No other item of this crate names an action method.** A check over this
12//! crate's own sources enumerates every syntactic reference to an action
13//! method of the printer port — a call, a path taken as a value, a function
14//! pointer, an alias — and refuses one outside that function.
15//! 2. **No item outside this module can obtain the handle to call one on.** The
16//! printer handle is declared once, as a private field here, and the
17//! identifier `PrinterPort` appears nowhere else in this crate. Nothing
18//! hands it out: no function anywhere returns it.
19//!
20//! **The decision gates actions, not port traffic.** Appending an event,
21//! writing its image, reading a snapshot, running a supervision turn and
22//! persisting its assessment are all port calls, none of them is an action
23//! anyone requested, and none of them takes a decision — the event append in
24//! particular is the *first* thing the loop does, before any decision could
25//! exist. What the policy stands between is a requested
26//! [`PrintAction`](crate::records::PrintAction) and the printer.
27//!
28//! The port's reads — `snapshot`, `job` and the three reads of the files the
29//! printer holds — are outside the rule for that same reason, and are reached
30//! through [`Supervisor::read_snapshot`], [`Supervisor::read_job`],
31//! [`Supervisor::read_file_facts`], [`Supervisor::read_printed_files`] and
32//! [`Supervisor::read_extruded_to`].
33//!
34//! # Nothing here sends a command string to a printer
35//!
36//! There is no method on the printer port that admits one, and the only
37//! caller-supplied text that reaches the machine's own file API is the
38//! [`FileName`](printobserver_types::FileName) newtype, which refuses anything
39//! but a name.
40
41use std::collections::{BTreeMap, BTreeSet};
42use std::sync::{Arc, Mutex, MutexGuard, Weak};
43use std::time::Duration;
44
45use crate::records::{
46 ActionId, ActionRecord, ActionRequest, ActorClass, ExecutionOutcome, PolicyDecision,
47 PrintAction, RecoveryDecision, RecoveryRejection, ZTrust,
48};
49use printobserver_printer_api::{
50 AxisPosition, FileFacts, JobSnapshot, PrintedExtent, PrinterCommand, PrinterError, PrinterPort,
51 PrinterSnapshot, ToolFilament,
52};
53use printobserver_supervisor_api::SupervisorPort;
54use printobserver_types::{EventPayload as _, EventRecord, FileName, PrintId, Timestamp};
55use printobserver_vision_api::VisionPort;
56
57use crate::store::{HistoryQuery, MAX_HISTORY_LIMIT, Stores};
58
59use crate::block_on::block_on;
60use crate::clock::{Clock, ClockReading};
61use crate::config::CoreConfig;
62use crate::decision::changes_the_machine;
63use crate::detector::DetectorPauses;
64use crate::error::CoreError;
65use crate::expiry::Deadlines;
66use crate::inbox::Inboxes;
67use crate::kinds::{ActionExecutedPayload, ActionRequestedPayload, RecoveryRequestedPayload};
68use crate::turn_access::{NoAccess, OpenedTurn, TurnAuthority};
69use crate::turn_lock::TurnLocks;
70use crate::watch::WatchState;
71
72/// What became of one request that reached [`Supervisor::issue_decided_action`].
73#[derive(Debug, Clone, PartialEq)]
74pub struct Issued {
75 /// The record of the request and the decision taken on it.
76 pub record: ActionRecord,
77 /// What the printer made of it, absent when the request was rejected.
78 pub executed: Option<Result<(), PrinterError>>,
79}
80
81impl Issued {
82 /// Whether the request was accepted and the printer took it.
83 #[must_use]
84 pub fn succeeded(&self) -> bool {
85 matches!(self.executed, Some(Ok(())))
86 }
87
88 /// Why the printer refused it, when it reached the printer and was refused.
89 #[must_use]
90 pub fn printer_error(&self) -> Option<&PrinterError> {
91 match &self.executed {
92 Some(Err(error)) => Some(error),
93 _ => None,
94 }
95 }
96}
97
98/// The status a printer port answers a method it does not implement with.
99const NOT_SUPPORTED: u16 = 501;
100
101/// What became of a recovery whose calls the printer answered so: carried
102/// out, or failed at the printer — or, when its first call is one the printer
103/// answers as not supported, which sent nothing, refused as one it cannot make.
104fn recovery_decision_of(
105 action: crate::records::RecoveryActionKind,
106 executed: Result<(), PrinterError>,
107 first: bool,
108) -> RecoveryDecision {
109 match executed {
110 Ok(()) => RecoveryDecision::Executed(ExecutionOutcome::Succeeded),
111 Err(PrinterError::Refused {
112 status: NOT_SUPPORTED,
113 detail,
114 }) if first => {
115 RecoveryDecision::Rejected(RecoveryRejection::PrinterCannot { action, detail })
116 }
117 failed @ Err(_) => RecoveryDecision::Executed(outcome_of(&failed)),
118 }
119}
120
121/// What the printer made of one request, as its record keeps it.
122fn outcome_of(executed: &Result<(), PrinterError>) -> ExecutionOutcome {
123 match executed {
124 Ok(()) => ExecutionOutcome::Succeeded,
125 Err(error) => ExecutionOutcome::Failed {
126 reason: error.to_string(),
127 },
128 }
129}
130
131/// One call a recovery makes at an action method of the printer port, which
132/// only [`Supervisor::issue_decided_action`] turns into one.
133#[derive(Debug, Clone, Copy, PartialEq)]
134pub(crate) enum PortCall {
135 /// One tool's target, in degrees Celsius.
136 ToolTarget {
137 /// The tool.
138 tool: i64,
139 /// The target.
140 target_c: f64,
141 },
142 /// The bed's target, in degrees Celsius.
143 BedTarget {
144 /// The target.
145 target_c: f64,
146 },
147 /// The part-cooling fan, in percent.
148 Fan {
149 /// The percentage.
150 percent: f64,
151 },
152 /// One command of the port's closed vocabulary.
153 Command(PrinterCommand),
154}
155
156/// What reaches the chokepoint: a print action and the decision policy took
157/// on it, or a recovery and the calls it was decided to make.
158#[derive(Debug, Clone)]
159pub(crate) enum Decided {
160 /// A print action.
161 Action {
162 /// The request.
163 request: Box<ActionRequest>,
164 /// The decision taken on it.
165 decision: PolicyDecision,
166 /// The print it was asked of, when it was asked of one.
167 against: Option<PrintId>,
168 },
169 /// A recovery.
170 Recovery {
171 /// The request, as it is written down.
172 requested: Box<RecoveryRequestedPayload>,
173 /// The calls it makes, in order, or the refusal it met.
174 calls: Result<Vec<PortCall>, RecoveryRejection>,
175 },
176}
177
178/// What the chokepoint answers for what reached it.
179#[derive(Debug, Clone, PartialEq)]
180pub(crate) enum IssuedAs {
181 /// A print action.
182 Action(Issued),
183 /// A recovery.
184 Recovery(RecoveryIssued),
185}
186
187/// What became of one recovery request.
188#[derive(Debug, Clone, PartialEq)]
189pub struct RecoveryIssued {
190 /// What became of it.
191 pub decision: RecoveryDecision,
192 /// The `recovery_requested` event.
193 pub requested: EventRecord,
194 /// The `recovery_executed` or `recovery_rejected` event.
195 pub settled: EventRecord,
196}
197
198/// The supervision core: one printer, one store, one agent, one clock.
199///
200/// Built with [`Supervisor::new`], which answers a shared handle because the
201/// expiry driver holds a weak reference to it: a bounded intervention expires
202/// with nothing asking it to, and the driver is the thread that makes that so.
203pub struct Supervisor {
204 /// The printer. Private to this module, and named nowhere else.
205 printer: Arc<dyn PrinterPort>,
206 /// Durable state, one handle per aggregate.
207 stores: Stores,
208 /// External observations.
209 vision: Arc<dyn VisionPort>,
210 /// The supervising agent's harness.
211 agent: Arc<dyn SupervisorPort>,
212 /// The one time source.
213 clock: Arc<dyn Clock>,
214 /// The server configuration.
215 config: CoreConfig,
216 /// One supervision turn per print at a time.
217 turns: TurnLocks,
218 /// One resolution of which print a job or an alert is at a time.
219 ///
220 /// Finding the print the printer's job belongs to and finding the print an
221 /// alert belongs to each read the open prints and may then write one, so
222 /// two of them interleaved could each find none and each open one. They
223 /// take this lock, under [`Supervisor::resolving_key`], for as long as that
224 /// read and write take.
225 resolving: TurnLocks,
226 /// The one key [`Supervisor::resolving`] is held under.
227 resolving_key: PrintId,
228 /// One expiry of a print's interventions at a time.
229 ///
230 /// The expiry driver's sweep, a print's close-out and a start's
231 /// reconciliation can each reach one intervention, and its restoration is
232 /// issued before its outcome is settled, so two expiries interleaved would
233 /// each put the value back.
234 expiring: TurnLocks,
235 /// One write to the spool ledger at a time.
236 ///
237 /// Every spool command, every settlement, every filament-change signal and
238 /// every accounting of the printer's tallies reads the spools it charges
239 /// and then writes them; two of them interleaved would each compute from
240 /// the same figure and one of the two would be lost. They take this lock,
241 /// under [`Supervisor::resolving_key`], for as long as that read and write
242 /// take, and never take another lock while they hold it.
243 spool_writes: TurnLocks,
244 /// The prints this supervisor has itself seen printing or paused, or
245 /// started: a print it closes out that is not among them ended while
246 /// nothing was watching it.
247 seen_running: Mutex<BTreeSet<PrintId>>,
248 /// When, on the clock nothing steps, the agent last changed the machine
249 /// on each print: absent until it is known, and `None` once it is known
250 /// the agent never has.
251 last_agent_action: Mutex<BTreeMap<PrintId, Option<AgentAction>>>,
252 /// Both of the clock's readings as this supervisor started, which every
253 /// instant a previous supervisor recorded is translated against once.
254 started: ClockReading,
255 /// The active interventions being counted down.
256 deadlines: Deadlines,
257 /// What reaches each print's running turn, and which prints have one.
258 inboxes: Inboxes,
259 /// The prints the detector paused and nobody has resumed yet.
260 detector_pauses: Mutex<DetectorPauses>,
261 /// Where each supervision turn's runs take their credentials from, once
262 /// the composition root has installed it.
263 turn_authority: std::sync::OnceLock<Arc<dyn TurnAuthority>>,
264 /// What reads the failure detector's own record of the print, once the
265 /// composition root has installed it.
266 scoring_probe: std::sync::OnceLock<Arc<dyn crate::scoring::ScoringProbe>>,
267 /// What makes the image every check is shown, once the composition root
268 /// has installed it.
269 pub(crate) check_images: std::sync::OnceLock<Arc<dyn crate::check_image::CheckImages>>,
270 /// The prints whose running turn acknowledged its event by command, which
271 /// is then not acknowledged again from the turn's answer.
272 pub(crate) acknowledged_by_turn: Mutex<BTreeSet<PrintId>>,
273 /// The prints whose running turn has asked for a pause or a cancel,
274 /// shared with the access each turn's port is handed.
275 pub(crate) stopped_by_turn: Arc<Mutex<BTreeSet<PrintId>>>,
276 /// What the printer watch holds between its reads.
277 pub(crate) watch: Mutex<WatchState>,
278 /// Whether Z is trusted, which this supervisor starts out not doing.
279 z_trust: Mutex<ZTrust>,
280 /// What the last print's G-code laid down, by the print and the file
281 /// position it was read to, so a recovery read does not read the file
282 /// again while neither has moved.
283 recovery_extents: Mutex<Option<RecoveryExtent>>,
284 /// The prints a recovery moved the printer under while they were paused,
285 /// and the `recovery_executed` event of the first that did.
286 moved_while_paused: Mutex<BTreeMap<PrintId, printobserver_types::EventId>>,
287 /// Every print's G-code index, built once per print for as long as this
288 /// supervisor runs.
289 gcode_indexes: crate::gcode_index::GcodeIndexes,
290}
291
292/// One print's G-code read to one file position, and what it laid down.
293type RecoveryExtent = ((PrintId, i64), Option<PrintedExtent>);
294
295/// When the agent last changed the machine on one print, as this supervisor
296/// measures it.
297#[derive(Debug, Clone, Copy)]
298struct AgentAction {
299 /// The reading of the clock nothing steps this supervisor counts on from.
300 seen_at: Duration,
301 /// How long before `seen_at` the change was made: nothing for one this
302 /// supervisor made, and for one a previous supervisor recorded, how long
303 /// it had been waited already as this one started.
304 already: Duration,
305}
306
307impl core::fmt::Debug for Supervisor {
308 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
309 formatter
310 .debug_struct("Supervisor")
311 .field("config", &self.config)
312 .finish_non_exhaustive()
313 }
314}
315
316impl Supervisor {
317 /// Build a supervisor over the three ports and the stores, and start its
318 /// expiry driver.
319 ///
320 /// The driver is a thread of core's own holding a weak reference, so it
321 /// stops of its own accord when the last handle to the supervisor is
322 /// dropped. It reads the injected clock and nothing else, which is what
323 /// makes a bounded intervention expire with nothing asking it to.
324 ///
325 /// # Panics
326 ///
327 /// Panics when the operating system refuses to start that thread, which is
328 /// a supervisor whose bounded interventions would never expire — the one
329 /// state this crate must not come up in quietly.
330 #[must_use]
331 pub fn new(
332 config: CoreConfig,
333 printer: Arc<dyn PrinterPort>,
334 stores: Stores,
335 vision: Arc<dyn VisionPort>,
336 agent: Arc<dyn SupervisorPort>,
337 clock: Arc<dyn Clock>,
338 ) -> Arc<Self> {
339 let poll = config.expiry_poll;
340 let started = ClockReading::of(clock.as_ref());
341 let supervisor = Arc::new(Self {
342 printer,
343 stores,
344 vision,
345 agent,
346 clock,
347 config,
348 turns: TurnLocks::default(),
349 resolving: TurnLocks::default(),
350 resolving_key: PrintId::new(),
351 expiring: TurnLocks::default(),
352 spool_writes: TurnLocks::default(),
353 seen_running: Mutex::new(BTreeSet::new()),
354 last_agent_action: Mutex::new(BTreeMap::new()),
355 started,
356 deadlines: Deadlines::default(),
357 inboxes: Inboxes::default(),
358 detector_pauses: Mutex::new(BTreeMap::new()),
359 turn_authority: std::sync::OnceLock::new(),
360 scoring_probe: std::sync::OnceLock::new(),
361 check_images: std::sync::OnceLock::new(),
362 acknowledged_by_turn: Mutex::new(BTreeSet::new()),
363 stopped_by_turn: Arc::new(Mutex::new(BTreeSet::new())),
364 watch: Mutex::new(WatchState::default()),
365 z_trust: Mutex::new(ZTrust::Untrusted(
366 crate::recovery::UNTRUSTED_AT_START.to_owned(),
367 )),
368 recovery_extents: Mutex::new(None),
369 moved_while_paused: Mutex::new(BTreeMap::new()),
370 gcode_indexes: crate::gcode_index::GcodeIndexes::default(),
371 });
372 let weak: Weak<Self> = Arc::downgrade(&supervisor);
373 std::thread::Builder::new()
374 .name("printobserver-expiry".to_owned())
375 .spawn(move || {
376 while let Some(supervisor) = weak.upgrade() {
377 let _ = block_on(supervisor.sweep_expired());
378 block_on(supervisor.resume_due_detector_pauses());
379 drop(supervisor);
380 std::thread::sleep(poll);
381 }
382 })
383 .expect("the expiry driver thread starts");
384 supervisor
385 }
386
387 /// Install where every supervision turn's runs take their credentials
388 /// from. The first installation stands; answers whether this one did.
389 pub fn install_turn_authority(&self, authority: Arc<dyn TurnAuthority>) -> bool {
390 self.turn_authority.set(authority).is_ok()
391 }
392
393 /// Install what reads the failure detector's own record of the print,
394 /// which every round of periodic observations asks first. The first
395 /// installation stands; answers whether this one did.
396 pub fn install_scoring_probe(&self, probe: Arc<dyn crate::scoring::ScoringProbe>) -> bool {
397 self.scoring_probe.set(probe).is_ok()
398 }
399
400 /// What reads the failure detector's own record of the print, when one is
401 /// installed.
402 pub(crate) fn scoring_probe(&self) -> Option<Arc<dyn crate::scoring::ScoringProbe>> {
403 self.scoring_probe.get().cloned()
404 }
405
406 /// Whether Z is trusted, held for one read or write.
407 pub(crate) fn z_trust_held(&self) -> MutexGuard<'_, ZTrust> {
408 self.z_trust
409 .lock()
410 .unwrap_or_else(std::sync::PoisonError::into_inner)
411 }
412
413 /// What the last print's G-code was last read to lay down, held for one
414 /// read or write.
415 pub(crate) fn recovery_extents(&self) -> MutexGuard<'_, Option<RecoveryExtent>> {
416 self.recovery_extents
417 .lock()
418 .unwrap_or_else(std::sync::PoisonError::into_inner)
419 }
420
421 /// The prints a recovery moved the printer under while they were paused,
422 /// held for one read or write.
423 pub(crate) fn moved_while_paused(
424 &self,
425 ) -> MutexGuard<'_, BTreeMap<PrintId, printobserver_types::EventId>> {
426 self.moved_while_paused
427 .lock()
428 .unwrap_or_else(std::sync::PoisonError::into_inner)
429 }
430
431 /// The issuer for one turn about one print, opened now, `handed_image`
432 /// whether the turn is handed its event's image.
433 pub(crate) fn open_turn(&self, print_id: PrintId, handed_image: bool) -> OpenedTurn {
434 self.turn_authority
435 .get()
436 .map_or_else(NoAccess::opened, |authority| {
437 authority.open(print_id, handed_image)
438 })
439 }
440
441 /// Every print's G-code index.
442 pub(crate) const fn gcode_indexes(&self) -> &crate::gcode_index::GcodeIndexes {
443 &self.gcode_indexes
444 }
445
446 /// Durable state, one handle per aggregate.
447 pub(crate) const fn stores(&self) -> &Stores {
448 &self.stores
449 }
450
451 /// External observations.
452 pub(crate) fn vision(&self) -> &Arc<dyn VisionPort> {
453 &self.vision
454 }
455
456 /// The supervising agent's harness.
457 pub(crate) fn agent(&self) -> &Arc<dyn SupervisorPort> {
458 &self.agent
459 }
460
461 /// The one time source.
462 pub(crate) fn clock(&self) -> &Arc<dyn Clock> {
463 &self.clock
464 }
465
466 /// The server configuration this supervisor runs under.
467 #[must_use]
468 pub const fn config(&self) -> &CoreConfig {
469 &self.config
470 }
471
472 /// One supervision turn per print at a time.
473 pub(crate) const fn turns(&self) -> &TurnLocks {
474 &self.turns
475 }
476
477 /// One expiry of a print's interventions at a time.
478 pub(crate) const fn expiring(&self) -> &TurnLocks {
479 &self.expiring
480 }
481
482 /// Both of the clock's readings as this supervisor started.
483 pub(crate) const fn started(&self) -> ClockReading {
484 self.started
485 }
486
487 /// The active interventions being counted down.
488 pub(crate) const fn deadlines(&self) -> &Deadlines {
489 &self.deadlines
490 }
491
492 /// What reaches each print's running turn.
493 pub(crate) const fn inboxes(&self) -> &Inboxes {
494 &self.inboxes
495 }
496
497 /// The prints the detector paused and nobody has resumed yet.
498 pub(crate) fn detector_pauses(&self) -> MutexGuard<'_, DetectorPauses> {
499 self.detector_pauses
500 .lock()
501 .unwrap_or_else(std::sync::PoisonError::into_inner)
502 }
503
504 /// Wait until no other resolution of a print is running, then hold it.
505 pub(crate) async fn resolving(&self) -> crate::turn_lock::TurnGuard<'_> {
506 self.resolving.acquire(self.resolving_key).await
507 }
508
509 /// Wait until no other write to the spool ledger is running, then hold it.
510 pub(crate) async fn spool_writes(&self) -> crate::turn_lock::TurnGuard<'_> {
511 self.spool_writes.acquire(self.resolving_key).await
512 }
513
514 /// Record that this supervisor saw one print's job printing or paused.
515 pub(crate) fn note_seen_running(&self, print_id: PrintId) {
516 self.seen_running
517 .lock()
518 .unwrap_or_else(std::sync::PoisonError::into_inner)
519 .insert(print_id);
520 }
521
522 /// Whether this supervisor saw one print's job printing or paused.
523 pub(crate) fn was_seen_running(&self, print_id: PrintId) -> bool {
524 self.seen_running
525 .lock()
526 .unwrap_or_else(std::sync::PoisonError::into_inner)
527 .contains(&print_id)
528 }
529
530 /// Record that the agent changed the machine on one print at a reading of
531 /// the clock nothing steps.
532 pub(crate) fn note_agent_action(&self, print_id: PrintId, at: Duration) {
533 self.last_agents_actions().insert(
534 print_id,
535 Some(AgentAction {
536 seen_at: at,
537 already: Duration::ZERO,
538 }),
539 );
540 }
541
542 /// How long ago, on the clock nothing steps, the agent last changed the
543 /// machine on one print, if it has.
544 ///
545 /// A print this supervisor has not seen the agent act on is read from its
546 /// history once: the newest change the agent made that reached the machine,
547 /// translated against the reading this supervisor took as it started, so
548 /// that what is left of the interval when a supervisor restarts is waited
549 /// out on the clock nothing steps. The time it had already been waited at
550 /// that reading is kept as a span of its own rather than as a reading of
551 /// that clock, whose origin may be later than the change: a host's
552 /// monotonic clock starts near zero with the process. A change recorded
553 /// after that reading — a wall clock stepped back across the restart — is
554 /// taken as made the moment this supervisor started, which waits the whole
555 /// interval rather than longer.
556 ///
557 /// # Errors
558 ///
559 /// Returns the store's own error when the print's history could not be
560 /// read, which the next request reads again.
561 pub(crate) async fn since_last_agent_action(
562 &self,
563 print_id: PrintId,
564 ) -> Result<Option<Duration>, CoreError> {
565 let known = self.last_agents_actions().get(&print_id).copied();
566 let last = if let Some(last) = known {
567 last
568 } else {
569 let started = self.started;
570 let recorded = self
571 .recorded_agent_action(print_id)
572 .await?
573 .map(|at| AgentAction {
574 seen_at: started.elapsed,
575 already: started
576 .wall
577 .as_utc()
578 .signed_duration_since(*at.as_utc())
579 .to_std()
580 .unwrap_or_default(),
581 });
582 *self
583 .last_agents_actions()
584 .entry(print_id)
585 .or_insert(recorded)
586 };
587 Ok(last.map(|action| {
588 self.clock()
589 .paced()
590 .saturating_sub(action.seen_at)
591 .saturating_add(action.already)
592 }))
593 }
594
595 /// When the newest change the agent made to the machine on one print was
596 /// recorded, if its history holds one.
597 async fn recorded_agent_action(
598 &self,
599 print_id: PrintId,
600 ) -> Result<Option<Timestamp>, CoreError> {
601 let history = self
602 .stores()
603 .events
604 .history(HistoryQuery {
605 print_id,
606 kinds: vec![
607 ActionRequestedPayload::kind(),
608 ActionExecutedPayload::kind(),
609 ],
610 since: None,
611 until: None,
612 limit: Some(MAX_HISTORY_LIMIT),
613 })
614 .await?;
615 let executed: BTreeSet<ActionId> = history
616 .iter()
617 .filter_map(EventRecord::payload_as::<ActionExecutedPayload>)
618 .filter_map(Result::ok)
619 .map(|payload| payload.action_id)
620 .collect();
621 // Newest first, so the first change found is the newest.
622 Ok(history.iter().find_map(|event| {
623 let requested = event.payload_as::<ActionRequestedPayload>()?.ok()?;
624 (executed.contains(&requested.action_id)
625 && requested.actor.class() == ActorClass::Agent
626 && changes_the_machine(requested.action.kind()))
627 .then_some(event.received_at)
628 }))
629 }
630
631 /// The agent's last change on each print, held for one read or write.
632 fn last_agents_actions(&self) -> MutexGuard<'_, BTreeMap<PrintId, Option<AgentAction>>> {
633 self.last_agent_action
634 .lock()
635 .unwrap_or_else(std::sync::PoisonError::into_inner)
636 }
637
638 /// Read the printer's current state.
639 ///
640 /// A read rather than an action: it changes nothing at the machine, so it
641 /// takes no policy decision and is outside the chokepoint's rule.
642 pub(crate) async fn read_snapshot(&self) -> Result<PrinterSnapshot, PrinterError> {
643 self.printer.snapshot().await
644 }
645
646 /// Read the job the printer reports it is running.
647 ///
648 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
649 pub(crate) async fn read_job(&self) -> Result<JobSnapshot, PrinterError> {
650 self.printer.job().await
651 }
652
653 /// Read what the printer knows of one file it holds.
654 ///
655 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
656 pub(crate) async fn read_file_facts(
657 &self,
658 file_name: FileName,
659 ) -> Result<FileFacts, PrinterError> {
660 self.printer.file_facts(file_name).await
661 }
662
663 /// Read the material each tool of one file was sliced for, tool 0 first.
664 // llmlint: ignore-block[invalid_states_unrepresentable] suppressions.toml has the reason.
665 pub(crate) async fn read_filament_types(
666 &self,
667 file_name: FileName,
668 ) -> Result<Vec<Option<String>>, PrinterError> {
669 // llmlint: ignore-end[invalid_states_unrepresentable]
670 self.printer.filament_types(file_name).await
671 }
672
673 /// Read every file the printer holds that carries a print tally.
674 ///
675 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
676 pub(crate) async fn read_printed_files(&self) -> Result<Vec<FileFacts>, PrinterError> {
677 self.printer.printed_files().await
678 }
679
680 /// Read what one file printed up to a byte position in it.
681 ///
682 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
683 pub(crate) async fn read_printed_extent(
684 &self,
685 file_name: FileName,
686 position_bytes: i64,
687 ) -> Result<Option<PrintedExtent>, PrinterError> {
688 self.printer.printed_extent(file_name, position_bytes).await
689 }
690
691 /// Stream one file's whole G-code into a sink.
692 ///
693 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
694 pub(crate) async fn read_gcode(
695 &self,
696 file_name: FileName,
697 sink: &mut dyn printobserver_printer_api::GcodeSink,
698 ) -> Result<(), PrinterError> {
699 self.printer.read_gcode(file_name, sink).await
700 }
701
702 /// Read where the print head is.
703 ///
704 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
705 pub(crate) async fn read_position(&self) -> Result<AxisPosition, PrinterError> {
706 self.printer.read_position().await
707 }
708
709 /// Read the filament each tool is fed by one file's own moves, up to a
710 /// byte position in it.
711 ///
712 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
713 pub(crate) async fn read_extruded_to(
714 &self,
715 file_name: FileName,
716 position_bytes: i64,
717 ) -> Result<Vec<ToolFilament>, PrinterError> {
718 self.printer.extruded_to(file_name, position_bytes).await
719 }
720
721 /// Record the decision for one request, and — if it was accepted — issue it.
722 ///
723 /// **This is the one function of this crate that calls an action method of
724 /// the printer port.** Every action, from every actor — the agent, an
725 /// operator, the command line, a client — arrives here, and the decision is
726 /// recorded before anything reaches the machine. A rejected request reaches
727 /// no action method at all: the record of the rejection is the only thing
728 /// that happens.
729 ///
730 /// `against` is the print the request was asked of, when it was asked of
731 /// one.
732 ///
733 /// # Errors
734 ///
735 /// Returns the store's own error when the decision or the execution could
736 /// not be recorded. A failure at the printer is not an error here: it is
737 /// recorded as [`ExecutionOutcome::Failed`] and answered in [`Issued`], so
738 /// that a caller sees a request that was made and refused rather than a
739 /// request that never happened.
740 pub(crate) async fn issue_decided_action(
741 &self,
742 decided: Decided,
743 ) -> Result<IssuedAs, CoreError> {
744 let (request, decision, against) = match decided {
745 Decided::Action {
746 request,
747 decision,
748 against,
749 } => (*request, decision, against),
750 // The request is written down before anything reaches the machine.
751 Decided::Recovery { requested, calls } => {
752 let requested_event = self.write_recovery_request(&requested).await?;
753 let decision = match calls {
754 Err(rejection) => RecoveryDecision::Rejected(rejection),
755 Ok(calls) => {
756 let (mut executed, mut first) = (Ok(()), true);
757 for call in calls {
758 executed = match call {
759 PortCall::ToolTarget { tool, target_c } => {
760 self.printer.set_tool_target_c(tool, target_c).await
761 }
762 PortCall::BedTarget { target_c } => {
763 self.printer.set_bed_target_c(target_c).await
764 }
765 PortCall::Fan { percent } => {
766 self.printer.set_fan_percent(percent).await
767 }
768 PortCall::Command(command) => {
769 self.printer.send_command(command).await
770 }
771 };
772 if executed.is_err() {
773 break;
774 }
775 first = false;
776 }
777 recovery_decision_of(requested.action.kind(), executed, first)
778 }
779 };
780 return self
781 .recovery_settled(*requested, requested_event, decision)
782 .await
783 .map(IssuedAs::Recovery);
784 }
785 };
786 // A close is asked of the record it names, which may have ended or may
787 // not be the newest open one, so it is recorded against that record;
788 // every other request binds where the store binds it.
789 let actions = &self.stores.actions;
790 let record = match (&request.action, against) {
791 (PrintAction::ClosePrint { .. }, Some(print_id)) => {
792 actions
793 .record_action_against(print_id, request.clone(), decision.clone())
794 .await?
795 }
796 _ => {
797 actions
798 .record_action(request.clone(), decision.clone())
799 .await?
800 }
801 };
802 if decision != PolicyDecision::Accepted {
803 return Ok(IssuedAs::Action(Issued {
804 record,
805 executed: None,
806 }));
807 }
808 let executed = match &request.action {
809 PrintAction::Pause { .. } => self.printer.pause().await,
810 PrintAction::Resume { .. } => self.printer.resume().await,
811 PrintAction::Cancel { .. } => self.printer.cancel().await,
812 PrintAction::StartPrint { file_name, .. } => {
813 self.printer.start(file_name.clone()).await
814 }
815 PrintAction::SetFeedrateFactor { factor, .. } => {
816 self.printer.set_feedrate_factor(*factor).await
817 }
818 PrintAction::SetFlowrateFactor { factor, .. } => {
819 self.printer.set_flowrate_factor(*factor).await
820 }
821 PrintAction::SetToolTargetC { tool, target_c, .. } => {
822 self.printer.set_tool_target_c(*tool, *target_c).await
823 }
824 PrintAction::SetBedTargetC { target_c, .. } => {
825 self.printer.set_bed_target_c(*target_c).await
826 }
827 PrintAction::SetFanPercent { percent, .. } => {
828 self.printer.set_fan_percent(*percent).await
829 }
830 // Acknowledging a failure is a decision about the print written into
831 // its record, and asks nothing of the machine whatever the
832 // disposition. Stopping a print is cancelling it, which the policy
833 // grants each actor on its own: an acknowledgement that cancelled
834 // would let an actor granted acknowledgements and not cancellation
835 // stop a print all the same. Closing a record writes that record
836 // and asks nothing of the machine either: what it does is done once
837 // its execution is recorded ([`crate::closing`]).
838 PrintAction::AcknowledgeFailure { .. } | PrintAction::ClosePrint { .. } => Ok(()),
839 };
840 let outcome = outcome_of(&executed);
841 let record = self
842 .stores
843 .actions
844 .record_execution(record.id, outcome)
845 .await?;
846 Ok(IssuedAs::Action(Issued {
847 record,
848 executed: Some(executed),
849 }))
850 }
851
852 /// Issue one print action through the chokepoint, answering what became
853 /// of it.
854 pub(crate) async fn issue_action(
855 &self,
856 request: ActionRequest,
857 decision: PolicyDecision,
858 against: Option<PrintId>,
859 ) -> Result<Issued, CoreError> {
860 match self
861 .issue_decided_action(Decided::Action {
862 request: Box::new(request),
863 decision,
864 against,
865 })
866 .await?
867 {
868 IssuedAs::Action(issued) => Ok(issued),
869 // The chokepoint answers each request in its own kind, so this is
870 // a chokepoint that has come apart from its callers.
871 IssuedAs::Recovery(_) => Err(CoreError::Unrepresentable {
872 detail: "a print action was answered as a recovery".to_owned(),
873 }),
874 }
875 }
876}