1use core::time::Duration;
40use std::collections::BTreeMap;
41use std::sync::Mutex;
42use std::sync::atomic::{AtomicBool, Ordering};
43
44use crate::records::{
45 Actor, Intervention, InterventionId, InterventionOutcome, MaterialObjection, PolicyDecision,
46 PrintAction, RejectionReason, SheetId, SheetObjection,
47};
48use crate::records::{CameraCheckId, CameraCheckObjection};
49use printobserver_printer_api::Adjustable;
50use printobserver_types::{PrintId, Timestamp};
51
52use crate::clock::ClockReading;
53use crate::decision::{DecisionInput, decide};
54use crate::error::CoreError;
55use crate::store::{EventDraft, SettleOutcome};
56use crate::supervisor::Supervisor;
57
58#[derive(Debug, Default)]
61pub(crate) struct Deadlines {
62 counting: Mutex<BTreeMap<InterventionId, (Intervention, Duration)>>,
64 adopted: AtomicBool,
67}
68
69impl Deadlines {
70 fn count(&self, intervention: &Intervention, reading: ClockReading) {
72 let due = reading.elapsed_at(intervention.expires_at);
73 self.counting()
74 .insert(intervention.id, (intervention.clone(), due));
75 }
76
77 fn adopt(&self, intervention: &Intervention, reading: ClockReading) {
79 let due = reading.elapsed_at(intervention.expires_at);
80 self.counting()
81 .entry(intervention.id)
82 .or_insert_with(|| (intervention.clone(), due));
83 }
84
85 fn forget(&self, intervention_id: InterventionId) {
87 self.counting().remove(&intervention_id);
88 }
89
90 fn due(&self, elapsed: Duration) -> Vec<Intervention> {
92 let mut due: Vec<(Duration, Intervention)> = self
93 .counting()
94 .values()
95 .filter(|(_, at)| *at <= elapsed)
96 .map(|(intervention, at)| (*at, intervention.clone()))
97 .collect();
98 due.sort_by_key(|(at, _)| *at);
99 due.into_iter()
100 .map(|(_, intervention)| intervention)
101 .collect()
102 }
103
104 fn counting(
106 &self,
107 ) -> std::sync::MutexGuard<'_, BTreeMap<InterventionId, (Intervention, Duration)>> {
108 self.counting
109 .lock()
110 .unwrap_or_else(std::sync::PoisonError::into_inner)
111 }
112}
113
114const RESTORE_REASON: &str = "the bounded intervention expired";
116
117#[must_use]
121pub fn restoring_action(adjustable: Adjustable, prior_value: f64) -> PrintAction {
122 match adjustable {
123 Adjustable::Feedrate => PrintAction::SetFeedrateFactor {
124 factor: prior_value,
125 duration_s: None,
126 reason: RESTORE_REASON.to_owned(),
127 actor: Actor::System,
128 },
129 Adjustable::Flowrate => PrintAction::SetFlowrateFactor {
130 factor: prior_value,
131 duration_s: None,
132 reason: RESTORE_REASON.to_owned(),
133 actor: Actor::System,
134 },
135 Adjustable::ToolTarget { tool } => PrintAction::SetToolTargetC {
136 tool,
137 target_c: prior_value,
138 duration_s: None,
139 reason: RESTORE_REASON.to_owned(),
140 actor: Actor::System,
141 },
142 Adjustable::BedTarget => PrintAction::SetBedTargetC {
143 target_c: prior_value,
144 duration_s: None,
145 reason: RESTORE_REASON.to_owned(),
146 actor: Actor::System,
147 },
148 Adjustable::Fan => PrintAction::SetFanPercent {
149 percent: prior_value,
150 duration_s: None,
151 reason: RESTORE_REASON.to_owned(),
152 actor: Actor::System,
153 },
154 }
155}
156
157fn material_detail(objection: &MaterialObjection) -> String {
160 match objection {
161 MaterialObjection::Mismatch(compared) => format!(
162 "the file was sliced for {}, and spool {} on tool {} is {}",
163 compared.sliced_for, compared.spool.name, compared.tool, compared.loaded
164 ),
165 MaterialObjection::Undeclared(uncompared) => format!(
166 "{} names no `filament_type`, so it cannot be compared with spool {} on tool {}, \
167 which is {}",
168 uncompared.file_name, uncompared.spool.name, uncompared.tool, uncompared.loaded
169 ),
170 MaterialObjection::Unread {
171 tool,
172 spool,
173 loaded,
174 file_name,
175 detail,
176 } => format!(
177 "the settings of {file_name} could not be read ({detail}), so it cannot be compared \
178 with spool {} on tool {tool}, which is {loaded}",
179 spool.name
180 ),
181 }
182}
183
184fn listed(sheets: &[SheetId]) -> String {
186 sheets
187 .iter()
188 .map(SheetId::as_str)
189 .collect::<Vec<_>>()
190 .join(", ")
191}
192
193fn camera_check_detail(camera_check: CameraCheckId, objection: &CameraCheckObjection) -> String {
195 match objection {
196 CameraCheckObjection::Unknown => format!(
197 "no camera check {camera_check} is recorded: run `check-camera` on the empty sheet \
198 and name the check it answers"
199 ),
200 CameraCheckObjection::NotAligned { verdict } => format!(
201 "camera check {camera_check} found the camera {}, and only an `aligned` check may \
202 be named: check the camera again once it is",
203 verdict.as_str()
204 ),
205 CameraCheckObjection::OtherSheet {
206 checked_on,
207 declared,
208 } => format!(
209 "camera check {camera_check} was made on {}, and the manifest declares {}: check \
210 the camera on the sheet the print goes down on",
211 checked_on.as_str(),
212 declared.as_str()
213 ),
214 }
215}
216
217fn sheet_detail(objection: &SheetObjection) -> String {
220 match objection {
221 SheetObjection::NotAllowed(compared) => format!(
222 "the sheet table allows {} on {} and not on {}",
223 compared.material,
224 listed(&compared.allowed),
225 compared.sheet
226 ),
227 SheetObjection::UnlistedMaterial { sheet, material } => format!(
228 "the sheet table has no entry for {material}, so {sheet} is not known to suit it"
229 ),
230 SheetObjection::UnknownSheet {
231 sheet,
232 material,
233 known,
234 } => format!(
235 "no entry of the sheet table lists {sheet}, so it is not known to suit {material}; \
236 the sheets it names are {}",
237 listed(known)
238 ),
239 }
240}
241
242const fn interval_left_s(interval_s: i64, since_last_s: i64) -> i64 {
246 let left = interval_s.saturating_sub(since_last_s);
247 if left < 1 { 1 } else { left }
248}
249
250fn meant_for(tool: i64, segment: Option<u32>) -> String {
253 match segment {
254 Some(segment) => format!(" for segment {segment} on tool {tool}"),
255 None => format!(" on tool {tool}"),
256 }
257}
258
259#[must_use]
261pub fn rejection_detail(reason: &RejectionReason) -> String {
262 match reason {
263 RejectionReason::OutOfBounds {
264 adjustable,
265 requested,
266 allowed,
267 } => format!(
268 "{requested} is outside the {} to {} allowed for {adjustable}",
269 allowed.min, allowed.max
270 ),
271 RejectionReason::ActorMayNotRequest {
272 actor_class,
273 action,
274 } => format!("{actor_class:?} may not request {action:?}"),
275 RejectionReason::NoActivePrint => "there is no active print to act on".to_owned(),
276 RejectionReason::InvalidFromState { state } => {
277 format!("this is not valid from {state:?}")
278 }
279 RejectionReason::MinIntervalNotElapsed {
280 interval_s,
281 since_last_s,
282 } => {
283 let left_s = interval_left_s(*interval_s, *since_last_s);
284 format!(
285 "the agent last acted {since_last_s}s ago and its minimum interval is \
286 {interval_s}s, so {left_s}s of it are left: send the same request again after \
287 a look that waits at least {left_s}s"
288 )
289 }
290 RejectionReason::UnsupportedAdjustable { adjustable } => {
291 format!("this printer has no {adjustable}")
292 }
293 RejectionReason::InsufficientFilament {
294 tool,
295 spool_name,
296 required_g,
297 buffer_g,
298 remaining_g,
299 segment,
300 ..
301 } => format!(
302 "spool {spool_name}{} holds {remaining_g}g, and the print needs {required_g}g and a \
303 {buffer_g}g buffer",
304 meant_for(*tool, *segment)
305 ),
306 RejectionReason::UnverifiedSpool {
307 tool,
308 spool_name,
309 segment,
310 ..
311 } => format!(
312 "spool {spool_name}{} is unverified",
313 meant_for(*tool, *segment)
314 ),
315 RejectionReason::PlannedChangeWaiting {
316 change_index,
317 layer,
318 z_mm,
319 color,
320 } => format!(
321 "the printer is waiting at planned change {change_index}, for {} to be loaded for \
322 layer {layer} (Z {z_mm} mm): a person finishes it on the printer, and nothing \
323 pauses, resumes or adjusts the print until it carries on",
324 color.as_deref().unwrap_or("the next filament")
325 ),
326 RejectionReason::AnalysisUnavailable {
327 file_name,
328 waited_s,
329 } => format!("{file_name} had no analysis after waiting {waited_s}s for one"),
330 RejectionReason::MaterialRefused { objection } => material_detail(objection),
331 RejectionReason::SheetRefused { objection } => sheet_detail(objection),
332 RejectionReason::SheetNotDeclared => "the manifest declares no `sheet`, and every start \
333 names the build sheet it goes down on; no override lets a start without one through"
334 .to_owned(),
335 RejectionReason::CameraCheckRefused {
336 camera_check,
337 objection,
338 } => camera_check_detail(*camera_check, objection),
339 RejectionReason::SpoolRefused { message, .. } => message.clone(),
340 RejectionReason::PrintAlreadyEnded => "this print's record has already ended".to_owned(),
341 RejectionReason::PrintStillActive { state } => {
342 format!("the printer shows this print's file still {state:?}")
343 }
344 RejectionReason::InterventionStillActive { intervention_id } => {
345 format!("intervention {intervention_id} has neither expired nor been restored")
346 }
347 RejectionReason::PrintNotResumable { recovery_event_id } => format!(
348 "recovery event {recovery_event_id} moved the printer while this print was paused, \
349 and resuming would print the rest of the layer at the wrong height"
350 ),
351 }
352}
353
354impl Supervisor {
355 pub async fn sweep_expired(&self) -> Result<(), CoreError> {
372 self.adopt_left_active().await?;
373 for intervention in self.deadlines().due(self.clock().elapsed()) {
374 let _ = self.expire_intervention(&intervention).await;
375 }
376 Ok(())
377 }
378
379 async fn adopt_left_active(&self) -> Result<(), CoreError> {
381 let deadlines = self.deadlines();
382 if deadlines.adopted.load(Ordering::Acquire) {
383 return Ok(());
384 }
385 for intervention in self
388 .stores()
389 .actions
390 .due_interventions(Timestamp::latest())
391 .await?
392 {
393 deadlines.adopt(&intervention, self.started());
394 }
395 deadlines.adopted.store(true, Ordering::Release);
396 Ok(())
397 }
398
399 pub(crate) fn count_down(&self, intervention: &Intervention) {
401 self.deadlines()
402 .count(intervention, ClockReading::of(self.clock().as_ref()));
403 }
404
405 pub(crate) fn stop_counting_down(&self, intervention_id: InterventionId) {
407 self.deadlines().forget(intervention_id);
408 }
409
410 pub(crate) async fn expire_all_active(&self, print_id: PrintId) -> Result<(), CoreError> {
420 for intervention in self.stores().actions.active_interventions(print_id).await? {
421 let _ = self.expire_intervention(&intervention).await;
422 }
423 Ok(())
424 }
425
426 pub async fn expire_intervention(
439 &self,
440 intervention: &Intervention,
441 ) -> Result<InterventionOutcome, CoreError> {
442 let outcome = self.expire_once(intervention).await?;
443 self.deadlines().forget(intervention.id);
444 Ok(outcome)
445 }
446
447 async fn expire_once(
449 &self,
450 intervention: &Intervention,
451 ) -> Result<InterventionOutcome, CoreError> {
452 if intervention.outcome != InterventionOutcome::StillActive {
453 return Ok(intervention.outcome.clone());
454 }
455 let _expiring = self.expiring().acquire(intervention.print_id).await;
460 let still_active = self
461 .stores()
462 .actions
463 .active_interventions(intervention.print_id)
464 .await?
465 .iter()
466 .any(|active| active.id == intervention.id);
467 if !still_active {
468 return self
471 .settle(intervention, InterventionOutcome::RestoreUnavailable)
472 .await;
473 }
474 let Some(prior_value) = intervention.prior_value else {
475 return self
476 .settle(intervention, InterventionOutcome::RestoreUnavailable)
477 .await;
478 };
479 let outcome = self.restore(intervention, prior_value).await?;
480 self.settle(intervention, outcome).await
481 }
482
483 async fn restore(
485 &self,
486 intervention: &Intervention,
487 prior_value: f64,
488 ) -> Result<InterventionOutcome, CoreError> {
489 let requested_at = self.clock().now();
490 let action = restoring_action(intervention.adjustable, prior_value);
491 let actor = action.actor().clone();
492 let print = self.stores().prints.print(intervention.print_id).await?;
493 let bounds = self
494 .bounds_for(print.as_ref(), intervention.print_id)
495 .await?;
496 let decision = decide(&DecisionInput {
497 action: &action,
498 actor: &actor,
499 requested_at,
500 print: print.as_ref(),
501 printer_state: None,
503 bounds: &bounds.effective,
504 envelope: &self.config().envelope,
505 since_last_agent_action: None,
506 });
507 let request = crate::records::ActionRequest {
508 action,
509 actor,
510 requested_at,
511 };
512 let issued = self.issue_action(request, decision, None).await?;
513 if let PolicyDecision::Rejected(reason) = &issued.record.decision {
514 return Ok(InterventionOutcome::RestoreFailed {
515 reason: rejection_detail(reason),
516 });
517 }
518 if let Some(error) = issued.printer_error() {
519 return Ok(InterventionOutcome::RestoreFailed {
520 reason: error.to_string(),
521 });
522 }
523 Ok(InterventionOutcome::Restored)
524 }
525
526 async fn settle(
528 &self,
529 intervention: &Intervention,
530 outcome: InterventionOutcome,
531 ) -> Result<InterventionOutcome, CoreError> {
532 let settled = self
533 .stores()
534 .actions
535 .settle_intervention(intervention.id, outcome)
536 .await?;
537 Ok(match settled {
538 SettleOutcome::Settled {
543 intervention: settled,
544 } => {
545 self.append_expiry_event(intervention, settled.outcome.clone())
546 .await?;
547 settled.outcome
548 }
549 SettleOutcome::AlreadySettled { outcome } => outcome,
550 })
551 }
552
553 async fn append_expiry_event(
555 &self,
556 intervention: &Intervention,
557 outcome: InterventionOutcome,
558 ) -> Result<(), CoreError> {
559 self.stores()
560 .events
561 .append_event(EventDraft {
562 print_id: Some(intervention.print_id),
563 source: crate::kinds::system_source(),
564 received_at: self.clock().now(),
565 body: printobserver_types::EventBody::of(
566 &crate::kinds::InterventionExpiredPayload {
567 intervention_id: intervention.id,
568 adjustable: intervention.adjustable,
569 outcome,
570 },
571 )?,
572 raw: None,
573 })
574 .await?;
575 Ok(())
576 }
577}