printobserver-core 0.4.1

Supervision logic for printobserver.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! The one path an action takes, whoever asked for it.
//!
//! # An action is written into the history as it happens
//!
//! Every request appends an [`ActionRequestedPayload`], carrying the whole
//! action — its own values and the reason the actor gave for it. A rejection
//! appends the decision beside it and an execution appends what it opened. The
//! reason a mutating request is required to carry is what makes the history
//! worth reading afterwards, and a reason that reached the `actions` table and
//! no further would be a reason nothing could ever read back.
//!
//! The agent, an operator, the command line and a client all arrive here. There
//! is no second path: [`Supervisor::request_action`] gathers what the decision
//! is taken from, takes it, and hands the pair to
//! [`Supervisor::issue_decided_action`], which is the only function of this
//! crate that reaches an action method of the printer port.

use crate::records::{
    AcknowledgementDisposition, ActionRecord, ActionRequest, Actor, ActorClass, Intervention,
    InterventionOutcome, PolicyDecision, Preflight, PrintAction, PrintRecord,
};
use printobserver_printer_api::Adjustable;
use printobserver_printer_api::{PrinterSnapshot, PrinterState};
use printobserver_types::{EventBody, EventSource, FileName, PrintId, Timestamp};

use crate::bounds::{Bounds, effective_bounds};
use crate::clock::plus_seconds;
use crate::decision::{DecisionInput, adjustment, changes_the_machine, decide};
use crate::error::CoreError;
use crate::kinds::{
    ActionExecutedPayload, ActionRejectedPayload, ActionRequestedPayload, PreflightCheckedPayload,
    agent_source, operator_source, system_source,
};
use crate::store::EventDraft;
use crate::supervisor::{Issued, Supervisor};

/// What became of one request, from the decision through to its intervention.
#[derive(Debug, Clone, PartialEq)]
pub struct ActionOutcome {
    /// The record of the request and the decision taken on it.
    pub record: ActionRecord,
    /// What the printer made of it, absent when it was rejected.
    pub executed: Option<Result<(), printobserver_printer_api::PrinterError>>,
    /// The bounded intervention it opened, when it opened one.
    pub intervention: Option<Intervention>,
}

impl ActionOutcome {
    /// The decision policy took on the request.
    #[must_use]
    pub const fn decision(&self) -> &PolicyDecision {
        &self.record.decision
    }
}

/// Where an event about one actor's action came from.
pub(crate) fn source_of(actor: &Actor) -> EventSource {
    match actor.class() {
        ActorClass::Agent => agent_source(),
        ActorClass::Operator => operator_source(),
        ActorClass::System => system_source(),
    }
}

/// How long a bounded change stands for, when the request bounds it.
fn duration_of(action: &PrintAction) -> Option<i64> {
    match action {
        PrintAction::SetFeedrateFactor { duration_s, .. }
        | PrintAction::SetFlowrateFactor { duration_s, .. }
        | PrintAction::SetToolTargetC { duration_s, .. }
        | PrintAction::SetBedTargetC { duration_s, .. }
        | PrintAction::SetFanPercent { duration_s, .. } => *duration_s,
        PrintAction::Pause { .. }
        | PrintAction::Resume { .. }
        | PrintAction::Cancel { .. }
        | PrintAction::StartPrint { .. }
        | PrintAction::AcknowledgeFailure { .. } => None,
    }
}

/// What the printer reported for one adjustable, when it reported anything.
///
/// Absent means the printer reported no value for it, which is what makes an
/// intervention's expiry restore nothing and say so rather than writing a
/// guessed default onto the machine.
#[must_use]
pub fn reported_value(snapshot: &PrinterSnapshot, adjustable: Adjustable) -> Option<f64> {
    let reported = match adjustable {
        Adjustable::Feedrate => snapshot.feedrate_factor,
        Adjustable::Flowrate => snapshot.flowrate_factor,
        Adjustable::Fan => snapshot.fan_percent,
        Adjustable::BedTarget => snapshot.bed.as_ref().and_then(|heater| heater.target_c),
        Adjustable::ToolTarget { tool } => usize::try_from(tool)
            .ok()
            .and_then(|index| snapshot.tools.get(index))
            .and_then(|heater| heater.target_c),
    };
    reported.map(|value| value.value())
}

