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; /// /// Hosts the server's (BRIEF §14.6) with the s registered in DI (directly or /// through 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 (: 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 () on the archive it serves and its sequences (): the desktop's /// workspace, sync and download jobs, and its jobs on other archives, stay its own. /// Progress goes out through the render nodes share, with what each job does now (owner review 5, #65). /// public sealed class JobEngineHost : IHostedService { private readonly EventHub _events; private readonly HashSet _kinds; private readonly bool _ownsEngine = true; private readonly ServerArchive? _archive; private readonly ChronosDatabase? _db; /// Hosted: whether each job seen is the shared archive's (its targets never change), and the latest state of one still being looked up. private readonly Dictionary _served = []; private readonly Dictionary _deciding = []; private readonly Lock _decide = new(); private int _subscribed; public JobEngineHost(ChronosDatabase db, IEnumerable handlers, IEnumerable 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(); } /// /// Relays , an engine Chronos Desktop runs (owner review 5, #67), from to /// ; the engine stays the desktop's. With and , only /// that archive's jobs and its sequences' are relayed and listed (). /// 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; } /// Node id stamped on jobs this server runs. public static string WorkerId { get; } = "server:" + Environment.MachineName; 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; } /// The engine is the one Chronos Desktop runs, which shares its library (owner review 5, #67). public bool Hosted => !_ownsEngine; /// 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 || (_ownsEngine ? _kinds.Contains(kind) : Engine.CanRun(kind) && Exposes(kind)); /// /// Whether the jobs API lists, shows and acts on jobs of : every kind on a server of its own; on a /// shared desktop library only the kinds a server runs (), so a client never sees or /// cancels the desktop's own workspace, sync and download jobs (owner review 5, #67). /// public bool Exposes(JobKind kind) => _ownsEngine || ServerSettingsStore.Kinds.Contains(kind); /// /// Whether the jobs API lists, shows and acts on , 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 () whose target is the served /// archive or one of its sequences (owner review 5, #67), never the desktop's work on its other archives. /// public async ValueTask 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; } /// The job's first target is the served archive or one of its sequences (a job without targets is the server's). private async Task 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; } /// /// 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). /// public event Action? ChangedOutside; /// Publishes a state change made outside the engine (render nodes, cancellation of node jobs). 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); } /// Looks up whether the job is the shared archive's, then publishes the latest state it had meanwhile when it is. 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))); } }