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, PolicyDecision, PrintAction,
46 RejectionReason,
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
156#[must_use]
158pub fn rejection_detail(reason: &RejectionReason) -> String {
159 match reason {
160 RejectionReason::OutOfBounds {
161 adjustable,
162 requested,
163 allowed,
164 } => format!(
165 "{requested} is outside the {} to {} allowed for {adjustable}",
166 allowed.min, allowed.max
167 ),
168 RejectionReason::ActorMayNotRequest {
169 actor_class,
170 action,
171 } => format!("{actor_class:?} may not request {action:?}"),
172 RejectionReason::NoActivePrint => "there is no active print to act on".to_owned(),
173 RejectionReason::InvalidFromState { state } => {
174 format!("this is not valid from {state:?}")
175 }
176 RejectionReason::MinIntervalNotElapsed {
177 interval_s,
178 since_last_s,
179 } => format!(
180 "the agent last acted {since_last_s}s ago and its minimum interval is {interval_s}s"
181 ),
182 RejectionReason::UnsupportedAdjustable { adjustable } => {
183 format!("this printer has no {adjustable}")
184 }
185 RejectionReason::InsufficientFilament {
186 tool,
187 spool_name,
188 required_g,
189 buffer_g,
190 remaining_g,
191 ..
192 } => format!(
193 "spool {spool_name} on tool {tool} holds {remaining_g}g, and the print needs \
194 {required_g}g and a {buffer_g}g buffer"
195 ),
196 RejectionReason::UnverifiedSpool {
197 tool, spool_name, ..
198 } => format!("spool {spool_name} on tool {tool} is unverified"),
199 RejectionReason::AnalysisUnavailable {
200 file_name,
201 waited_s,
202 } => format!("{file_name} had no analysis after waiting {waited_s}s for one"),
203 RejectionReason::SpoolRefused { message, .. } => message.clone(),
204 RejectionReason::PrintAlreadyEnded => "this print's record has already ended".to_owned(),
205 RejectionReason::PrintStillActive { state } => {
206 format!("the printer shows this print's file still {state:?}")
207 }
208 RejectionReason::InterventionStillActive { intervention_id } => {
209 format!("intervention {intervention_id} has neither expired nor been restored")
210 }
211 RejectionReason::PrintNotResumable { recovery_event_id } => format!(
212 "recovery event {recovery_event_id} moved the printer while this print was paused, \
213 and resuming would print the rest of the layer at the wrong height"
214 ),
215 }
216}
217
218impl Supervisor {
219 pub async fn sweep_expired(&self) -> Result<(), CoreError> {
236 self.adopt_left_active().await?;
237 for intervention in self.deadlines().due(self.clock().elapsed()) {
238 let _ = self.expire_intervention(&intervention).await;
239 }
240 Ok(())
241 }
242
243 async fn adopt_left_active(&self) -> Result<(), CoreError> {
245 let deadlines = self.deadlines();
246 if deadlines.adopted.load(Ordering::Acquire) {
247 return Ok(());
248 }
249 for intervention in self
252 .stores()
253 .actions
254 .due_interventions(Timestamp::latest())
255 .await?
256 {
257 deadlines.adopt(&intervention, self.started());
258 }
259 deadlines.adopted.store(true, Ordering::Release);
260 Ok(())
261 }
262
263 pub(crate) fn count_down(&self, intervention: &Intervention) {
265 self.deadlines()
266 .count(intervention, ClockReading::of(self.clock().as_ref()));
267 }
268
269 pub(crate) fn stop_counting_down(&self, intervention_id: InterventionId) {
271 self.deadlines().forget(intervention_id);
272 }
273
274 pub(crate) async fn expire_all_active(&self, print_id: PrintId) -> Result<(), CoreError> {
284 for intervention in self.stores().actions.active_interventions(print_id).await? {
285 let _ = self.expire_intervention(&intervention).await;
286 }
287 Ok(())
288 }
289
290 pub async fn expire_intervention(
303 &self,
304 intervention: &Intervention,
305 ) -> Result<InterventionOutcome, CoreError> {
306 let outcome = self.expire_once(intervention).await?;
307 self.deadlines().forget(intervention.id);
308 Ok(outcome)
309 }
310
311 async fn expire_once(
313 &self,
314 intervention: &Intervention,
315 ) -> Result<InterventionOutcome, CoreError> {
316 if intervention.outcome != InterventionOutcome::StillActive {
317 return Ok(intervention.outcome.clone());
318 }
319 let _expiring = self.expiring().acquire(intervention.print_id).await;
324 let still_active = self
325 .stores()
326 .actions
327 .active_interventions(intervention.print_id)
328 .await?
329 .iter()
330 .any(|active| active.id == intervention.id);
331 if !still_active {
332 return self
335 .settle(intervention, InterventionOutcome::RestoreUnavailable)
336 .await;
337 }
338 let Some(prior_value) = intervention.prior_value else {
339 return self
340 .settle(intervention, InterventionOutcome::RestoreUnavailable)
341 .await;
342 };
343 let outcome = self.restore(intervention, prior_value).await?;
344 self.settle(intervention, outcome).await
345 }
346
347 async fn restore(
349 &self,
350 intervention: &Intervention,
351 prior_value: f64,
352 ) -> Result<InterventionOutcome, CoreError> {
353 let requested_at = self.clock().now();
354 let action = restoring_action(intervention.adjustable, prior_value);
355 let actor = action.actor().clone();
356 let print = self.stores().prints.print(intervention.print_id).await?;
357 let bounds = self
358 .bounds_for(print.as_ref(), intervention.print_id)
359 .await?;
360 let decision = decide(&DecisionInput {
361 action: &action,
362 actor: &actor,
363 requested_at,
364 print: print.as_ref(),
365 printer_state: None,
367 bounds: &bounds.effective,
368 envelope: &self.config().envelope,
369 since_last_agent_action: None,
370 });
371 let request = crate::records::ActionRequest {
372 action,
373 actor,
374 requested_at,
375 };
376 let issued = self.issue_action(request, decision, None).await?;
377 if let PolicyDecision::Rejected(reason) = &issued.record.decision {
378 return Ok(InterventionOutcome::RestoreFailed {
379 reason: rejection_detail(reason),
380 });
381 }
382 if let Some(error) = issued.printer_error() {
383 return Ok(InterventionOutcome::RestoreFailed {
384 reason: error.to_string(),
385 });
386 }
387 Ok(InterventionOutcome::Restored)
388 }
389
390 async fn settle(
392 &self,
393 intervention: &Intervention,
394 outcome: InterventionOutcome,
395 ) -> Result<InterventionOutcome, CoreError> {
396 let settled = self
397 .stores()
398 .actions
399 .settle_intervention(intervention.id, outcome)
400 .await?;
401 Ok(match settled {
402 SettleOutcome::Settled {
407 intervention: settled,
408 } => {
409 self.append_expiry_event(intervention, settled.outcome.clone())
410 .await?;
411 settled.outcome
412 }
413 SettleOutcome::AlreadySettled { outcome } => outcome,
414 })
415 }
416
417 async fn append_expiry_event(
419 &self,
420 intervention: &Intervention,
421 outcome: InterventionOutcome,
422 ) -> Result<(), CoreError> {
423 self.stores()
424 .events
425 .append_event(EventDraft {
426 print_id: Some(intervention.print_id),
427 source: crate::kinds::system_source(),
428 received_at: self.clock().now(),
429 body: printobserver_types::EventBody::of(
430 &crate::kinds::InterventionExpiredPayload {
431 intervention_id: intervention.id,
432 adjustable: intervention.adjustable,
433 outcome,
434 },
435 )?,
436 raw: None,
437 })
438 .await?;
439 Ok(())
440 }
441}