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