1use crate::records::{
19 AcknowledgementDisposition, ActionRecord, ActionRequest, Actor, ActorClass, Intervention,
20 InterventionOutcome, PolicyDecision, Preflight, PrintAction, PrintRecord,
21};
22use printobserver_printer_api::Adjustable;
23use printobserver_printer_api::{PrinterSnapshot, PrinterState};
24use printobserver_types::{EventBody, EventSource, FileName, PrintId, Timestamp};
25
26use crate::bounds::{Bounds, effective_bounds};
27use crate::clock::plus_seconds;
28use crate::decision::{DecisionInput, adjustment, changes_the_machine, decide};
29use crate::error::CoreError;
30use crate::kinds::{
31 ActionExecutedPayload, ActionRejectedPayload, ActionRequestedPayload, PreflightCheckedPayload,
32 agent_source, operator_source, system_source,
33};
34use crate::store::EventDraft;
35use crate::supervisor::{Issued, Supervisor};
36
37#[derive(Debug, Clone, PartialEq)]
39pub struct ActionOutcome {
40 pub record: ActionRecord,
42 pub executed: Option<Result<(), printobserver_printer_api::PrinterError>>,
44 pub intervention: Option<Intervention>,
46}
47
48impl ActionOutcome {
49 #[must_use]
51 pub const fn decision(&self) -> &PolicyDecision {
52 &self.record.decision
53 }
54}
55
56pub(crate) fn 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
65fn 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#[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 pub async fn request_action(
119 &self,
120 print_id: PrintId,
121 action: PrintAction,
122 ) -> Result<ActionOutcome, CoreError> {
123 if let PrintAction::StartPrint { file_name, .. } = &action {
126 self.await_analysis(file_name, action.actor()).await?;
128 }
129 let (_starting, print_id) = match &action {
133 PrintAction::StartPrint { file_name, .. } => {
134 let resolving = self.resolving().await;
135 (
136 Some(resolving),
137 self.print_to_start(print_id, file_name).await?,
138 )
139 }
140 _ => (None, print_id),
141 };
142 let requested_at = self.clock().now();
143 let actor = action.actor().clone();
144 let print = self.stores().prints.print(print_id).await?;
145 let bounds = self.bounds_for(print.as_ref(), print_id).await?;
146 let snapshot = self.read_snapshot().await.ok();
147 let mut decision = decide(&DecisionInput {
148 action: &action,
149 actor: &actor,
150 requested_at,
151 print: print.as_ref(),
152 printer_state: snapshot.as_ref().map(|taken| &taken.connection),
153 bounds: &bounds.effective,
154 envelope: &self.config().envelope,
155 last_agent_action: self.last_agent_action(print_id),
156 });
157 let preflight = self
158 .check_accepted(&action, print.as_ref(), &mut decision)
159 .await?;
160 let request = ActionRequest {
161 action: action.clone(),
162 actor: actor.clone(),
163 requested_at,
164 };
165 let issued = self.issue_decided_action(request, decision).await?;
166 let source = source_of(&actor);
167 self.write_decision_down(print_id, &source, &action, &issued, preflight.as_ref())
168 .await?;
169 if !issued.succeeded() {
170 return Ok(ActionOutcome {
171 record: issued.record,
172 executed: issued.executed,
173 intervention: None,
174 });
175 }
176 if actor.class() == ActorClass::Agent && changes_the_machine(action.kind()) {
178 self.note_agent_action(print_id, requested_at);
179 }
180 self.follow_the_detectors_pause(print_id, &action, snapshot.as_ref());
181 if let PrintAction::StartPrint {
182 manifest,
183 file_name,
184 ..
185 } = &action
186 {
187 self.attach_manifest(print_id, manifest.clone()).await?;
188 self.follow_the_start(print_id, file_name, &issued, preflight)
189 .await?;
190 }
191 let intervention = self
192 .open_bounded_intervention(print_id, &action, &issued, snapshot.as_ref(), requested_at)
193 .await?;
194 self.append_action_event(
195 print_id,
196 source,
197 EventBody::of(&ActionExecutedPayload {
198 action_id: issued.record.id,
199 intervention_id: intervention.as_ref().map(|opened| opened.id),
200 })?,
201 )
202 .await?;
203 Ok(ActionOutcome {
204 record: issued.record,
205 executed: issued.executed,
206 intervention,
207 })
208 }
209
210 async fn write_decision_down(
214 &self,
215 print_id: PrintId,
216 source: &EventSource,
217 action: &PrintAction,
218 issued: &Issued,
219 preflight: Option<&Preflight>,
220 ) -> Result<(), CoreError> {
221 self.append_action_event(
222 print_id,
223 source.clone(),
224 EventBody::of(&ActionRequestedPayload {
225 action_id: issued.record.id,
226 action: action.clone(),
227 actor: action.actor().clone(),
228 })?,
229 )
230 .await?;
231 if let Some(checked) = preflight {
233 self.append_action_event(
234 print_id,
235 source.clone(),
236 EventBody::of(&PreflightCheckedPayload {
237 preflight: checked.clone(),
238 action_id: Some(issued.record.id),
239 })?,
240 )
241 .await?;
242 }
243 if let PolicyDecision::Rejected(_) = &issued.record.decision {
244 self.append_action_event(
245 print_id,
246 source.clone(),
247 EventBody::of(&ActionRejectedPayload {
248 action_id: issued.record.id,
249 decision: issued.record.decision.clone(),
250 })?,
251 )
252 .await?;
253 }
254 Ok(())
255 }
256
257 async fn check_accepted(
265 &self,
266 action: &PrintAction,
267 print: Option<&PrintRecord>,
268 decision: &mut PolicyDecision,
269 ) -> Result<Option<Preflight>, CoreError> {
270 if *decision != PolicyDecision::Accepted {
271 return Ok(None);
272 }
273 match action {
274 PrintAction::StartPrint {
275 file_name,
276 override_filament_check,
277 actor,
278 ..
279 } => {
280 let (checked, refusal) = self
281 .check_start(file_name, actor, (*override_filament_check).into())
282 .await?;
283 if let Some(reason) = refusal {
284 *decision = PolicyDecision::Rejected(reason);
285 }
286 Ok(Some(checked))
287 }
288 PrintAction::Cancel { .. } => {
289 if let Some(print) = print
291 && let Ok(job) = self.read_job().await
292 {
293 self.record_position_from(print, &job, self.clock().now())
294 .await?;
295 }
296 Ok(None)
297 }
298 _ => Ok(None),
299 }
300 }
301
302 async fn follow_the_start(
307 &self,
308 print_id: PrintId,
309 file_name: &FileName,
310 issued: &Issued,
311 preflight: Option<Preflight>,
312 ) -> Result<(), CoreError> {
313 self.note_seen_running(print_id);
314 if self.print_started_of(print_id).await?.is_none() {
315 self.record_print_started(
316 print_id,
317 Some(file_name.as_str().to_owned()),
318 Some(issued.record.id),
319 preflight,
320 )
321 .await?;
322 }
323 Ok(())
324 }
325
326 async fn print_to_start(
337 &self,
338 asked: PrintId,
339 file_name: &FileName,
340 ) -> Result<PrintId, CoreError> {
341 if let Some(observed) = self.observe_job().await {
342 self.settle_open_prints(&observed).await?;
343 }
344 if !self.stores().prints.open_prints().await?.is_empty() {
345 return Ok(asked);
346 }
347 let opened = self
348 .stores()
349 .prints
350 .open_print(None, Some(file_name.as_str().to_owned()))
351 .await?;
352 Ok(opened.id)
353 }
354
355 fn follow_the_detectors_pause(
362 &self,
363 print_id: PrintId,
364 action: &PrintAction,
365 snapshot: Option<&PrinterSnapshot>,
366 ) {
367 if !self.detector_paused(print_id) {
368 return;
369 }
370 let paused = snapshot.is_some_and(|taken| taken.connection == PrinterState::Paused);
371 match (action.actor().class(), action) {
372 (ActorClass::Agent, _) if adjustment(action).is_some() && paused => {
373 self.note_adjustment_while_paused(print_id, action.reason());
374 }
375 (
376 ActorClass::Agent,
377 PrintAction::AcknowledgeFailure {
378 disposition: AcknowledgementDisposition::Stop,
379 ..
380 },
381 )
382 | (_, PrintAction::Resume { .. } | PrintAction::Cancel { .. }) => {
383 self.forget_detector_pause(print_id);
384 }
385 _ => {}
386 }
387 }
388
389 async fn append_action_event(
391 &self,
392 print_id: PrintId,
393 source: EventSource,
394 body: EventBody,
395 ) -> Result<(), CoreError> {
396 self.stores()
397 .events
398 .append_event(EventDraft {
399 print_id: Some(print_id),
400 source,
401 received_at: self.clock().now(),
402 body,
403 raw: None,
404 })
405 .await?;
406 Ok(())
407 }
408
409 pub(crate) async fn bounds_for(
411 &self,
412 print: Option<&PrintRecord>,
413 print_id: PrintId,
414 ) -> Result<Bounds, CoreError> {
415 let manifest = if print.is_some() {
416 self.stores().prints.manifest(print_id).await?
417 } else {
418 None
419 };
420 Ok(effective_bounds(&self.config().envelope, manifest.as_ref()))
421 }
422
423 async fn attach_manifest(
426 &self,
427 print_id: PrintId,
428 manifest: crate::records::JobManifest,
429 ) -> Result<(), CoreError> {
430 let narrowed = effective_bounds(&self.config().envelope, Some(&manifest));
431 self.stores()
432 .prints
433 .put_manifest(print_id, manifest)
434 .await?;
435 for narrowing in narrowed.narrowings {
436 self.stores()
437 .prints
438 .record_narrowing(print_id, narrowing)
439 .await?;
440 }
441 Ok(())
442 }
443
444 async fn open_bounded_intervention(
451 &self,
452 print_id: PrintId,
453 action: &PrintAction,
454 issued: &Issued,
455 snapshot: Option<&PrinterSnapshot>,
456 applied_at: Timestamp,
457 ) -> Result<Option<Intervention>, CoreError> {
458 let (Some((adjustable, applied_value)), Some(duration_s)) =
459 (adjustment(action), duration_of(action))
460 else {
461 return Ok(None);
462 };
463 let mut superseded = self.stores().actions.active_interventions(print_id).await?;
464 superseded.retain(|held| held.adjustable == adjustable);
465 superseded.sort_by_key(|held| held.applied_at);
466 let prior_value = superseded.first().map_or_else(
467 || snapshot.and_then(|taken| reported_value(taken, adjustable)),
468 |earliest| earliest.prior_value,
469 );
470 let expires_at =
471 plus_seconds(applied_at, duration_s).map_err(|error| CoreError::Unrepresentable {
472 detail: error.to_string(),
473 })?;
474 let opened = self
475 .stores()
476 .actions
477 .open_intervention(
478 issued.record.id,
479 adjustable,
480 prior_value,
481 applied_value,
482 applied_at,
483 expires_at,
484 )
485 .await?;
486 for earlier in superseded {
487 self.stores()
488 .actions
489 .settle_intervention(
490 earlier.id,
491 InterventionOutcome::Superseded { by: opened.id },
492 )
493 .await?;
494 }
495 Ok(Some(opened))
496 }
497}