test(server): auth, uploads, ranges, sync, jobs, render nodes, events

Covers bootstrap admin, sign-in failure, lockout and rate limit, token
revocation and expiry, 401 versus 403, CSRF on cookie sessions, the error
shape and API header, chunked upload happy path, resume, hash
short-circuit, damaged chunk, quota, Range on originals, thumbnails and
exports, path traversal, settings_version conflicts, job state
transitions with a fake handler, render node claim, heartbeat timeout and
reassignment, output upload, WebSocket progress events, the discovery
beacon, the Windows service command line and status rules, and a
PostgreSQL run (TITANO_TEST_PG).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 12:28:47 +00:00
1 parent c78747053e
commit 80b91d0585
16 files changed
+1646

No files matched your search

@@ -0,0 +1,139 @@
using System.Net;
using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Titano.Core.Model;
using Titano.Data.Jobs;
using Titano.Protocol;
using Titano.Testing;
namespace Titano.Server.Tests.Jobs;
[Category("server")]
public sealed class JobApiTests(TestContext context)
{
[Test]
public async Task JobsMoveThroughPauseResumeAndDone()
{
var handler = new BlockingJobHandler(JobKind.DeepAnalyse);
await using var server = await TestServer.StartAsync(context, services: s => s.AddSingleton<IJobHandler>(handler));
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var sequence = await CreateSequenceAsync(editor);
var job = await CreateAsync(editor, "deep-analyse", sequence);
Assert.Equal(("queued", "user", "Harbour sunset"), (job.State, job.Priority, job.TargetLabel));
await handler.Started.Task.WaitAsync(TimeSpan.FromSeconds(10));
await WaitForAsync(editor, job.Id, "running");
Assert.Equal("paused", (await ActAsync(editor, job.Id, "pause", HttpStatusCode.OK)).State);
await WaitForAsync(editor, job.Id, "paused");
await ActAsync(editor, job.Id, "pause", HttpStatusCode.Conflict);
await ActAsync(editor, job.Id, "retry", HttpStatusCode.Conflict);
await ActAsync(editor, job.Id, "resume", HttpStatusCode.OK);
await WaitForAsync(editor, job.Id, "running");
handler.Release();
var done = await WaitForAsync(editor, job.Id, "done");
Assert.Equal((4L, 4L), (done.ProgressDone, done.ProgressTotal));
await ActAsync(editor, job.Id, "cancel", HttpStatusCode.Conflict);
using var list = await editor.GetAsync("/api/v1/jobs?state=done&kind=deep-analyse");
Assert.Equal(job.Id, (await list.ReadAsync(ProtocolJson.Default.PageJobDto)).Items.Single().Id);
}
[Test]
public async Task FailedJobsRetryAndRunningJobsCancel()
{
var handler = new BlockingJobHandler(JobKind.Proxies) { FailWith = "decoder exploded" };
await using var server = await TestServer.StartAsync(context, services: s => s.AddSingleton<IJobHandler>(handler));
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var sequence = await CreateSequenceAsync(editor);
var job = await CreateAsync(editor, "proxies", sequence);
var failed = await WaitForAsync(editor, job.Id, "failed");
Assert.Equal("decoder exploded", failed.Error);
Assert.Contains("decoder exploded", failed.LogTail);
await ActAsync(editor, job.Id, "retry", HttpStatusCode.OK);
await WaitForAsync(editor, job.Id, "running");
Assert.Equal("cancelled", (await ActAsync(editor, job.Id, "cancel", HttpStatusCode.OK)).State);
await Task.Delay(200);
Assert.Equal("cancelled", (await GetAsync(editor, job.Id)).State);
}
[Test]
public async Task WaitingJobsChangePriorityAndRightsAreChecked()
{
var handler = new BlockingJobHandler(JobKind.Thumbs);
await using var server = await TestServer.StartAsync(context, o => o.Workers = 1, s => s.AddSingleton<IJobHandler>(handler));
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var (viewer, _, _) = await server.UserAsync("marco", "viewer");
var sequence = await CreateSequenceAsync(editor);
var first = await CreateAsync(editor, "thumbs", sequence);
await WaitForAsync(editor, first.Id, "running");
var second = await CreateAsync(editor, "thumbs", sequence);
using (var lower = await editor.PostAsJsonAsync($"/api/v1/jobs/{second.Id}/priority", new JobPriorityRequest("background"), ProtocolJson.Default.JobPriorityRequest))
Assert.Equal("background", (await lower.ReadAsync(ProtocolJson.Default.JobDto)).Priority);
using (var bad = await editor.PostAsJsonAsync($"/api/v1/jobs/{second.Id}/priority", new JobPriorityRequest("urgent"), ProtocolJson.Default.JobPriorityRequest))
await bad.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_priority");
using (var foreign = await viewer.PostAsync($"/api/v1/jobs/{second.Id}/cancel", null)) await foreign.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var create = await viewer.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("thumbs", [sequence], null), ProtocolJson.Default.CreateJobRequest))
await create.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var unknown = await editor.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("teleport", [sequence], null), ProtocolJson.Default.CreateJobRequest))
await unknown.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_job_kind");
using (var unavailable = await editor.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("deep-analyse", [sequence], null), ProtocolJson.Default.CreateJobRequest))
await unavailable.ExpectErrorAsync(HttpStatusCode.Conflict, "job_unavailable");
using (var render = await editor.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("render", [sequence], "{}"), ProtocolJson.Default.CreateJobRequest))
await render.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_parameters");
var admin = await server.AdminAsync();
using (var removed = await admin.PostAsync($"/api/v1/jobs/{second.Id}/cancel", null)) await removed.ExpectAsync(HttpStatusCode.OK);
handler.Release();
await WaitForAsync(editor, first.Id, "done");
}
public static async Task<Guid> CreateSequenceAsync(HttpClient client, string title = "Harbour sunset")
{
using var created = await client.PostAsJsonAsync("/api/v1/sequences", new CreateSequenceRequest(title, null), ProtocolJson.Default.CreateSequenceRequest);
await created.ExpectAsync(HttpStatusCode.Created);
return (await created.ReadAsync(ProtocolJson.Default.SequenceDto)).Id;
}
public static async Task<JobDto> CreateAsync(HttpClient client, string kind, Guid target, string? parameters = null)
{
using var response = await client.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest(kind, [target], parameters), ProtocolJson.Default.CreateJobRequest);
await response.ExpectAsync(HttpStatusCode.Accepted);
return await response.ReadAsync(ProtocolJson.Default.JobDto);
}
public static async Task<JobDto> GetAsync(HttpClient client, Guid id)
{
using var response = await client.GetAsync($"/api/v1/jobs/{id}");
return await response.ReadAsync(ProtocolJson.Default.JobDto);
}
public static async Task<JobDto> WaitForAsync(HttpClient client, Guid id, string state)
{
var deadline = DateTime.UtcNow.AddSeconds(15);
while (true)
{
var job = await GetAsync(client, id);
if (job.State == state) return job;
if (DateTime.UtcNow > deadline) Assert.Fail($"Job {id} is {job.State}, expected {state}");
await Task.Delay(50);
}
}
private static async Task<JobDto> ActAsync(HttpClient client, Guid id, string action, HttpStatusCode expected)
{
using var response = await client.PostAsync($"/api/v1/jobs/{id}/{action}", null);
if (expected != HttpStatusCode.OK)
{
await response.ExpectErrorAsync(expected, "invalid_state");
return await GetAsync(client, id);
}
await response.ExpectAsync(expected);
return await response.ReadAsync(ProtocolJson.Default.JobDto);
}
}
@@ -0,0 +1,133 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Titano.Protocol;
using Titano.Protocol.Client;
using Titano.Server.Jobs;
using Titano.Testing;
namespace Titano.Server.Tests.Jobs;
[Category("server")]
public sealed class RenderNodeTests(TestContext context)
{
private static readonly string HevcJob = JsonSerializer.Serialize(
new RenderJobParameters("4K HEVC", """{"codec":"hevc","bitrate":60}""", "hevc", 3840, 2160, UseProxies: false, null), ProtocolJson.Default.RenderJobParameters);
[Test]
public async Task NodesClaimWhatTheyCanEncodeAndLoseJobsWhenSilent()
{
var clock = new ManualTimeProvider();
await using var server = await TestServer.StartAsync(context, o => o.NodeTimeoutSeconds = 60, s => s.AddSingleton<TimeProvider>(clock));
var (editor, _, _) = await server.UserAsync("alberto", "editor", renderNode: true);
var frame = await Uploads.UploadAsync(editor, Uploads.Photo(5000, 51), "IMG_0001.CR3");
var job = await JobApiTests.CreateAsync(editor, "render", frame.SequenceId, HevcJob);
var studio = await RegisterAsync(editor, "studio-pc", "hevc", 8192);
var laptop = await RegisterAsync(editor, "laptop", "h264", 4096);
var spare = await RegisterAsync(editor, "spare-pc", "HEVC", 0);
using (var none = await editor.PostAsync($"/api/v1/nodes/{laptop.Id}/claim", null)) await none.ExpectAsync(HttpStatusCode.NoContent);
ClaimedJob claimed;
using (var claim = await editor.PostAsync($"/api/v1/nodes/{studio.Id}/claim", null))
{
await claim.ExpectAsync(HttpStatusCode.OK);
claimed = await claim.ReadAsync(ProtocolJson.Default.ClaimedJob);
}
Assert.Equal((job.Id, frame.SequenceId, "running"), (claimed.Job.Id, claimed.SequenceId, claimed.Job.State));
Assert.Equal(frame.FrameId, claimed.Frames.Single().Id);
Assert.Equal(studio.Id.ToString(), claimed.Job.NodeId);
using (var second = await editor.PostAsync($"/api/v1/nodes/{spare.Id}/claim", null)) await second.ExpectAsync(HttpStatusCode.NoContent);
using (var progress = await editor.PostAsJsonAsync($"/api/v1/nodes/{studio.Id}/jobs/{job.Id}/progress", new NodeProgress(120, 3600, 40, "encoding"),
ProtocolJson.Default.NodeProgress))
await progress.ExpectAsync(HttpStatusCode.NoContent);
Assert.Equal(120L, (await JobApiTests.GetAsync(editor, job.Id)).ProgressDone);
// studio-pc goes silent; the others keep heart-beating.
clock.Advance(TimeSpan.FromSeconds(90));
foreach (var alive in new[] { laptop, spare })
using (var beat = await editor.PostAsync($"/api/v1/nodes/{alive.Id}/heartbeat", null)) await beat.ExpectAsync(HttpStatusCode.NoContent);
await server.Services.GetRequiredService<RenderNodeMonitor>().SweepAsync(context.Cancellation);
var requeued = await JobApiTests.GetAsync(editor, job.Id);
Assert.Equal("queued", requeued.State);
Assert.Contains("studio-pc stopped responding", requeued.LogTail);
using (var nodes = await editor.GetAsync("/api/v1/nodes"))
{
var states = (await nodes.ReadAsync(ProtocolJson.Default.ListRenderNodeDto)).ToDictionary(n => n.ClientName, n => n.State);
Assert.Equal(("offline", "idle"), (states["studio-pc"], states["laptop"]));
}
using (var late = await editor.PostAsJsonAsync($"/api/v1/nodes/{studio.Id}/jobs/{job.Id}/progress", new NodeProgress(200, 3600, 40, null),
ProtocolJson.Default.NodeProgress))
await late.ExpectErrorAsync(HttpStatusCode.Conflict, "job_not_assigned");
using (var reassigned = await editor.PostAsync($"/api/v1/nodes/{spare.Id}/claim", null))
{
var again = await reassigned.ReadAsync(ProtocolJson.Default.ClaimedJob);
Assert.Equal((job.Id, 2), (again.Job.Id, again.Job.Attempts));
}
}
[Test]
public async Task TheOutputUploadBecomesARenderAndFinishesTheJob()
{
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = 64 * 1024);
var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
var frame = await Uploads.UploadAsync(editor, Uploads.Photo(5000, 52), "IMG_0001.CR3");
var job = await JobApiTests.CreateAsync(editor, "render", frame.SequenceId, HevcJob);
using var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), "studio-pc") { Token = token };
var node = await client.RegisterNodeAsync(new RegisterNodeRequest("studio-pc", [new NodeEncoder("hevc", "NVENC HEVC", true, true)], 8192, 8192));
var claimed = Assert.NotNull(await client.ClaimAsync(node.Id));
await client.ReportNodeProgressAsync(node.Id, claimed.Job.Id, new NodeProgress(3600, 3600, 50, "muxing"));
var output = Path.Combine(context.CreateTempDirectory("render"), "Harbour sunset - 4K HEVC.mp4");
var video = Uploads.Photo(150_000, 53);
await File.WriteAllBytesAsync(output, video);
var render = await client.UploadRenderResultAsync(node.Id, job.Id, output,
new RenderResultRequest(Path.GetFileName(output), video.Length, Uploads.Sha(video), "4K HEVC", "hevc", 3840, 2160, 25, 144));
Assert.Equal(("4K HEVC", "studio-pc", (long)video.Length), (render.PresetName, render.ProducedBy, render.Bytes));
var done = await JobApiTests.GetAsync(editor, job.Id);
Assert.Equal("done", done.State);
var sequence = (await server.Database.Sequences.GetAsync(frame.SequenceId))!;
Assert.Equal(1, sequence.RenderedCount);
var file = Path.Combine(server.Options.ArchivePath, sequence.Folder, "exports", "Harbour sunset - 4K HEVC.mp4");
await Http.BytesEqualAsync(video, File.ReadAllBytesAsync(file));
using var renders = await editor.GetAsync($"/api/v1/sequences/{sequence.Id}/renders");
Assert.Equal(render.Id, (await renders.ReadAsync(ProtocolJson.Default.ListRenderDto)).Single().Id);
}
[Test]
public async Task NodesReportFailuresAndNeedTheRight()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, _) = await server.UserAsync("alberto", "editor", renderNode: true);
var (plain, _, _) = await server.UserAsync("giulia", "editor");
var sequence = await JobApiTests.CreateSequenceAsync(editor);
var job = await JobApiTests.CreateAsync(editor, "render", sequence, HevcJob);
var node = await 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 failed = await editor.PostAsJsonAsync($"/api/v1/nodes/{node.Id}/jobs/{job.Id}/failed", new NodeJobFailure("NVENC session limit reached"),
ProtocolJson.Default.NodeJobFailure))
await failed.ExpectAsync(HttpStatusCode.NoContent);
var state = await JobApiTests.GetAsync(editor, job.Id);
Assert.Equal(("failed", "NVENC session limit reached"), (state.State, state.Error));
using var refused = await plain.PostAsJsonAsync("/api/v1/nodes/register", new RegisterNodeRequest("giulia-pc", [new NodeEncoder("hevc", "QSV", true, false)], 0, 0),
ProtocolJson.Default.RegisterNodeRequest);
await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using var foreign = await plain.PostAsync($"/api/v1/nodes/{node.Id}/heartbeat", null);
await foreign.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
}
private static async Task<RenderNodeDto> RegisterAsync(HttpClient client, string name, string codec, int maxWidth)
{
using var response = await client.PostAsJsonAsync("/api/v1/nodes/register",
new RegisterNodeRequest(name, [new NodeEncoder(codec, codec.ToUpperInvariant() + " encoder", true, false)], maxWidth, maxWidth), ProtocolJson.Default.RegisterNodeRequest);
await response.ExpectAsync(HttpStatusCode.OK);
return await response.ReadAsync(ProtocolJson.Default.RenderNodeDto);
}
}