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.
432 pub(crate) fn open_turn(&self, print_id: PrintId) -> OpenedTurn {
433 self.turn_authority
434 .get()
435 .map_or_else(NoAccess::opened, |authority| authority.open(print_id))
436 }
437
438 /// Every print's G-code index.
439 pub(crate) const fn gcode_indexes(&self) -> &crate::gcode_index::GcodeIndexes {
440 &self.gcode_indexes
441 }
442
443 /// Durable state, one handle per aggregate.
444 pub(crate) const fn stores(&self) -> &Stores {
445 &self.stores
446 }
447
448 /// External observations.
449 pub(crate) fn vision(&self) -> &Arc<dyn VisionPort> {
450 &self.vision
451 }
452
453 /// The supervising agent's harness.
454 pub(crate) fn agent(&self) -> &Arc<dyn SupervisorPort> {
455 &self.agent
456 }
457
458 /// The one time source.
459 pub(crate) fn clock(&self) -> &Arc<dyn Clock> {
460 &self.clock
461 }
462
463 /// The server configuration this supervisor runs under.
464 #[must_use]
465 pub const fn config(&self) -> &CoreConfig {
466 &self.config
467 }
468
469 /// One supervision turn per print at a time.
470 pub(crate) const fn turns(&self) -> &TurnLocks {
471 &self.turns
472 }
473
474 /// One expiry of a print's interventions at a time.
475 pub(crate) const fn expiring(&self) -> &TurnLocks {
476 &self.expiring
477 }
478
479 /// Both of the clock's readings as this supervisor started.
480 pub(crate) const fn started(&self) -> ClockReading {
481 self.started
482 }
483
484 /// The active interventions being counted down.
485 pub(crate) const fn deadlines(&self) -> &Deadlines {
486 &self.deadlines
487 }
488
489 /// What reaches each print's running turn.
490 pub(crate) const fn inboxes(&self) -> &Inboxes {
491 &self.inboxes
492 }
493
494 /// The prints the detector paused and nobody has resumed yet.
495 pub(crate) fn detector_pauses(&self) -> MutexGuard<'_, DetectorPauses> {
496 self.detector_pauses
497 .lock()
498 .unwrap_or_else(std::sync::PoisonError::into_inner)
499 }
500
501 /// Wait until no other resolution of a print is running, then hold it.
502 pub(crate) async fn resolving(&self) -> crate::turn_lock::TurnGuard<'_> {
503 self.resolving.acquire(self.resolving_key).await
504 }
505
506 /// Wait until no other write to the spool ledger is running, then hold it.
507 pub(crate) async fn spool_writes(&self) -> crate::turn_lock::TurnGuard<'_> {
508 self.spool_writes.acquire(self.resolving_key).await
509 }
510
511 /// Record that this supervisor saw one print's job printing or paused.
512 pub(crate) fn note_seen_running(&self, print_id: PrintId) {
513 self.seen_running
514 .lock()
515 .unwrap_or_else(std::sync::PoisonError::into_inner)
516 .insert(print_id);
517 }
518
519 /// Whether this supervisor saw one print's job printing or paused.
520 pub(crate) fn was_seen_running(&self, print_id: PrintId) -> bool {
521 self.seen_running
522 .lock()
523 .unwrap_or_else(std::sync::PoisonError::into_inner)
524 .contains(&print_id)
525 }
526
527 /// Record that the agent changed the machine on one print at a reading of
528 /// the clock nothing steps.
529 pub(crate) fn note_agent_action(&self, print_id: PrintId, at: Duration) {
530 self.last_agents_actions().insert(
531 print_id,
532 Some(AgentAction {
533 seen_at: at,
534 already: Duration::ZERO,
535 }),
536 );
537 }
538
539 /// How long ago, on the clock nothing steps, the agent last changed the
540 /// machine on one print, if it has.
541 ///
542 /// A print this supervisor has not seen the agent act on is read from its
543 /// history once: the newest change the agent made that reached the machine,
544 /// translated against the reading this supervisor took as it started, so
545 /// that what is left of the interval when a supervisor restarts is waited
546 /// out on the clock nothing steps. The time it had already been waited at
547 /// that reading is kept as a span of its own rather than as a reading of
548 /// that clock, whose origin may be later than the change: a host's
549 /// monotonic clock starts near zero with the process. A change recorded
550 /// after that reading — a wall clock stepped back across the restart — is
551 /// taken as made the moment this supervisor started, which waits the whole
552 /// interval rather than longer.
553 ///
554 /// # Errors
555 ///
556 /// Returns the store's own error when the print's history could not be
557 /// read, which the next request reads again.
558 pub(crate) async fn since_last_agent_action(
559 &self,
560 print_id: PrintId,
561 ) -> Result<Option<Duration>, CoreError> {
562 let known = self.last_agents_actions().get(&print_id).copied();
563 let last = if let Some(last) = known {
564 last
565 } else {
566 let started = self.started;
567 let recorded = self
568 .recorded_agent_action(print_id)
569 .await?
570 .map(|at| AgentAction {
571 seen_at: started.elapsed,
572 already: started
573 .wall
574 .as_utc()
575 .signed_duration_since(*at.as_utc())
576 .to_std()
577 .unwrap_or_default(),
578 });
579 *self
580 .last_agents_actions()
581 .entry(print_id)
582 .or_insert(recorded)
583 };
584 Ok(last.map(|action| {
585 self.clock()
586 .paced()
587 .saturating_sub(action.seen_at)
588 .saturating_add(action.already)
589 }))
590 }
591
592 /// When the newest change the agent made to the machine on one print was
593 /// recorded, if its history holds one.
594 async fn recorded_agent_action(
595 &self,
596 print_id: PrintId,
597 ) -> Result<Option<Timestamp>, CoreError> {
598 let history = self
599 .stores()
600 .events
601 .history(HistoryQuery {
602 print_id,
603 kinds: vec![
604 ActionRequestedPayload::kind(),
605 ActionExecutedPayload::kind(),
606 ],
607 since: None,
608 until: None,
609 limit: Some(MAX_HISTORY_LIMIT),
610 })
611 .await?;
612 let executed: BTreeSet<ActionId> = history
613 .iter()
614 .filter_map(EventRecord::payload_as::<ActionExecutedPayload>)
615 .filter_map(Result::ok)
616 .map(|payload| payload.action_id)
617 .collect();
618 // Newest first, so the first change found is the newest.
619 Ok(history.iter().find_map(|event| {
620 let requested = event.payload_as::<ActionRequestedPayload>()?.ok()?;
621 (executed.contains(&requested.action_id)
622 && requested.actor.class() == ActorClass::Agent
623 && changes_the_machine(requested.action.kind()))
624 .then_some(event.received_at)
625 }))
626 }
627
628 /// The agent's last change on each print, held for one read or write.
629 fn last_agents_actions(&self) -> MutexGuard<'_, BTreeMap<PrintId, Option<AgentAction>>> {
630 self.last_agent_action
631 .lock()
632 .unwrap_or_else(std::sync::PoisonError::into_inner)
633 }
634
635 /// Read the printer's current state.
636 ///
637 /// A read rather than an action: it changes nothing at the machine, so it
638 /// takes no policy decision and is outside the chokepoint's rule.
639 pub(crate) async fn read_snapshot(&self) -> Result<PrinterSnapshot, PrinterError> {
640 self.printer.snapshot().await
641 }
642
643 /// Read the job the printer reports it is running.
644 ///
645 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
646 pub(crate) async fn read_job(&self) -> Result<JobSnapshot, PrinterError> {
647 self.printer.job().await
648 }
649
650 /// Read what the printer knows of one file it holds.
651 ///
652 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
653 pub(crate) async fn read_file_facts(
654 &self,
655 file_name: FileName,
656 ) -> Result<FileFacts, PrinterError> {
657 self.printer.file_facts(file_name).await
658 }
659
660 /// Read the material each tool of one file was sliced for, tool 0 first.
661 // llmlint: ignore-block[invalid_states_unrepresentable] suppressions.toml has the reason.
662 pub(crate) async fn read_filament_types(
663 &self,
664 file_name: FileName,
665 ) -> Result<Vec<Option<String>>, PrinterError> {
666 // llmlint: ignore-end[invalid_states_unrepresentable]
667 self.printer.filament_types(file_name).await
668 }
669
670 /// Read every file the printer holds that carries a print tally.
671 ///
672 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
673 pub(crate) async fn read_printed_files(&self) -> Result<Vec<FileFacts>, PrinterError> {
674 self.printer.printed_files().await
675 }
676
677 /// Read what one file printed up to a byte position in it.
678 ///
679 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
680 pub(crate) async fn read_printed_extent(
681 &self,
682 file_name: FileName,
683 position_bytes: i64,
684 ) -> Result<Option<PrintedExtent>, PrinterError> {
685 self.printer.printed_extent(file_name, position_bytes).await
686 }
687
688 /// Stream one file's whole G-code into a sink.
689 ///
690 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
691 pub(crate) async fn read_gcode(
692 &self,
693 file_name: FileName,
694 sink: &mut dyn printobserver_printer_api::GcodeSink,
695 ) -> Result<(), PrinterError> {
696 self.printer.read_gcode(file_name, sink).await
697 }
698
699 /// Read where the print head is.
700 ///
701 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
702 pub(crate) async fn read_position(&self) -> Result<AxisPosition, PrinterError> {
703 self.printer.read_position().await
704 }
705
706 /// Read the filament each tool is fed by one file's own moves, up to a
707 /// byte position in it.
708 ///
709 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
710 pub(crate) async fn read_extruded_to(
711 &self,
712 file_name: FileName,
713 position_bytes: i64,
714 ) -> Result<Vec<ToolFilament>, PrinterError> {
715 self.printer.extruded_to(file_name, position_bytes).await
716 }
717
718 /// Record the decision for one request, and — if it was accepted — issue it.
719 ///
720 /// **This is the one function of this crate that calls an action method of
721 /// the printer port.** Every action, from every actor — the agent, an
722 /// operator, the command line, a client — arrives here, and the decision is
723 /// recorded before anything reaches the machine. A rejected request reaches
724 /// no action method at all: the record of the rejection is the only thing
725 /// that happens.
726 ///
727 /// `against` is the print the request was asked of, when it was asked of
728 /// one.
729 ///
730 /// # Errors
731 ///
732 /// Returns the store's own error when the decision or the execution could
733 /// not be recorded. A failure at the printer is not an error here: it is
734 /// recorded as [`ExecutionOutcome::Failed`] and answered in [`Issued`], so
735 /// that a caller sees a request that was made and refused rather than a
736 /// request that never happened.
737 pub(crate) async fn issue_decided_action(
738 &self,
739 decided: Decided,
740 ) -> Result<IssuedAs, CoreError> {
741 let (request, decision, against) = match decided {
742 Decided::Action {
743 request,
744 decision,
745 against,
746 } => (*request, decision, against),
747 // The request is written down before anything reaches the machine.
748 Decided::Recovery { requested, calls } => {
749 let requested_event = self.write_recovery_request(&requested).await?;
750 let decision = match calls {
751 Err(rejection) => RecoveryDecision::Rejected(rejection),
752 Ok(calls) => {
753 let (mut executed, mut first) = (Ok(()), true);
754 for call in calls {
755 executed = match call {
756 PortCall::ToolTarget { tool, target_c } => {
757 self.printer.set_tool_target_c(tool, target_c).await
758 }
759 PortCall::BedTarget { target_c } => {
760 self.printer.set_bed_target_c(target_c).await
761 }
762 PortCall::Fan { percent } => {
763 self.printer.set_fan_percent(percent).await
764 }
765 PortCall::Command(command) => {
766 self.printer.send_command(command).await
767 }
768 };
769 if executed.is_err() {
770 break;
771 }
772 first = false;
773 }
774 recovery_decision_of(requested.action.kind(), executed, first)
775 }
776 };
777 return self
778 .recovery_settled(*requested, requested_event, decision)
779 .await
780 .map(IssuedAs::Recovery);
781 }
782 };
783 // A close is asked of the record it names, which may have ended or may
784 // not be the newest open one, so it is recorded against that record;
785 // every other request binds where the store binds it.
786 let actions = &self.stores.actions;
787 let record = match (&request.action, against) {
788 (PrintAction::ClosePrint { .. }, Some(print_id)) => {
789 actions
790 .record_action_against(print_id, request.clone(), decision.clone())
791 .await?
792 }
793 _ => {
794 actions
795 .record_action(request.clone(), decision.clone())
796 .await?
797 }
798 };
799 if decision != PolicyDecision::Accepted {
800 return Ok(IssuedAs::Action(Issued {
801 record,
802 executed: None,
803 }));
804 }
805 let executed = match &request.action {
806 PrintAction::Pause { .. } => self.printer.pause().await,
807 PrintAction::Resume { .. } => self.printer.resume().await,
808 PrintAction::Cancel { .. } => self.printer.cancel().await,
809 PrintAction::StartPrint { file_name, .. } => {
810 self.printer.start(file_name.clone()).await
811 }
812 PrintAction::SetFeedrateFactor { factor, .. } => {
813 self.printer.set_feedrate_factor(*factor).await
814 }
815 PrintAction::SetFlowrateFactor { factor, .. } => {
816 self.printer.set_flowrate_factor(*factor).await
817 }
818 PrintAction::SetToolTargetC { tool, target_c, .. } => {
819 self.printer.set_tool_target_c(*tool, *target_c).await
820 }
821 PrintAction::SetBedTargetC { target_c, .. } => {
822 self.printer.set_bed_target_c(*target_c).await
823 }
824 PrintAction::SetFanPercent { percent, .. } => {
825 self.printer.set_fan_percent(*percent).await
826 }
827 // Acknowledging a failure is a decision about the print written into
828 // its record, and asks nothing of the machine whatever the
829 // disposition. Stopping a print is cancelling it, which the policy
830 // grants each actor on its own: an acknowledgement that cancelled
831 // would let an actor granted acknowledgements and not cancellation
832 // stop a print all the same. Closing a record writes that record
833 // and asks nothing of the machine either: what it does is done once
834 // its execution is recorded ([`crate::closing`]).
835 PrintAction::AcknowledgeFailure { .. } | PrintAction::ClosePrint { .. } => Ok(()),
836 };
837 let outcome = outcome_of(&executed);
838 let record = self
839 .stores
840 .actions
841 .record_execution(record.id, outcome)
842 .await?;
843 Ok(IssuedAs::Action(Issued {
844 record,
845 executed: Some(executed),
846 }))
847 }
848
849 /// Issue one print action through the chokepoint, answering what became
850 /// of it.
851 pub(crate) async fn issue_action(
852 &self,
853 request: ActionRequest,
854 decision: PolicyDecision,
855 against: Option<PrintId>,
856 ) -> Result<Issued, CoreError> {
857 match self
858 .issue_decided_action(Decided::Action {
859 request: Box::new(request),
860 decision,
861 against,
862 })
863 .await?
864 {
865 IssuedAs::Action(issued) => Ok(issued),
866 // The chokepoint answers each request in its own kind, so this is
867 // a chokepoint that has come apart from its callers.
868 IssuedAs::Recovery(_) => Err(CoreError::Unrepresentable {
869 detail: "a print action was answered as a recovery".to_owned(),
870 }),
871 }
872 }
873}