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