Skip to main content

egui_pop_model/
jobs.rs

1//! Jobs: the application's background work, folded from the job events
2//! its host publishes on the `pop.job.event` point (ADR 0010), each
3//! typed by a [`JobEventKind`]. egui-pop never runs jobs and never polls
4//! for them: the host publishes, [`Jobs`] follows, and the views (bars,
5//! the status bar, the jobs centre) draw what it holds. The table names
6//! each kind by the label it is journaled under; the model reads the
7//! kind, never a name.
8//!
9//! <div class="warning">Experimental: may change in any release
10//! (docs/stability.md).</div>
11//!
12//! | Kind (journal label) | Data |
13//! |---|---|
14//! | `job.started` | `id`, `title`, `kind`, `badge` (a symbol before the title, [`JobBadge`]), `parent`, `weight` (its share of its parent), `total` (none: indeterminate), `steps` (`[{id, title, weight}]` or names), `cancellable` (true), `pausable` (false), `retryable` (true), `owner` (the plugin the job runs for), `command` (the command that started it) |
15//! | `job.progress` | `id`, `done`, `total`, `failed`, `skipped`, `item` (the current item), `item_progress` (0 to 1), `phase`, `step` (the current step), `step_done`, `step_total`, `estimate` (the host's own fraction, 0 to 1), `badge` (`null` takes it away) |
16//! | `job.item_failed` | `id`, `item`, `error` (the job goes on) |
17//! | `job.paused`, `job.resumed` | `id` |
18//! | `job.cancelling` | `id`, `reason` (why, when it was not the user) |
19//! | `job.failed` | `id`, `error` |
20//! | `job.finished` | `id`, `actions` (`[{title, command, args}]`) |
21//! | `job.cancelled` | `id`, `reason` (why, when it was not the user) |
22//! | `job.orphaned` | `id`, `plugin`, `reason` (published by egui-pop: the job's plugin is disconnected and the job goes on) |
23//! | `job.adopted` | `plugin`, `jobs` (their ids; published by egui-pop: the plugin is back and its orphaned jobs are its own again) |
24//! | `job.log` | `id`, `text` (lines of the job's log) |
25//!
26//! **A job has an owner** when its `job.started` names one: `owner`, the
27//! plugin it runs for, or `command`, the command that started it; a job
28//! naming neither belongs to the plugin that published it, when its
29//! events' source is a plugin. When that plugin is disconnected (ADR
30//! 0028, [`Jobs::left_by`]) a job naming it that can be cancelled is
31//! cancelled through the host's `job.cancel`, with the reason
32//! ([`Job::reason`]); any other is kept and marked orphaned
33//! ([`Job::orphaned`], from `job.orphaned`) until it ends, starts again
34//! or its plugin is back ([`Jobs::adopt`]). An orphaned job can be
35//! dismissed while it goes on: nothing may ever end it.
36//!
37//! A `job.started` for a job already known starts it again (a retry):
38//! its progress is reset, its log kept, its finished children
39//! forgotten.
40//!
41//! **Forgetting a job** ([`Jobs::dismiss`], [`Jobs::clear_finished`],
42//! the history's trim) takes it and its ended descendants away; a
43//! descendant still going on is kept and becomes a top-level job (its
44//! `parent` cleared), so it stays in sight and ends on its own. A job
45//! forgotten leaves a tombstone, kept [`TOMBSTONE_SECS`] seconds (by the
46//! events' clock) and at most [`TOMBSTONES`] of them: an event for it
47//! arriving late (a progress, a log line, its end) is dropped rather
48//! than making the job up again; a `job.started` for it is a new run
49//! and lifts the tombstone.
50//!
51//! **Every job carries an estimated overall fraction** ([`Job::fraction`],
52//! 0 to 1), or none while it cannot estimate (indeterminate):
53//!
54//! - a job with sub-steps (declared `steps`, and child jobs naming it as
55//!   `parent`) rolls them up, each weighted by its estimate (`weight`,
56//!   1 by default): finished steps count whole, the current one by its
57//!   own progress, the others nothing. A parent with a `total` counts its
58//!   children not started yet at weight 1 each;
59//! - otherwise `done` of `total`, the current item's progress included;
60//! - otherwise the host's `estimate`;
61//! - otherwise none: the job is indeterminate until one of these comes,
62//!   and once determinate it never goes back (its last estimate stays);
63//! - [`Jobs::refine`] overrides it (the application's `jobs.estimate`
64//!   hook, ADR 0011).
65//!
66//! Time left ([`Job::eta`]) comes from the rate of that fraction, an
67//! exponential moving average over the times events arrived at, given
68//! by an injected clock (`now`): it is not given before [`ETA_AFTER`]
69//! seconds.
70//!
71//! Cancel, pause, resume and retry are commands the host runs
72//! (`job.cancel`, `job.pause`, `job.resume`, `job.retry`, each with
73//! `{ "id" }`): the model follows their `command.dispatched` and
74//! `command.failed` events too, so a job shows "cancelling" from the
75//! moment it was asked until the host says it is cancelled, and a
76//! refused request says why.
77//!
78//! ```
79//! use egui_pop_model::jobs::{Incoming, JobEventKind, JobState, Jobs};
80//! use serde_json::json;
81//!
82//! let mut jobs = Jobs::new();
83//! let mut at = |seq, kind, data: serde_json::Value, now| {
84//!     jobs.apply(&Incoming::new(seq, kind, &data), now);
85//! };
86//! at(1, JobEventKind::Started, json!({ "id": "export", "title": "Export", "total": 4 }), 0.0);
87//! at(2, JobEventKind::Progress, json!({ "id": "export", "done": 1, "item": "a.raw" }), 1.0);
88//! let job = jobs.get("export").unwrap();
89//! assert_eq!(job.state, JobState::Running);
90//! assert_eq!(job.fraction, Some(0.25));
91//! assert_eq!(job.item.as_deref(), Some("a.raw"));
92//! ```
93
94use std::collections::{BTreeMap, BTreeSet, VecDeque};
95
96use serde::{Deserialize, Serialize};
97use serde_json::{Value as Json, json};
98
99use crate::admin::{Tone, tone_named};
100
101/// A job started (or started again).
102pub const STARTED: &str = "job.started";
103/// A job moved on.
104pub const PROGRESS: &str = "job.progress";
105/// One item failed; the job goes on.
106pub const ITEM_FAILED: &str = "job.item_failed";
107pub const PAUSED: &str = "job.paused";
108pub const RESUMED: &str = "job.resumed";
109/// Cancelling was accepted; the job winds down.
110pub const CANCELLING: &str = "job.cancelling";
111pub const FAILED: &str = "job.failed";
112pub const FINISHED: &str = "job.finished";
113pub const CANCELLED: &str = "job.cancelled";
114/// The job's plugin is disconnected and the job goes on (published by
115/// egui-pop, not by the host).
116pub const ORPHANED: &str = "job.orphaned";
117/// The plugin of orphaned jobs is back: `{ "plugin", "jobs": [ids] }`
118/// (published by egui-pop, not by the host).
119pub const ADOPTED: &str = "job.adopted";
120/// Lines of a job's log.
121pub const LOG: &str = "job.log";
122
123/// The commands the host runs on a job, each with `{ "id" }`.
124pub const CMD_CANCEL: &str = "job.cancel";
125pub const CMD_PAUSE: &str = "job.pause";
126pub const CMD_RESUME: &str = "job.resume";
127pub const CMD_RETRY: &str = "job.retry";
128
129/// What a job event says: the kind the host gives when it publishes the
130/// event on `pop.job.event` (egui-pop-api's `JobEvents`). The model folds
131/// events by this kind, never by a journal entry's name; [`name`]
132/// (`job.started`…) is only the label the event is journaled under.
133///
134/// [`name`]: JobEventKind::name
135#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
136#[serde(rename_all = "snake_case")]
137#[non_exhaustive]
138pub enum JobEventKind {
139    /// A job started (or started again).
140    Started,
141    /// A job moved on.
142    Progress,
143    /// One item failed; the job goes on.
144    ItemFailed,
145    Paused,
146    Resumed,
147    /// Cancelling was accepted; the job winds down.
148    Cancelling,
149    Failed,
150    Finished,
151    Cancelled,
152    /// The job's plugin is disconnected and the job goes on (said by
153    /// egui-pop, not by the host).
154    Orphaned,
155    /// The plugin of orphaned jobs is back (said by egui-pop).
156    Adopted,
157    /// Lines of a job's log.
158    Log,
159    /// A job command (`job.cancel`…) was dispatched (said by egui-pop).
160    CommandDispatched,
161    /// A job command ran (said by egui-pop; its cause is the dispatch).
162    CommandDone,
163    /// A job command failed (said by egui-pop; its cause is the dispatch).
164    CommandFailed,
165}
166
167impl JobEventKind {
168    /// Every kind, in declaration order.
169    pub const ALL: [JobEventKind; 15] = [
170        JobEventKind::Started,
171        JobEventKind::Progress,
172        JobEventKind::ItemFailed,
173        JobEventKind::Paused,
174        JobEventKind::Resumed,
175        JobEventKind::Cancelling,
176        JobEventKind::Failed,
177        JobEventKind::Finished,
178        JobEventKind::Cancelled,
179        JobEventKind::Orphaned,
180        JobEventKind::Adopted,
181        JobEventKind::Log,
182        JobEventKind::CommandDispatched,
183        JobEventKind::CommandDone,
184        JobEventKind::CommandFailed,
185    ];
186
187    /// The label the event is journaled under (`job.started`,
188    /// `command.done`…), for the journal's readers; nothing folds by it.
189    pub fn name(self) -> &'static str {
190        match self {
191            JobEventKind::Started => STARTED,
192            JobEventKind::Progress => PROGRESS,
193            JobEventKind::ItemFailed => ITEM_FAILED,
194            JobEventKind::Paused => PAUSED,
195            JobEventKind::Resumed => RESUMED,
196            JobEventKind::Cancelling => CANCELLING,
197            JobEventKind::Failed => FAILED,
198            JobEventKind::Finished => FINISHED,
199            JobEventKind::Cancelled => CANCELLED,
200            JobEventKind::Orphaned => ORPHANED,
201            JobEventKind::Adopted => ADOPTED,
202            JobEventKind::Log => LOG,
203            JobEventKind::CommandDispatched => "command.dispatched",
204            JobEventKind::CommandDone => "command.done",
205            JobEventKind::CommandFailed => "command.failed",
206        }
207    }
208}
209
210/// Time left is not given before a job ran this long (seconds).
211pub const ETA_AFTER: f64 = 3.0;
212/// How many lines of a job's log are kept by default.
213pub const LOG_LINES: usize = 5000;
214/// How many finished jobs are kept by default.
215pub const HISTORY: usize = 100;
216/// How many failed items a job keeps.
217pub const ITEM_ERRORS: usize = 100;
218/// How many forgotten jobs are remembered by default, to drop their late
219/// events.
220pub const TOMBSTONES: usize = 256;
221/// How long (seconds) a forgotten job is remembered by default.
222pub const TOMBSTONE_SECS: f64 = 60.0;
223
224/// How quickly the rate follows the latest events (0 to 1).
225const ALPHA: f64 = 0.3;
226/// How deep jobs may nest (a cycle of parents stops there).
227const DEPTH: usize = 16;
228
229/// Where a job is.
230#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
231#[serde(rename_all = "snake_case")]
232pub enum JobState {
233    #[default]
234    Running,
235    Paused,
236    /// Cancelling was accepted: the job winds down.
237    Cancelling,
238    Done,
239    Failed,
240    Cancelled,
241}
242
243impl JobState {
244    /// Whether the job is still going (running, paused, cancelling).
245    pub fn active(self) -> bool {
246        matches!(
247            self,
248            JobState::Running | JobState::Paused | JobState::Cancelling
249        )
250    }
251
252    pub fn name(self) -> &'static str {
253        match self {
254            JobState::Running => "running",
255            JobState::Paused => "paused",
256            JobState::Cancelling => "cancelling",
257            JobState::Done => "done",
258            JobState::Failed => "failed",
259            JobState::Cancelled => "cancelled",
260        }
261    }
262}
263
264/// Something asked of the host about a job, waiting for its answer.
265#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
266#[serde(rename_all = "snake_case")]
267pub enum Request {
268    Cancel,
269    Pause,
270    Resume,
271    Retry,
272}
273
274impl Request {
275    pub const ALL: [Request; 4] = [
276        Request::Cancel,
277        Request::Pause,
278        Request::Resume,
279        Request::Retry,
280    ];
281
282    /// The command that asks it.
283    pub fn command(self) -> &'static str {
284        match self {
285            Request::Cancel => CMD_CANCEL,
286            Request::Pause => CMD_PAUSE,
287            Request::Resume => CMD_RESUME,
288            Request::Retry => CMD_RETRY,
289        }
290    }
291
292    pub fn from_command(command: &str) -> Option<Request> {
293        Request::ALL.into_iter().find(|r| r.command() == command)
294    }
295}
296
297/// A declared sub-step of a job.
298#[derive(Clone, Debug, PartialEq, Serialize)]
299pub struct Step {
300    pub id: String,
301    pub title: String,
302    /// Its share of the job, against the other steps' (its estimate).
303    pub weight: f64,
304    pub done: u64,
305    pub total: Option<u64>,
306    pub started: bool,
307    pub finished: bool,
308}
309
310impl Step {
311    /// How far it is (0 to 1); none while it runs without a total.
312    pub fn fraction(&self) -> Option<f64> {
313        if self.finished {
314            return Some(1.0);
315        }
316        if !self.started {
317            return Some(0.0);
318        }
319        match self.total {
320            Some(t) if t > 0 => Some((self.done as f64 / t as f64).clamp(0.0, 1.0)),
321            _ => None,
322        }
323    }
324}
325
326/// An item that failed.
327#[derive(Clone, Debug, PartialEq, Serialize)]
328pub struct ItemError {
329    pub item: String,
330    pub error: String,
331}
332
333/// A command a finished job offers ("Show in folder").
334#[derive(Clone, Debug, PartialEq, Serialize)]
335pub struct JobAction {
336    pub title: String,
337    pub command: String,
338    pub args: Json,
339}
340
341/// A symbol drawn before a job's title (the node a remote job runs on, a
342/// state): a registry icon's name (`phosphor:hard-drives`), its tone, and
343/// its tooltip, which is also its accessible name, so a screen reader
344/// hears what the symbol means. Given by `job.started` or `job.progress`
345/// as `badge`:
346///
347/// ```json
348/// { "icon": "phosphor:hard-drives", "tone": "muted", "tip": "On the NAS" }
349/// ```
350///
351/// An icon the registry does not know draws its placeholder.
352///
353/// ```
354/// use egui_pop_model::admin::Tone;
355/// use egui_pop_model::jobs::JobBadge;
356/// use serde_json::json;
357///
358/// let badge = JobBadge::new("phosphor:hard-drives", "On the NAS").tone(Tone::Muted);
359/// let data = json!({ "icon": "phosphor:hard-drives", "tone": "muted", "tip": "On the NAS" });
360/// assert_eq!(serde_json::to_value(&badge).unwrap(), data);
361/// assert_eq!(JobBadge::of(&data), Some(badge));
362/// ```
363#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
364#[non_exhaustive]
365pub struct JobBadge {
366    /// A registry icon's name.
367    pub icon: String,
368    /// Its tone; the text's when none.
369    #[serde(default, skip_serializing_if = "Option::is_none")]
370    pub tone: Option<Tone>,
371    /// What it means: its tooltip and its accessible name.
372    pub tip: String,
373}
374
375impl JobBadge {
376    pub fn new(icon: &str, tip: &str) -> JobBadge {
377        JobBadge {
378            icon: icon.into(),
379            tone: None,
380            tip: tip.into(),
381        }
382    }
383
384    pub fn tone(mut self, tone: Tone) -> JobBadge {
385        self.tone = Some(tone);
386        self
387    }
388
389    /// The badge an event's `badge` holds: an object with `icon`, `tip`
390    /// and `tone` (a name, as [`tone_named`] reads it); none for anything
391    /// else (null, an empty icon name).
392    pub fn of(v: &Json) -> Option<JobBadge> {
393        let icon = v["icon"].as_str().filter(|i| !i.is_empty())?;
394        Some(JobBadge {
395            icon: icon.into(),
396            tone: v["tone"].as_str().and_then(tone_named),
397            tip: v["tip"].as_str().unwrap_or_default().into(),
398        })
399    }
400}
401
402/// A job, as the events made it.
403#[derive(Clone, Debug, PartialEq, Serialize)]
404pub struct Job {
405    pub id: String,
406    pub title: String,
407    /// What kind of work (an icon role: `export`, `import`, `render`).
408    pub kind: String,
409    /// A symbol before its title ([`JobBadge`]).
410    pub badge: Option<JobBadge>,
411    /// Who published it (the journal's source).
412    pub source: String,
413    /// The plugin it runs for, when its `job.started` named one.
414    pub owner: Option<String>,
415    /// The command that started it, when its `job.started` named one.
416    pub command: Option<String>,
417    /// The plugin it was left by: its owner is disconnected and the job
418    /// goes on (`job.orphaned`).
419    pub orphaned: Option<String>,
420    /// Why it is being cancelled or was, when it was not the user (its
421    /// plugin is disconnected).
422    pub reason: Option<String>,
423    pub parent: Option<String>,
424    /// Its share of its parent.
425    pub weight: f64,
426    pub state: JobState,
427    pub done: u64,
428    pub total: Option<u64>,
429    pub failed: u64,
430    pub skipped: u64,
431    /// The item being worked on, and how far it is (0 to 1).
432    pub item: Option<String>,
433    pub item_progress: Option<f64>,
434    pub phase: Option<String>,
435    pub steps: Vec<Step>,
436    /// The current step's id.
437    pub step: Option<String>,
438    /// The host's own estimate (0 to 1).
439    pub hint: Option<f64>,
440    /// The application's estimate ([`Jobs::refine`]), overriding the
441    /// model's.
442    pub refined: Option<f64>,
443    /// The estimated overall fraction (0 to 1); none: indeterminate.
444    pub fraction: Option<f64>,
445    pub cancellable: bool,
446    pub pausable: bool,
447    pub retryable: bool,
448    pub error: Option<String>,
449    /// The last failed items, oldest first.
450    pub errors: Vec<ItemError>,
451    pub actions: Vec<JobAction>,
452    /// What was asked of the host, until it answers.
453    pub requested: Option<Request>,
454    /// Why the host refused the last request.
455    pub request_error: Option<String>,
456    pub started_at: f64,
457    pub updated_at: f64,
458    pub ended_at: Option<f64>,
459    /// How many times it started (1, then retries).
460    pub attempts: u32,
461    /// The last event that changed it.
462    pub seq: u64,
463    /// Lines ever written to its log.
464    pub log_total: u64,
465    /// Its place in the list (the order jobs first started in).
466    pub serial: u64,
467    #[serde(skip)]
468    rate: Option<f64>,
469    #[serde(skip)]
470    sample: Option<(f64, f64)>,
471}
472
473impl Job {
474    fn new(id: &str, now: f64, serial: u64) -> Job {
475        Job {
476            id: id.into(),
477            title: id.into(),
478            kind: String::new(),
479            badge: None,
480            source: String::new(),
481            owner: None,
482            command: None,
483            orphaned: None,
484            reason: None,
485            parent: None,
486            weight: 1.0,
487            state: JobState::Running,
488            done: 0,
489            total: None,
490            failed: 0,
491            skipped: 0,
492            item: None,
493            item_progress: None,
494            phase: None,
495            steps: Vec::new(),
496            step: None,
497            hint: None,
498            refined: None,
499            fraction: None,
500            cancellable: true,
501            pausable: false,
502            retryable: true,
503            error: None,
504            errors: Vec::new(),
505            actions: Vec::new(),
506            requested: None,
507            request_error: None,
508            started_at: now,
509            updated_at: now,
510            ended_at: None,
511            attempts: 1,
512            seq: 0,
513            log_total: 0,
514            serial,
515            rate: None,
516            sample: None,
517        }
518    }
519
520    /// Whether it still goes on.
521    pub fn active(&self) -> bool {
522        self.state.active()
523    }
524
525    /// Whether its fraction is known.
526    pub fn determinate(&self) -> bool {
527        self.fraction.is_some()
528    }
529
530    /// The estimated overall percentage (0 to 100); none: indeterminate.
531    pub fn percent(&self) -> Option<f64> {
532        self.fraction.map(|f| f * 100.0)
533    }
534
535    /// How long it ran, until now or its end.
536    pub fn elapsed(&self, now: f64) -> f64 {
537        (self.ended_at.unwrap_or(now) - self.started_at).max(0.0)
538    }
539
540    /// The seconds left, from the rate of its fraction: none before
541    /// [`ETA_AFTER`] seconds, while indeterminate, paused or ended.
542    pub fn eta(&self, now: f64) -> Option<f64> {
543        if self.state != JobState::Running || self.elapsed(now) < ETA_AFTER {
544            return None;
545        }
546        let f = self.fraction?;
547        let rate = self.rate.filter(|r| *r > 1e-9)?;
548        Some(((1.0 - f) / rate).max(0.0))
549    }
550
551    fn step_index(&self, id: &str) -> Option<usize> {
552        self.steps.iter().position(|s| s.id == id)
553    }
554
555    /// Starts again (a retry): progress reset, log kept.
556    fn restart(&mut self, now: f64) {
557        let fresh = Job::new(&self.id, now, self.serial);
558        let (log_total, attempts) = (self.log_total, self.attempts + 1);
559        *self = Job {
560            log_total,
561            attempts,
562            ..fresh
563        };
564    }
565
566    fn sample(&mut self, now: f64) {
567        let Some(f) = self.fraction else {
568            return;
569        };
570        // Progress starts from nothing when the job starts.
571        let (t0, f0) = *self.sample.get_or_insert((self.started_at, 0.0));
572        if now - t0 > 1e-3 {
573            let inst = (f - f0) / (now - t0);
574            if inst >= 0.0 {
575                self.rate = Some(self.rate.map_or(inst, |r| r + ALPHA * (inst - r)));
576            }
577            self.sample = Some((now, f));
578        }
579    }
580}
581
582/// The jobs a disconnected plugin left ([`Jobs::left_by`]).
583#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
584#[non_exhaustive]
585pub struct Left {
586    /// Jobs naming it as owner that can be cancelled: the host is asked.
587    pub cancel: Vec<String>,
588    /// Jobs kept and marked orphaned: those that cannot be cancelled,
589    /// and those it published itself without naming an owner.
590    pub orphan: Vec<String>,
591}
592
593impl Left {
594    pub fn is_empty(&self) -> bool {
595        self.cancel.is_empty() && self.orphan.is_empty()
596    }
597}
598
599/// An event as the model reads it.
600#[derive(Clone, Copy, Debug)]
601pub struct Incoming<'a> {
602    pub seq: u64,
603    pub source: &'a str,
604    pub cause: Option<u64>,
605    /// What happened, typed: the model never reads an event's name.
606    pub kind: JobEventKind,
607    pub data: &'a Json,
608}
609
610impl<'a> Incoming<'a> {
611    pub fn new(seq: u64, kind: JobEventKind, data: &'a Json) -> Self {
612        Self {
613            seq,
614            source: "",
615            cause: None,
616            kind,
617            data,
618        }
619    }
620
621    pub fn source(mut self, source: &'a str) -> Self {
622        self.source = source;
623        self
624    }
625
626    pub fn cause(mut self, cause: Option<u64>) -> Self {
627        self.cause = cause;
628        self
629    }
630}
631
632/// All jobs at a glance.
633#[derive(Clone, Debug, Default, PartialEq, Serialize)]
634pub struct Summary {
635    /// Jobs going on (top-level ones).
636    pub active: usize,
637    /// Jobs that failed and were not dismissed.
638    pub failed: usize,
639    /// The mean fraction of the active jobs; none when one of them is
640    /// indeterminate (or none is active).
641    pub fraction: Option<f64>,
642}
643
644/// The jobs, folded from the journal.
645#[derive(Clone, Debug)]
646pub struct Jobs {
647    jobs: BTreeMap<String, Job>,
648    /// Each job's log, the last lines kept.
649    logs: BTreeMap<String, VecDeque<String>>,
650    /// Job commands dispatched, by their `command.dispatched` sequence
651    /// number: which job, what was asked.
652    dispatched: BTreeMap<u64, (String, Request)>,
653    serial: u64,
654    log_lines: usize,
655    history: usize,
656    changed: BTreeSet<String>,
657    /// Jobs forgotten lately, oldest first, with when: their late events
658    /// are dropped.
659    tombstones: VecDeque<(String, f64)>,
660    tombstone_count: usize,
661    tombstone_secs: f64,
662    /// The time of the last event folded: when a job forgotten between
663    /// events was forgotten.
664    now: f64,
665}
666
667impl Default for Jobs {
668    fn default() -> Self {
669        Self::new()
670    }
671}
672
673fn text(data: &Json, key: &str) -> Option<String> {
674    match &data[key] {
675        Json::String(s) => Some(s.clone()),
676        Json::Number(n) => Some(n.to_string()),
677        _ => None,
678    }
679}
680
681fn count(data: &Json, key: &str) -> Option<u64> {
682    data[key]
683        .as_u64()
684        .or_else(|| data[key].as_f64().map(|f| f.max(0.0) as u64))
685}
686
687fn fraction(data: &Json, key: &str) -> Option<f64> {
688    data[key].as_f64().map(|f| f.clamp(0.0, 1.0))
689}
690
691fn flag(data: &Json, key: &str, default: bool) -> bool {
692    data[key].as_bool().unwrap_or(default)
693}
694
695impl Jobs {
696    pub fn new() -> Self {
697        Self {
698            jobs: BTreeMap::new(),
699            logs: BTreeMap::new(),
700            dispatched: BTreeMap::new(),
701            serial: 0,
702            log_lines: LOG_LINES,
703            history: HISTORY,
704            changed: BTreeSet::new(),
705            tombstones: VecDeque::new(),
706            tombstone_count: TOMBSTONES,
707            tombstone_secs: TOMBSTONE_SECS,
708            now: 0.0,
709        }
710    }
711
712    /// Remembers at most `count` forgotten jobs, each for `secs` seconds,
713    /// to drop their late events (0 turns it off).
714    pub fn with_tombstones(mut self, count: usize, secs: f64) -> Self {
715        self.tombstone_count = count;
716        self.tombstone_secs = secs.max(0.0);
717        self
718    }
719
720    /// Moves the model's clock on to `now` (it never goes back): when a
721    /// job forgotten from now on is forgotten. Folding an event does it.
722    pub fn advance(&mut self, now: f64) {
723        self.now = self.now.max(now);
724    }
725
726    /// Whether `id` was forgotten lately: its events are dropped until a
727    /// `job.started` starts it again.
728    pub fn forgotten(&self, id: &str) -> bool {
729        self.tombstones.iter().any(|(t, _)| t == id)
730    }
731
732    fn bury(&mut self, id: &str) {
733        if self.tombstone_count == 0 {
734            return;
735        }
736        self.tombstones.retain(|(t, _)| t != id);
737        self.tombstones.push_back((id.to_string(), self.now));
738        while self.tombstones.len() > self.tombstone_count {
739            self.tombstones.pop_front();
740        }
741    }
742
743    fn expire_tombstones(&mut self, now: f64) {
744        while self
745            .tombstones
746            .front()
747            .is_some_and(|(_, at)| now - at >= self.tombstone_secs)
748        {
749            self.tombstones.pop_front();
750        }
751    }
752
753    /// Keeps `lines` lines of each job's log.
754    pub fn with_log_lines(mut self, lines: usize) -> Self {
755        self.log_lines = lines.max(1);
756        self
757    }
758
759    /// Keeps `jobs` finished top-level jobs.
760    pub fn with_history(mut self, jobs: usize) -> Self {
761        self.history = jobs;
762        self
763    }
764
765    /// Folds an event at time `now`; whether it changed a job.
766    pub fn apply(&mut self, e: &Incoming<'_>, now: f64) -> bool {
767        use JobEventKind as K;
768        self.advance(now);
769        self.expire_tombstones(now);
770        if matches!(
771            e.kind,
772            K::CommandDispatched | K::CommandDone | K::CommandFailed
773        ) {
774            return self.command(e.kind, e);
775        }
776        let d = e.data;
777        if e.kind == K::Adopted {
778            return self.adopted(d);
779        }
780        let Some(id) = text(d, "id") else {
781            return false;
782        };
783        if e.kind == K::Orphaned && !self.jobs.get(&id).is_some_and(Job::active) {
784            // Only a job going on is left behind.
785            return false;
786        }
787        if e.kind == K::Started {
788            // A new run: no longer forgotten.
789            self.tombstones.retain(|(t, _)| *t != id);
790            self.start(&id, e, now);
791        } else if !self.jobs.contains_key(&id) {
792            if self.forgotten(&id) {
793                // A late event for a job forgotten: not made up again.
794                return false;
795            }
796            // A host that skipped `job.started`: the job is made up.
797            self.serial += 1;
798            let mut job = Job::new(&id, now, self.serial);
799            job.source = e.source.into();
800            self.jobs.insert(id.clone(), job);
801        }
802        let job = self.jobs.get_mut(&id).expect("just made");
803        job.seq = e.seq;
804        job.updated_at = now;
805        match e.kind {
806            K::Started => {}
807            K::Progress => {
808                if let Some(n) = count(d, "total") {
809                    job.total = Some(n);
810                }
811                if let Some(n) = count(d, "done") {
812                    job.done = n;
813                }
814                if let Some(n) = count(d, "failed") {
815                    job.failed = n;
816                }
817                if let Some(n) = count(d, "skipped") {
818                    job.skipped = n;
819                }
820                if let Some(item) = text(d, "item") {
821                    if job.item.as_ref() != Some(&item) {
822                        job.item_progress = None;
823                    }
824                    job.item = Some(item);
825                }
826                if !d["item_progress"].is_null() {
827                    job.item_progress = fraction(d, "item_progress");
828                }
829                if let Some(p) = text(d, "phase") {
830                    job.phase = Some(p);
831                }
832                if let Some(h) = fraction(d, "estimate") {
833                    job.hint = Some(h);
834                }
835                if let Some(badge) = d.get("badge") {
836                    job.badge = JobBadge::of(badge);
837                }
838                if let Some(step) = text(d, "step") {
839                    let at = match job.step_index(&step) {
840                        Some(i) => i,
841                        None => {
842                            // A step nobody declared: added, at weight 1.
843                            job.steps.push(Step {
844                                id: step.clone(),
845                                title: step.clone(),
846                                weight: 1.0,
847                                done: 0,
848                                total: None,
849                                started: false,
850                                finished: false,
851                            });
852                            job.steps.len() - 1
853                        }
854                    };
855                    for s in &mut job.steps[..at] {
856                        s.started = true;
857                        s.finished = true;
858                    }
859                    let s = &mut job.steps[at];
860                    s.started = true;
861                    if let Some(n) = count(d, "step_total") {
862                        s.total = Some(n);
863                    }
864                    if let Some(n) = count(d, "step_done") {
865                        s.done = n;
866                    }
867                    s.finished = s.total.is_some_and(|t| s.done >= t);
868                    job.step = Some(step);
869                }
870                if job.state == JobState::Paused {
871                    job.state = JobState::Running;
872                }
873            }
874            K::ItemFailed => {
875                job.failed += 1;
876                job.errors.push(ItemError {
877                    item: text(d, "item").unwrap_or_default(),
878                    error: text(d, "error").unwrap_or_default(),
879                });
880                let len = job.errors.len();
881                if len > ITEM_ERRORS {
882                    job.errors.drain(..len - ITEM_ERRORS);
883                }
884            }
885            K::Paused => {
886                job.state = JobState::Paused;
887                job.requested = None;
888            }
889            K::Resumed => {
890                job.state = JobState::Running;
891                job.requested = None;
892                // The pause is not part of the rate.
893                job.sample = job.fraction.map(|f| (now, f));
894            }
895            K::Cancelling => {
896                job.state = JobState::Cancelling;
897                job.requested = None;
898                if let Some(reason) = text(d, "reason") {
899                    job.reason = Some(reason);
900                }
901            }
902            K::Orphaned => {
903                job.orphaned = Some(text(d, "plugin").unwrap_or_default());
904            }
905            K::Failed => {
906                job.state = JobState::Failed;
907                job.error = text(d, "error").or_else(|| Some(String::new()));
908                job.ended_at = Some(now);
909                job.requested = None;
910                job.orphaned = None;
911            }
912            K::Finished => {
913                job.state = match d["outcome"].as_str() {
914                    Some("failed") => JobState::Failed,
915                    Some("cancelled") => JobState::Cancelled,
916                    _ => JobState::Done,
917                };
918                if let Some(err) = text(d, "error") {
919                    job.error = Some(err);
920                }
921                if let Some(n) = count(d, "failed") {
922                    job.failed = n;
923                }
924                if let Some(n) = count(d, "skipped") {
925                    job.skipped = n;
926                }
927                if let Some(list) = d["actions"].as_array() {
928                    job.actions = list
929                        .iter()
930                        .filter_map(|a| {
931                            Some(JobAction {
932                                title: text(a, "title")?,
933                                command: text(a, "command")?,
934                                args: a["args"].clone(),
935                            })
936                        })
937                        .collect();
938                }
939                if job.state == JobState::Done {
940                    for s in &mut job.steps {
941                        s.started = true;
942                        s.finished = true;
943                    }
944                    if let Some(t) = job.total {
945                        job.done = job.done.max(t);
946                    }
947                }
948                job.item = None;
949                job.item_progress = None;
950                job.ended_at = Some(now);
951                job.requested = None;
952                job.orphaned = None;
953            }
954            K::Cancelled => {
955                job.state = JobState::Cancelled;
956                job.ended_at = Some(now);
957                job.requested = None;
958                job.orphaned = None;
959                if let Some(reason) = text(d, "reason") {
960                    job.reason = Some(reason);
961                }
962            }
963            K::Log => {
964                let text = text(d, "text").unwrap_or_default();
965                let text = text.strip_suffix('\n').unwrap_or(&text);
966                let log = self.logs.entry(id.clone()).or_default();
967                for line in text.split('\n') {
968                    log.push_back(line.strip_suffix('\r').unwrap_or(line).into());
969                    job.log_total += 1;
970                }
971                while log.len() > self.log_lines {
972                    log.pop_front();
973                }
974                self.changed.insert(id);
975                return true;
976            }
977            _ => return false,
978        }
979        self.recompute(&id, now);
980        if !self.jobs[&id].active() {
981            self.trim_history();
982        }
983        true
984    }
985
986    fn start(&mut self, id: &str, e: &Incoming<'_>, now: f64) {
987        let d = e.data;
988        let serial = match self.jobs.get_mut(id) {
989            Some(job) => {
990                job.restart(now);
991                let serial = job.serial;
992                // Its finished children belong to the last attempt.
993                let ended: Vec<String> = self
994                    .jobs
995                    .values()
996                    .filter(|c| c.parent.as_deref() == Some(id) && !c.active())
997                    .map(|c| c.id.clone())
998                    .collect();
999                for c in ended {
1000                    self.dismiss(&c);
1001                }
1002                serial
1003            }
1004            None => {
1005                self.serial += 1;
1006                self.jobs.insert(id.into(), Job::new(id, now, self.serial));
1007                self.serial
1008            }
1009        };
1010        let job = self.jobs.get_mut(id).expect("just made");
1011        job.serial = serial;
1012        job.title = text(d, "title").unwrap_or_else(|| id.into());
1013        job.kind = text(d, "kind").unwrap_or_default();
1014        job.badge = JobBadge::of(&d["badge"]);
1015        job.source = text(d, "source").unwrap_or_else(|| e.source.into());
1016        job.owner = text(d, "owner");
1017        job.command = text(d, "command");
1018        job.parent = text(d, "parent").filter(|p| p != id);
1019        job.weight = d["weight"].as_f64().unwrap_or(1.0).max(0.0);
1020        job.total = count(d, "total");
1021        job.hint = fraction(d, "estimate");
1022        job.cancellable = flag(d, "cancellable", true);
1023        job.pausable = flag(d, "pausable", false);
1024        job.retryable = flag(d, "retryable", true);
1025        if let Some(steps) = d["steps"].as_array() {
1026            job.steps = steps
1027                .iter()
1028                .filter_map(|s| {
1029                    let (id, title, weight) = match s {
1030                        Json::String(name) => (name.clone(), name.clone(), 1.0),
1031                        _ => {
1032                            let id = text(s, "id")?;
1033                            let title = text(s, "title").unwrap_or_else(|| id.clone());
1034                            (id, title, s["weight"].as_f64().unwrap_or(1.0))
1035                        }
1036                    };
1037                    Some(Step {
1038                        id,
1039                        title,
1040                        weight: weight.max(0.0),
1041                        done: 0,
1042                        total: None,
1043                        started: false,
1044                        finished: false,
1045                    })
1046                })
1047                .collect();
1048        }
1049    }
1050
1051    /// Follows the job commands: asked, refused.
1052    fn command(&mut self, what: JobEventKind, e: &Incoming<'_>) -> bool {
1053        match what {
1054            JobEventKind::CommandDispatched => {
1055                let Some(req) = e.data["command"].as_str().and_then(Request::from_command) else {
1056                    return false;
1057                };
1058                let Some(id) = text(&e.data["args"], "id") else {
1059                    return false;
1060                };
1061                let Some(job) = self.jobs.get_mut(&id) else {
1062                    return false;
1063                };
1064                job.requested = Some(req);
1065                job.request_error = None;
1066                if req == Request::Cancel {
1067                    // Why, when it is not the user asking.
1068                    job.reason = text(&e.data["args"], "reason");
1069                }
1070                self.dispatched.insert(e.seq, (id.clone(), req));
1071                self.changed.insert(id);
1072                true
1073            }
1074            JobEventKind::CommandDone | JobEventKind::CommandFailed => {
1075                let Some((id, req)) = e.cause.and_then(|c| self.dispatched.remove(&c)) else {
1076                    return false;
1077                };
1078                let Some(job) = self.jobs.get_mut(&id) else {
1079                    return false;
1080                };
1081                if what == JobEventKind::CommandFailed {
1082                    job.request_error = Some(text(e.data, "error").unwrap_or_default());
1083                    if job.requested == Some(req) {
1084                        job.requested = None;
1085                    }
1086                } else if req == Request::Retry && job.requested == Some(req) {
1087                    // A retry may start a job of another id: the request
1088                    // is answered.
1089                    job.requested = None;
1090                }
1091                self.changed.insert(id);
1092                true
1093            }
1094            _ => false,
1095        }
1096    }
1097
1098    /// Notes a request made before its command's event comes back (a
1099    /// view greys its button at once).
1100    pub fn request(&mut self, id: &str, request: Request) {
1101        if let Some(job) = self.jobs.get_mut(id) {
1102            job.requested = Some(request);
1103            job.request_error = None;
1104            self.changed.insert(id.into());
1105        }
1106    }
1107
1108    /// Overrides a job's estimate (0 to 1), or gives it back to the
1109    /// model (`None`); its ancestors follow.
1110    pub fn refine(&mut self, id: &str, fraction: Option<f64>, now: f64) {
1111        let Some(job) = self.jobs.get_mut(id) else {
1112            return;
1113        };
1114        let fraction = fraction.map(|f| f.clamp(0.0, 1.0));
1115        if job.refined == fraction {
1116            return;
1117        }
1118        job.refined = fraction;
1119        self.recompute(id, now);
1120    }
1121
1122    /// The model's own estimate of a job, before any refinement and
1123    /// without the last one kept: what the `jobs.estimate` step starts
1124    /// from.
1125    pub fn own_fraction(&self, id: &str) -> Option<f64> {
1126        self.jobs.get(id).and_then(|j| self.own(j))
1127    }
1128
1129    /// A job's estimate: the application's, or the model's own.
1130    fn estimate(&self, job: &Job) -> Option<f64> {
1131        if job.state == JobState::Done {
1132            return Some(1.0);
1133        }
1134        job.refined.or_else(|| self.own(job))
1135    }
1136
1137    /// A job's estimate from its parts, its counts or its host.
1138    fn own(&self, job: &Job) -> Option<f64> {
1139        if job.state == JobState::Done {
1140            return Some(1.0);
1141        }
1142        let mut parts: Vec<(f64, Option<f64>)> = job
1143            .steps
1144            .iter()
1145            .map(|s| (s.weight, s.fraction().filter(|_| s.started)))
1146            .collect();
1147        let mut known = job
1148            .steps
1149            .iter()
1150            .any(|s| s.started && s.fraction().is_some());
1151        let children: Vec<&Job> = self
1152            .jobs
1153            .values()
1154            .filter(|c| c.parent.as_deref() == Some(job.id.as_str()))
1155            .collect();
1156        for c in &children {
1157            let f = if c.state == JobState::Done {
1158                Some(1.0)
1159            } else {
1160                c.fraction
1161            };
1162            known |= f.is_some();
1163            parts.push((c.weight, f));
1164        }
1165        if !children.is_empty()
1166            && let Some(t) = job.total
1167        {
1168            let missing = (t as usize).saturating_sub(children.len());
1169            parts.extend(std::iter::repeat_n((1.0, Some(0.0)), missing));
1170        }
1171        // Parts telling something: the unknown ones count as nothing
1172        // yet. Parts telling nothing yet: the counts may.
1173        let weight: f64 = parts.iter().map(|(w, _)| w).sum();
1174        if known && weight > 0.0 {
1175            let sum: f64 = parts.iter().map(|(w, f)| w * f.unwrap_or(0.0)).sum();
1176            return Some((sum / weight).clamp(0.0, 1.0));
1177        }
1178        if let Some(t) = job.total.filter(|t| *t > 0) {
1179            let done = job.done as f64 + job.item_progress.unwrap_or(0.0);
1180            return Some((done / t as f64).clamp(0.0, 1.0));
1181        }
1182        job.hint
1183    }
1184
1185    /// Recomputes a job's fraction, then its ancestors'.
1186    fn recompute(&mut self, id: &str, now: f64) {
1187        let mut at = Some(id.to_string());
1188        for _ in 0..DEPTH {
1189            let Some(id) = at.take() else {
1190                break;
1191            };
1192            let Some(job) = self.jobs.get(&id) else {
1193                break;
1194            };
1195            let f = self.estimate(job).or(job.fraction);
1196            let job = self.jobs.get_mut(&id).expect("there");
1197            job.fraction = f;
1198            job.updated_at = job.updated_at.max(now);
1199            if job.state == JobState::Running {
1200                job.sample(now);
1201            }
1202            at = job.parent.clone();
1203            self.changed.insert(id);
1204        }
1205    }
1206
1207    /// Drops the oldest finished top-level jobs past the history's size
1208    /// (with their children).
1209    fn trim_history(&mut self) {
1210        let mut ended: Vec<(u64, String)> = self
1211            .jobs
1212            .values()
1213            .filter(|j| j.parent.is_none() && !j.active())
1214            .map(|j| (j.serial, j.id.clone()))
1215            .collect();
1216        if ended.len() <= self.history {
1217            return;
1218        }
1219        ended.sort();
1220        let drop = ended.len() - self.history;
1221        for (_, id) in ended.into_iter().take(drop) {
1222            self.dismiss(&id);
1223        }
1224    }
1225
1226    /// The jobs going on that a disconnected plugin left (ADR 0028), by
1227    /// what becomes of them. `owners` are the names it goes by (its
1228    /// plugin id, its owner id), `commands` the commands that went with
1229    /// it. A job naming it (`owner`, or `command`) that is cancellable is
1230    /// to be cancelled by the host; one that is not, and one naming no
1231    /// owner that it published itself (its events' source), is to be
1232    /// marked orphaned. A child job follows its parent: it is not listed.
1233    pub fn left_by(&self, owners: &[&str], commands: &[&str]) -> Left {
1234        let mut left = Left::default();
1235        for job in self.all() {
1236            if !job.active() || job.orphaned.is_some() {
1237                continue;
1238            }
1239            let named = job.owner.as_deref().is_some_and(|o| owners.contains(&o))
1240                || job
1241                    .command
1242                    .as_deref()
1243                    .is_some_and(|c| commands.contains(&c));
1244            let published =
1245                job.owner.is_none() && job.command.is_none() && owners.contains(&&*job.source);
1246            if !named && !published {
1247                continue;
1248            }
1249            if job
1250                .parent
1251                .as_ref()
1252                .is_some_and(|p| self.jobs.get(p).is_some_and(Job::active))
1253            {
1254                continue;
1255            }
1256            if named && job.cancellable {
1257                if job.state != JobState::Cancelling && job.requested != Some(Request::Cancel) {
1258                    left.cancel.push(job.id.clone());
1259                }
1260            } else {
1261                left.orphan.push(job.id.clone());
1262            }
1263        }
1264        left
1265    }
1266
1267    /// Folds `job.adopted`: the jobs it names, orphaned by its plugin,
1268    /// are its own again.
1269    fn adopted(&mut self, d: &Json) -> bool {
1270        let Some(plugin) = text(d, "plugin") else {
1271            return false;
1272        };
1273        let named: BTreeSet<&str> = d["jobs"]
1274            .as_array()
1275            .map(|a| a.iter().filter_map(Json::as_str).collect())
1276            .unwrap_or_default();
1277        let mut back = Vec::new();
1278        for job in self.jobs.values_mut() {
1279            if named.contains(job.id.as_str()) && job.orphaned.as_deref() == Some(plugin.as_str()) {
1280                job.orphaned = None;
1281                back.push(job.id.clone());
1282            }
1283        }
1284        let changed = !back.is_empty();
1285        self.changed.extend(back);
1286        changed
1287    }
1288
1289    /// The jobs marked orphaned by `plugin`, in id order: those its
1290    /// return takes back (`job.adopted`).
1291    pub fn orphaned_by(&self, plugin: &str) -> Vec<String> {
1292        self.jobs
1293            .values()
1294            .filter(|j| j.orphaned.as_deref() == Some(plugin))
1295            .map(|j| j.id.clone())
1296            .collect()
1297    }
1298
1299    /// Takes the orphaned mark off the jobs a plugin left: it is back.
1300    /// Returns the jobs it took it off; the same as folding the
1301    /// `job.adopted` event naming them.
1302    pub fn adopt(&mut self, plugin: &str) -> Vec<String> {
1303        let mut back = Vec::new();
1304        for job in self.jobs.values_mut() {
1305            if job.orphaned.as_deref() == Some(plugin) {
1306                job.orphaned = None;
1307                back.push(job.id.clone());
1308            }
1309        }
1310        self.changed.extend(back.iter().cloned());
1311        back
1312    }
1313
1314    /// Forgets a job and its ended descendants (a dismissed error, a
1315    /// cleared history entry); an active job is kept, unless it is
1316    /// orphaned (nothing may ever end it). A descendant still going on
1317    /// (and not orphaned) is not forgotten with it: it becomes a
1318    /// top-level job, with its own children, and ends on its own. Each
1319    /// job forgotten leaves a tombstone: its late events are dropped.
1320    pub fn dismiss(&mut self, id: &str) -> bool {
1321        let goes_on = |j: &Job| j.active() && j.orphaned.is_none();
1322        if self.jobs.get(id).is_none_or(goes_on) {
1323            return false;
1324        }
1325        let mut gone = vec![id.to_string()];
1326        let mut kept = Vec::new();
1327        let mut i = 0;
1328        while i < gone.len() {
1329            let parent = gone[i].clone();
1330            for j in self
1331                .jobs
1332                .values()
1333                .filter(|j| j.parent.as_deref() == Some(parent.as_str()))
1334            {
1335                if goes_on(j) {
1336                    kept.push(j.id.clone());
1337                } else if !gone.contains(&j.id) {
1338                    gone.push(j.id.clone());
1339                }
1340            }
1341            i += 1;
1342        }
1343        for id in kept {
1344            if let Some(j) = self.jobs.get_mut(&id) {
1345                j.parent = None;
1346            }
1347            self.changed.insert(id);
1348        }
1349        for id in gone {
1350            self.jobs.remove(&id);
1351            self.logs.remove(&id);
1352            self.bury(&id);
1353            self.changed.insert(id);
1354        }
1355        true
1356    }
1357
1358    /// Forgets every finished top-level job.
1359    pub fn clear_finished(&mut self) {
1360        let ended: Vec<String> = self
1361            .jobs
1362            .values()
1363            .filter(|j| j.parent.is_none() && !j.active())
1364            .map(|j| j.id.clone())
1365            .collect();
1366        for id in ended {
1367            self.dismiss(&id);
1368        }
1369    }
1370
1371    pub fn get(&self, id: &str) -> Option<&Job> {
1372        self.jobs.get(id)
1373    }
1374
1375    /// The lines of a job's log still kept, oldest first.
1376    pub fn log(&self, id: &str) -> Vec<&str> {
1377        self.log_from(id, 0)
1378    }
1379
1380    /// The lines of a job's log from line `from` on (numbered from 0 since
1381    /// the job first started), as far as they are still kept: what a
1382    /// console that showed `from` lines writes next.
1383    pub fn log_from(&self, id: &str, from: u64) -> Vec<&str> {
1384        let (Some(job), Some(log)) = (self.jobs.get(id), self.logs.get(id)) else {
1385            return Vec::new();
1386        };
1387        let first = job.log_total - log.len() as u64;
1388        let skip = from.saturating_sub(first) as usize;
1389        log.iter().skip(skip).map(String::as_str).collect()
1390    }
1391
1392    /// Every job, in the order they first started.
1393    pub fn all(&self) -> Vec<&Job> {
1394        let mut v: Vec<&Job> = self.jobs.values().collect();
1395        v.sort_by_key(|j| j.serial);
1396        v
1397    }
1398
1399    /// Top-level jobs (no parent, or a parent not known), in order.
1400    pub fn roots(&self) -> Vec<&Job> {
1401        let mut v: Vec<&Job> = self
1402            .jobs
1403            .values()
1404            .filter(|j| j.parent.as_ref().is_none_or(|p| !self.jobs.contains_key(p)))
1405            .collect();
1406        v.sort_by_key(|j| j.serial);
1407        v
1408    }
1409
1410    /// A job's children, in order.
1411    pub fn children(&self, id: &str) -> Vec<&Job> {
1412        let mut v: Vec<&Job> = self
1413            .jobs
1414            .values()
1415            .filter(|j| j.parent.as_deref() == Some(id))
1416            .collect();
1417        v.sort_by_key(|j| j.serial);
1418        v
1419    }
1420
1421    /// The jobs going on, in order.
1422    pub fn active(&self) -> Vec<&Job> {
1423        self.all().into_iter().filter(|j| j.active()).collect()
1424    }
1425
1426    /// Whether no job that something still owns goes on (what an agent
1427    /// waits for). An orphaned job ([`Job::orphaned`]: its plugin is
1428    /// disconnected) may never end and nobody is there to end it, so it
1429    /// is not waited on: [`Jobs::orphans`] says it apart.
1430    pub fn idle(&self) -> bool {
1431        self.jobs
1432            .values()
1433            .all(|j| !j.active() || j.orphaned.is_some())
1434    }
1435
1436    /// The orphaned jobs still going on, in order: left by their
1437    /// disconnected plugin, not counted by [`Jobs::idle`].
1438    pub fn orphans(&self) -> Vec<&Job> {
1439        self.all()
1440            .into_iter()
1441            .filter(|j| j.active() && j.orphaned.is_some())
1442            .collect()
1443    }
1444
1445    pub fn is_empty(&self) -> bool {
1446        self.jobs.is_empty()
1447    }
1448
1449    /// All jobs at a glance (the status bar's).
1450    pub fn summary(&self) -> Summary {
1451        let roots: Vec<&Job> = self.roots();
1452        let active: Vec<&&Job> = roots.iter().filter(|j| j.active()).collect();
1453        let fraction = if active.is_empty() || active.iter().any(|j| j.fraction.is_none()) {
1454            None
1455        } else {
1456            Some(active.iter().filter_map(|j| j.fraction).sum::<f64>() / active.len() as f64)
1457        };
1458        Summary {
1459            active: active.len(),
1460            failed: roots.iter().filter(|j| j.state == JobState::Failed).count(),
1461            fraction,
1462        }
1463    }
1464
1465    /// The jobs changed since the last call (by id), for views that
1466    /// coalesce.
1467    pub fn take_changed(&mut self) -> BTreeSet<String> {
1468        std::mem::take(&mut self.changed)
1469    }
1470
1471    /// What the `jobs` debug collector shows.
1472    pub fn describe(&self, now: f64) -> Json {
1473        json!({
1474            "idle": self.idle(),
1475            "orphaned": self.orphans().len(),
1476            "summary": self.summary(),
1477            "jobs": self.all().into_iter().map(|j| {
1478                let mut v = serde_json::to_value(j).unwrap_or(Json::Null);
1479                v["percent"] = json!(j.percent());
1480                v["eta"] = json!(j.eta(now));
1481                v["elapsed"] = json!(j.elapsed(now));
1482                let log = self.log(&j.id);
1483                v["log_tail"] = json!(log[log.len().saturating_sub(5)..]);
1484                v
1485            }).collect::<Vec<_>>(),
1486        })
1487    }
1488}
1489
1490#[cfg(test)]
1491mod tests {
1492    use super::*;
1493
1494    struct Feed {
1495        jobs: Jobs,
1496        seq: u64,
1497    }
1498
1499    impl Feed {
1500        fn new() -> Self {
1501            Self {
1502                jobs: Jobs::new(),
1503                seq: 0,
1504            }
1505        }
1506
1507        fn at(&mut self, now: f64, name: &str, data: Json) -> u64 {
1508            self.seq += 1;
1509            // The tests read best by label; the model takes the kind.
1510            let kind = JobEventKind::ALL
1511                .into_iter()
1512                .find(|k| k.name() == name)
1513                .expect("a job event label");
1514            self.jobs.apply(&Incoming::new(self.seq, kind, &data), now);
1515            self.seq
1516        }
1517
1518        fn job(&self, id: &str) -> &Job {
1519            self.jobs.get(id).expect("the job")
1520        }
1521    }
1522
1523    fn near(a: Option<f64>, b: f64) -> bool {
1524        a.is_some_and(|a| (a - b).abs() < 1e-9)
1525    }
1526
1527    #[test]
1528    fn a_badge_comes_with_the_start_and_changes_with_progress() {
1529        let mut f = Feed::new();
1530        let nas = json!({ "icon": "phosphor:hard-drives", "tone": "muted", "tip": "On the NAS" });
1531        f.at(
1532            0.0,
1533            STARTED,
1534            json!({ "id": "r", "title": "Backup", "badge": nas }),
1535        );
1536        assert_eq!(
1537            f.job("r").badge,
1538            Some(JobBadge::new("phosphor:hard-drives", "On the NAS").tone(Tone::Muted))
1539        );
1540        // Said on the bus as it came.
1541        assert_eq!(serde_json::to_value(f.job("r")).unwrap()["badge"], nas);
1542        // A progress without one keeps it.
1543        f.at(1.0, PROGRESS, json!({ "id": "r", "done": 1 }));
1544        assert!(f.job("r").badge.is_some());
1545        // A progress with one changes it, toneless.
1546        f.at(
1547            2.0,
1548            PROGRESS,
1549            json!({ "id": "r", "badge": { "icon": "warning", "tip": "NAS slow" } }),
1550        );
1551        assert_eq!(f.job("r").badge, Some(JobBadge::new("warning", "NAS slow")));
1552        // `null` takes it away, as does a start again without one.
1553        f.at(3.0, PROGRESS, json!({ "id": "r", "badge": null }));
1554        assert_eq!(f.job("r").badge, None);
1555        f.at(4.0, PROGRESS, json!({ "id": "r", "badge": nas }));
1556        f.at(5.0, STARTED, json!({ "id": "r", "title": "Backup" }));
1557        assert_eq!(f.job("r").badge, None);
1558        // No icon, no badge.
1559        assert_eq!(JobBadge::of(&json!({ "icon": "", "tip": "x" })), None);
1560        assert_eq!(JobBadge::of(&json!("warning")), None);
1561    }
1562
1563    #[test]
1564    fn a_job_runs_from_start_to_finish() {
1565        let mut f = Feed::new();
1566        f.at(
1567            0.0,
1568            STARTED,
1569            json!({ "id": "e", "title": "Export", "total": 4 }),
1570        );
1571        assert!(!f.jobs.idle());
1572        assert!(near(f.job("e").fraction, 0.0));
1573        f.at(
1574            1.0,
1575            PROGRESS,
1576            json!({ "id": "e", "done": 2, "item": "b.raw" }),
1577        );
1578        assert!(near(f.job("e").percent(), 50.0));
1579        f.at(2.0, FINISHED, json!({ "id": "e" }));
1580        let j = f.job("e");
1581        assert_eq!(j.state, JobState::Done);
1582        assert!(near(j.fraction, 1.0));
1583        assert_eq!(j.elapsed(10.0), 2.0);
1584        assert!(f.jobs.idle());
1585    }
1586
1587    #[test]
1588    fn without_a_total_a_job_is_indeterminate_until_it_can_estimate() {
1589        let mut f = Feed::new();
1590        f.at(0.0, STARTED, json!({ "id": "scan" }));
1591        f.at(1.0, PROGRESS, json!({ "id": "scan", "done": 30 }));
1592        assert_eq!(f.job("scan").fraction, None);
1593        f.at(2.0, PROGRESS, json!({ "id": "scan", "total": 120 }));
1594        assert!(near(f.job("scan").fraction, 0.25));
1595        // The total grows: the bar goes back, never indeterminate again.
1596        f.at(3.0, PROGRESS, json!({ "id": "scan", "total": 300 }));
1597        assert!(near(f.job("scan").fraction, 0.1));
1598    }
1599
1600    #[test]
1601    fn steps_roll_up_weighted_by_their_estimates() {
1602        let mut f = Feed::new();
1603        f.at(
1604            0.0,
1605            STARTED,
1606            json!({ "id": "r", "steps": [
1607                { "id": "decode", "weight": 1 },
1608                { "id": "process", "weight": 3 },
1609                { "id": "write", "weight": 1 },
1610            ] }),
1611        );
1612        f.at(0.5, PROGRESS, json!({ "id": "r", "step": "decode" }));
1613        // The current step tells nothing yet: indeterminate.
1614        assert_eq!(f.job("r").fraction, None);
1615        f.at(
1616            1.0,
1617            PROGRESS,
1618            json!({ "id": "r", "step": "process", "step_done": 1, "step_total": 2 }),
1619        );
1620        // decode whole (1), half of process (1.5), of 5.
1621        assert!(near(f.job("r").fraction, 0.5));
1622        f.at(2.0, PROGRESS, json!({ "id": "r", "step": "write" }));
1623        // write without a total: decode and process count (4 of 5).
1624        assert!(near(f.job("r").fraction, 0.8));
1625    }
1626
1627    #[test]
1628    fn child_jobs_roll_up_into_their_parent() {
1629        let mut f = Feed::new();
1630        f.at(0.0, STARTED, json!({ "id": "batch", "total": 4 }));
1631        f.at(
1632            0.0,
1633            STARTED,
1634            json!({ "id": "a", "parent": "batch", "total": 10 }),
1635        );
1636        f.at(1.0, PROGRESS, json!({ "id": "a", "done": 5 }));
1637        // a half done, three more to come: 0.5 of 4.
1638        assert!(near(f.job("batch").fraction, 0.125));
1639        f.at(2.0, FINISHED, json!({ "id": "a" }));
1640        assert!(near(f.job("batch").fraction, 0.25));
1641        assert_eq!(f.jobs.roots().len(), 1);
1642        assert_eq!(f.jobs.children("batch").len(), 1);
1643    }
1644
1645    #[test]
1646    fn a_refined_estimate_wins_and_can_be_given_back() {
1647        let mut f = Feed::new();
1648        f.at(0.0, STARTED, json!({ "id": "x" }));
1649        f.jobs.refine("x", Some(0.4), 1.0);
1650        assert!(near(f.job("x").fraction, 0.4));
1651        f.jobs.refine("x", None, 2.0);
1652        // Determinate once: the last estimate stays.
1653        assert!(near(f.job("x").fraction, 0.4));
1654    }
1655
1656    #[test]
1657    fn time_left_follows_the_rate_after_a_while() {
1658        let mut f = Feed::new();
1659        f.at(0.0, STARTED, json!({ "id": "e", "total": 100 }));
1660        f.at(1.0, PROGRESS, json!({ "id": "e", "done": 10 }));
1661        assert_eq!(f.job("e").eta(1.0), None, "too early");
1662        f.at(2.0, PROGRESS, json!({ "id": "e", "done": 20 }));
1663        f.at(3.0, PROGRESS, json!({ "id": "e", "done": 30 }));
1664        let eta = f.job("e").eta(3.0).expect("after 3 s");
1665        assert!((eta - 7.0).abs() < 0.5, "{eta}");
1666        f.at(4.0, PAUSED, json!({ "id": "e" }));
1667        assert_eq!(f.job("e").eta(4.0), None, "paused");
1668    }
1669
1670    #[test]
1671    fn requests_wait_for_the_host_and_a_refusal_says_why() {
1672        let mut f = Feed::new();
1673        f.at(0.0, STARTED, json!({ "id": "e" }));
1674        let asked = f.at(
1675            1.0,
1676            "command.dispatched",
1677            json!({ "command": "job.cancel", "args": { "id": "e" } }),
1678        );
1679        assert_eq!(f.job("e").requested, Some(Request::Cancel));
1680        f.seq += 1;
1681        let data = json!({ "command": "job.cancel", "error": "too late" });
1682        f.jobs.apply(
1683            &Incoming::new(f.seq, JobEventKind::CommandFailed, &data).cause(Some(asked)),
1684            1.5,
1685        );
1686        assert_eq!(f.job("e").requested, None);
1687        assert_eq!(f.job("e").request_error.as_deref(), Some("too late"));
1688        f.jobs.request("e", Request::Cancel);
1689        f.at(2.0, CANCELLED, json!({ "id": "e" }));
1690        assert_eq!(f.job("e").state, JobState::Cancelled);
1691        assert_eq!(f.job("e").requested, None);
1692    }
1693
1694    #[test]
1695    fn a_gone_plugins_jobs_are_cancelled_or_orphaned() {
1696        let mut f = Feed::new();
1697        f.at(0.0, STARTED, json!({ "id": "mine", "owner": "p" }));
1698        f.at(
1699            0.0,
1700            STARTED,
1701            json!({ "id": "fixed", "owner": "p", "cancellable": false }),
1702        );
1703        f.at(
1704            0.0,
1705            STARTED,
1706            json!({ "id": "by-command", "command": "p.go" }),
1707        );
1708        f.at(0.0, STARTED, json!({ "id": "other", "owner": "q" }));
1709        f.at(0.0, STARTED, json!({ "id": "ended", "owner": "p" }));
1710        f.at(0.5, FINISHED, json!({ "id": "ended" }));
1711        // One it published itself, naming no owner.
1712        f.seq += 1;
1713        let data = json!({ "id": "own" });
1714        f.jobs.apply(
1715            &Incoming::new(f.seq, JobEventKind::Started, &data).source("p"),
1716            0.0,
1717        );
1718        let left = f.jobs.left_by(&["p"], &["p.go"]);
1719        assert_eq!(left.cancel, ["mine", "by-command"]);
1720        assert_eq!(left.orphan, ["fixed", "own"]);
1721
1722        // The host is asked, with the reason; the others are marked.
1723        f.at(
1724            1.0,
1725            "command.dispatched",
1726            json!({ "command": "job.cancel", "args": { "id": "mine", "reason": "its plugin `p` is disconnected" } }),
1727        );
1728        f.at(1.0, ORPHANED, json!({ "id": "fixed", "plugin": "p" }));
1729        f.at(1.0, ORPHANED, json!({ "id": "ended", "plugin": "p" }));
1730        f.at(1.0, ORPHANED, json!({ "id": "never", "plugin": "p" }));
1731        assert_eq!(f.job("mine").requested, Some(Request::Cancel));
1732        assert_eq!(f.job("fixed").orphaned.as_deref(), Some("p"));
1733        assert_eq!(f.job("ended").orphaned, None, "it had ended");
1734        assert!(f.jobs.get("never").is_none(), "not made up");
1735        assert!(f.job("fixed").active());
1736        // Asked once: neither is listed again.
1737        let again = f.jobs.left_by(&["p"], &[]);
1738        assert_eq!(again.cancel, Vec::<String>::new());
1739        assert_eq!(again.orphan, ["own"]);
1740
1741        f.at(2.0, CANCELLED, json!({ "id": "mine" }));
1742        let j = f.job("mine");
1743        assert_eq!(j.state, JobState::Cancelled);
1744        assert_eq!(j.reason.as_deref(), Some("its plugin `p` is disconnected"));
1745
1746        // Its plugin back, the job is its own again; left once more, it
1747        // can be dismissed while it goes on.
1748        assert_eq!(f.jobs.adopt("p"), ["fixed"]);
1749        assert_eq!(f.job("fixed").orphaned, None);
1750        assert!(!f.jobs.dismiss("fixed"), "it goes on");
1751        f.at(3.0, ORPHANED, json!({ "id": "fixed", "plugin": "p" }));
1752        assert!(f.jobs.dismiss("fixed"));
1753    }
1754
1755    #[test]
1756    fn a_retry_starts_again_and_keeps_the_log() {
1757        let mut f = Feed::new();
1758        f.at(0.0, STARTED, json!({ "id": "e", "total": 2 }));
1759        f.at(0.1, LOG, json!({ "id": "e", "text": "one\ntwo\n" }));
1760        f.at(1.0, FAILED, json!({ "id": "e", "error": "disk full" }));
1761        assert_eq!(f.job("e").error.as_deref(), Some("disk full"));
1762        assert_eq!(f.jobs.summary().failed, 1);
1763        f.at(2.0, STARTED, json!({ "id": "e", "total": 2 }));
1764        let j = f.job("e");
1765        assert_eq!(
1766            (j.state, j.attempts, j.error.clone()),
1767            (JobState::Running, 2, None)
1768        );
1769        assert_eq!(f.jobs.log("e"), ["one", "two"]);
1770        assert_eq!(f.jobs.log_from("e", 1), ["two"]);
1771    }
1772
1773    #[test]
1774    fn the_log_and_the_history_are_bounded() {
1775        let mut f = Feed::new();
1776        f.jobs = Jobs::new().with_log_lines(2).with_history(1);
1777        f.at(0.0, STARTED, json!({ "id": "a" }));
1778        f.at(0.0, LOG, json!({ "id": "a", "text": "1\n2\n3" }));
1779        assert_eq!(f.jobs.log("a"), ["2", "3"]);
1780        assert_eq!(f.job("a").log_total, 3);
1781        assert_eq!(f.jobs.log_from("a", 0).len(), 2);
1782        f.at(1.0, FINISHED, json!({ "id": "a" }));
1783        f.at(1.0, STARTED, json!({ "id": "b" }));
1784        f.at(2.0, FINISHED, json!({ "id": "b" }));
1785        assert!(f.jobs.get("a").is_none(), "past the history");
1786        f.jobs.clear_finished();
1787        assert!(f.jobs.is_empty());
1788    }
1789
1790    #[test]
1791    fn the_summary_is_indeterminate_while_one_job_is() {
1792        let mut f = Feed::new();
1793        f.at(0.0, STARTED, json!({ "id": "a", "total": 2 }));
1794        f.at(0.0, PROGRESS, json!({ "id": "a", "done": 1 }));
1795        f.at(0.0, STARTED, json!({ "id": "b", "total": 4 }));
1796        assert!(near(f.jobs.summary().fraction, 0.25));
1797        f.at(0.0, STARTED, json!({ "id": "c" }));
1798        assert_eq!(f.jobs.summary().fraction, None);
1799        assert_eq!(f.jobs.summary().active, 3);
1800        let d = f.jobs.describe(1.0);
1801        assert_eq!(d["jobs"].as_array().unwrap().len(), 3);
1802        assert_eq!(d["idle"], false);
1803    }
1804
1805    #[test]
1806    fn dismissing_a_parent_keeps_a_running_child_as_a_top_level_job() {
1807        let mut f = Feed::new();
1808        f.at(0.0, STARTED, json!({ "id": "p" }));
1809        f.at(0.0, STARTED, json!({ "id": "done", "parent": "p" }));
1810        f.at(0.0, STARTED, json!({ "id": "busy", "parent": "p" }));
1811        f.at(0.0, STARTED, json!({ "id": "grand", "parent": "busy" }));
1812        f.at(1.0, FINISHED, json!({ "id": "done" }));
1813        f.at(2.0, FINISHED, json!({ "id": "p" }));
1814        assert!(f.jobs.dismiss("p"));
1815        assert!(f.jobs.get("p").is_none());
1816        assert!(f.jobs.get("done").is_none(), "an ended child goes");
1817        let busy = f.job("busy");
1818        assert!(busy.active(), "a running child stays");
1819        assert_eq!(busy.parent, None);
1820        assert_eq!(f.job("grand").parent.as_deref(), Some("busy"));
1821        let roots: Vec<&str> = f.jobs.roots().iter().map(|j| j.id.as_str()).collect();
1822        assert_eq!(roots, ["busy"]);
1823        // It ends on its own, then goes with the finished ones.
1824        f.at(3.0, FINISHED, json!({ "id": "grand" }));
1825        f.at(3.0, FINISHED, json!({ "id": "busy" }));
1826        assert_eq!(f.job("busy").state, JobState::Done);
1827        f.jobs.clear_finished();
1828        assert!(f.jobs.is_empty());
1829    }
1830
1831    #[test]
1832    fn a_late_event_for_a_forgotten_job_is_dropped() {
1833        let mut f = Feed::new();
1834        f.at(0.0, STARTED, json!({ "id": "e" }));
1835        f.at(1.0, FINISHED, json!({ "id": "e" }));
1836        assert!(f.jobs.dismiss("e"));
1837        assert!(f.jobs.forgotten("e"));
1838        f.at(1.5, PROGRESS, json!({ "id": "e", "done": 3 }));
1839        f.at(1.5, LOG, json!({ "id": "e", "text": "late" }));
1840        f.at(2.0, FINISHED, json!({ "id": "e" }));
1841        assert!(f.jobs.get("e").is_none(), "not made up again");
1842        assert!(f.jobs.is_empty());
1843        // An unknown job never forgotten is still made up.
1844        f.at(2.0, PROGRESS, json!({ "id": "x", "done": 1 }));
1845        assert!(f.jobs.get("x").is_some());
1846        // A new start of the forgotten job is a new run.
1847        f.at(3.0, STARTED, json!({ "id": "e" }));
1848        assert!(!f.jobs.forgotten("e"));
1849        assert!(f.job("e").active());
1850    }
1851
1852    #[test]
1853    fn tombstones_expire_and_are_bounded() {
1854        let mut f = Feed::new();
1855        f.jobs = Jobs::new().with_tombstones(2, 10.0);
1856        for id in ["a", "b", "c"] {
1857            f.at(0.0, STARTED, json!({ "id": id }));
1858            f.at(0.0, FINISHED, json!({ "id": id }));
1859            f.jobs.dismiss(id);
1860        }
1861        // At most two are kept: the oldest went.
1862        assert!(!f.jobs.forgotten("a"));
1863        assert!(f.jobs.forgotten("b") && f.jobs.forgotten("c"));
1864        // Past their time, they go too: a later event makes the job up.
1865        f.at(10.0, PROGRESS, json!({ "id": "b", "done": 1 }));
1866        assert!(!f.jobs.forgotten("b") && !f.jobs.forgotten("c"));
1867        assert!(f.jobs.get("b").is_some());
1868        // The clock moved on between events counts as the time forgotten.
1869        f.at(11.0, STARTED, json!({ "id": "d" }));
1870        f.at(11.0, FINISHED, json!({ "id": "d" }));
1871        f.jobs.advance(30.0);
1872        f.jobs.dismiss("d");
1873        f.at(35.0, PROGRESS, json!({ "id": "d" }));
1874        assert!(f.jobs.get("d").is_none());
1875        f.at(40.0, PROGRESS, json!({ "id": "d" }));
1876        assert!(f.jobs.get("d").is_some());
1877    }
1878}