merge: analysis and render jobs, render node client and server managed fallback
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
53 files changed
+2412
-291
No files matched your search
@@ -1,6 +1,7 @@
|
||||
using System.Text.Json;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Processing;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Jobs;
|
||||
using Titano.Server.Security;
|
||||
@@ -9,8 +10,8 @@ using Titano.Server.Storage;
|
||||
namespace Titano.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/v1/jobs</c> (BRIEF §14.6): queue and history, creation, cancel, pause, resume, retry and priority. Changes
|
||||
/// reach WebSocket clients as <c>jobState</c> and <c>jobProgress</c> events.
|
||||
/// <c>/api/v1/jobs</c> (BRIEF §14.6): queue and history, creation (a render batch becomes one job per preset), cancel,
|
||||
/// pause, resume, retry and priority. Changes reach WebSocket clients as <c>jobState</c> and <c>jobProgress</c> events.
|
||||
/// </summary>
|
||||
public static class JobEndpoints
|
||||
{
|
||||
@@ -88,21 +89,46 @@ public static class JobEndpoints
|
||||
targets = ids;
|
||||
label = titles.Count == 1 ? titles[0] : string.Join(", ", titles.Take(3)) + (titles.Count > 3 ? " …" : string.Empty);
|
||||
}
|
||||
List<(string Label, string? Parameters)> queue = [(label, request.ParametersJson)];
|
||||
if (kind == JobKind.Render)
|
||||
{
|
||||
if (ParseRender(request.ParametersJson) is not { } render) return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
|
||||
label = $"{label} → {render.PresetName}";
|
||||
// A batch becomes one job per preset: a render node uploads one file per job (BRIEF §14.7).
|
||||
IReadOnlyList<RenderJobParameters> each;
|
||||
try
|
||||
{
|
||||
var (width, height) = await SourceSizeAsync(db, targets[0], render, ct);
|
||||
each = ProcessingJobs.Split(render, width, height);
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
|
||||
}
|
||||
queue = each.Count == 1
|
||||
? [($"{label} → {render.PresetName}", request.ParametersJson)]
|
||||
: [.. each.Select(p => ($"{label} → {p.PresetName}", (string?)JsonSerializer.Serialize(p, ProtocolJson.Default.RenderJobParameters)))];
|
||||
}
|
||||
else if (request.ParametersJson is not null && !IsJsonObject(request.ParametersJson))
|
||||
{
|
||||
return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
|
||||
}
|
||||
|
||||
var job = await host.Engine.EnqueueAsync(kind, targets, label, request.ParametersJson, JobPriority.User, caller.Id, ct);
|
||||
await audit.WriteAsync(caller, context, "job_created", "job", job.Id.ToString(), $"{JobWire.Kind(kind)} · {label}");
|
||||
return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
|
||||
Job? first = null;
|
||||
foreach (var (jobLabel, parameters) in queue)
|
||||
{
|
||||
var job = await host.Engine.EnqueueAsync(kind, targets, jobLabel, parameters, JobPriority.User, caller.Id, ct);
|
||||
await audit.WriteAsync(caller, context, "job_created", "job", job.Id.ToString(), $"{JobWire.Kind(kind)} · {jobLabel}");
|
||||
first ??= job;
|
||||
}
|
||||
return Results.Json(Dto.Job(first!), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
|
||||
}
|
||||
|
||||
/// <summary>The oriented size of the sequence's first frame (what a preset without a fixed size renders at), else the job's size.</summary>
|
||||
private static async Task<(int Width, int Height)> SourceSizeAsync(TitanoDatabase db, Guid sequenceId, RenderJobParameters render, CancellationToken ct) =>
|
||||
(await db.Frames.ListBySequenceAsync(sequenceId, limit: 1, cancellationToken: ct)).FirstOrDefault() is { Width: > 0, Height: > 0 } frame
|
||||
? frame.Orientation is >= 5 and <= 8 ? (frame.Height, frame.Width) : (frame.Width, frame.Height)
|
||||
: (render.Width, render.Height);
|
||||
|
||||
private static async Task<IResult> PriorityAsync(HttpContext context, Caller caller, Guid id, JobPriorityRequest request, TitanoDatabase db, JobEngineHost host)
|
||||
{
|
||||
if (!JobWire.TryParsePriority(request.Priority, out var priority)) return ApiErrors.BadRequest(context, "invalid_priority");
|
||||
|
||||
@@ -12,8 +12,9 @@ namespace Titano.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. Render jobs are never run here: render nodes claim them
|
||||
/// (BRIEF §14.7). On shutdown running jobs stay marked running and are requeued from their checkpoints at the next start.
|
||||
/// relays its state changes and progress as WebSocket events. 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.
|
||||
/// </summary>
|
||||
public sealed class JobEngineHost : IHostedService
|
||||
{
|
||||
@@ -30,7 +31,8 @@ public sealed class JobEngineHost : IHostedService
|
||||
{
|
||||
_db = db;
|
||||
_events = events;
|
||||
var local = handlers.Concat(providers.SelectMany(p => p.CreateJobHandlers())).Where(h => h.Kind != JobKind.Render).ToList();
|
||||
// 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: an engine with an empty kind list would claim every kind.
|
||||
Workers = _kinds.Count == 0 ? 0 : options.Workers;
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
using System.Diagnostics;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Api;
|
||||
using Titano.Server.Configuration;
|
||||
|
||||
namespace Titano.Server.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Whether a queued render job that needs a platform encoder still waits for a render node (BRIEF §14.7); once it does
|
||||
/// not, the server's own engine renders it in a managed format. A job waits at least as long as a node may stay silent
|
||||
/// (<see cref="ServerOptions.NodeTimeoutSeconds"/>), so a node that is restarting or reconnecting takes it back, and
|
||||
/// then as long as an online node can encode its codec at its size. The server's render handler asks for every queued
|
||||
/// job it examines, so the online nodes are read at most once a second.
|
||||
/// </summary>
|
||||
public sealed class RenderNodeAvailability(TitanoDatabase db, ServerOptions options, TimeProvider time)
|
||||
{
|
||||
private static readonly TimeSpan SnapshotAge = TimeSpan.FromSeconds(1);
|
||||
|
||||
private Snapshot? _snapshot;
|
||||
|
||||
public async Task<bool> AwaitsNodeAsync(Job job, RenderJobParameters parameters, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(job);
|
||||
ArgumentNullException.ThrowIfNull(parameters);
|
||||
var now = time.GetUtcNow();
|
||||
var timeout = TimeSpan.FromSeconds(options.NodeTimeoutSeconds);
|
||||
if (now - job.Created < timeout) return true;
|
||||
var snapshot = Volatile.Read(ref _snapshot);
|
||||
if (snapshot is null || Stopwatch.GetElapsedTime(snapshot.Read) >= SnapshotAge)
|
||||
{
|
||||
var online = await db.RenderNodes.ListOnlineAsync(now - timeout, cancellationToken);
|
||||
snapshot = new Snapshot(Stopwatch.GetTimestamp(), [.. online.Select(Dto.Capabilities).OfType<RegisterNodeRequest>()]);
|
||||
Volatile.Write(ref _snapshot, snapshot);
|
||||
}
|
||||
return snapshot.Nodes.Any(node => RenderNodeService.CanEncode(node, parameters));
|
||||
}
|
||||
|
||||
/// <summary>What the online nodes announced, and when it was read (a <see cref="Stopwatch"/> timestamp).</summary>
|
||||
private sealed record Snapshot(long Read, IReadOnlyList<RegisterNodeRequest> Nodes);
|
||||
}
|
||||
@@ -47,26 +47,8 @@ public sealed class RenderNodeMonitor(TitanoDatabase db, ServerOptions options,
|
||||
{
|
||||
await db.RenderNodes.SetStateAsync(node.Id, RenderNodeService.Offline, cancellationToken);
|
||||
events.Publish(new NodeStateEvent(node.Id, node.ClientName, RenderNodeService.Offline));
|
||||
var key = RenderNodeService.NodeKey(node);
|
||||
var lost = await db.Jobs.ListRunningByNodeAsync(key, cancellationToken);
|
||||
foreach (var job in lost)
|
||||
{
|
||||
var line = RenderNodeService.AppendLog(job.LogTail, $"Render node {node.ClientName} stopped responding.");
|
||||
if (job.Attempts >= MaxAttempts)
|
||||
{
|
||||
await db.Jobs.FinishNodeJobAsync(job.Id, key, JobState.Failed, $"Lost its render node {job.Attempts} times.", line, cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
await db.Jobs.UpdateNodeProgressAsync(job.Id, key, job.ProgressDone, job.ProgressTotal, null, null, line, cancellationToken);
|
||||
}
|
||||
}
|
||||
var requeued = await db.Jobs.RequeueRunningAsync(key, cancellationToken);
|
||||
var requeued = await RenderNodeService.ReleaseJobsAsync(db, jobs, node, $"Render node {node.ClientName} stopped responding.", cancellationToken);
|
||||
logger.LogWarning("Render node {Node} is offline; {Count} job(s) back in the queue", node.ClientName, requeued);
|
||||
foreach (var job in lost)
|
||||
{
|
||||
if (await db.Jobs.GetAsync(job.Id, cancellationToken) is { } current) jobs.Publish(current);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,16 +41,17 @@ public sealed class RenderNodeService(
|
||||
return Outcome<RenderNodeDto>.Fail(400, "bad_request", "encoders");
|
||||
|
||||
var existing = (await db.RenderNodes.ListAsync(cancellationToken)).FirstOrDefault(n => n.UserId == caller.Id && n.ClientName == name);
|
||||
var id = existing?.Id ?? Guid.CreateVersion7();
|
||||
var running = await db.Jobs.ListRunningByNodeAsync(id.ToString(), cancellationToken);
|
||||
// A node registers when it starts, holding no job: what the server still lists as running on it was abandoned
|
||||
// by its previous run (stopped, restarted or crashed within the heartbeat timeout) and goes back to the queue.
|
||||
if (existing is not null) await ReleaseJobsAsync(db, jobs, existing, $"Render node {name} restarted.", cancellationToken);
|
||||
var node = new RenderNode
|
||||
{
|
||||
Id = id,
|
||||
Id = existing?.Id ?? Guid.CreateVersion7(),
|
||||
UserId = caller.Id,
|
||||
ClientName = name,
|
||||
CapabilitiesJson = JsonSerializer.Serialize(request with { ClientName = name }, ProtocolJson.Default.RegisterNodeRequest),
|
||||
LastHeartbeat = time.GetUtcNow(),
|
||||
State = running.Count > 0 ? Busy : Idle,
|
||||
State = Idle,
|
||||
};
|
||||
await db.RenderNodes.RegisterAsync(node, cancellationToken);
|
||||
events.Publish(new NodeStateEvent(node.Id, node.ClientName, node.State));
|
||||
@@ -71,6 +72,9 @@ public sealed class RenderNodeService(
|
||||
var capabilities = Dto.Capabilities(node);
|
||||
foreach (var queued in await db.Jobs.ListQueuedAsync(JobKind.Render, 50, cancellationToken))
|
||||
{
|
||||
// A render the server's own engine started (it left a checkpoint) resumes there: only it knows that attempt's
|
||||
// leftovers and the batch entries it recorded.
|
||||
if (queued.Checkpoint is not null) continue;
|
||||
if (JobEndpoints.ParseRender(queued.ParametersJson) is not { } parameters || capabilities is null || !CanEncode(capabilities, parameters)) continue;
|
||||
if (await db.Jobs.TryClaimAsync(queued.Id, NodeKey(node), cancellationToken) is not { } job) continue;
|
||||
jobs.Publish(job);
|
||||
@@ -182,6 +186,31 @@ public sealed class RenderNodeService(
|
||||
/// <summary>Running-job owner key stored in <c>jobs.node_id</c>.</summary>
|
||||
public static string NodeKey(RenderNode node) => node.Id.ToString();
|
||||
|
||||
/// <summary>
|
||||
/// Gives the jobs running on <paramref name="node"/> back to the queue with <paramref name="reason"/> in their log
|
||||
/// (checkpoint and progress kept); a job that already lost its node <see cref="RenderNodeMonitor.MaxAttempts"/> times
|
||||
/// fails instead. Returns how many went back.
|
||||
/// </summary>
|
||||
internal static async Task<int> ReleaseJobsAsync(TitanoDatabase db, JobEngineHost jobs, RenderNode node, string reason, CancellationToken cancellationToken)
|
||||
{
|
||||
var key = NodeKey(node);
|
||||
var lost = await db.Jobs.ListRunningByNodeAsync(key, cancellationToken);
|
||||
foreach (var job in lost)
|
||||
{
|
||||
var line = AppendLog(job.LogTail, reason);
|
||||
if (job.Attempts >= RenderNodeMonitor.MaxAttempts)
|
||||
await db.Jobs.FinishNodeJobAsync(job.Id, key, JobState.Failed, $"Lost its render node {job.Attempts} times.", line, cancellationToken);
|
||||
else
|
||||
await db.Jobs.UpdateNodeProgressAsync(job.Id, key, job.ProgressDone, job.ProgressTotal, null, null, line, cancellationToken);
|
||||
}
|
||||
var requeued = await db.Jobs.RequeueRunningAsync(key, cancellationToken);
|
||||
foreach (var job in lost)
|
||||
{
|
||||
if (await db.Jobs.GetAsync(job.Id, cancellationToken) is { } current) jobs.Publish(current);
|
||||
}
|
||||
return requeued;
|
||||
}
|
||||
|
||||
private async Task<RenderNode?> OwnedNodeAsync(Caller caller, Guid nodeId, CancellationToken cancellationToken) =>
|
||||
await db.RenderNodes.GetAsync(nodeId, cancellationToken) is { } node && node.UserId == caller.Id ? node : null;
|
||||
|
||||
@@ -221,11 +250,16 @@ public sealed class RenderNodeService(
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The node has an encoder for the job's codec and handles its resolution (0 = no announced limit).</summary>
|
||||
private static bool CanEncode(RegisterNodeRequest node, RenderJobParameters job) =>
|
||||
node.Encoders.Any(e => string.Equals(e.Codec, job.Codec, StringComparison.OrdinalIgnoreCase))
|
||||
&& (node.MaxWidth <= 0 || job.Width <= node.MaxWidth)
|
||||
&& (node.MaxHeight <= 0 || job.Height <= node.MaxHeight);
|
||||
/// <summary>
|
||||
/// The node has an encoder for the job's codec that handles its resolution: the encoder's own limit, else the node's
|
||||
/// (0 = no announced limit).
|
||||
/// </summary>
|
||||
internal static bool CanEncode(RegisterNodeRequest node, RenderJobParameters job) =>
|
||||
node.Encoders.Any(e => string.Equals(e.Codec, job.Codec, StringComparison.OrdinalIgnoreCase)
|
||||
&& Fits(job.Width, e.MaxWidth > 0 ? e.MaxWidth : node.MaxWidth)
|
||||
&& Fits(job.Height, e.MaxHeight > 0 ? e.MaxHeight : node.MaxHeight));
|
||||
|
||||
private static bool Fits(int size, int limit) => limit <= 0 || size <= limit;
|
||||
|
||||
internal static string? AppendLog(string? tail, string? line)
|
||||
{
|
||||
|
||||
@@ -26,15 +26,22 @@ switch (command.Command)
|
||||
case ServerCommand.UninstallService when OperatingSystem.IsWindows():
|
||||
return ServiceAction(ServiceInstaller.Uninstall, $"Removed the {WindowsServiceHost.ServiceName} service.");
|
||||
case ServerCommand.Service when OperatingSystem.IsWindows():
|
||||
if (WindowsServiceHost.Run(() => ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], ArchiveModule.Register))) return 0;
|
||||
if (WindowsServiceHost.Run(() => ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], RegisterModules))) return 0;
|
||||
await Console.Error.WriteLineAsync("--service is used by the Service Control Manager; start the service with 'sc start TitanoServer'.");
|
||||
return 1;
|
||||
default:
|
||||
var app = ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], ArchiveModule.Register);
|
||||
var app = ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], RegisterModules);
|
||||
await app.RunAsync();
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The archive engine, then analysis and managed rendering over it.
|
||||
static void RegisterModules(IServiceCollection services)
|
||||
{
|
||||
ArchiveModule.Register(services);
|
||||
ProcessingModule.Register(services);
|
||||
}
|
||||
|
||||
static int ServiceAction(Action action, string done)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -7,8 +7,8 @@ namespace Titano.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// The archive engine behind the server (BRIEF §7, §14.4): ingest of verified uploads, lookup of proxies and
|
||||
/// thumbnails, and its job handlers (scan, rebuild, verify, import, thumbnails, proxies, maintenance), plus the
|
||||
/// analysis handlers of <see cref="ProcessingModule"/>. Decoding is managed only (BRIEF §4.2).
|
||||
/// thumbnails, and its job handlers (scan, rebuild, verify, import, thumbnails, proxies, maintenance). Decoding is
|
||||
/// managed only (BRIEF §4.2).
|
||||
/// </summary>
|
||||
public static class ArchiveModule
|
||||
{
|
||||
@@ -22,6 +22,5 @@ public static class ArchiveModule
|
||||
services.AddSingleton<IArchiveIngest>(sp => sp.GetRequiredService<ArchiveService>().Ingest);
|
||||
services.AddSingleton<IJobHandlerProvider>(sp => sp.GetRequiredService<ArchiveService>());
|
||||
services.AddSingleton<IFrameAssetLocator, ArchiveAssetLocator>();
|
||||
ProcessingModule.Register(services);
|
||||
}
|
||||
}
|
||||
@@ -5,26 +5,44 @@ using Titano.Data;
|
||||
using Titano.Data.Archiving;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Data.Processing;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Configuration;
|
||||
using Titano.Server.Events;
|
||||
using Titano.Server.Jobs;
|
||||
|
||||
namespace Titano.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Analysis and render engine of the server (BRIEF §4.2, §10, §14.6): light and deep analysis job handlers with managed
|
||||
/// decoders, so the light analysis queued after uploads runs here. Its render handler is registered too, but the job
|
||||
/// engine host never runs render jobs: render nodes claim them (BRIEF §14.7).
|
||||
/// Analysis and render engine of the server (BRIEF §4.2, §10, §14.5, §14.6): light and deep analysis with managed
|
||||
/// decoders (the light analysis queued after uploads runs here) and renders with managed encoders only. The render
|
||||
/// handler takes the jobs whose every output a managed encoder produces (AVI MJPEG, image sequences, GIF, APNG); MP4
|
||||
/// jobs wait for render nodes until none can take them (<see cref="RenderNodeAvailability"/>), and then render here as
|
||||
/// MJPEG in AVI with a line in the job log (BRIEF §14.7). Renders recorded and Auto values changed here reach connected
|
||||
/// clients as <c>sequenceChanged</c> events (§14.3).
|
||||
/// </summary>
|
||||
public static class ProcessingModule
|
||||
{
|
||||
public static void Register(IServiceCollection services)
|
||||
{
|
||||
services.AddSingleton(sp => new ProcessingService(sp.GetRequiredService<TitanoDatabase>(), new ProcessingOptions
|
||||
services.AddSingleton<RenderNodeAvailability>();
|
||||
services.AddSingleton(sp =>
|
||||
{
|
||||
Archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner },
|
||||
Encoders = [new ManagedEncoderProvider()],
|
||||
Host = EncoderHost.Server,
|
||||
ProducedBy = sp.GetRequiredService<ServerOptions>().ServerName,
|
||||
}));
|
||||
var db = sp.GetRequiredService<TitanoDatabase>();
|
||||
var events = sp.GetRequiredService<EventHub>();
|
||||
return new ProcessingService(db, new ProcessingOptions
|
||||
{
|
||||
Archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner },
|
||||
Encoders = [new ManagedEncoderProvider()],
|
||||
Host = EncoderHost.Server,
|
||||
AwaitsRenderNode = sp.GetRequiredService<RenderNodeAvailability>().AwaitsNodeAsync,
|
||||
ProducedBy = sp.GetRequiredService<ServerOptions>().ServerName,
|
||||
SequenceChanged = async (id, change, ct) =>
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, ct) is { } sequence)
|
||||
events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion));
|
||||
},
|
||||
});
|
||||
});
|
||||
services.AddSingleton<IJobHandlerProvider>(sp => sp.GetRequiredService<ProcessingService>());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user