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 since_last_agent_action = if actor.class() == ActorClass::Agent {
148 self.since_last_agent_action(print_id).await?
149 } else {
150 None
151 };
152 let mut decision = decide(&DecisionInput {
153 action: &action,
154 actor: &actor,
155 requested_at,
156 print: print.as_ref(),
157 printer_state: snapshot.as_ref().map(|taken| &taken.connection),
158 bounds: &bounds.effective,
159 envelope: &self.config().envelope,
160 since_last_agent_action,
161 });
162 let preflight = self
163 .check_accepted(&action, print.as_ref(), &mut decision)
164 .await?;
165 let request = ActionRequest {
166 action: action.clone(),
167 actor: actor.clone(),
168 requested_at,
169 };
170 let issued = self.issue_decided_action(request, decision).await?;
171 let source = source_of(&actor);
172 self.write_decision_down(print_id, &source, &action, &issued, preflight.as_ref())
173 .await?;
174 if !issued.succeeded() {
175 return Ok(ActionOutcome {
176 record: issued.record,
177 executed: issued.executed,
178 intervention: None,
179 });
180 }
181 if actor.class() == ActorClass::Agent && changes_the_machine(action.kind()) {
183 self.note_agent_action(print_id, self.clock().elapsed());
184 }
185 self.follow_the_detectors_pause(print_id, &action, snapshot.as_ref());
186 if let PrintAction::StartPrint {
187 manifest,
188 file_name,
189 ..
190 } = &action
191 {
192 self.attach_manifest(print_id, manifest.clone()).await?;
193 self.follow_the_start(print_id, file_name, &issued, preflight)
194 .await?;
195 }
196 let intervention = self
197 .open_bounded_intervention(print_id, &action, &issued, snapshot.as_ref(), requested_at)
198 .await?;
199 self.append_action_event(
200 print_id,
201 source,
202 EventBody::of(&ActionExecutedPayload {
203 action_id: issued.record.id,
204 intervention_id: intervention.as_ref().map(|opened| opened.id),
205 })?,
206 )
207 .await?;
208 Ok(ActionOutcome {
209 record: issued.record,
210 executed: issued.executed,
211 intervention,
212 })
213 }
214
215 async fn write_decision_down(
219 &self,
220 print_id: PrintId,
221 source: &EventSource,
222 action: &PrintAction,
223 issued: &Issued,
224 preflight: Option<&Preflight>,
225 ) -> Result<(), CoreError> {
226 self.append_action_event(
227 print_id,
228 source.clone(),
229 EventBody::of(&ActionRequestedPayload {
230 action_id: issued.record.id,
231 action: action.clone(),
232 actor: action.actor().clone(),
233 })?,
234 )
235 .await?;
236 if let Some(checked) = preflight {
238 self.append_action_event(
239 print_id,
240 source.clone(),
241 EventBody::of(&PreflightCheckedPayload {
242 preflight: checked.clone(),
243 action_id: Some(issued.record.id),
244 })?,
245 )
246 .await?;
247 }
248 if let PolicyDecision::Rejected(_) = &issued.record.decision {
249 self.append_action_event(
250 print_id,
251 source.clone(),
252 EventBody::of(&ActionRejectedPayload {
253 action_id: issued.record.id,
254 decision: issued.record.decision.clone(),
255 })?,
256 )
257 .await?;
258 }
259 Ok(())
260 }
261
262 async fn check_accepted(
270 &self,
271 action: &PrintAction,
272 print: Option<&PrintRecord>,
273 decision: &mut PolicyDecision,
274 ) -> Result<Option<Preflight>, CoreError> {
275 if *decision != PolicyDecision::Accepted {
276 return Ok(None);
277 }
278 match action {
279 PrintAction::StartPrint {
280 file_name,
281 override_filament_check,
282 actor,
283 ..
284 } => {
285 let (checked, refusal) = self
286 .check_start(file_name, actor, (*override_filament_check).into())
287 .await?;
288 if let Some(reason) = refusal {
289 *decision = PolicyDecision::Rejected(reason);
290 }
291 Ok(Some(checked))
292 }
293 PrintAction::Cancel { .. } => {
294 if let Some(print) = print
296 && let Ok(job) = self.read_job().await
297 {
298 self.record_position_from(print, &job, self.clock().now())
299 .await?;
300 }
301 Ok(None)
302 }
303 _ => Ok(None),
304 }
305 }
306
307 async fn follow_the_start(
312 &self,
313 print_id: PrintId,
314 file_name: &FileName,
315 issued: &Issued,
316 preflight: Option<Preflight>,
317 ) -> Result<(), CoreError> {
318 self.note_seen_running(print_id);
319 if self.print_started_of(print_id).await?.is_none() {
320 self.record_print_started(
321 print_id,
322 Some(file_name.as_str().to_owned()),
323 Some(issued.record.id),
324 preflight,
325 )
326 .await?;
327 }
328 Ok(())
329 }
330
331 async fn print_to_start(
342 &self,
343 asked: PrintId,
344 file_name: &FileName,
345 ) -> Result<PrintId, CoreError> {
346 if let Some(observed) = self.observe_job().await {
347 self.settle_open_prints(&observed).await?;
348 }
349 if !self.stores().prints.open_prints().await?.is_empty() {
350 return Ok(asked);
351 }
352 let opened = self
353 .stores()
354 .prints
355 .open_print(None, Some(file_name.as_str().to_owned()))
356 .await?;
357 Ok(opened.id)
358 }
359
360 fn follow_the_detectors_pause(
367 &self,
368 print_id: PrintId,
369 action: &PrintAction,
370 snapshot: Option<&PrinterSnapshot>,
371 ) {
372 if !self.detector_paused(print_id) {
373 return;
374 }
375 let paused = snapshot.is_some_and(|taken| taken.connection == PrinterState::Paused);
376 match (action.actor().class(), action) {
377 (ActorClass::Agent, _) if adjustment(action).is_some() && paused => {
378 self.note_adjustment_while_paused(print_id, action.reason());
379 }
380 (
381 ActorClass::Agent,
382 PrintAction::AcknowledgeFailure {
383 disposition: AcknowledgementDisposition::Stop,
384 ..
385 },
386 )
387 | (_, PrintAction::Resume { .. } | PrintAction::Cancel { .. }) => {
388 self.forget_detector_pause(print_id);
389 }
390 _ => {}
391 }
392 }
393
394 async fn append_action_event(
396 &self,
397 print_id: PrintId,
398 source: EventSource,
399 body: EventBody,
400 ) -> Result<(), CoreError> {
401 self.stores()
402 .events
403 .append_event(EventDraft {
404 print_id: Some(print_id),
405 source,
406 received_at: self.clock().now(),
407 body,
408 raw: None,
409 })
410 .await?;
411 Ok(())
412 }
413
414 pub(crate) async fn bounds_for(
416 &self,
417 print: Option<&PrintRecord>,
418 print_id: PrintId,
419 ) -> Result<Bounds, CoreError> {
420 let manifest = if print.is_some() {
421 self.stores().prints.manifest(print_id).await?
422 } else {
423 None
424 };
425 Ok(effective_bounds(&self.config().envelope, manifest.as_ref()))
426 }
427
428 async fn attach_manifest(
431 &self,
432 print_id: PrintId,
433 manifest: crate::records::JobManifest,
434 ) -> Result<(), CoreError> {
435 let narrowed = effective_bounds(&self.config().envelope, Some(&manifest));
436 self.stores()
437 .prints
438 .put_manifest(print_id, manifest)
439 .await?;
440 for narrowing in narrowed.narrowings {
441 self.stores()
442 .prints
443 .record_narrowing(print_id, narrowing)
444 .await?;
445 }
446 Ok(())
447 }
448
449 async fn open_bounded_intervention(
456 &self,
457 print_id: PrintId,
458 action: &PrintAction,
459 issued: &Issued,
460 snapshot: Option<&PrinterSnapshot>,
461 applied_at: Timestamp,
462 ) -> Result<Option<Intervention>, CoreError> {
463 let (Some((adjustable, applied_value)), Some(duration_s)) =
464 (adjustment(action), duration_of(action))
465 else {
466 return Ok(None);
467 };
468 let mut superseded = self.stores().actions.active_interventions(print_id).await?;
469 superseded.retain(|held| held.adjustable == adjustable);
470 superseded.sort_by_key(|held| held.applied_at);
471 let prior_value = superseded.first().map_or_else(
472 || snapshot.and_then(|taken| reported_value(taken, adjustable)),
473 |earliest| earliest.prior_value,
474 );
475 let expires_at =
476 plus_seconds(applied_at, duration_s).map_err(|error| CoreError::Unrepresentable {
477 detail: error.to_string(),
478 })?;
479 let opened = self
480 .stores()
481 .actions
482 .open_intervention(
483 issued.record.id,
484 adjustable,
485 prior_value,
486 applied_value,
487 applied_at,
488 expires_at,
489 )
490 .await?;
491 self.count_down(&opened);
492 for earlier in superseded {
493 self.stores()
494 .actions
495 .settle_intervention(
496 earlier.id,
497 InterventionOutcome::Superseded { by: opened.id },
498 )
499 .await?;
500 self.stop_counting_down(earlier.id);
501 }
502 Ok(Some(opened))
503 }
504}