1use printobserver_types::{
28 Actor, Adjustable, Intervention, InterventionOutcome, PolicyDecision, PrintAction, PrintId,
29 RejectionReason,
30};
31
32use crate::decision::{DecisionInput, decide};
33use crate::error::CoreError;
34use crate::supervisor::Supervisor;
35
36const RESTORE_REASON: &str = "the bounded intervention expired";
38
39#[must_use]
43pub fn restoring_action(adjustable: Adjustable, prior_value: f64) -> PrintAction {
44 match adjustable {
45 Adjustable::Feedrate => PrintAction::SetFeedrateFactor {
46 factor: prior_value,
47 duration_s: None,
48 reason: RESTORE_REASON.to_owned(),
49 actor: Actor::System,
50 },
51 Adjustable::Flowrate => PrintAction::SetFlowrateFactor {
52 factor: prior_value,
53 duration_s: None,
54 reason: RESTORE_REASON.to_owned(),
55 actor: Actor::System,
56 },
57 Adjustable::ToolTarget { tool } => PrintAction::SetToolTargetC {
58 tool,
59 target_c: prior_value,
60 duration_s: None,
61 reason: RESTORE_REASON.to_owned(),
62 actor: Actor::System,
63 },
64 Adjustable::BedTarget => PrintAction::SetBedTargetC {
65 target_c: prior_value,
66 duration_s: None,
67 reason: RESTORE_REASON.to_owned(),
68 actor: Actor::System,
69 },
70 Adjustable::Fan => PrintAction::SetFanPercent {
71 percent: prior_value,
72 duration_s: None,
73 reason: RESTORE_REASON.to_owned(),
74 actor: Actor::System,
75 },
76 }
77}
78
79#[must_use]
81pub fn rejection_detail(reason: &RejectionReason) -> String {
82 match reason {
83 RejectionReason::OutOfBounds {
84 adjustable,
85 requested,
86 allowed,
87 } => format!(
88 "{requested} is outside the {} to {} allowed for {adjustable}",
89 allowed.min, allowed.max
90 ),
91 RejectionReason::ActorMayNotRequest {
92 actor_class,
93 action,
94 } => format!("{actor_class:?} may not request {action:?}"),
95 RejectionReason::NoActivePrint => "there is no active print to act on".to_owned(),
96 RejectionReason::InvalidFromState { state } => {
97 format!("this is not valid from {state:?}")
98 }
99 RejectionReason::MinIntervalNotElapsed {
100 interval_s,
101 since_last_s,
102 } => format!(
103 "the agent last acted {since_last_s}s ago and its minimum interval is {interval_s}s"
104 ),
105 RejectionReason::UnsupportedAdjustable { adjustable } => {
106 format!("this printer has no {adjustable}")
107 }
108 }
109}
110
111impl Supervisor {
112 pub async fn sweep_expired(&self) -> Result<(), CoreError> {
127 let at = self.clock().now();
128 for intervention in self.store().due_interventions(at).await? {
129 let _ = self.expire_intervention(&intervention).await;
130 }
131 Ok(())
132 }
133
134 pub(crate) async fn expire_all_active(&self, print_id: PrintId) -> Result<(), CoreError> {
144 for intervention in self.store().active_interventions(print_id).await? {
145 let _ = self.expire_intervention(&intervention).await;
146 }
147 Ok(())
148 }
149
150 pub async fn expire_intervention(
163 &self,
164 intervention: &Intervention,
165 ) -> Result<InterventionOutcome, CoreError> {
166 if intervention.outcome != InterventionOutcome::StillActive {
167 return Ok(intervention.outcome.clone());
168 }
169 let Some(prior_value) = intervention.prior_value else {
170 return self
171 .settle(intervention, InterventionOutcome::RestoreUnavailable)
172 .await;
173 };
174 let outcome = self.restore(intervention, prior_value).await?;
175 self.settle(intervention, outcome).await
176 }
177
178 async fn restore(
180 &self,
181 intervention: &Intervention,
182 prior_value: f64,
183 ) -> Result<InterventionOutcome, CoreError> {
184 let requested_at = self.clock().now();
185 let action = restoring_action(intervention.adjustable, prior_value);
186 let actor = action.actor().clone();
187 let print = self.store().print(intervention.print_id).await?;
188 let bounds = self
189 .bounds_for(print.as_ref(), intervention.print_id)
190 .await?;
191 let decision = decide(&DecisionInput {
192 action: &action,
193 actor: &actor,
194 requested_at,
195 print: print.as_ref(),
196 printer_state: None,
198 bounds: &bounds.effective,
199 envelope: &self.config().envelope,
200 last_agent_action: None,
201 });
202 let request = printobserver_types::ActionRequest {
203 action,
204 actor,
205 requested_at,
206 };
207 let issued = self.issue_decided_action(request, decision).await?;
208 if let PolicyDecision::Rejected(reason) = &issued.record.decision {
209 return Ok(InterventionOutcome::RestoreFailed {
210 reason: rejection_detail(reason),
211 });
212 }
213 if let Some(error) = issued.printer_error() {
214 return Ok(InterventionOutcome::RestoreFailed {
215 reason: error.to_string(),
216 });
217 }
218 Ok(InterventionOutcome::Restored)
219 }
220
221 async fn settle(
223 &self,
224 intervention: &Intervention,
225 outcome: InterventionOutcome,
226 ) -> Result<InterventionOutcome, CoreError> {
227 let settled = self
228 .store()
229 .settle_intervention(intervention.id, outcome)
230 .await?;
231 Ok(match settled {
232 printobserver_store_api::SettleOutcome::Settled {
237 intervention: settled,
238 } => {
239 self.append_expiry_event(intervention, settled.outcome.clone())
240 .await?;
241 settled.outcome
242 }
243 printobserver_store_api::SettleOutcome::AlreadySettled { outcome } => outcome,
244 })
245 }
246
247 async fn append_expiry_event(
249 &self,
250 intervention: &Intervention,
251 outcome: InterventionOutcome,
252 ) -> Result<(), CoreError> {
253 self.store()
254 .append_event(printobserver_store_api::EventDraft {
255 print_id: Some(intervention.print_id),
256 source: printobserver_types::EventSource::System,
257 received_at: self.clock().now(),
258 payload: printobserver_types::EventPayload::InterventionExpired(
259 printobserver_types::InterventionExpiredPayload {
260 intervention_id: intervention.id,
261 adjustable: intervention.adjustable,
262 outcome,
263 },
264 ),
265 raw: None,
266 })
267 .await?;
268 Ok(())
269 }
270}