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
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:
1 parent
c99842cc86
commit
f2b58522b9
1801 files changed
+11804
-10676
No files matched your search
@@ -0,0 +1,512 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Threading.Channels;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.Data.Jobs;
|
||||
|
||||
public sealed record JobEngineOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Jobs run at once: one (owner review 1, R2). Jobs run one at a time and the host's parallelism decides how many
|
||||
/// photos the running job processes at once; tests run more workers to exercise concurrent claims.
|
||||
/// </summary>
|
||||
public int Workers { get; init; } = 1;
|
||||
|
||||
/// <summary>Identity stamped on claimed jobs (node id); also used for crash recovery.</summary>
|
||||
public string WorkerId { get; init; } = Environment.MachineName;
|
||||
|
||||
/// <summary>Kinds this engine runs; null = every kind with a registered handler.</summary>
|
||||
public IReadOnlyCollection<JobKind>? Kinds { get; init; }
|
||||
|
||||
public TimeSpan CheckpointInterval { get; init; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>Fallback poll for jobs enqueued by other processes; also how often the priority queue is reviewed.</summary>
|
||||
public TimeSpan PollInterval { get; init; } = TimeSpan.FromSeconds(3);
|
||||
|
||||
/// <summary>Finished jobs older than this are purged (BRIEF §14.6: 90 days).</summary>
|
||||
public TimeSpan HistoryRetention { get; init; } = TimeSpan.FromDays(90);
|
||||
|
||||
/// <summary>Clock of the throughput windows and the checkpoint interval (tests pass their own).</summary>
|
||||
public TimeProvider Time { get; init; } = TimeProvider.System;
|
||||
|
||||
/// <summary>The priority queue as the settings have it now, asked at every claim and review; null: off (<see cref="JobPriorityQueue"/>).</summary>
|
||||
public Func<JobPriorityQueue>? PriorityQueue { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persistent job queue runner (BRIEF §14.6, amended by owner review 1): one worker claims queued jobs from the database
|
||||
/// in claim order, runs the registered handler, checkpoints progress, and survives crashes (running jobs are requeued at
|
||||
/// start with their checkpoints). Used by the desktop client (local mode) and the server. Jobs an
|
||||
/// <see cref="ISelectiveJobHandler"/> declines stay queued for other claimers. With the priority queue on
|
||||
/// (<see cref="JobEngineOptions.PriorityQueue"/>) a queued job of a higher level makes the running job of a lower level
|
||||
/// yield: it goes back to the queue with its checkpoint and resumes by itself afterwards, never interrupted by the
|
||||
/// follow-ups it queued itself.
|
||||
/// </summary>
|
||||
public sealed class JobEngine : IAsyncDisposable
|
||||
{
|
||||
/// <summary>Queued jobs of selective kinds examined per claim; jobs declined beyond it wait until those ahead leave the queue.</summary>
|
||||
private const int SelectiveWindow = 100;
|
||||
|
||||
/// <summary>Queued jobs a review looks through for one that is not a follow-up of the running job.</summary>
|
||||
private const int ReviewWindow = 50;
|
||||
|
||||
/// <summary>Claims lost to other workers before a worker waits for the next poll.</summary>
|
||||
private const int MaxClaimRaces = 16;
|
||||
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly Dictionary<JobKind, IJobHandler> _handlers;
|
||||
private IReadOnlyCollection<JobKind> _kinds = [];
|
||||
private Dictionary<JobKind, ISelectiveJobHandler> _selective = [];
|
||||
private IReadOnlyCollection<JobKind> _others = [];
|
||||
private readonly ConcurrentDictionary<Guid, RunningJob> _running = new();
|
||||
private readonly Channel<bool> _wake = Channel.CreateBounded<bool>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
|
||||
private readonly Channel<bool> _review = Channel.CreateBounded<bool>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
|
||||
private readonly CancellationTokenSource _shutdown = new();
|
||||
private readonly List<Task> _loops = [];
|
||||
private readonly Lock _gate = new();
|
||||
|
||||
public JobEngine(ChronosDatabase db, IEnumerable<IJobHandler> handlers, JobEngineOptions? options = null)
|
||||
{
|
||||
_db = db;
|
||||
Options = options ?? new JobEngineOptions();
|
||||
_handlers = handlers.ToDictionary(h => h.Kind);
|
||||
}
|
||||
|
||||
public JobEngineOptions Options { get; }
|
||||
|
||||
/// <summary>A job changed state (queued, running, done, failed, cancelled, paused).</summary>
|
||||
public event Action<Job>? JobChanged;
|
||||
|
||||
/// <summary>Progress of a running job (high frequency; throttle in the UI).</summary>
|
||||
public event Action<JobProgressInfo>? Progress;
|
||||
|
||||
public IReadOnlyCollection<Guid> RunningJobIds => [.. _running.Keys];
|
||||
|
||||
/// <summary>The priority queue as it is now (<see cref="JobEngineOptions.PriorityQueue"/>).</summary>
|
||||
public JobPriorityQueue PriorityQueue => Options.PriorityQueue?.Invoke() ?? JobPriorityQueue.Off;
|
||||
|
||||
/// <summary>Requeues this worker's interrupted jobs, purges old history and starts the worker and the queue's review.</summary>
|
||||
public async Task StartAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var requeued = await _db.Jobs.RequeueRunningAsync(Options.WorkerId, cancellationToken).ConfigureAwait(false);
|
||||
if (requeued > 0) Log.Info("jobs", $"Requeued {requeued} interrupted job(s)");
|
||||
await _db.Jobs.PurgeHistoryAsync(DateTimeOffset.UtcNow - Options.HistoryRetention, cancellationToken).ConfigureAwait(false);
|
||||
// Only kinds this engine can run: an empty filter would claim (and fail) every job, render-node work included.
|
||||
_kinds = [.. (Options.Kinds ?? _handlers.Keys).Where(_handlers.ContainsKey).Distinct()];
|
||||
_selective = _kinds.Select(k => _handlers[k]).OfType<ISelectiveJobHandler>().ToDictionary(h => h.Kind);
|
||||
_others = [.. _kinds.Where(k => !_selective.ContainsKey(k))];
|
||||
if (_kinds.Count == 0)
|
||||
{
|
||||
Log.Info("jobs", "No job handlers; this engine claims nothing");
|
||||
return;
|
||||
}
|
||||
var shutdown = _shutdown.Token;
|
||||
lock (_gate)
|
||||
{
|
||||
for (var i = 0; i < Options.Workers; i++)
|
||||
{
|
||||
// A single worker keeps the plain id; numbered ones get "#n" (crash recovery requeues both).
|
||||
var id = Options.Workers == 1 ? Options.WorkerId : $"{Options.WorkerId}#{i}";
|
||||
_loops.Add(Task.Run(() => WorkerLoopAsync(id, shutdown), CancellationToken.None));
|
||||
}
|
||||
_loops.Add(Task.Run(() => SuperviseAsync(shutdown), CancellationToken.None));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Queues a job and wakes a worker.</summary>
|
||||
public Task<Job> EnqueueAsync(JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel = null, string? parametersJson = null,
|
||||
JobPriority priority = JobPriority.Normal, Guid? createdBy = null, CancellationToken cancellationToken = default) =>
|
||||
EnqueueAsync(Guid.CreateVersion7(), kind, targets, targetLabel, parametersJson, priority, createdBy, cancellationToken);
|
||||
|
||||
/// <summary>Cancels a queued or running job; a running handler observes its token.</summary>
|
||||
public Task CancelAsync(Guid id, CancellationToken cancellationToken = default) => TransitionAsync(id, JobState.Cancelled, cancellationToken);
|
||||
|
||||
/// <summary>Pauses a job: a running one stops at its next check and keeps its checkpoint, and the next queued job starts.</summary>
|
||||
public Task PauseAsync(Guid id, CancellationToken cancellationToken = default) => TransitionAsync(id, JobState.Paused, cancellationToken);
|
||||
|
||||
/// <summary>Resumes a paused job or retries a failed/cancelled one from its last checkpoint.</summary>
|
||||
public async Task ResumeAsync(Guid id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _db.Jobs.SetStateAsync(id, JobState.Queued, null, cancellationToken).ConfigureAwait(false);
|
||||
await NotifyAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
Wake();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Signals that the queue may have changed (also call on PostgreSQL NOTIFY, and after the priority queue's settings
|
||||
/// changed): an idle worker looks for work, and the priority queue is reviewed at once.
|
||||
/// </summary>
|
||||
public void Wake()
|
||||
{
|
||||
_wake.Writer.TryWrite(true);
|
||||
_review.Writer.TryWrite(true);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
Task[] loops;
|
||||
lock (_gate) loops = [.. _loops];
|
||||
await _shutdown.CancelAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(loops).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
_shutdown.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>Broadcasts live progress. A subscriber that throws never fails the job it watches (logged once per job).</summary>
|
||||
internal void PublishProgress(JobContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
var (rate, eta) = context.Rate();
|
||||
Progress?.Invoke(new JobProgressInfo(context.Job.Id, context.Job.Kind, context.Job.TargetLabel, context.Done, context.Total, rate, eta, context.Message));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (context.FirstProgressFailure()) Log.Warning("jobs", $"Progress of {context.Job.Kind} job {context.Job.Id} not published", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves progress, checkpoint and log tail; false when the job no longer runs here (cancelled or paused elsewhere).
|
||||
/// Saving is best effort and never throws: a failure is logged and the job goes on, so its final state is always written.
|
||||
/// </summary>
|
||||
internal async Task<bool> PersistAsync(JobContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
var (rate, eta) = context.Rate();
|
||||
return await _db.Jobs.UpdateProgressAsync(context.Job.Id, context.Done, context.Total, rate, eta, context.Checkpoint, context.LogTail, CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch (DatabaseException ex) when (ex.IsTransient)
|
||||
{
|
||||
Log.Warning("jobs", "Progress not saved (transient database error)", ex);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning("jobs", $"Progress of {context.Job.Kind} job {context.Job.Id} not saved", ex);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when this engine claims jobs of <paramref name="kind"/> (it has a handler and the kind is not filtered out).</summary>
|
||||
internal bool Runs(JobKind kind) => _kinds.Contains(kind);
|
||||
|
||||
/// <summary>
|
||||
/// Queues follow-up work of the running job <paramref name="parent"/> (<see cref="JobContext.EnqueueFollowUpAsync"/>):
|
||||
/// it works on what the parent produces, so it never interrupts it, whatever its level. Null when this engine has no
|
||||
/// handler for <paramref name="kind"/>.
|
||||
/// </summary>
|
||||
internal async Task<Job?> EnqueueFollowUpAsync(Guid parent, JobKind kind, IReadOnlyList<Guid> targets, string? label, string? parametersJson,
|
||||
JobPriority priority, Guid? createdBy, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!Runs(kind)) return null;
|
||||
var id = Guid.CreateVersion7();
|
||||
// Known before the job is queued, so the review its queueing starts already leaves the parent running.
|
||||
if (_running.TryGetValue(parent, out var run)) run.FollowUps.TryAdd(id, 0);
|
||||
return await EnqueueAsync(id, kind, targets, label, parametersJson, priority, createdBy, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal void StopJob(Guid id)
|
||||
{
|
||||
if (_running.TryGetValue(id, out var run)) run.Stop();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes the running job yield when the priority queue is on and a queued job of a higher level waits that this engine
|
||||
/// would claim (not a follow-up of that running job): the running job of the lowest level stops, goes back to the
|
||||
/// queue with its checkpoint and resumes after the higher ones. A free worker would claim the waiting job anyway, so
|
||||
/// only a full engine interrupts one. True when a job was asked to yield.
|
||||
/// </summary>
|
||||
internal async Task<bool> ReviewAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var queue = PriorityQueue;
|
||||
if (!queue.Enabled) return false;
|
||||
var running = _running.Values.Where(r => !r.Yielding).ToList();
|
||||
if (running.Count == 0 || running.Count < Options.Workers) return false;
|
||||
var lowest = running.MinBy(r => queue.LevelOf(r.Job.Kind))!;
|
||||
if (queue.LevelOf(lowest.Job.Kind) == JobKindPriority.High) return false;
|
||||
var next = await PeekAsync(queue, lowest, cancellationToken).ConfigureAwait(false);
|
||||
if (next is null || !queue.Interrupts(next.Kind, lowest.Job.Kind)) return false;
|
||||
if (!lowest.Yield(next)) return false;
|
||||
Log.Info("jobs", $"{lowest.Job.Kind} job {lowest.Job.Id} yields to {next.Kind} job {next.Id} (priority queue)");
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task<Job> EnqueueAsync(Guid id, JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel, string? parametersJson,
|
||||
JobPriority priority, Guid? createdBy, CancellationToken cancellationToken)
|
||||
{
|
||||
var job = new Job
|
||||
{
|
||||
Id = id,
|
||||
Kind = kind,
|
||||
TargetIds = targets,
|
||||
TargetLabel = targetLabel,
|
||||
ParametersJson = parametersJson,
|
||||
Priority = priority,
|
||||
State = JobState.Queued,
|
||||
CreatedBy = createdBy,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
};
|
||||
await _db.Jobs.EnqueueAsync(job, cancellationToken).ConfigureAwait(false);
|
||||
JobChanged?.Invoke(job);
|
||||
Wake();
|
||||
return job;
|
||||
}
|
||||
|
||||
private async Task TransitionAsync(Guid id, JobState state, CancellationToken cancellationToken)
|
||||
{
|
||||
await _db.Jobs.SetStateAsync(id, state, null, cancellationToken).ConfigureAwait(false);
|
||||
StopJob(id);
|
||||
await NotifyAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task NotifyAsync(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await _db.Jobs.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } job) JobChanged?.Invoke(job);
|
||||
}
|
||||
|
||||
/// <summary>Claims and runs jobs until shutdown. Nothing a job or a handler throws ends the worker.</summary>
|
||||
private async Task WorkerLoopAsync(string workerId, CancellationToken shutdown)
|
||||
{
|
||||
while (!shutdown.IsCancellationRequested)
|
||||
{
|
||||
Job? job;
|
||||
try
|
||||
{
|
||||
job = await ClaimAsync(workerId, shutdown).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (shutdown.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning("jobs", "Claiming a job failed", ex);
|
||||
job = null;
|
||||
}
|
||||
|
||||
if (job is null)
|
||||
{
|
||||
await WaitAsync(_wake, shutdown).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await RunAsync(job, workerId, shutdown).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// The job's final state could not be stored (also while stopping): it stays running and is requeued at the
|
||||
// next start. The worker never faults, so disposing the engine never throws.
|
||||
Log.Error("jobs", $"{job.Kind} job {job.Id} could not be finished", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reviews the priority queue (<see cref="ReviewAsync"/>) whenever the queue may have changed (<see cref="Wake"/>) and
|
||||
/// at every poll, which also covers jobs queued by other processes. Nothing a review throws ends it.
|
||||
/// </summary>
|
||||
private async Task SuperviseAsync(CancellationToken shutdown)
|
||||
{
|
||||
while (!shutdown.IsCancellationRequested)
|
||||
{
|
||||
await WaitAsync(_review, shutdown).ConfigureAwait(false);
|
||||
if (shutdown.IsCancellationRequested) return;
|
||||
try
|
||||
{
|
||||
await ReviewAsync(shutdown).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (shutdown.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning("jobs", "The priority queue could not be reviewed", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Waits for a signal on <paramref name="channel"/>, the poll interval or shutdown, whichever comes first.</summary>
|
||||
private async Task WaitAsync(Channel<bool> channel, CancellationToken shutdown)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(shutdown);
|
||||
timeout.CancelAfter(Options.PollInterval);
|
||||
try
|
||||
{
|
||||
await channel.Reader.ReadAsync(timeout.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Poll interval elapsed or shutdown.
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The next job in claim order (<see cref="JobPriorityQueue.ClaimsBefore"/>). Without selective handlers the database
|
||||
/// picks it atomically. With them, the first job a selective handler accepts among the first
|
||||
/// <see cref="SelectiveWindow"/> of its kinds competes with the head of the other kinds: the other kinds are still
|
||||
/// claimed atomically, the selective job by id. A lost race means another worker took a job, so looking again at once
|
||||
/// makes progress.
|
||||
/// </summary>
|
||||
private async Task<Job?> ClaimAsync(string workerId, CancellationToken cancellationToken)
|
||||
{
|
||||
var queue = PriorityQueue;
|
||||
if (_selective.Count == 0) return await _db.Jobs.ClaimNextAsync(workerId, _kinds, queue, cancellationToken).ConfigureAwait(false);
|
||||
for (var attempt = 0; attempt < MaxClaimRaces; attempt++)
|
||||
{
|
||||
var candidate = await AcceptedAsync(queue, null, cancellationToken).ConfigureAwait(false);
|
||||
if (candidate is null) return _others.Count > 0 ? await _db.Jobs.ClaimNextAsync(workerId, _others, queue, cancellationToken).ConfigureAwait(false) : null;
|
||||
if (_others.Count > 0 && (await _db.Jobs.ListQueuedAsync(_others, 1, queue, cancellationToken).ConfigureAwait(false)).FirstOrDefault() is { } head
|
||||
&& queue.ClaimsBefore(head, candidate))
|
||||
{
|
||||
if (await _db.Jobs.ClaimNextAsync(workerId, _others, queue, cancellationToken).ConfigureAwait(false) is { } next) return next;
|
||||
}
|
||||
else if (await _db.Jobs.TryClaimAsync(candidate.Id, workerId, cancellationToken).ConfigureAwait(false) is { } claimed)
|
||||
{
|
||||
return claimed;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The job a free worker would claim now (<see cref="ClaimAsync"/>) leaving out the follow-ups of <paramref name="running"/>, without claiming it.</summary>
|
||||
private async Task<Job?> PeekAsync(JobPriorityQueue queue, RunningJob running, CancellationToken cancellationToken)
|
||||
{
|
||||
var candidate = _selective.Count > 0 ? await AcceptedAsync(queue, running, cancellationToken).ConfigureAwait(false) : null;
|
||||
Job? head = null;
|
||||
if (_others.Count > 0)
|
||||
{
|
||||
foreach (var queued in await _db.Jobs.ListQueuedAsync(_others, ReviewWindow, queue, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (running.FollowUps.ContainsKey(queued.Id)) continue;
|
||||
head = queued;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return head is null ? candidate : candidate is null || queue.ClaimsBefore(head, candidate) ? head : candidate;
|
||||
}
|
||||
|
||||
/// <summary>The first queued job of the selective kinds whose handler takes it now, leaving out the follow-ups of <paramref name="running"/>.</summary>
|
||||
private async Task<Job?> AcceptedAsync(JobPriorityQueue queue, RunningJob? running, CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var queued in await _db.Jobs.ListQueuedAsync(_selective.Keys, SelectiveWindow, queue, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (running?.FollowUps.ContainsKey(queued.Id) == true || !await AcceptsAsync(queued, cancellationToken).ConfigureAwait(false)) continue;
|
||||
return queued;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>A job its handler cannot judge is taken, so it fails here with its reason instead of blocking the queue.</summary>
|
||||
private async ValueTask<bool> AcceptsAsync(Job job, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await _selective[job.Kind].AcceptsAsync(job, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (!(ex is OperationCanceledException && cancellationToken.IsCancellationRequested))
|
||||
{
|
||||
Log.Warning("jobs", $"{job.Kind} job {job.Id} could not be examined; it is claimed so that it fails with its reason", ex);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunAsync(Job job, string workerId, CancellationToken shutdown)
|
||||
{
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(shutdown);
|
||||
var run = new RunningJob(job, cts);
|
||||
_running[job.Id] = run;
|
||||
JobChanged?.Invoke(job);
|
||||
// A job queued while this one was being claimed may outrank it.
|
||||
_review.Writer.TryWrite(true);
|
||||
var context = new JobContext(this, job, cts.Token);
|
||||
JobState final;
|
||||
string? error = null;
|
||||
try
|
||||
{
|
||||
if (!_handlers.TryGetValue(job.Kind, out var handler))
|
||||
throw new InvalidOperationException($"No handler for {job.Kind} jobs on this worker.");
|
||||
await handler.RunAsync(context).ConfigureAwait(false);
|
||||
await PersistAsync(context).ConfigureAwait(false);
|
||||
final = JobState.Done;
|
||||
}
|
||||
catch (OperationCanceledException) when (cts.IsCancellationRequested)
|
||||
{
|
||||
// Read once: the job a yield names is set together with the yield itself.
|
||||
var yieldsTo = shutdown.IsCancellationRequested ? null : run.YieldsTo;
|
||||
var yielded = yieldsTo is not null;
|
||||
if (yieldsTo is not null) context.Log(Loc.L("Jobs.Line.Yielded", Loc.L("Jobs.Kind." + yieldsTo.Kind)));
|
||||
await PersistAsync(context).ConfigureAwait(false);
|
||||
_running.TryRemove(job.Id, out _);
|
||||
// Engine stopping: leave the job running so the next start requeues it from its checkpoint.
|
||||
if (shutdown.IsCancellationRequested) return;
|
||||
// Yielded to a higher job: back to the queue with its checkpoint, unless the user paused or cancelled it
|
||||
// meanwhile (their state stays). Otherwise cancel or pause already wrote the state; keep it.
|
||||
if (yielded) await _db.Jobs.RequeueAsync(job.Id, workerId, CancellationToken.None).ConfigureAwait(false);
|
||||
await NotifyAsync(job.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Error("jobs", $"{job.Kind} job {job.Id} failed", ex);
|
||||
context.Log(ex.Message);
|
||||
await PersistAsync(context).ConfigureAwait(false);
|
||||
final = JobState.Failed;
|
||||
error = ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_running.TryRemove(job.Id, out _);
|
||||
}
|
||||
await _db.Jobs.SetStateAsync(job.Id, final, error, CancellationToken.None).ConfigureAwait(false);
|
||||
await NotifyAsync(job.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>A job a worker runs: how it is stopped, whether it was stopped to yield, and the follow-ups it queued.</summary>
|
||||
private sealed class RunningJob(Job job, CancellationTokenSource cancellation)
|
||||
{
|
||||
private Job? _yieldsTo;
|
||||
|
||||
public Job Job { get; } = job;
|
||||
|
||||
/// <summary>Jobs this one queued as follow-ups (<see cref="EnqueueFollowUpAsync"/>): they never make it yield.</summary>
|
||||
public ConcurrentDictionary<Guid, byte> FollowUps { get; } = new();
|
||||
|
||||
public bool Yielding => YieldsTo is not null;
|
||||
|
||||
/// <summary>The job of a higher level this one yields to; set, atomically, before it is stopped.</summary>
|
||||
public Job? YieldsTo => Volatile.Read(ref _yieldsTo);
|
||||
|
||||
/// <summary>Signals the job's token; a job that ended meanwhile (its source disposed) needs nothing.</summary>
|
||||
public void Stop()
|
||||
{
|
||||
try
|
||||
{
|
||||
cancellation.Cancel();
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stops the job to yield to <paramref name="to"/>; false when it is yielding already.</summary>
|
||||
public bool Yield(Job to)
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _yieldsTo, to, null) is not null) return false;
|
||||
Stop();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
using System.Text;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.Data.Jobs;
|
||||
|
||||
/// <summary>Runs one kind of job (scan, verify, render, …). Handlers must honour <see cref="JobContext.Cancellation"/>
|
||||
/// and resume from <see cref="JobContext.Checkpoint"/> when it is set.</summary>
|
||||
public interface IJobHandler
|
||||
{
|
||||
JobKind Kind { get; }
|
||||
|
||||
Task RunAsync(JobContext context);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A handler that runs only some jobs of its kind. The engine leaves the others queued for other claimers and asks again
|
||||
/// at every claim, so an answer may change while the job waits: the server renders what its managed encoders produce,
|
||||
/// leaves the rest to render nodes, and takes those too in a managed format once no node can (BRIEF §14.5, §14.7).
|
||||
/// </summary>
|
||||
public interface ISelectiveJobHandler : IJobHandler
|
||||
{
|
||||
/// <summary>Whether this handler takes <paramref name="job"/> now. A job it cannot read should be taken, so it fails with its reason.</summary>
|
||||
ValueTask<bool> AcceptsAsync(Job job, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>A component that brings several handlers (the archive engine: scan, rebuild, verify, import, images, maintenance).</summary>
|
||||
public interface IJobHandlerProvider
|
||||
{
|
||||
IReadOnlyList<IJobHandler> CreateJobHandlers();
|
||||
}
|
||||
|
||||
/// <summary>Live progress of a running job (pushed to the job bar, the Jobs screen and WebSocket clients).</summary>
|
||||
public sealed record JobProgressInfo(Guid JobId, JobKind Kind, string? TargetLabel, long Done, long Total, double? ItemsPerSecond, TimeSpan? Eta, string? Message);
|
||||
|
||||
/// <summary>Everything a handler needs while it runs. Progress is cheap to report; the engine persists it at most every
|
||||
/// checkpoint interval (BRIEF §14.6: checkpoints every 5 s).</summary>
|
||||
public sealed class JobContext
|
||||
{
|
||||
private const int LogTailLines = 40;
|
||||
private readonly JobEngine _engine;
|
||||
private readonly TimeProvider _time;
|
||||
private readonly long _started;
|
||||
private readonly Queue<string> _log = new();
|
||||
private readonly Lock _gate = new();
|
||||
private readonly JobThroughput _throughput;
|
||||
private long _lastPersist;
|
||||
private int _progressFailures;
|
||||
|
||||
internal JobContext(JobEngine engine, Job job, CancellationToken cancellation)
|
||||
{
|
||||
_engine = engine;
|
||||
_time = engine.Options.Time;
|
||||
_started = _time.GetTimestamp();
|
||||
_lastPersist = _started;
|
||||
Job = job;
|
||||
Cancellation = cancellation;
|
||||
Checkpoint = job.Checkpoint;
|
||||
Done = job.ProgressDone;
|
||||
Total = job.ProgressTotal;
|
||||
_throughput = new JobThroughput(Done);
|
||||
if (job.LogTail is { Length: > 0 } tail)
|
||||
{
|
||||
foreach (var line in tail.Split('\n')) _log.Enqueue(line);
|
||||
}
|
||||
}
|
||||
|
||||
public Job Job { get; }
|
||||
|
||||
/// <summary>Signalled on cancel, pause and engine shutdown.</summary>
|
||||
public CancellationToken Cancellation { get; }
|
||||
|
||||
/// <summary>Resume cursor saved by a previous attempt (null on the first run).</summary>
|
||||
public string? Checkpoint { get; private set; }
|
||||
|
||||
public long Done { get; private set; }
|
||||
|
||||
public long Total { get; private set; }
|
||||
|
||||
public string? Message { get; private set; }
|
||||
|
||||
/// <summary>Reports progress; persisted and broadcast at most every checkpoint interval.</summary>
|
||||
public ValueTask ReportAsync(long done, long total, string? message = null) => ReportCoreAsync(done, total, message, force: false);
|
||||
|
||||
/// <summary>Saves a resume cursor together with the current progress (persisted immediately).</summary>
|
||||
public ValueTask CheckpointAsync(string checkpoint, long done, long total)
|
||||
{
|
||||
Checkpoint = checkpoint;
|
||||
return ReportCoreAsync(done, total, Message, force: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues follow-up work on this job's engine for the same user (light analysis after an import); null when the
|
||||
/// engine has no handler for <paramref name="kind"/>, since nothing here would run it. A follow-up never makes this job
|
||||
/// yield in the priority queue: it works on what this job produces.
|
||||
/// </summary>
|
||||
public Task<Job?> EnqueueFollowUpAsync(JobKind kind, IReadOnlyList<Guid> targets, string? label, string? parametersJson, JobPriority priority) =>
|
||||
_engine.EnqueueFollowUpAsync(Job.Id, kind, targets, label, parametersJson, priority, Job.CreatedBy, Cancellation);
|
||||
|
||||
/// <summary>Appends a line to the job log (the last lines are kept with the job).</summary>
|
||||
public void Log(string line)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_log.Enqueue($"{DateTime.UtcNow:HH:mm:ss} {line}");
|
||||
while (_log.Count > LogTailLines) _log.Dequeue();
|
||||
}
|
||||
}
|
||||
|
||||
internal string LogTail
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
foreach (var l in _log)
|
||||
{
|
||||
if (sb.Length > 0) sb.Append('\n');
|
||||
sb.Append(l);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Throughput and time left (<see cref="JobThroughput"/>); never throws, whatever the progress reported.</summary>
|
||||
internal (double? Rate, TimeSpan? Eta) Rate()
|
||||
{
|
||||
lock (_gate) return _throughput.Sample(_time.GetElapsedTime(_started).TotalSeconds, Done, Total);
|
||||
}
|
||||
|
||||
/// <summary>True the first time publishing this job's progress failed, so the failure is logged once.</summary>
|
||||
internal bool FirstProgressFailure() => Interlocked.Increment(ref _progressFailures) == 1;
|
||||
|
||||
private async ValueTask ReportCoreAsync(long done, long total, string? message, bool force)
|
||||
{
|
||||
Done = done;
|
||||
Total = total;
|
||||
Message = message;
|
||||
var now = _time.GetTimestamp();
|
||||
var due = _time.GetElapsedTime(Interlocked.Read(ref _lastPersist), now) >= _engine.Options.CheckpointInterval;
|
||||
_engine.PublishProgress(this);
|
||||
if (!force && !due) return;
|
||||
Interlocked.Exchange(ref _lastPersist, now);
|
||||
if (!await _engine.PersistAsync(this).ConfigureAwait(false))
|
||||
_engine.StopJob(Job.Id); // cancelled or paused by someone else
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.Data.Jobs;
|
||||
|
||||
/// <summary>How much a kind of job counts in the priority queue (<see cref="JobPriorityQueue"/>).</summary>
|
||||
public enum JobKindPriority
|
||||
{
|
||||
Low,
|
||||
Normal,
|
||||
High,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The priority queue of Settings (owner review 1, R2). Jobs always run one at a time. Off, they run in claim order
|
||||
/// (priority, then age) and a running job is never interrupted: the user pauses it to let the next one start. On, a kind
|
||||
/// of a higher <see cref="JobKindPriority"/> runs first, and a queued job of a higher level that the engine can run makes
|
||||
/// the running job of a lower level yield without asking: it goes back to the queue with its checkpoint and resumes by
|
||||
/// itself once nothing above it waits. Kinds of the same level never interrupt each other.
|
||||
/// </summary>
|
||||
public sealed record JobPriorityQueue
|
||||
{
|
||||
/// <summary>The levels a kind has unless the user changed it: renders, imports and downloads first; the long passes that resume anywhere last.</summary>
|
||||
public static IReadOnlyDictionary<JobKind, JobKindPriority> DefaultLevels { get; } = new Dictionary<JobKind, JobKindPriority>
|
||||
{
|
||||
[JobKind.Render] = JobKindPriority.High,
|
||||
[JobKind.Import] = JobKindPriority.High,
|
||||
[JobKind.Download] = JobKindPriority.High,
|
||||
[JobKind.Verify] = JobKindPriority.Low,
|
||||
[JobKind.Proxies] = JobKindPriority.Low,
|
||||
};
|
||||
|
||||
/// <summary>The strict queue: no levels, no interruptions.</summary>
|
||||
public static JobPriorityQueue Off { get; } = new();
|
||||
|
||||
/// <summary>Whether levels order the queue and interrupt lower jobs.</summary>
|
||||
public bool Enabled { get; init; }
|
||||
|
||||
/// <summary>Levels the user set; a kind not listed has its <see cref="DefaultLevels"/> level, else normal.</summary>
|
||||
public IReadOnlyDictionary<JobKind, JobKindPriority> Levels { get; init; } = new Dictionary<JobKind, JobKindPriority>();
|
||||
|
||||
/// <summary>The level of <paramref name="kind"/>.</summary>
|
||||
public JobKindPriority LevelOf(JobKind kind) =>
|
||||
Levels.TryGetValue(kind, out var level) || DefaultLevels.TryGetValue(kind, out level) ? level : JobKindPriority.Normal;
|
||||
|
||||
/// <summary>Whether a queued job of <paramref name="challenger"/> interrupts a running job of <paramref name="running"/>.</summary>
|
||||
public bool Interrupts(JobKind challenger, JobKind running) => Enabled && LevelOf(challenger) > LevelOf(running);
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="a"/> is claimed before <paramref name="b"/>: the higher level first while the queue is on,
|
||||
/// then the higher priority, the older job and the lower id (<see cref="Repositories.JobRepository.ClaimNextAsync"/>).
|
||||
/// </summary>
|
||||
public bool ClaimsBefore(Job a, Job b)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(a);
|
||||
ArgumentNullException.ThrowIfNull(b);
|
||||
if (Enabled && LevelOf(a.Kind) != LevelOf(b.Kind)) return LevelOf(a.Kind) > LevelOf(b.Kind);
|
||||
return a.Priority != b.Priority ? a.Priority > b.Priority : a.Created != b.Created ? a.Created < b.Created : a.Id.CompareTo(b.Id) < 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The SQL ordering of the queue (before priority, age and id): the levels of <paramref name="kinds"/>, highest first, as
|
||||
/// a <c>CASE</c> over the kind column; empty while the queue is off or every kind has the same level.
|
||||
/// </summary>
|
||||
internal string OrderSql(IEnumerable<JobKind> kinds)
|
||||
{
|
||||
if (!Enabled) return string.Empty;
|
||||
var levels = kinds.Distinct().GroupBy(LevelOf).Where(g => g.Key != JobKindPriority.Normal).ToList();
|
||||
if (levels.Count == 0) return string.Empty;
|
||||
var sql = new StringBuilder("CASE");
|
||||
foreach (var level in levels)
|
||||
{
|
||||
sql.Append(" WHEN kind IN (").AppendJoin(", ", level.Select(k => ((int)k).ToString(CultureInfo.InvariantCulture))).Append(") THEN ")
|
||||
.Append(((int)level.Key).ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
return sql.Append(" ELSE ").Append(((int)JobKindPriority.Normal).ToString(CultureInfo.InvariantCulture)).Append(" END DESC, ").ToString();
|
||||
}
|
||||
|
||||
/// <summary>Wire name of a level in API v1 and settings files: <c>high</c>, <c>normal</c>, <c>low</c>.</summary>
|
||||
public static string Wire(JobKindPriority level) => level.ToString().ToLowerInvariant();
|
||||
|
||||
/// <summary>The level named <paramref name="text"/> (<see cref="Wire"/>, any case); false for anything else.</summary>
|
||||
public static bool TryParse(string? text, out JobKindPriority level)
|
||||
{
|
||||
foreach (var candidate in Enum.GetValues<JobKindPriority>())
|
||||
{
|
||||
if (!string.Equals(text, Wire(candidate), StringComparison.OrdinalIgnoreCase)) continue;
|
||||
level = candidate;
|
||||
return true;
|
||||
}
|
||||
level = JobKindPriority.Normal;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The queue from settings: <paramref name="levels"/> maps kind names (<see cref="JobWire.Kind"/> or the enum name) to
|
||||
/// level names; unknown kinds and levels are skipped, so a settings file written by a newer build still loads.
|
||||
/// </summary>
|
||||
public static JobPriorityQueue From(bool enabled, IReadOnlyDictionary<string, string>? levels)
|
||||
{
|
||||
var parsed = new Dictionary<JobKind, JobKindPriority>();
|
||||
foreach (var (name, value) in levels ?? new Dictionary<string, string>())
|
||||
{
|
||||
if ((JobWire.TryParseKind(name, out var kind) || Enum.TryParse(name, ignoreCase: true, out kind)) && Enum.IsDefined(kind) && TryParse(value, out var level))
|
||||
parsed[kind] = level;
|
||||
}
|
||||
return new JobPriorityQueue { Enabled = enabled, Levels = parsed };
|
||||
}
|
||||
|
||||
/// <summary>The levels that differ from <see cref="DefaultLevels"/>, by wire kind name: what settings store.</summary>
|
||||
public static Dictionary<string, string> Changed(IReadOnlyDictionary<JobKind, JobKindPriority> levels)
|
||||
{
|
||||
var defaults = new JobPriorityQueue();
|
||||
return levels.Where(l => defaults.LevelOf(l.Key) != l.Value).OrderBy(l => l.Key)
|
||||
.ToDictionary(l => JobWire.Kind(l.Key), l => Wire(l.Value), StringComparer.Ordinal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
namespace Chronos.Data.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Time left of a job: unknown (null) when nothing remains, the rate is unknown, or the result is not a finite duration
|
||||
/// of at most <see cref="Max"/>. Every conversion of a stored or reported time left goes through here, so a stalled job
|
||||
/// shows no time left instead of overflowing <see cref="TimeSpan"/>.
|
||||
/// </summary>
|
||||
public static class JobEta
|
||||
{
|
||||
/// <summary>Longest time left worth showing; beyond it the job reads as stalled.</summary>
|
||||
public static readonly TimeSpan Max = TimeSpan.FromDays(365);
|
||||
|
||||
/// <summary>The time <paramref name="remaining"/> items take at <paramref name="perSecond"/>.</summary>
|
||||
public static TimeSpan? Of(long remaining, double? perSecond) =>
|
||||
remaining > 0 && perSecond is > 0 and var rate ? FromSeconds(remaining / rate) : null;
|
||||
|
||||
/// <summary>A stored or reported number of seconds as a time left, or null when it is not a usable one.</summary>
|
||||
public static TimeSpan? FromSeconds(double? seconds) =>
|
||||
seconds is { } s && double.IsFinite(s) && s >= 0 && s <= Max.TotalSeconds ? TimeSpan.FromSeconds(s) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Throughput of a running job as a moving average over windows of at least two seconds. The first window that saw
|
||||
/// progress seeds the average; each later window weighs 30 %. A window without progress lowers the rate, which tends to
|
||||
/// zero without reaching it: below <see cref="MinRate"/> it reads as unknown, and the time left with it.
|
||||
/// </summary>
|
||||
internal sealed class JobThroughput(long done)
|
||||
{
|
||||
private const double WindowSeconds = 2;
|
||||
|
||||
/// <summary>Items per second below which a job counts as stalled.</summary>
|
||||
internal const double MinRate = 1e-6;
|
||||
|
||||
private long _done = done;
|
||||
private double _seconds;
|
||||
private double? _rate;
|
||||
|
||||
/// <summary>Takes a sample at <paramref name="seconds"/> since the job started and returns the rate and time left.</summary>
|
||||
public (double? Rate, TimeSpan? Eta) Sample(double seconds, long done, long total)
|
||||
{
|
||||
if (done < _done)
|
||||
{
|
||||
// Progress went back (a handler restarted its count): start a new window there.
|
||||
_done = done;
|
||||
_seconds = seconds;
|
||||
}
|
||||
else if (seconds - _seconds >= WindowSeconds)
|
||||
{
|
||||
var sample = (done - _done) / (seconds - _seconds);
|
||||
if (_rate is { } previous) _rate = previous * 0.7 + sample * 0.3;
|
||||
else if (sample > 0) _rate = sample;
|
||||
_done = done;
|
||||
_seconds = seconds;
|
||||
}
|
||||
var rate = _rate is >= MinRate ? _rate : null;
|
||||
return (rate, JobEta.Of(total - done, rate));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
using System.Text;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.Data.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Wire names of job kinds, states and priorities in API v1: kebab-case (<c>deep-analyse</c>) and lower-case
|
||||
/// (<c>running</c>). The server writes them; clients read the server's jobs back with <see cref="FromDto"/>.
|
||||
/// </summary>
|
||||
public static class JobWire
|
||||
{
|
||||
public static string Kind(JobKind kind)
|
||||
{
|
||||
var name = kind.ToString();
|
||||
var sb = new StringBuilder(name.Length + 4);
|
||||
for (var i = 0; i < name.Length; i++)
|
||||
{
|
||||
if (i > 0 && char.IsUpper(name[i])) sb.Append('-');
|
||||
sb.Append(char.ToLowerInvariant(name[i]));
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
public static bool TryParseKind(string? text, out JobKind kind) => TryParse(text, Kind, out kind);
|
||||
|
||||
public static string State(JobState state) => state.ToString().ToLowerInvariant();
|
||||
|
||||
public static bool TryParseState(string? text, out JobState state) => TryParse(text, State, out state);
|
||||
|
||||
public static string Priority(JobPriority priority) => priority.ToString().ToLowerInvariant();
|
||||
|
||||
public static bool TryParsePriority(string? text, out JobPriority priority) => TryParse(text, Priority, out priority);
|
||||
|
||||
/// <summary>A server job as the client's job model; null for a kind or state this build does not know.</summary>
|
||||
public static Job? FromDto(JobDto dto)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(dto);
|
||||
if (!TryParseKind(dto.Kind, out var kind) || !TryParseState(dto.State, out var state)) return null;
|
||||
return new Job
|
||||
{
|
||||
Id = dto.Id,
|
||||
Kind = kind,
|
||||
TargetIds = dto.TargetIds,
|
||||
TargetLabel = dto.TargetLabel,
|
||||
State = state,
|
||||
Priority = TryParsePriority(dto.Priority, out var priority) ? priority : JobPriority.Normal,
|
||||
ProgressDone = dto.ProgressDone,
|
||||
ProgressTotal = dto.ProgressTotal,
|
||||
ItemsPerSecond = dto.ItemsPerSecond,
|
||||
Eta = JobEta.FromSeconds(dto.EtaSeconds),
|
||||
LogTail = dto.LogTail,
|
||||
NodeId = dto.NodeId,
|
||||
Attempts = dto.Attempts,
|
||||
Error = dto.Error,
|
||||
Created = dto.Created,
|
||||
Started = dto.Started,
|
||||
Finished = dto.Finished,
|
||||
};
|
||||
}
|
||||
|
||||
private static bool TryParse<T>(string? text, Func<T, string> name, out T value) where T : struct, Enum
|
||||
{
|
||||
foreach (var candidate in Enum.GetValues<T>())
|
||||
{
|
||||
if (string.Equals(name(candidate), text, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
value = candidate;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
value = default;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user