impl Supervisor {
    /// Request one action against one print.
    ///
    /// The same call an operator's action makes, an agent's action makes and a
    /// client's action makes. A rejected request reaches no action method of
    /// the printer port at all, and the rejection is persisted carrying its own
    /// reason so that the caller can ask again inside the range.
    ///
    /// # Errors
    ///
    /// Returns the store's own error when the decision, the execution or the
    /// intervention could not be recorded. A refusal by the printer is not an
    /// error: it is recorded and reported in [`ActionOutcome::executed`].
    ///
    /// A start may be made against a print other than `print_id`: it is
    /// recorded against [`Self::print_to_start`]'s, which the answer's record
    /// names.
    pub async fn request_action(
        &self,
        print_id: PrintId,
        action: PrintAction,
    ) -> Result<ActionOutcome, CoreError> {
        // A start that will need an analysis waits for it before it holds the
        // resolution of prints, so the wait holds up no alert and no read.
        if let PrintAction::StartPrint { file_name, .. } = &action {
            // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
            self.await_analysis(file_name, action.actor()).await?;
        }
        // A start holds every resolution of a print from the read that chooses
        // its print until the printer has been asked to start: a read between
        // the two would find the machine idle and close the print just opened.
        let (_starting, print_id) = match &action {
            PrintAction::StartPrint { file_name, .. } => {
                let resolving = self.resolving().await;
                (
                    Some(resolving),
                    self.print_to_start(print_id, file_name).await?,
                )
            }
            _ => (None, print_id),
        };
        let requested_at = self.clock().now();
        let actor = action.actor().clone();
        let print = self.stores().prints.print(print_id).await?;
        let bounds = self.bounds_for(print.as_ref(), print_id).await?;
        let snapshot = self.read_snapshot().await.ok();
        let mut decision = decide(&DecisionInput {
            action: &action,
            actor: &actor,
            requested_at,
            print: print.as_ref(),
            printer_state: snapshot.as_ref().map(|taken| &taken.connection),
            bounds: &bounds.effective,
            envelope: &self.config().envelope,
            last_agent_action: self.last_agent_action(print_id),
        });
        let preflight = self
            .check_accepted(&action, print.as_ref(), &mut decision)
            .await?;
        let request = ActionRequest {
            action: action.clone(),
            actor: actor.clone(),
            requested_at,
        };
        let issued = self.issue_decided_action(request, decision).await?;
        let source = source_of(&actor);
        self.write_decision_down(print_id, &source, &action, &issued, preflight.as_ref())
            .await?;
        if !issued.succeeded() {
            return Ok(ActionOutcome {
                record: issued.record,
                executed: issued.executed,
                intervention: None,
            });
        }
        // Only a change to the machine starts the agent's interval again.
        if actor.class() == ActorClass::Agent && changes_the_machine(action.kind()) {
            self.note_agent_action(print_id, requested_at);
        }
        self.follow_the_detectors_pause(print_id, &action, snapshot.as_ref());
        if let PrintAction::StartPrint {
            manifest,
            file_name,
            ..
        } = &action
        {
            self.attach_manifest(print_id, manifest.clone()).await?;
            self.follow_the_start(print_id, file_name, &issued, preflight)
                .await?;
        }
        let intervention = self
            .open_bounded_intervention(print_id, &action, &issued, snapshot.as_ref(), requested_at)
            .await?;
        self.append_action_event(
            print_id,
            source,
            EventBody::of(&ActionExecutedPayload {
                action_id: issued.record.id,
                intervention_id: intervention.as_ref().map(|opened| opened.id),
            })?,
        )
        .await?;
        Ok(ActionOutcome {
            record: issued.record,
            executed: issued.executed,
            intervention,
        })
    }

