Skip to main content

printobserver_core/
actions.rs

1//! The one path an action takes, whoever asked for it.
2//!
3//! # An action is written into the history as it happens
4//!
5//! Every request appends an [`ActionRequestedPayload`], carrying the whole
6//! action — its own values and the reason the actor gave for it. A rejection
7//! appends the decision beside it and an execution appends what it opened. The
8//! reason a mutating request is required to carry is what makes the history
9//! worth reading afterwards, and a reason that reached the `actions` table and
10//! no further would be a reason nothing could ever read back.
11//!
12//! The agent, an operator, the command line and a client all arrive here. There
13//! is no second path: [`Supervisor::request_action`] gathers what the decision
14//! is taken from, takes it, and hands the pair to
15//! [`Supervisor::issue_decided_action`], which is the only function of this
16//! crate that reaches an action method of the printer port.
17
18use crate::records::{
19    AcknowledgementDisposition, ActionRecord, ActionRequest, Actor, ActorClass, Intervention,
20    InterventionOutcome, PolicyDecision, Preflight, PrintAction, PrintRecord,
21};
22use printobserver_printer_api::Adjustable;
23use printobserver_printer_api::{PrinterSnapshot, PrinterState};
24use printobserver_types::{EventBody, EventSource, FileName, PrintId, Timestamp};
25
26use crate::bounds::{Bounds, effective_bounds};
27use crate::clock::plus_seconds;
28use crate::decision::{DecisionInput, adjustment, changes_the_machine, decide};
29use crate::error::CoreError;
30use crate::kinds::{
31    ActionExecutedPayload, ActionRejectedPayload, ActionRequestedPayload, PreflightCheckedPayload,
32    agent_source, operator_source, system_source,
33};
34use crate::store::EventDraft;
35use crate::supervisor::{Issued, Supervisor};
36
37/// What became of one request, from the decision through to its intervention.
38#[derive(Debug, Clone, PartialEq)]
39pub struct ActionOutcome {
40    /// The record of the request and the decision taken on it.
41    pub record: ActionRecord,
42    /// What the printer made of it, absent when it was rejected.
43    pub executed: Option<Result<(), printobserver_printer_api::PrinterError>>,
44    /// The bounded intervention it opened, when it opened one.
45    pub intervention: Option<Intervention>,
46}
47
48impl ActionOutcome {
49    /// The decision policy took on the request.
50    #[must_use]
51    pub const fn decision(&self) -> &PolicyDecision {
52        &self.record.decision
53    }
54}
55
56/// Where an event about one actor's action came from.
57pub(crate) fn source_of(actor: &Actor) -> EventSource {
58    match actor.class() {
59        ActorClass::Agent => agent_source(),
60        ActorClass::Operator => operator_source(),
61        ActorClass::System => system_source(),
62    }
63}
64
65/// How long a bounded change stands for, when the request bounds it.
66fn duration_of(action: &PrintAction) -> Option<i64> {
67    match action {
68        PrintAction::SetFeedrateFactor { duration_s, .. }
69        | PrintAction::SetFlowrateFactor { duration_s, .. }
70        | PrintAction::SetToolTargetC { duration_s, .. }
71        | PrintAction::SetBedTargetC { duration_s, .. }
72        | PrintAction::SetFanPercent { duration_s, .. } => *duration_s,
73        PrintAction::Pause { .. }
74        | PrintAction::Resume { .. }
75        | PrintAction::Cancel { .. }
76        | PrintAction::StartPrint { .. }
77        | PrintAction::AcknowledgeFailure { .. }
78        | PrintAction::ClosePrint { .. } => None,
79    }
80}
81
82/// What the printer reported for one adjustable, when it reported anything.
83///
84/// Absent means the printer reported no value for it, which is what makes an
85/// intervention's expiry restore nothing and say so rather than writing a
86/// guessed default onto the machine.
87#[must_use]
88pub fn reported_value(snapshot: &PrinterSnapshot, adjustable: Adjustable) -> Option<f64> {
89    let reported = match adjustable {
90        Adjustable::Feedrate => snapshot.feedrate_factor,
91        Adjustable::Flowrate => snapshot.flowrate_factor,
92        Adjustable::Fan => snapshot.fan_percent,
93        Adjustable::BedTarget => snapshot.bed.as_ref().and_then(|heater| heater.target_c),
94        Adjustable::ToolTarget { tool } => usize::try_from(tool)
95            .ok()
96            .and_then(|index| snapshot.tools.get(index))
97            .and_then(|heater| heater.target_c),
98    };
99    reported.map(|value| value.value())
100}
101
102impl Supervisor {
103    /// Request one action against one print.
104    ///
105    /// The same call an operator's action makes, an agent's action makes and a
106    /// client's action makes. A rejected request reaches no action method of
107    /// the printer port at all, and the rejection is persisted carrying its own
108    /// reason so that the caller can ask again inside the range.
109    ///
110    /// # Errors
111    ///
112    /// Returns the store's own error when the decision, the execution or the
113    /// intervention could not be recorded. A refusal by the printer is not an
114    /// error: it is recorded and reported in [`ActionOutcome::executed`].
115    ///
116    /// A start may be made against a print other than `print_id`: it is
117    /// recorded against [`Self::print_to_start`]'s, which the answer's record
118    /// names.
119    pub async fn request_action(
120        &self,
121        print_id: PrintId,
122        action: PrintAction,
123    ) -> Result<ActionOutcome, CoreError> {
124        // A start that will need an analysis waits for it before it holds the
125        // resolution of prints, so the wait holds up no alert and no read.
126        if let PrintAction::StartPrint { file_name, .. } = &action {
127            // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
128            self.await_analysis(file_name, action.actor()).await?;
129        }
130        // A start holds every resolution of a print from the read that chooses
131        // its print until the printer has been asked to start: a read between
132        // the two would find the machine idle and close the print just opened.
133        // A close holds it too, from the read that finds the record over until
134        // the record is ended, so no other read closes it in between.
135        let (_starting, print_id) = match &action {
136            PrintAction::StartPrint { file_name, .. } => {
137                let resolving = self.resolving().await;
138                (
139                    Some(resolving),
140                    self.print_to_start(print_id, file_name).await?,
141                )
142            }
143            PrintAction::ClosePrint { .. } => (Some(self.resolving().await), print_id),
144            _ => (None, print_id),
145        };
146        let requested_at = self.clock().now();
147        let actor = action.actor().clone();
148        let print = self.stores().prints.print(print_id).await?;
149        let bounds = self.bounds_for(print.as_ref(), print_id).await?;
150        let snapshot = self.read_snapshot().await.ok();
151        let since_last_agent_action = if actor.class() == ActorClass::Agent {
152            self.since_last_agent_action(print_id).await?
153        } else {
154            None
155        };
156        let mut decision = decide(&DecisionInput {
157            action: &action,
158            actor: &actor,
159            requested_at,
160            print: print.as_ref(),
161            printer_state: snapshot.as_ref().map(|taken| &taken.connection),
162            bounds: &bounds.effective,
163            envelope: &self.config().envelope,
164            since_last_agent_action,
165        });
166        let preflight = self
167            .check_accepted(&action, print.as_ref(), &mut decision)
168            .await?;
169        let closing_state = self
170            .check_accepted_close(&action, print.as_ref(), &mut decision)
171            .await?;
172        let request = ActionRequest {
173            action: action.clone(),
174            actor: actor.clone(),
175            requested_at,
176        };
177        let issued = self
178            .issue_decided_action(request, decision, Some(print_id))
179            .await?;
180        let source = source_of(&actor);
181        self.write_decision_down(print_id, &source, &action, &issued, preflight.as_ref())
182            .await?;
183        if !issued.succeeded() {
184            return Ok(ActionOutcome {
185                record: issued.record,
186                executed: issued.executed,
187                intervention: None,
188            });
189        }
190        // Only a change to the machine starts the agent's interval again.
191        if actor.class() == ActorClass::Agent && changes_the_machine(action.kind()) {
192            self.note_agent_action(print_id, self.clock().elapsed());
193        }
194        self.follow_the_detectors_pause(print_id, &action, snapshot.as_ref());
195        if let PrintAction::StartPrint {
196            manifest,
197            file_name,
198            ..
199        } = &action
200        {
201            self.attach_manifest(print_id, manifest.clone()).await?;
202            self.follow_the_start(print_id, file_name, &issued, preflight)
203                .await?;
204        }
205        let intervention = self
206            .open_bounded_intervention(print_id, &action, &issued, snapshot.as_ref(), requested_at)
207            .await?;
208        self.append_action_event(
209            print_id,
210            source,
211            EventBody::of(&ActionExecutedPayload {
212                action_id: issued.record.id,
213                intervention_id: intervention.as_ref().map(|opened| opened.id),
214            })?,
215        )
216        .await?;
217        self.follow_the_close(print_id, &action, closing_state.as_ref())
218            .await?;
219        Ok(ActionOutcome {
220            record: issued.record,
221            executed: issued.executed,
222            intervention,
223        })
224    }
225
226    /// Write one request into its print's history: what was asked for, the
227    /// filament check a start was held to, and the rejection when there was
228    /// one.
229    async fn write_decision_down(
230        &self,
231        print_id: PrintId,
232        source: &EventSource,
233        action: &PrintAction,
234        issued: &Issued,
235        preflight: Option<&Preflight>,
236    ) -> Result<(), CoreError> {
237        self.append_action_event(
238            print_id,
239            source.clone(),
240            EventBody::of(&ActionRequestedPayload {
241                action_id: issued.record.id,
242                action: action.clone(),
243                actor: action.actor().clone(),
244            })?,
245        )
246        .await?;
247        // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
248        if let Some(checked) = preflight {
249            self.append_action_event(
250                print_id,
251                source.clone(),
252                EventBody::of(&PreflightCheckedPayload {
253                    preflight: checked.clone(),
254                    action_id: Some(issued.record.id),
255                })?,
256            )
257            .await?;
258        }
259        if let PolicyDecision::Rejected(_) = &issued.record.decision {
260            self.append_action_event(
261                print_id,
262                source.clone(),
263                EventBody::of(&ActionRejectedPayload {
264                    action_id: issued.record.id,
265                    decision: issued.record.decision.clone(),
266                })?,
267            )
268            .await?;
269        }
270        Ok(())
271    }
272
273    /// What an accepted request is checked against beyond the decision, and
274    /// what it reads first.
275    ///
276    /// A start is held to the filament check ([`crate::preflight`]), whose
277    /// refusal replaces the decision and whose finding is answered. A cancel
278    /// reads where the print had got first: `OctoPrint` clears a job's
279    /// position as it cancels, so this is where the print is known to stop.
280    async fn check_accepted(
281        &self,
282        action: &PrintAction,
283        print: Option<&PrintRecord>,
284        decision: &mut PolicyDecision,
285    ) -> Result<Option<Preflight>, CoreError> {
286        if *decision != PolicyDecision::Accepted {
287            return Ok(None);
288        }
289        match action {
290            PrintAction::StartPrint {
291                file_name,
292                override_filament_check,
293                actor,
294                ..
295            } => {
296                let (checked, refusal) = self
297                    .check_start(file_name, actor, (*override_filament_check).into())
298                    .await?;
299                if let Some(reason) = refusal {
300                    *decision = PolicyDecision::Rejected(reason);
301                }
302                Ok(Some(checked))
303            }
304            PrintAction::Cancel { .. } => {
305                // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
306                if let Some(print) = print
307                    && let Ok(job) = self.read_job().await
308                {
309                    self.record_position_from(print, &job, self.clock().now())
310                        .await?;
311                }
312                Ok(None)
313            }
314            _ => Ok(None),
315        }
316    }
317
318    /// What a start the printer took records: that this supervisor saw its
319    /// print begin, and the print's `print_started` naming the start, the
320    /// spools loaded and the check it passed — unless the print has one.
321    // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
322    async fn follow_the_start(
323        &self,
324        print_id: PrintId,
325        file_name: &FileName,
326        issued: &Issued,
327        preflight: Option<Preflight>,
328    ) -> Result<(), CoreError> {
329        self.note_seen_running(print_id);
330        if self.print_started_of(print_id).await?.is_none() {
331            self.record_print_started(
332                print_id,
333                Some(file_name.as_str().to_owned()),
334                Some(issued.record.id),
335                preflight,
336            )
337            .await?;
338        }
339        Ok(())
340    }
341
342    /// The print a start is made against.
343    ///
344    /// Starting a job begins a print of its own. So the printer is read first,
345    /// which closes every open print that read shows is over exactly as any
346    /// other read does ([`crate::listing`]), and when no print is open after it
347    /// one is opened for the file the start names — with no provider
348    /// identifier, and no sighting of a job until a read finds it running. A
349    /// print still open after the read is the one asked for, as it always was:
350    /// a printer running or holding a job refuses a start whichever print it
351    /// is recorded against.
352    async fn print_to_start(
353        &self,
354        asked: PrintId,
355        file_name: &FileName,
356    ) -> Result<PrintId, CoreError> {
357        if let Some(observed) = self.observe_job().await {
358            self.settle_open_prints(&observed).await?;
359        }
360        if !self.stores().prints.open_prints().await?.is_empty() {
361            return Ok(asked);
362        }
363        let opened = self
364            .stores()
365            .prints
366            .open_print(None, Some(file_name.as_str().to_owned()))
367            .await?;
368        Ok(opened.id)
369    }
370
371    /// What one action that went through does to a pause the detector made.
372    ///
373    /// An agent's adjustment to a print the detector's pause is holding earns
374    /// the print its resume ([`crate::detector`]); an agent's acknowledgement
375    /// with `stop` leaves the pause for a person; and a print somebody else
376    /// resumed or cancelled is no longer the detector's to hold.
377    fn follow_the_detectors_pause(
378        &self,
379        print_id: PrintId,
380        action: &PrintAction,
381        snapshot: Option<&PrinterSnapshot>,
382    ) {
383        if !self.detector_paused(print_id) {
384            return;
385        }
386        let paused = snapshot.is_some_and(|taken| taken.connection == PrinterState::Paused);
387        match (action.actor().class(), action) {
388            (ActorClass::Agent, _) if adjustment(action).is_some() && paused => {
389                self.note_adjustment_while_paused(print_id, action.reason());
390            }
391            (
392                ActorClass::Agent,
393                PrintAction::AcknowledgeFailure {
394                    disposition: AcknowledgementDisposition::Stop,
395                    ..
396                },
397            )
398            | (_, PrintAction::Resume { .. } | PrintAction::Cancel { .. }) => {
399                self.forget_detector_pause(print_id);
400            }
401            _ => {}
402        }
403    }
404
405    /// Append one event about an action, sourced from whoever asked for it.
406    async fn append_action_event(
407        &self,
408        print_id: PrintId,
409        source: EventSource,
410        body: EventBody,
411    ) -> Result<(), CoreError> {
412        self.stores()
413            .events
414            .append_event(EventDraft {
415                print_id: Some(print_id),
416                source,
417                received_at: self.clock().now(),
418                body,
419                raw: None,
420            })
421            .await?;
422        Ok(())
423    }
424
425    /// The bounds in force for one print: the envelope, narrowed by its manifest.
426    pub(crate) async fn bounds_for(
427        &self,
428        print: Option<&PrintRecord>,
429        print_id: PrintId,
430    ) -> Result<Bounds, CoreError> {
431        let manifest = if print.is_some() {
432            self.stores().prints.manifest(print_id).await?
433        } else {
434            None
435        };
436        Ok(effective_bounds(&self.config().envelope, manifest.as_ref()))
437    }
438
439    /// Store a print's manifest, recording every range it asked wider than the
440    /// envelope's, so that nobody has to wonder later which bound applied.
441    async fn attach_manifest(
442        &self,
443        print_id: PrintId,
444        manifest: crate::records::JobManifest,
445    ) -> Result<(), CoreError> {
446        let narrowed = effective_bounds(&self.config().envelope, Some(&manifest));
447        self.stores()
448            .prints
449            .put_manifest(print_id, manifest)
450            .await?;
451        for narrowing in narrowed.narrowings {
452            self.stores()
453                .prints
454                .record_narrowing(print_id, narrowing)
455                .await?;
456        }
457        Ok(())
458    }
459
460    /// Open the bounded intervention an accepted adjustment asked for.
461    ///
462    /// An adjustable changed again before its expiry supersedes the earlier
463    /// intervention rather than stacking with it, and the later one carries the
464    /// earlier's prior value forward so that restoring still reaches the value
465    /// the print started from.
466    async fn open_bounded_intervention(
467        &self,
468        print_id: PrintId,
469        action: &PrintAction,
470        issued: &Issued,
471        snapshot: Option<&PrinterSnapshot>,
472        applied_at: Timestamp,
473    ) -> Result<Option<Intervention>, CoreError> {
474        let (Some((adjustable, applied_value)), Some(duration_s)) =
475            (adjustment(action), duration_of(action))
476        else {
477            return Ok(None);
478        };
479        let mut superseded = self.stores().actions.active_interventions(print_id).await?;
480        superseded.retain(|held| held.adjustable == adjustable);
481        superseded.sort_by_key(|held| held.applied_at);
482        let prior_value = superseded.first().map_or_else(
483            || snapshot.and_then(|taken| reported_value(taken, adjustable)),
484            |earliest| earliest.prior_value,
485        );
486        let expires_at =
487            plus_seconds(applied_at, duration_s).map_err(|error| CoreError::Unrepresentable {
488                detail: error.to_string(),
489            })?;
490        let opened = self
491            .stores()
492            .actions
493            .open_intervention(
494                issued.record.id,
495                adjustable,
496                prior_value,
497                applied_value,
498                applied_at,
499                expires_at,
500            )
501            .await?;
502        self.count_down(&opened);
503        for earlier in superseded {
504            self.stores()
505                .actions
506                .settle_intervention(
507                    earlier.id,
508                    InterventionOutcome::Superseded { by: opened.id },
509                )
510                .await?;
511            self.stop_counting_down(earlier.id);
512        }
513        Ok(Some(opened))
514    }
515}