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