1use crate::records::{
28 Actor, Intervention, InterventionOutcome, PolicyDecision, PrintAction, RejectionReason,
29};
30use printobserver_printer_api::Adjustable;
31use printobserver_types::PrintId;
32
33use crate::decision::{DecisionInput, decide};
34use crate::error::CoreError;
35use crate::store::{EventDraft, SettleOutcome};
36use crate::supervisor::Supervisor;
37
38const RESTORE_REASON: &str = "the bounded intervention expired";
40
41#[must_use]
45pub fn restoring_action(adjustable: Adjustable, prior_value: f64) -> PrintAction {
46 match adjustable {
47 Adjustable::Feedrate => PrintAction::SetFeedrateFactor {
48 factor: prior_value,
49 duration_s: None,
50 reason: RESTORE_REASON.to_owned(),
51 actor: Actor::System,
52 },
53 Adjustable::Flowrate => PrintAction::SetFlowrateFactor {
54 factor: prior_value,
55 duration_s: None,
56 reason: RESTORE_REASON.to_owned(),
57 actor: Actor::System,
58 },
59 Adjustable::ToolTarget { tool } => PrintAction::SetToolTargetC {
60 tool,
61 target_c: prior_value,
62 duration_s: None,
63 reason: RESTORE_REASON.to_owned(),
64 actor: Actor::System,
65 },
66 Adjustable::BedTarget => PrintAction::SetBedTargetC {
67 target_c: prior_value,
68 duration_s: None,
69 reason: RESTORE_REASON.to_owned(),
70 actor: Actor::System,
71 },
72 Adjustable::Fan => PrintAction::SetFanPercent {
73 percent: prior_value,
74 duration_s: None,
75 reason: RESTORE_REASON.to_owned(),
76 actor: Actor::System,
77 },
78 }
79}
80
81#[must_use]
83pub fn rejection_detail(reason: &RejectionReason) -> String {
84 match reason {
85 RejectionReason::OutOfBounds {
86 adjustable,
87 requested,
88 allowed,
89 } => format!(
90 "{requested} is outside the {} to {} allowed for {adjustable}",
91 allowed.min, allowed.max
92 ),
93 RejectionReason::ActorMayNotRequest {
94 actor_class,
95 action,
96 } => format!("{actor_class:?} may not request {action:?}"),
97 RejectionReason::NoActivePrint => "there is no active print to act on".to_owned(),
98 RejectionReason::InvalidFromState { state } => {
99 format!("this is not valid from {state:?}")
100 }
101 RejectionReason::MinIntervalNotElapsed {
102 interval_s,
103 since_last_s,
104 } => format!(
105 "the agent last acted {since_last_s}s ago and its minimum interval is {interval_s}s"
106 ),
107 RejectionReason::UnsupportedAdjustable { adjustable } => {
108 format!("this printer has no {adjustable}")
109 }
110 RejectionReason::InsufficientFilament {
111 tool,
112 spool_name,
113 required_g,
114 buffer_g,
115 remaining_g,
116 ..
117 } => format!(
118 "spool {spool_name} on tool {tool} holds {remaining_g}g, and the print needs \
119 {required_g}g and a {buffer_g}g buffer"
120 ),
121 RejectionReason::UnverifiedSpool {
122 tool, spool_name, ..
123 } => format!("spool {spool_name} on tool {tool} is unverified"),
124 RejectionReason::AnalysisUnavailable {
125 file_name,
126 waited_s,
127 } => format!("{file_name} had no analysis after waiting {waited_s}s for one"),
128 RejectionReason::SpoolRefused { detail } => detail.clone(),
129 }
130}
131
132impl Supervisor {
133 pub async fn sweep_expired(&self) -> Result<(), CoreError> {
148 let at = self.clock().now();
149 for intervention in self.stores().actions.due_interventions(at).await? {
150 let _ = self.expire_intervention(&intervention).await;
151 }
152 Ok(())
153 }
154
155 pub(crate) async fn expire_all_active(&self, print_id: PrintId) -> Result<(), CoreError> {
165 for intervention in self.stores().actions.active_interventions(print_id).await? {
166 let _ = self.expire_intervention(&intervention).await;
167 }
168 Ok(())
169 }
170
171 pub async fn expire_intervention(
184 &self,
185 intervention: &Intervention,
186 ) -> Result<InterventionOutcome, CoreError> {
187 if intervention.outcome != InterventionOutcome::StillActive {
188 return Ok(intervention.outcome.clone());
189 }
190 let _expiring = self.expiring().acquire(intervention.print_id).await;
195 let still_active = self
196 .stores()
197 .actions
198 .active_interventions(intervention.print_id)
199 .await?
200 .iter()
201 .any(|active| active.id == intervention.id);
202 if !still_active {
203 return self
206 .settle(intervention, InterventionOutcome::RestoreUnavailable)
207 .await;
208 }
209 let Some(prior_value) = intervention.prior_value else {
210 return self
211 .settle(intervention, InterventionOutcome::RestoreUnavailable)
212 .await;
213 };
214 let outcome = self.restore(intervention, prior_value).await?;
215 self.settle(intervention, outcome).await
216 }
217
218 async fn restore(
220 &self,
221 intervention: &Intervention,
222 prior_value: f64,
223 ) -> Result<InterventionOutcome, CoreError> {
224 let requested_at = self.clock().now();
225 let action = restoring_action(intervention.adjustable, prior_value);
226 let actor = action.actor().clone();
227 let print = self.stores().prints.print(intervention.print_id).await?;
228 let bounds = self
229 .bounds_for(print.as_ref(), intervention.print_id)
230 .await?;
231 let decision = decide(&DecisionInput {
232 action: &action,
233 actor: &actor,
234 requested_at,
235 print: print.as_ref(),
236 printer_state: None,
238 bounds: &bounds.effective,
239 envelope: &self.config().envelope,
240 last_agent_action: None,
241 });
242 let request = crate::records::ActionRequest {
243 action,
244 actor,
245 requested_at,
246 };
247 let issued = self.issue_decided_action(request, decision).await?;
248 if let PolicyDecision::Rejected(reason) = &issued.record.decision {
249 return Ok(InterventionOutcome::RestoreFailed {
250 reason: rejection_detail(reason),
251 });
252 }
253 if let Some(error) = issued.printer_error() {
254 return Ok(InterventionOutcome::RestoreFailed {
255 reason: error.to_string(),
256 });
257 }
258 Ok(InterventionOutcome::Restored)
259 }
260
261 async fn settle(
263 &self,
264 intervention: &Intervention,
265 outcome: InterventionOutcome,
266 ) -> Result<InterventionOutcome, CoreError> {
267 let settled = self
268 .stores()
269 .actions
270 .settle_intervention(intervention.id, outcome)
271 .await?;
272 Ok(match settled {
273 SettleOutcome::Settled {
278 intervention: settled,
279 } => {
280 self.append_expiry_event(intervention, settled.outcome.clone())
281 .await?;
282 settled.outcome
283 }
284 SettleOutcome::AlreadySettled { outcome } => outcome,
285 })
286 }
287
288 async fn append_expiry_event(
290 &self,
291 intervention: &Intervention,
292 outcome: InterventionOutcome,
293 ) -> Result<(), CoreError> {
294 self.stores()
295 .events
296 .append_event(EventDraft {
297 print_id: Some(intervention.print_id),
298 source: crate::kinds::system_source(),
299 received_at: self.clock().now(),
300 body: printobserver_types::EventBody::of(
301 &crate::kinds::InterventionExpiredPayload {
302 intervention_id: intervention.id,
303 adjustable: intervention.adjustable,
304 outcome,
305 },
306 )?,
307 raw: None,
308 })
309 .await?;
310 Ok(())
311 }
312}