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 { .. }
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
178 .issue_decided_action(request, decision, Some(print_id))
179 .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().elapsed());
193 }
194 self.follow_the_detectors_pause(print_id, &action, snapshot.as_ref());
195 if let PrintAction::StartPrint {
196 manifest,
197 file_name,
198 ..
199 } = &action
200 {
201 self.attach_manifest(print_id, manifest.clone()).await?;
202 self.follow_the_start(print_id, file_name, &issued, preflight)
203 .await?;
204 }
205 let intervention = self
206 .open_bounded_intervention(print_id, &action, &issued, snapshot.as_ref(), requested_at)
207 .await?;
208 self.append_action_event(
209 print_id,
210 source,
211 EventBody::of(&ActionExecutedPayload {
212 action_id: issued.record.id,
213 intervention_id: intervention.as_ref().map(|opened| opened.id),
214 })?,
215 )
216 .await?;
217 self.follow_the_close(print_id, &action, closing_state.as_ref())
218 .await?;
219 Ok(ActionOutcome {
220 record: issued.record,
221 executed: issued.executed,
222 intervention,
223 })
224 }
225
226 async fn write_decision_down(
230 &self,
231 print_id: PrintId,
232 source: &EventSource,
233 action: &PrintAction,
234 issued: &Issued,
235 preflight: Option<&Preflight>,
236 ) -> Result<(), CoreError> {
237 self.append_action_event(
238 print_id,
239 source.clone(),
240 EventBody::of(&ActionRequestedPayload {
241 action_id: issued.record.id,
242 action: action.clone(),
243 actor: action.actor().clone(),
244 })?,
245 )
246 .await?;
247 if let Some(checked) = preflight {
249 self.append_action_event(
250 print_id,
251 source.clone(),
252 EventBody::of(&PreflightCheckedPayload {
253 preflight: checked.clone(),
254 action_id: Some(issued.record.id),
255 })?,
256 )
257 .await?;
258 }
259 if let PolicyDecision::Rejected(_) = &issued.record.decision {
260 self.append_action_event(
261 print_id,
262 source.clone(),
263 EventBody::of(&ActionRejectedPayload {
264 action_id: issued.record.id,
265 decision: issued.record.decision.clone(),
266 })?,
267 )
268 .await?;
269 }
270 Ok(())
271 }
272
273 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 override_filament_check,
293 actor,
294 ..
295 } => {
296 let (checked, refusal) = self
297 .check_start(file_name, actor, (*override_filament_check).into())
298 .await?;
299 if let Some(reason) = refusal {
300 *decision = PolicyDecision::Rejected(reason);
301 }
302 Ok(Some(checked))
303 }
304 PrintAction::Cancel { .. } => {
305 if let Some(print) = print
307 && let Ok(job) = self.read_job().await
308 {
309 self.record_position_from(print, &job, self.clock().now())
310 .await?;
311 }
312 Ok(None)
313 }
314 _ => Ok(None),
315 }
316 }
317
318 async fn follow_the_start(
323 &self,
324 print_id: PrintId,
325 file_name: &FileName,
326 issued: &Issued,
327 preflight: Option<Preflight>,
328 ) -> Result<(), CoreError> {
329 self.note_seen_running(print_id);
330 if self.print_started_of(print_id).await?.is_none() {
331 self.record_print_started(
332 print_id,
333 Some(file_name.as_str().to_owned()),
334 Some(issued.record.id),
335 preflight,
336 )
337 .await?;
338 }
339 Ok(())
340 }
341
342 async fn print_to_start(
353 &self,
354 asked: PrintId,
355 file_name: &FileName,
356 ) -> Result<PrintId, CoreError> {
357 if let Some(observed) = self.observe_job().await {
358 self.settle_open_prints(&observed).await?;
359 }
360 if !self.stores().prints.open_prints().await?.is_empty() {
361 return Ok(asked);
362 }
363 let opened = self
364 .stores()
365 .prints
366 .open_print(None, Some(file_name.as_str().to_owned()))
367 .await?;
368 Ok(opened.id)
369 }
370
371 fn follow_the_detectors_pause(
378 &self,
379 print_id: PrintId,
380 action: &PrintAction,
381 snapshot: Option<&PrinterSnapshot>,
382 ) {
383 if !self.detector_paused(print_id) {
384 return;
385 }
386 let paused = snapshot.is_some_and(|taken| taken.connection == PrinterState::Paused);
387 match (action.actor().class(), action) {
388 (ActorClass::Agent, _) if adjustment(action).is_some() && paused => {
389 self.note_adjustment_while_paused(print_id, action.reason());
390 }
391 (
392 ActorClass::Agent,
393 PrintAction::AcknowledgeFailure {
394 disposition: AcknowledgementDisposition::Stop,
395 ..
396 },
397 )
398 | (_, PrintAction::Resume { .. } | PrintAction::Cancel { .. }) => {
399 self.forget_detector_pause(print_id);
400 }
401 _ => {}
402 }
403 }
404
405 async fn append_action_event(
407 &self,
408 print_id: PrintId,
409 source: EventSource,
410 body: EventBody,
411 ) -> Result<(), CoreError> {
412 self.stores()
413 .events
414 .append_event(EventDraft {
415 print_id: Some(print_id),
416 source,
417 received_at: self.clock().now(),
418 body,
419 raw: None,
420 })
421 .await?;
422 Ok(())
423 }
424
425 pub(crate) async fn bounds_for(
427 &self,
428 print: Option<&PrintRecord>,
429 print_id: PrintId,
430 ) -> Result<Bounds, CoreError> {
431 let manifest = if print.is_some() {
432 self.stores().prints.manifest(print_id).await?
433 } else {
434 None
435 };
436 Ok(effective_bounds(&self.config().envelope, manifest.as_ref()))
437 }
438
439 async fn attach_manifest(
442 &self,
443 print_id: PrintId,
444 manifest: crate::records::JobManifest,
445 ) -> Result<(), CoreError> {
446 let narrowed = effective_bounds(&self.config().envelope, Some(&manifest));
447 self.stores()
448 .prints
449 .put_manifest(print_id, manifest)
450 .await?;
451 for narrowing in narrowed.narrowings {
452 self.stores()
453 .prints
454 .record_narrowing(print_id, narrowing)
455 .await?;
456 }
457 Ok(())
458 }
459
460 async fn open_bounded_intervention(
467 &self,
468 print_id: PrintId,
469 action: &PrintAction,
470 issued: &Issued,
471 snapshot: Option<&PrinterSnapshot>,
472 applied_at: Timestamp,
473 ) -> Result<Option<Intervention>, CoreError> {
474 let (Some((adjustable, applied_value)), Some(duration_s)) =
475 (adjustment(action), duration_of(action))
476 else {
477 return Ok(None);
478 };
479 let mut superseded = self.stores().actions.active_interventions(print_id).await?;
480 superseded.retain(|held| held.adjustable == adjustable);
481 superseded.sort_by_key(|held| held.applied_at);
482 let prior_value = superseded.first().map_or_else(
483 || snapshot.and_then(|taken| reported_value(taken, adjustable)),
484 |earliest| earliest.prior_value,
485 );
486 let expires_at =
487 plus_seconds(applied_at, duration_s).map_err(|error| CoreError::Unrepresentable {
488 detail: error.to_string(),
489 })?;
490 let opened = self
491 .stores()
492 .actions
493 .open_intervention(
494 issued.record.id,
495 adjustable,
496 prior_value,
497 applied_value,
498 applied_at,
499 expires_at,
500 )
501 .await?;
502 self.count_down(&opened);
503 for earlier in superseded {
504 self.stores()
505 .actions
506 .settle_intervention(
507 earlier.id,
508 InterventionOutcome::Superseded { by: opened.id },
509 )
510 .await?;
511 self.stop_counting_down(earlier.id);
512 }
513 Ok(Some(opened))
514 }
515}