1use 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
101pub const STARTED: &str = "job.started";
103pub const PROGRESS: &str = "job.progress";
105pub const ITEM_FAILED: &str = "job.item_failed";
107pub const PAUSED: &str = "job.paused";
108pub const RESUMED: &str = "job.resumed";
109pub const CANCELLING: &str = "job.cancelling";
111pub const FAILED: &str = "job.failed";
112pub const FINISHED: &str = "job.finished";
113pub const CANCELLED: &str = "job.cancelled";
114pub const ORPHANED: &str = "job.orphaned";
117pub const ADOPTED: &str = "job.adopted";
120pub const LOG: &str = "job.log";
122
123pub 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
136#[serde(rename_all = "snake_case")]
137#[non_exhaustive]
138pub enum JobEventKind {
139 Started,
141 Progress,
143 ItemFailed,
145 Paused,
146 Resumed,
147 Cancelling,
149 Failed,
150 Finished,
151 Cancelled,
152 Orphaned,
155 Adopted,
157 Log,
159 CommandDispatched,
161 CommandDone,
163 CommandFailed,
165}
166
167impl JobEventKind {
168 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 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
210pub const ETA_AFTER: f64 = 3.0;
212pub const LOG_LINES: usize = 5000;
214pub const HISTORY: usize = 100;
216pub const ITEM_ERRORS: usize = 100;
218pub const TOMBSTONES: usize = 256;
221pub const TOMBSTONE_SECS: f64 = 60.0;
223
224const ALPHA: f64 = 0.3;
226const DEPTH: usize = 16;
228
229#[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,
238 Done,
239 Failed,
240 Cancelled,
241}
242
243impl JobState {
244 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#[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 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#[derive(Clone, Debug, PartialEq, Serialize)]
299pub struct Step {
300 pub id: String,
301 pub title: String,
302 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 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#[derive(Clone, Debug, PartialEq, Serialize)]
328pub struct ItemError {
329 pub item: String,
330 pub error: String,
331}
332
333#[derive(Clone, Debug, PartialEq, Serialize)]
335pub struct JobAction {
336 pub title: String,
337 pub command: String,
338 pub args: Json,
339}
340
341#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
364#[non_exhaustive]
365pub struct JobBadge {
366 pub icon: String,
368 #[serde(default, skip_serializing_if = "Option::is_none")]
370 pub tone: Option<Tone>,
371 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 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#[derive(Clone, Debug, PartialEq, Serialize)]
404pub struct Job {
405 pub id: String,
406 pub title: String,
407 pub kind: String,
409 pub badge: Option<JobBadge>,
411 pub source: String,
413 pub owner: Option<String>,
415 pub command: Option<String>,
417 pub orphaned: Option<String>,
420 pub reason: Option<String>,
423 pub parent: Option<String>,
424 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 pub item: Option<String>,
433 pub item_progress: Option<f64>,
434 pub phase: Option<String>,
435 pub steps: Vec<Step>,
436 pub step: Option<String>,
438 pub hint: Option<f64>,
440 pub refined: Option<f64>,
443 pub fraction: Option<f64>,
445 pub cancellable: bool,
446 pub pausable: bool,
447 pub retryable: bool,
448 pub error: Option<String>,
449 pub errors: Vec<ItemError>,
451 pub actions: Vec<JobAction>,
452 pub requested: Option<Request>,
454 pub request_error: Option<String>,
456 pub started_at: f64,
457 pub updated_at: f64,
458 pub ended_at: Option<f64>,
459 pub attempts: u32,
461 pub seq: u64,
463 pub log_total: u64,
465 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 pub fn active(&self) -> bool {
522 self.state.active()
523 }
524
525 pub fn determinate(&self) -> bool {
527 self.fraction.is_some()
528 }
529
530 pub fn percent(&self) -> Option<f64> {
532 self.fraction.map(|f| f * 100.0)
533 }
534
535 pub fn elapsed(&self, now: f64) -> f64 {
537 (self.ended_at.unwrap_or(now) - self.started_at).max(0.0)
538 }
539
540 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 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 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#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
584#[non_exhaustive]
585pub struct Left {
586 pub cancel: Vec<String>,
588 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#[derive(Clone, Copy, Debug)]
601pub struct Incoming<'a> {
602 pub seq: u64,
603 pub source: &'a str,
604 pub cause: Option<u64>,
605 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#[derive(Clone, Debug, Default, PartialEq, Serialize)]
634pub struct Summary {
635 pub active: usize,
637 pub failed: usize,
639 pub fraction: Option<f64>,
642}
643
644#[derive(Clone, Debug)]
646pub struct Jobs {
647 jobs: BTreeMap<String, Job>,
648 logs: BTreeMap<String, VecDeque<String>>,
650 dispatched: BTreeMap<u64, (String, Request)>,
653 serial: u64,
654 log_lines: usize,
655 history: usize,
656 changed: BTreeSet<String>,
657 tombstones: VecDeque<(String, f64)>,
660 tombstone_count: usize,
661 tombstone_secs: f64,
662 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 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 pub fn advance(&mut self, now: f64) {
723 self.now = self.now.max(now);
724 }
725
726 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 pub fn with_log_lines(mut self, lines: usize) -> Self {
755 self.log_lines = lines.max(1);
756 self
757 }
758
759 pub fn with_history(mut self, jobs: usize) -> Self {
761 self.history = jobs;
762 self
763 }
764
765 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 return false;
786 }
787 if e.kind == K::Started {
788 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 return false;
795 }
796 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 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 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 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 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 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 job.requested = None;
1090 }
1091 self.changed.insert(id);
1092 true
1093 }
1094 _ => false,
1095 }
1096 }
1097
1098 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 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 pub fn own_fraction(&self, id: &str) -> Option<f64> {
1126 self.jobs.get(id).and_then(|j| self.own(j))
1127 }
1128
1129 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 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 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 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 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 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 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 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 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 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 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 pub fn log(&self, id: &str) -> Vec<&str> {
1377 self.log_from(id, 0)
1378 }
1379
1380 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 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 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 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 pub fn active(&self) -> Vec<&Job> {
1423 self.all().into_iter().filter(|j| j.active()).collect()
1424 }
1425
1426 pub fn idle(&self) -> bool {
1431 self.jobs
1432 .values()
1433 .all(|j| !j.active() || j.orphaned.is_some())
1434 }
1435
1436 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 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 pub fn take_changed(&mut self) -> BTreeSet<String> {
1468 std::mem::take(&mut self.changed)
1469 }
1470
1471 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 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 assert_eq!(serde_json::to_value(f.job("r")).unwrap()["badge"], nas);
1542 f.at(1.0, PROGRESS, json!({ "id": "r", "done": 1 }));
1544 assert!(f.job("r").badge.is_some());
1545 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 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 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 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 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 assert!(near(f.job("r").fraction, 0.5));
1622 f.at(2.0, PROGRESS, json!({ "id": "r", "step": "write" }));
1623 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 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 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 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 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 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 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 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 f.at(2.0, PROGRESS, json!({ "id": "x", "done": 1 }));
1845 assert!(f.jobs.get("x").is_some());
1846 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 assert!(!f.jobs.forgotten("a"));
1863 assert!(f.jobs.forgotten("b") && f.jobs.forgotten("c"));
1864 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 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}