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, PolicyDecision, Preflight, PrintAction, PrintRecord, RejectionReason,
22};
23use printobserver_printer_api::Adjustable;
24use printobserver_printer_api::{PrinterSnapshot, PrinterState};
25use printobserver_types::{EventBody, EventSource, FileName, PrintId, Timestamp};
26
27use crate::bounds::{Bounds, effective_bounds};
28use crate::clock::plus_seconds;
29use crate::decision::{DecisionInput, adjustment, changes_the_machine, decide};
30use crate::error::CoreError;
31use crate::kinds::{
32    ActionExecutedPayload, ActionRejectedPayload, ActionRequestedPayload, PreflightCheckedPayload,
33    agent_source, operator_source, system_source,
34};
35use crate::store::EventDraft;
36use crate::supervisor::{Issued, Supervisor};
37
38/// What became of one request, from the decision through to its intervention.
39#[derive(Debug, Clone, PartialEq)]
40pub struct ActionOutcome {
41    /// The record of the request and the decision taken on it.
42    pub record: ActionRecord,
43    /// What the printer made of it, absent when it was rejected.
44    pub executed: Option<Result<(), printobserver_printer_api::PrinterError>>,
45    /// The bounded intervention it opened, when it opened one.
46    pub intervention: Option<Intervention>,
47}
48
49impl ActionOutcome {
50    /// The decision policy took on the request.
51    #[must_use]
52    pub const fn decision(&self) -> &PolicyDecision {
53        &self.record.decision
54    }
55}
56
57/// Where an event about one actor's action came from.
58pub(crate) fn source_of(actor: &Actor) -> EventSource {
59    match actor.class() {
60        ActorClass::Agent => agent_source(),
61        ActorClass::Operator => operator_source(),
62        ActorClass::System => system_source(),
63    }
64}
65
66/// How long a bounded change stands for, when the request bounds it.
67fn duration_of(action: &PrintAction) -> Option<i64> {
68    match action {
69        PrintAction::SetFeedrateFactor { duration_s, .. }
70        | PrintAction::SetFlowrateFactor { duration_s, .. }
71        | PrintAction::SetToolTargetC { duration_s, .. }
72        | PrintAction::SetBedTargetC { duration_s, .. }
73        | PrintAction::SetFanPercent { duration_s, .. } => *duration_s,
74        PrintAction::Pause { .. }
75        | PrintAction::Resume { .. }
76        | PrintAction::Cancel { .. }
77        | PrintAction::StartPrint { .. }
78        | PrintAction::AcknowledgeFailure { .. }
79        | PrintAction::ClosePrint { .. } => None,
80    }
81}
82
83/// What the printer reported for one adjustable, when it reported anything.
84///
85/// Absent means the printer reported no value for it, which is what makes an
86/// intervention's expiry restore nothing and say so rather than writing a
87/// guessed default onto the machine.
88#[must_use]
89pub fn reported_value(snapshot: &PrinterSnapshot, adjustable: Adjustable) -> Option<f64> {
90    let reported = match adjustable {
91        Adjustable::Feedrate => snapshot.feedrate_factor,
92        Adjustable::Flowrate => snapshot.flowrate_factor,
93        Adjustable::Fan => snapshot.fan_percent,
94        Adjustable::BedTarget => snapshot.bed.as_ref().and_then(|heater| heater.target_c),
95        Adjustable::ToolTarget { tool } => usize::try_from(tool)
96            .ok()
97            .and_then(|index| snapshot.tools.get(index))
98            .and_then(|heater| heater.target_c),
99    };
100    reported.map(|value| value.value())
101}
102
103impl Supervisor {
104    /// Request one action against one print.
105    ///
106    /// The same call an operator's action makes, an agent's action makes and a
107    /// client's action makes. A rejected request reaches no action method of
108    /// the printer port at all, and the rejection is persisted carrying its own
109    /// reason so that the caller can ask again inside the range.
110    ///
111    /// # Errors
112    ///
113    /// Returns the store's own error when the decision, the execution or the
114    /// intervention could not be recorded. A refusal by the printer is not an
115    /// error: it is recorded and reported in [`ActionOutcome::executed`].
116    ///
117    /// A start may be made against a print other than `print_id`: it is
118    /// recorded against [`Self::print_to_start`]'s, which the answer's record
119    /// names.
120    pub async fn request_action(
121        &self,
122        print_id: PrintId,
123        action: PrintAction,
124    ) -> Result<ActionOutcome, CoreError> {
125        // A start that will need an analysis waits for it before it holds the
126        // resolution of prints, so the wait holds up no alert and no read.
127        if let PrintAction::StartPrint { file_name, .. } = &action {
128            // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
129            self.await_analysis(file_name, action.actor()).await?;
130        }
131        // A start holds every resolution of a print from the read that chooses
132        // its print until the printer has been asked to start: a read between
133        // the two would find the machine idle and close the print just opened.
134        // A close holds it too, from the read that finds the record over until
135        // the record is ended, so no other read closes it in between.
136        let (_starting, print_id) = match &action {
137            PrintAction::StartPrint { file_name, .. } => {
138                let resolving = self.resolving().await;
139                (
140                    Some(resolving),
141                    self.print_to_start(print_id, file_name).await?,
142                )
143            }
144            PrintAction::ClosePrint { .. } => (Some(self.resolving().await), print_id),
145            _ => (None, print_id),
146        };
147        let requested_at = self.clock().now();
148        let actor = action.actor().clone();
149        let print = self.stores().prints.print(print_id).await?;
150        let bounds = self.bounds_for(print.as_ref(), print_id).await?;
151        let snapshot = self.read_snapshot().await.ok();
152        let since_last_agent_action = if actor.class() == ActorClass::Agent {
153            self.since_last_agent_action(print_id).await?
154        } else {
155            None
156        };
157        let mut decision = decide(&DecisionInput {
158            action: &action,
159            actor: &actor,
160            requested_at,
161            print: print.as_ref(),
162            printer_state: snapshot.as_ref().map(|taken| &taken.connection),
163            bounds: &bounds.effective,
164            envelope: &self.config().envelope,
165            since_last_agent_action,
166        });
167        let preflight = self
168            .check_accepted(&action, print.as_ref(), &mut decision)
169            .await?;
170        let closing_state = self
171            .check_accepted_close(&action, print.as_ref(), &mut decision)
172            .await?;
173        let request = ActionRequest {
174            action: action.clone(),
175            actor: actor.clone(),
176            requested_at,
177        };
178        let issued = self.issue_action(request, decision, Some(print_id)).await?;
179        let source = source_of(&actor);
180        self.write_decision_down(print_id, &source, &action, &issued, preflight.as_ref())
181            .await?;
182        if !issued.succeeded() {
183            return Ok(ActionOutcome {
184                record: issued.record,
185                executed: issued.executed,
186                intervention: None,
187            });
188        }
189        // Only a change to the machine starts the agent's interval again.
190        if actor.class() == ActorClass::Agent && changes_the_machine(action.kind()) {
191            self.note_agent_action(print_id, self.clock().paced());
192        }
193        self.follow_an_accepted_action(print_id, &action, snapshot.as_ref());
194        if let PrintAction::StartPrint {
195            manifest,
196            file_name,
197            ..
198        } = &action
199        {
200            self.attach_manifest(print_id, manifest.clone()).await?;
201            self.follow_the_start(print_id, file_name, &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                        actor,
351                        asked,
352                    )
353                    .await?;
354                if let Some(reason) = refusal {
355                    *decision = PolicyDecision::Rejected(reason);
356                }
357                Ok(Some(checked))
358            }
359            PrintAction::Resume { .. } => {
360                if let Some(print) = print
361                    && let Some(recovery_event_id) = self.recovery_while_open(print).await?
362                {
363                    *decision = PolicyDecision::Rejected(RejectionReason::PrintNotResumable {
364                        recovery_event_id,
365                    });
366                }
367                Ok(None)
368            }
369            PrintAction::Cancel { .. } => {
370                // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
371                if let Some(print) = print
372                    && let Ok(job) = self.read_job().await
373                {
374                    self.record_position_from(print, &job, self.clock().now())
375                        .await?;
376                }
377                Ok(None)
378            }
379            _ => Ok(None),
380        }
381    }
382
383    /// What a start the printer took records: that this supervisor saw its
384    /// print begin, and the print's `print_started` naming the start, the
385    /// spools loaded and the check it passed — unless the print has one.
386    // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
387    async fn follow_the_start(
388        &self,
389        print_id: PrintId,
390        file_name: &FileName,
391        issued: &Issued,
392        preflight: Option<Preflight>,
393    ) -> Result<(), CoreError> {
394        self.note_seen_running(print_id);
395        // A print homes the machine as it starts, so Z is where its own
396        // G-code put it from here on.
397        self.trust_z();
398        if self.print_started_of(print_id).await?.is_none() {
399            self.record_print_started(
400                print_id,
401                Some(file_name.as_str().to_owned()),
402                Some(issued.record.id),
403                preflight,
404            )
405            .await?;
406        }
407        Ok(())
408    }
409
410    /// The print a start is made against.
411    ///
412    /// Starting a job begins a print of its own. So the printer is read first,
413    /// which closes every open print that read shows is over exactly as any
414    /// other read does ([`crate::listing`]), and when no print is open after it
415    /// one is opened for the file the start names — with no provider
416    /// identifier, and no sighting of a job until a read finds it running. A
417    /// print still open after the read is the one asked for, as it always was:
418    /// a printer running or holding a job refuses a start whichever print it
419    /// is recorded against.
420    async fn print_to_start(
421        &self,
422        asked: PrintId,
423        file_name: &FileName,
424    ) -> Result<PrintId, CoreError> {
425        if let Some(observed) = self.observe_job().await {
426            self.settle_open_prints(&observed).await?;
427        }
428        if !self.stores().prints.open_prints().await?.is_empty() {
429            return Ok(asked);
430        }
431        let opened = self
432            .stores()
433            .prints
434            .open_print(None, Some(file_name.as_str().to_owned()))
435            .await?;
436        Ok(opened.id)
437    }
438
439    /// What one action that went through does to what the supervisor holds of
440    /// its print: the detector's pause, and whether the running turn
441    /// acknowledged its event by command.
442    fn follow_an_accepted_action(
443        &self,
444        print_id: PrintId,
445        action: &PrintAction,
446        snapshot: Option<&PrinterSnapshot>,
447    ) {
448        self.follow_the_detectors_pause(print_id, action, snapshot);
449        if action.actor().class() == ActorClass::Agent
450            && matches!(action, PrintAction::AcknowledgeFailure { .. })
451        {
452            self.note_acknowledged_by_turn(print_id);
453        }
454    }
455
456    /// What one action that went through does to a pause the detector made.
457    ///
458    /// An agent's adjustment to a print the detector's pause is holding earns
459    /// the print its resume ([`crate::detector`]); an agent's acknowledgement
460    /// with `stop` leaves the pause for a person; and a print somebody else
461    /// resumed or cancelled is no longer the detector's to hold.
462    fn follow_the_detectors_pause(
463        &self,
464        print_id: PrintId,
465        action: &PrintAction,
466        snapshot: Option<&PrinterSnapshot>,
467    ) {
468        if !self.detector_paused(print_id) {
469            return;
470        }
471        let paused = snapshot.is_some_and(|taken| taken.connection == PrinterState::Paused);
472        match (action.actor().class(), action) {
473            (ActorClass::Agent, _) if adjustment(action).is_some() && paused => {
474                self.note_adjustment_while_paused(print_id, action.reason());
475            }
476            (
477                ActorClass::Agent,
478                PrintAction::AcknowledgeFailure {
479                    disposition: AcknowledgementDisposition::Stop,
480                    ..
481                },
482            )
483            | (_, PrintAction::Resume { .. } | PrintAction::Cancel { .. }) => {
484                self.forget_detector_pause(print_id);
485            }
486            _ => {}
487        }
488    }
489
490    /// Append one event about an action, sourced from whoever asked for it.
491    async fn append_action_event(
492        &self,
493        print_id: PrintId,
494        source: EventSource,
495        body: EventBody,
496    ) -> Result<(), CoreError> {
497        self.stores()
498            .events
499            .append_event(EventDraft {
500                print_id: Some(print_id),
501                source,
502                received_at: self.clock().now(),
503                body,
504                raw: None,
505            })
506            .await?;
507        Ok(())
508    }
509
510    /// The bounds in force for one print: the envelope, narrowed by its manifest.
511    pub(crate) async fn bounds_for(
512        &self,
513        print: Option<&PrintRecord>,
514        print_id: PrintId,
515    ) -> Result<Bounds, CoreError> {
516        let manifest = if print.is_some() {
517            self.stores().prints.manifest(print_id).await?
518        } else {
519            None
520        };
521        Ok(effective_bounds(&self.config().envelope, manifest.as_ref()))
522    }
523
524    /// Store a print's manifest, recording every range it asked wider than the
525    /// envelope's, so that nobody has to wonder later which bound applied.
526    async fn attach_manifest(
527        &self,
528        print_id: PrintId,
529        manifest: crate::records::JobManifest,
530    ) -> Result<(), CoreError> {
531        let narrowed = effective_bounds(&self.config().envelope, Some(&manifest));
532        self.stores()
533            .prints
534            .put_manifest(print_id, manifest)
535            .await?;
536        for narrowing in narrowed.narrowings {
537            self.stores()
538                .prints
539                .record_narrowing(print_id, narrowing)
540                .await?;
541        }
542        Ok(())
543    }
544
545    /// Open the bounded intervention an accepted adjustment asked for.
546    ///
547    /// An adjustable changed again before its expiry supersedes the earlier
548    /// intervention rather than stacking with it, and the later one carries the
549    /// earlier's prior value forward so that restoring still reaches the value
550    /// the print started from.
551    async fn open_bounded_intervention(
552        &self,
553        print_id: PrintId,
554        action: &PrintAction,
555        issued: &Issued,
556        snapshot: Option<&PrinterSnapshot>,
557        applied_at: Timestamp,
558    ) -> Result<Option<Intervention>, CoreError> {
559        let (Some((adjustable, applied_value)), Some(duration_s)) =
560            (adjustment(action), duration_of(action))
561        else {
562            return Ok(None);
563        };
564        let mut superseded = self.stores().actions.active_interventions(print_id).await?;
565        superseded.retain(|held| held.adjustable == adjustable);
566        superseded.sort_by_key(|held| held.applied_at);
567        let prior_value = superseded.first().map_or_else(
568            || snapshot.and_then(|taken| reported_value(taken, adjustable)),
569            |earliest| earliest.prior_value,
570        );
571        let expires_at =
572            plus_seconds(applied_at, duration_s).map_err(|error| CoreError::Unrepresentable {
573                detail: error.to_string(),
574            })?;
575        let opened = self
576            .stores()
577            .actions
578            .open_intervention(
579                issued.record.id,
580                adjustable,
581                prior_value,
582                applied_value,
583                applied_at,
584                expires_at,
585            )
586            .await?;
587        self.count_down(&opened);
588        for earlier in superseded {
589            self.stores()
590                .actions
591                .settle_intervention(
592                    earlier.id,
593                    InterventionOutcome::Superseded { by: opened.id },
594                )
595                .await?;
596            self.stop_counting_down(earlier.id);
597        }
598        Ok(Some(opened))
599    }
600}