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`](printobserver_types::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 printobserver_printer_api::{PrinterError, PrinterPort};
43use printobserver_store_api::{StoreError, StorePort};
44use printobserver_supervisor_api::SupervisorPort;
45use printobserver_types::{
46 ActionRecord, ActionRequest, ExecutionOutcome, JobSnapshot, PolicyDecision, PrintAction,
47 PrintContext, PrintId, PrinterSnapshot, Timestamp,
48};
49use printobserver_vision_api::VisionPort;
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.
91 store: Arc<dyn StorePort>,
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 /// When the agent last acted on each print.
103 last_agent_action: Mutex<BTreeMap<PrintId, Timestamp>>,
104 /// The context collected for the turn currently running on each print.
105 pending_context: Mutex<BTreeMap<PrintId, PrintContext>>,
106}
107
108impl core::fmt::Debug for Supervisor {
109 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
110 formatter
111 .debug_struct("Supervisor")
112 .field("config", &self.config)
113 .finish_non_exhaustive()
114 }
115}
116
117impl Supervisor {
118 /// Build a supervisor over the four ports, and start its expiry driver.
119 ///
120 /// The driver is a thread of core's own holding a weak reference, so it
121 /// stops of its own accord when the last handle to the supervisor is
122 /// dropped. It reads the injected clock and nothing else, which is what
123 /// makes a bounded intervention expire with nothing asking it to.
124 ///
125 /// # Panics
126 ///
127 /// Panics when the operating system refuses to start that thread, which is
128 /// a supervisor whose bounded interventions would never expire — the one
129 /// state this crate must not come up in quietly.
130 #[must_use]
131 pub fn new(
132 config: CoreConfig,
133 printer: Arc<dyn PrinterPort>,
134 store: Arc<dyn StorePort>,
135 vision: Arc<dyn VisionPort>,
136 agent: Arc<dyn SupervisorPort>,
137 clock: Arc<dyn Clock>,
138 ) -> Arc<Self> {
139 let poll = config.expiry_poll;
140 let supervisor = Arc::new(Self {
141 printer,
142 store,
143 vision,
144 agent,
145 clock,
146 config,
147 turns: TurnLocks::default(),
148 last_agent_action: Mutex::new(BTreeMap::new()),
149 pending_context: Mutex::new(BTreeMap::new()),
150 });
151 let weak: Weak<Self> = Arc::downgrade(&supervisor);
152 std::thread::Builder::new()
153 .name("printobserver-expiry".to_owned())
154 .spawn(move || {
155 while let Some(supervisor) = weak.upgrade() {
156 let _ = block_on(supervisor.sweep_expired());
157 drop(supervisor);
158 std::thread::sleep(poll);
159 }
160 })
161 .expect("the expiry driver thread starts");
162 supervisor
163 }
164
165 /// Durable state.
166 pub(crate) fn store(&self) -> &Arc<dyn StorePort> {
167 &self.store
168 }
169
170 /// External observations.
171 pub(crate) fn vision(&self) -> &Arc<dyn VisionPort> {
172 &self.vision
173 }
174
175 /// The supervising agent's harness.
176 pub(crate) fn agent(&self) -> &Arc<dyn SupervisorPort> {
177 &self.agent
178 }
179
180 /// The one time source.
181 pub(crate) fn clock(&self) -> &Arc<dyn Clock> {
182 &self.clock
183 }
184
185 /// The server configuration this supervisor runs under.
186 #[must_use]
187 pub const fn config(&self) -> &CoreConfig {
188 &self.config
189 }
190
191 /// One supervision turn per print at a time.
192 pub(crate) const fn turns(&self) -> &TurnLocks {
193 &self.turns
194 }
195
196 /// Record that the agent acted on one print at an instant.
197 pub(crate) fn note_agent_action(&self, print_id: PrintId, at: Timestamp) {
198 self.last_agent_action
199 .lock()
200 .expect("the agent's own record is not poisoned")
201 .insert(print_id, at);
202 }
203
204 /// When the agent last acted on one print, if it has.
205 pub(crate) fn last_agent_action(&self, print_id: PrintId) -> Option<Timestamp> {
206 self.last_agent_action
207 .lock()
208 .expect("the agent's own record is not poisoned")
209 .get(&print_id)
210 .copied()
211 }
212
213 /// Hold the context collected for the turn now running on one print.
214 pub(crate) fn hold_context(&self, print_id: PrintId, context: PrintContext) {
215 self.pending_context
216 .lock()
217 .expect("the held context is not poisoned")
218 .insert(print_id, context);
219 }
220
221 /// Drop the context held for one print, once its turn has returned.
222 pub(crate) fn drop_context(&self, print_id: PrintId) {
223 self.pending_context
224 .lock()
225 .expect("the held context is not poisoned")
226 .remove(&print_id);
227 }
228
229 /// The context held for the turn now running on one print, if one is.
230 pub(crate) fn held_context(&self, print_id: PrintId) -> Option<PrintContext> {
231 self.pending_context
232 .lock()
233 .expect("the held context is not poisoned")
234 .get(&print_id)
235 .cloned()
236 }
237
238 /// Read the printer's current state.
239 ///
240 /// A read rather than an action: it changes nothing at the machine, so it
241 /// takes no policy decision and is outside the chokepoint's rule.
242 pub(crate) async fn read_snapshot(&self) -> Result<PrinterSnapshot, PrinterError> {
243 self.printer.snapshot().await
244 }
245
246 /// Read the job the printer reports it is running.
247 ///
248 /// A read, for the same reason [`Supervisor::read_snapshot`] is.
249 pub(crate) async fn read_job(&self) -> Result<JobSnapshot, PrinterError> {
250 self.printer.job().await
251 }
252
253 /// Record the decision for one request, and — if it was accepted — issue it.
254 ///
255 /// **This is the one function of this crate that calls an action method of
256 /// the printer port.** Every action, from every actor — the agent, an
257 /// operator, the command line, a client — arrives here, and the decision is
258 /// recorded before anything reaches the machine. A rejected request reaches
259 /// no action method at all: the record of the rejection is the only thing
260 /// that happens.
261 ///
262 /// # Errors
263 ///
264 /// Returns the store's own error when the decision or the execution could
265 /// not be recorded. A failure at the printer is not an error here: it is
266 /// recorded as [`ExecutionOutcome::Failed`] and answered in [`Issued`], so
267 /// that a caller sees a request that was made and refused rather than a
268 /// request that never happened.
269 pub(crate) async fn issue_decided_action(
270 &self,
271 request: ActionRequest,
272 decision: PolicyDecision,
273 ) -> Result<Issued, StoreError> {
274 let record = self
275 .store
276 .record_action(request.clone(), decision.clone())
277 .await?;
278 if decision != PolicyDecision::Accepted {
279 return Ok(Issued {
280 record,
281 executed: None,
282 });
283 }
284 let executed = match &request.action {
285 PrintAction::Pause { .. } => self.printer.pause().await,
286 PrintAction::Resume { .. } => self.printer.resume().await,
287 PrintAction::Cancel { .. } => self.printer.cancel().await,
288 PrintAction::StartPrint { file_name, .. } => {
289 self.printer.start(file_name.clone()).await
290 }
291 PrintAction::SetFeedrateFactor { factor, .. } => {
292 self.printer.set_feedrate_factor(*factor).await
293 }
294 PrintAction::SetFlowrateFactor { factor, .. } => {
295 self.printer.set_flowrate_factor(*factor).await
296 }
297 PrintAction::SetToolTargetC { tool, target_c, .. } => {
298 self.printer.set_tool_target_c(*tool, *target_c).await
299 }
300 PrintAction::SetBedTargetC { target_c, .. } => {
301 self.printer.set_bed_target_c(*target_c).await
302 }
303 PrintAction::SetFanPercent { percent, .. } => {
304 self.printer.set_fan_percent(*percent).await
305 }
306 // Acknowledging a failure is a decision about the print rather than
307 // a movement of the machine. `Stop` is the one disposition that
308 // asks for something at the printer, and cancelling is how a print
309 // is stopped; the other two ask for nothing there.
310 PrintAction::AcknowledgeFailure { disposition, .. } => {
311 if matches!(
312 disposition,
313 printobserver_types::AcknowledgementDisposition::Stop
314 ) {
315 self.printer.cancel().await
316 } else {
317 Ok(())
318 }
319 }
320 };
321 let outcome = match &executed {
322 Ok(()) => ExecutionOutcome::Succeeded,
323 Err(error) => ExecutionOutcome::Failed {
324 reason: error.to_string(),
325 },
326 };
327 let record = self.store.record_execution(record.id, outcome).await?;
328 Ok(Issued {
329 record,
330 executed: Some(executed),
331 })
332 }
333}