1use crate::preflight::Overrides;
19use crate::records::{
20 AcknowledgementDisposition, ActionRecord, ActionRequest, Actor, ActorClass, Intervention,
21 InterventionOutcome, PolicyDecision, Preflight, PrintAction, PrintRecord, RejectionReason,
22};
23use printobserver_printer_api::Adjustable;
24use printobserver_printer_api::{PrinterSnapshot, PrinterState};
25use printobserver_types::{EventBody, EventSource, FileName, PrintId, Timestamp};
26
27use crate::bounds::{Bounds, effective_bounds};
28use crate::clock::plus_seconds;
29use crate::decision::{DecisionInput, adjustment, changes_the_machine, decide};
30use crate::error::CoreError;
31use crate::kinds::{
32 ActionExecutedPayload, ActionRejectedPayload, ActionRequestedPayload, PreflightCheckedPayload,
33 agent_source, operator_source, system_source,
34};
35use crate::store::EventDraft;
36use crate::supervisor::{Issued, Supervisor};
37
38#[derive(Debug, Clone, PartialEq)]
40pub struct ActionOutcome {
41 pub record: ActionRecord,
43 pub executed: Option<Result<(), printobserver_printer_api::PrinterError>>,
45 pub intervention: Option<Intervention>,
47}
48
49impl ActionOutcome {
50 #[must_use]
52 pub const fn decision(&self) -> &PolicyDecision {
53 &self.record.decision
54 }
55}
56
57pub(crate) fn source_of(actor: &Actor) -> EventSource {
59 match actor.class() {
60 ActorClass::Agent => agent_source(),
61 ActorClass::Operator => operator_source(),
62 ActorClass::System => system_source(),
63 }
64}
65
66fn duration_of(action: &PrintAction) -> Option<i64> {
68 match action {
69 PrintAction::SetFeedrateFactor { duration_s, .. }
70 | PrintAction::SetFlowrateFactor { duration_s, .. }
71 | PrintAction::SetToolTargetC { duration_s, .. }
72 | PrintAction::SetBedTargetC { duration_s, .. }
73 | PrintAction::SetFanPercent { duration_s, .. } => *duration_s,
74 PrintAction::Pause { .. }
75 | PrintAction::Resume { .. }
76 | PrintAction::Cancel { .. }
77 | PrintAction::StartPrint { .. }
78 | PrintAction::AcknowledgeFailure { .. }
79 | PrintAction::ClosePrint { .. } => None,
80 }
81}
82
83#[must_use]
89pub fn reported_value(snapshot: &PrinterSnapshot, adjustable: Adjustable) -> Option<f64> {
90 let reported = match adjustable {
91 Adjustable::Feedrate => snapshot.feedrate_factor,
92 Adjustable::Flowrate => snapshot.flowrate_factor,
93 Adjustable::Fan => snapshot.fan_percent,
94 Adjustable::BedTarget => snapshot.bed.as_ref().and_then(|heater| heater.target_c),
95 Adjustable::ToolTarget { tool } => usize::try_from(tool)
96 .ok()
97 .and_then(|index| snapshot.tools.get(index))
98 .and_then(|heater| heater.target_c),
99 };
100 reported.map(|value| value.value())
101}
102
103impl Supervisor {
104 pub async fn request_action(
121 &self,
122 print_id: PrintId,
123 action: PrintAction,
124 ) -> Result<ActionOutcome, CoreError> {
125 if let PrintAction::StartPrint { file_name, .. } = &action {
128 self.await_analysis(file_name, action.actor()).await?;
130 }
131 let (_starting, print_id) = match &action {
137 PrintAction::StartPrint { file_name, .. } => {
138 let resolving = self.resolving().await;
139 (
140 Some(resolving),
141 self.print_to_start(print_id, file_name).await?,
142 )
143 }
144 PrintAction::ClosePrint { .. } => (Some(self.resolving().await), print_id),
145 _ => (None, print_id),
146 };
147 let requested_at = self.clock().now();
148 let actor = action.actor().clone();
149 let print = self.stores().prints.print(print_id).await?;
150 let bounds = self.bounds_for(print.as_ref(), print_id).await?;
151 let snapshot = self.read_snapshot().await.ok();
152 let since_last_agent_action = if actor.class() == ActorClass::Agent {
153 self.since_last_agent_action(print_id).await?
154 } else {
155 None
156 };
157 let mut decision = decide(&DecisionInput {
158 action: &action,
159 actor: &actor,
160 requested_at,
161 print: print.as_ref(),
162 printer_state: snapshot.as_ref().map(|taken| &taken.connection),
163 bounds: &bounds.effective,
164 envelope: &self.config().envelope,
165 since_last_agent_action,
166 });
167 let preflight = self
168 .check_accepted(&action, print.as_ref(), &mut decision)
169 .await?;
170 let closing_state = self
171 .check_accepted_close(&action, print.as_ref(), &mut decision)
172 .await?;
173 let request = ActionRequest {
174 action: action.clone(),
175 actor: actor.clone(),
176 requested_at,
177 };
178 let issued = self.issue_action(request, decision, Some(print_id)).await?;
179 let source = source_of(&actor);
180 self.write_decision_down(print_id, &source, &action, &issued, preflight.as_ref())
181 .await?;
182 if !issued.succeeded() {
183 return Ok(ActionOutcome {
184 record: issued.record,
185 executed: issued.executed,
186 intervention: None,
187 });
188 }
189 if actor.class() == ActorClass::Agent && changes_the_machine(action.kind()) {
191 self.note_agent_action(print_id, self.clock().elapsed());
192 }
193 self.follow_the_detectors_pause(print_id, &action, snapshot.as_ref());
194 if let PrintAction::StartPrint {
195 manifest,
196 file_name,
197 ..
198 } = &action
199 {
200 self.attach_manifest(print_id, manifest.clone()).await?;
201 self.follow_the_start(print_id, file_name, &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 self.append_action_event(
208 print_id,
209 source,
210 EventBody::of(&ActionExecutedPayload {
211 action_id: issued.record.id,
212 intervention_id: intervention.as_ref().map(|opened| opened.id),
213 })?,
214 )
215 .await?;
216 self.follow_the_close(print_id, &action, closing_state.as_ref())
217 .await?;
218 Ok(ActionOutcome {
219 record: issued.record,
220 executed: issued.executed,
221 intervention,
222 })
223 }
224
225 async fn write_decision_down(
229 &self,
230 print_id: PrintId,
231 source: &EventSource,
232 action: &PrintAction,
233 issued: &Issued,
234 preflight: Option<&Preflight>,
235 ) -> Result<(), CoreError> {
236 self.append_action_event(
237 print_id,
238 source.clone(),
239 EventBody::of(&ActionRequestedPayload {
240 action_id: issued.record.id,
241 action: action.clone(),
242 actor: action.actor().clone(),
243 })?,
244 )
245 .await?;
246 if let Some(checked) = preflight {
248 self.append_action_event(
249 print_id,
250 source.clone(),
251 EventBody::of(&PreflightCheckedPayload {
252 preflight: checked.clone(),
253 action_id: Some(issued.record.id),
254 })?,
255 )
256 .await?;
257 }
258 if let PolicyDecision::Rejected(_) = &issued.record.decision {
259 self.append_action_event(
260 print_id,
261 source.clone(),
262 EventBody::of(&ActionRejectedPayload {
263 action_id: issued.record.id,
264 decision: issued.record.decision.clone(),
265 })?,
266 )
267 .await?;
268 }
269 Ok(())
270 }
271
272 async fn check_accepted(
281 &self,
282 action: &PrintAction,
283 print: Option<&PrintRecord>,
284 decision: &mut PolicyDecision,
285 ) -> Result<Option<Preflight>, CoreError> {
286 if *decision != PolicyDecision::Accepted {
287 return Ok(None);
288 }
289 match action {
290 PrintAction::StartPrint {
291 file_name,
292 manifest,
293 override_filament_check,
294 override_material_check,
295 override_sheet_check,
296 actor,
297 ..
298 } => {
299 let asked = Overrides {
300 filament: (*override_filament_check).into(),
301 material: (*override_material_check).into(),
302 sheet: (*override_sheet_check).into(),
303 };
304 let (checked, refusal) = self
305 .check_start(file_name, manifest.sheet.as_deref(), actor, asked)
306 .await?;
307 if let Some(reason) = refusal {
308 *decision = PolicyDecision::Rejected(reason);
309 }
310 Ok(Some(checked))
311 }
312 PrintAction::Resume { .. } => {
313 if let Some(print) = print
314 && let Some(recovery_event_id) = self.recovery_while_open(print).await?
315 {
316 *decision = PolicyDecision::Rejected(RejectionReason::PrintNotResumable {
317 recovery_event_id,
318 });
319 }
320 Ok(None)
321 }
322 PrintAction::Cancel { .. } => {
323 if let Some(print) = print
325 && let Ok(job) = self.read_job().await
326 {
327 self.record_position_from(print, &job, self.clock().now())
328 .await?;
329 }
330 Ok(None)
331 }
332 _ => Ok(None),
333 }
334 }
335
336 async fn follow_the_start(
341 &self,
342 print_id: PrintId,
343 file_name: &FileName,
344 issued: &Issued,
345 preflight: Option<Preflight>,
346 ) -> Result<(), CoreError> {
347 self.note_seen_running(print_id);
348 self.trust_z();
351 if self.print_started_of(print_id).await?.is_none() {
352 self.record_print_started(
353 print_id,
354 Some(file_name.as_str().to_owned()),
355 Some(issued.record.id),
356 preflight,
357 )
358 .await?;
359 }
360 Ok(())
361 }
362
363 async fn print_to_start(
374 &self,
375 asked: PrintId,
376 file_name: &FileName,
377 ) -> Result<PrintId, CoreError> {
378 if let Some(observed) = self.observe_job().await {
379 self.settle_open_prints(&observed).await?;
380 }
381 if !self.stores().prints.open_prints().await?.is_empty() {
382 return Ok(asked);
383 }
384 let opened = self
385 .stores()
386 .prints
387 .open_print(None, Some(file_name.as_str().to_owned()))
388 .await?;
389 Ok(opened.id)
390 }
391
392 fn follow_the_detectors_pause(
399 &self,
400 print_id: PrintId,
401 action: &PrintAction,
402 snapshot: Option<&PrinterSnapshot>,
403 ) {
404 if !self.detector_paused(print_id) {
405 return;
406 }
407 let paused = snapshot.is_some_and(|taken| taken.connection == PrinterState::Paused);
408 match (action.actor().class(), action) {
409 (ActorClass::Agent, _) if adjustment(action).is_some() && paused => {
410 self.note_adjustment_while_paused(print_id, action.reason());
411 }
412 (
413 ActorClass::Agent,
414 PrintAction::AcknowledgeFailure {
415 disposition: AcknowledgementDisposition::Stop,
416 ..
417 },
418 )
419 | (_, PrintAction::Resume { .. } | PrintAction::Cancel { .. }) => {
420 self.forget_detector_pause(print_id);
421 }
422 _ => {}
423 }
424 }
425
426 async fn append_action_event(
428 &self,
429 print_id: PrintId,
430 source: EventSource,
431 body: EventBody,
432 ) -> Result<(), CoreError> {
433 self.stores()
434 .events
435 .append_event(EventDraft {
436 print_id: Some(print_id),
437 source,
438 received_at: self.clock().now(),
439 body,
440 raw: None,
441 })
442 .await?;
443 Ok(())
444 }
445
446 pub(crate) async fn bounds_for(
448 &self,
449 print: Option<&PrintRecord>,
450 print_id: PrintId,
451 ) -> Result<Bounds, CoreError> {
452 let manifest = if print.is_some() {
453 self.stores().prints.manifest(print_id).await?
454 } else {
455 None
456 };
457 Ok(effective_bounds(&self.config().envelope, manifest.as_ref()))
458 }
459
460 async fn attach_manifest(
463 &self,
464 print_id: PrintId,
465 manifest: crate::records::JobManifest,
466 ) -> Result<(), CoreError> {
467 let narrowed = effective_bounds(&self.config().envelope, Some(&manifest));
468 self.stores()
469 .prints
470 .put_manifest(print_id, manifest)
471 .await?;
472 for narrowing in narrowed.narrowings {
473 self.stores()
474 .prints
475 .record_narrowing(print_id, narrowing)
476 .await?;
477 }
478 Ok(())
479 }
480
481 async fn open_bounded_intervention(
488 &self,
489 print_id: PrintId,
490 action: &PrintAction,
491 issued: &Issued,
492 snapshot: Option<&PrinterSnapshot>,
493 applied_at: Timestamp,
494 ) -> Result<Option<Intervention>, CoreError> {
495 let (Some((adjustable, applied_value)), Some(duration_s)) =
496 (adjustment(action), duration_of(action))
497 else {
498 return Ok(None);
499 };
500 let mut superseded = self.stores().actions.active_interventions(print_id).await?;
501 superseded.retain(|held| held.adjustable == adjustable);
502 superseded.sort_by_key(|held| held.applied_at);
503 let prior_value = superseded.first().map_or_else(
504 || snapshot.and_then(|taken| reported_value(taken, adjustable)),
505 |earliest| earliest.prior_value,
506 );
507 let expires_at =
508 plus_seconds(applied_at, duration_s).map_err(|error| CoreError::Unrepresentable {
509 detail: error.to_string(),
510 })?;
511 let opened = self
512 .stores()
513 .actions
514 .open_intervention(
515 issued.record.id,
516 adjustable,
517 prior_value,
518 applied_value,
519 applied_at,
520 expires_at,
521 )
522 .await?;
523 self.count_down(&opened);
524 for earlier in superseded {
525 self.stores()
526 .actions
527 .settle_intervention(
528 earlier.id,
529 InterventionOutcome::Superseded { by: opened.id },
530 )
531 .await?;
532 self.stop_counting_down(earlier.id);
533 }
534 Ok(Some(opened))
535 }
536}