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