    /// Write one request into its print's history: what was asked for, the
    /// filament check a start was held to, and the rejection when there was
    /// one.
    async fn write_decision_down(
        &self,
        print_id: PrintId,
        source: &EventSource,
        action: &PrintAction,
        issued: &Issued,
        preflight: Option<&Preflight>,
    ) -> Result<(), CoreError> {
        self.append_action_event(
            print_id,
            source.clone(),
            EventBody::of(&ActionRequestedPayload {
                action_id: issued.record.id,
                action: action.clone(),
                actor: action.actor().clone(),
            })?,
        )
        .await?;
        // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
        if let Some(checked) = preflight {
            self.append_action_event(
                print_id,
                source.clone(),
                EventBody::of(&PreflightCheckedPayload {
                    preflight: checked.clone(),
                    action_id: Some(issued.record.id),
                })?,
            )
            .await?;
        }
        if let PolicyDecision::Rejected(_) = &issued.record.decision {
            self.append_action_event(
                print_id,
                source.clone(),
                EventBody::of(&ActionRejectedPayload {
                    action_id: issued.record.id,
                    decision: issued.record.decision.clone(),
                })?,
            )
            .await?;
        }
        Ok(())
    }

    /// What an accepted request is checked against beyond the decision, and
    /// what it reads first.
    ///
    /// A start is held to the filament check ([`crate::preflight`]), whose
    /// refusal replaces the decision and whose finding is answered. A cancel
    /// reads where the print had got first: `OctoPrint` clears a job's
    /// position as it cancels, so this is where the print is known to stop.
    async fn check_accepted(
        &self,
        action: &PrintAction,
        print: Option<&PrintRecord>,
        decision: &mut PolicyDecision,
    ) -> Result<Option<Preflight>, CoreError> {
        if *decision != PolicyDecision::Accepted {
            return Ok(None);
        }
        match action {
            PrintAction::StartPrint {
                file_name,
                override_filament_check,
                actor,
                ..
            } => {
                let (checked, refusal) = self
                    .check_start(file_name, actor, (*override_filament_check).into())
                    .await?;
                if let Some(reason) = refusal {
                    *decision = PolicyDecision::Rejected(reason);
                }
                Ok(Some(checked))
            }
            PrintAction::Cancel { .. } => {
                // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
                if let Some(print) = print
                    && let Ok(job) = self.read_job().await
                {
                    self.record_position_from(print, &job, self.clock().now())
                        .await?;
                }
                Ok(None)
            }
            _ => Ok(None),
        }
    }

    /// What a start the printer took records: that this supervisor saw its
    /// print begin, and the print's `print_started` naming the start, the
    /// spools loaded and the check it passed — unless the print has one.
    // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
    async fn follow_the_start(
        &self,
        print_id: PrintId,
        file_name: &FileName,
        issued: &Issued,
        preflight: Option<Preflight>,
    ) -> Result<(), CoreError> {
        self.note_seen_running(print_id);
        if self.print_started_of(print_id).await?.is_none() {
            self.record_print_started(
                print_id,
                Some(file_name.as_str().to_owned()),
                Some(issued.record.id),
                preflight,
            )
            .await?;
        }
        Ok(())
    }

    /// The print a start is made against.
    ///
    /// Starting a job begins a print of its own. So the printer is read first,
    /// which closes every open print that read shows is over exactly as any
    /// other read does ([`crate::listing`]), and when no print is open after it
    /// one is opened for the file the start names — with no provider
    /// identifier, and no sighting of a job until a read finds it running. A
    /// print still open after the read is the one asked for, as it always was:
    /// a printer running or holding a job refuses a start whichever print it
    /// is recorded against.
    async fn print_to_start(
        &self,
        asked: PrintId,
        file_name: &FileName,
    ) -> Result<PrintId, CoreError> {
        if let Some(observed) = self.observe_job().await {
            self.settle_open_prints(&observed).await?;
        }
        if !self.stores().prints.open_prints().await?.is_empty() {
            return Ok(asked);
        }
        let opened = self
            .stores()
            .prints
            .open_print(None, Some(file_name.as_str().to_owned()))
            .await?;
        Ok(opened.id)
    }

