refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-23 12:45:18 +02:00
1 parent c99842cc86
commit f2b58522b9
1801 files changed
+11804 -10676

No files matched your search

+178
View File
@@ -0,0 +1,178 @@
using Chronos.Core.Model;
using Chronos.Data.Jobs;
namespace Chronos.App.Jobs;
/// <summary>Filter chips of the Jobs screen (BRIEF §12.6).</summary>
public enum JobFilter
{
All,
Running,
Queued,
Done,
Failed,
}
/// <summary>One job as the Jobs screen knows it: the last stored snapshot plus live progress while it runs.</summary>
public sealed class JobEntry(Job job)
{
public Job Job { get; internal set; } = job;
/// <summary>Latest progress event of the running job; null once it stops.</summary>
public JobProgressInfo? Live { get; internal set; }
/// <summary><see cref="JobListModel.Stamp"/> of the last update.</summary>
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;
/// <summary>0…1, or null while the total is unknown.</summary>
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;
}
/// <summary>
/// The job list behind the Jobs screen and the job bar: merges stored snapshots (<see cref="JobEngine.JobChanged"/>,
/// repository pages) with live progress (<see cref="JobEngine.Progress"/>), keeps queue order and answers the
/// filters. WPF-free and not thread-safe; feed it on the UI thread (through <see cref="JobUpdateBuffer"/>).
/// </summary>
public sealed class JobListModel
{
private readonly Dictionary<Guid, JobEntry> _entries = [];
private long _stamp;
public int Count => _entries.Count;
public JobEntry? this[Guid id] => _entries.GetValueOrDefault(id);
/// <summary>
/// Change counter. Read it before requesting a page from the database and pass it to <see cref="ApplyLoaded"/>,
/// so a page that was read before an event cannot overwrite the newer state the event brought.
/// </summary>
public long Stamp => _stamp;
/// <summary>The priority queue the engine claims jobs by, which orders the queue here too (<see cref="JobPriorityQueue.ClaimsBefore"/>).</summary>
public JobPriorityQueue PriorityQueue { get; set; } = JobPriorityQueue.Off;
/// <summary>Inserts or replaces a snapshot that is known to be current (an engine event). True when something changed.</summary>
public bool Apply(Job job) => Store(job, ++_stamp);
/// <summary>Inserts a snapshot read from the database; skipped when an event updated the job after <paramref name="readAt"/>.</summary>
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;
}
/// <summary>Live progress of a running job; ignored for unknown or no longer running jobs. True when something changed.</summary>
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;
}
/// <summary>Removes jobs no longer present (e.g. purged history).</summary>
public bool Remove(Guid id) => _entries.Remove(id);
/// <summary>
/// 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
/// <paramref name="clearedBefore"/> are hidden.
/// </summary>
public IReadOnlyList<JobEntry> 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();
}
/// <summary>Jobs per filter chip (after "Clear done").</summary>
public int CountOf(JobFilter filter, DateTimeOffset? clearedBefore = null) =>
_entries.Values.Count(e => Matches(e, filter) && Visible(e, clearedBefore));
/// <summary>1-based place of a queued job in the order workers claim jobs; 0 when it is not queued.</summary>
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;
}
/// <summary>The job the job bar mirrors: the running job with the most recent progress, else the first running one.</summary>
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);
/// <summary>Running jobs claimed by this machine's workers (<paramref name="localWorkerId"/>), not by render nodes or other PCs.</summary>
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);
/// <summary>
/// A job of <paramref name="kind"/> 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.
/// </summary>
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);
/// <summary>Same order as <c>JobRepository.ClaimNextAsync</c> with the priority queue off: priority descending, then creation time and id.</summary>
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);
}
+98
View File
@@ -0,0 +1,98 @@
using Chronos.Core.Model;
namespace Chronos.App.Jobs;
/// <summary>What the shell says when a job of this PC ends.</summary>
public enum JobNotice
{
None,
Done,
Failed,
}
/// <summary>
/// Which job endings raise a toast (BRIEF §12.1 "toasts for job completion"): the long operations the user asked for
/// end with one toast, whichever screen started them. Background work (thumbnails, proxies, light analysis, the
/// analysis queued after an import) and scans (the archive is rescanned every 10 minutes) end silently; an import
/// has its own toast when it ends well, and a download shows on its Library card and Server row. Every other failure
/// is said. Cancelled jobs were stopped on purpose.
/// </summary>
public static class JobNotices
{
/// <summary>
/// The notice for <paramref name="job"/> after a change from <paramref name="before"/> (null: not seen before).
/// A job already finished before the change (a repeated event, a page read again) says nothing.
/// </summary>
public static JobNotice For(JobState? before, Job job)
{
ArgumentNullException.ThrowIfNull(job);
if (before is JobState.Done or JobState.Failed or JobState.Cancelled || job.Priority == JobPriority.Background) return JobNotice.None;
return job.State switch
{
JobState.Done when Announces(job.Kind) => JobNotice.Done,
JobState.Failed when !IsUpkeep(job.Kind) => JobNotice.Failed,
_ => JobNotice.None,
};
}
private static bool Announces(JobKind kind) =>
kind is JobKind.Render or JobKind.DeepAnalyse or JobKind.Verify or JobKind.Rebuild or JobKind.Maintenance or JobKind.UploadCommit
or JobKind.Move or JobKind.Adopt;
/// <summary>Work that keeps the index and its previews current: the next run repeats it, the Archive screen shows what is missing.</summary>
private static bool IsUpkeep(JobKind kind) =>
kind is JobKind.Scan or JobKind.Thumbs or JobKind.Proxies or JobKind.LightAnalyse;
}
/// <summary>Endings said in one toast: one job, or several of a batch.</summary>
public sealed record JobEnding(JobNotice Notice, IReadOnlyList<Job> Jobs);
/// <summary>
/// Job endings waiting for their toast, so that a batch speaks once (Server › Upload all queues one upload per
/// sequence): finished jobs of one kind wait until no job of that kind the user waits for is queued or running, then
/// one toast says how many finished; failures are said at the end of the update that brought them, together when
/// several failed at once. WPF-free; feed it on the UI thread.
/// </summary>
public sealed class JobEndings
{
private readonly SortedDictionary<JobKind, List<Job>> _done = [];
private readonly List<Job> _failed = [];
/// <summary>Finished jobs still waiting for the rest of their kind (tests).</summary>
public int Waiting => _done.Values.Sum(l => l.Count);
public void Add(JobNotice notice, Job job)
{
ArgumentNullException.ThrowIfNull(job);
if (notice == JobNotice.Failed)
{
_failed.Add(job);
}
else if (notice == JobNotice.Done)
{
if (!_done.TryGetValue(job.Kind, out var jobs)) _done[job.Kind] = jobs = [];
jobs.Add(job);
}
}
/// <summary>
/// The toasts due now: the failures added since the last call, then each finished kind that <paramref name="busy"/>
/// no longer reports as queued or running. What is returned is forgotten.
/// </summary>
public IReadOnlyList<JobEnding> Take(Func<JobKind, bool> busy)
{
ArgumentNullException.ThrowIfNull(busy);
var due = new List<JobEnding>();
if (_failed.Count > 0)
{
due.Add(new JobEnding(JobNotice.Failed, [.. _failed]));
_failed.Clear();
}
foreach (var kind in _done.Keys.Where(k => !busy(k)).ToList())
{
due.Add(new JobEnding(JobNotice.Done, _done[kind]));
_done.Remove(kind);
}
return due;
}
}
+106
View File
@@ -0,0 +1,106 @@
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Jobs;
using Chronos.Data.Repositories;
namespace Chronos.App.Jobs;
/// <summary>What the Jobs screen, the job bar and the Library need from the job system.</summary>
public interface IJobQueue
{
/// <summary>A job changed state (any thread).</summary>
event Action<Job>? JobChanged;
/// <summary>Progress of a running job (any thread, high frequency).</summary>
event Action<JobProgressInfo>? Progress;
/// <summary>Node id stamped on jobs run by this PC.</summary>
string WorkerId { get; }
/// <summary>The local engine runs jobs (it runs none before it starts, or without handlers).</summary>
bool IsRunning { get; }
/// <summary>Kinds this PC can run.</summary>
IReadOnlyCollection<JobKind> Kinds { get; }
Task<Page<Job>> ListAsync(string? cursor, int limit, CancellationToken ct = default);
Task<Job?> GetAsync(Guid id, CancellationToken ct = default);
Task<Job> EnqueueAsync(JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel, JobPriority priority = JobPriority.User, CancellationToken ct = default);
Task PauseAsync(Guid id);
/// <summary>Resumes a paused job, or retries a failed or cancelled one from its checkpoint.</summary>
Task ResumeAsync(Guid id);
/// <summary>Cancels a running or queued job.</summary>
Task CancelAsync(Guid id);
/// <summary>Moves a queued job ahead of lower-priority jobs (one priority level up).</summary>
Task RaisePriorityAsync(Guid id);
}
/// <summary><see cref="IJobQueue"/> over the local <see cref="JobEngine"/> and the job table.</summary>
public sealed class EngineJobQueue : IJobQueue, IDisposable
{
private readonly ChronosDatabase _db;
private readonly JobEngine _engine;
private readonly bool _started;
public EngineJobQueue(ChronosDatabase db, JobEngine engine, bool started)
{
_db = db;
_engine = engine;
_started = started;
_engine.JobChanged += OnJobChanged;
_engine.Progress += OnProgress;
}
public event Action<Job>? JobChanged;
public event Action<JobProgressInfo>? Progress;
public string WorkerId => _engine.Options.WorkerId;
public bool IsRunning => _started;
public IReadOnlyCollection<JobKind> Kinds => _engine.Options.Kinds ?? [];
public Task<Page<Job>> ListAsync(string? cursor, int limit, CancellationToken ct = default) => _db.Jobs.ListAsync(null, limit, cursor, ct);
public Task<Job?> GetAsync(Guid id, CancellationToken ct = default) => _db.Jobs.GetAsync(id, ct);
public Task<Job> EnqueueAsync(JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel, JobPriority priority = JobPriority.User, CancellationToken ct = default) =>
_engine.EnqueueAsync(kind, targets, targetLabel, priority: priority, cancellationToken: ct);
public Task PauseAsync(Guid id) => _engine.PauseAsync(id);
public Task ResumeAsync(Guid id) => _engine.ResumeAsync(id);
public Task CancelAsync(Guid id) => _engine.CancelAsync(id);
public async Task RaisePriorityAsync(Guid id)
{
// JobRepository has no priority update yet; one guarded statement keeps it atomic (queued jobs only).
var session = await _db.Database.OpenAsync(CancellationToken.None);
await using (session)
{
await session.ExecuteAsync(
$"UPDATE jobs SET priority = priority + 1 WHERE id = $1 AND state = {(int)JobState.Queued} AND priority < {(int)JobPriority.User}",
[id], CancellationToken.None);
}
if (await _db.Jobs.GetAsync(id) is { } job) JobChanged?.Invoke(job);
_engine.Wake();
}
public void Dispose()
{
_engine.JobChanged -= OnJobChanged;
_engine.Progress -= OnProgress;
}
private void OnJobChanged(Job job) => JobChanged?.Invoke(job);
private void OnProgress(JobProgressInfo progress) => Progress?.Invoke(progress);
}
+149
View File
@@ -0,0 +1,149 @@
using System.Windows.Input;
using Chronos.App.Infrastructure;
using Chronos.App.Sections;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Jobs;
/// <summary>A row action: label, tooltip, the name screen readers hear (label and row) and command (26-px row buttons, DESIGN §4 tables).</summary>
public sealed record JobAction(string Text, string ToolTip, string AccessibleName, ICommand Command);
/// <summary>One row of the Jobs table (Jobs.html): kind, target, progress, speed, left, where, state, actions, log.</summary>
public sealed class JobRowViewModel : ObservableObject
{
private readonly JobActions _actions;
private JobEntry _entry;
private int _queuePosition;
private bool _isExpanded;
private string? _logTail;
internal JobRowViewModel(JobEntry entry, int queuePosition, JobActions actions)
{
_entry = entry;
_queuePosition = queuePosition;
_actions = actions;
ToggleLogCommand = new RelayCommand(() => IsExpanded = !IsExpanded);
}
public JobEntry Entry => _entry;
public Guid Id => _entry.Id;
public Job Job => _entry.Job;
public string Kind => JobText.Kind(_entry.Job.Kind);
public string Target => _entry.Job.TargetLabel ?? string.Empty;
/// <summary>"Render · Harbour sunset → 4K HEVC": the row's name for screen readers.</summary>
public string AccessibleName => JobText.Name(_entry.Job);
/// <summary>Progress 0…1 (0 while unknown).</summary>
public double Progress => _entry.State == JobState.Done ? 1 : _entry.Fraction ?? 0;
/// <summary>"62 %", "—" while queued or unknown.</summary>
public string PercentText => _entry.State == JobState.Done ? Formatting.Percent(1) : _entry.Fraction is { } f && _entry.State != JobState.Queued ? Formatting.Percent(f) : "—";
public string SpeedText => _entry.State is JobState.Running or JobState.Done ? Blank(JobText.Speed(_entry.Job.Kind, _entry.ItemsPerSecond)) : "—";
public string LeftText => Blank(JobText.Left(_entry, _queuePosition));
public string WhereText => _entry.State == JobState.Queued ? Loc.L("Jobs.Where.ThisPc") : Blank(JobText.Where(_entry.Job.NodeId, _actions.WorkerId));
public string StateText => JobText.State(_entry);
/// <summary>"Render · Harbour sunset: done · 3:00": what a screen reader announces when the state changes (not progress).</summary>
public string StateAnnouncement => Loc.L("Jobs.Row.State", AccessibleName, StateText);
/// <summary>Glyph and colour of the state (paired with the word, never colour alone).</summary>
public StatusKind StateKind => _entry.State switch
{
JobState.Running => StatusKind.Running,
JobState.Queued => StatusKind.Queued,
JobState.Paused => StatusKind.Paused,
JobState.Done => StatusKind.Done,
JobState.Failed => StatusKind.Failed,
_ => StatusKind.Offline,
};
/// <summary>
/// The state as the cell shows it (whole: the narrow column cuts longer states at the minimum window), then the error of
/// a failed job or what the state means (worded not to repeat the state).
/// </summary>
public string StateToolTip => string.Join(Loc.Separator, StateText,
_entry.Job.Error is { Length: > 0 } error ? error : Loc.L("Tooltips.Jobs.State." + _entry.State));
/// <summary>Muted text for rows that are not doing anything (queued, history), as in the mockup.</summary>
public bool IsDimmed => _entry.State is JobState.Queued or JobState.Done or JobState.Cancelled;
public bool IsFailed => _entry.State == JobState.Failed;
public bool IsDone => _entry.State == JobState.Done;
public IReadOnlyList<JobAction> Actions => _actions.For(_entry);
public ICommand ToggleLogCommand { get; }
public bool IsExpanded
{
get => _isExpanded;
set
{
if (!Set(ref _isExpanded, value)) return;
OnPropertyChanged(nameof(ToggleToolTip));
OnPropertyChanged(nameof(ToggleName));
if (value) _ = _actions.LoadLogAsync(this);
}
}
public string ToggleToolTip => Loc.L(_isExpanded ? "Tooltips.Jobs.HideLog" : "Tooltips.Jobs.ShowLog");
/// <summary>"Show log: Render · Harbour sunset": the expander names its row.</summary>
public string ToggleName => Loc.L("Jobs.ActionFor", Loc.L(_isExpanded ? "Jobs.Log.Hide" : "Jobs.Log.Show"), AccessibleName);
/// <summary>The last lines of the job log, plus the live message while it runs.</summary>
public string LogText
{
get
{
var tail = _logTail ?? _entry.Job.LogTail ?? string.Empty;
if (_entry.State == JobState.Running && _entry.Message is { Length: > 0 } message && !tail.EndsWith(message, StringComparison.Ordinal))
tail = tail.Length == 0 ? message : tail + "\n" + message;
return tail.Length == 0 ? Loc.L("Jobs.Log.Empty") : tail;
}
}
internal void SetLog(string? logTail)
{
_logTail = logTail;
OnPropertyChanged(nameof(LogText));
}
/// <summary>Refreshes the row from the model; returns true when it changed position-relevant data.</summary>
internal void Update(JobEntry entry, int queuePosition)
{
var stateChanged = entry.State != _entry.State;
_entry = entry;
_queuePosition = queuePosition;
if (stateChanged)
{
_logTail = null;
OnAllPropertiesChanged();
if (_isExpanded) _ = _actions.LoadLogAsync(this);
return;
}
OnPropertyChanged(nameof(Progress));
OnPropertyChanged(nameof(PercentText));
OnPropertyChanged(nameof(SpeedText));
OnPropertyChanged(nameof(LeftText));
OnPropertyChanged(nameof(WhereText));
OnPropertyChanged(nameof(StateText));
OnPropertyChanged(nameof(StateToolTip));
OnPropertyChanged(nameof(StateAnnouncement));
if (_isExpanded) OnPropertyChanged(nameof(LogText));
}
internal void Refresh() => OnAllPropertiesChanged();
private static string Blank(string text) => text.Length == 0 ? "—" : text;
}
+85
View File
@@ -0,0 +1,85 @@
using Chronos.App.Infrastructure;
using Chronos.Core.Localization;
using Chronos.Core.Model;
namespace Chronos.App.Jobs;
/// <summary>Localized texts of jobs: kind, speed, time left, place in the queue, state (Jobs screen and job bar).</summary>
public static class JobText
{
/// <summary>"Render", "Deep analysis", …</summary>
public static string Kind(JobKind kind) => Loc.L("Jobs.Kind." + kind);
/// <summary>True for jobs whose items are frames, so their speed reads in fps.</summary>
public static bool CountsFrames(JobKind kind) =>
kind is JobKind.Render or JobKind.Proxies or JobKind.Thumbs or JobKind.DeepAnalyse;
/// <summary>True for jobs whose progress counts bytes (hash verification, card import).</summary>
public static bool CountsBytes(JobKind kind) => kind is JobKind.Verify or JobKind.Import;
/// <summary>"11.3 fps" for frame jobs, "57 MB/s" for byte jobs, "41/s" otherwise; empty when unknown.</summary>
public static string Speed(JobKind kind, double? perSecond) => perSecond switch
{
> 0 and var rate when CountsBytes(kind) => Loc.L("Jobs.Speed.Bytes", Formatting.Bytes((long)rate)),
> 0 and var rate => Loc.L(CountsFrames(kind) ? "Jobs.Speed.Fps" : "Jobs.Speed.PerSecond", Formatting.Rate(rate)),
_ => string.Empty,
};
/// <summary>"1,240 / 3,600"; empty while the total is unknown.</summary>
public static string Counter(long done, long total) =>
total > 0 ? Loc.L("Jobs.Counter", Formatting.Count(done), Formatting.Count(total)) : string.Empty;
/// <summary>
/// The "Left" column: time left while running, "after n" while queued, the finish time of the history.
/// </summary>
public static string Left(JobEntry entry, int queuePosition) => entry.State switch
{
JobState.Running => entry.Eta is { } eta ? Formatting.Duration(eta) : string.Empty,
JobState.Queued => queuePosition > 1 ? Loc.L("Jobs.Left.After", queuePosition - 1) : Loc.L("Jobs.Left.Next"),
_ when entry.Job.Finished is { } finished => Formatting.TimeOfDay(finished),
_ => string.Empty,
};
/// <summary>State word, with the run time for done jobs ("done · 2:41").</summary>
public static string State(JobEntry entry)
{
var word = Loc.L("Jobs.State." + entry.State);
return entry.State == JobState.Done && entry.Job is { Started: { } started, Finished: { } finished }
? Loc.L("Jobs.State.WithDetail", word, Formatting.Elapsed(finished - started))
: word;
}
/// <summary>Where the job runs: "this PC" for this machine's workers, the node name otherwise.</summary>
public static string Where(string? nodeId, string localWorkerId)
{
if (string.IsNullOrEmpty(nodeId)) return string.Empty;
return IsLocal(nodeId, localWorkerId) ? Loc.L("Jobs.Where.ThisPc") : NodeName(nodeId);
}
/// <summary>The job was claimed by one of this machine's numbered workers ("node#0", "node#1", …).</summary>
public static bool IsLocal(string? nodeId, string localWorkerId) =>
!string.IsNullOrEmpty(nodeId) && NodeName(nodeId).Equals(localWorkerId, StringComparison.OrdinalIgnoreCase);
/// <summary>"Kind: target" ("Render: Harbour sunset → 4K HEVC"), what a row is called for screen readers.</summary>
public static string Name(Job job) =>
string.IsNullOrWhiteSpace(job.TargetLabel) ? Kind(job.Kind) : Loc.L("Jobs.Row.Name", Kind(job.Kind), job.TargetLabel);
private static string NodeName(string nodeId)
{
var hash = nodeId.IndexOf('#', StringComparison.Ordinal);
return hash < 0 ? nodeId : nodeId[..hash];
}
/// <summary>
/// Job bar line (DESIGN §4): "Render · Harbour sunset · 2,232 / 3,600 · 11.3 fps · 2 min left".
/// </summary>
public static string Bar(JobEntry entry)
{
var parts = new List<string>(5) { Kind(entry.Job.Kind) };
if (!string.IsNullOrWhiteSpace(entry.Job.TargetLabel)) parts.Add(entry.Job.TargetLabel!);
if (Counter(entry.Done, entry.Total) is { Length: > 0 } counter) parts.Add(counter);
if (Speed(entry.Job.Kind, entry.ItemsPerSecond) is { Length: > 0 } speed) parts.Add(speed);
if (entry.Eta is { } eta) parts.Add(Loc.L("Jobs.Bar.Left", Formatting.Duration(eta)));
return string.Join(Loc.Separator, parts);
}
}
+143
View File
@@ -0,0 +1,143 @@
using Chronos.Core.Model;
using Chronos.Data.Jobs;
namespace Chronos.App.Jobs;
/// <summary>
/// Collects job events from worker threads and hands them to the UI in batches: per job only the newest snapshot
/// and the newest progress survive, so a handler reporting thousands of times per second costs the UI one update per
/// flush. Thread-safe.
/// </summary>
public sealed class JobUpdateBuffer
{
private readonly Lock _gate = new();
private Dictionary<Guid, Job> _jobs = [];
private Dictionary<Guid, JobProgressInfo> _progress = [];
private long _posted;
/// <summary>Events accepted since creation (diagnostics, tests).</summary>
public long Posted => Interlocked.Read(ref _posted);
/// <summary>Records a state change; true when the buffer was empty (the caller schedules a flush).</summary>
public bool Post(Job job)
{
lock (_gate)
{
var wasEmpty = IsEmptyLocked;
_jobs[job.Id] = job;
// A newer snapshot supersedes progress reported before it.
_progress.Remove(job.Id);
_posted++;
return wasEmpty;
}
}
/// <summary>Records progress; true when the buffer was empty (the caller schedules a flush).</summary>
public bool Post(JobProgressInfo progress)
{
lock (_gate)
{
var wasEmpty = IsEmptyLocked;
_progress[progress.JobId] = progress;
_posted++;
return wasEmpty;
}
}
public bool IsEmpty
{
get
{
lock (_gate) return IsEmptyLocked;
}
}
/// <summary>Takes everything collected since the last drain (snapshots first, then progress).</summary>
public (IReadOnlyCollection<Job> Jobs, IReadOnlyCollection<JobProgressInfo> Progress) Drain()
{
lock (_gate)
{
var jobs = _jobs;
var progress = _progress;
_jobs = [];
_progress = [];
return (jobs.Values, progress.Values);
}
}
private bool IsEmptyLocked => _jobs.Count == 0 && _progress.Count == 0;
}
/// <summary>
/// Runs an action on a synchronization context at most once per interval, however often it is signalled from any
/// thread: the first signal after a flush schedules the next flush for <c>interval</c> after the previous one
/// (the job list refreshes at about 10 Hz).
/// </summary>
public sealed class CoalescingThrottle : IDisposable
{
private readonly TimeSpan _interval;
private readonly SynchronizationContext? _context;
private readonly Action _flush;
private readonly Func<long> _now;
private readonly Timer _timer;
private readonly Lock _gate = new();
private long _lastFlush = long.MinValue;
private bool _scheduled;
private bool _disposed;
/// <param name="interval">Minimum time between two flushes.</param>
/// <param name="context">Where <paramref name="flush"/> runs (the UI); null runs it on the timer thread.</param>
/// <param name="flush">The batched work.</param>
/// <param name="clock">Milliseconds clock for tests; defaults to the high-resolution <see cref="System.Diagnostics.Stopwatch"/>.</param>
public CoalescingThrottle(TimeSpan interval, SynchronizationContext? context, Action flush, Func<long>? clock = null)
{
_interval = interval;
_context = context;
_flush = flush;
_now = clock ?? (() => System.Diagnostics.Stopwatch.GetTimestamp() * 1000 / System.Diagnostics.Stopwatch.Frequency);
_timer = new Timer(_ => Dispatch(), null, Timeout.Infinite, Timeout.Infinite);
}
/// <summary>Flushes performed (tests).</summary>
public int Flushes { get; private set; }
/// <summary>Asks for a flush; coalesced with every other signal until it runs.</summary>
public void Signal()
{
lock (_gate)
{
if (_scheduled || _disposed) return;
_scheduled = true;
var wait = _lastFlush == long.MinValue ? 0 : (long)_interval.TotalMilliseconds - (_now() - _lastFlush);
if (wait <= 0) wait = 0;
_timer.Change(wait, Timeout.Infinite);
}
}
public void Dispose()
{
lock (_gate)
{
_disposed = true;
_timer.Dispose();
}
}
private void Dispatch()
{
if (_context is null) Run();
else _context.Post(_ => Run(), null);
}
private void Run()
{
lock (_gate)
{
if (_disposed) return;
_scheduled = false;
_lastFlush = _now();
Flushes++;
}
_flush();
}
}