Skip to main content

printobserver_core/
listing.rs

1//! Every print this system holds, and the one the printer is running now.
2//!
3//! A print is otherwise known here only once a provider reports on it, and an
4//! identifier nothing lists is one nobody can act with. So reading the listing
5//! also **adopts** the job the printer reports: when that job is in one of
6//! [`ACTIVE_STATES`] and no open print records it, one is opened for it, and
7//! the listing names it active. An alert about the same job later attaches its
8//! provider's identifier to that print rather than opening a second, which is
9//! [`Supervisor::handle_event`]'s own rule.
10//!
11//! # Which open print a running job is
12//!
13//! The printer names a job by its file and by nothing else, so a file name
14//! alone cannot tell one job from a later one of the same file. What can is how
15//! long each has been printing. `OctoPrint` reports a job's running time as the
16//! time since it started less every pause it has **resumed** from: a pause
17//! counts while it lasts, and comes back out at the resume. So the running time
18//! a read finds a job *printing* at is the time it has spent printing, and that
19//! only grows; the one a read finds it *paused* at is at least that.
20//!
21//! A print records the longest running time any read found its job printing at
22//! ([`PrintRecord::job_print_time_s`]) and, from the latest read that found its
23//! job printing or paused, when that read put the job's start
24//! ([`PrintRecord::job_started_at`] — the read's instant less the running time
25//! it reported, which a resume moves later, so a read putting it further than
26//! the tolerance from the one recorded resets it).
27//! An open print of the running job's file is that job unless the job reports
28//! a running time more than [`JOB_IDENTITY_TOLERANCE_S`] short of the longest
29//! the print recorded: a job cannot have printed for less than it had already
30//! printed, so that one is a later job, and the print is closed with
31//! [`REPLACED_REASON`] before the running job is given a print of its own. The
32//! tolerance is printing time, and a pause, observed or not, shortens no job's
33//! printing time, so no pause splits a print.
34//!
35//! Where either side reports no running time — a print recorded before these
36//! were, one an alert or a start opened before any read saw its job, one only
37//! ever seen paused, or a job whose printer reports none — the file name is
38//! the whole of what is known, and it decides as it did before.
39//!
40//! What this cannot tell apart, and so keeps as one print: a later job that,
41//! when it is first read, has printed for as long as the earlier job was last
42//! seen printing, less the tolerance, or longer. An earlier job paused between
43//! two reads and resumed reports exactly that, because the pause is taken back
44//! out of its running time at the resume; nothing a read returns tells the two
45//! apart.
46//!
47//! # A read that finds the job over closes its print
48//!
49//! A print ends when the printer is seen not to be running it, whoever was
50//! looking. A supervision turn that reads a terminal state closes its print,
51//! and so does every read this module makes and the status and context reads
52//! make: a job no longer in one of [`ACTIVE_STATES`] closes the open prints it
53//! could be, through the same close-out a turn takes. A printer that cannot be
54//! read closes nothing, and neither does a state this vocabulary does not name,
55//! because neither is a finding that the job is over.
56//!
57//! A close-out from a read never waits on a supervision turn: the read may be
58//! the agent's own, made from inside that turn. So a print whose turn is
59//! running is left for that turn, and the next read after it, to close, and a
60//! turn that finds its print ended by the time it holds the print runs nothing.
61//!
62//! # What it asks of the printer
63//!
64//! One read of the job, which is a read rather than an action: nothing here
65//! reaches an action method of the printer port, so adopting a job commands
66//! nothing at the machine. Closing a print is the one exception, and it is the
67//! close-out's rather than this module's: the close-out expires the print's
68//! active interventions, and an expiry may put an adjusted value back through
69//! the same decided path any action takes.
70//!
71//! # What an adopted print records
72//!
73//! The store records a print's state when it opens it and when it ends it, and
74//! at no point between. An adopted print is opened exactly as an alert opens
75//! one, so it records `printing` whether or not the machine is paused at that
76//! moment: what the machine is doing now is the status read's answer, and never
77//! the record's.
78
79use printobserver_printer_api::{JobSnapshot, PrinterState};
80use printobserver_types::{PrintId, Timestamp};
81
82use crate::clock::seconds_between;
83use crate::error::CoreError;
84use crate::records::PrintRecord;
85use crate::supervisor::Supervisor;
86
87/// The job states a printer's job is adoptable in: a job it is running, and a
88/// job it has paused part-way through.
89///
90/// Every other state is a machine with no job in progress — idle, cancelling
91/// the one it had, in error, unreachable, or saying something this vocabulary
92/// does not name — and a print opened for one of those would be a record of a
93/// job that is not there.
94pub const ACTIVE_STATES: [PrinterState; 2] = [PrinterState::Printing, PrinterState::Paused];
95
96/// How far, in seconds of printing, a job's reported running time may fall
97/// short of the longest a print recorded for its job and still be that job —
98/// and how much later than a print's recorded start an alert may put its job's
99/// start and still be that print's.
100///
101/// A running time is whole seconds read off the printer's clock at an instant
102/// read off another, and `OctoPrint` reports a job it is still *pausing* — the
103/// head finishing its move — as printing with the pause already counting, so
104/// two reads of one job do not agree to the second. Two jobs of one file
105/// cannot be closer together than the time it takes to print one and start
106/// the next.
107pub const JOB_IDENTITY_TOLERANCE_S: i64 = 120;
108
109/// Why a print is ended when a later job of its file is found running.
110pub const REPLACED_REASON: &str = "a later job of the same file replaced it";
111
112/// The printer's job, as one read observed it.
113#[derive(Debug, Clone, PartialEq)]
114pub struct ObservedJob {
115    /// What the printer reported.
116    pub job: JobSnapshot,
117    /// The instant the report was read at.
118    pub observed_at: Timestamp,
119}
120
121impl ObservedJob {
122    /// Whether the printer is running this job, or has paused it part-way.
123    #[must_use]
124    pub fn is_active(&self) -> bool {
125        ACTIVE_STATES.contains(&self.job.state)
126    }
127
128    /// Whether the printer reports this job over.
129    #[must_use]
130    pub const fn has_ended(&self) -> bool {
131        is_over(&self.job.state)
132    }
133
134    /// The running time the printer reported for this job, when it reported
135    /// one a job can have run for.
136    ///
137    /// A negative count is no running time at all, so it is read as none
138    /// rather than as a job that began after it was observed: the file name is
139    /// then the whole of what is known, as it is for a printer reporting none.
140    #[must_use]
141    pub fn running_time_s(&self) -> Option<i64> {
142        self.job.print_time_s.filter(|seconds| *seconds >= 0)
143    }
144
145    /// When the job began, less every pause it has resumed from: the instant
146    /// it was observed, less the running time the printer reported for it
147    /// then. Unknown when it reported none.
148    #[must_use]
149    pub fn started_at(&self) -> Option<Timestamp> {
150        let running = self.running_time_s()?;
151        self.observed_at.plus_seconds(-running).ok()
152    }
153
154    /// How long the job has spent printing, when this read found it printing
155    /// and reporting a running time; a paused job's running time counts the
156    /// pause, so it is not one.
157    #[must_use]
158    pub fn printing_time_s(&self) -> Option<i64> {
159        (self.job.state == PrinterState::Printing)
160            .then(|| self.running_time_s())
161            .flatten()
162    }
163}
164
165/// Whether a running job of a print's file may be the job that print records.
166///
167/// Not when the job reports a running time more than
168/// [`JOB_IDENTITY_TOLERANCE_S`] short of the longest the print recorded for its
169/// job; otherwise, and whenever either side reports none, it may — the file
170/// name the caller already compared is then the whole of what is known.
171#[must_use]
172pub fn may_be_same_job(print: &PrintRecord, observed: &ObservedJob) -> bool {
173    match (print.job_print_time_s, observed.running_time_s()) {
174        (Some(longest), Some(running)) => {
175            running.saturating_add(JOB_IDENTITY_TOLERANCE_S) >= longest
176        }
177        _ => true,
178    }
179}
180
181/// Whether a job a provider says began at `started_at` may be the job a print
182/// of its file records.
183///
184/// Not when it began more than [`JOB_IDENTITY_TOLERANCE_S`] after the start
185/// the print records. Earlier is no objection: a resume moves the recorded
186/// start later than the job's own, and a provider records the job's own.
187#[must_use]
188pub fn may_have_started_it(print: &PrintRecord, started_at: Option<Timestamp>) -> bool {
189    match (print.job_started_at, started_at) {
190        (Some(recorded), Some(started)) => {
191            seconds_between(recorded, started) <= JOB_IDENTITY_TOLERANCE_S
192        }
193        _ => true,
194    }
195}
196
197/// Whether a job in this state is over: a state the printer's vocabulary
198/// names, and not one of [`ACTIVE_STATES`].
199#[must_use]
200pub const fn is_over(state: &PrinterState) -> bool {
201    !matches!(
202        state,
203        PrinterState::Printing | PrinterState::Paused | PrinterState::Unknown(_)
204    )
205}
206
207/// The reason a print ends with when the printer was seen in `state`.
208pub(crate) fn reached_reason(state: &PrinterState) -> String {
209    format!("the print reached {state:?}")
210}
211
212/// Every print, and the one the printer is running now.
213#[derive(Debug, Clone, PartialEq)]
214pub struct PrintListing {
215    /// Every print, ended or not, most recently opened first.
216    pub prints: Vec<PrintRecord>,
217    /// The print the printer's job belongs to, present exactly when the printer
218    /// reports a job in one of [`ACTIVE_STATES`] with a file name.
219    pub active: Option<PrintId>,
220}
221
222/// What one observation of the printer's job settled among the open prints.
223#[derive(Debug, Clone, Default, PartialEq)]
224pub struct Settled {
225    /// The open print the running job is, when one is.
226    pub running: Option<PrintRecord>,
227    /// Every print this observation closed.
228    pub closed: Vec<PrintId>,
229}
230
231impl Supervisor {
232    /// Every print, and the one the printer's job belongs to — **opening** one
233    /// for that job when no open print records it, and **closing** the open
234    /// prints the printer's job shows are over.
235    ///
236    /// Named for the half a caller sees, because it is not only a read: the
237    /// listing is what a caller asked for, and the print it may open is what
238    /// makes that listing name the job at all. A printer that cannot be read is
239    /// a listing with nothing active, and nothing closed, rather than a
240    /// failure: the stored prints are still the answer to which prints there
241    /// are.
242    ///
243    /// # Errors
244    ///
245    /// Returns the store's own error when the prints could not be read, or a
246    /// print could not be opened or closed.
247    pub async fn list_and_adopt_prints(&self) -> Result<PrintListing, CoreError> {
248        let _resolving = self.resolving().await;
249        let Some(observed) = self.observe_job().await else {
250            return Ok(PrintListing {
251                prints: self.stores().prints.prints().await?,
252                active: None,
253            });
254        };
255        let active = self.settle_and_adopt(&observed).await?;
256        Ok(PrintListing {
257            prints: self.stores().prints.prints().await?,
258            active,
259        })
260    }
261
262    /// Settle the open prints against one observation of the printer's job,
263    /// adopt that job when it is active and no open print is it, and answer
264    /// the print it is.
265    ///
266    /// The caller holds resolution from before it read that job.
267    pub(crate) async fn settle_and_adopt(
268        &self,
269        observed: &ObservedJob,
270    ) -> Result<Option<PrintId>, CoreError> {
271        let settled = self.settle_open_prints(observed).await?;
272        Ok(match (settled.running, &observed.job.file_name) {
273            (Some(running), _) => Some(running.id),
274            (None, Some(file_name)) if observed.is_active() => {
275                Some(self.open_running_print(observed, file_name).await?.id)
276            }
277            (None, _) => None,
278        })
279    }
280
281    /// Close every open print the printer's job shows is over, and record the
282    /// running job's start on the open print it is.
283    ///
284    /// What a supervisor does with the printer as it starts, before it adopts
285    /// what is left open: a print that ended while nothing was watching is not
286    /// one to go on watching. A printer that cannot be read settles nothing.
287    ///
288    /// # Errors
289    ///
290    /// Returns the store's own error when the open prints could not be read or
291    /// a print could not be closed.
292    pub async fn settle_with_printer(&self) -> Result<Settled, CoreError> {
293        let _resolving = self.resolving().await;
294        match self.observe_job().await {
295            Some(observed) => self.settle_open_prints(&observed).await,
296            None => Ok(Settled::default()),
297        }
298    }
299
300    /// Read the printer's job, and the instant it was read at; nothing when it
301    /// cannot be read.
302    pub(crate) async fn observe_job(&self) -> Option<ObservedJob> {
303        let job = self.read_job().await.ok()?;
304        Some(ObservedJob {
305            job,
306            observed_at: self.clock().now(),
307        })
308    }
309
310    /// Settle the open prints against one observation of the printer's job.
311    ///
312    /// A job that is over closes every open print, since one printer runs one
313    /// job and it is running none. A running job is the most recently opened
314    /// open print of its file that may be the same job; every open print of
315    /// its file that cannot be is closed as replaced. Prints of other files are
316    /// left as they are.
317    pub(crate) async fn settle_open_prints(
318        &self,
319        observed: &ObservedJob,
320    ) -> Result<Settled, CoreError> {
321        let mut settled = Settled::default();
322        let open = self.stores().prints.open_prints().await?;
323        if observed.has_ended() {
324            let reason = reached_reason(&observed.job.state);
325            for print in open {
326                if self
327                    .close_out_from_read(
328                        print.id,
329                        &observed.job.state,
330                        &reason,
331                        Some(&observed.job),
332                    )
333                    .await?
334                {
335                    settled.closed.push(print.id);
336                }
337            }
338            return Ok(settled);
339        }
340        let Some(file_name) = observed
341            .job
342            .file_name
343            .as_ref()
344            .filter(|_| observed.is_active())
345        else {
346            return Ok(settled);
347        };
348        // Most recently opened first, so the first that may be the job is the
349        // most recent of them.
350        for print in open
351            .into_iter()
352            .filter(|print| print.file_name.as_ref() == Some(file_name))
353        {
354            if !may_be_same_job(&print, observed) {
355                // The earlier job ended before this one began, and a printer
356                // begins a job only from idle.
357                if self
358                    .close_out_from_read(
359                        print.id,
360                        &PrinterState::Operational,
361                        REPLACED_REASON,
362                        None,
363                    )
364                    .await?
365                {
366                    settled.closed.push(print.id);
367                }
368            } else if settled.running.is_none() {
369                let running = self.record_sighting(print, observed).await?;
370                self.note_running(&running, observed).await?;
371                settled.running = Some(running);
372            }
373        }
374        Ok(settled)
375    }
376
377    /// Record what one read saw of the job a print was matched to.
378    ///
379    /// The start a print records is moved only when a read puts the job's
380    /// start more than [`JOB_IDENTITY_TOLERANCE_S`] from it, as a resume after
381    /// a longer pause does: a whole-second running time read at an instant off
382    /// another clock puts one job's start a second or so apart from one read to
383    /// the next, and a record rewritten at every read for that would be a
384    /// record of the reads rather than of the job. Nothing is written when the
385    /// read saw nothing the print does not already carry.
386    async fn record_sighting(
387        &self,
388        print: PrintRecord,
389        observed: &ObservedJob,
390    ) -> Result<PrintRecord, CoreError> {
391        let Some(seen) = observed.started_at() else {
392            return Ok(print);
393        };
394        let printing = observed.printing_time_s();
395        let started_at = match print.job_started_at {
396            Some(held) if seconds_between(held, seen).abs() <= JOB_IDENTITY_TOLERANCE_S => held,
397            _ => seen,
398        };
399        if print.job_started_at == Some(started_at) && printing <= print.job_print_time_s {
400            return Ok(print);
401        }
402        Ok(self
403            .stores()
404            .prints
405            .record_job_sighting(print.id, started_at, printing)
406            .await?)
407    }
408
409    /// Open a print for the job the printer is running, recording what the
410    /// read saw of it.
411    async fn open_running_print(
412        &self,
413        observed: &ObservedJob,
414        file_name: &str,
415    ) -> Result<PrintRecord, CoreError> {
416        let opened = self
417            .stores()
418            .prints
419            .open_print(None, Some(file_name.to_owned()))
420            .await?;
421        // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
422        let opened = self.record_sighting(opened, observed).await?;
423        self.record_print_started(opened.id, Some(file_name.to_owned()), None, None)
424            .await?;
425        self.note_running(&opened, observed).await?;
426        Ok(opened)
427    }
428
429    /// Note that a read found a print's job printing or paused, and record how
430    /// far into its file the job had got: `OctoPrint` clears a job's position
431    /// when it is cancelled or fails, so every read that finds it running is
432    /// where the print is next known to have stopped.
433    // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
434    async fn note_running(
435        &self,
436        print: &PrintRecord,
437        observed: &ObservedJob,
438    ) -> Result<(), CoreError> {
439        self.note_seen_running(print.id);
440        self.record_position_from(print, &observed.job, observed.observed_at)
441            .await?;
442        Ok(())
443    }
444
445    /// Close one print a read found over, unless a supervision turn holds it.
446    ///
447    /// Answers whether this closed it: a print a turn holds is that turn's, and
448    /// one already ended has nothing left to close.
449    ///
450    /// `closing_job` is the read that found it over, when that read was of
451    /// this print's job rather than of a later one.
452    pub(crate) async fn close_out_from_read(
453        &self,
454        print_id: PrintId,
455        state: &PrinterState,
456        reason: &str,
457        closing_job: Option<&JobSnapshot>,
458    ) -> Result<bool, CoreError> {
459        let Some(_turn) = self.turns().try_acquire(print_id) else {
460            return Ok(false);
461        };
462        self.close_out_print(print_id, state, reason, closing_job)
463            .await
464    }
465}