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