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 two reads, `snapshot` and `job`, are outside the rule for that
29//! same reason, and are reached through [`Supervisor::read_snapshot`] and
30//! [`Supervisor::read_job`].
31//!
32//! # Nothing here sends a command string to a printer
33//!
34//! There is no method on the printer port that admits one, and the only
35//! caller-supplied text that reaches the machine's own file API is the
36//! [`FileName`](printobserver_types::FileName) newtype, which refuses anything
37//! but a name.
38
39use std::collections::BTreeMap;
40use std::sync::{Arc, Mutex, Weak};
41
42use crate::records::{ActionRecord, ActionRequest, ExecutionOutcome, PolicyDecision, PrintAction};
43use printobserver_printer_api::{JobSnapshot, PrinterError, PrinterPort, PrinterSnapshot};
44use printobserver_supervisor_api::SupervisorPort;
45use printobserver_types::{PrintId, Timestamp};
46use printobserver_vision_api::VisionPort;
47
48use crate::context::PrintContext;
49use crate::store::{StoreError, Stores};
50
51use crate::block_on::block_on;
52use crate::clock::Clock;
53use crate::config::CoreConfig;
54use crate::turn_lock::TurnLocks;
55
56/// What became of one request that reached [`Supervisor::issue_decided_action`].
57#[derive(Debug, Clone, PartialEq)]
58pub struct Issued {
59 /// The record of the request and the decision taken on it.
60 pub record: ActionRecord,
61 /// What the printer made of it, absent when the request was rejected.
62 pub executed: Option<Result<(), PrinterError>>,
63}
64
65impl Issued {
66 /// Whether the request was accepted and the printer took it.
67 #[must_use]
68 pub fn succeeded(&self) -> bool {
69 matches!(self.executed, Some(Ok(())))
70 }
71
72 /// Why the printer refused it, when it reached the printer and was refused.
73 #[must_use]
74 pub fn printer_error(&self) -> Option<&PrinterError> {
75 match &self.executed {
76 Some(Err(error)) => Some(error),
77 _ => None,
78 }
79 }
80}
81
82/// The supervision core: one printer, one store, one agent, one clock.
83///
84/// Built with [`Supervisor::new`], which answers a shared handle because the
85/// expiry driver holds a weak reference to it: a bounded intervention expires
86/// with nothing asking it to, and the driver is the thread that makes that so.
87pub struct Supervisor {
88 /// The printer. Private to this module, and named nowhere else.
89 printer: Arc<dyn PrinterPort>,
90 /// Durable state, one handle per aggregate.
91 stores: Stores,
92 /// External observations.
93 vision: Arc<dyn VisionPort>,
94 /// The supervising agent's harness.
95 agent: Arc<dyn SupervisorPort>,
96 /// The one time source.
97 clock: Arc<dyn Clock>,
98 /// The server configuration.
99 config: CoreConfig,
100 /// One supervision turn per print at a time.
101 turns: TurnLocks,
102 /// One resolution of which print a job or an alert is at a time.
103 ///
104 /// Finding the print the printer's job belongs to and finding the print an
105 /// alert belongs to each read the open prints and may then write one, so
106 /// two of them interleaved could each find none and each open one. They
107 /// take this lock, under [`Supervisor::resolving_key`], for as long as that
108 /// read and write take.
109 resolving: TurnLocks,
110 /// The one key [`Supervisor::resolving`] is held under.
111 resolving_key: PrintId,
112 /// When the agent last acted on each print.
113 last_agent_action: Mutex<BTreeMap<PrintId, Timestamp>>,
114 /// The context collected for the turn currently running on each print.
115 pending_context: Mutex<BTreeMap<PrintId, PrintContext>>,
116}
117
118impl core::fmt::Debug for Supervisor {
119 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
120 formatter
121 .debug_struct("Supervisor")
122 .field("config", &self.config)
123 .finish_non_exhaustive()
124 }
125}
126
127impl Supervisor {
128 /// Build a supervisor over the three ports and the stores, and start its
129 /// expiry driver.
130 ///
131 /// The driver is a thread of core's own holding a weak reference, so it
132 /// stops of its own accord when the last handle to the supervisor is
133 /// dropped. It reads the injected clock and nothing else, which is what
134 /// makes a bounded intervention expire with nothing asking it to.
135 ///
136 /// # Panics
137 ///
138 /// Panics when the operating system refuses to start that thread, which is
139 /// a supervisor whose bounded interventions would never expire — the one
140 /// state this crate must not come up in quietly.
141 #[must_use]
142 pub fn new(
143 config: CoreConfig,
144 printer: Arc<dyn PrinterPort>,
145 stores: Stores,
146 vision: Arc<dyn VisionPort>,
147 agent: Arc<dyn SupervisorPort>,
148 clock: Arc<dyn Clock>,
149 ) -> Arc<Self> {
150 let poll = config.expiry_poll;
151 let supervisor = Arc::new(Self {
152 printer,
153 stores,
154 vision,
155 agent,
156 clock,
157 config,
158 turns: TurnLocks::default(),
159 resolving: TurnLocks::default(),
160 resolving_key: PrintId::new(),
161 last_agent_action: Mutex::new(BTreeMap::new()),
162 pending_context: Mutex::new(BTreeMap::new()),
163 });
164 let weak: Weak<Self> = Arc::downgrade(&supervisor);
165 std::thread::Builder::new()
166 .name("printobserver-expiry".to_owned())
167 .spawn(move || {
168 while let Some(supervisor) = weak.upgrade() {
169 let _ = block_on(supervisor.sweep_expired());
170 drop(supervisor);
171 std::thread::sleep(poll);
172 }
173 })
174 .expect("the expiry driver thread starts");
175 supervisor
176 }
177
178 /// Durable state, one handle per aggregate.
179 pub(crate) const fn stores(&self) -> &Stores {
180 &self.stores
181 }
182
183 /// External observations.
184 pub(crate) fn vision(&self) -> &Arc<dyn VisionPort> {
185 &self.vision
186 }
187
188 /// The supervising agent's harness.
189 pub(crate) fn agent(&self) -> &Arc<dyn SupervisorPort> {
190 &self.agent
191 }
192
193 /// The one time source.
194 pub(crate) fn clock(&self) -> &Arc<dyn Clock> {
195 &self.clock
196 }
197
198 /// The server configuration this supervisor runs under.
199 #[must_use]
200 pub const fn config(&self) -> &CoreConfig {
201 &self.config
202 }
203
204 /// One supervision turn per print at a time.
205 pub(crate) const fn turns(&self) -> &TurnLocks {
206 &self.turns
207 }
208
209 /// Wait until no other resolution of a print is running, then hold it.
210 pub(crate) async fn resolving(&self) -> crate::turn_lock::TurnGuard<'_> {
211 self.resolving.acquire(self.resolving_key).await
212 }
213
214 /// Record that the agent acted on one print at an instant.
215 pub(crate) fn note_agent_action(&self, print_id: PrintId, at: Timestamp) {
216 self.last_agent_action
217 .lock()
218 .expect("the agent's own record is not poisoned")
219 .insert(print_id, at);
220 }
221
222 /// When the agent last acted on one print, if it has.
223 pub(crate) fn last_agent_action(&self, print_id: PrintId) -> Option<Timestamp> {
224 self.last_agent_action
225 .lock()
226 .expect("the agent's own record is not poisoned")
227 .get(&print_id)
228 .copied()
229 }
230
231 /// Hold the context collected for the turn now running on one print.
232 pub(crate) fn hold_context(&self, print_id: PrintId, context: PrintContext) {
233 self.pending_context
234 .lock()
235 .expect("the held context is not poisoned")
236 .insert(print_id, context);
237 }
238
239 /// Drop the context held for one print, once its turn has returned.
240 pub(crate) fn drop_context(&self, print_id: PrintId) {
241 self.pending_context
242 .lock()
243 .expect("the held context is not poisoned")
244 .remove(&print_id);
245 }
246
247 /// The context held for the turn now running on one print, if one is.
248 pub(crate) fn held_context(&self, print_id: PrintId) -> Option<PrintContext> {
249 self.pending_context
250 .lock()
251 .expect("the held context is not poisoned")
252 .get(&print_id)
253 .cloned()
254 }
255
256 /// Read the printer's current state.
257 ///
258 /// A read rather than an action: it changes nothing at the machine, so it
259 /// takes no policy decision and is outside the chokepoint's rule.
260 pub(crate) async fn read_snapshot(&self) -> Result<PrinterSnapshot, PrinterError> {
261 self.printer.snapshot().await
262 }
263
264 /// Read the job the printer reports it is running.
265 ///
266 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
267 pub(crate) async fn read_job(&self) -> Result<JobSnapshot, PrinterError> {
268 self.printer.job().await
269 }
270
271 /// Record the decision for one request, and — if it was accepted — issue it.
272 ///
273 /// **This is the one function of this crate that calls an action method of
274 /// the printer port.** Every action, from every actor — the agent, an
275 /// operator, the command line, a client — arrives here, and the decision is
276 /// recorded before anything reaches the machine. A rejected request reaches
277 /// no action method at all: the record of the rejection is the only thing
278 /// that happens.
279 ///
280 /// # Errors
281 ///
282 /// Returns the store's own error when the decision or the execution could
283 /// not be recorded. A failure at the printer is not an error here: it is
284 /// recorded as [`ExecutionOutcome::Failed`] and answered in [`Issued`], so
285 /// that a caller sees a request that was made and refused rather than a
286 /// request that never happened.
287 pub(crate) async fn issue_decided_action(
288 &self,
289 request: ActionRequest,
290 decision: PolicyDecision,
291 ) -> Result<Issued, StoreError> {
292 let record = self
293 .stores
294 .actions
295 .record_action(request.clone(), decision.clone())
296 .await?;
297 if decision != PolicyDecision::Accepted {
298 return Ok(Issued {
299 record,
300 executed: None,
301 });
302 }
303 let executed = match &request.action {
304 PrintAction::Pause { .. } => self.printer.pause().await,
305 PrintAction::Resume { .. } => self.printer.resume().await,
306 PrintAction::Cancel { .. } => self.printer.cancel().await,
307 PrintAction::StartPrint { file_name, .. } => {
308 self.printer.start(file_name.clone()).await
309 }
310 PrintAction::SetFeedrateFactor { factor, .. } => {
311 self.printer.set_feedrate_factor(*factor).await
312 }
313 PrintAction::SetFlowrateFactor { factor, .. } => {
314 self.printer.set_flowrate_factor(*factor).await
315 }
316 PrintAction::SetToolTargetC { tool, target_c, .. } => {
317 self.printer.set_tool_target_c(*tool, *target_c).await
318 }
319 PrintAction::SetBedTargetC { target_c, .. } => {
320 self.printer.set_bed_target_c(*target_c).await
321 }
322 PrintAction::SetFanPercent { percent, .. } => {
323 self.printer.set_fan_percent(*percent).await
324 }
325 // Acknowledging a failure is a decision about the print rather than
326 // a movement of the machine. `Stop` is the one disposition that
327 // asks for something at the printer, and cancelling is how a print
328 // is stopped; the other two ask for nothing there.
329 PrintAction::AcknowledgeFailure { disposition, .. } => {
330 if matches!(
331 disposition,
332 crate::records::AcknowledgementDisposition::Stop
333 ) {
334 self.printer.cancel().await
335 } else {
336 Ok(())
337 }
338 }
339 };
340 let outcome = match &executed {
341 Ok(()) => ExecutionOutcome::Succeeded,
342 Err(error) => ExecutionOutcome::Failed {
343 reason: error.to_string(),
344 },
345 };
346 let record = self
347 .stores
348 .actions
349 .record_execution(record.id, outcome)
350 .await?;
351 Ok(Issued {
352 record,
353 executed: Some(executed),
354 })
355 }
356}