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};
43
44use crate::records::{ActionRecord, ActionRequest, ExecutionOutcome, PolicyDecision, PrintAction};
45use printobserver_printer_api::{
46    FileFacts, JobSnapshot, PrinterError, PrinterPort, PrinterSnapshot, ToolFilament,
47};
48use printobserver_supervisor_api::SupervisorPort;
49use printobserver_types::{FileName, PrintId, Timestamp};
50use printobserver_vision_api::VisionPort;
51
52use crate::store::{StoreError, Stores};
53
54use crate::block_on::block_on;
55use crate::clock::Clock;
56use crate::config::CoreConfig;
57use crate::detector::DetectorPauses;
58use crate::inbox::Inboxes;
59use crate::turn_access::{NoAccess, OpenedTurn, TurnAuthority};
60use crate::turn_lock::TurnLocks;
61
62/// What became of one request that reached [`Supervisor::issue_decided_action`].
63#[derive(Debug, Clone, PartialEq)]
64pub struct Issued {
65    /// The record of the request and the decision taken on it.
66    pub record: ActionRecord,
67    /// What the printer made of it, absent when the request was rejected.
68    pub executed: Option<Result<(), PrinterError>>,
69}
70
71impl Issued {
72    /// Whether the request was accepted and the printer took it.
73    #[must_use]
74    pub fn succeeded(&self) -> bool {
75        matches!(self.executed, Some(Ok(())))
76    }
77
78    /// Why the printer refused it, when it reached the printer and was refused.
79    #[must_use]
80    pub fn printer_error(&self) -> Option<&PrinterError> {
81        match &self.executed {
82            Some(Err(error)) => Some(error),
83            _ => None,
84        }
85    }
86}
87
88/// The supervision core: one printer, one store, one agent, one clock.
89///
90/// Built with [`Supervisor::new`], which answers a shared handle because the
91/// expiry driver holds a weak reference to it: a bounded intervention expires
92/// with nothing asking it to, and the driver is the thread that makes that so.
93pub struct Supervisor {
94    /// The printer. Private to this module, and named nowhere else.
95    printer: Arc<dyn PrinterPort>,
96    /// Durable state, one handle per aggregate.
97    stores: Stores,
98    /// External observations.
99    vision: Arc<dyn VisionPort>,
100    /// The supervising agent's harness.
101    agent: Arc<dyn SupervisorPort>,
102    /// The one time source.
103    clock: Arc<dyn Clock>,
104    /// The server configuration.
105    config: CoreConfig,
106    /// One supervision turn per print at a time.
107    turns: TurnLocks,
108    /// One resolution of which print a job or an alert is at a time.
109    ///
110    /// Finding the print the printer's job belongs to and finding the print an
111    /// alert belongs to each read the open prints and may then write one, so
112    /// two of them interleaved could each find none and each open one. They
113    /// take this lock, under [`Supervisor::resolving_key`], for as long as that
114    /// read and write take.
115    resolving: TurnLocks,
116    /// The one key [`Supervisor::resolving`] is held under.
117    resolving_key: PrintId,
118    /// One expiry of a print's interventions at a time.
119    ///
120    /// The expiry driver's sweep, a print's close-out and a start's
121    /// reconciliation can each reach one intervention, and its restoration is
122    /// issued before its outcome is settled, so two expiries interleaved would
123    /// each put the value back.
124    expiring: TurnLocks,
125    /// One write to the spool ledger at a time.
126    ///
127    /// Every spool command, every settlement, every filament-change signal and
128    /// every accounting of the printer's tallies reads the spools it charges
129    /// and then writes them; two of them interleaved would each compute from
130    /// the same figure and one of the two would be lost. They take this lock,
131    /// under [`Supervisor::resolving_key`], for as long as that read and write
132    /// take, and never take another lock while they hold it.
133    spool_writes: TurnLocks,
134    /// The prints this supervisor has itself seen printing or paused, or
135    /// started: a print it closes out that is not among them ended while
136    /// nothing was watching it.
137    seen_running: Mutex<BTreeSet<PrintId>>,
138    /// When the agent last acted on each print.
139    last_agent_action: Mutex<BTreeMap<PrintId, Timestamp>>,
140    /// What reaches each print's running turn, and which prints have one.
141    inboxes: Inboxes,
142    /// The prints the detector paused and nobody has resumed yet.
143    detector_pauses: Mutex<DetectorPauses>,
144    /// Where each supervision turn's runs take their credentials from, once
145    /// the composition root has installed it.
146    turn_authority: std::sync::OnceLock<Arc<dyn TurnAuthority>>,
147}
148
149impl core::fmt::Debug for Supervisor {
150    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
151        formatter
152            .debug_struct("Supervisor")
153            .field("config", &self.config)
154            .finish_non_exhaustive()
155    }
156}
157
158impl Supervisor {
159    /// Build a supervisor over the three ports and the stores, and start its
160    /// expiry driver.
161    ///
162    /// The driver is a thread of core's own holding a weak reference, so it
163    /// stops of its own accord when the last handle to the supervisor is
164    /// dropped. It reads the injected clock and nothing else, which is what
165    /// makes a bounded intervention expire with nothing asking it to.
166    ///
167    /// # Panics
168    ///
169    /// Panics when the operating system refuses to start that thread, which is
170    /// a supervisor whose bounded interventions would never expire — the one
171    /// state this crate must not come up in quietly.
172    #[must_use]
173    pub fn new(
174        config: CoreConfig,
175        printer: Arc<dyn PrinterPort>,
176        stores: Stores,
177        vision: Arc<dyn VisionPort>,
178        agent: Arc<dyn SupervisorPort>,
179        clock: Arc<dyn Clock>,
180    ) -> Arc<Self> {
181        let poll = config.expiry_poll;
182        let supervisor = Arc::new(Self {
183            printer,
184            stores,
185            vision,
186            agent,
187            clock,
188            config,
189            turns: TurnLocks::default(),
190            resolving: TurnLocks::default(),
191            resolving_key: PrintId::new(),
192            expiring: TurnLocks::default(),
193            spool_writes: TurnLocks::default(),
194            seen_running: Mutex::new(BTreeSet::new()),
195            last_agent_action: Mutex::new(BTreeMap::new()),
196            inboxes: Inboxes::default(),
197            detector_pauses: Mutex::new(BTreeMap::new()),
198            turn_authority: std::sync::OnceLock::new(),
199        });
200        let weak: Weak<Self> = Arc::downgrade(&supervisor);
201        std::thread::Builder::new()
202            .name("printobserver-expiry".to_owned())
203            .spawn(move || {
204                while let Some(supervisor) = weak.upgrade() {
205                    let _ = block_on(supervisor.sweep_expired());
206                    block_on(supervisor.resume_due_detector_pauses());
207                    drop(supervisor);
208                    std::thread::sleep(poll);
209                }
210            })
211            .expect("the expiry driver thread starts");
212        supervisor
213    }
214
215    /// Install where every supervision turn's runs take their credentials
216    /// from. The first installation stands; answers whether this one did.
217    pub fn install_turn_authority(&self, authority: Arc<dyn TurnAuthority>) -> bool {
218        self.turn_authority.set(authority).is_ok()
219    }
220
221    /// The issuer for one turn about one print, opened now.
222    pub(crate) fn open_turn(&self, print_id: PrintId) -> OpenedTurn {
223        self.turn_authority
224            .get()
225            .map_or_else(NoAccess::opened, |authority| authority.open(print_id))
226    }
227
228    /// Durable state, one handle per aggregate.
229    pub(crate) const fn stores(&self) -> &Stores {
230        &self.stores
231    }
232
233    /// External observations.
234    pub(crate) fn vision(&self) -> &Arc<dyn VisionPort> {
235        &self.vision
236    }
237
238    /// The supervising agent's harness.
239    pub(crate) fn agent(&self) -> &Arc<dyn SupervisorPort> {
240        &self.agent
241    }
242
243    /// The one time source.
244    pub(crate) fn clock(&self) -> &Arc<dyn Clock> {
245        &self.clock
246    }
247
248    /// The server configuration this supervisor runs under.
249    #[must_use]
250    pub const fn config(&self) -> &CoreConfig {
251        &self.config
252    }
253
254    /// One supervision turn per print at a time.
255    pub(crate) const fn turns(&self) -> &TurnLocks {
256        &self.turns
257    }
258
259    /// One expiry of a print's interventions at a time.
260    pub(crate) const fn expiring(&self) -> &TurnLocks {
261        &self.expiring
262    }
263
264    /// What reaches each print's running turn.
265    pub(crate) const fn inboxes(&self) -> &Inboxes {
266        &self.inboxes
267    }
268
269    /// The prints the detector paused and nobody has resumed yet.
270    pub(crate) fn detector_pauses(&self) -> MutexGuard<'_, DetectorPauses> {
271        self.detector_pauses
272            .lock()
273            .unwrap_or_else(std::sync::PoisonError::into_inner)
274    }
275
276    /// Wait until no other resolution of a print is running, then hold it.
277    pub(crate) async fn resolving(&self) -> crate::turn_lock::TurnGuard<'_> {
278        self.resolving.acquire(self.resolving_key).await
279    }
280
281    /// Wait until no other write to the spool ledger is running, then hold it.
282    pub(crate) async fn spool_writes(&self) -> crate::turn_lock::TurnGuard<'_> {
283        self.spool_writes.acquire(self.resolving_key).await
284    }
285
286    /// Record that this supervisor saw one print's job printing or paused.
287    pub(crate) fn note_seen_running(&self, print_id: PrintId) {
288        self.seen_running
289            .lock()
290            .unwrap_or_else(std::sync::PoisonError::into_inner)
291            .insert(print_id);
292    }
293
294    /// Whether this supervisor saw one print's job printing or paused.
295    pub(crate) fn was_seen_running(&self, print_id: PrintId) -> bool {
296        self.seen_running
297            .lock()
298            .unwrap_or_else(std::sync::PoisonError::into_inner)
299            .contains(&print_id)
300    }
301
302    /// Record that the agent acted on one print at an instant.
303    pub(crate) fn note_agent_action(&self, print_id: PrintId, at: Timestamp) {
304        self.last_agent_action
305            .lock()
306            .expect("the agent's own record is not poisoned")
307            .insert(print_id, at);
308    }
309
310    /// When the agent last acted on one print, if it has.
311    pub(crate) fn last_agent_action(&self, print_id: PrintId) -> Option<Timestamp> {
312        self.last_agent_action
313            .lock()
314            .expect("the agent's own record is not poisoned")
315            .get(&print_id)
316            .copied()
317    }
318
319    /// Read the printer's current state.
320    ///
321    /// A read rather than an action: it changes nothing at the machine, so it
322    /// takes no policy decision and is outside the chokepoint's rule.
323    pub(crate) async fn read_snapshot(&self) -> Result<PrinterSnapshot, PrinterError> {
324        self.printer.snapshot().await
325    }
326
327    /// Read the job the printer reports it is running.
328    ///
329    /// A read, for the same reason [`Supervisor::read_snapshot`] is.
330    pub(crate) async fn read_job(&self) -> Result<JobSnapshot, PrinterError> {
331        self.printer.job().await
332    }
333
334    /// Read what the printer knows of one file it holds.
335    ///
336    /// A read, for the same reason [`Supervisor::read_snapshot`] is.
337    pub(crate) async fn read_file_facts(
338        &self,
339        file_name: FileName,
340    ) -> Result<FileFacts, PrinterError> {
341        self.printer.file_facts(file_name).await
342    }
343
344    /// Read every file the printer holds that carries a print tally.
345    ///
346    /// A read, for the same reason [`Supervisor::read_snapshot`] is.
347    pub(crate) async fn read_printed_files(&self) -> Result<Vec<FileFacts>, PrinterError> {
348        self.printer.printed_files().await
349    }
350
351    /// Read the filament each tool is fed by one file's own moves, up to a
352    /// byte position in it.
353    ///
354    /// A read, for the same reason [`Supervisor::read_snapshot`] is.
355    pub(crate) async fn read_extruded_to(
356        &self,
357        file_name: FileName,
358        position_bytes: i64,
359    ) -> Result<Vec<ToolFilament>, PrinterError> {
360        self.printer.extruded_to(file_name, position_bytes).await
361    }
362
363    /// Record the decision for one request, and — if it was accepted — issue it.
364    ///
365    /// **This is the one function of this crate that calls an action method of
366    /// the printer port.** Every action, from every actor — the agent, an
367    /// operator, the command line, a client — arrives here, and the decision is
368    /// recorded before anything reaches the machine. A rejected request reaches
369    /// no action method at all: the record of the rejection is the only thing
370    /// that happens.
371    ///
372    /// # Errors
373    ///
374    /// Returns the store's own error when the decision or the execution could
375    /// not be recorded. A failure at the printer is not an error here: it is
376    /// recorded as [`ExecutionOutcome::Failed`] and answered in [`Issued`], so
377    /// that a caller sees a request that was made and refused rather than a
378    /// request that never happened.
379    pub(crate) async fn issue_decided_action(
380        &self,
381        request: ActionRequest,
382        decision: PolicyDecision,
383    ) -> Result<Issued, StoreError> {
384        let record = self
385            .stores
386            .actions
387            .record_action(request.clone(), decision.clone())
388            .await?;
389        if decision != PolicyDecision::Accepted {
390            return Ok(Issued {
391                record,
392                executed: None,
393            });
394        }
395        let executed = match &request.action {
396            PrintAction::Pause { .. } => self.printer.pause().await,
397            PrintAction::Resume { .. } => self.printer.resume().await,
398            PrintAction::Cancel { .. } => self.printer.cancel().await,
399            PrintAction::StartPrint { file_name, .. } => {
400                self.printer.start(file_name.clone()).await
401            }
402            PrintAction::SetFeedrateFactor { factor, .. } => {
403                self.printer.set_feedrate_factor(*factor).await
404            }
405            PrintAction::SetFlowrateFactor { factor, .. } => {
406                self.printer.set_flowrate_factor(*factor).await
407            }
408            PrintAction::SetToolTargetC { tool, target_c, .. } => {
409                self.printer.set_tool_target_c(*tool, *target_c).await
410            }
411            PrintAction::SetBedTargetC { target_c, .. } => {
412                self.printer.set_bed_target_c(*target_c).await
413            }
414            PrintAction::SetFanPercent { percent, .. } => {
415                self.printer.set_fan_percent(*percent).await
416            }
417            // Acknowledging a failure is a decision about the print written into
418            // its record, and asks nothing of the machine whatever the
419            // disposition. Stopping a print is cancelling it, which the policy
420            // grants each actor on its own: an acknowledgement that cancelled
421            // would let an actor granted acknowledgements and not cancellation
422            // stop a print all the same.
423            PrintAction::AcknowledgeFailure { .. } => Ok(()),
424        };
425        let outcome = match &executed {
426            Ok(()) => ExecutionOutcome::Succeeded,
427            Err(error) => ExecutionOutcome::Failed {
428                reason: error.to_string(),
429            },
430        };
431        let record = self
432            .stores
433            .actions
434            .record_execution(record.id, outcome)
435            .await?;
436        Ok(Issued {
437            record,
438            executed: Some(executed),
439        })
440    }
441}