1use crate::preflight::Overrides;
19use crate::records::{
20 AcknowledgementDisposition, ActionRecord, ActionRequest, Actor, ActorClass, Intervention,
21 InterventionOutcome, JobManifest, PolicyDecision, Preflight, PrintAction, PrintRecord,
22 RejectionReason,
23};
24use printobserver_printer_api::Adjustable;
25use printobserver_printer_api::{PrinterSnapshot, PrinterState};
26use printobserver_types::{EventBody, EventSource, FileName, PrintId, Timestamp};
27
28use crate::bounds::{Bounds, effective_bounds};
29use crate::clock::plus_seconds;
30use crate::decision::{DecisionInput, adjustment, changes_the_machine, decide};
31use crate::error::CoreError;
32use crate::kinds::{
33 ActionExecutedPayload, ActionRejectedPayload, ActionRequestedPayload, PreflightCheckedPayload,
34 agent_source, operator_source, system_source,
35};
36use crate::store::EventDraft;
37use crate::supervisor::{Issued, Supervisor};
38
39#[derive(Debug, Clone, PartialEq)]
41pub struct ActionOutcome {
42 pub record: ActionRecord,
44 pub executed: Option<Result<(), printobserver_printer_api::PrinterError>>,
46 pub intervention: Option<Intervention>,
48}
49
50impl ActionOutcome {
51 #[must_use]
53 pub const fn decision(&self) -> &PolicyDecision {
54 &self.record.decision
55 }
56}
57
58pub(crate) fn source_of(actor: &Actor) -> EventSource {
60 match actor.class() {
61 ActorClass::Agent => agent_source(),
62 ActorClass::Operator => operator_source(),
63 ActorClass::System => system_source(),
64 }
65}
66
67fn duration_of(action: &PrintAction) -> Option<i64> {
69 match action {
70 PrintAction::SetFeedrateFactor { duration_s, .. }
71 | PrintAction::SetFlowrateFactor { duration_s, .. }
72 | PrintAction::SetToolTargetC { duration_s, .. }
73 | PrintAction::SetBedTargetC { duration_s, .. }
74 | PrintAction::SetFanPercent { duration_s, .. } => *duration_s,
75 PrintAction::Pause { .. }
76 | PrintAction::Resume { .. }
77 | PrintAction::Cancel { .. }
78 | PrintAction::StartPrint { .. }
79 | PrintAction::AcknowledgeFailure { .. }
80 | PrintAction::ClosePrint { .. } => None,
81 }
82}
83
84#[must_use]
90pub fn reported_value(snapshot: &PrinterSnapshot, adjustable: Adjustable) -> Option<f64> {
91 let reported = match adjustable {
92 Adjustable::Feedrate => snapshot.feedrate_factor,
93 Adjustable::Flowrate => snapshot.flowrate_factor,
94 Adjustable::Fan => snapshot.fan_percent,
95 Adjustable::BedTarget => snapshot.bed.as_ref().and_then(|heater| heater.target_c),
96 Adjustable::ToolTarget { tool } => usize::try_from(tool)
97 .ok()
98 .and_then(|index| snapshot.tools.get(index))
99 .and_then(|heater| heater.target_c),
100 };
101 reported.map(|value| value.value())
102}
103
104impl Supervisor {
105 pub async fn request_action(
122 &self,
123 print_id: PrintId,
124 action: PrintAction,
125 ) -> Result<ActionOutcome, CoreError> {
126 if let PrintAction::StartPrint { file_name, .. } = &action {
129 self.await_analysis(file_name, action.actor()).await?;
131 }
132 let (_starting, print_id) = match &action {
138 PrintAction::StartPrint { file_name, .. } => {
139 let resolving = self.resolving().await;
140 (
141 Some(resolving),
142 self.print_to_start(print_id, file_name).await?,
143 )
144 }
145 PrintAction::ClosePrint { .. } => (Some(self.resolving().await), print_id),
146 _ => (None, print_id),
147 };
148 let requested_at = self.clock().now();
149 let actor = action.actor().clone();
150 let print = self.stores().prints.print(print_id).await?;
151 let bounds = self.bounds_for(print.as_ref(), print_id).await?;
152 let snapshot = self.read_snapshot().await.ok();
153 let since_last_agent_action = if actor.class() == ActorClass::Agent {
154 self.since_last_agent_action(print_id).await?
155 } else {
156 None
157 };
158 let mut decision = decide(&DecisionInput {
159 action: &action,
160 actor: &actor,
161 requested_at,
162 print: print.as_ref(),
163 printer_state: snapshot.as_ref().map(|taken| &taken.connection),
164 bounds: &bounds.effective,
165 envelope: &self.config().envelope,
166 since_last_agent_action,
167 });
168 let preflight = self
169 .check_accepted(&action, print.as_ref(), &mut decision)
170 .await?;
171 let closing_state = self
172 .check_accepted_close(&action, print.as_ref(), &mut decision)
173 .await?;
174 let request = ActionRequest {
175 action: action.clone(),
176 actor: actor.clone(),
177 requested_at,
178 };
179 let issued = self.issue_action(request, decision, Some(print_id)).await?;
180 let source = source_of(&actor);
181 self.write_decision_down(print_id, &source, &action, &issued, preflight.as_ref())
182 .await?;
183 if !issued.succeeded() {
184 return Ok(ActionOutcome {
185 record: issued.record,
186 executed: issued.executed,
187 intervention: None,
188 });
189 }
190 if actor.class() == ActorClass::Agent && changes_the_machine(action.kind()) {
192 self.note_agent_action(print_id, self.clock().paced());
193 }
194 self.follow_an_accepted_action(print_id, &action, snapshot.as_ref());
195 if let PrintAction::StartPrint {
196 manifest,
197 file_name,
198 ..
199 } = &action
200 {
201 self.follow_the_start(print_id, file_name, manifest, &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 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 async fn refusing_while_waiting(
241 &self,
242 action: &PrintAction,
243 print: Option<&PrintRecord>,
244 decided: PolicyDecision,
245 ) -> Result<PolicyDecision, CoreError> {
246 let open = print.filter(|print| print.ended_at.is_none());
247 let Some(print) =
248 open.filter(|_| crate::planned::REFUSED_WHILE_WAITING.contains(&action.kind()))
249 else {
250 return Ok(decided);
251 };
252 Ok(match self.planned_change_waiting(print.id).await? {
253 Some(waiting) => PolicyDecision::Rejected(waiting.refusal()),
254 None => decided,
255 })
256 }
257
258 async fn write_decision_down(
262 &self,
263 print_id: PrintId,
264 source: &EventSource,
265 action: &PrintAction,
266 issued: &Issued,
267 preflight: Option<&Preflight>,
268 ) -> Result<(), CoreError> {
269 self.note_stop_asked(print_id, action);
271 self.append_action_event(
272 print_id,
273 source.clone(),
274 EventBody::of(&ActionRequestedPayload {
275 action_id: issued.record.id,
276 action: action.clone(),
277 actor: action.actor().clone(),
278 })?,
279 )
280 .await?;
281 if let Some(checked) = preflight {
283 self.append_action_event(
284 print_id,
285 source.clone(),
286 EventBody::of(&PreflightCheckedPayload {
287 preflight: checked.clone(),
288 action_id: Some(issued.record.id),
289 })?,
290 )
291 .await?;
292 }
293 if let PolicyDecision::Rejected(_) = &issued.record.decision {
294 self.append_action_event(
295 print_id,
296 source.clone(),
297 EventBody::of(&ActionRejectedPayload {
298 action_id: issued.record.id,
299 decision: issued.record.decision.clone(),
300 })?,
301 )
302 .await?;
303 }
304 Ok(())
305 }
306
307 async fn check_accepted(
319 &self,
320 action: &PrintAction,
321 print: Option<&PrintRecord>,
322 decision: &mut PolicyDecision,
323 ) -> Result<Option<Preflight>, CoreError> {
324 *decision = self
325 .refusing_while_waiting(action, print, decision.clone())
326 .await?;
327 if *decision != PolicyDecision::Accepted {
328 return Ok(None);
329 }
330 match action {
331 PrintAction::StartPrint {
332 file_name,
333 manifest,
334 override_filament_check,
335 override_material_check,
336 override_sheet_check,
337 actor,
338 ..
339 } => {
340 let asked = Overrides {
341 filament: (*override_filament_check).into(),
342 material: (*override_material_check).into(),
343 sheet: (*override_sheet_check).into(),
344 };
345 let (checked, refusal) = self
346 .check_start(
347 file_name,
348 manifest.sheet.as_deref(),
349 &manifest.segment_spools,
350 manifest.camera_check,
351 actor,
352 asked,
353 )
354 .await?;
355 if let Some(reason) = refusal {
356 *decision = PolicyDecision::Rejected(reason);
357 }
358 Ok(Some(checked))
359 }
360 PrintAction::Resume { .. } => {
361 if let Some(print) = print
362 && let Some(recovery_event_id) = self.recovery_while_open(print).await?
363 {
364 *decision = PolicyDecision::Rejected(RejectionReason::PrintNotResumable {
365 recovery_event_id,
366 });
367 }
368 Ok(None)
369 }
370 PrintAction::Cancel { .. } => {
371 if let Some(print) = print
373 && let Ok(job) = self.read_job().await
374 {
375 self.record_position_from(print, &job, self.clock().now())
376 .await?;
377 }
378 Ok(None)
379 }
380 _ => Ok(None),
381 }
382 }
383
384 async fn follow_the_start(
390 &self,
391 print_id: PrintId,
392 file_name: &FileName,
393 manifest: &JobManifest,
394 issued: &Issued,
395 preflight: Option<Preflight>,
396 ) -> Result<(), CoreError> {
397 self.attach_manifest(print_id, manifest.clone()).await?;
398 self.note_seen_running(print_id);
399 self.trust_z();
402 if self.print_started_of(print_id).await?.is_none() {
403 self.record_print_started(
404 print_id,
405 Some(file_name.as_str().to_owned()),
406 Some(issued.record.id),
407 preflight,
408 manifest.camera_check,
409 )
410 .await?;
411 }
412 Ok(())
413 }
414
415 async fn print_to_start(
426 &self,
427 asked: PrintId,
428 file_name: &FileName,
429 ) -> Result<PrintId, CoreError> {
430 if let Some(observed) = self.observe_job().await {
431 self.settle_open_prints(&observed).await?;
432 }
433 if !self.stores().prints.open_prints().await?.is_empty() {
434 return Ok(asked);
435 }
436 let opened = self
437 .stores()
438 .prints
439 .open_print(None, Some(file_name.as_str().to_owned()))
440 .await?;
441 Ok(opened.id)
442 }
443
444 fn follow_an_accepted_action(
449 &self,
450 print_id: PrintId,
451 action: &PrintAction,
452 snapshot: Option<&PrinterSnapshot>,
453 ) {
454 self.follow_the_detectors_pause(print_id, action, snapshot);
455 match (action.actor().class(), action) {
456 (ActorClass::Agent, PrintAction::Pause { .. }) => self.note_agent_pause(print_id),
457 (_, PrintAction::Resume { .. } | PrintAction::Cancel { .. }) => {
458 self.note_pause_lifted(print_id);
459 }
460 _ => {}
461 }
462 if action.actor().class() == ActorClass::Agent
463 && matches!(action, PrintAction::AcknowledgeFailure { .. })
464 {
465 self.note_acknowledged_by_turn(print_id);
466 }
467 }
468
469 fn follow_the_detectors_pause(
476 &self,
477 print_id: PrintId,
478 action: &PrintAction,
479 snapshot: Option<&PrinterSnapshot>,
480 ) {
481 if !self.detector_paused(print_id) {
482 return;
483 }
484 let paused = snapshot.is_some_and(|taken| taken.connection == PrinterState::Paused);
485 match (action.actor().class(), action) {
486 (ActorClass::Agent, _) if adjustment(action).is_some() && paused => {
487 self.note_adjustment_while_paused(print_id, action.reason());
488 }
489 (
490 ActorClass::Agent,
491 PrintAction::AcknowledgeFailure {
492 disposition: AcknowledgementDisposition::Stop,
493 ..
494 },
495 )
496 | (_, PrintAction::Resume { .. } | PrintAction::Cancel { .. }) => {
497 self.forget_detector_pause(print_id);
498 }
499 _ => {}
500 }
501 }
502
503 async fn append_action_event(
505 &self,
506 print_id: PrintId,
507 source: EventSource,
508 body: EventBody,
509 ) -> Result<(), CoreError> {
510 self.stores()
511 .events
512 .append_event(EventDraft {
513 print_id: Some(print_id),
514 source,
515 received_at: self.clock().now(),
516 body,
517 raw: None,
518 })
519 .await?;
520 Ok(())
521 }
522
523 pub(crate) async fn bounds_for(
525 &self,
526 print: Option<&PrintRecord>,
527 print_id: PrintId,
528 ) -> Result<Bounds, CoreError> {
529 let manifest = if print.is_some() {
530 self.stores().prints.manifest(print_id).await?
531 } else {
532 None
533 };
534 Ok(effective_bounds(&self.config().envelope, manifest.as_ref()))
535 }
536
537 async fn attach_manifest(
540 &self,
541 print_id: PrintId,
542 manifest: crate::records::JobManifest,
543 ) -> Result<(), CoreError> {
544 let narrowed = effective_bounds(&self.config().envelope, Some(&manifest));
545 self.stores()
546 .prints
547 .put_manifest(print_id, manifest)
548 .await?;
549 for narrowing in narrowed.narrowings {
550 self.stores()
551 .prints
552 .record_narrowing(print_id, narrowing)
553 .await?;
554 }
555 Ok(())
556 }
557
558 async fn open_bounded_intervention(
565 &self,
566 print_id: PrintId,
567 action: &PrintAction,
568 issued: &Issued,
569 snapshot: Option<&PrinterSnapshot>,
570 applied_at: Timestamp,
571 ) -> Result<Option<Intervention>, CoreError> {
572 let (Some((adjustable, applied_value)), Some(duration_s)) =
573 (adjustment(action), duration_of(action))
574 else {
575 return Ok(None);
576 };
577 let mut superseded = self.stores().actions.active_interventions(print_id).await?;
578 superseded.retain(|held| held.adjustable == adjustable);
579 superseded.sort_by_key(|held| held.applied_at);
580 let prior_value = superseded.first().map_or_else(
581 || snapshot.and_then(|taken| reported_value(taken, adjustable)),
582 |earliest| earliest.prior_value,
583 );
584 let expires_at =
585 plus_seconds(applied_at, duration_s).map_err(|error| CoreError::Unrepresentable {
586 detail: error.to_string(),
587 })?;
588 let opened = self
589 .stores()
590 .actions
591 .open_intervention(
592 issued.record.id,
593 adjustable,
594 prior_value,
595 applied_value,
596 applied_at,
597 expires_at,
598 )
599 .await?;
600 self.count_down(&opened);
601 for earlier in superseded {
602 self.stores()
603 .actions
604 .settle_intervention(
605 earlier.id,
606 InterventionOutcome::Superseded { by: opened.id },
607 )
608 .await?;
609 self.stop_counting_down(earlier.id);
610 }
611 Ok(Some(opened))
612 }
613}