fix(render-node): a restarted node frees its job; downloads resume; batches split on arrival
A node registering again gives back the job its previous run abandoned, so a restart within the heartbeat timeout no longer leaves it running forever. Frame downloads retry dropped connections from the partial file; a 404 at registration waits for the next poll; render remarks reach the job log; a render the server engine started stays with it. POST /jobs splits a batch into one job per preset, and a node fails a batch it cannot send back instead of reporting it done. Renders honour Settings > Rendering: hardware encoders only where the preference allows them, also for what a node offers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
14 files changed
+512
-82
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");
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
Reference in new issue
Block a user