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 [`EventKind::ActionRequested`], 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 printobserver_types::{
19    ActionExecutedPayload, ActionRecord, ActionRejectedPayload, ActionRequest,
20    ActionRequestedPayload, Actor, ActorClass, Adjustable, EventPayload, EventSource, Intervention,
21    InterventionOutcome, PolicyDecision, PrintAction, PrintId, PrintRecord, PrinterSnapshot,
22    Timestamp,
23};
24
25use crate::bounds::{Bounds, effective_bounds};
26use crate::clock::plus_seconds;
27use crate::decision::{DecisionInput, adjustment, decide};
28use crate::error::CoreError;
29use crate::supervisor::{Issued, Supervisor};
30
31/// What became of one request, from the decision through to its intervention.
32#[derive(Debug, Clone, PartialEq)]
33pub struct ActionOutcome {
34    /// The record of the request and the decision taken on it.
35    pub record: ActionRecord,
36    /// What the printer made of it, absent when it was rejected.
37    pub executed: Option<Result<(), printobserver_printer_api::PrinterError>>,
38    /// The bounded intervention it opened, when it opened one.
39    pub intervention: Option<Intervention>,
40}
41
42impl ActionOutcome {
43    /// The decision policy took on the request.
44    #[must_use]
45    pub const fn decision(&self) -> &PolicyDecision {
46        &self.record.decision
47    }
48}
49
50/// Where an event about one actor's action came from.
51const fn source_of(actor: &Actor) -> EventSource {
52    match actor.class() {
53        ActorClass::Agent => EventSource::Agent,
54        ActorClass::Operator => EventSource::Operator,
55        ActorClass::System => EventSource::System,
56    }
57}
58
59/// How long a bounded change stands for, when the request bounds it.
60fn duration_of(action: &PrintAction) -> Option<i64> {
61    match action {
62        PrintAction::SetFeedrateFactor { duration_s, .. }
63        | PrintAction::SetFlowrateFactor { duration_s, .. }
64        | PrintAction::SetToolTargetC { duration_s, .. }
65        | PrintAction::SetBedTargetC { duration_s, .. }
66        | PrintAction::SetFanPercent { duration_s, .. } => *duration_s,
67        PrintAction::Pause { .. }
68        | PrintAction::Resume { .. }
69        | PrintAction::Cancel { .. }
70        | PrintAction::StartPrint { .. }
71        | PrintAction::AcknowledgeFailure { .. } => None,
72    }
73}
74
75/// What the printer reported for one adjustable, when it reported anything.
76///
77/// Absent means the printer reported no value for it, which is what makes an
78/// intervention's expiry restore nothing and say so rather than writing a
79/// guessed default onto the machine.
80#[must_use]
81pub fn reported_value(snapshot: &PrinterSnapshot, adjustable: Adjustable) -> Option<f64> {
82    let reported = match adjustable {
83        Adjustable::Feedrate => snapshot.feedrate_factor,
84        Adjustable::Flowrate => snapshot.flowrate_factor,
85        Adjustable::Fan => snapshot.fan_percent,
86        Adjustable::BedTarget => snapshot.bed.as_ref().and_then(|heater| heater.target_c),
87        Adjustable::ToolTarget { tool } => usize::try_from(tool)
88            .ok()
89            .and_then(|index| snapshot.tools.get(index))
90            .and_then(|heater| heater.target_c),
91    };
92    reported.map(|value| value.value())
93}
94
95impl Supervisor {
96    /// Request one action against one print.
97    ///
98    /// The same call an operator's action makes, an agent's action makes and a
99    /// client's action makes. A rejected request reaches no action method of
100    /// the printer port at all, and the rejection is persisted carrying its own
101    /// reason so that the caller can ask again inside the range.
102    ///
103    /// # Errors
104    ///
105    /// Returns the store's own error when the decision, the execution or the
106    /// intervention could not be recorded. A refusal by the printer is not an
107    /// error: it is recorded and reported in [`ActionOutcome::executed`].
108    pub async fn request_action(
109        &self,
110        print_id: PrintId,
111        action: PrintAction,
112    ) -> Result<ActionOutcome, CoreError> {
113        let requested_at = self.clock().now();
114        let actor = action.actor().clone();
115        let print = self.store().print(print_id).await?;
116        let bounds = self.bounds_for(print.as_ref(), print_id).await?;
117        let snapshot = self.read_snapshot().await.ok();
118        let decision = decide(&DecisionInput {
119            action: &action,
120            actor: &actor,
121            requested_at,
122            print: print.as_ref(),
123            printer_state: snapshot.as_ref().map(|taken| &taken.connection),
124            bounds: &bounds.effective,
125            envelope: &self.config().envelope,
126            last_agent_action: self.last_agent_action(print_id),
127        });
128        let request = ActionRequest {
129            action: action.clone(),
130            actor: actor.clone(),
131            requested_at,
132        };
133        let issued = self.issue_decided_action(request, decision).await?;
134        let source = source_of(&actor);
135        self.append_action_event(
136            print_id,
137            source,
138            EventPayload::ActionRequested(ActionRequestedPayload {
139                action_id: issued.record.id,
140                action: action.clone(),
141                actor: actor.clone(),
142            }),
143        )
144        .await?;
145        if let PolicyDecision::Rejected(_) = &issued.record.decision {
146            self.append_action_event(
147                print_id,
148                source,
149                EventPayload::ActionRejected(ActionRejectedPayload {
150                    action_id: issued.record.id,
151                    decision: issued.record.decision.clone(),
152                }),
153            )
154            .await?;
155        }
156        if !issued.succeeded() {
157            return Ok(ActionOutcome {
158                record: issued.record,
159                executed: issued.executed,
160                intervention: None,
161            });
162        }
163        if actor.class() == ActorClass::Agent {
164            self.note_agent_action(print_id, requested_at);
165        }
166        if let PrintAction::StartPrint { manifest, .. } = &action {
167            self.attach_manifest(print_id, manifest.clone()).await?;
168        }
169        let intervention = self
170            .open_bounded_intervention(print_id, &action, &issued, snapshot.as_ref(), requested_at)
171            .await?;
172        self.append_action_event(
173            print_id,
174            source,
175            EventPayload::ActionExecuted(ActionExecutedPayload {
176                action_id: issued.record.id,
177                intervention_id: intervention.as_ref().map(|opened| opened.id),
178            }),
179        )
180        .await?;
181        Ok(ActionOutcome {
182            record: issued.record,
183            executed: issued.executed,
184            intervention,
185        })
186    }
187
188    /// Append one event about an action, sourced from whoever asked for it.
189    async fn append_action_event(
190        &self,
191        print_id: PrintId,
192        source: EventSource,
193        payload: EventPayload,
194    ) -> Result<(), CoreError> {
195        self.store()
196            .append_event(printobserver_store_api::EventDraft {
197                print_id: Some(print_id),
198                source,
199                received_at: self.clock().now(),
200                payload,
201                raw: None,
202            })
203            .await?;
204        Ok(())
205    }
206
207    /// The bounds in force for one print: the envelope, narrowed by its manifest.
208    pub(crate) async fn bounds_for(
209        &self,
210        print: Option<&PrintRecord>,
211        print_id: PrintId,
212    ) -> Result<Bounds, CoreError> {
213        let manifest = if print.is_some() {
214            self.store().manifest(print_id).await?
215        } else {
216            None
217        };
218        Ok(effective_bounds(&self.config().envelope, manifest.as_ref()))
219    }
220
221    /// Store a print's manifest, recording every range it asked wider than the
222    /// envelope's, so that nobody has to wonder later which bound applied.
223    async fn attach_manifest(
224        &self,
225        print_id: PrintId,
226        manifest: printobserver_types::JobManifest,
227    ) -> Result<(), CoreError> {
228        let narrowed = effective_bounds(&self.config().envelope, Some(&manifest));
229        self.store().put_manifest(print_id, manifest).await?;
230        for narrowing in narrowed.narrowings {
231            self.store().record_narrowing(print_id, narrowing).await?;
232        }
233        Ok(())
234    }
235
236    /// Open the bounded intervention an accepted adjustment asked for.
237    ///
238    /// An adjustable changed again before its expiry supersedes the earlier
239    /// intervention rather than stacking with it, and the later one carries the
240    /// earlier's prior value forward so that restoring still reaches the value
241    /// the print started from.
242    async fn open_bounded_intervention(
243        &self,
244        print_id: PrintId,
245        action: &PrintAction,
246        issued: &Issued,
247        snapshot: Option<&PrinterSnapshot>,
248        applied_at: Timestamp,
249    ) -> Result<Option<Intervention>, CoreError> {
250        let (Some((adjustable, applied_value)), Some(duration_s)) =
251            (adjustment(action), duration_of(action))
252        else {
253            return Ok(None);
254        };
255        let mut superseded = self.store().active_interventions(print_id).await?;
256        superseded.retain(|held| held.adjustable == adjustable);
257        superseded.sort_by_key(|held| held.applied_at);
258        let prior_value = superseded.first().map_or_else(
259            || snapshot.and_then(|taken| reported_value(taken, adjustable)),
260            |earliest| earliest.prior_value,
261        );
262        let expires_at =
263            plus_seconds(applied_at, duration_s).map_err(|error| CoreError::Unrepresentable {
264                detail: error.to_string(),
265            })?;
266        let opened = self
267            .store()
268            .open_intervention(
269                issued.record.id,
270                adjustable,
271                prior_value,
272                applied_value,
273                applied_at,
274                expires_at,
275            )
276            .await?;
277        for earlier in superseded {
278            self.store()
279                .settle_intervention(
280                    earlier.id,
281                    InterventionOutcome::Superseded { by: opened.id },
282                )
283                .await?;
284        }
285        Ok(Some(opened))
286    }
287}