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