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    ActionRecord, ActionRequest, Actor, ActorClass, Intervention, InterventionOutcome,
20    PolicyDecision, PrintAction, PrintRecord,
21};
22use printobserver_printer_api::Adjustable;
23use printobserver_printer_api::PrinterSnapshot;
24use printobserver_types::{EventBody, EventSource, PrintId, Timestamp};
25
26use crate::bounds::{Bounds, effective_bounds};
27use crate::clock::plus_seconds;
28use crate::decision::{DecisionInput, adjustment, decide};
29use crate::error::CoreError;
30use crate::kinds::{
31    ActionExecutedPayload, ActionRejectedPayload, ActionRequestedPayload, agent_source,
32    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.
57fn 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    pub async fn request_action(
115        &self,
116        print_id: PrintId,
117        action: PrintAction,
118    ) -> Result<ActionOutcome, CoreError> {
119        let requested_at = self.clock().now();
120        let actor = action.actor().clone();
121        let print = self.stores().prints.print(print_id).await?;
122        let bounds = self.bounds_for(print.as_ref(), print_id).await?;
123        let snapshot = self.read_snapshot().await.ok();
124        let decision = decide(&DecisionInput {
125            action: &action,
126            actor: &actor,
127            requested_at,
128            print: print.as_ref(),
129            printer_state: snapshot.as_ref().map(|taken| &taken.connection),
130            bounds: &bounds.effective,
131            envelope: &self.config().envelope,
132            last_agent_action: self.last_agent_action(print_id),
133        });
134        let request = ActionRequest {
135            action: action.clone(),
136            actor: actor.clone(),
137            requested_at,
138        };
139        let issued = self.issue_decided_action(request, decision).await?;
140        let source = source_of(&actor);
141        self.append_action_event(
142            print_id,
143            source.clone(),
144            EventBody::of(&ActionRequestedPayload {
145                action_id: issued.record.id,
146                action: action.clone(),
147                actor: actor.clone(),
148            })?,
149        )
150        .await?;
151        if let PolicyDecision::Rejected(_) = &issued.record.decision {
152            self.append_action_event(
153                print_id,
154                source.clone(),
155                EventBody::of(&ActionRejectedPayload {
156                    action_id: issued.record.id,
157                    decision: issued.record.decision.clone(),
158                })?,
159            )
160            .await?;
161        }
162        if !issued.succeeded() {
163            return Ok(ActionOutcome {
164                record: issued.record,
165                executed: issued.executed,
166                intervention: None,
167            });
168        }
169        if actor.class() == ActorClass::Agent {
170            self.note_agent_action(print_id, requested_at);
171        }
172        if let PrintAction::StartPrint { manifest, .. } = &action {
173            self.attach_manifest(print_id, manifest.clone()).await?;
174        }
175        let intervention = self
176            .open_bounded_intervention(print_id, &action, &issued, snapshot.as_ref(), requested_at)
177            .await?;
178        self.append_action_event(
179            print_id,
180            source,
181            EventBody::of(&ActionExecutedPayload {
182                action_id: issued.record.id,
183                intervention_id: intervention.as_ref().map(|opened| opened.id),
184            })?,
185        )
186        .await?;
187        Ok(ActionOutcome {
188            record: issued.record,
189            executed: issued.executed,
190            intervention,
191        })
192    }
193
194    /// Append one event about an action, sourced from whoever asked for it.
195    async fn append_action_event(
196        &self,
197        print_id: PrintId,
198        source: EventSource,
199        body: EventBody,
200    ) -> Result<(), CoreError> {
201        self.stores()
202            .events
203            .append_event(EventDraft {
204                print_id: Some(print_id),
205                source,
206                received_at: self.clock().now(),
207                body,
208                raw: None,
209            })
210            .await?;
211        Ok(())
212    }
213
214    /// The bounds in force for one print: the envelope, narrowed by its manifest.
215    pub(crate) async fn bounds_for(
216        &self,
217        print: Option<&PrintRecord>,
218        print_id: PrintId,
219    ) -> Result<Bounds, CoreError> {
220        let manifest = if print.is_some() {
221            self.stores().prints.manifest(print_id).await?
222        } else {
223            None
224        };
225        Ok(effective_bounds(&self.config().envelope, manifest.as_ref()))
226    }
227
228    /// Store a print's manifest, recording every range it asked wider than the
229    /// envelope's, so that nobody has to wonder later which bound applied.
230    async fn attach_manifest(
231        &self,
232        print_id: PrintId,
233        manifest: crate::records::JobManifest,
234    ) -> Result<(), CoreError> {
235        let narrowed = effective_bounds(&self.config().envelope, Some(&manifest));
236        self.stores()
237            .prints
238            .put_manifest(print_id, manifest)
239            .await?;
240        for narrowing in narrowed.narrowings {
241            self.stores()
242                .prints
243                .record_narrowing(print_id, narrowing)
244                .await?;
245        }
246        Ok(())
247    }
248
249    /// Open the bounded intervention an accepted adjustment asked for.
250    ///
251    /// An adjustable changed again before its expiry supersedes the earlier
252    /// intervention rather than stacking with it, and the later one carries the
253    /// earlier's prior value forward so that restoring still reaches the value
254    /// the print started from.
255    async fn open_bounded_intervention(
256        &self,
257        print_id: PrintId,
258        action: &PrintAction,
259        issued: &Issued,
260        snapshot: Option<&PrinterSnapshot>,
261        applied_at: Timestamp,
262    ) -> Result<Option<Intervention>, CoreError> {
263        let (Some((adjustable, applied_value)), Some(duration_s)) =
264            (adjustment(action), duration_of(action))
265        else {
266            return Ok(None);
267        };
268        let mut superseded = self.stores().actions.active_interventions(print_id).await?;
269        superseded.retain(|held| held.adjustable == adjustable);
270        superseded.sort_by_key(|held| held.applied_at);
271        let prior_value = superseded.first().map_or_else(
272            || snapshot.and_then(|taken| reported_value(taken, adjustable)),
273            |earliest| earliest.prior_value,
274        );
275        let expires_at =
276            plus_seconds(applied_at, duration_s).map_err(|error| CoreError::Unrepresentable {
277                detail: error.to_string(),
278            })?;
279        let opened = self
280            .stores()
281            .actions
282            .open_intervention(
283                issued.record.id,
284                adjustable,
285                prior_value,
286                applied_value,
287                applied_at,
288                expires_at,
289            )
290            .await?;
291        for earlier in superseded {
292            self.stores()
293                .actions
294                .settle_intervention(
295                    earlier.id,
296                    InterventionOutcome::Superseded { by: opened.id },
297                )
298                .await?;
299        }
300        Ok(Some(opened))
301    }
302}