using Chronos.Core.Model; using Chronos.Data.Jobs; namespace Chronos.App.Jobs; /// Filter chips of the Jobs screen (BRIEF §12.6). public enum JobFilter { All, Running, Queued, Done, Failed, } /// One job as the Jobs screen knows it: the last stored snapshot plus live progress while it runs. public sealed class JobEntry(Job job) { public Job Job { get; internal set; } = job; /// Latest progress event of the running job; null once it stops. public JobProgressInfo? Live { get; internal set; } /// of the last update. internal long Stamp { get; set; } public Guid Id => Job.Id; public JobState State => Job.State; public long Done => Live?.Done ?? Job.ProgressDone; public long Total => Live?.Total ?? Job.ProgressTotal; public double? ItemsPerSecond => Live?.ItemsPerSecond ?? Job.ItemsPerSecond; public TimeSpan? Eta => Live?.Eta ?? Job.Eta; public string? Message => Live?.Message; /// /// What the job does now (owner review 5, #65): the live detail while it runs, else the one stored with its last saved /// progress (where a paused or failed job stopped); null when its handler reports none. /// public JobDetail? Detail => Live?.Detail ?? Job.Detail; /// 0…1, or null while the total is unknown. public double? Fraction => Total > 0 ? Math.Clamp((double)Done / Total, 0, 1) : null; public bool IsFinished => State is JobState.Done or JobState.Failed or JobState.Cancelled; } /// /// The job list behind the Jobs screen and the job bar: merges stored snapshots (, /// repository pages) with live progress (), keeps queue order and answers the /// filters. WPF-free and not thread-safe; feed it on the UI thread (through ). /// public sealed class JobListModel { private readonly Dictionary _entries = []; private long _stamp; public int Count => _entries.Count; public JobEntry? this[Guid id] => _entries.GetValueOrDefault(id); /// /// Change counter. Read it before requesting a page from the database and pass it to , /// so a page that was read before an event cannot overwrite the newer state the event brought. /// public long Stamp => _stamp; /// The priority queue the engine claims jobs by, which orders the queue here too (). public JobPriorityQueue PriorityQueue { get; set; } = JobPriorityQueue.Off; /// Inserts or replaces a snapshot that is known to be current (an engine event). True when something changed. public bool Apply(Job job) => Store(job, ++_stamp); /// Inserts a snapshot read from the database; skipped when an event updated the job after . public bool ApplyLoaded(Job job, long readAt) { if (_entries.TryGetValue(job.Id, out var entry) && entry.Stamp > readAt) return false; return Store(job, readAt); } private bool Store(Job job, long stamp) { if (!_entries.TryGetValue(job.Id, out var entry)) { _entries[job.Id] = new JobEntry(job) { Stamp = stamp }; return true; } entry.Stamp = Math.Max(entry.Stamp, stamp); if (entry.Job == job) return false; entry.Job = job; if (job.State != JobState.Running) entry.Live = null; return true; } /// Live progress of a running job; ignored for unknown or no longer running jobs. True when something changed. public bool Apply(JobProgressInfo progress) { if (!_entries.TryGetValue(progress.JobId, out var entry) || entry.State != JobState.Running) return false; if (entry.Live == progress) return false; entry.Live = progress; return true; } /// Removes jobs no longer present (e.g. purged history). public bool Remove(Guid id) => _entries.Remove(id); /// /// Display order: running (oldest start first), paused, queued in the order the engine claims them (the level of the /// priority queue while it is on, priority, then age), then the history, newest finish first. Finished jobs before /// are hidden. /// public IReadOnlyList Ordered(JobFilter filter = JobFilter.All, string? search = null, DateTimeOffset? clearedBefore = null) { var text = string.IsNullOrWhiteSpace(search) ? null : search.Trim(); return _entries.Values .Where(e => Matches(e, filter) && Visible(e, clearedBefore) && (text is null || MatchesText(e, text))) .OrderBy(Group) .ThenBy(e => e.State == JobState.Queued && PriorityQueue.Enabled ? -(int)PriorityQueue.LevelOf(e.Job.Kind) : 0) .ThenBy(e => e.State == JobState.Queued ? -(int)e.Job.Priority : 0) .ThenBy(e => e.IsFinished ? -(e.Job.Finished ?? e.Job.Created).UtcTicks : (e.Job.Started ?? e.Job.Created).UtcTicks) .ThenBy(e => e.Job.Created) .ThenBy(e => e.Id) .ToList(); } /// Jobs per filter chip (after "Clear done"). public int CountOf(JobFilter filter, DateTimeOffset? clearedBefore = null) => _entries.Values.Count(e => Matches(e, filter) && Visible(e, clearedBefore)); /// 1-based place of a queued job in the order workers claim jobs; 0 when it is not queued. public int QueuePosition(Guid id) { if (!_entries.TryGetValue(id, out var entry) || entry.State != JobState.Queued) return 0; return _entries.Values.Count(e => e.State == JobState.Queued && PriorityQueue.ClaimsBefore(e.Job, entry.Job)) + 1; } /// The job the job bar mirrors: the running job with the most recent progress, else the first running one. public JobEntry? Current => _entries.Values.Where(e => e.State == JobState.Running) .OrderByDescending(e => e.Live is not null) .ThenBy(e => (e.Job.Started ?? e.Job.Created).UtcTicks) .FirstOrDefault(); public int RunningCount => _entries.Values.Count(e => e.State == JobState.Running); /// Running jobs claimed by this machine's workers (), not by render nodes or other PCs. public int RunningOn(string localWorkerId) => _entries.Values.Count(e => e.State == JobState.Running && JobText.IsLocal(e.Job.NodeId, localWorkerId)); public int QueuedCount => _entries.Values.Count(e => e.State == JobState.Queued); /// /// A job of that the user waits for (not background work) is queued or running. Paused jobs /// do not count: they wait for the user, or for an unmetered network, not for the queue. /// public bool IsBusy(JobKind kind) => _entries.Values.Any(e => e.Job.Kind == kind && e.Job.Priority != JobPriority.Background && e.State is JobState.Queued or JobState.Running); /// Same order as JobRepository.ClaimNextAsync with the priority queue off: priority descending, then creation time and id. public static bool ClaimsBefore(Job a, Job b) => JobPriorityQueue.Off.ClaimsBefore(a, b); private static int Group(JobEntry e) => e.State switch { JobState.Running => 0, JobState.Paused => 1, JobState.Queued => 2, _ => 3, }; private static bool Matches(JobEntry e, JobFilter filter) => filter switch { JobFilter.Running => e.State is JobState.Running or JobState.Paused, JobFilter.Queued => e.State == JobState.Queued, JobFilter.Done => e.State == JobState.Done, JobFilter.Failed => e.State is JobState.Failed or JobState.Cancelled, _ => true, }; private static bool Visible(JobEntry e, DateTimeOffset? clearedBefore) => clearedBefore is null || !e.IsFinished || (e.Job.Finished ?? e.Job.Created) > clearedBefore; private static bool MatchesText(JobEntry e, string text) => (e.Job.TargetLabel?.Contains(text, StringComparison.CurrentCultureIgnoreCase) ?? false) || JobText.Kind(e.Job.Kind).Contains(text, StringComparison.CurrentCultureIgnoreCase); }