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 printobserver_printer_api::Adjustable;
49use printobserver_types::{PrintId, Timestamp};
50
51use crate::clock::ClockReading;
52use crate::decision::{DecisionInput, decide};
53use crate::error::CoreError;
54use crate::store::{EventDraft, SettleOutcome};
55use crate::supervisor::Supervisor;
56
57#[derive(Debug, Default)]
60pub(crate) struct Deadlines {
61 counting: Mutex<BTreeMap<InterventionId, (Intervention, Duration)>>,
63 adopted: AtomicBool,
66}
67
68impl Deadlines {
69 fn count(&self, intervention: &Intervention, reading: ClockReading) {
71 let due = reading.elapsed_at(intervention.expires_at);
72 self.counting()
73 .insert(intervention.id, (intervention.clone(), due));
74 }
75
76 fn adopt(&self, intervention: &Intervention, reading: ClockReading) {
78 let due = reading.elapsed_at(intervention.expires_at);
79 self.counting()
80 .entry(intervention.id)
81 .or_insert_with(|| (intervention.clone(), due));
82 }
83
84 fn forget(&self, intervention_id: InterventionId) {
86 self.counting().remove(&intervention_id);
87 }
88
89 fn due(&self, elapsed: Duration) -> Vec<Intervention> {
91 let mut due: Vec<(Duration, Intervention)> = self
92 .counting()
93 .values()
94 .filter(|(_, at)| *at <= elapsed)
95 .map(|(intervention, at)| (*at, intervention.clone()))
96 .collect();
97 due.sort_by_key(|(at, _)| *at);
98 due.into_iter()
99 .map(|(_, intervention)| intervention)
100 .collect()
101 }
102
103 fn counting(
105 &self,
106 ) -> std::sync::MutexGuard<'_, BTreeMap<InterventionId, (Intervention, Duration)>> {
107 self.counting
108 .lock()
109 .unwrap_or_else(std::sync::PoisonError::into_inner)
110 }
111}
112
113const RESTORE_REASON: &str = "the bounded intervention expired";
115
116#[must_use]
120pub fn restoring_action(adjustable: Adjustable, prior_value: f64) -> PrintAction {
121 match adjustable {
122 Adjustable::Feedrate => PrintAction::SetFeedrateFactor {
123 factor: prior_value,
124 duration_s: None,
125 reason: RESTORE_REASON.to_owned(),
126 actor: Actor::System,
127 },
128 Adjustable::Flowrate => PrintAction::SetFlowrateFactor {
129 factor: prior_value,
130 duration_s: None,
131 reason: RESTORE_REASON.to_owned(),
132 actor: Actor::System,
133 },
134 Adjustable::ToolTarget { tool } => PrintAction::SetToolTargetC {
135 tool,
136 target_c: prior_value,
137 duration_s: None,
138 reason: RESTORE_REASON.to_owned(),
139 actor: Actor::System,
140 },
141 Adjustable::BedTarget => PrintAction::SetBedTargetC {
142 target_c: prior_value,
143 duration_s: None,
144 reason: RESTORE_REASON.to_owned(),
145 actor: Actor::System,
146 },
147 Adjustable::Fan => PrintAction::SetFanPercent {
148 percent: prior_value,
149 duration_s: None,
150 reason: RESTORE_REASON.to_owned(),
151 actor: Actor::System,
152 },
153 }
154}
155
156fn material_detail(objection: &MaterialObjection) -> String {
159 match objection {
160 MaterialObjection::Mismatch(compared) => format!(
161 "the file was sliced for {}, and spool {} on tool {} is {}",
162 compared.sliced_for, compared.spool.name, compared.tool, compared.loaded
163 ),
164 MaterialObjection::Undeclared(uncompared) => format!(
165 "{} names no `filament_type`, so it cannot be compared with spool {} on tool {}, \
166 which is {}",
167 uncompared.file_name, uncompared.spool.name, uncompared.tool, uncompared.loaded
168 ),
169 MaterialObjection::Unread {
170 tool,
171 spool,
172 loaded,
173 file_name,
174 detail,
175 } => format!(
176 "the settings of {file_name} could not be read ({detail}), so it cannot be compared \
177 with spool {} on tool {tool}, which is {loaded}",
178 spool.name
179 ),
180 }
181}
182
183fn listed(sheets: &[SheetId]) -> String {
185 sheets
186 .iter()
187 .map(SheetId::as_str)
188 .collect::<Vec<_>>()
189 .join(", ")
190}
191
192fn sheet_detail(objection: &SheetObjection) -> String {
195 match objection {
196 SheetObjection::NotAllowed(compared) => format!(
197 "the sheet table allows {} on {} and not on {}",
198 compared.material,
199 listed(&compared.allowed),
200 compared.sheet
201 ),
202 SheetObjection::UnlistedMaterial { sheet, material } => format!(
203 "the sheet table has no entry for {material}, so {sheet} is not known to suit it"
204 ),
205 SheetObjection::UnknownSheet {
206 sheet,
207 material,
208 known,
209 } => format!(
210 "no entry of the sheet table lists {sheet}, so it is not known to suit {material}; \
211 the sheets it names are {}",
212 listed(known)
213 ),
214 }
215}
216
217const fn interval_left_s(interval_s: i64, since_last_s: i64) -> i64 {
221 let left = interval_s.saturating_sub(since_last_s);
222 if left < 1 { 1 } else { left }
223}
224
225fn meant_for(tool: i64, segment: Option<u32>) -> String {
228 match segment {
229 Some(segment) => format!(" for segment {segment} on tool {tool}"),
230 None => format!(" on tool {tool}"),
231 }
232}
233
234#[must_use]
236pub fn rejection_detail(reason: &RejectionReason) -> String {
237 match reason {
238 RejectionReason::OutOfBounds {
239 adjustable,
240 requested,
241 allowed,
242 } => format!(
243 "{requested} is outside the {} to {} allowed for {adjustable}",
244 allowed.min, allowed.max
245 ),
246 RejectionReason::ActorMayNotRequest {
247 actor_class,
248 action,
249 } => format!("{actor_class:?} may not request {action:?}"),
250 RejectionReason::NoActivePrint => "there is no active print to act on".to_owned(),
251 RejectionReason::InvalidFromState { state } => {
252 format!("this is not valid from {state:?}")
253 }
254 RejectionReason::MinIntervalNotElapsed {
255 interval_s,
256 since_last_s,
257 } => {
258 let left_s = interval_left_s(*interval_s, *since_last_s);
259 format!(
260 "the agent last acted {since_last_s}s ago and its minimum interval is \
261 {interval_s}s, so {left_s}s of it are left: send the same request again after \
262 a look that waits at least {left_s}s"
263 )
264 }
265 RejectionReason::UnsupportedAdjustable { adjustable } => {
266 format!("this printer has no {adjustable}")
267 }
268 RejectionReason::InsufficientFilament {
269 tool,
270 spool_name,
271 required_g,
272 buffer_g,
273 remaining_g,
274 segment,
275 ..
276 } => format!(
277 "spool {spool_name}{} holds {remaining_g}g, and the print needs {required_g}g and a \
278 {buffer_g}g buffer",
279 meant_for(*tool, *segment)
280 ),
281 RejectionReason::UnverifiedSpool {
282 tool,
283 spool_name,
284 segment,
285 ..
286 } => format!(
287 "spool {spool_name}{} is unverified",
288 meant_for(*tool, *segment)
289 ),
290 RejectionReason::PlannedChangeWaiting {
291 change_index,
292 layer,
293 z_mm,
294 color,
295 } => format!(
296 "the printer is waiting at planned change {change_index}, for {} to be loaded for \
297 layer {layer} (Z {z_mm} mm): a person finishes it on the printer, and nothing \
298 pauses, resumes or adjusts the print until it carries on",
299 color.as_deref().unwrap_or("the next filament")
300 ),
301 RejectionReason::AnalysisUnavailable {
302 file_name,
303 waited_s,
304 } => format!("{file_name} had no analysis after waiting {waited_s}s for one"),
305 RejectionReason::MaterialRefused { objection } => material_detail(objection),
306 RejectionReason::SheetRefused { objection } => sheet_detail(objection),
307 RejectionReason::SheetNotDeclared => "the manifest declares no `sheet`, and every start \
308 names the build sheet it goes down on; no override lets a start without one through"
309 .to_owned(),
310 RejectionReason::SpoolRefused { message, .. } => message.clone(),
311 RejectionReason::PrintAlreadyEnded => "this print's record has already ended".to_owned(),
312 RejectionReason::PrintStillActive { state } => {
313 format!("the printer shows this print's file still {state:?}")
314 }
315 RejectionReason::InterventionStillActive { intervention_id } => {
316 format!("intervention {intervention_id} has neither expired nor been restored")
317 }
318 RejectionReason::PrintNotResumable { recovery_event_id } => format!(
319 "recovery event {recovery_event_id} moved the printer while this print was paused, \
320 and resuming would print the rest of the layer at the wrong height"
321 ),
322 }
323}
324
325impl Supervisor {
326 pub async fn sweep_expired(&self) -> Result<(), CoreError> {
343 self.adopt_left_active().await?;
344 for intervention in self.deadlines().due(self.clock().elapsed()) {
345 let _ = self.expire_intervention(&intervention).await;
346 }
347 Ok(())
348 }
349
350 async fn adopt_left_active(&self) -> Result<(), CoreError> {
352 let deadlines = self.deadlines();
353 if deadlines.adopted.load(Ordering::Acquire) {
354 return Ok(());
355 }
356 for intervention in self
359 .stores()
360 .actions
361 .due_interventions(Timestamp::latest())
362 .await?
363 {
364 deadlines.adopt(&intervention, self.started());
365 }
366 deadlines.adopted.store(true, Ordering::Release);
367 Ok(())
368 }
369
370 pub(crate) fn count_down(&self, intervention: &Intervention) {
372 self.deadlines()
373 .count(intervention, ClockReading::of(self.clock().as_ref()));
374 }
375
376 pub(crate) fn stop_counting_down(&self, intervention_id: InterventionId) {
378 self.deadlines().forget(intervention_id);
379 }
380
381 pub(crate) async fn expire_all_active(&self, print_id: PrintId) -> Result<(), CoreError> {
391 for intervention in self.stores().actions.active_interventions(print_id).await? {
392 let _ = self.expire_intervention(&intervention).await;
393 }
394 Ok(())
395 }
396
397 pub async fn expire_intervention(
410 &self,
411 intervention: &Intervention,
412 ) -> Result<InterventionOutcome, CoreError> {
413 let outcome = self.expire_once(intervention).await?;
414 self.deadlines().forget(intervention.id);
415 Ok(outcome)
416 }
417
418 async fn expire_once(
420 &self,
421 intervention: &Intervention,
422 ) -> Result<InterventionOutcome, CoreError> {
423 if intervention.outcome != InterventionOutcome::StillActive {
424 return Ok(intervention.outcome.clone());
425 }
426 let _expiring = self.expiring().acquire(intervention.print_id).await;
431 let still_active = self
432 .stores()
433 .actions
434 .active_interventions(intervention.print_id)
435 .await?
436 .iter()
437 .any(|active| active.id == intervention.id);
438 if !still_active {
439 return self
442 .settle(intervention, InterventionOutcome::RestoreUnavailable)
443 .await;
444 }
445 let Some(prior_value) = intervention.prior_value else {
446 return self
447 .settle(intervention, InterventionOutcome::RestoreUnavailable)
448 .await;
449 };
450 let outcome = self.restore(intervention, prior_value).await?;
451 self.settle(intervention, outcome).await
452 }
453
454 async fn restore(
456 &self,
457 intervention: &Intervention,
458 prior_value: f64,
459 ) -> Result<InterventionOutcome, CoreError> {
460 let requested_at = self.clock().now();
461 let action = restoring_action(intervention.adjustable, prior_value);
462 let actor = action.actor().clone();
463 let print = self.stores().prints.print(intervention.print_id).await?;
464 let bounds = self
465 .bounds_for(print.as_ref(), intervention.print_id)
466 .await?;
467 let decision = decide(&DecisionInput {
468 action: &action,
469 actor: &actor,
470 requested_at,
471 print: print.as_ref(),
472 printer_state: None,
474 bounds: &bounds.effective,
475 envelope: &self.config().envelope,
476 since_last_agent_action: None,
477 });
478 let request = crate::records::ActionRequest {
479 action,
480 actor,
481 requested_at,
482 };
483 let issued = self.issue_action(request, decision, None).await?;
484 if let PolicyDecision::Rejected(reason) = &issued.record.decision {
485 return Ok(InterventionOutcome::RestoreFailed {
486 reason: rejection_detail(reason),
487 });
488 }
489 if let Some(error) = issued.printer_error() {
490 return Ok(InterventionOutcome::RestoreFailed {
491 reason: error.to_string(),
492 });
493 }
494 Ok(InterventionOutcome::Restored)
495 }
496
497 async fn settle(
499 &self,
500 intervention: &Intervention,
501 outcome: InterventionOutcome,
502 ) -> Result<InterventionOutcome, CoreError> {
503 let settled = self
504 .stores()
505 .actions
506 .settle_intervention(intervention.id, outcome)
507 .await?;
508 Ok(match settled {
509 SettleOutcome::Settled {
514 intervention: settled,
515 } => {
516 self.append_expiry_event(intervention, settled.outcome.clone())
517 .await?;
518 settled.outcome
519 }
520 SettleOutcome::AlreadySettled { outcome } => outcome,
521 })
522 }
523
524 async fn append_expiry_event(
526 &self,
527 intervention: &Intervention,
528 outcome: InterventionOutcome,
529 ) -> Result<(), CoreError> {
530 self.stores()
531 .events
532 .append_event(EventDraft {
533 print_id: Some(intervention.print_id),
534 source: crate::kinds::system_source(),
535 received_at: self.clock().now(),
536 body: printobserver_types::EventBody::of(
537 &crate::kinds::InterventionExpiredPayload {
538 intervention_id: intervention.id,
539 adjustable: intervention.adjustable,
540 outcome,
541 },
542 )?,
543 raw: None,
544 })
545 .await?;
546 Ok(())
547 }
548}