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, RejectionReason,
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.issue_action(request, decision, Some(print_id)).await?;
178        let source = source_of(&actor);
179        self.write_decision_down(print_id, &source, &action, &issued, preflight.as_ref())
180            .await?;
181        if !issued.succeeded() {
182            return Ok(ActionOutcome {
183                record: issued.record,
184                executed: issued.executed,
185                intervention: None,
186            });
187        }
188        // Only a change to the machine starts the agent's interval again.
189        if actor.class() == ActorClass::Agent && changes_the_machine(action.kind()) {
190            self.note_agent_action(print_id, self.clock().elapsed());
191        }
192        self.follow_the_detectors_pause(print_id, &action, snapshot.as_ref());
193        if let PrintAction::StartPrint {
194            manifest,
195            file_name,
196            ..
197        } = &action
198        {
199            self.attach_manifest(print_id, manifest.clone()).await?;
200            self.follow_the_start(print_id, file_name, &issued, preflight)
201                .await?;
202        }
203        let intervention = self
204            .open_bounded_intervention(print_id, &action, &issued, snapshot.as_ref(), requested_at)
205            .await?;
206        self.append_action_event(
207            print_id,
208            source,
209            EventBody::of(&ActionExecutedPayload {
210                action_id: issued.record.id,
211                intervention_id: intervention.as_ref().map(|opened| opened.id),
212            })?,
213        )
214        .await?;
215        self.follow_the_close(print_id, &action, closing_state.as_ref())
216            .await?;
217        Ok(ActionOutcome {
218            record: issued.record,
219            executed: issued.executed,
220            intervention,
221        })
222    }
223
224    /// Write one request into its print's history: what was asked for, the
225    /// filament check a start was held to, and the rejection when there was
226    /// one.
227    async fn write_decision_down(
228        &self,
229        print_id: PrintId,
230        source: &EventSource,
231        action: &PrintAction,
232        issued: &Issued,
233        preflight: Option<&Preflight>,
234    ) -> Result<(), CoreError> {
235        self.append_action_event(
236            print_id,
237            source.clone(),
238            EventBody::of(&ActionRequestedPayload {
239                action_id: issued.record.id,
240                action: action.clone(),
241                actor: action.actor().clone(),
242            })?,
243        )
244        .await?;
245        // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
246        if let Some(checked) = preflight {
247            self.append_action_event(
248                print_id,
249                source.clone(),
250                EventBody::of(&PreflightCheckedPayload {
251                    preflight: checked.clone(),
252                    action_id: Some(issued.record.id),
253                })?,
254            )
255            .await?;
256        }
257        if let PolicyDecision::Rejected(_) = &issued.record.decision {
258            self.append_action_event(
259                print_id,
260                source.clone(),
261                EventBody::of(&ActionRejectedPayload {
262                    action_id: issued.record.id,
263                    decision: issued.record.decision.clone(),
264                })?,
265            )
266            .await?;
267        }
268        Ok(())
269    }
270
271    /// What an accepted request is checked against beyond the decision, and
272    /// what it reads first.
273    ///
274    /// A start is held to the filament check ([`crate::preflight`]), whose
275    /// refusal replaces the decision and whose finding is answered. A cancel
276    /// reads where the print had got first: `OctoPrint` clears a job's
277    /// position as it cancels, so this is where the print is known to stop.
278    async fn check_accepted(
279        &self,
280        action: &PrintAction,
281        print: Option<&PrintRecord>,
282        decision: &mut PolicyDecision,
283    ) -> Result<Option<Preflight>, CoreError> {
284        if *decision != PolicyDecision::Accepted {
285            return Ok(None);
286        }
287        match action {
288            PrintAction::StartPrint {
289                file_name,
290                override_filament_check,
291                actor,
292                ..
293            } => {
294                let (checked, refusal) = self
295                    .check_start(file_name, actor, (*override_filament_check).into())
296                    .await?;
297                if let Some(reason) = refusal {
298                    *decision = PolicyDecision::Rejected(reason);
299                }
300                Ok(Some(checked))
301            }
302            PrintAction::Resume { .. } => {
303                if let Some(print) = print
304                    && let Some(recovery_event_id) = self.recovery_while_open(print).await?
305                {
306                    *decision = PolicyDecision::Rejected(RejectionReason::PrintNotResumable {
307                        recovery_event_id,
308                    });
309                }
310                Ok(None)
311            }
312            PrintAction::Cancel { .. } => {
313                // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
314                if let Some(print) = print
315                    && let Ok(job) = self.read_job().await
316                {
317                    self.record_position_from(print, &job, self.clock().now())
318                        .await?;
319                }
320                Ok(None)
321            }
322            _ => Ok(None),
323        }
324    }
325
326    /// What a start the printer took records: that this supervisor saw its
327    /// print begin, and the print's `print_started` naming the start, the
328    /// spools loaded and the check it passed — unless the print has one.
329    // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
330    async fn follow_the_start(
331        &self,
332        print_id: PrintId,
333        file_name: &FileName,
334        issued: &Issued,
335        preflight: Option<Preflight>,
336    ) -> Result<(), CoreError> {
337        self.note_seen_running(print_id);
338        // A print homes the machine as it starts, so Z is where its own
339        // G-code put it from here on.
340        self.trust_z();
341        if self.print_started_of(print_id).await?.is_none() {
342            self.record_print_started(
343                print_id,
344                Some(file_name.as_str().to_owned()),
345                Some(issued.record.id),
346                preflight,
347            )
348            .await?;
349        }
350        Ok(())
351    }
352
353    /// The print a start is made against.
354    ///
355    /// Starting a job begins a print of its own. So the printer is read first,
356    /// which closes every open print that read shows is over exactly as any
357    /// other read does ([`crate::listing`]), and when no print is open after it
358    /// one is opened for the file the start names — with no provider
359    /// identifier, and no sighting of a job until a read finds it running. A
360    /// print still open after the read is the one asked for, as it always was:
361    /// a printer running or holding a job refuses a start whichever print it
362    /// is recorded against.
363    async fn print_to_start(
364        &self,
365        asked: PrintId,
366        file_name: &FileName,
367    ) -> Result<PrintId, CoreError> {
368        if let Some(observed) = self.observe_job().await {
369            self.settle_open_prints(&observed).await?;
370        }
371        if !self.stores().prints.open_prints().await?.is_empty() {
372            return Ok(asked);
373        }
374        let opened = self
375            .stores()
376            .prints
377            .open_print(None, Some(file_name.as_str().to_owned()))
378            .await?;
379        Ok(opened.id)
380    }
381
382    /// What one action that went through does to a pause the detector made.
383    ///
384    /// An agent's adjustment to a print the detector's pause is holding earns
385    /// the print its resume ([`crate::detector`]); an agent's acknowledgement
386    /// with `stop` leaves the pause for a person; and a print somebody else
387    /// resumed or cancelled is no longer the detector's to hold.
388    fn follow_the_detectors_pause(
389        &self,
390        print_id: PrintId,
391        action: &PrintAction,
392        snapshot: Option<&PrinterSnapshot>,
393    ) {
394        if !self.detector_paused(print_id) {
395            return;
396        }
397        let paused = snapshot.is_some_and(|taken| taken.connection == PrinterState::Paused);
398        match (action.actor().class(), action) {
399            (ActorClass::Agent, _) if adjustment(action).is_some() && paused => {
400                self.note_adjustment_while_paused(print_id, action.reason());
401            }
402            (
403                ActorClass::Agent,
404                PrintAction::AcknowledgeFailure {
405                    disposition: AcknowledgementDisposition::Stop,
406                    ..
407                },
408            )
409            | (_, PrintAction::Resume { .. } | PrintAction::Cancel { .. }) => {
410                self.forget_detector_pause(print_id);
411            }
412            _ => {}
413        }
414    }
415
416    /// Append one event about an action, sourced from whoever asked for it.
417    async fn append_action_event(
418        &self,
419        print_id: PrintId,
420        source: EventSource,
421        body: EventBody,
422    ) -> Result<(), CoreError> {
423        self.stores()
424            .events
425            .append_event(EventDraft {
426                print_id: Some(print_id),
427                source,
428                received_at: self.clock().now(),
429                body,
430                raw: None,
431            })
432            .await?;
433        Ok(())
434    }
435
436    /// The bounds in force for one print: the envelope, narrowed by its manifest.
437    pub(crate) async fn bounds_for(
438        &self,
439        print: Option<&PrintRecord>,
440        print_id: PrintId,
441    ) -> Result<Bounds, CoreError> {
442        let manifest = if print.is_some() {
443            self.stores().prints.manifest(print_id).await?
444        } else {
445            None
446        };
447        Ok(effective_bounds(&self.config().envelope, manifest.as_ref()))
448    }
449
450    /// Store a print's manifest, recording every range it asked wider than the
451    /// envelope's, so that nobody has to wonder later which bound applied.
452    async fn attach_manifest(
453        &self,
454        print_id: PrintId,
455        manifest: crate::records::JobManifest,
456    ) -> Result<(), CoreError> {
457        let narrowed = effective_bounds(&self.config().envelope, Some(&manifest));
458        self.stores()
459            .prints
460            .put_manifest(print_id, manifest)
461            .await?;
462        for narrowing in narrowed.narrowings {
463            self.stores()
464                .prints
465                .record_narrowing(print_id, narrowing)
466                .await?;
467        }
468        Ok(())
469    }
470
471    /// Open the bounded intervention an accepted adjustment asked for.
472    ///
473    /// An adjustable changed again before its expiry supersedes the earlier
474    /// intervention rather than stacking with it, and the later one carries the
475    /// earlier's prior value forward so that restoring still reaches the value
476    /// the print started from.
477    async fn open_bounded_intervention(
478        &self,
479        print_id: PrintId,
480        action: &PrintAction,
481        issued: &Issued,
482        snapshot: Option<&PrinterSnapshot>,
483        applied_at: Timestamp,
484    ) -> Result<Option<Intervention>, CoreError> {
485        let (Some((adjustable, applied_value)), Some(duration_s)) =
486            (adjustment(action), duration_of(action))
487        else {
488            return Ok(None);
489        };
490        let mut superseded = self.stores().actions.active_interventions(print_id).await?;
491        superseded.retain(|held| held.adjustable == adjustable);
492        superseded.sort_by_key(|held| held.applied_at);
493        let prior_value = superseded.first().map_or_else(
494            || snapshot.and_then(|taken| reported_value(taken, adjustable)),
495            |earliest| earliest.prior_value,
496        );
497        let expires_at =
498            plus_seconds(applied_at, duration_s).map_err(|error| CoreError::Unrepresentable {
499                detail: error.to_string(),
500            })?;
501        let opened = self
502            .stores()
503            .actions
504            .open_intervention(
505                issued.record.id,
506                adjustable,
507                prior_value,
508                applied_value,
509                applied_at,
510                expires_at,
511            )
512            .await?;
513        self.count_down(&opened);
514        for earlier in superseded {
515            self.stores()
516                .actions
517                .settle_intervention(
518                    earlier.id,
519                    InterventionOutcome::Superseded { by: opened.id },
520                )
521                .await?;
522            self.stop_counting_down(earlier.id);
523        }
524        Ok(Some(opened))
525    }
526}