From ee9505df2231216c44ce8b2f7eaed21f7d49808f Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Sun, 15 Nov 2026 13:02:59 +0100 Subject: [PATCH] feat(jobs): progress detail contract and a 2/s publish throttle Mass passes need to say what they do now (photo x of y, sequence n of m) without slowing down. This adds the contract and the engine side; handlers and displays follow in their own parcels. - Core: JobDetail (step, item, item x of y, part n of m with unit), JobStep and JobPartUnit appended-only and stored by kebab name; Job.Detail. - Protocol: JobDetailDto, appended as JobDto.Detail, JobProgressEvent.Detail and NodeProgress.Detail, so older peers ignore it and newer ones fall back. - Data: JobContext keeps a detail across reports (ReportAsync with a detail, ReportItemAsync without allocating, CheckpointAsync with a detail) and publishes at most once per ProgressInterval (500 ms on the engine's TimeProvider), at once for the first report, a new step or a completed count; a dropped report costs no allocation or lock, and the persist that falls due publishes what it saves. Persist stays at most every 5 s. JobWire maps steps, units and details; an unknown name reads as none. - Migration 0011 adds jobs.progress_detail (nullable JSON text); an unreadable cell reads as no detail. Lists return it. - Server: ProgressGate (500 ms per job, step-change and completion bypass) shared by the engine host and render nodes; node details are stored and broadcast, an older node without one still works. Refs #65 Co-Authored-By: Claude Opus 5.5 --- src/Chronos.Core/Model/Entities.cs | 6 + src/Chronos.Core/Model/JobDetail.cs | 79 ++++++ src/Chronos.Data/Jobs/JobEngine.cs | 19 +- src/Chronos.Data/Jobs/JobHandler.cs | 112 ++++++++- src/Chronos.Data/Jobs/JobWire.cs | 80 +++++-- .../postgres/0011_job_progress_detail.sql | 6 + .../sqlite/0011_job_progress_detail.sql | 6 + .../Repositories/JobRepository.cs | 41 +++- src/Chronos.Protocol/Events.cs | 6 +- src/Chronos.Protocol/Jobs.cs | 25 +- src/Chronos.Protocol/ProtocolJson.cs | 1 + src/Chronos.Server/Api/Dto.cs | 2 +- src/Chronos.Server/Jobs/JobEngineHost.cs | 27 +-- src/Chronos.Server/Jobs/ProgressGate.cs | 53 +++++ src/Chronos.Server/Jobs/RenderNodeService.cs | 8 +- .../Jobs/JobContextProgressTests.cs | 225 ++++++++++++++++++ tests/Chronos.Data.Tests/Jobs/JobWireTests.cs | 69 ++++++ .../Migrations/MigrationTests.cs | 18 ++ .../Repositories/JobRepositoryTests.cs | 42 +++- .../Events/ProgressEventTests.cs | 206 ++++++++++++++++ 20 files changed, 968 insertions(+), 63 deletions(-) create mode 100644 src/Chronos.Core/Model/JobDetail.cs create mode 100644 src/Chronos.Data/Migrations/postgres/0011_job_progress_detail.sql create mode 100644 src/Chronos.Data/Migrations/sqlite/0011_job_progress_detail.sql create mode 100644 src/Chronos.Server/Jobs/ProgressGate.cs create mode 100644 tests/Chronos.Data.Tests/Jobs/JobContextProgressTests.cs create mode 100644 tests/Chronos.Server.Tests/Events/ProgressEventTests.cs diff --git a/src/Chronos.Core/Model/Entities.cs b/src/Chronos.Core/Model/Entities.cs index 636275c2..d7d99cc4 100644 --- a/src/Chronos.Core/Model/Entities.cs +++ b/src/Chronos.Core/Model/Entities.cs @@ -393,6 +393,12 @@ public sealed record Job /// The schedule that queued this job; null for jobs queued by a user or by other jobs (owner review 2, R10). public Guid? ScheduleId { get; init; } + + /// + /// What the job did when its progress was last saved (step, item, photo x of y, part n of m); null when its handler + /// reports none or the job never ran. Kept when the job stops, so a paused or failed one tells where it stopped. + /// + public JobDetail? Detail { get; init; } } /// diff --git a/src/Chronos.Core/Model/JobDetail.cs b/src/Chronos.Core/Model/JobDetail.cs new file mode 100644 index 00000000..c0414d7b --- /dev/null +++ b/src/Chronos.Core/Model/JobDetail.cs @@ -0,0 +1,79 @@ +namespace Chronos.Core.Model; + +/// +/// What a running job does now (). Values are appended only, never reordered or renamed: they +/// are stored and sent by their kebab-case name (copy-photo), and a name a build does not know reads as +/// . Each client words a step in its own language; a handler never sends progress text. +/// +public enum JobStep +{ + None, + List, + Check, + Index, + Verify, + Thumbs, + Proxies, + Analyse, + Convert, + Replace, + Reorganize, + CopyPhoto, + CopyProxy, + CopyOriginal, + CopyVideo, + Encode, + Upload, + Download, + Erase, + Backup, + Cleanup, + Maintenance, + FollowUps, + Process, +} + +/// +/// What a job counts its parts in (: sequence 12 of 340). Appended only and stored by name, +/// as . +/// +public enum JobPartUnit +{ + None, + Sequence, + Folder, + Render, + Entry, + Step, +} + +/// +/// The detail of a running job's progress beside its overall done and total, which alone drive the bar, the rate and the +/// time left: the step, the item it works on, how far it is inside that item (photo x of y) and which part of the job that +/// item is (sequence n of m). Data, never wording: clients localize the step and the unit. +/// +/// What the job does now. +/// +/// The sequence title, folder, file name, or the key of a sub-step (clean-up, maintenance) it works on; null for none. Cut +/// to characters. +/// +/// Photos (frames, files) done inside the item; 0 of 0 when not counted. +/// Photos (frames, files) of the item; 0 when not counted. +/// The 1-based part of the item is; 0 of 0 for a job of one part. +/// The parts of the job, counted in . +/// What a part is. +public sealed record JobDetail(JobStep Step, string? Item = null, long ItemDone = 0, long ItemTotal = 0, int Part = 0, int Parts = 0, + JobPartUnit PartUnit = JobPartUnit.None) +{ + /// The longest kept; a longer one is cut (never inside a surrogate pair). + public const int MaxItemLength = 160; + + public string? Item { get; init => field = Cut(value); } = Cut(Item); + + private static string? Cut(string? item) + { + if (item is not { Length: > MaxItemLength }) return item; + var length = char.IsHighSurrogate(item[MaxItemLength - 1]) ? MaxItemLength - 1 : MaxItemLength; + return item[..length]; + } +} diff --git a/src/Chronos.Data/Jobs/JobEngine.cs b/src/Chronos.Data/Jobs/JobEngine.cs index 469228fc..3ef4c784 100644 --- a/src/Chronos.Data/Jobs/JobEngine.cs +++ b/src/Chronos.Data/Jobs/JobEngine.cs @@ -22,10 +22,16 @@ public sealed record JobEngineOptions public TimeSpan CheckpointInterval { get; init; } = TimeSpan.FromSeconds(5); + /// + /// The shortest time between two publishes of one job's progress (): twice a second. A new + /// step, a count that completes and the run's first report go out at once (). + /// + public TimeSpan ProgressInterval { get; init; } = TimeSpan.FromMilliseconds(500); + /// Fallback poll for jobs enqueued by other processes; also how often the priority queue is reviewed. public TimeSpan PollInterval { get; init; } = TimeSpan.FromSeconds(3); - /// Clock of the throughput windows and the checkpoint interval (tests pass their own). + /// Clock of the throughput windows, the progress interval and the checkpoint interval (tests pass their own). public TimeProvider Time { get; init; } = TimeProvider.System; /// The priority queue as the settings have it now, asked at every claim and review; null: off (). @@ -77,7 +83,7 @@ public sealed class JobEngine : IAsyncDisposable /// A job changed state (queued, running, done, failed, cancelled, paused). public event Action? JobChanged; - /// Progress of a running job (high frequency; throttle in the UI). + /// Progress of a running job, at most once per per job but for new steps and completed counts. public event Action? Progress; public IReadOnlyCollection RunningJobIds => [.. _running.Keys]; @@ -202,7 +208,8 @@ public sealed class JobEngine : IAsyncDisposable 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)); + Progress?.Invoke(new JobProgressInfo(context.Job.Id, context.Job.Kind, context.Job.TargetLabel, context.Done, context.Total, rate, eta, context.Message, + context.Detail)); } catch (Exception ex) { @@ -211,7 +218,7 @@ public sealed class JobEngine : IAsyncDisposable } /// - /// Saves progress, checkpoint and log tail; false when the job no longer runs here (cancelled or paused elsewhere). + /// Saves progress, its detail, 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. /// internal async Task PersistAsync(JobContext context) @@ -219,8 +226,8 @@ public sealed class JobEngine : IAsyncDisposable 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); + return await _db.Jobs.UpdateProgressAsync(context.Job.Id, context.Done, context.Total, rate, eta, context.Checkpoint, context.LogTail, context.Detail, + CancellationToken.None).ConfigureAwait(false); } catch (DatabaseException ex) when (ex.IsTransient) { diff --git a/src/Chronos.Data/Jobs/JobHandler.cs b/src/Chronos.Data/Jobs/JobHandler.cs index 4c09f139..42021599 100644 --- a/src/Chronos.Data/Jobs/JobHandler.cs +++ b/src/Chronos.Data/Jobs/JobHandler.cs @@ -43,11 +43,20 @@ public interface IJobHandlerProvider IReadOnlyList CreateJobHandlers(); } -/// Live progress of a running job (pushed to the job bar, the Jobs screen and WebSocket clients). -public sealed record JobProgressInfo(Guid JobId, JobKind Kind, string? TargetLabel, long Done, long Total, double? ItemsPerSecond, TimeSpan? Eta, string? Message); +/// +/// Live progress of a running job (pushed to the job bar, the Jobs screen and WebSocket clients). : what +/// the job does now (step, item, photo x of y, part n of m), null when its handler reports none. +/// +public sealed record JobProgressInfo(Guid JobId, JobKind Kind, string? TargetLabel, long Done, long Total, double? ItemsPerSecond, TimeSpan? Eta, string? Message, + JobDetail? Detail = null); -/// 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). +/// +/// Everything a handler needs while it runs. Progress is cheap to report, so a handler may report every photo: the engine +/// publishes it at most once per progress interval (, twice a second) and at +/// once when the step changes, the job's count completes or it is the run's first report; a report it drops costs no +/// allocation, no lock and no rate. It persists progress at most every checkpoint interval (BRIEF §14.6: checkpoints every +/// 5 s), and a checkpoint at once; a persist that falls due also publishes the state it saves when the last report was dropped. +/// public sealed class JobContext { private const int LogTailLines = 40; @@ -59,6 +68,15 @@ public sealed class JobContext private readonly JobThroughput _throughput; private long _lastPersist; private int _progressFailures; + private JobDetail? _detail; + private long _itemDone; + private long _itemTotal; + private bool _published; + private long _lastPublish; + private JobStep _publishedStep; + private long _publishedDone; + private long _publishedTotal; + private bool _pending; internal JobContext(JobEngine engine, Job job, CancellationToken cancellation) { @@ -92,16 +110,62 @@ public sealed class JobContext public string? Message { get; private set; } - /// Reports progress; persisted and broadcast at most every checkpoint interval. + /// + /// What the job does now, as last reported (), with the item + /// counts of ; null until the handler reports one. Kept across reports that pass none. + /// + public JobDetail? Detail + { + get + { + var detail = _detail; + if (detail is null || (detail.ItemDone == _itemDone && detail.ItemTotal == _itemTotal)) return detail; + // Built when read (a publish, a persist), not at each report. + return _detail = detail with { ItemDone = _itemDone, ItemTotal = _itemTotal }; + } + } + + /// Reports progress, keeping the ; published at most every progress interval, persisted at most every checkpoint interval. public ValueTask ReportAsync(long done, long total, string? message = null) => ReportCoreAsync(done, total, message, force: false); - /// Saves a resume cursor together with the current progress (persisted immediately). + /// + /// Reports progress with what the job does now (, kept for the reports that follow); published + /// at once when its step differs from the last one published, else as . + /// + public ValueTask ReportAsync(long done, long total, JobDetail detail, string? message = null) + { + SetDetail(detail); + return ReportCoreAsync(done, total, message, force: false); + } + + /// + /// Reports progress inside the current item (photo of ) without a + /// new , so a handler can report every photo without allocating; with no detail reported yet the + /// step is . Keeps the . + /// + public ValueTask ReportItemAsync(long done, long total, long itemDone, long itemTotal) + { + _detail ??= new JobDetail(JobStep.Process); + _itemDone = itemDone; + _itemTotal = itemTotal; + return ReportCoreAsync(done, total, Message, force: false); + } + + /// Saves a resume cursor together with the current progress (persisted immediately), keeping the . public ValueTask CheckpointAsync(string checkpoint, long done, long total) { Checkpoint = checkpoint; return ReportCoreAsync(done, total, Message, force: true); } + /// Saves a resume cursor together with the current progress and what the job does now (persisted immediately). + public ValueTask CheckpointAsync(string checkpoint, long done, long total, JobDetail detail) + { + SetDetail(detail); + Checkpoint = checkpoint; + return ReportCoreAsync(done, total, Message, force: true); + } + /// /// 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 , since nothing here would run it. A follow-up never makes this job @@ -156,6 +220,14 @@ public sealed class JobContext /// True the first time publishing this job's progress failed, so the failure is logged once. internal bool FirstProgressFailure() => Interlocked.Increment(ref _progressFailures) == 1; + private void SetDetail(JobDetail detail) + { + ArgumentNullException.ThrowIfNull(detail); + _detail = detail; + _itemDone = detail.ItemDone; + _itemTotal = detail.ItemTotal; + } + private async ValueTask ReportCoreAsync(long done, long total, string? message, bool force) { Done = done; @@ -163,10 +235,36 @@ public sealed class JobContext Message = message; var now = _time.GetTimestamp(); var due = _time.GetElapsedTime(Interlocked.Read(ref _lastPersist), now) >= _engine.Options.CheckpointInterval; - _engine.PublishProgress(this); + if (Publishes(now)) Publish(now); + else _pending = true; if (!force && !due) return; Interlocked.Exchange(ref _lastPersist, now); + // The persist that falls due shows what it saves, so a job that went quiet after a dropped report is not left behind. + if (due && _pending) Publish(now); if (!await _engine.PersistAsync(this).ConfigureAwait(false)) _engine.StopJob(Job.Id); // cancelled or paused by someone else } + + /// + /// Whether this report goes out now: the run's first, a new step, a count that completes (once), or the progress interval + /// passed since the last one. Reads fields and the clock only. + /// + private bool Publishes(long now) + { + if (!_published) return true; + if ((_detail?.Step ?? JobStep.None) != _publishedStep) return true; + if (Total > 0 && Done >= Total && (Done != _publishedDone || Total != _publishedTotal)) return true; + return _time.GetElapsedTime(_lastPublish, now) >= _engine.Options.ProgressInterval; + } + + private void Publish(long now) + { + _published = true; + _lastPublish = now; + _publishedStep = _detail?.Step ?? JobStep.None; + _publishedDone = Done; + _publishedTotal = Total; + _pending = false; + _engine.PublishProgress(this); + } } diff --git a/src/Chronos.Data/Jobs/JobWire.cs b/src/Chronos.Data/Jobs/JobWire.cs index 63158120..fe77e9a6 100644 --- a/src/Chronos.Data/Jobs/JobWire.cs +++ b/src/Chronos.Data/Jobs/JobWire.cs @@ -1,29 +1,69 @@ using System.Text; +using System.Text.Json; using Chronos.Core.Model; using Chronos.Protocol; namespace Chronos.Data.Jobs; /// -/// Wire names of job kinds, states and priorities in API v1: kebab-case (deep-analyse) and lower-case -/// (running). The server writes them; clients read the server's jobs back with . +/// Wire names of job kinds, states, priorities, progress steps and part units in API v1: kebab-case (deep-analyse, +/// copy-photo) and lower-case (running). The server writes them; clients read the server's jobs back with +/// . The jobs table stores a progress detail in the same form (). /// 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 string Kind(JobKind kind) => Kebab(kind.ToString()); public static bool TryParseKind(string? text, out JobKind kind) => TryParse(text, Kind, out kind); + public static string Step(JobStep step) => Kebab(step.ToString()); + + public static bool TryParseStep(string? text, out JobStep step) => TryParse(text, Step, out step); + + public static string PartUnit(JobPartUnit unit) => Kebab(unit.ToString()); + + public static bool TryParsePartUnit(string? text, out JobPartUnit unit) => TryParse(text, PartUnit, out unit); + + /// A progress detail as API v1 sends it; null for none. A unit of none is left out. + public static JobDetailDto? Detail(JobDetail? detail) => detail is null + ? null + : new JobDetailDto(Step(detail.Step), detail.Item, detail.ItemDone, detail.ItemTotal, detail.Part, detail.Parts, + detail.PartUnit == JobPartUnit.None ? null : PartUnit(detail.PartUnit)); + + /// + /// A progress detail of a server or a render node as the job model has it; null for none. A step or unit this build does + /// not know reads as none (the counts still show), a negative count as 0, and an item is cut to + /// characters. + /// + public static JobDetail? FromDto(JobDetailDto? dto) => dto is null + ? null + : new JobDetail( + TryParseStep(dto.Step, out var step) ? step : JobStep.None, + dto.Item, + Math.Max(0, dto.ItemDone), + Math.Max(0, dto.ItemTotal), + Math.Max(0, dto.Part), + Math.Max(0, dto.Parts), + TryParsePartUnit(dto.PartUnit, out var unit) ? unit : JobPartUnit.None); + + /// A progress detail as the jobs table stores it (the JSON of ); null for none. + public static string? DetailJson(JobDetail? detail) => + Detail(detail) is { } dto ? JsonSerializer.Serialize(dto, ProtocolJson.Default.JobDetailDto) : null; + + /// A stored progress detail (); null for none and for a cell that cannot be read, never an error. + public static JobDetail? ParseDetailJson(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return null; + try + { + return FromDto(JsonSerializer.Deserialize(json, ProtocolJson.Default.JobDetailDto)); + } + catch (JsonException) + { + return null; + } + } + public static string State(JobState state) => state.ToString().ToLowerInvariant(); public static bool TryParseState(string? text, out JobState state) => TryParse(text, State, out state); @@ -32,7 +72,7 @@ public static class JobWire public static bool TryParsePriority(string? text, out JobPriority priority) => TryParse(text, Priority, out priority); - /// A server job as the client's job model; null for a kind or state this build does not know. + /// A server job as the client's job model, its progress detail included; null for a kind or state this build does not know. public static Job? FromDto(JobDto dto) { ArgumentNullException.ThrowIfNull(dto); @@ -57,9 +97,21 @@ public static class JobWire Started = dto.Started, Finished = dto.Finished, ScheduleId = dto.ScheduleId, + Detail = FromDto(dto.Detail), }; } + private static string Kebab(string name) + { + 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(); + } + private static bool TryParse(string? text, Func name, out T value) where T : struct, Enum { foreach (var candidate in Enum.GetValues()) diff --git a/src/Chronos.Data/Migrations/postgres/0011_job_progress_detail.sql b/src/Chronos.Data/Migrations/postgres/0011_job_progress_detail.sql new file mode 100644 index 00000000..ec772b31 --- /dev/null +++ b/src/Chronos.Data/Migrations/postgres/0011_job_progress_detail.sql @@ -0,0 +1,6 @@ +-- The detail of a job's progress (owner review 5, #65): what it did when its progress was last saved (step, item, photo x +-- of y, part n of m), as the JSON of API v1's JobDetailDto with kebab-case keys. Null when its handler reports none; kept +-- when the job stops, so a paused or failed job tells where it stopped. Plain text, not jsonb: a cell the build cannot read +-- is treated as none. No backfill, no index. Mirrors sqlite/0011_job_progress_detail.sql. + +ALTER TABLE jobs ADD COLUMN progress_detail text; diff --git a/src/Chronos.Data/Migrations/sqlite/0011_job_progress_detail.sql b/src/Chronos.Data/Migrations/sqlite/0011_job_progress_detail.sql new file mode 100644 index 00000000..6aa5e164 --- /dev/null +++ b/src/Chronos.Data/Migrations/sqlite/0011_job_progress_detail.sql @@ -0,0 +1,6 @@ +-- The detail of a job's progress (owner review 5, #65): what it did when its progress was last saved (step, item, photo x +-- of y, part n of m), as the JSON of API v1's JobDetailDto with kebab-case keys. Null when its handler reports none; kept +-- when the job stops, so a paused or failed job tells where it stopped. No backfill, no index. Mirrors +-- postgres/0011_job_progress_detail.sql. + +ALTER TABLE jobs ADD COLUMN progress_detail TEXT; diff --git a/src/Chronos.Data/Repositories/JobRepository.cs b/src/Chronos.Data/Repositories/JobRepository.cs index 15766f17..70c40d69 100644 --- a/src/Chronos.Data/Repositories/JobRepository.cs +++ b/src/Chronos.Data/Repositories/JobRepository.cs @@ -21,15 +21,16 @@ public sealed class JobRepository { private const string Columns = "id, kind, target_ids, target_label, parameters_json, state, priority, progress_done, progress_total, items_per_second, " + - "eta_seconds, checkpoint, log_tail, created_by, node_id, attempts, error, created, started, finished, schedule_id"; + "eta_seconds, checkpoint, log_tail, created_by, node_id, attempts, error, created, started, finished, schedule_id, progress_detail"; /// /// as lists read them (): the parameters left out, null. A conversion's or /// an import's name every sequence or file they work on; the job reads them, and so do the screens that act on that one job. + /// The progress detail is small and stays: a list shows where a paused job stopped. /// private const string BriefColumns = "id, kind, target_ids, target_label, CAST(NULL AS TEXT), state, priority, progress_done, progress_total, items_per_second, " + - "eta_seconds, checkpoint, log_tail, created_by, node_id, attempts, error, created, started, finished, schedule_id"; + "eta_seconds, checkpoint, log_tail, created_by, node_id, attempts, error, created, started, finished, schedule_id, progress_detail"; /// The states of a job that has not ended: queued, running, paused. private static readonly string PendingStates = @@ -41,11 +42,11 @@ public sealed class JobRepository public async Task EnqueueAsync(Job job, CancellationToken cancellationToken = default) => await _db.ExecuteAsync( - $"INSERT INTO jobs ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21)", + $"INSERT INTO jobs ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22)", [ job.Id, (int)job.Kind, string.Join(',', job.TargetIds), job.TargetLabel, DbParam.Json(job.ParametersJson), (int)job.State, (int)job.Priority, job.ProgressDone, job.ProgressTotal, job.ItemsPerSecond, job.Eta?.TotalSeconds, job.Checkpoint, job.LogTail, - job.CreatedBy, job.NodeId, job.Attempts, job.Error, job.Created, job.Started, job.Finished, job.ScheduleId, + job.CreatedBy, job.NodeId, job.Attempts, job.Error, job.Created, job.Started, job.Finished, job.ScheduleId, JobWire.DetailJson(job.Detail), ], cancellationToken).ConfigureAwait(false); public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => @@ -89,15 +90,23 @@ public sealed class JobRepository } /// - /// Checkpoint of a running job. Returns false when the job is no longer running (cancelled or paused meanwhile), - /// which tells the worker to stop. + /// Checkpoint of a running job, without a progress detail (it is cleared). Returns false when the job is no longer + /// running (cancelled or paused meanwhile), which tells the worker to stop. + /// + public Task UpdateProgressAsync(Guid id, long done, long total, double? itemsPerSecond, TimeSpan? eta, + string? checkpoint, string? logTail, CancellationToken cancellationToken = default) => + UpdateProgressAsync(id, done, total, itemsPerSecond, eta, checkpoint, logTail, null, cancellationToken); + + /// + /// Checkpoint of a running job with what it does now (, null for none), written in the same + /// statement. Returns false when the job is no longer running (cancelled or paused meanwhile), which tells the worker to stop. /// public async Task UpdateProgressAsync(Guid id, long done, long total, double? itemsPerSecond, TimeSpan? eta, - string? checkpoint, string? logTail, CancellationToken cancellationToken = default) => + string? checkpoint, string? logTail, JobDetail? detail, CancellationToken cancellationToken = default) => await _db.ExecuteAsync( - "UPDATE jobs SET progress_done = $2, progress_total = $3, items_per_second = $4, eta_seconds = $5, checkpoint = $6, log_tail = $7 " + + "UPDATE jobs SET progress_done = $2, progress_total = $3, items_per_second = $4, eta_seconds = $5, checkpoint = $6, log_tail = $7, progress_detail = $8 " + $"WHERE id = $1 AND state = {(int)JobState.Running}", - [id, done, total, itemsPerSecond, eta?.TotalSeconds, checkpoint, logTail], cancellationToken).ConfigureAwait(false) > 0; + [id, done, total, itemsPerSecond, eta?.TotalSeconds, checkpoint, logTail, JobWire.DetailJson(detail)], cancellationToken).ConfigureAwait(false) > 0; /// Moves a job to ; done/failed/cancelled stamp the finish time, queued clears it for a retry. public async Task SetStateAsync(Guid id, JobState state, string? error = null, CancellationToken cancellationToken = default) @@ -330,7 +339,7 @@ public sealed class JobRepository return await session.QuerySingleOrDefaultAsync($"SELECT {Columns} FROM jobs WHERE id = $1", [id], Map, cancellationToken).ConfigureAwait(false); }, cancellationToken); - /// Progress of a job a render node runs; false when the job is no longer running on that node. + /// Progress of a job a render node runs, its progress detail kept; false when the job is no longer running on that node. public async Task UpdateNodeProgressAsync(Guid id, string nodeId, long done, long total, double? itemsPerSecond, TimeSpan? eta, string? logTail, CancellationToken cancellationToken = default) => await _db.ExecuteAsync( @@ -338,6 +347,17 @@ public sealed class JobRepository $"WHERE id = $1 AND node_id = $2 AND state = {(int)JobState.Running}", [id, nodeId, done, total, itemsPerSecond, eta?.TotalSeconds, logTail], cancellationToken).ConfigureAwait(false) > 0; + /// + /// Progress of a job a render node runs with what the node does now (; null, from an older node, + /// clears it); false when the job is no longer running on that node. + /// + public async Task UpdateNodeProgressAsync(Guid id, string nodeId, long done, long total, double? itemsPerSecond, TimeSpan? eta, + string? logTail, JobDetail? detail, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync( + "UPDATE jobs SET progress_done = $3, progress_total = $4, items_per_second = $5, eta_seconds = $6, log_tail = $7, progress_detail = $8 " + + $"WHERE id = $1 AND node_id = $2 AND state = {(int)JobState.Running}", + [id, nodeId, done, total, itemsPerSecond, eta?.TotalSeconds, logTail, JobWire.DetailJson(detail)], cancellationToken).ConfigureAwait(false) > 0; + /// Ends a job a render node runs (done or failed); false when it is no longer running on that node. public async Task FinishNodeJobAsync(Guid id, string nodeId, JobState state, string? error, string? logTail, CancellationToken cancellationToken = default) { @@ -391,5 +411,6 @@ public sealed class JobRepository Started = r.GetDateTimeOffsetOrNull(18), Finished = r.GetDateTimeOffsetOrNull(19), ScheduleId = r.GetGuidOrNull(20), + Detail = JobWire.ParseDetailJson(r.GetStringOrNull(21)), }; } diff --git a/src/Chronos.Protocol/Events.cs b/src/Chronos.Protocol/Events.cs index aaeac114..09efb9ac 100644 --- a/src/Chronos.Protocol/Events.cs +++ b/src/Chronos.Protocol/Events.cs @@ -17,7 +17,11 @@ namespace Chronos.Protocol; [JsonDerivedType(typeof(ProjectChangedEvent), "projectChanged")] public abstract record ServerEvent; -public sealed record JobProgressEvent(Guid JobId, long Done, long Total, double? ItemsPerSecond, double? EtaSeconds) : ServerEvent; +/// +/// A running job's progress, sent at most twice a second per job. (owner review 5, #65): what it does +/// now; appended, absent from an older server, ignored by an older client. +/// +public sealed record JobProgressEvent(Guid JobId, long Done, long Total, double? ItemsPerSecond, double? EtaSeconds, JobDetailDto? Detail = null) : ServerEvent; public sealed record JobStateEvent(Guid JobId, string State, string? Error) : ServerEvent; diff --git a/src/Chronos.Protocol/Jobs.cs b/src/Chronos.Protocol/Jobs.cs index eb0bc69e..222c7285 100644 --- a/src/Chronos.Protocol/Jobs.cs +++ b/src/Chronos.Protocol/Jobs.cs @@ -1,6 +1,10 @@ namespace Chronos.Protocol; -/// A job of the queue. : the schedule that queued it (owner review 2, R10), absent otherwise. +/// +/// A job of the queue. : the schedule that queued it (owner review 2, R10), absent otherwise. +/// : what it did when its progress was last saved (owner review 5, #65), absent from an older server or +/// for a job whose handler reports none; appended, so an older client ignores it. +/// public sealed record JobDto( Guid Id, string Kind, @@ -19,7 +23,17 @@ public sealed record JobDto( DateTimeOffset Created, DateTimeOffset? Started, DateTimeOffset? Finished, - Guid? ScheduleId = null); + Guid? ScheduleId = null, + JobDetailDto? Detail = null); + +/// +/// What a running job does now, beside its overall progress (owner review 5, #65): and +/// are kebab-case keys (copy-photo, sequence) each client words in its own language; +/// a key a client does not know reads as none, and the counts still show. is data (a sequence title, a +/// folder, a file name, a sub-step key), at most 160 characters. of counts +/// the photos inside the item, of the item among the job's parts; 0 of 0 when not counted. +/// +public sealed record JobDetailDto(string Step, string? Item = null, long ItemDone = 0, long ItemTotal = 0, int Part = 0, int Parts = 0, string? PartUnit = null); /// POST /api/v1/jobs: kind = render, deep-analyse, proxies, thumbs, verify, scan, rebuild, maintenance… public sealed record CreateJobRequest(string Kind, IReadOnlyList Target, string? ParametersJson); @@ -48,8 +62,11 @@ public sealed record RenderNodeDto(Guid Id, string ClientName, string Username, public sealed record ClaimedJob(JobDto Job, Guid SequenceId, string SettingsJson, string PresetJson, bool UseProxies, IReadOnlyList Frames, ProxySpec? Proxies = null); -/// POST /api/v1/nodes/{id}/jobs/{jobId}/progress. -public sealed record NodeProgress(long Done, long Total, double? ItemsPerSecond, string? LogLine); +/// +/// POST /api/v1/nodes/{id}/jobs/{jobId}/progress. (owner review 5, #65): what the node does now; +/// appended, so an older node sends none (the server then shows the counts alone) and an older server ignores it. +/// +public sealed record NodeProgress(long Done, long Total, double? ItemsPerSecond, string? LogLine, JobDetailDto? Detail = null); /// POST /api/v1/jobs/{id}/priority: background, normal or user. public sealed record JobPriorityRequest(string Priority); diff --git a/src/Chronos.Protocol/ProtocolJson.cs b/src/Chronos.Protocol/ProtocolJson.cs index 24eff253..e73054f0 100644 --- a/src/Chronos.Protocol/ProtocolJson.cs +++ b/src/Chronos.Protocol/ProtocolJson.cs @@ -37,6 +37,7 @@ namespace Chronos.Protocol; [JsonSerializable(typeof(UploadState))] [JsonSerializable(typeof(CardImportReport))] [JsonSerializable(typeof(JobDto))] +[JsonSerializable(typeof(JobDetailDto))] [JsonSerializable(typeof(Page))] [JsonSerializable(typeof(CreateJobRequest))] [JsonSerializable(typeof(RegisterNodeRequest))] diff --git a/src/Chronos.Server/Api/Dto.cs b/src/Chronos.Server/Api/Dto.cs index dd6c37e9..df296036 100644 --- a/src/Chronos.Server/Api/Dto.cs +++ b/src/Chronos.Server/Api/Dto.cs @@ -29,7 +29,7 @@ public static class Dto public static JobDto Job(Job j) => new( j.Id, JobWire.Kind(j.Kind), j.TargetIds, j.TargetLabel, JobWire.State(j.State), JobWire.Priority(j.Priority), j.ProgressDone, j.ProgressTotal, j.ItemsPerSecond, j.Eta?.TotalSeconds, j.LogTail, j.NodeId, j.Attempts, j.Error, j.Created, j.Started, j.Finished, - j.ScheduleId); + j.ScheduleId, JobWire.Detail(j.Detail)); public static AuditEntryDto Audit(AuditEntry a) => new(a.Id, a.At, a.UserId, a.Username, a.Action, a.TargetKind, a.TargetId, a.Details, a.RemoteAddress); diff --git a/src/Chronos.Server/Jobs/JobEngineHost.cs b/src/Chronos.Server/Jobs/JobEngineHost.cs index e77f3fc1..79ddec33 100644 --- a/src/Chronos.Server/Jobs/JobEngineHost.cs +++ b/src/Chronos.Server/Jobs/JobEngineHost.cs @@ -1,4 +1,3 @@ -using System.Diagnostics; using Chronos.Core.Model; using Chronos.Data; using Chronos.Data.Jobs; @@ -16,22 +15,20 @@ namespace Chronos.Server.Jobs; /// running one, in the order of the priority queue of the settings (owner review 1). Render jobs run here only when the registered render /// handler accepts them (: managed formats, and MP4 jobs no render node can take); /// render nodes claim the others (BRIEF §14.5, §14.7). On shutdown running jobs stay marked running and are requeued from their checkpoints at the next start. +/// Progress goes out through the render nodes share, with what each job does now (owner review 5, #65). /// public sealed class JobEngineHost : IHostedService { - private static readonly long ProgressInterval = Stopwatch.Frequency / 4; - private readonly ChronosDatabase _db; private readonly EventHub _events; private readonly HashSet _kinds; - private readonly Dictionary _lastProgress = []; - private readonly Lock _gate = new(); public JobEngineHost(ChronosDatabase db, IEnumerable handlers, IEnumerable providers, ServerOptions options, - EventHub events) + EventHub events, TimeProvider time) { _db = db; _events = events; + Gate = new ProgressGate(time); // A render handler must be selective: a plain one would take the jobs that need a render node's encoder. var local = handlers.Concat(providers.SelectMany(p => p.CreateJobHandlers())).Where(h => h.Kind != JobKind.Render || h is ISelectiveJobHandler).ToList(); _kinds = [.. local.Select(h => h.Kind)]; @@ -51,6 +48,9 @@ public sealed class JobEngineHost : IHostedService public JobEngine Engine { get; } + /// The pace of every job's progress events, the server's own jobs and render nodes' alike. + public ProgressGate Gate { get; } + /// True when a job of has somewhere to run: a local handler, or render nodes for renders. public bool CanRun(JobKind kind) => kind == JobKind.Render || _kinds.Contains(kind); @@ -63,21 +63,14 @@ public sealed class JobEngineHost : IHostedService private void OnJobChanged(Job job) { - if (job.State != JobState.Running) - { - lock (_gate) _lastProgress.Remove(job.Id); - } + if (job.State != JobState.Running) Gate.Forget(job.Id); _events.Publish(new JobStateEvent(job.Id, JobWire.State(job.State), job.Error)); } private void OnProgress(JobProgressInfo progress) { - var now = Stopwatch.GetTimestamp(); - lock (_gate) - { - if (_lastProgress.TryGetValue(progress.JobId, out var last) && now - last < ProgressInterval && progress.Done < progress.Total) return; - _lastProgress[progress.JobId] = now; - } - _events.Publish(new JobProgressEvent(progress.JobId, progress.Done, progress.Total, progress.ItemsPerSecond, progress.Eta?.TotalSeconds)); + if (!Gate.Passes(progress.JobId, progress.Done, progress.Total, progress.Detail?.Step ?? JobStep.None)) return; + _events.Publish(new JobProgressEvent(progress.JobId, progress.Done, progress.Total, progress.ItemsPerSecond, progress.Eta?.TotalSeconds, + JobWire.Detail(progress.Detail))); } } diff --git a/src/Chronos.Server/Jobs/ProgressGate.cs b/src/Chronos.Server/Jobs/ProgressGate.cs new file mode 100644 index 00000000..4c2d8a79 --- /dev/null +++ b/src/Chronos.Server/Jobs/ProgressGate.cs @@ -0,0 +1,53 @@ +using Chronos.Core.Model; + +namespace Chronos.Server.Jobs; + +/// +/// How often a job's progress goes out on the event socket (owner review 5, #65): at most once per +/// per job, for the server's own jobs () and those render nodes run () +/// alike. A job's first report, a new step and a count that completes always pass. A job that stops running is forgotten +/// (), so its next run starts afresh. +/// +public sealed class ProgressGate(TimeProvider time) +{ + /// The shortest time between two progress events of one job: twice a second, as the job engine publishes. + public static readonly TimeSpan Interval = TimeSpan.FromMilliseconds(500); + + /// + /// What a report may come early by and still pass: the engine spaces its reports by the same interval, measured a moment + /// before this gate reads its own clock, and a report it sent on time must not wait for the next one. + /// + private static readonly TimeSpan Slack = TimeSpan.FromMilliseconds(50); + + private readonly Dictionary _last = []; + private readonly Lock _gate = new(); + + /// True when the report ( of , at ) goes out now; it is then the job's last. + public bool Passes(Guid jobId, long done, long total, JobStep step) + { + var now = time.GetTimestamp(); + lock (_gate) + { + if (_last.TryGetValue(jobId, out var last) && last.Step == step && !(total > 0 && done >= total) + && time.GetElapsedTime(last.At, now) < Interval - Slack) + return false; + _last[jobId] = (now, step); + return true; + } + } + + /// Forgets a job that no longer runs (done, failed, paused, requeued). + public void Forget(Guid jobId) + { + lock (_gate) _last.Remove(jobId); + } + + /// The jobs the gate remembers (tests). + internal int Count + { + get + { + lock (_gate) return _last.Count; + } + } +} diff --git a/src/Chronos.Server/Jobs/RenderNodeService.cs b/src/Chronos.Server/Jobs/RenderNodeService.cs index bc2866bc..5d3adef7 100644 --- a/src/Chronos.Server/Jobs/RenderNodeService.cs +++ b/src/Chronos.Server/Jobs/RenderNodeService.cs @@ -185,10 +185,14 @@ public sealed class RenderNodeService( var rate = progress.ItemsPerSecond is { } r && double.IsFinite(r) && r > 0 ? r : (double?)null; var eta = JobEta.Of(progress.Total - progress.Done, rate); var tail = AppendLog(job.LogTail, progress.LogLine); - if (!await db.Jobs.UpdateNodeProgressAsync(jobId, NodeKey(node), progress.Done, progress.Total, rate, eta, tail, cancellationToken)) + // What the node does now (owner review 5, #65), read as this build knows it; an older node sends none, which clears it. + var detail = JobWire.FromDto(progress.Detail); + if (!await db.Jobs.UpdateNodeProgressAsync(jobId, NodeKey(node), progress.Done, progress.Total, rate, eta, tail, detail, cancellationToken)) return Outcome.Fail(409, "job_not_assigned"); await TouchAsync(node, cancellationToken); - events.Publish(new JobProgressEvent(jobId, progress.Done, progress.Total, rate, eta?.TotalSeconds)); + // Every report is stored; the event socket gets them at the pace of the server's own jobs. + if (jobs.Gate.Passes(jobId, progress.Done, progress.Total, detail?.Step ?? JobStep.None)) + events.Publish(new JobProgressEvent(jobId, progress.Done, progress.Total, rate, eta?.TotalSeconds, JobWire.Detail(detail))); return true; } diff --git a/tests/Chronos.Data.Tests/Jobs/JobContextProgressTests.cs b/tests/Chronos.Data.Tests/Jobs/JobContextProgressTests.cs new file mode 100644 index 00000000..f2c969a9 --- /dev/null +++ b/tests/Chronos.Data.Tests/Jobs/JobContextProgressTests.cs @@ -0,0 +1,225 @@ +using Chronos.Core.Model; +using Chronos.Data.Jobs; +using Chronos.Testing; + +namespace Chronos.Data.Tests.Jobs; + +/// +/// How a running job's progress goes out (owner review 5, #65): at most twice a second, at once for the run's first report, +/// a new step and a completed count, and with the persist that falls due when the last report was dropped; saved at most +/// every checkpoint interval and at each checkpoint, with its detail. +/// +[Category("jobs")] +public sealed class JobContextProgressTests(TestContext context) +{ + private static readonly TimeSpan Tick = TimeSpan.FromMilliseconds(10); + + [Test] + public async Task AHundredReportsInASecondGoOutAtMostThreeTimes() + { + await using var run = await StartAsync(); + for (var i = 1; i <= 100; i++) + { + await run.Context.ReportAsync(i, 1000); + run.Time.Advance(Tick); + } + Assert.True(run.Published.Count <= 3, $"{run.Published.Count} publishes"); + // The first at once, then one per half second. + Assert.SequenceEqual([1L, 51L], run.Published.Select(p => p.Done)); + } + + [Test] + public async Task ANewStepAndACompletedCountGoOutAtOnce() + { + await using var run = await StartAsync(); + var index = new JobDetail(JobStep.Index, "2024/Harbour sunset", 1, 5, 1, 2, JobPartUnit.Folder); + await run.Context.ReportAsync(1, 10, new JobDetail(JobStep.List)); + run.Time.Advance(Tick); + await run.Context.ReportAsync(2, 10, new JobDetail(JobStep.List)); + run.Time.Advance(Tick); + await run.Context.ReportAsync(3, 10, index); + run.Time.Advance(Tick); + await run.Context.ReportItemAsync(4, 10, 2, 5); + run.Time.Advance(Tick); + await run.Context.ReportAsync(10, 10); + run.Time.Advance(Tick); + await run.Context.ReportAsync(10, 10); + + Assert.SequenceEqual([1L, 3L, 10L], run.Published.Select(p => p.Done)); + Assert.Equal(index, run.Published[1].Detail); + // A report without a detail keeps the last one, with the item counts reported since. + Assert.Equal(index with { ItemDone = 2 }, run.Published[2].Detail); + Assert.Equal(index with { ItemDone = 2 }, run.Context.Detail); + } + + [Test] + public async Task ADroppedReportGoesOutWithThePersistThatFallsDue() + { + await using var run = await StartAsync(); + await run.Context.ReportAsync(1, 100); + run.Time.Advance(TimeSpan.FromSeconds(4.8)); + await run.Context.ReportAsync(2, 100); + Assert.Equal(0L, (await run.StoredAsync()).ProgressDone); + run.Time.Advance(TimeSpan.FromSeconds(0.2)); + // Too soon for a publish, but the persist falls due: it shows what it saves. + await run.Context.ReportAsync(3, 100); + Assert.SequenceEqual([1L, 2L, 3L], run.Published.Select(p => p.Done)); + Assert.Equal(3L, (await run.StoredAsync()).ProgressDone); + } + + [Test] + public async Task ProgressIsSavedAtMostEveryCheckpointIntervalAndAtEachCheckpoint() + { + await using var run = await StartAsync(); + for (var i = 1; i <= 50; i++) + { + await run.Context.ReportAsync(i, 100); + run.Time.Advance(TimeSpan.FromMilliseconds(99)); + } + Assert.Equal(0L, (await run.StoredAsync()).ProgressDone); + run.Time.Advance(TimeSpan.FromMilliseconds(50)); + await run.Context.ReportAsync(51, 100); + Assert.Equal(51L, (await run.StoredAsync()).ProgressDone); + var published = run.Published.Count; + + // A checkpoint is saved at once; it goes out as any report would. + run.Time.Advance(Tick); + await run.Context.CheckpointAsync("52", 52, 100); + var stored = await run.StoredAsync(); + Assert.Equal((52L, "52"), (stored.ProgressDone, stored.Checkpoint)); + Assert.Null(stored.Detail); + Assert.Equal(published, run.Published.Count); + + var verify = new JobDetail(JobStep.Verify, "Harbour sunset", 1, 9, 1, 3, JobPartUnit.Sequence); + run.Time.Advance(Tick); + await run.Context.CheckpointAsync("53", 53, 100, verify); + stored = await run.StoredAsync(); + Assert.Equal((53L, "53", verify), (stored.ProgressDone, stored.Checkpoint, stored.Detail)); + Assert.Equal(verify, run.Published[^1].Detail); + + // A checkpoint without a detail keeps it. + run.Time.Advance(Tick); + await run.Context.CheckpointAsync("54", 54, 100); + Assert.Equal(verify, (await run.StoredAsync()).Detail); + } + + [Test] + public async Task TheRateIsTheSameUnderThePublishThrottle() + { + await using var run = await StartAsync(); + // 100 photos a second for ten seconds, every photo reported. + for (var i = 1; i <= 1000; i++) + { + await run.Context.ReportAsync(i, 2000); + run.Time.Advance(Tick); + } + Assert.True(run.Published.Count <= 22, $"{run.Published.Count} publishes"); + var last = run.Published[^1]; + Assert.Approximately(100, last.ItemsPerSecond!.Value, 0.5); + Assert.Approximately((2000 - last.Done) / 100.0, last.Eta!.Value.TotalSeconds, 0.1); + } + + [Test] + public async Task ItemCountsWithoutADetailAreAPhotoPass() + { + await using var run = await StartAsync(); + Assert.Null(run.Context.Detail); + await run.Context.ReportItemAsync(1, 10, 3, 9); + Assert.Equal(new JobDetail(JobStep.Process, null, 3, 9), run.Context.Detail); + Assert.Equal(run.Context.Detail, run.Published.Single().Detail); + // A plain report keeps the detail and drops the old free text. + await run.Context.ReportAsync(2, 10, "IMG_0001.CR3"); + await run.Context.ReportAsync(3, 10); + Assert.Null(run.Context.Message); + Assert.Equal(new JobDetail(JobStep.Process, null, 3, 9), run.Context.Detail); + } + + [Test] + public async Task ADroppedReportAllocatesNothing() + { + await using var run = await StartAsync(); + var thumbs = new JobDetail(JobStep.Thumbs, "Harbour sunset", 0, 3600, 2, 7, JobPartUnit.Sequence); + await run.Context.ReportAsync(1, 1_000_000, thumbs); + var job = run.Context; + var dropped = 0; + for (var i = 0; i < 200; i++) dropped += Drop(job, thumbs, i) ? 1 : 0; + var before = GC.GetAllocatedBytesForCurrentThread(); + for (var i = 0; i < 20_000; i++) dropped += Drop(job, thumbs, i) ? 1 : 0; + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + Assert.Equal(20_200, dropped); + Assert.Equal(0L, allocated); + Assert.Count(1, run.Published); + } + + [Test] + public async Task TheEngineSendsAndSavesTheDetail() + { + await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(), "jobs.db")), context.Cancellation); + var verify = new JobDetail(JobStep.Verify, "Harbour sunset", 5, 9, 1, 2, JobPartUnit.Sequence); + var handler = new CallbackHandler(JobKind.Verify, async c => + { + await c.CheckpointAsync("1", 1, 2, verify); + await c.ReportAsync(2, 2); + }); + await using var engine = new JobEngine(db, [handler], new JobEngineOptions { Workers = 1, WorkerId = "t" }); + var published = new List(); + engine.Progress += p => + { + lock (published) published.Add(p); + }; + await engine.StartAsync(context.Cancellation); + var job = await engine.EnqueueAsync(JobKind.Verify, [Guid.NewGuid()], cancellationToken: context.Cancellation); + var until = DateTime.UtcNow.AddSeconds(15); + Job? done = null; + while (DateTime.UtcNow < until && (done = await db.Jobs.GetAsync(job.Id, context.Cancellation))?.State != JobState.Done) await Task.Delay(20, context.Cancellation); + Assert.Equal(JobState.Done, done?.State); + Assert.Equal(verify, done!.Detail); + lock (published) Assert.SequenceEqual([verify, verify], published.Select(p => p.Detail)); + } + + /// One report dropped by the throttle: no new step, no completed count, no time passed. + private static bool Drop(JobContext job, JobDetail detail, int i) + { + var item = job.ReportItemAsync(2 + i, 1_000_000, i, 3600); + var full = job.ReportAsync(3 + i, 1_000_000, detail); + return item.IsCompletedSuccessfully && full.IsCompletedSuccessfully; + } + + private async Task StartAsync() + { + var time = new ManualTime(); + var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(), "jobs.db")), context.Cancellation); + var engine = new JobEngine(db, [], new JobEngineOptions { WorkerId = "t", Time = time }); + var run = new Run(db, engine, time); + engine.Progress += run.Published.Add; + await db.Jobs.EnqueueAsync(new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Verify, State = JobState.Queued, Created = DateTimeOffset.UtcNow }, + context.Cancellation); + var claimed = Assert.NotNull(await db.Jobs.ClaimNextAsync("t", null, context.Cancellation)); + run.Context = new JobContext(engine, claimed, context.Cancellation); + return run; + } + + private sealed class Run(ChronosDatabase db, JobEngine engine, ManualTime time) : IAsyncDisposable + { + public ManualTime Time { get; } = time; + + public JobContext Context { get; set; } = null!; + + public List Published { get; } = []; + + public async Task StoredAsync() => (await db.Jobs.GetAsync(Context.Job.Id))!; + + public async ValueTask DisposeAsync() + { + await engine.DisposeAsync(); + await db.DisposeAsync(); + } + } + + private sealed class CallbackHandler(JobKind kind, Func run) : IJobHandler + { + public JobKind Kind => kind; + + public Task RunAsync(JobContext context) => run(context); + } +} diff --git a/tests/Chronos.Data.Tests/Jobs/JobWireTests.cs b/tests/Chronos.Data.Tests/Jobs/JobWireTests.cs index b8fbd11f..714f7cb6 100644 --- a/tests/Chronos.Data.Tests/Jobs/JobWireTests.cs +++ b/tests/Chronos.Data.Tests/Jobs/JobWireTests.cs @@ -1,5 +1,6 @@ using Chronos.Core.Model; using Chronos.Data.Jobs; +using Chronos.Protocol; using Chronos.Testing; namespace Chronos.Data.Tests.Jobs; @@ -29,4 +30,72 @@ public sealed class JobWireTests Assert.Equal(names.Count, names.Distinct(StringComparer.Ordinal).Count()); Assert.False(JobWire.TryParseKind("workspace-teleport", out _)); } + + /// Steps and units are stored and sent by name, appended only: these values and names are pinned once shipped. + [Theory] + [Case(JobStep.None, 0, "none")] + [Case(JobStep.List, 1, "list")] + [Case(JobStep.Verify, 4, "verify")] + [Case(JobStep.CopyPhoto, 11, "copy-photo")] + [Case(JobStep.CopyOriginal, 13, "copy-original")] + [Case(JobStep.FollowUps, 22, "follow-ups")] + [Case(JobStep.Process, 23, "process")] + public void StepsKeepTheirValueAndName(JobStep step, int value, string name) + { + Assert.Equal(value, (int)step); + Assert.Equal(name, JobWire.Step(step)); + Assert.True(JobWire.TryParseStep(name, out var parsed), name); + Assert.Equal(step, parsed); + } + + [Test] + public void EveryStepAndUnitHasItsOwnName() + { + var steps = Enum.GetValues().Select(JobWire.Step).ToList(); + Assert.Equal(steps.Count, steps.Distinct(StringComparer.Ordinal).Count()); + Assert.SequenceEqual(["none", "sequence", "folder", "render", "entry", "step"], Enum.GetValues().Select(JobWire.PartUnit)); + Assert.False(JobWire.TryParseStep("teleport", out _)); + Assert.False(JobWire.TryParsePartUnit(null, out _)); + } + + [Test] + public void ADetailCrossesTheWireAndBack() + { + var detail = new JobDetail(JobStep.CopyOriginal, "2024/2024-09-27 Harbour sunset", 1240, 3600, 12, 340, JobPartUnit.Folder); + var dto = JobWire.Detail(detail)!; + Assert.Equal(new JobDetailDto("copy-original", "2024/2024-09-27 Harbour sunset", 1240, 3600, 12, 340, "folder"), dto); + Assert.Equal(detail, JobWire.FromDto(dto)); + // A unit of none is left out; nothing is none. + Assert.Null(JobWire.Detail(new JobDetail(JobStep.Backup))!.PartUnit); + Assert.Null(JobWire.Detail(null)); + Assert.Null(JobWire.FromDto((JobDetailDto?)null)); + + // A newer peer's step or unit reads as none and its counts stay; nonsense counts read as 0. + Assert.Equal(new JobDetail(JobStep.None, "x", 0, 9, 2, 0), JobWire.FromDto(new JobDetailDto("teleport", "x", -4, 9, 2, -1, "galaxy"))); + Assert.Equal(new JobDetail(JobStep.None), JobWire.FromDto(new JobDetailDto(null!))); + } + + [Test] + public void AnItemIsCutToItsLongestLengthWithoutSplittingACharacter() + { + var plain = new string('a', JobDetail.MaxItemLength + 40); + Assert.Equal(JobDetail.MaxItemLength, new JobDetail(JobStep.Index, plain).Item!.Length); + // A pair whose high half would be the last kept character goes whole. + var emoji = new string('a', JobDetail.MaxItemLength - 1) + "\U0001F4F7" + "tail"; + var cut = new JobDetail(JobStep.Index, emoji).Item!; + Assert.Equal(JobDetail.MaxItemLength - 1, cut.Length); + Assert.False(char.IsHighSurrogate(cut[^1])); + Assert.Equal(JobDetail.MaxItemLength, (new JobDetail(JobStep.Index) with { Item = plain }).Item!.Length); + Assert.Equal(JobDetail.MaxItemLength, JobWire.FromDto(new JobDetailDto("index", plain))!.Item!.Length); + Assert.Equal("short", new JobDetail(JobStep.Index, "short").Item); + } + + [Test] + public void AServerJobBringsItsDetail() + { + var dto = new JobDto(Guid.NewGuid(), "verify", [], "Archive", "paused", "normal", 4, 10, null, null, null, null, 1, null, DateTimeOffset.UtcNow, null, null, + Detail: new JobDetailDto("verify", "Harbour sunset", 812, 2400, 3, 41, "sequence")); + Assert.Equal(new JobDetail(JobStep.Verify, "Harbour sunset", 812, 2400, 3, 41, JobPartUnit.Sequence), JobWire.FromDto(dto)!.Detail); + Assert.Null(JobWire.FromDto(dto with { Detail = null })!.Detail); + } } diff --git a/tests/Chronos.Data.Tests/Migrations/MigrationTests.cs b/tests/Chronos.Data.Tests/Migrations/MigrationTests.cs index a191dd0f..80bf1bca 100644 --- a/tests/Chronos.Data.Tests/Migrations/MigrationTests.cs +++ b/tests/Chronos.Data.Tests/Migrations/MigrationTests.cs @@ -139,6 +139,24 @@ public abstract class MigrationTests(TestContext context) : RepositoryTest(conte Assert.Equal(0L, await session.ScalarAsync("SELECT bytes FROM render_copies WHERE path = $1", ["C:/Videos/b"], Ct)); } + [Test] + public async Task TheProgressDetailColumnJoinsAnIndexOfTheVideosRelease() + { + var database = await OpenDatabaseAsync(); + var all = MigrationRunner.Load(Dialect); + Assert.Equal(10, await MigrationRunner.MigrateAsync(database, [.. all.Where(m => m.Version <= 10)], Ct)); + var id = Guid.CreateVersion7(); + await using (var session = await database.OpenAsync(Ct)) + await session.ExecuteAsync("INSERT INTO jobs (id, kind, state, priority, created) VALUES ($1, $2, $3, $4, $5)", + [id, (int)JobKind.Verify, (int)JobState.Paused, (int)JobPriority.Normal, DateTimeOffset.UtcNow], Ct); + + Assert.Equal(11, all.Single(m => m.Name == "job_progress_detail").Version); + Assert.Equal(all[^1].Version, await MigrationRunner.MigrateAsync(database, Ct)); + await using var after = await database.OpenAsync(Ct); + // No backfill: a job of 1.0 has no detail. + Assert.Equal(1L, await after.ScalarAsync("SELECT count(*) FROM jobs WHERE id = $1 AND progress_detail IS NULL", [id], Ct)); + } + [Test] public async Task AppliesOnlyPendingMigrations() { diff --git a/tests/Chronos.Data.Tests/Repositories/JobRepositoryTests.cs b/tests/Chronos.Data.Tests/Repositories/JobRepositoryTests.cs index d07851da..a2bb9467 100644 --- a/tests/Chronos.Data.Tests/Repositories/JobRepositoryTests.cs +++ b/tests/Chronos.Data.Tests/Repositories/JobRepositoryTests.cs @@ -30,12 +30,52 @@ public abstract class JobRepositoryTests(TestContext context) : RepositoryTest(c Started = TestData.Now.AddMinutes(1), Finished = TestData.Now.AddMinutes(2), ScheduleId = Guid.CreateVersion7(), + Detail = new JobDetail(JobStep.Encode, "Harbour sunset", 5, 10, 1, 2, JobPartUnit.Render), }; await db.Jobs.EnqueueAsync(job, Ct); var read = Assert.NotNull(await db.Jobs.GetAsync(job.Id, Ct)); Assert.SequenceEqual(job.TargetIds, read.TargetIds); Assert.Equal(job with { TargetIds = read.TargetIds }, read); - Assert.Null((await db.Jobs.GetAsync((await EnqueueAsync(db, TestData.Job())).Id, Ct))!.ScheduleId); + var plain = (await db.Jobs.GetAsync((await EnqueueAsync(db, TestData.Job())).Id, Ct))!; + Assert.Null(plain.ScheduleId); + Assert.Null(plain.Detail); + } + + [Test] + public async Task TheProgressDetailIsSavedWithTheProgressAndListedWithTheJob() + { + var db = await OpenChronosAsync(); + var job = TestData.Job(JobKind.Verify); + await db.Jobs.EnqueueAsync(job, Ct); + await db.Jobs.ClaimNextAsync("w", cancellationToken: Ct); + var detail = new JobDetail(JobStep.Verify, "Harbour sunset · 2024", 812, 2400, 3, 41, JobPartUnit.Sequence); + Assert.True(await db.Jobs.UpdateProgressAsync(job.Id, 4, 10, null, null, "cursor:4", null, detail, Ct)); + Assert.Equal(detail, (await db.Jobs.GetAsync(job.Id, Ct))!.Detail); + // Lists read it too: a paused job tells where it stopped. + Assert.SequenceEqual([detail], (await db.Jobs.ListBriefAsync(JobState.Running, null, cancellationToken: Ct)).Items.Select(j => j.Detail)); + + // Without a detail the column is cleared; a node's progress keeps or replaces it. + Assert.True(await db.Jobs.UpdateProgressAsync(job.Id, 5, 10, null, null, "cursor:5", null, Ct)); + Assert.Null((await db.Jobs.GetAsync(job.Id, Ct))!.Detail); + var node = new JobDetail(JobStep.Encode, null, 120, 3600); + Assert.True(await db.Jobs.UpdateNodeProgressAsync(job.Id, "w", 6, 10, null, null, null, node, Ct)); + Assert.True(await db.Jobs.UpdateNodeProgressAsync(job.Id, "w", 7, 10, null, null, "line", Ct)); + Assert.Equal(node, (await db.Jobs.GetAsync(job.Id, Ct))!.Detail); + Assert.True(await db.Jobs.UpdateNodeProgressAsync(job.Id, "w", 8, 10, null, null, null, null, Ct)); + Assert.Null((await db.Jobs.GetAsync(job.Id, Ct))!.Detail); + + // A cell this build cannot read is no detail, never an error. + foreach (var unreadable in new[] { "not json", "42", "[]", "{\"step\": 7}" }) + { + await using (var session = await db.Database.OpenAsync(Ct)) + await session.ExecuteAsync("UPDATE jobs SET progress_detail = $1 WHERE id = $2", [unreadable, job.Id], Ct); + Assert.Null((await db.Jobs.GetAsync(job.Id, Ct))!.Detail); + } + // One of a newer build: its step and unit read as none, the counts stay. + await using (var session = await db.Database.OpenAsync(Ct)) + await session.ExecuteAsync("UPDATE jobs SET progress_detail = $1 WHERE id = $2", + ["""{"step":"teleport","itemDone":3,"itemTotal":9,"part":2,"parts":4,"partUnit":"galaxy","future":true}""", job.Id], Ct); + Assert.Equal(new JobDetail(JobStep.None, null, 3, 9, 2, 4), (await db.Jobs.GetAsync(job.Id, Ct))!.Detail); } [Test] diff --git a/tests/Chronos.Server.Tests/Events/ProgressEventTests.cs b/tests/Chronos.Server.Tests/Events/ProgressEventTests.cs new file mode 100644 index 00000000..c66f9bf8 --- /dev/null +++ b/tests/Chronos.Server.Tests/Events/ProgressEventTests.cs @@ -0,0 +1,206 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; +using Chronos.Core.Model; +using Chronos.Data.Jobs; +using Chronos.Protocol; +using Chronos.Server.Events; +using Chronos.Server.Jobs; +using Chronos.Server.Tests.Jobs; +using Chronos.Testing; + +namespace Chronos.Server.Tests.Events; + +/// +/// What a job does now on the wire (owner review 5, #65): the progress event, the job and a render node's report carry an +/// optional detail, older and newer peers read each other, and the event socket gets a job's progress at most twice a second. +/// +[Category("server")] +public sealed class ProgressEventTests(TestContext context) +{ + private static readonly JobDetailDto Verify = new("verify", "Harbour sunset", 812, 2400, 3, 41, "sequence"); + + [Test] + public void TheProgressEventCarriesItsDetailInCamelCase() + { + var id = Guid.CreateVersion7(); + var json = JsonSerializer.Serialize(new JobProgressEvent(id, 3, 10, 2.5, 4, Verify), ProtocolJson.Default.ServerEvent); + Assert.Contains("\"type\":\"jobProgress\"", json); + Assert.Contains("\"detail\":{\"step\":\"verify\",\"item\":\"Harbour sunset\",\"itemDone\":812,\"itemTotal\":2400,\"part\":3,\"parts\":41,\"partUnit\":\"sequence\"}", json); + Assert.Equal(new JobProgressEvent(id, 3, 10, 2.5, 4, Verify), JsonSerializer.Deserialize(json, ProtocolJson.Default.ServerEvent)); + // None is left out. + var plain = JsonSerializer.Serialize(new JobProgressEvent(id, 3, 10, null, null), ProtocolJson.Default.ServerEvent); + Assert.False(plain.Contains("detail", StringComparison.Ordinal), plain); + } + + [Test] + public void AnOlderPeersPayloadReadsWithoutADetail() + { + var id = Guid.CreateVersion7(); + var progress = JsonSerializer.Deserialize($$"""{"type":"jobProgress","jobId":"{{id}}","done":1,"total":4,"itemsPerSecond":null,"etaSeconds":null}""", + ProtocolJson.Default.ServerEvent); + Assert.Equal(new JobProgressEvent(id, 1, 4, null, null), progress); + Assert.Equal(new NodeProgress(120, 3600, 40, "encoding"), + JsonSerializer.Deserialize("""{"done":120,"total":3600,"itemsPerSecond":40,"logLine":"encoding"}""", ProtocolJson.Default.NodeProgress)); + var job = JsonSerializer.Deserialize($$""" + {"id":"{{id}}","kind":"verify","targetIds":[],"state":"running","priority":"normal","progressDone":1,"progressTotal":4, + "attempts":1,"created":"2026-11-15T10:00:00Z"} + """, ProtocolJson.Default.JobDto)!; + Assert.Null(job.Detail); + Assert.Null(JobWire.FromDto(job)!.Detail); + // A detail of fewer fields (a newer peer's that drops some, or a sparse one) reads with zeros. + Assert.Equal(new JobDetailDto("backup"), JsonSerializer.Deserialize("""{"step":"backup"}""", ProtocolJson.Default.JobDetailDto)); + } + + [Test] + public void ANewerPayloadReadsIntoAnOlderRecord() + { + var id = Guid.CreateVersion7(); + var web = new JsonSerializerOptions(JsonSerializerDefaults.Web); + var json = JsonSerializer.Serialize(new JobProgressEvent(id, 3, 10, 2.5, 4, Verify), ProtocolJson.Default.ServerEvent); + Assert.Equal(new JobProgressBefore(id, 3, 10, 2.5, 4), JsonSerializer.Deserialize(json, web)); + var node = JsonSerializer.Serialize(new NodeProgress(120, 3600, 40, "encoding", new JobDetailDto("encode", null, 120, 3600)), ProtocolJson.Default.NodeProgress); + Assert.Equal(new NodeProgressBefore(120, 3600, 40, "encoding"), JsonSerializer.Deserialize(node, web)); + } + + [Test] + public void TheGateLetsAJobsProgressOutTwiceASecondButForNewStepsAndCompletedCounts() + { + var clock = new TimestampClock(); + var gate = new ProgressGate(clock); + var job = Guid.CreateVersion7(); + Assert.True(gate.Passes(job, 1, 100, JobStep.Verify), "the first"); + clock.Advance(TimeSpan.FromMilliseconds(100)); + Assert.False(gate.Passes(job, 2, 100, JobStep.Verify)); + Assert.True(gate.Passes(job, 3, 100, JobStep.Replace), "a new step"); + Assert.True(gate.Passes(job, 100, 100, JobStep.Replace), "a completed count"); + Assert.True(gate.Passes(Guid.CreateVersion7(), 1, 100, JobStep.Verify), "another job"); + clock.Advance(TimeSpan.FromMilliseconds(300)); + Assert.False(gate.Passes(job, 4, 100, JobStep.Replace)); + // The engine spaces its reports by the same half second, measured a moment before: they are not dropped. + clock.Advance(TimeSpan.FromMilliseconds(160)); + Assert.True(gate.Passes(job, 5, 100, JobStep.Replace), "on time"); + Assert.False(gate.Passes(job, 6, 100, JobStep.Replace)); + // A job that stops running is forgotten; its next run starts afresh. + gate.Forget(job); + Assert.True(gate.Passes(job, 7, 100, JobStep.Replace), "after a pause"); + gate.Forget(job); + Assert.Equal(1, gate.Count); + Assert.Equal(TimeSpan.FromMilliseconds(500), ProgressGate.Interval); + } + + [Test] + public async Task TheServerSendsAndSavesWhatItsJobsDo() + { + var handler = new DetailJobHandler(); + await using var server = await TestServer.StartAsync(context, services: s => s.AddSingleton(handler)); + var (editor, _, _) = await server.UserAsync("alberto", "editor"); + var sequence = await JobApiTests.CreateSequenceAsync(editor); + var hub = server.Services.GetRequiredService(); + using var subscription = hub.Subscribe(); + + var job = await JobApiTests.CreateAsync(editor, "deep-analyse", sequence); + await handler.Started.Task.WaitAsync(TimeSpan.FromSeconds(10)); + var running = await JobApiTests.GetAsync(editor, job.Id); + Assert.Equal(DetailJobHandler.Expected, running.Detail); + handler.Release(); + var done = await JobApiTests.WaitForAsync(editor, job.Id, "done"); + // Kept once the job ends, as it was last saved. + Assert.Equal(DetailJobHandler.Expected with { ItemDone = 4 }, done.Detail); + using (var list = await editor.GetAsync("/api/v1/jobs")) + { + var page = await list.ReadAsync(ProtocolJson.Default.PageJobDto); + Assert.Equal(DetailJobHandler.Expected with { ItemDone = 4 }, page.Items.Single(j => j.Id == job.Id).Detail); + } + + var progress = new List(); + while (subscription.Reader.TryRead(out var e)) + { + if (e is JobProgressEvent p && p.JobId == job.Id) progress.Add(p); + } + Assert.SequenceEqual([1L, 4L], progress.Select(p => p.Done)); + Assert.SequenceEqual([DetailJobHandler.Expected, DetailJobHandler.Expected with { ItemDone = 4 }], progress.Select(p => p.Detail)); + // The ended job is forgotten once its state goes out. + var gate = server.Services.GetRequiredService().Gate; + for (var i = 0; i < 200 && gate.Count > 0; i++) await Task.Delay(25, context.Cancellation); + Assert.Equal(0, gate.Count); + } + + [Test] + public async Task ARenderNodeSendsWhatItDoesAndAnOlderNodeNothing() + { + await using var server = await TestServer.StartAsync(context); + var (editor, _, _) = await server.UserAsync("alberto", "editor", renderNode: true); + var sequence = await JobApiTests.CreateSequenceAsync(editor); + var job = await JobApiTests.CreateAsync(editor, "render", sequence, RenderNodeTests.HevcJob); + var node = await RenderNodeTests.RegisterAsync(editor, "studio-pc", "hevc", 8192); + using (var claim = await editor.PostAsync($"/api/v1/nodes/{node.Id}/claim", null)) await claim.ExpectAsync(HttpStatusCode.OK); + using var subscription = server.Services.GetRequiredService().Subscribe(); + + var encode = new JobDetailDto("encode", "Harbour sunset", 120, 3600, 1, 1, "render"); + await ReportAsync(new NodeProgress(120, 3600, 40, "encoding", encode)); + Assert.Equal(encode, (await JobApiTests.GetAsync(editor, job.Id)).Detail); + // A step or unit this server does not know is stored as none, with its counts. + await ReportAsync(new NodeProgress(130, 3600, 40, null, new JobDetailDto("teleport", null, 130, 3600, 0, 0, "galaxy"))); + Assert.Equal(new JobDetailDto("none", null, 130, 3600), (await JobApiTests.GetAsync(editor, job.Id)).Detail); + // An older node sends none: the counts alone. + await ReportAsync(new NodeProgress(140, 3600, 40, null)); + var stored = await JobApiTests.GetAsync(editor, job.Id); + Assert.Equal((140L, (JobDetailDto?)null), (stored.ProgressDone, stored.Detail)); + + var events = new List(); + while (subscription.Reader.TryRead(out var e)) + { + if (e is JobProgressEvent p) events.Add(p); + } + Assert.Equal(encode, events[0].Detail); + Assert.True(events.All(e => e.JobId == job.Id), "only the node's job"); + + async Task ReportAsync(NodeProgress progress) + { + using var response = await editor.PostAsJsonAsync($"/api/v1/nodes/{node.Id}/jobs/{job.Id}/progress", progress, ProtocolJson.Default.NodeProgress); + await response.ExpectAsync(HttpStatusCode.NoContent); + } + } + + /// A progress event as a 1.0 client reads it. + private sealed record JobProgressBefore(Guid JobId, long Done, long Total, double? ItemsPerSecond, double? EtaSeconds); + + /// A node's report as a 1.0 server reads it. + private sealed record NodeProgressBefore(long Done, long Total, double? ItemsPerSecond, string? LogLine); + + /// A monotonic clock the test moves by hand. + private sealed class TimestampClock : TimeProvider + { + private long _ticks; + + public override long TimestampFrequency => TimeSpan.TicksPerSecond; + + public override long GetTimestamp() => Interlocked.Read(ref _ticks); + + public void Advance(TimeSpan by) => Interlocked.Add(ref _ticks, by.Ticks); + } + + /// A deep analysis that says what it does, waits to be released, then completes. + private sealed class DetailJobHandler : IJobHandler + { + public static readonly JobDetailDto Expected = new("analyse", "Harbour sunset", 1, 4, 1, 1, "sequence"); + + private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public JobKind Kind => JobKind.DeepAnalyse; + + public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public void Release() => _release.TrySetResult(); + + public async Task RunAsync(JobContext context) + { + await context.CheckpointAsync("1", 1, 4, JobWire.FromDto(Expected)!); + Started.TrySetResult(); + await _release.Task.WaitAsync(context.Cancellation); + await context.ReportItemAsync(4, 4, 4, 4); + } + } +}