1use crate::records::{
19 AcknowledgementDisposition, ActionRecord, ActionRequest, Actor, ActorClass, Intervention,
20 InterventionOutcome, PolicyDecision, Preflight, PrintAction, PrintRecord, RejectionReason,
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 { .. }
78 | PrintAction::ClosePrint { .. } => None,
79 }
80}
81
82#[must_use]
88pub fn reported_value(snapshot: &PrinterSnapshot, adjustable: Adjustable) -> Option<f64> {
89 let reported = match adjustable {
90 Adjustable::Feedrate => snapshot.feedrate_factor,
91 Adjustable::Flowrate => snapshot.flowrate_factor,
92 Adjustable::Fan => snapshot.fan_percent,
93 Adjustable::BedTarget => snapshot.bed.as_ref().and_then(|heater| heater.target_c),
94 Adjustable::ToolTarget { tool } => usize::try_from(tool)
95 .ok()
96 .and_then(|index| snapshot.tools.get(index))
97 .and_then(|heater| heater.target_c),
98 };
99 reported.map(|value| value.value())
100}
101
102impl Supervisor {
103 pub async fn request_action(
120 &self,
121 print_id: PrintId,
122 action: PrintAction,
123 ) -> Result<ActionOutcome, CoreError> {
124 if let PrintAction::StartPrint { file_name, .. } = &action {
127 self.await_analysis(file_name, action.actor()).await?;
129 }
130 let (_starting, print_id) = match &action {
136 PrintAction::StartPrint { file_name, .. } => {
137 let resolving = self.resolving().await;
138 (
139 Some(resolving),
140 self.print_to_start(print_id, file_name).await?,
141 )
142 }
143 PrintAction::ClosePrint { .. } => (Some(self.resolving().await), print_id),
144 _ => (None, print_id),
145 };
146 let requested_at = self.clock().now();
147 let actor = action.actor().clone();
148 let print = self.stores().prints.print(print_id).await?;
149 let bounds = self.bounds_for(print.as_ref(), print_id).await?;
150 let snapshot = self.read_snapshot().await.ok();
151 let since_last_agent_action = if actor.class() == ActorClass::Agent {
152 self.since_last_agent_action(print_id).await?
153 } else {
154 None
155 };
156 let mut decision = decide(&DecisionInput {
157 action: &action,
158 actor: &actor,
159 requested_at,
160 print: print.as_ref(),
161 printer_state: snapshot.as_ref().map(|taken| &taken.connection),
162 bounds: &bounds.effective,
163 envelope: &self.config().envelope,
164 since_last_agent_action,
165 });
166 let preflight = self
167 .check_accepted(&action, print.as_ref(), &mut decision)
168 .await?;
169 let closing_state = self
170 .check_accepted_close(&action, print.as_ref(), &mut decision)
171 .await?;
172 let request = ActionRequest {
173 action: action.clone(),
174 actor: actor.clone(),
175 requested_at,
176 };
177 let issued = self.issue_action(request, decision, Some(print_id)).await?;
178 let source = source_of(&actor);
179 self.write_decision_down(print_id, &source, &action, &issued, preflight.as_ref())
180 .await?;
181 if !issued.succeeded() {
182 return Ok(ActionOutcome {
183 record: issued.record,
184 executed: issued.executed,
185 intervention: None,
186 });
187 }
188 if actor.class() == ActorClass::Agent && changes_the_machine(action.kind()) {
190 self.note_agent_action(print_id, self.clock().elapsed());
191 }
192 self.follow_the_detectors_pause(print_id, &action, snapshot.as_ref());
193 if let PrintAction::StartPrint {
194 manifest,
195 file_name,
196 ..
197 } = &action
198 {
199 self.attach_manifest(print_id, manifest.clone()).await?;
200 self.follow_the_start(print_id, file_name, &issued, preflight)
201 .await?;
202 }
203 let intervention = self
204 .open_bounded_intervention(print_id, &action, &issued, snapshot.as_ref(), requested_at)
205 .await?;
206 self.append_action_event(
207 print_id,
208 source,
209 EventBody::of(&ActionExecutedPayload {
210 action_id: issued.record.id,
211 intervention_id: intervention.as_ref().map(|opened| opened.id),
212 })?,
213 )
214 .await?;
215 self.follow_the_close(print_id, &action, closing_state.as_ref())
216 .await?;
217 Ok(ActionOutcome {
218 record: issued.record,
219 executed: issued.executed,
220 intervention,
221 })
222 }
223
224 async fn write_decision_down(
228 &self,
229 print_id: PrintId,
230 source: &EventSource,
231 action: &PrintAction,
232 issued: &Issued,
233 preflight: Option<&Preflight>,
234 ) -> Result<(), CoreError> {
235 self.append_action_event(
236 print_id,
237 source.clone(),
238 EventBody::of(&ActionRequestedPayload {
239 action_id: issued.record.id,
240 action: action.clone(),
241 actor: action.actor().clone(),
242 })?,
243 )
244 .await?;
245 if let Some(checked) = preflight {
247 self.append_action_event(
248 print_id,
249 source.clone(),
250 EventBody::of(&PreflightCheckedPayload {
251 preflight: checked.clone(),
252 action_id: Some(issued.record.id),
253 })?,
254 )
255 .await?;
256 }
257 if let PolicyDecision::Rejected(_) = &issued.record.decision {
258 self.append_action_event(
259 print_id,
260 source.clone(),
261 EventBody::of(&ActionRejectedPayload {
262 action_id: issued.record.id,
263 decision: issued.record.decision.clone(),
264 })?,
265 )
266 .await?;
267 }
268 Ok(())
269 }
270
271 async fn check_accepted(
279 &self,
280 action: &PrintAction,
281 print: Option<&PrintRecord>,
282 decision: &mut PolicyDecision,
283 ) -> Result<Option<Preflight>, CoreError> {
284 if *decision != PolicyDecision::Accepted {
285 return Ok(None);
286 }
287 match action {
288 PrintAction::StartPrint {
289 file_name,
290 override_filament_check,
291 actor,
292 ..
293 } => {
294 let (checked, refusal) = self
295 .check_start(file_name, actor, (*override_filament_check).into())
296 .await?;
297 if let Some(reason) = refusal {
298 *decision = PolicyDecision::Rejected(reason);
299 }
300 Ok(Some(checked))
301 }
302 PrintAction::Resume { .. } => {
303 if let Some(print) = print
304 && let Some(recovery_event_id) = self.recovery_while_open(print).await?
305 {
306 *decision = PolicyDecision::Rejected(RejectionReason::PrintNotResumable {
307 recovery_event_id,
308 });
309 }
310 Ok(None)
311 }
312 PrintAction::Cancel { .. } => {
313 if let Some(print) = print
315 && let Ok(job) = self.read_job().await
316 {
317 self.record_position_from(print, &job, self.clock().now())
318 .await?;
319 }
320 Ok(None)
321 }
322 _ => Ok(None),
323 }
324 }
325
326 async fn follow_the_start(
331 &self,
332 print_id: PrintId,
333 file_name: &FileName,
334 issued: &Issued,
335 preflight: Option<Preflight>,
336 ) -> Result<(), CoreError> {
337 self.note_seen_running(print_id);
338 self.trust_z();
341 if self.print_started_of(print_id).await?.is_none() {
342 self.record_print_started(
343 print_id,
344 Some(file_name.as_str().to_owned()),
345 Some(issued.record.id),
346 preflight,
347 )
348 .await?;
349 }
350 Ok(())
351 }
352
353 async fn print_to_start(
364 &self,
365 asked: PrintId,
366 file_name: &FileName,
367 ) -> Result<PrintId, CoreError> {
368 if let Some(observed) = self.observe_job().await {
369 self.settle_open_prints(&observed).await?;
370 }
371 if !self.stores().prints.open_prints().await?.is_empty() {
372 return Ok(asked);
373 }
374 let opened = self
375 .stores()
376 .prints
377 .open_print(None, Some(file_name.as_str().to_owned()))
378 .await?;
379 Ok(opened.id)
380 }
381
382 fn follow_the_detectors_pause(
389 &self,
390 print_id: PrintId,
391 action: &PrintAction,
392 snapshot: Option<&PrinterSnapshot>,
393 ) {
394 if !self.detector_paused(print_id) {
395 return;
396 }
397 let paused = snapshot.is_some_and(|taken| taken.connection == PrinterState::Paused);
398 match (action.actor().class(), action) {
399 (ActorClass::Agent, _) if adjustment(action).is_some() && paused => {
400 self.note_adjustment_while_paused(print_id, action.reason());
401 }
402 (
403 ActorClass::Agent,
404 PrintAction::AcknowledgeFailure {
405 disposition: AcknowledgementDisposition::Stop,
406 ..
407 },
408 )
409 | (_, PrintAction::Resume { .. } | PrintAction::Cancel { .. }) => {
410 self.forget_detector_pause(print_id);
411 }
412 _ => {}
413 }
414 }
415
416 async fn append_action_event(
418 &self,
419 print_id: PrintId,
420 source: EventSource,
421 body: EventBody,
422 ) -> Result<(), CoreError> {
423 self.stores()
424 .events
425 .append_event(EventDraft {
426 print_id: Some(print_id),
427 source,
428 received_at: self.clock().now(),
429 body,
430 raw: None,
431 })
432 .await?;
433 Ok(())
434 }
435
436 pub(crate) async fn bounds_for(
438 &self,
439 print: Option<&PrintRecord>,
440 print_id: PrintId,
441 ) -> Result<Bounds, CoreError> {
442 let manifest = if print.is_some() {
443 self.stores().prints.manifest(print_id).await?
444 } else {
445 None
446 };
447 Ok(effective_bounds(&self.config().envelope, manifest.as_ref()))
448 }
449
450 async fn attach_manifest(
453 &self,
454 print_id: PrintId,
455 manifest: crate::records::JobManifest,
456 ) -> Result<(), CoreError> {
457 let narrowed = effective_bounds(&self.config().envelope, Some(&manifest));
458 self.stores()
459 .prints
460 .put_manifest(print_id, manifest)
461 .await?;
462 for narrowing in narrowed.narrowings {
463 self.stores()
464 .prints
465 .record_narrowing(print_id, narrowing)
466 .await?;
467 }
468 Ok(())
469 }
470
471 async fn open_bounded_intervention(
478 &self,
479 print_id: PrintId,
480 action: &PrintAction,
481 issued: &Issued,
482 snapshot: Option<&PrinterSnapshot>,
483 applied_at: Timestamp,
484 ) -> Result<Option<Intervention>, CoreError> {
485 let (Some((adjustable, applied_value)), Some(duration_s)) =
486 (adjustment(action), duration_of(action))
487 else {
488 return Ok(None);
489 };
490 let mut superseded = self.stores().actions.active_interventions(print_id).await?;
491 superseded.retain(|held| held.adjustable == adjustable);
492 superseded.sort_by_key(|held| held.applied_at);
493 let prior_value = superseded.first().map_or_else(
494 || snapshot.and_then(|taken| reported_value(taken, adjustable)),
495 |earliest| earliest.prior_value,
496 );
497 let expires_at =
498 plus_seconds(applied_at, duration_s).map_err(|error| CoreError::Unrepresentable {
499 detail: error.to_string(),
500 })?;
501 let opened = self
502 .stores()
503 .actions
504 .open_intervention(
505 issued.record.id,
506 adjustable,
507 prior_value,
508 applied_value,
509 applied_at,
510 expires_at,
511 )
512 .await?;
513 self.count_down(&opened);
514 for earlier in superseded {
515 self.stores()
516 .actions
517 .settle_intervention(
518 earlier.id,
519 InterventionOutcome::Superseded { by: opened.id },
520 )
521 .await?;
522 self.stop_counting_down(earlier.id);
523 }
524 Ok(Some(opened))
525 }
526}