Skip to main content

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