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 the printer watch holds between its reads.
265 pub(crate) watch: Mutex<WatchState>,
266 /// Whether Z is trusted, which this supervisor starts out not doing.
267 z_trust: Mutex<ZTrust>,
268 /// What the last print's G-code laid down, by the print and the file
269 /// position it was read to, so a recovery read does not read the file
270 /// again while neither has moved.
271 recovery_extents: Mutex<Option<RecoveryExtent>>,
272 /// The prints a recovery moved the printer under while they were paused,
273 /// and the `recovery_executed` event of the first that did.
274 moved_while_paused: Mutex<BTreeMap<PrintId, printobserver_types::EventId>>,
275 /// Every print's G-code index, built once per print for as long as this
276 /// supervisor runs.
277 gcode_indexes: crate::gcode_index::GcodeIndexes,
278}
279
280/// One print's G-code read to one file position, and what it laid down.
281type RecoveryExtent = ((PrintId, i64), Option<PrintedExtent>);
282
283/// When the agent last changed the machine on one print, as this supervisor
284/// measures it.
285#[derive(Debug, Clone, Copy)]
286struct AgentAction {
287 /// The reading of the clock nothing steps this supervisor counts on from.
288 seen_at: Duration,
289 /// How long before `seen_at` the change was made: nothing for one this
290 /// supervisor made, and for one a previous supervisor recorded, how long
291 /// it had been waited already as this one started.
292 already: Duration,
293}
294
295impl core::fmt::Debug for Supervisor {
296 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
297 formatter
298 .debug_struct("Supervisor")
299 .field("config", &self.config)
300 .finish_non_exhaustive()
301 }
302}
303
304impl Supervisor {
305 /// Build a supervisor over the three ports and the stores, and start its
306 /// expiry driver.
307 ///
308 /// The driver is a thread of core's own holding a weak reference, so it
309 /// stops of its own accord when the last handle to the supervisor is
310 /// dropped. It reads the injected clock and nothing else, which is what
311 /// makes a bounded intervention expire with nothing asking it to.
312 ///
313 /// # Panics
314 ///
315 /// Panics when the operating system refuses to start that thread, which is
316 /// a supervisor whose bounded interventions would never expire — the one
317 /// state this crate must not come up in quietly.
318 #[must_use]
319 pub fn new(
320 config: CoreConfig,
321 printer: Arc<dyn PrinterPort>,
322 stores: Stores,
323 vision: Arc<dyn VisionPort>,
324 agent: Arc<dyn SupervisorPort>,
325 clock: Arc<dyn Clock>,
326 ) -> Arc<Self> {
327 let poll = config.expiry_poll;
328 let started = ClockReading::of(clock.as_ref());
329 let supervisor = Arc::new(Self {
330 printer,
331 stores,
332 vision,
333 agent,
334 clock,
335 config,
336 turns: TurnLocks::default(),
337 resolving: TurnLocks::default(),
338 resolving_key: PrintId::new(),
339 expiring: TurnLocks::default(),
340 spool_writes: TurnLocks::default(),
341 seen_running: Mutex::new(BTreeSet::new()),
342 last_agent_action: Mutex::new(BTreeMap::new()),
343 started,
344 deadlines: Deadlines::default(),
345 inboxes: Inboxes::default(),
346 detector_pauses: Mutex::new(BTreeMap::new()),
347 turn_authority: std::sync::OnceLock::new(),
348 watch: Mutex::new(WatchState::default()),
349 z_trust: Mutex::new(ZTrust::Untrusted(
350 crate::recovery::UNTRUSTED_AT_START.to_owned(),
351 )),
352 recovery_extents: Mutex::new(None),
353 moved_while_paused: Mutex::new(BTreeMap::new()),
354 gcode_indexes: crate::gcode_index::GcodeIndexes::default(),
355 });
356 let weak: Weak<Self> = Arc::downgrade(&supervisor);
357 std::thread::Builder::new()
358 .name("printobserver-expiry".to_owned())
359 .spawn(move || {
360 while let Some(supervisor) = weak.upgrade() {
361 let _ = block_on(supervisor.sweep_expired());
362 block_on(supervisor.resume_due_detector_pauses());
363 drop(supervisor);
364 std::thread::sleep(poll);
365 }
366 })
367 .expect("the expiry driver thread starts");
368 supervisor
369 }
370
371 /// Install where every supervision turn's runs take their credentials
372 /// from. The first installation stands; answers whether this one did.
373 pub fn install_turn_authority(&self, authority: Arc<dyn TurnAuthority>) -> bool {
374 self.turn_authority.set(authority).is_ok()
375 }
376
377 /// Whether Z is trusted, held for one read or write.
378 pub(crate) fn z_trust_held(&self) -> MutexGuard<'_, ZTrust> {
379 self.z_trust
380 .lock()
381 .unwrap_or_else(std::sync::PoisonError::into_inner)
382 }
383
384 /// What the last print's G-code was last read to lay down, held for one
385 /// read or write.
386 pub(crate) fn recovery_extents(&self) -> MutexGuard<'_, Option<RecoveryExtent>> {
387 self.recovery_extents
388 .lock()
389 .unwrap_or_else(std::sync::PoisonError::into_inner)
390 }
391
392 /// The prints a recovery moved the printer under while they were paused,
393 /// held for one read or write.
394 pub(crate) fn moved_while_paused(
395 &self,
396 ) -> MutexGuard<'_, BTreeMap<PrintId, printobserver_types::EventId>> {
397 self.moved_while_paused
398 .lock()
399 .unwrap_or_else(std::sync::PoisonError::into_inner)
400 }
401
402 /// The issuer for one turn about one print, opened now.
403 pub(crate) fn open_turn(&self, print_id: PrintId) -> OpenedTurn {
404 self.turn_authority
405 .get()
406 .map_or_else(NoAccess::opened, |authority| authority.open(print_id))
407 }
408
409 /// Every print's G-code index.
410 pub(crate) const fn gcode_indexes(&self) -> &crate::gcode_index::GcodeIndexes {
411 &self.gcode_indexes
412 }
413
414 /// Durable state, one handle per aggregate.
415 pub(crate) const fn stores(&self) -> &Stores {
416 &self.stores
417 }
418
419 /// External observations.
420 pub(crate) fn vision(&self) -> &Arc<dyn VisionPort> {
421 &self.vision
422 }
423
424 /// The supervising agent's harness.
425 pub(crate) fn agent(&self) -> &Arc<dyn SupervisorPort> {
426 &self.agent
427 }
428
429 /// The one time source.
430 pub(crate) fn clock(&self) -> &Arc<dyn Clock> {
431 &self.clock
432 }
433
434 /// The server configuration this supervisor runs under.
435 #[must_use]
436 pub const fn config(&self) -> &CoreConfig {
437 &self.config
438 }
439
440 /// One supervision turn per print at a time.
441 pub(crate) const fn turns(&self) -> &TurnLocks {
442 &self.turns
443 }
444
445 /// One expiry of a print's interventions at a time.
446 pub(crate) const fn expiring(&self) -> &TurnLocks {
447 &self.expiring
448 }
449
450 /// Both of the clock's readings as this supervisor started.
451 pub(crate) const fn started(&self) -> ClockReading {
452 self.started
453 }
454
455 /// The active interventions being counted down.
456 pub(crate) const fn deadlines(&self) -> &Deadlines {
457 &self.deadlines
458 }
459
460 /// What reaches each print's running turn.
461 pub(crate) const fn inboxes(&self) -> &Inboxes {
462 &self.inboxes
463 }
464
465 /// The prints the detector paused and nobody has resumed yet.
466 pub(crate) fn detector_pauses(&self) -> MutexGuard<'_, DetectorPauses> {
467 self.detector_pauses
468 .lock()
469 .unwrap_or_else(std::sync::PoisonError::into_inner)
470 }
471
472 /// Wait until no other resolution of a print is running, then hold it.
473 pub(crate) async fn resolving(&self) -> crate::turn_lock::TurnGuard<'_> {
474 self.resolving.acquire(self.resolving_key).await
475 }
476
477 /// Wait until no other write to the spool ledger is running, then hold it.
478 pub(crate) async fn spool_writes(&self) -> crate::turn_lock::TurnGuard<'_> {
479 self.spool_writes.acquire(self.resolving_key).await
480 }
481
482 /// Record that this supervisor saw one print's job printing or paused.
483 pub(crate) fn note_seen_running(&self, print_id: PrintId) {
484 self.seen_running
485 .lock()
486 .unwrap_or_else(std::sync::PoisonError::into_inner)
487 .insert(print_id);
488 }
489
490 /// Whether this supervisor saw one print's job printing or paused.
491 pub(crate) fn was_seen_running(&self, print_id: PrintId) -> bool {
492 self.seen_running
493 .lock()
494 .unwrap_or_else(std::sync::PoisonError::into_inner)
495 .contains(&print_id)
496 }
497
498 /// Record that the agent changed the machine on one print at a reading of
499 /// the clock nothing steps.
500 pub(crate) fn note_agent_action(&self, print_id: PrintId, at: Duration) {
501 self.last_agents_actions().insert(
502 print_id,
503 Some(AgentAction {
504 seen_at: at,
505 already: Duration::ZERO,
506 }),
507 );
508 }
509
510 /// How long ago, on the clock nothing steps, the agent last changed the
511 /// machine on one print, if it has.
512 ///
513 /// A print this supervisor has not seen the agent act on is read from its
514 /// history once: the newest change the agent made that reached the machine,
515 /// translated against the reading this supervisor took as it started, so
516 /// that what is left of the interval when a supervisor restarts is waited
517 /// out on the clock nothing steps. The time it had already been waited at
518 /// that reading is kept as a span of its own rather than as a reading of
519 /// that clock, whose origin may be later than the change: a host's
520 /// monotonic clock starts near zero with the process. A change recorded
521 /// after that reading — a wall clock stepped back across the restart — is
522 /// taken as made the moment this supervisor started, which waits the whole
523 /// interval rather than longer.
524 ///
525 /// # Errors
526 ///
527 /// Returns the store's own error when the print's history could not be
528 /// read, which the next request reads again.
529 pub(crate) async fn since_last_agent_action(
530 &self,
531 print_id: PrintId,
532 ) -> Result<Option<Duration>, CoreError> {
533 let known = self.last_agents_actions().get(&print_id).copied();
534 let last = if let Some(last) = known {
535 last
536 } else {
537 let started = self.started;
538 let recorded = self
539 .recorded_agent_action(print_id)
540 .await?
541 .map(|at| AgentAction {
542 seen_at: started.elapsed,
543 already: started
544 .wall
545 .as_utc()
546 .signed_duration_since(*at.as_utc())
547 .to_std()
548 .unwrap_or_default(),
549 });
550 *self
551 .last_agents_actions()
552 .entry(print_id)
553 .or_insert(recorded)
554 };
555 Ok(last.map(|action| {
556 self.clock()
557 .elapsed()
558 .saturating_sub(action.seen_at)
559 .saturating_add(action.already)
560 }))
561 }
562
563 /// When the newest change the agent made to the machine on one print was
564 /// recorded, if its history holds one.
565 async fn recorded_agent_action(
566 &self,
567 print_id: PrintId,
568 ) -> Result<Option<Timestamp>, CoreError> {
569 let history = self
570 .stores()
571 .events
572 .history(HistoryQuery {
573 print_id,
574 kinds: vec![
575 ActionRequestedPayload::kind(),
576 ActionExecutedPayload::kind(),
577 ],
578 since: None,
579 until: None,
580 limit: Some(MAX_HISTORY_LIMIT),
581 })
582 .await?;
583 let executed: BTreeSet<ActionId> = history
584 .iter()
585 .filter_map(EventRecord::payload_as::<ActionExecutedPayload>)
586 .filter_map(Result::ok)
587 .map(|payload| payload.action_id)
588 .collect();
589 // Newest first, so the first change found is the newest.
590 Ok(history.iter().find_map(|event| {
591 let requested = event.payload_as::<ActionRequestedPayload>()?.ok()?;
592 (executed.contains(&requested.action_id)
593 && requested.actor.class() == ActorClass::Agent
594 && changes_the_machine(requested.action.kind()))
595 .then_some(event.received_at)
596 }))
597 }
598
599 /// The agent's last change on each print, held for one read or write.
600 fn last_agents_actions(&self) -> MutexGuard<'_, BTreeMap<PrintId, Option<AgentAction>>> {
601 self.last_agent_action
602 .lock()
603 .unwrap_or_else(std::sync::PoisonError::into_inner)
604 }
605
606 /// Read the printer's current state.
607 ///
608 /// A read rather than an action: it changes nothing at the machine, so it
609 /// takes no policy decision and is outside the chokepoint's rule.
610 pub(crate) async fn read_snapshot(&self) -> Result<PrinterSnapshot, PrinterError> {
611 self.printer.snapshot().await
612 }
613
614 /// Read the job the printer reports it is running.
615 ///
616 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
617 pub(crate) async fn read_job(&self) -> Result<JobSnapshot, PrinterError> {
618 self.printer.job().await
619 }
620
621 /// Read what the printer knows of one file it holds.
622 ///
623 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
624 pub(crate) async fn read_file_facts(
625 &self,
626 file_name: FileName,
627 ) -> Result<FileFacts, PrinterError> {
628 self.printer.file_facts(file_name).await
629 }
630
631 /// Read the material each tool of one file was sliced for, tool 0 first.
632 // llmlint: ignore-block[invalid_states_unrepresentable] suppressions.toml has the reason.
633 pub(crate) async fn read_filament_types(
634 &self,
635 file_name: FileName,
636 ) -> Result<Vec<Option<String>>, PrinterError> {
637 // llmlint: ignore-end[invalid_states_unrepresentable]
638 self.printer.filament_types(file_name).await
639 }
640
641 /// Read every file the printer holds that carries a print tally.
642 ///
643 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
644 pub(crate) async fn read_printed_files(&self) -> Result<Vec<FileFacts>, PrinterError> {
645 self.printer.printed_files().await
646 }
647
648 /// Read what one file printed up to a byte position in it.
649 ///
650 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
651 pub(crate) async fn read_printed_extent(
652 &self,
653 file_name: FileName,
654 position_bytes: i64,
655 ) -> Result<Option<PrintedExtent>, PrinterError> {
656 self.printer.printed_extent(file_name, position_bytes).await
657 }
658
659 /// Stream one file's whole G-code into a sink.
660 ///
661 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
662 pub(crate) async fn read_gcode(
663 &self,
664 file_name: FileName,
665 sink: &mut dyn printobserver_printer_api::GcodeSink,
666 ) -> Result<(), PrinterError> {
667 self.printer.read_gcode(file_name, sink).await
668 }
669
670 /// Read where the print head is.
671 ///
672 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
673 pub(crate) async fn read_position(&self) -> Result<AxisPosition, PrinterError> {
674 self.printer.read_position().await
675 }
676
677 /// Read the filament each tool is fed by one file's own moves, up to a
678 /// byte position in it.
679 ///
680 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
681 pub(crate) async fn read_extruded_to(
682 &self,
683 file_name: FileName,
684 position_bytes: i64,
685 ) -> Result<Vec<ToolFilament>, PrinterError> {
686 self.printer.extruded_to(file_name, position_bytes).await
687 }
688
689 /// Record the decision for one request, and — if it was accepted — issue it.
690 ///
691 /// **This is the one function of this crate that calls an action method of
692 /// the printer port.** Every action, from every actor — the agent, an
693 /// operator, the command line, a client — arrives here, and the decision is
694 /// recorded before anything reaches the machine. A rejected request reaches
695 /// no action method at all: the record of the rejection is the only thing
696 /// that happens.
697 ///
698 /// `against` is the print the request was asked of, when it was asked of
699 /// one.
700 ///
701 /// # Errors
702 ///
703 /// Returns the store's own error when the decision or the execution could
704 /// not be recorded. A failure at the printer is not an error here: it is
705 /// recorded as [`ExecutionOutcome::Failed`] and answered in [`Issued`], so
706 /// that a caller sees a request that was made and refused rather than a
707 /// request that never happened.
708 pub(crate) async fn issue_decided_action(
709 &self,
710 decided: Decided,
711 ) -> Result<IssuedAs, CoreError> {
712 let (request, decision, against) = match decided {
713 Decided::Action {
714 request,
715 decision,
716 against,
717 } => (*request, decision, against),
718 // The request is written down before anything reaches the machine.
719 Decided::Recovery { requested, calls } => {
720 let requested_event = self.write_recovery_request(&requested).await?;
721 let decision = match calls {
722 Err(rejection) => RecoveryDecision::Rejected(rejection),
723 Ok(calls) => {
724 let (mut executed, mut first) = (Ok(()), true);
725 for call in calls {
726 executed = match call {
727 PortCall::ToolTarget { tool, target_c } => {
728 self.printer.set_tool_target_c(tool, target_c).await
729 }
730 PortCall::BedTarget { target_c } => {
731 self.printer.set_bed_target_c(target_c).await
732 }
733 PortCall::Fan { percent } => {
734 self.printer.set_fan_percent(percent).await
735 }
736 PortCall::Command(command) => {
737 self.printer.send_command(command).await
738 }
739 };
740 if executed.is_err() {
741 break;
742 }
743 first = false;
744 }
745 recovery_decision_of(requested.action.kind(), executed, first)
746 }
747 };
748 return self
749 .recovery_settled(*requested, requested_event, decision)
750 .await
751 .map(IssuedAs::Recovery);
752 }
753 };
754 // A close is asked of the record it names, which may have ended or may
755 // not be the newest open one, so it is recorded against that record;
756 // every other request binds where the store binds it.
757 let actions = &self.stores.actions;
758 let record = match (&request.action, against) {
759 (PrintAction::ClosePrint { .. }, Some(print_id)) => {
760 actions
761 .record_action_against(print_id, request.clone(), decision.clone())
762 .await?
763 }
764 _ => {
765 actions
766 .record_action(request.clone(), decision.clone())
767 .await?
768 }
769 };
770 if decision != PolicyDecision::Accepted {
771 return Ok(IssuedAs::Action(Issued {
772 record,
773 executed: None,
774 }));
775 }
776 let executed = match &request.action {
777 PrintAction::Pause { .. } => self.printer.pause().await,
778 PrintAction::Resume { .. } => self.printer.resume().await,
779 PrintAction::Cancel { .. } => self.printer.cancel().await,
780 PrintAction::StartPrint { file_name, .. } => {
781 self.printer.start(file_name.clone()).await
782 }
783 PrintAction::SetFeedrateFactor { factor, .. } => {
784 self.printer.set_feedrate_factor(*factor).await
785 }
786 PrintAction::SetFlowrateFactor { factor, .. } => {
787 self.printer.set_flowrate_factor(*factor).await
788 }
789 PrintAction::SetToolTargetC { tool, target_c, .. } => {
790 self.printer.set_tool_target_c(*tool, *target_c).await
791 }
792 PrintAction::SetBedTargetC { target_c, .. } => {
793 self.printer.set_bed_target_c(*target_c).await
794 }
795 PrintAction::SetFanPercent { percent, .. } => {
796 self.printer.set_fan_percent(*percent).await
797 }
798 // Acknowledging a failure is a decision about the print written into
799 // its record, and asks nothing of the machine whatever the
800 // disposition. Stopping a print is cancelling it, which the policy
801 // grants each actor on its own: an acknowledgement that cancelled
802 // would let an actor granted acknowledgements and not cancellation
803 // stop a print all the same. Closing a record writes that record
804 // and asks nothing of the machine either: what it does is done once
805 // its execution is recorded ([`crate::closing`]).
806 PrintAction::AcknowledgeFailure { .. } | PrintAction::ClosePrint { .. } => Ok(()),
807 };
808 let outcome = outcome_of(&executed);
809 let record = self
810 .stores
811 .actions
812 .record_execution(record.id, outcome)
813 .await?;
814 Ok(IssuedAs::Action(Issued {
815 record,
816 executed: Some(executed),
817 }))
818 }
819
820 /// Issue one print action through the chokepoint, answering what became
821 /// of it.
822 pub(crate) async fn issue_action(
823 &self,
824 request: ActionRequest,
825 decision: PolicyDecision,
826 against: Option<PrintId>,
827 ) -> Result<Issued, CoreError> {
828 match self
829 .issue_decided_action(Decided::Action {
830 request: Box::new(request),
831 decision,
832 against,
833 })
834 .await?
835 {
836 IssuedAs::Action(issued) => Ok(issued),
837 // The chokepoint answers each request in its own kind, so this is
838 // a chokepoint that has come apart from its callers.
839 IssuedAs::Recovery(_) => Err(CoreError::Unrepresentable {
840 detail: "a print action was answered as a recovery".to_owned(),
841 }),
842 }
843 }
844}