Setup: a kept 1.0 Uploader no longer fixes the scope and folder, the Remove tooltip promises kept files only with a hashed log, and a single-program setup preselects it. The Uploader always downloads the setup. Sync links move to the server id at every sign-in while folders wait for jobs and open editors; jobs of a pending homes sort still find their projects. A shared library exposes only the shared archive's client-visible jobs and events, render nodes take only client renders, and the share counts as its own while starting. Progress: a new step waits a quarter interval and a trailing timer publishes the last state; the job bar tooltip carries the whole line; Recent maintenance and the Server jobs list pick up jobs that start while they are shown. Refs #64 #65 #66 #67 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
227 lines
10 KiB
C#
227 lines
10 KiB
C#
using Chronos.Core.Model;
|
|
using Chronos.Data;
|
|
using Chronos.Data.Jobs;
|
|
using Chronos.Protocol;
|
|
using Chronos.Server.Api;
|
|
using Chronos.Server.Configuration;
|
|
using Chronos.Server.Events;
|
|
using Chronos.Server.Storage;
|
|
|
|
namespace Chronos.Server.Jobs;
|
|
|
|
/// <summary>
|
|
/// Hosts the server's <see cref="JobEngine"/> (BRIEF §14.6) with the <see cref="IJobHandler"/>s registered in DI (directly or
|
|
/// through <see cref="IJobHandlerProvider"/>s) and
|
|
/// relays its state changes and progress as WebSocket events. Jobs run one at a time, the parallelism working inside the
|
|
/// 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.
|
|
/// When Chronos Desktop shares its library (owner review 5, #67) the engine is the desktop's own: this host relays it while the
|
|
/// server runs, never starts, stops or disposes it, and the jobs API and the events show only the jobs of the kinds a server
|
|
/// runs (<see cref="Exposes"/>) on the archive it serves and its sequences (<see cref="ServesAsync"/>): the desktop's
|
|
/// workspace, sync and download jobs, and its jobs on other archives, stay its own.
|
|
/// 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 readonly EventHub _events;
|
|
private readonly HashSet<JobKind> _kinds;
|
|
private readonly bool _ownsEngine = true;
|
|
private readonly ServerArchive? _archive;
|
|
private readonly ChronosDatabase? _db;
|
|
|
|
/// <summary>Hosted: whether each job seen is the shared archive's (its targets never change), and the latest state of one still being looked up.</summary>
|
|
private readonly Dictionary<Guid, bool> _served = [];
|
|
private readonly Dictionary<Guid, Job> _deciding = [];
|
|
private readonly Lock _decide = new();
|
|
private int _subscribed;
|
|
|
|
public JobEngineHost(ChronosDatabase db, IEnumerable<IJobHandler> handlers, IEnumerable<IJobHandlerProvider> providers, ServerOptions options,
|
|
EventHub events, TimeProvider time)
|
|
{
|
|
_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)];
|
|
// Without handlers no worker starts (StartAsync): an engine with an empty kind list would claim every kind.
|
|
Engine = new JobEngine(db, local, new JobEngineOptions
|
|
{
|
|
WorkerId = WorkerId,
|
|
Kinds = _kinds,
|
|
PriorityQueue = () => ServerSettingsStore.PriorityQueue(options),
|
|
});
|
|
Subscribe();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Relays <paramref name="engine"/>, an engine Chronos Desktop runs (owner review 5, #67), from <see cref="StartAsync"/> to
|
|
/// <see cref="StopAsync"/>; the engine stays the desktop's. With <paramref name="archive"/> and <paramref name="db"/>, only
|
|
/// that archive's jobs and its sequences' are relayed and listed (<see cref="ServesAsync"/>).
|
|
/// </summary>
|
|
public JobEngineHost(JobEngine engine, EventHub events, TimeProvider time, ServerArchive? archive = null, ChronosDatabase? db = null)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(engine);
|
|
_events = events;
|
|
Gate = new ProgressGate(time);
|
|
_ownsEngine = false;
|
|
_kinds = [];
|
|
_archive = archive;
|
|
_db = db;
|
|
Engine = engine;
|
|
}
|
|
|
|
/// <summary>Node id stamped on jobs this server runs.</summary>
|
|
public static string WorkerId { get; } = "server:" + Environment.MachineName;
|
|
|
|
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>The engine is the one Chronos Desktop runs, which shares its library (owner review 5, #67).</summary>
|
|
public bool Hosted => !_ownsEngine;
|
|
|
|
/// <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 || (_ownsEngine ? _kinds.Contains(kind) : Engine.CanRun(kind) && Exposes(kind));
|
|
|
|
/// <summary>
|
|
/// Whether the jobs API lists, shows and acts on jobs of <paramref name="kind"/>: every kind on a server of its own; on a
|
|
/// shared desktop library only the kinds a server runs (<see cref="ServerSettingsStore.Kinds"/>), so a client never sees or
|
|
/// cancels the desktop's own workspace, sync and download jobs (owner review 5, #67).
|
|
/// </summary>
|
|
public bool Exposes(JobKind kind) => _ownsEngine || ServerSettingsStore.Kinds.Contains(kind);
|
|
|
|
/// <summary>
|
|
/// Whether the jobs API lists, shows and acts on <paramref name="job"/>, and its events go out: every job on a server of
|
|
/// its own; on a shared desktop library a job of a kind it exposes (<see cref="Exposes"/>) whose target is the served
|
|
/// archive or one of its sequences (owner review 5, #67), never the desktop's work on its other archives.
|
|
/// </summary>
|
|
public async ValueTask<bool> ServesAsync(Job job, CancellationToken cancellationToken)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(job);
|
|
if (_ownsEngine) return true;
|
|
if (!Exposes(job.Kind)) return false;
|
|
if (_archive is null || _db is null) return true;
|
|
lock (_decide)
|
|
{
|
|
if (_served.TryGetValue(job.Id, out var known)) return known;
|
|
}
|
|
var served = await TargetsServedAsync(job, cancellationToken).ConfigureAwait(false);
|
|
lock (_decide) _served[job.Id] = served;
|
|
return served;
|
|
}
|
|
|
|
/// <summary>The job's first target is the served archive or one of its sequences (a job without targets is the server's).</summary>
|
|
private async Task<bool> TargetsServedAsync(Job job, CancellationToken cancellationToken)
|
|
{
|
|
if (job.TargetIds is not [var target, ..] || target == _archive!.Id) return true;
|
|
return _archive.Owns(await _db!.Sequences.GetAsync(target, cancellationToken).ConfigureAwait(false));
|
|
}
|
|
|
|
public Task StartAsync(CancellationToken cancellationToken)
|
|
{
|
|
if (_ownsEngine) return Engine.StartAsync(cancellationToken);
|
|
Subscribe();
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public async Task StopAsync(CancellationToken cancellationToken)
|
|
{
|
|
if (_ownsEngine)
|
|
{
|
|
await Engine.DisposeAsync();
|
|
return;
|
|
}
|
|
// The desktop's engine runs on: only this server stops following it.
|
|
if (Interlocked.Exchange(ref _subscribed, 0) == 1)
|
|
{
|
|
Engine.JobChanged -= OnJobChanged;
|
|
Engine.Progress -= OnProgress;
|
|
}
|
|
}
|
|
|
|
private void Subscribe()
|
|
{
|
|
if (Interlocked.Exchange(ref _subscribed, 1) == 1) return;
|
|
Engine.JobChanged += OnJobChanged;
|
|
Engine.Progress += OnProgress;
|
|
}
|
|
|
|
/// <summary>
|
|
/// A job's state changed outside the engine (render nodes, cancellation of node jobs): Chronos Desktop's Jobs section
|
|
/// follows these as it follows its engine's own changes while it shares its library (owner review 5, #67).
|
|
/// </summary>
|
|
public event Action<Job>? ChangedOutside;
|
|
|
|
/// <summary>Publishes a state change made outside the engine (render nodes, cancellation of node jobs).</summary>
|
|
public void Publish(Job job)
|
|
{
|
|
OnJobChanged(job);
|
|
ChangedOutside?.Invoke(job);
|
|
}
|
|
|
|
private void OnJobChanged(Job job)
|
|
{
|
|
if (job.State != JobState.Running) Gate.Forget(job.Id);
|
|
// A shared desktop library tells its clients nothing of the desktop's own jobs (owner review 5, #67).
|
|
if (!Exposes(job.Kind)) return;
|
|
if (_ownsEngine || _archive is null || _db is null)
|
|
{
|
|
PublishState(job);
|
|
return;
|
|
}
|
|
lock (_decide)
|
|
{
|
|
// Published under the lock, so the states of one job go out in order while its archive is looked up.
|
|
if (_served.TryGetValue(job.Id, out var served))
|
|
{
|
|
if (served) PublishState(job);
|
|
return;
|
|
}
|
|
var looking = _deciding.ContainsKey(job.Id);
|
|
_deciding[job.Id] = job;
|
|
if (looking) return;
|
|
}
|
|
_ = DecideAsync(job);
|
|
}
|
|
|
|
/// <summary>Looks up whether the job is the shared archive's, then publishes the latest state it had meanwhile when it is.</summary>
|
|
private async Task DecideAsync(Job job)
|
|
{
|
|
bool served;
|
|
try
|
|
{
|
|
served = await TargetsServedAsync(job, CancellationToken.None).ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex) when (ex is DatabaseException or ObjectDisposedException or InvalidOperationException)
|
|
{
|
|
// Not known to be the archive's: its clients are told nothing of it.
|
|
served = false;
|
|
}
|
|
lock (_decide)
|
|
{
|
|
_served[job.Id] = served;
|
|
if (_deciding.Remove(job.Id, out var latest) && served) PublishState(latest);
|
|
}
|
|
}
|
|
|
|
private void PublishState(Job job) => _events.Publish(new JobStateEvent(job.Id, JobWire.State(job.State), job.Error));
|
|
|
|
private void OnProgress(JobProgressInfo progress)
|
|
{
|
|
if (!Exposes(progress.Kind)) return;
|
|
if (!_ownsEngine && _archive is not null && _db is not null)
|
|
{
|
|
// Only a job known to be the shared archive's: its state, which comes first, decided it.
|
|
lock (_decide)
|
|
{
|
|
if (!_served.TryGetValue(progress.JobId, out var served) || !served) return;
|
|
}
|
|
}
|
|
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)));
|
|
}
|
|
}
|