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 }
111}
112
113impl Supervisor {
114 pub async fn sweep_expired(&self) -> Result<(), CoreError> {
129 let at = self.clock().now();
130 for intervention in self.stores().actions.due_interventions(at).await? {
131 let _ = self.expire_intervention(&intervention).await;
132 }
133 Ok(())
134 }
135
136 pub(crate) async fn expire_all_active(&self, print_id: PrintId) -> Result<(), CoreError> {
146 for intervention in self.stores().actions.active_interventions(print_id).await? {
147 let _ = self.expire_intervention(&intervention).await;
148 }
149 Ok(())
150 }
151
152 pub async fn expire_intervention(
165 &self,
166 intervention: &Intervention,
167 ) -> Result<InterventionOutcome, CoreError> {
168 if intervention.outcome != InterventionOutcome::StillActive {
169 return Ok(intervention.outcome.clone());
170 }
171 let Some(prior_value) = intervention.prior_value else {
172 return self
173 .settle(intervention, InterventionOutcome::RestoreUnavailable)
174 .await;
175 };
176 let outcome = self.restore(intervention, prior_value).await?;
177 self.settle(intervention, outcome).await
178 }
179
180 async fn restore(
182 &self,
183 intervention: &Intervention,
184 prior_value: f64,
185 ) -> Result<InterventionOutcome, CoreError> {
186 let requested_at = self.clock().now();
187 let action = restoring_action(intervention.adjustable, prior_value);
188 let actor = action.actor().clone();
189 let print = self.stores().prints.print(intervention.print_id).await?;
190 let bounds = self
191 .bounds_for(print.as_ref(), intervention.print_id)
192 .await?;
193 let decision = decide(&DecisionInput {
194 action: &action,
195 actor: &actor,
196 requested_at,
197 print: print.as_ref(),
198 printer_state: None,
200 bounds: &bounds.effective,
201 envelope: &self.config().envelope,
202 last_agent_action: None,
203 });
204 let request = crate::records::ActionRequest {
205 action,
206 actor,
207 requested_at,
208 };
209 let issued = self.issue_decided_action(request, decision).await?;
210 if let PolicyDecision::Rejected(reason) = &issued.record.decision {
211 return Ok(InterventionOutcome::RestoreFailed {
212 reason: rejection_detail(reason),
213 });
214 }
215 if let Some(error) = issued.printer_error() {
216 return Ok(InterventionOutcome::RestoreFailed {
217 reason: error.to_string(),
218 });
219 }
220 Ok(InterventionOutcome::Restored)
221 }
222
223 async fn settle(
225 &self,
226 intervention: &Intervention,
227 outcome: InterventionOutcome,
228 ) -> Result<InterventionOutcome, CoreError> {
229 let settled = self
230 .stores()
231 .actions
232 .settle_intervention(intervention.id, outcome)
233 .await?;
234 Ok(match settled {
235 SettleOutcome::Settled {
240 intervention: settled,
241 } => {
242 self.append_expiry_event(intervention, settled.outcome.clone())
243 .await?;
244 settled.outcome
245 }
246 SettleOutcome::AlreadySettled { outcome } => outcome,
247 })
248 }
249
250 async fn append_expiry_event(
252 &self,
253 intervention: &Intervention,
254 outcome: InterventionOutcome,
255 ) -> Result<(), CoreError> {
256 self.stores()
257 .events
258 .append_event(EventDraft {
259 print_id: Some(intervention.print_id),
260 source: crate::kinds::system_source(),
261 received_at: self.clock().now(),
262 body: printobserver_types::EventBody::of(
263 &crate::kinds::InterventionExpiredPayload {
264 intervention_id: intervention.id,
265 adjustable: intervention.adjustable,
266 outcome,
267 },
268 )?,
269 raw: None,
270 })
271 .await?;
272 Ok(())
273 }
274}