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,
48};
49use printobserver_printer_api::{
50    FileFacts, JobSnapshot, PrinterError, PrinterPort, PrinterSnapshot, ToolFilament,
51};
52use printobserver_supervisor_api::SupervisorPort;
53use printobserver_types::{EventPayload as _, EventRecord, FileName, PrintId, Timestamp};
54use printobserver_vision_api::VisionPort;
55
56use crate::store::{HistoryQuery, MAX_HISTORY_LIMIT, StoreError, Stores};
57
58use crate::block_on::block_on;
59use crate::clock::{Clock, ClockReading};
60use crate::config::CoreConfig;
61use crate::decision::changes_the_machine;
62use crate::detector::DetectorPauses;
63use crate::error::CoreError;
64use crate::expiry::Deadlines;
65use crate::inbox::Inboxes;
66use crate::kinds::{ActionExecutedPayload, ActionRequestedPayload};
67use crate::turn_access::{NoAccess, OpenedTurn, TurnAuthority};
68use crate::turn_lock::TurnLocks;
69
70/// What became of one request that reached [`Supervisor::issue_decided_action`].
71#[derive(Debug, Clone, PartialEq)]
72pub struct Issued {
73    /// The record of the request and the decision taken on it.
74    pub record: ActionRecord,
75    /// What the printer made of it, absent when the request was rejected.
76    pub executed: Option<Result<(), PrinterError>>,
77}
78
79impl Issued {
80    /// Whether the request was accepted and the printer took it.
81    #[must_use]
82    pub fn succeeded(&self) -> bool {
83        matches!(self.executed, Some(Ok(())))
84    }
85
86    /// Why the printer refused it, when it reached the printer and was refused.
87    #[must_use]
88    pub fn printer_error(&self) -> Option<&PrinterError> {
89        match &self.executed {
90            Some(Err(error)) => Some(error),
91            _ => None,
92        }
93    }
94}
95
96/// The supervision core: one printer, one store, one agent, one clock.
97///
98/// Built with [`Supervisor::new`], which answers a shared handle because the
99/// expiry driver holds a weak reference to it: a bounded intervention expires
100/// with nothing asking it to, and the driver is the thread that makes that so.
101pub struct Supervisor {
102    /// The printer. Private to this module, and named nowhere else.
103    printer: Arc<dyn PrinterPort>,
104    /// Durable state, one handle per aggregate.
105    stores: Stores,
106    /// External observations.
107    vision: Arc<dyn VisionPort>,
108    /// The supervising agent's harness.
109    agent: Arc<dyn SupervisorPort>,
110    /// The one time source.
111    clock: Arc<dyn Clock>,
112    /// The server configuration.
113    config: CoreConfig,
114    /// One supervision turn per print at a time.
115    turns: TurnLocks,
116    /// One resolution of which print a job or an alert is at a time.
117    ///
118    /// Finding the print the printer's job belongs to and finding the print an
119    /// alert belongs to each read the open prints and may then write one, so
120    /// two of them interleaved could each find none and each open one. They
121    /// take this lock, under [`Supervisor::resolving_key`], for as long as that
122    /// read and write take.
123    resolving: TurnLocks,
124    /// The one key [`Supervisor::resolving`] is held under.
125    resolving_key: PrintId,
126    /// One expiry of a print's interventions at a time.
127    ///
128    /// The expiry driver's sweep, a print's close-out and a start's
129    /// reconciliation can each reach one intervention, and its restoration is
130    /// issued before its outcome is settled, so two expiries interleaved would
131    /// each put the value back.
132    expiring: TurnLocks,
133    /// One write to the spool ledger at a time.
134    ///
135    /// Every spool command, every settlement, every filament-change signal and
136    /// every accounting of the printer's tallies reads the spools it charges
137    /// and then writes them; two of them interleaved would each compute from
138    /// the same figure and one of the two would be lost. They take this lock,
139    /// under [`Supervisor::resolving_key`], for as long as that read and write
140    /// take, and never take another lock while they hold it.
141    spool_writes: TurnLocks,
142    /// The prints this supervisor has itself seen printing or paused, or
143    /// started: a print it closes out that is not among them ended while
144    /// nothing was watching it.
145    seen_running: Mutex<BTreeSet<PrintId>>,
146    /// When, on the clock nothing steps, the agent last changed the machine
147    /// on each print: absent until it is known, and `None` once it is known
148    /// the agent never has.
149    last_agent_action: Mutex<BTreeMap<PrintId, Option<AgentAction>>>,
150    /// Both of the clock's readings as this supervisor started, which every
151    /// instant a previous supervisor recorded is translated against once.
152    started: ClockReading,
153    /// The active interventions being counted down.
154    deadlines: Deadlines,
155    /// What reaches each print's running turn, and which prints have one.
156    inboxes: Inboxes,
157    /// The prints the detector paused and nobody has resumed yet.
158    detector_pauses: Mutex<DetectorPauses>,
159    /// Where each supervision turn's runs take their credentials from, once
160    /// the composition root has installed it.
161    turn_authority: std::sync::OnceLock<Arc<dyn TurnAuthority>>,
162}
163
164/// When the agent last changed the machine on one print, as this supervisor
165/// measures it.
166#[derive(Debug, Clone, Copy)]
167struct AgentAction {
168    /// The reading of the clock nothing steps this supervisor counts on from.
169    seen_at: Duration,
170    /// How long before `seen_at` the change was made: nothing for one this
171    /// supervisor made, and for one a previous supervisor recorded, how long
172    /// it had been waited already as this one started.
173    already: Duration,
174}
175
176impl core::fmt::Debug for Supervisor {
177    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
178        formatter
179            .debug_struct("Supervisor")
180            .field("config", &self.config)
181            .finish_non_exhaustive()
182    }
183}
184
185impl Supervisor {
186    /// Build a supervisor over the three ports and the stores, and start its
187    /// expiry driver.
188    ///
189    /// The driver is a thread of core's own holding a weak reference, so it
190    /// stops of its own accord when the last handle to the supervisor is
191    /// dropped. It reads the injected clock and nothing else, which is what
192    /// makes a bounded intervention expire with nothing asking it to.
193    ///
194    /// # Panics
195    ///
196    /// Panics when the operating system refuses to start that thread, which is
197    /// a supervisor whose bounded interventions would never expire — the one
198    /// state this crate must not come up in quietly.
199    #[must_use]
200    pub fn new(
201        config: CoreConfig,
202        printer: Arc<dyn PrinterPort>,
203        stores: Stores,
204        vision: Arc<dyn VisionPort>,
205        agent: Arc<dyn SupervisorPort>,
206        clock: Arc<dyn Clock>,
207    ) -> Arc<Self> {
208        let poll = config.expiry_poll;
209        let started = ClockReading::of(clock.as_ref());
210        let supervisor = Arc::new(Self {
211            printer,
212            stores,
213            vision,
214            agent,
215            clock,
216            config,
217            turns: TurnLocks::default(),
218            resolving: TurnLocks::default(),
219            resolving_key: PrintId::new(),
220            expiring: TurnLocks::default(),
221            spool_writes: TurnLocks::default(),
222            seen_running: Mutex::new(BTreeSet::new()),
223            last_agent_action: Mutex::new(BTreeMap::new()),
224            started,
225            deadlines: Deadlines::default(),
226            inboxes: Inboxes::default(),
227            detector_pauses: Mutex::new(BTreeMap::new()),
228            turn_authority: std::sync::OnceLock::new(),
229        });
230        let weak: Weak<Self> = Arc::downgrade(&supervisor);
231        std::thread::Builder::new()
232            .name("printobserver-expiry".to_owned())
233            .spawn(move || {
234                while let Some(supervisor) = weak.upgrade() {
235                    let _ = block_on(supervisor.sweep_expired());
236                    block_on(supervisor.resume_due_detector_pauses());
237                    drop(supervisor);
238                    std::thread::sleep(poll);
239                }
240            })
241            .expect("the expiry driver thread starts");
242        supervisor
243    }
244
245    /// Install where every supervision turn's runs take their credentials
246    /// from. The first installation stands; answers whether this one did.
247    pub fn install_turn_authority(&self, authority: Arc<dyn TurnAuthority>) -> bool {
248        self.turn_authority.set(authority).is_ok()
249    }
250
251    /// The issuer for one turn about one print, opened now.
252    pub(crate) fn open_turn(&self, print_id: PrintId) -> OpenedTurn {
253        self.turn_authority
254            .get()
255            .map_or_else(NoAccess::opened, |authority| authority.open(print_id))
256    }
257
258    /// Durable state, one handle per aggregate.
259    pub(crate) const fn stores(&self) -> &Stores {
260        &self.stores
261    }
262
263    /// External observations.
264    pub(crate) fn vision(&self) -> &Arc<dyn VisionPort> {
265        &self.vision
266    }
267
268    /// The supervising agent's harness.
269    pub(crate) fn agent(&self) -> &Arc<dyn SupervisorPort> {
270        &self.agent
271    }
272
273    /// The one time source.
274    pub(crate) fn clock(&self) -> &Arc<dyn Clock> {
275        &self.clock
276    }
277
278    /// The server configuration this supervisor runs under.
279    #[must_use]
280    pub const fn config(&self) -> &CoreConfig {
281        &self.config
282    }
283
284    /// One supervision turn per print at a time.
285    pub(crate) const fn turns(&self) -> &TurnLocks {
286        &self.turns
287    }
288
289    /// One expiry of a print's interventions at a time.
290    pub(crate) const fn expiring(&self) -> &TurnLocks {
291        &self.expiring
292    }
293
294    /// Both of the clock's readings as this supervisor started.
295    pub(crate) const fn started(&self) -> ClockReading {
296        self.started
297    }
298
299    /// The active interventions being counted down.
300    pub(crate) const fn deadlines(&self) -> &Deadlines {
301        &self.deadlines
302    }
303
304    /// What reaches each print's running turn.
305    pub(crate) const fn inboxes(&self) -> &Inboxes {
306        &self.inboxes
307    }
308
309    /// The prints the detector paused and nobody has resumed yet.
310    pub(crate) fn detector_pauses(&self) -> MutexGuard<'_, DetectorPauses> {
311        self.detector_pauses
312            .lock()
313            .unwrap_or_else(std::sync::PoisonError::into_inner)
314    }
315
316    /// Wait until no other resolution of a print is running, then hold it.
317    pub(crate) async fn resolving(&self) -> crate::turn_lock::TurnGuard<'_> {
318        self.resolving.acquire(self.resolving_key).await
319    }
320
321    /// Wait until no other write to the spool ledger is running, then hold it.
322    pub(crate) async fn spool_writes(&self) -> crate::turn_lock::TurnGuard<'_> {
323        self.spool_writes.acquire(self.resolving_key).await
324    }
325
326    /// Record that this supervisor saw one print's job printing or paused.
327    pub(crate) fn note_seen_running(&self, print_id: PrintId) {
328        self.seen_running
329            .lock()
330            .unwrap_or_else(std::sync::PoisonError::into_inner)
331            .insert(print_id);
332    }
333
334    /// Whether this supervisor saw one print's job printing or paused.
335    pub(crate) fn was_seen_running(&self, print_id: PrintId) -> bool {
336        self.seen_running
337            .lock()
338            .unwrap_or_else(std::sync::PoisonError::into_inner)
339            .contains(&print_id)
340    }
341
342    /// Record that the agent changed the machine on one print at a reading of
343    /// the clock nothing steps.
344    pub(crate) fn note_agent_action(&self, print_id: PrintId, at: Duration) {
345        self.last_agents_actions().insert(
346            print_id,
347            Some(AgentAction {
348                seen_at: at,
349                already: Duration::ZERO,
350            }),
351        );
352    }
353
354    /// How long ago, on the clock nothing steps, the agent last changed the
355    /// machine on one print, if it has.
356    ///
357    /// A print this supervisor has not seen the agent act on is read from its
358    /// history once: the newest change the agent made that reached the machine,
359    /// translated against the reading this supervisor took as it started, so
360    /// that what is left of the interval when a supervisor restarts is waited
361    /// out on the clock nothing steps. The time it had already been waited at
362    /// that reading is kept as a span of its own rather than as a reading of
363    /// that clock, whose origin may be later than the change: a host's
364    /// monotonic clock starts near zero with the process. A change recorded
365    /// after that reading — a wall clock stepped back across the restart — is
366    /// taken as made the moment this supervisor started, which waits the whole
367    /// interval rather than longer.
368    ///
369    /// # Errors
370    ///
371    /// Returns the store's own error when the print's history could not be
372    /// read, which the next request reads again.
373    pub(crate) async fn since_last_agent_action(
374        &self,
375        print_id: PrintId,
376    ) -> Result<Option<Duration>, CoreError> {
377        let known = self.last_agents_actions().get(&print_id).copied();
378        let last = if let Some(last) = known {
379            last
380        } else {
381            let started = self.started;
382            let recorded = self
383                .recorded_agent_action(print_id)
384                .await?
385                .map(|at| AgentAction {
386                    seen_at: started.elapsed,
387                    already: started
388                        .wall
389                        .as_utc()
390                        .signed_duration_since(*at.as_utc())
391                        .to_std()
392                        .unwrap_or_default(),
393                });
394            *self
395                .last_agents_actions()
396                .entry(print_id)
397                .or_insert(recorded)
398        };
399        Ok(last.map(|action| {
400            self.clock()
401                .elapsed()
402                .saturating_sub(action.seen_at)
403                .saturating_add(action.already)
404        }))
405    }
406
407    /// When the newest change the agent made to the machine on one print was
408    /// recorded, if its history holds one.
409    async fn recorded_agent_action(
410        &self,
411        print_id: PrintId,
412    ) -> Result<Option<Timestamp>, CoreError> {
413        let history = self
414            .stores()
415            .events
416            .history(HistoryQuery {
417                print_id,
418                kinds: vec![
419                    ActionRequestedPayload::kind(),
420                    ActionExecutedPayload::kind(),
421                ],
422                since: None,
423                until: None,
424                limit: Some(MAX_HISTORY_LIMIT),
425            })
426            .await?;
427        let executed: BTreeSet<ActionId> = history
428            .iter()
429            .filter_map(EventRecord::payload_as::<ActionExecutedPayload>)
430            .filter_map(Result::ok)
431            .map(|payload| payload.action_id)
432            .collect();
433        // Newest first, so the first change found is the newest.
434        Ok(history.iter().find_map(|event| {
435            let requested = event.payload_as::<ActionRequestedPayload>()?.ok()?;
436            (executed.contains(&requested.action_id)
437                && requested.actor.class() == ActorClass::Agent
438                && changes_the_machine(requested.action.kind()))
439            .then_some(event.received_at)
440        }))
441    }
442
443    /// The agent's last change on each print, held for one read or write.
444    fn last_agents_actions(&self) -> MutexGuard<'_, BTreeMap<PrintId, Option<AgentAction>>> {
445        self.last_agent_action
446            .lock()
447            .unwrap_or_else(std::sync::PoisonError::into_inner)
448    }
449
450    /// Read the printer's current state.
451    ///
452    /// A read rather than an action: it changes nothing at the machine, so it
453    /// takes no policy decision and is outside the chokepoint's rule.
454    pub(crate) async fn read_snapshot(&self) -> Result<PrinterSnapshot, PrinterError> {
455        self.printer.snapshot().await
456    }
457
458    /// Read the job the printer reports it is running.
459    ///
460    /// A read, for the same reason [`Supervisor::read_snapshot`] is.
461    pub(crate) async fn read_job(&self) -> Result<JobSnapshot, PrinterError> {
462        self.printer.job().await
463    }
464
465    /// Read what the printer knows of one file it holds.
466    ///
467    /// A read, for the same reason [`Supervisor::read_snapshot`] is.
468    pub(crate) async fn read_file_facts(
469        &self,
470        file_name: FileName,
471    ) -> Result<FileFacts, PrinterError> {
472        self.printer.file_facts(file_name).await
473    }
474
475    /// Read every file the printer holds that carries a print tally.
476    ///
477    /// A read, for the same reason [`Supervisor::read_snapshot`] is.
478    pub(crate) async fn read_printed_files(&self) -> Result<Vec<FileFacts>, PrinterError> {
479        self.printer.printed_files().await
480    }
481
482    /// Read the filament each tool is fed by one file's own moves, up to a
483    /// byte position in it.
484    ///
485    /// A read, for the same reason [`Supervisor::read_snapshot`] is.
486    pub(crate) async fn read_extruded_to(
487        &self,
488        file_name: FileName,
489        position_bytes: i64,
490    ) -> Result<Vec<ToolFilament>, PrinterError> {
491        self.printer.extruded_to(file_name, position_bytes).await
492    }
493
494    /// Record the decision for one request, and — if it was accepted — issue it.
495    ///
496    /// **This is the one function of this crate that calls an action method of
497    /// the printer port.** Every action, from every actor — the agent, an
498    /// operator, the command line, a client — arrives here, and the decision is
499    /// recorded before anything reaches the machine. A rejected request reaches
500    /// no action method at all: the record of the rejection is the only thing
501    /// that happens.
502    ///
503    /// # Errors
504    ///
505    /// Returns the store's own error when the decision or the execution could
506    /// not be recorded. A failure at the printer is not an error here: it is
507    /// recorded as [`ExecutionOutcome::Failed`] and answered in [`Issued`], so
508    /// that a caller sees a request that was made and refused rather than a
509    /// request that never happened.
510    pub(crate) async fn issue_decided_action(
511        &self,
512        request: ActionRequest,
513        decision: PolicyDecision,
514    ) -> Result<Issued, StoreError> {
515        let record = self
516            .stores
517            .actions
518            .record_action(request.clone(), decision.clone())
519            .await?;
520        if decision != PolicyDecision::Accepted {
521            return Ok(Issued {
522                record,
523                executed: None,
524            });
525        }
526        let executed = match &request.action {
527            PrintAction::Pause { .. } => self.printer.pause().await,
528            PrintAction::Resume { .. } => self.printer.resume().await,
529            PrintAction::Cancel { .. } => self.printer.cancel().await,
530            PrintAction::StartPrint { file_name, .. } => {
531                self.printer.start(file_name.clone()).await
532            }
533            PrintAction::SetFeedrateFactor { factor, .. } => {
534                self.printer.set_feedrate_factor(*factor).await
535            }
536            PrintAction::SetFlowrateFactor { factor, .. } => {
537                self.printer.set_flowrate_factor(*factor).await
538            }
539            PrintAction::SetToolTargetC { tool, target_c, .. } => {
540                self.printer.set_tool_target_c(*tool, *target_c).await
541            }
542            PrintAction::SetBedTargetC { target_c, .. } => {
543                self.printer.set_bed_target_c(*target_c).await
544            }
545            PrintAction::SetFanPercent { percent, .. } => {
546                self.printer.set_fan_percent(*percent).await
547            }
548            // Acknowledging a failure is a decision about the print written into
549            // its record, and asks nothing of the machine whatever the
550            // disposition. Stopping a print is cancelling it, which the policy
551            // grants each actor on its own: an acknowledgement that cancelled
552            // would let an actor granted acknowledgements and not cancellation
553            // stop a print all the same.
554            PrintAction::AcknowledgeFailure { .. } => Ok(()),
555        };
556        let outcome = match &executed {
557            Ok(()) => ExecutionOutcome::Succeeded,
558            Err(error) => ExecutionOutcome::Failed {
559                reason: error.to_string(),
560            },
561        };
562        let record = self
563            .stores
564            .actions
565            .record_execution(record.id, outcome)
566            .await?;
567        Ok(Issued {
568            record,
569            executed: Some(executed),
570        })
571    }
572}