1use 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#[derive(Debug, Clone, PartialEq)]
33pub struct ActionOutcome {
34 pub record: ActionRecord,
36 pub executed: Option<Result<(), printobserver_printer_api::PrinterError>>,
38 pub intervention: Option<Intervention>,
40}
41
42impl ActionOutcome {
43 #[must_use]
45 pub const fn decision(&self) -> &PolicyDecision {
46 &self.record.decision
47 }
48}
49
50const 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
59fn 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#[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 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 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 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 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 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}