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 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-15 13:02:59 +01:00
1 parent 58ed737310
commit ee9505df22
20 files changed
+968 -63

No files matched your search

+6
View File
@@ -393,6 +393,12 @@ public sealed record Job
/// <summary>The schedule that queued this job; null for jobs queued by a user or by other jobs (owner review 2, R10).</summary>
public Guid? ScheduleId { get; init; }
/// <summary>
/// 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.
/// </summary>
public JobDetail? Detail { get; init; }
}
/// <summary>
+79
View File
@@ -0,0 +1,79 @@
namespace Chronos.Core.Model;
/// <summary>
/// What a running job does now (<see cref="JobDetail.Step"/>). Values are appended only, never reordered or renamed: they
/// are stored and sent by their kebab-case name (<c>copy-photo</c>), and a name a build does not know reads as
/// <see cref="None"/>. Each client words a step in its own language; a handler never sends progress text.
/// </summary>
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,
}
/// <summary>
/// What a job counts its parts in (<see cref="JobDetail.Parts"/>: sequence 12 of 340). Appended only and stored by name,
/// as <see cref="JobStep"/>.
/// </summary>
public enum JobPartUnit
{
None,
Sequence,
Folder,
Render,
Entry,
Step,
}
/// <summary>
/// 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.
/// </summary>
/// <param name="Step">What the job does now.</param>
/// <param name="Item">
/// The sequence title, folder, file name, or the key of a sub-step (clean-up, maintenance) it works on; null for none. Cut
/// to <see cref="MaxItemLength"/> characters.
/// </param>
/// <param name="ItemDone">Photos (frames, files) done inside the item; 0 of 0 when not counted.</param>
/// <param name="ItemTotal">Photos (frames, files) of the item; 0 when not counted.</param>
/// <param name="Part">The 1-based part of <paramref name="Parts"/> the item is; 0 of 0 for a job of one part.</param>
/// <param name="Parts">The parts of the job, counted in <paramref name="PartUnit"/>.</param>
/// <param name="PartUnit">What a part is.</param>
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)
{
/// <summary>The longest <see cref="Item"/> kept; a longer one is cut (never inside a surrogate pair).</summary>
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];
}
}
+13 -6
View File
@@ -22,10 +22,16 @@ public sealed record JobEngineOptions
public TimeSpan CheckpointInterval { get; init; } = TimeSpan.FromSeconds(5);
/// <summary>
/// The shortest time between two publishes of one job's progress (<see cref="JobEngine.Progress"/>): twice a second. A new
/// step, a count that completes and the run's first report go out at once (<see cref="JobContext"/>).
/// </summary>
public TimeSpan ProgressInterval { get; init; } = TimeSpan.FromMilliseconds(500);
/// <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>Clock of the throughput windows and the checkpoint interval (tests pass their own).</summary>
/// <summary>Clock of the throughput windows, the progress interval 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>
@@ -77,7 +83,7 @@ public sealed class JobEngine : IAsyncDisposable
/// <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>
/// <summary>Progress of a running job, at most once per <see cref="JobEngineOptions.ProgressInterval"/> per job but for new steps and completed counts.</summary>
public event Action<JobProgressInfo>? Progress;
public IReadOnlyCollection<Guid> 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
}
/// <summary>
/// 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.
/// </summary>
internal async Task<bool> 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)
{
+105 -7
View File
@@ -43,11 +43,20 @@ 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>
/// Live progress of a running job (pushed to the job bar, the Jobs screen and WebSocket clients). <see cref="Detail"/>: what
/// the job does now (step, item, photo x of y, part n of m), null when its handler reports none.
/// </summary>
public sealed record JobProgressInfo(Guid JobId, JobKind Kind, string? TargetLabel, long Done, long Total, double? ItemsPerSecond, TimeSpan? Eta, string? Message,
JobDetail? Detail = null);
/// <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>
/// <summary>
/// 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 (<see cref="JobEngineOptions.ProgressInterval"/>, 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.
/// </summary>
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; }
/// <summary>Reports progress; persisted and broadcast at most every checkpoint interval.</summary>
/// <summary>
/// What the job does now, as last reported (<see cref="ReportAsync(long, long, JobDetail, string?)"/>), with the item
/// counts of <see cref="ReportItemAsync"/>; null until the handler reports one. Kept across reports that pass none.
/// </summary>
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 };
}
}
/// <summary>Reports progress, keeping the <see cref="Detail"/>; published at most every progress interval, persisted 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>
/// <summary>
/// Reports progress with what the job does now (<paramref name="detail"/>, kept for the reports that follow); published
/// at once when its step differs from the last one published, else as <see cref="ReportAsync(long, long, string?)"/>.
/// </summary>
public ValueTask ReportAsync(long done, long total, JobDetail detail, string? message = null)
{
SetDetail(detail);
return ReportCoreAsync(done, total, message, force: false);
}
/// <summary>
/// Reports progress inside the current item (photo <paramref name="itemDone"/> of <paramref name="itemTotal"/>) without a
/// new <see cref="JobDetail"/>, so a handler can report every photo without allocating; with no detail reported yet the
/// step is <see cref="JobStep.Process"/>. Keeps the <see cref="Message"/>.
/// </summary>
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);
}
/// <summary>Saves a resume cursor together with the current progress (persisted immediately), keeping the <see cref="Detail"/>.</summary>
public ValueTask CheckpointAsync(string checkpoint, long done, long total)
{
Checkpoint = checkpoint;
return ReportCoreAsync(done, total, Message, force: true);
}
/// <summary>Saves a resume cursor together with the current progress and what the job does now (persisted immediately).</summary>
public ValueTask CheckpointAsync(string checkpoint, long done, long total, JobDetail detail)
{
SetDetail(detail);
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
@@ -156,6 +220,14 @@ public sealed class JobContext
/// <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 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
}
/// <summary>
/// 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.
/// </summary>
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);
}
}
+66 -14
View File
@@ -1,29 +1,69 @@
using System.Text;
using System.Text.Json;
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"/>.
/// Wire names of job kinds, states, priorities, progress steps and part units in API v1: kebab-case (<c>deep-analyse</c>,
/// <c>copy-photo</c>) and lower-case (<c>running</c>). The server writes them; clients read the server's jobs back with
/// <see cref="FromDto(JobDto)"/>. The jobs table stores a progress detail in the same form (<see cref="DetailJson"/>).
/// </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 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);
/// <summary>A progress detail as API v1 sends it; null for none. A unit of none is left out.</summary>
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));
/// <summary>
/// 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
/// <see cref="JobDetail.MaxItemLength"/> characters.
/// </summary>
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);
/// <summary>A progress detail as the jobs table stores it (the JSON of <see cref="Detail(JobDetail?)"/>); null for none.</summary>
public static string? DetailJson(JobDetail? detail) =>
Detail(detail) is { } dto ? JsonSerializer.Serialize(dto, ProtocolJson.Default.JobDetailDto) : null;
/// <summary>A stored progress detail (<see cref="DetailJson"/>); null for none and for a cell that cannot be read, never an error.</summary>
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);
/// <summary>A server job as the client's job model; null for a kind or state this build does not know.</summary>
/// <summary>A server job as the client's job model, its progress detail included; null for a kind or state this build does not know.</summary>
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<T>(string? text, Func<T, string> name, out T value) where T : struct, Enum
{
foreach (var candidate in Enum.GetValues<T>())
@@ -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;
@@ -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;
+31 -10
View File
@@ -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";
/// <summary>
/// <see cref="Columns"/> as lists read them (<see cref="ListBriefAsync"/>): 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.
/// </summary>
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";
/// <summary>The states of a job that has not ended: queued, running, paused.</summary>
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<Job?> GetAsync(Guid id, CancellationToken cancellationToken = default) =>
@@ -89,15 +90,23 @@ public sealed class JobRepository
}
/// <summary>
/// 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.
/// </summary>
public Task<bool> 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);
/// <summary>
/// Checkpoint of a running job with what it does now (<paramref name="detail"/>, 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.
/// </summary>
public async Task<bool> 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;
/// <summary>Moves a job to <paramref name="state"/>; done/failed/cancelled stamp the finish time, queued clears it for a retry.</summary>
public async Task<bool> 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);
/// <summary>Progress of a job a render node runs; false when the job is no longer running on that node.</summary>
/// <summary>Progress of a job a render node runs, its progress detail kept; false when the job is no longer running on that node.</summary>
public async Task<bool> 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;
/// <summary>
/// Progress of a job a render node runs with what the node does now (<paramref name="detail"/>; null, from an older node,
/// clears it); false when the job is no longer running on that node.
/// </summary>
public async Task<bool> 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;
/// <summary>Ends a job a render node runs (done or failed); false when it is no longer running on that node.</summary>
public async Task<bool> 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)),
};
}
+5 -1
View File
@@ -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;
/// <summary>
/// A running job's progress, sent at most twice a second per job. <see cref="Detail"/> (owner review 5, #65): what it does
/// now; appended, absent from an older server, ignored by an older client.
/// </summary>
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;
+21 -4
View File
@@ -1,6 +1,10 @@
namespace Chronos.Protocol;
/// <summary>A job of the queue. <see cref="ScheduleId"/>: the schedule that queued it (owner review 2, R10), absent otherwise.</summary>
/// <summary>
/// A job of the queue. <see cref="ScheduleId"/>: the schedule that queued it (owner review 2, R10), absent otherwise.
/// <see cref="Detail"/>: 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.
/// </summary>
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);
/// <summary>
/// What a running job does now, beside its overall progress (owner review 5, #65): <see cref="Step"/> and
/// <see cref="PartUnit"/> are kebab-case keys (<c>copy-photo</c>, <c>sequence</c>) each client words in its own language;
/// a key a client does not know reads as none, and the counts still show. <see cref="Item"/> is data (a sequence title, a
/// folder, a file name, a sub-step key), at most 160 characters. <see cref="ItemDone"/> of <see cref="ItemTotal"/> counts
/// the photos inside the item, <see cref="Part"/> of <see cref="Parts"/> the item among the job's parts; 0 of 0 when not counted.
/// </summary>
public sealed record JobDetailDto(string Step, string? Item = null, long ItemDone = 0, long ItemTotal = 0, int Part = 0, int Parts = 0, string? PartUnit = null);
/// <summary><c>POST /api/v1/jobs</c>: kind = render, deep-analyse, proxies, thumbs, verify, scan, rebuild, maintenance…</summary>
public sealed record CreateJobRequest(string Kind, IReadOnlyList<Guid> 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<ManifestFrame> Frames,
ProxySpec? Proxies = null);
/// <summary><c>POST /api/v1/nodes/{id}/jobs/{jobId}/progress</c>.</summary>
public sealed record NodeProgress(long Done, long Total, double? ItemsPerSecond, string? LogLine);
/// <summary>
/// <c>POST /api/v1/nodes/{id}/jobs/{jobId}/progress</c>. <see cref="Detail"/> (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.
/// </summary>
public sealed record NodeProgress(long Done, long Total, double? ItemsPerSecond, string? LogLine, JobDetailDto? Detail = null);
/// <summary><c>POST /api/v1/jobs/{id}/priority</c>: background, normal or user.</summary>
public sealed record JobPriorityRequest(string Priority);
+1
View File
@@ -37,6 +37,7 @@ namespace Chronos.Protocol;
[JsonSerializable(typeof(UploadState))]
[JsonSerializable(typeof(CardImportReport))]
[JsonSerializable(typeof(JobDto))]
[JsonSerializable(typeof(JobDetailDto))]
[JsonSerializable(typeof(Page<JobDto>))]
[JsonSerializable(typeof(CreateJobRequest))]
[JsonSerializable(typeof(RegisterNodeRequest))]
+1 -1
View File
@@ -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);
+10 -17
View File
@@ -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 (<see cref="ISelectiveJobHandler"/>: 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 <see cref="Gate"/> render nodes share, with what each job does now (owner review 5, #65).
/// </summary>
public sealed class JobEngineHost : IHostedService
{
private static readonly long ProgressInterval = Stopwatch.Frequency / 4;
private readonly ChronosDatabase _db;
private readonly EventHub _events;
private readonly HashSet<JobKind> _kinds;
private readonly Dictionary<Guid, long> _lastProgress = [];
private readonly Lock _gate = new();
public JobEngineHost(ChronosDatabase db, IEnumerable<IJobHandler> handlers, IEnumerable<IJobHandlerProvider> 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; }
/// <summary>The pace of every job's progress events, the server's own jobs and render nodes' alike.</summary>
public ProgressGate Gate { get; }
/// <summary>True when a job of <paramref name="kind"/> has somewhere to run: a local handler, or render nodes for renders.</summary>
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)));
}
}
+53
View File
@@ -0,0 +1,53 @@
using Chronos.Core.Model;
namespace Chronos.Server.Jobs;
/// <summary>
/// How often a job's progress goes out on the event socket (owner review 5, #65): at most once per <see cref="Interval"/>
/// per job, for the server's own jobs (<see cref="JobEngineHost"/>) and those render nodes run (<see cref="RenderNodeService"/>)
/// alike. A job's first report, a new step and a count that completes always pass. A job that stops running is forgotten
/// (<see cref="Forget"/>), so its next run starts afresh.
/// </summary>
public sealed class ProgressGate(TimeProvider time)
{
/// <summary>The shortest time between two progress events of one job: twice a second, as the job engine publishes.</summary>
public static readonly TimeSpan Interval = TimeSpan.FromMilliseconds(500);
/// <summary>
/// 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.
/// </summary>
private static readonly TimeSpan Slack = TimeSpan.FromMilliseconds(50);
private readonly Dictionary<Guid, (long At, JobStep Step)> _last = [];
private readonly Lock _gate = new();
/// <summary>True when the report (<paramref name="done"/> of <paramref name="total"/>, at <paramref name="step"/>) goes out now; it is then the job's last.</summary>
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;
}
}
/// <summary>Forgets a job that no longer runs (done, failed, paused, requeued).</summary>
public void Forget(Guid jobId)
{
lock (_gate) _last.Remove(jobId);
}
/// <summary>The jobs the gate remembers (tests).</summary>
internal int Count
{
get
{
lock (_gate) return _last.Count;
}
}
}
+6 -2
View File
@@ -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<bool>.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;
}
@@ -0,0 +1,225 @@
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Testing;
namespace Chronos.Data.Tests.Jobs;
/// <summary>
/// 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.
/// </summary>
[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<JobProgressInfo>();
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));
}
/// <summary>One report dropped by the throttle: no new step, no completed count, no time passed.</summary>
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<Run> 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<JobProgressInfo> Published { get; } = [];
public async Task<Job> 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<JobContext, Task> run) : IJobHandler
{
public JobKind Kind => kind;
public Task RunAsync(JobContext context) => run(context);
}
}
@@ -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 _));
}
/// <summary>Steps and units are stored and sent by name, appended only: these values and names are pinned once shipped.</summary>
[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<JobStep>().Select(JobWire.Step).ToList();
Assert.Equal(steps.Count, steps.Distinct(StringComparer.Ordinal).Count());
Assert.SequenceEqual(["none", "sequence", "folder", "render", "entry", "step"], Enum.GetValues<JobPartUnit>().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);
}
}
@@ -139,6 +139,24 @@ public abstract class MigrationTests(TestContext context) : RepositoryTest(conte
Assert.Equal(0L, await session.ScalarAsync<long>("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<long>("SELECT count(*) FROM jobs WHERE id = $1 AND progress_detail IS NULL", [id], Ct));
}
[Test]
public async Task AppliesOnlyPendingMigrations()
{
@@ -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]
@@ -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;
/// <summary>
/// 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.
/// </summary>
[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<ServerEvent>(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<ServerEvent>(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<ServerEvent>(new JobProgressEvent(id, 3, 10, 2.5, 4, Verify), ProtocolJson.Default.ServerEvent);
Assert.Equal(new JobProgressBefore(id, 3, 10, 2.5, 4), JsonSerializer.Deserialize<JobProgressBefore>(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<NodeProgressBefore>(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<IJobHandler>(handler));
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var sequence = await JobApiTests.CreateSequenceAsync(editor);
var hub = server.Services.GetRequiredService<EventHub>();
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<JobProgressEvent>();
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<JobEngineHost>().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<EventHub>().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<JobProgressEvent>();
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);
}
}
/// <summary>A progress event as a 1.0 client reads it.</summary>
private sealed record JobProgressBefore(Guid JobId, long Done, long Total, double? ItemsPerSecond, double? EtaSeconds);
/// <summary>A node's report as a 1.0 server reads it.</summary>
private sealed record NodeProgressBefore(long Done, long Total, double? ItemsPerSecond, string? LogLine);
/// <summary>A monotonic clock the test moves by hand.</summary>
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);
}
/// <summary>A deep analysis that says what it does, waits to be released, then completes.</summary>
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);
}
}
}