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