    /// What one action that went through does to a pause the detector made.
    ///
    /// An agent's adjustment to a print the detector's pause is holding earns
    /// the print its resume ([`crate::detector`]); an agent's acknowledgement
    /// with `stop` leaves the pause for a person; and a print somebody else
    /// resumed or cancelled is no longer the detector's to hold.
    fn follow_the_detectors_pause(
        &self,
        print_id: PrintId,
        action: &PrintAction,
        snapshot: Option<&PrinterSnapshot>,
    ) {
        if !self.detector_paused(print_id) {
            return;
        }
        let paused = snapshot.is_some_and(|taken| taken.connection == PrinterState::Paused);
        match (action.actor().class(), action) {
            (ActorClass::Agent, _) if adjustment(action).is_some() && paused => {
                self.note_adjustment_while_paused(print_id, action.reason());
            }
            (
                ActorClass::Agent,
                PrintAction::AcknowledgeFailure {
                    disposition: AcknowledgementDisposition::Stop,
                    ..
                },
            )
            | (_, PrintAction::Resume { .. } | PrintAction::Cancel { .. }) => {
                self.forget_detector_pause(print_id);
            }
            _ => {}
        }
    }

    /// Append one event about an action, sourced from whoever asked for it.
    async fn append_action_event(
        &self,
        print_id: PrintId,
        source: EventSource,
        body: EventBody,
    ) -> Result<(), CoreError> {
        self.stores()
            .events
            .append_event(EventDraft {
                print_id: Some(print_id),
                source,
                received_at: self.clock().now(),
                body,
                raw: None,
            })
            .await?;
        Ok(())
    }

    /// The bounds in force for one print: the envelope, narrowed by its manifest.
    pub(crate) async fn bounds_for(
        &self,
        print: Option<&PrintRecord>,
        print_id: PrintId,
    ) -> Result<Bounds, CoreError> {
        let manifest = if print.is_some() {
            self.stores().prints.manifest(print_id).await?
        } else {
            None
        };
        Ok(effective_bounds(&self.config().envelope, manifest.as_ref()))
    }

    /// Store a print's manifest, recording every range it asked wider than the
    /// envelope's, so that nobody has to wonder later which bound applied.
    async fn attach_manifest(
        &self,
        print_id: PrintId,
        manifest: crate::records::JobManifest,
    ) -> Result<(), CoreError> {
        let narrowed = effective_bounds(&self.config().envelope, Some(&manifest));
        self.stores()
            .prints
            .put_manifest(print_id, manifest)
            .await?;
        for narrowing in narrowed.narrowings {
            self.stores()
                .prints
                .record_narrowing(print_id, narrowing)
                .await?;
        }
        Ok(())
    }

    /// Open the bounded intervention an accepted adjustment asked for.
    ///
    /// An adjustable changed again before its expiry supersedes the earlier
    /// intervention rather than stacking with it, and the later one carries the
    /// earlier's prior value forward so that restoring still reaches the value
    /// the print started from.
    async fn open_bounded_intervention(
        &self,
        print_id: PrintId,
        action: &PrintAction,
        issued: &Issued,
        snapshot: Option<&PrinterSnapshot>,
        applied_at: Timestamp,
    ) -> Result<Option<Intervention>, CoreError> {
        let (Some((adjustable, applied_value)), Some(duration_s)) =
            (adjustment(action), duration_of(action))
        else {
            return Ok(None);
        };
        let mut superseded = self.stores().actions.active_interventions(print_id).await?;
        superseded.retain(|held| held.adjustable == adjustable);
        superseded.sort_by_key(|held| held.applied_at);
        let prior_value = superseded.first().map_or_else(
            || snapshot.and_then(|taken| reported_value(taken, adjustable)),
            |earliest| earliest.prior_value,
        );
        let expires_at =
            plus_seconds(applied_at, duration_s).map_err(|error| CoreError::Unrepresentable {
                detail: error.to_string(),
            })?;
        let opened = self
            .stores()
            .actions
            .open_intervention(
                issued.record.id,
                adjustable,
                prior_value,
                applied_value,
                applied_at,
                expires_at,
            )
            .await?;
        for earlier in superseded {
            self.stores()
                .actions
                .settle_intervention(
                    earlier.id,
                    InterventionOutcome::Superseded { by: opened.id },
                )
                .await?;
        }
        Ok(Some(opened))
    }
}