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