1use crate::records::{
19 ActionRecord, ActionRequest, Actor, ActorClass, Intervention, InterventionOutcome,
20 PolicyDecision, PrintAction, PrintRecord,
21};
22use printobserver_printer_api::Adjustable;
23use printobserver_printer_api::PrinterSnapshot;
24use printobserver_types::{EventBody, EventSource, PrintId, Timestamp};
25
26use crate::bounds::{Bounds, effective_bounds};
27use crate::clock::plus_seconds;
28use crate::decision::{DecisionInput, adjustment, decide};
29use crate::error::CoreError;
30use crate::kinds::{
31 ActionExecutedPayload, ActionRejectedPayload, ActionRequestedPayload, agent_source,
32 operator_source, system_source,
33};
34use crate::store::EventDraft;
35use crate::supervisor::{Issued, Supervisor};
36
37#[derive(Debug, Clone, PartialEq)]
39pub struct ActionOutcome {
40 pub record: ActionRecord,
42 pub executed: Option<Result<(), printobserver_printer_api::PrinterError>>,
44 pub intervention: Option<Intervention>,
46}
47
48impl ActionOutcome {
49 #[must_use]
51 pub const fn decision(&self) -> &PolicyDecision {
52 &self.record.decision
53 }
54}
55
56fn source_of(actor: &Actor) -> EventSource {
58 match actor.class() {
59 ActorClass::Agent => agent_source(),
60 ActorClass::Operator => operator_source(),
61 ActorClass::System => system_source(),
62 }
63}
64
65fn duration_of(action: &PrintAction) -> Option<i64> {
67 match action {
68 PrintAction::SetFeedrateFactor { duration_s, .. }
69 | PrintAction::SetFlowrateFactor { duration_s, .. }
70 | PrintAction::SetToolTargetC { duration_s, .. }
71 | PrintAction::SetBedTargetC { duration_s, .. }
72 | PrintAction::SetFanPercent { duration_s, .. } => *duration_s,
73 PrintAction::Pause { .. }
74 | PrintAction::Resume { .. }
75 | PrintAction::Cancel { .. }
76 | PrintAction::StartPrint { .. }
77 | PrintAction::AcknowledgeFailure { .. } => None,
78 }
79}
80
81#[must_use]
87pub fn reported_value(snapshot: &PrinterSnapshot, adjustable: Adjustable) -> Option<f64> {
88 let reported = match adjustable {
89 Adjustable::Feedrate => snapshot.feedrate_factor,
90 Adjustable::Flowrate => snapshot.flowrate_factor,
91 Adjustable::Fan => snapshot.fan_percent,
92 Adjustable::BedTarget => snapshot.bed.as_ref().and_then(|heater| heater.target_c),
93 Adjustable::ToolTarget { tool } => usize::try_from(tool)
94 .ok()
95 .and_then(|index| snapshot.tools.get(index))
96 .and_then(|heater| heater.target_c),
97 };
98 reported.map(|value| value.value())
99}
100
101impl Supervisor {
102 pub async fn request_action(
115 &self,
116 print_id: PrintId,
117 action: PrintAction,
118 ) -> Result<ActionOutcome, CoreError> {
119 let requested_at = self.clock().now();
120 let actor = action.actor().clone();
121 let print = self.stores().prints.print(print_id).await?;
122 let bounds = self.bounds_for(print.as_ref(), print_id).await?;
123 let snapshot = self.read_snapshot().await.ok();
124 let decision = decide(&DecisionInput {
125 action: &action,
126 actor: &actor,
127 requested_at,
128 print: print.as_ref(),
129 printer_state: snapshot.as_ref().map(|taken| &taken.connection),
130 bounds: &bounds.effective,
131 envelope: &self.config().envelope,
132 last_agent_action: self.last_agent_action(print_id),
133 });
134 let request = ActionRequest {
135 action: action.clone(),
136 actor: actor.clone(),
137 requested_at,
138 };
139 let issued = self.issue_decided_action(request, decision).await?;
140 let source = source_of(&actor);
141 self.append_action_event(
142 print_id,
143 source.clone(),
144 EventBody::of(&ActionRequestedPayload {
145 action_id: issued.record.id,
146 action: action.clone(),
147 actor: actor.clone(),
148 })?,
149 )
150 .await?;
151 if let PolicyDecision::Rejected(_) = &issued.record.decision {
152 self.append_action_event(
153 print_id,
154 source.clone(),
155 EventBody::of(&ActionRejectedPayload {
156 action_id: issued.record.id,
157 decision: issued.record.decision.clone(),
158 })?,
159 )
160 .await?;
161 }
162 if !issued.succeeded() {
163 return Ok(ActionOutcome {
164 record: issued.record,
165 executed: issued.executed,
166 intervention: None,
167 });
168 }
169 if actor.class() == ActorClass::Agent {
170 self.note_agent_action(print_id, requested_at);
171 }
172 if let PrintAction::StartPrint { manifest, .. } = &action {
173 self.attach_manifest(print_id, manifest.clone()).await?;
174 }
175 let intervention = self
176 .open_bounded_intervention(print_id, &action, &issued, snapshot.as_ref(), requested_at)
177 .await?;
178 self.append_action_event(
179 print_id,
180 source,
181 EventBody::of(&ActionExecutedPayload {
182 action_id: issued.record.id,
183 intervention_id: intervention.as_ref().map(|opened| opened.id),
184 })?,
185 )
186 .await?;
187 Ok(ActionOutcome {
188 record: issued.record,
189 executed: issued.executed,
190 intervention,
191 })
192 }
193
194 async fn append_action_event(
196 &self,
197 print_id: PrintId,
198 source: EventSource,
199 body: EventBody,
200 ) -> Result<(), CoreError> {
201 self.stores()
202 .events
203 .append_event(EventDraft {
204 print_id: Some(print_id),
205 source,
206 received_at: self.clock().now(),
207 body,
208 raw: None,
209 })
210 .await?;
211 Ok(())
212 }
213
214 pub(crate) async fn bounds_for(
216 &self,
217 print: Option<&PrintRecord>,
218 print_id: PrintId,
219 ) -> Result<Bounds, CoreError> {
220 let manifest = if print.is_some() {
221 self.stores().prints.manifest(print_id).await?
222 } else {
223 None
224 };
225 Ok(effective_bounds(&self.config().envelope, manifest.as_ref()))
226 }
227
228 async fn attach_manifest(
231 &self,
232 print_id: PrintId,
233 manifest: crate::records::JobManifest,
234 ) -> Result<(), CoreError> {
235 let narrowed = effective_bounds(&self.config().envelope, Some(&manifest));
236 self.stores()
237 .prints
238 .put_manifest(print_id, manifest)
239 .await?;
240 for narrowing in narrowed.narrowings {
241 self.stores()
242 .prints
243 .record_narrowing(print_id, narrowing)
244 .await?;
245 }
246 Ok(())
247 }
248
249 async fn open_bounded_intervention(
256 &self,
257 print_id: PrintId,
258 action: &PrintAction,
259 issued: &Issued,
260 snapshot: Option<&PrinterSnapshot>,
261 applied_at: Timestamp,
262 ) -> Result<Option<Intervention>, CoreError> {
263 let (Some((adjustable, applied_value)), Some(duration_s)) =
264 (adjustment(action), duration_of(action))
265 else {
266 return Ok(None);
267 };
268 let mut superseded = self.stores().actions.active_interventions(print_id).await?;
269 superseded.retain(|held| held.adjustable == adjustable);
270 superseded.sort_by_key(|held| held.applied_at);
271 let prior_value = superseded.first().map_or_else(
272 || snapshot.and_then(|taken| reported_value(taken, adjustable)),
273 |earliest| earliest.prior_value,
274 );
275 let expires_at =
276 plus_seconds(applied_at, duration_s).map_err(|error| CoreError::Unrepresentable {
277 detail: error.to_string(),
278 })?;
279 let opened = self
280 .stores()
281 .actions
282 .open_intervention(
283 issued.record.id,
284 adjustable,
285 prior_value,
286 applied_value,
287 applied_at,
288 expires_at,
289 )
290 .await?;
291 for earlier in superseded {
292 self.stores()
293 .actions
294 .settle_intervention(
295 earlier.id,
296 InterventionOutcome::Superseded { by: opened.id },
297 )
298 .await?;
299 }
300 Ok(Some(opened))
301 }
302}