refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-23 12:45:18 +02:00
1 parent c99842cc86
commit f2b58522b9
1801 files changed
+11804 -10676

No files matched your search

@@ -0,0 +1,253 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json.Nodes;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Protocol;
using Chronos.Server.Configuration;
using Chronos.Server.Hosting;
using Chronos.Testing;
namespace Chronos.Server.Tests.Api;
[Category("server")]
public sealed class AdminTests(TestContext context)
{
[Test]
public async Task TheDashboardSummarisesTheServer()
{
await using var server = await TestServer.StartAsync(context, o => o.ServerName = "Studio NAS");
var (editor, _, _) = await server.UserAsync("alberto", "editor");
await Uploads.UploadAsync(editor, Uploads.Photo(4000, 61));
var admin = await server.AdminAsync();
using var response = await admin.GetAsync("/api/v1/server/dashboard");
await response.ExpectAsync(HttpStatusCode.OK);
var dashboard = await response.ReadAsync(ProtocolJson.Default.DashboardDto);
Assert.Equal(("Studio NAS", 2, 1L, 1L), (dashboard.ServerName, dashboard.Users, dashboard.Archive.Sequences, dashboard.Archive.Photos));
Assert.True(dashboard.Database.StartsWith("SQLite ", StringComparison.Ordinal), dashboard.Database);
Assert.Equal(1L, dashboard.Uploads.Single().Frames);
Assert.Contains(dashboard.Activity, a => a.Action == "user_created");
Assert.True(dashboard.Archive.CapacityBytes > 0);
}
[Test]
public async Task SettingsAreSavedAndRestartOnlyValuesFlagged()
{
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
using var read = await admin.GetAsync("/api/v1/server/settings");
var settings = await read.ReadAsync(ProtocolJson.Default.ServerSettingsDto);
Assert.False(settings.RestartRequired);
var edited = settings with { ServerName = "Rooftop", Discovery = true, HttpPort = 18080, HttpsPort = 18443 };
using (var saved = await admin.PutAsJsonAsync("/api/v1/server/settings", edited, ProtocolJson.Default.ServerSettingsDto))
Assert.True((await saved.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).RestartRequired);
// Name and discovery apply at once; ports wait for the restart.
Assert.Equal(("Rooftop", true, 0), (server.Options.ServerName, server.Options.Discovery, server.Options.HttpPort));
using (var again = await admin.GetAsync("/api/v1/server/settings"))
Assert.Equal(18080, (await again.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).HttpPort);
var file = JsonNode.Parse(await File.ReadAllTextAsync(server.Options.SettingsFile))!.AsObject();
Assert.Equal(("Rooftop", 18080), (file["ServerName"]!.GetValue<string>(), file["HttpPort"]!.GetValue<int>()));
Assert.False(file.ContainsKey("AdminPassword"));
using var invalid = await admin.PutAsJsonAsync("/api/v1/server/settings", edited with { Language = "tlh" }, ProtocolJson.Default.ServerSettingsDto);
Assert.Equal("Language", (await invalid.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_setting")).Details);
}
[Test]
public async Task TheParallelismAndThePriorityQueueApplyAtOnce()
{
// Owner review 1 (R2): jobs run one at a time; the parallelism (photos at once) and the priority queue need no restart.
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
using var read = await admin.GetAsync("/api/v1/server/settings");
var settings = await read.ReadAsync(ProtocolJson.Default.ServerSettingsDto);
Assert.Equal((2, false), (settings.Parallelism, settings.PriorityQueue));
Assert.Equal(ServerSettingsStore.Kinds.Count, settings.JobPriorities.Count);
Assert.Equal(("render", "high"), (settings.JobPriorities[0].Kind, settings.JobPriorities[0].Level));
Assert.Equal("low", settings.JobPriorities.Single(p => p.Kind == "verify").Level);
Assert.DoesNotContain("download", settings.JobPriorities.Select(p => p.Kind));
// The test server listens on ports the system chose (0), which no request may set.
var edited = settings with
{
HttpPort = 18080,
HttpsPort = 18443,
Parallelism = 3,
PriorityQueue = true,
JobPriorities = [.. settings.JobPriorities.Select(p => p.Kind == "scan" ? p with { Level = "high" } : p)],
};
using (var saved = await admin.PutAsJsonAsync("/api/v1/server/settings", edited, ProtocolJson.Default.ServerSettingsDto))
await saved.ExpectAsync(HttpStatusCode.OK);
// Applied at once, while the ports wait for the restart.
Assert.Equal((3, true, 0), (server.Options.Parallelism, server.Options.PriorityQueue, server.Options.HttpPort));
var queue = ServerSettingsStore.PriorityQueue(server.Options);
Assert.True(queue.Enabled);
Assert.Equal((JobKindPriority.High, JobKindPriority.High), (queue.LevelOf(JobKind.Scan), queue.LevelOf(JobKind.Render)));
// Only the level that differs from the defaults is stored.
var file = JsonNode.Parse(await File.ReadAllTextAsync(server.Options.SettingsFile))!.AsObject();
Assert.Equal((3, true), (file["Parallelism"]!.GetValue<int>(), file["PriorityQueue"]!.GetValue<bool>()));
Assert.Equal("""{"scan":"high"}""", file["JobPriorities"]!.ToJsonString());
Assert.False(file.ContainsKey("Workers"));
using (var dashboard = await admin.GetAsync("/api/v1/server/dashboard"))
{
var d = await dashboard.ReadAsync(ProtocolJson.Default.DashboardDto);
Assert.Equal((3, true), (d.Parallelism, d.PriorityQueue));
}
foreach (var (invalid, setting) in new (ServerSettingsDto, string)[]
{
(edited with { Parallelism = 0 }, "Parallelism"),
(edited with { JobPriorities = [new JobPriorityDto("download", "high")] }, "JobPriorities"),
(edited with { JobPriorities = [new JobPriorityDto("scan", "urgent")] }, "JobPriorities"),
})
{
using var refused = await admin.PutAsJsonAsync("/api/v1/server/settings", invalid, ProtocolJson.Default.ServerSettingsDto);
Assert.Equal(setting, (await refused.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_setting")).Details);
}
}
[Test]
public async Task LogsAreReadableButOnlyByName()
{
await using var server = await TestServer.StartAsync(context, o => o.LogLevel = Microsoft.Extensions.Logging.LogLevel.Information);
var admin = await server.AdminAsync();
using var tail = await admin.GetAsync("/api/v1/logs?lines=20");
var lines = await tail.ReadAsync(ProtocolJson.Default.LogTailDto);
Assert.NotEmpty(lines.Lines);
Assert.True(lines.Lines.Count <= 20);
using var files = await admin.GetAsync("/api/v1/logs/files");
var name = (await files.ReadAsync(ProtocolJson.Default.ListLogFileDto)).First().Name;
using (var download = await admin.GetAsync($"/api/v1/logs/files/{name}")) await download.ExpectAsync(HttpStatusCode.OK);
using var traversal = await admin.GetAsync("/api/v1/logs/files/..%2Fserver.json");
await traversal.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
}
[Test]
public async Task TheCurrentLogDownloadsWhileTheServerKeepsLogging()
{
await using var server = await TestServer.StartAsync(context, o => o.LogLevel = Microsoft.Extensions.Logging.LogLevel.Information);
var admin = await server.AdminAsync();
using var files = await admin.GetAsync("/api/v1/logs/files");
var name = (await files.ReadAsync(ProtocolJson.Default.ListLogFileDto)).First().Name;
// Jobs, uploads and sign-ins keep writing to the file an administrator downloads: a log of a few megabytes takes
// a while to send, and a line lands about every millisecond meanwhile. Only to the file and never in a tight loop:
// engine code of every test server in this process logs through the last one started, so this server's console
// and file lock are shared with the tests running alongside.
var logger = server.Services.GetServices<ILoggerProvider>().OfType<FileLoggerProvider>().Single().CreateLogger("Chronos.Server.Tests");
var block = new string('x', 64 * 1024);
for (var i = 0; i < 32; i++) logger.LogInformation("{Block}", block);
using var stop = new CancellationTokenSource();
var logging = Task.Factory.StartNew(() =>
{
while (!stop.IsCancellationRequested)
{
logger.LogInformation("Busy");
Thread.Sleep(1);
}
}, TaskCreationOptions.LongRunning);
try
{
for (var i = 0; i < 5; i++)
{
using var download = await admin.GetAsync($"/api/v1/logs/files/{name}");
await download.ExpectAsync(HttpStatusCode.OK);
Assert.Equal(download.Content.Headers.ContentLength, (await download.Content.ReadAsByteArrayAsync()).LongLength);
}
}
finally
{
await stop.CancelAsync();
await logging;
}
}
[Test]
public async Task ArchiveSettingsValidateTemplatesAndJobsNeedHandlers()
{
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
using var read = await admin.GetAsync("/api/v1/archive/settings");
var archive = await read.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto);
Assert.Equal(Path.GetFullPath(server.Options.ArchivePath), archive.RootPath);
using (var bad = await admin.PutAsJsonAsync("/api/v1/archive/settings", archive with { FolderTemplate = "{year/{date" }, ProtocolJson.Default.ArchiveSettingsDto))
Assert.Equal("folderTemplate", (await bad.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template")).Details);
using (var good = await admin.PutAsJsonAsync("/api/v1/archive/settings", archive with { Name = "Studio", ProxyLongEdge = 2560 }, ProtocolJson.Default.ArchiveSettingsDto))
{
var saved = await good.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto);
Assert.Equal(("Studio", 2560), (saved.Name, saved.ProxyLongEdge));
}
using var scan = await admin.PostAsync("/api/v1/archive/scan", null);
await scan.ExpectErrorAsync(HttpStatusCode.Conflict, "job_unavailable");
using var stats = await admin.GetAsync("/api/v1/archive/stats");
await stats.ExpectAsync(HttpStatusCode.OK);
}
[Test]
public async Task ArchiveSettingsAreWrittenToArchiveJsonAndSurviveARestart()
{
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
using var read = await admin.GetAsync("/api/v1/archive/settings");
var archive = await read.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto);
var changed = archive with { Name = "Studio", FolderTemplate = "{year}/{camera}", FileTemplate = "{name}", ProxyLongEdge = -1 };
using (var put = await admin.PutAsJsonAsync("/api/v1/archive/settings", changed, ProtocolJson.Default.ArchiveSettingsDto))
await put.ExpectAsync(HttpStatusCode.OK);
// archive.json is the truth (BRIEF §7): the proxy jobs read it, and the next start registers the archive from it.
var manifest = Chronos.Core.Archiving.ManifestStore.ReadArchive(new Chronos.Core.Archiving.ArchivePaths(server.Options.ArchivePath).ManifestPath);
Assert.Equal(("Studio", "{year}/{camera}", "{name}", -1), (manifest.Name, manifest.LayoutTemplates.Folder, manifest.LayoutTemplates.File, manifest.ProxyPolicy.LongEdge));
var restarted = await Chronos.Server.Storage.ServerArchive.OpenAsync(server.Database, server.Options, context.Cancellation);
Assert.Equal(("Studio", "{name}", -1), (restarted.Current.Name, restarted.Current.FileTemplate, restarted.Current.ProxyLongEdge));
using var again = await admin.GetAsync("/api/v1/archive/settings");
Assert.Equal(changed, await again.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto));
// The archive drive is gone: nothing is written and the admin hears why.
var path = new Chronos.Core.Archiving.ArchivePaths(server.Options.ArchivePath).ManifestPath;
File.Move(path, path + ".away");
try
{
using var offline = await admin.PutAsJsonAsync("/api/v1/archive/settings", changed with { ProxyLongEdge = 1280 }, ProtocolJson.Default.ArchiveSettingsDto);
await offline.ExpectErrorAsync(HttpStatusCode.ServiceUnavailable, "archive_offline");
}
finally
{
File.Move(path + ".away", path);
}
Assert.Equal(-1, Chronos.Core.Archiving.ManifestStore.ReadArchive(path).ProxyPolicy.LongEdge);
// A damaged archive.json is reported as such (not as an internal error) and left as it is.
var saved = await File.ReadAllBytesAsync(path, context.Cancellation);
await File.WriteAllTextAsync(path, "{ not json", context.Cancellation);
try
{
using var damaged = await admin.PutAsJsonAsync("/api/v1/archive/settings", changed with { ProxyLongEdge = 1280 }, ProtocolJson.Default.ArchiveSettingsDto);
await damaged.ExpectErrorAsync(HttpStatusCode.Conflict, "archive_manifest");
Assert.Equal("{ not json", await File.ReadAllTextAsync(path, context.Cancellation));
}
finally
{
await File.WriteAllBytesAsync(path, saved, context.Cancellation);
}
// A policy this form cannot set, written out of range by another tool, is named so the admin can correct the file.
var current = Chronos.Core.Archiving.ManifestStore.ReadArchive(path);
foreach (var (odd, property) in new[]
{
(current with { ThumbnailPolicy = new Chronos.Core.Archiving.ThumbnailPolicy { LongEdge = 2048 } }, "thumbnailPolicy"),
(current with { ProxyPolicy = current.ProxyPolicy with { Quality = 0 } }, "proxyPolicy"),
})
{
Chronos.Core.Archiving.ManifestStore.WriteArchive(path, odd);
var before = await File.ReadAllBytesAsync(path, context.Cancellation);
using var refused = await admin.PutAsJsonAsync("/api/v1/archive/settings", changed with { ProxyLongEdge = 1280 }, ProtocolJson.Default.ArchiveSettingsDto);
Assert.Equal(property, (await refused.ExpectErrorAsync(HttpStatusCode.Conflict, "archive_policy")).Details);
Assert.SequenceEqual(before, await File.ReadAllBytesAsync(path, context.Cancellation));
}
await File.WriteAllBytesAsync(path, saved, context.Cancellation);
}
}
@@ -0,0 +1,70 @@
using System.IO.Compression;
using System.Net;
using System.Text.Json;
using Chronos.Core.Model;
using Chronos.Testing;
namespace Chronos.Server.Tests.Api;
[Category("server")]
public sealed class DiagnosticsTests(TestContext context)
{
private const string DbPassword = "db-secret-pw-42";
private const string ConnectionPassword = "correct horse, \"battery\" staple";
[Test]
public async Task TheBundleHoldsReportsLogsAndFailuresWithoutSecrets()
{
await using var server = await TestServer.StartAsync(context, o => o.DbPassword = DbPassword);
var admin = await server.AdminAsync();
// Only reported, never opened: the test server already runs on its own database.
server.Options.DbConnectionString = $"Host=db;Username=chronos;Password={ConnectionPassword};SslMode=prefer";
Directory.CreateDirectory(server.Options.LogPath);
await File.WriteAllTextAsync(Path.Combine(server.Options.LogPath, "chronos-server-test.log"),
$"connecting with Password={DbPassword}\nAuthorization: Bearer {TestServer.Password}\n");
var job = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Render, State = JobState.Queued, Created = DateTimeOffset.UtcNow };
await server.Database.Jobs.EnqueueAsync(job);
await server.Database.Jobs.SetStateAsync(job.Id, JobState.Failed, "rejected: token=" + DbPassword + " for db");
using var response = await admin.GetAsync("/api/v1/server/diagnostics");
await response.ExpectAsync(HttpStatusCode.OK);
Assert.Equal("application/zip", response.Content.Headers.ContentType?.MediaType);
await using var body = await response.Content.ReadAsStreamAsync();
using var zip = new ZipArchive(body, ZipArchiveMode.Read);
var texts = zip.Entries.ToDictionary(e => e.FullName, Read);
Assert.Contains("environment.txt", texts.Keys);
Assert.Contains("encoders.txt", texts.Keys);
Assert.Contains("logs/chronos-server-test.log", texts.Keys);
foreach (var (name, text) in texts)
{
Assert.False(text.Contains(DbPassword, StringComparison.Ordinal), $"{name} leaks the database password");
Assert.False(text.Contains(TestServer.AdminPassword, StringComparison.Ordinal), $"{name} leaks the admin password");
Assert.False(text.Contains(TestServer.Password, StringComparison.Ordinal), $"{name} leaks a user password");
Assert.False(text.Contains("horse", StringComparison.Ordinal) || text.Contains("staple", StringComparison.Ordinal), $"{name} leaks the connection-string password");
}
Assert.Contains("Chronos Server ", texts["environment.txt"]);
using (var settings = JsonDocument.Parse(texts["settings.json"]))
{
Assert.Equal("[removed]", settings.RootElement.GetProperty("DbPassword").GetString());
Assert.Equal("[removed]", settings.RootElement.GetProperty("AdminPassword").GetString());
Assert.Equal("Host=db;Username=chronos;Password=[removed];SslMode=prefer", settings.RootElement.GetProperty("DbConnectionString").GetString());
}
using (var failed = JsonDocument.Parse(texts["jobs-failed.json"]))
{
var entry = failed.RootElement.EnumerateArray().Single();
Assert.Equal(("Render", "rejected: token=[removed]"), (entry.GetProperty("kind").GetString(), entry.GetProperty("error").GetString()));
}
var (viewer, _, _) = await server.UserAsync("vera", "viewer");
using var refused = await viewer.GetAsync("/api/v1/server/diagnostics");
await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
Assert.NotEmpty((await server.Database.Audit.ListAsync(null, "server_diagnostics", 10, null)).Items);
}
private static string Read(ZipArchiveEntry entry)
{
using var reader = new StreamReader(entry.Open());
return reader.ReadToEnd();
}
}
@@ -0,0 +1,218 @@
using System.Net;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Archiving;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using Chronos.Testing;
namespace Chronos.Server.Tests.Api;
/// <summary>
/// What a desktop editor of a server sequence asks of the API (BRIEF §14.5 "edit with proxies, render where the
/// originals are"): the full analysis report, settings edits carrying their version and the hero frame, and the jobs
/// it posts and reads back.
/// </summary>
[Category("server")]
public sealed class RemoteEditingTests(TestContext context)
{
[Test]
public async Task TheAnalysisReportIsServedOnceTheSequenceWasAnalysed()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, token) = await server.UserAsync("alberto", "editor");
using var client = Client(server, token);
var frame = await Uploads.UploadAsync(editor, Uploads.Photo(2000, 41));
Assert.Null(await client.GetAnalysisReportAsync(frame.SequenceId, context.Cancellation), "never deep-analysed");
var sequence = (await server.Database.Sequences.GetAsync(frame.SequenceId))!;
var path = new ArchivePaths(server.Options.ArchivePath).Sequence(sequence.Folder).AnalysisPath;
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var report = Reports.Minimal(1).ToJson();
await File.WriteAllTextAsync(path, report, context.Cancellation);
Assert.Equal(report, await client.GetAnalysisReportAsync(frame.SequenceId, context.Cancellation));
// One made for other frames is not this sequence's report.
await File.WriteAllTextAsync(path, Reports.Minimal(2).ToJson(), context.Cancellation);
Assert.Null(await client.GetAnalysisReportAsync(frame.SequenceId, context.Cancellation), "another frame count");
var gone = await Assert.ThrowsAsync<ChronosApiException>(() => client.GetAnalysisReportAsync(Guid.CreateVersion7(), context.Cancellation));
Assert.Equal(HttpStatusCode.NotFound, gone.Status);
}
[Test]
public async Task AnEditCarriesItsVersionAndTheHeroFrame()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, token) = await server.UserAsync("alberto", "editor");
using var client = Client(server, token);
var first = await Uploads.UploadAsync(editor, Uploads.Photo(2000, 42), "a.CR3", sessionKey: "harbour");
var second = await Uploads.UploadAsync(editor, Uploads.Photo(2000, 43), "b.CR3", sessionKey: "harbour");
var foreign = await Uploads.UploadAsync(editor, Uploads.Photo(2000, 44), "c.CR3", sessionKey: "elsewhere");
var id = first.SequenceId;
Assert.Equal(id, second.SequenceId);
var read = await client.GetSequenceAsync(id, context.Cancellation);
var settings = new ProjectSettings { HeroFrame = second.Index }.ToJson();
var hero = await client.UpdateSequenceAsync(id, new UpdateSequenceRequest(null, null, null, null, settings, read.SettingsVersion, second.FrameId),
context.Cancellation);
Assert.Equal(second.FrameId, hero.HeroFrameId);
Assert.Equal(read.SettingsVersion + 1, hero.SettingsVersion);
// An edit made from an older version is refused and changes nothing (the editor merges and sends again).
var stale = await Assert.ThrowsAsync<ChronosApiException>(() =>
client.UpdateSequenceAsync(id, new UpdateSequenceRequest(null, null, null, null, settings, read.SettingsVersion, first.FrameId), context.Cancellation));
Assert.Equal(HttpStatusCode.Conflict, stale.Status);
Assert.Equal(second.FrameId, (await client.GetSequenceAsync(id, context.Cancellation)).HeroFrameId);
var other = await client.UpdateSequenceAsync(id, new UpdateSequenceRequest(null, null, null, null, null, hero.SettingsVersion, foreign.FrameId),
context.Cancellation);
Assert.Equal(second.FrameId, other.HeroFrameId, "a frame of another sequence is not its hero");
var cleared = await client.UpdateSequenceAsync(id, new UpdateSequenceRequest(null, null, null, null, null, other.SettingsVersion, Guid.Empty),
context.Cancellation);
Assert.Null(cleared.HeroFrameId);
}
[Test]
public async Task SettingsAloneMoveTheHeroFrameWithTheProjectsHero()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, token) = await server.UserAsync("alberto", "editor");
using var client = Client(server, token);
await Uploads.UploadAsync(editor, Uploads.Photo(2000, 46), "a.CR3", sessionKey: "pier");
var second = await Uploads.UploadAsync(editor, Uploads.Photo(2000, 47), "b.CR3", sessionKey: "pier");
var id = second.SequenceId;
var read = await client.GetSequenceAsync(id, context.Cancellation);
// The sync of a local copy sends the project only.
var project = new ProjectSettings { HeroFrame = second.Index };
var hero = await client.UpdateSequenceAsync(id, new UpdateSequenceRequest(null, null, null, null, project.ToJson(), read.SettingsVersion),
context.Cancellation);
Assert.Equal(second.FrameId, hero.HeroFrameId);
var exposure = project with { Exposure = project.Exposure with { ExposureOffsetEv = 0.3 } };
var kept = await client.UpdateSequenceAsync(id, new UpdateSequenceRequest(null, null, null, null, exposure.ToJson(), hero.SettingsVersion),
context.Cancellation);
Assert.Equal(second.FrameId, kept.HeroFrameId, "other changes keep the hero");
var cleared = await client.UpdateSequenceAsync(id, new UpdateSequenceRequest(null, null, null, null, (exposure with { HeroFrame = null }).ToJson(),
kept.SettingsVersion), context.Cancellation);
Assert.Null(cleared.HeroFrameId, "no hero shows the first frame");
}
[Test]
public async Task JobsPostedOnePerPresetReadBackAsTheClientsJobs()
{
var handler = new BlockingJobHandler(JobKind.DeepAnalyse);
await using var server = await TestServer.StartAsync(context, services: s => s.AddSingleton<IJobHandler>(handler));
var (editor, _, token) = await server.UserAsync("alberto", "editor");
using var client = Client(server, token);
var frame = await Uploads.UploadAsync(editor, Uploads.Photo(2000, 45));
var dto = await client.GetSequenceAsync(frame.SequenceId, context.Cancellation);
var sequence = new Sequence { Id = dto.Id, ArchiveId = Guid.Empty, Folder = dto.Folder, Title = dto.Title };
var export = new ExportSettings { Preset = new Auto<string>().WithManual("4k-hevc"), Batch = ["1440p-h264"] };
var posted = new List<Job>();
foreach (var request in ProcessingJobs.RenderEach(sequence, export, 3840, 2160, new ProjectSettings { Export = export }))
{
var job = await client.CreateJobAsync(new CreateJobRequest(JobWire.Kind(request.Kind), request.Targets, request.ParametersJson), context.Cancellation);
posted.Add(Assert.NotNull(JobWire.FromDto(job)));
}
Assert.Count(2, posted);
Assert.True(posted.All(j => j is { Kind: JobKind.Render, State: JobState.Queued } && j.TargetIds.SequenceEqual([sequence.Id])));
var analysis = Assert.NotNull(JobWire.FromDto(await client.CreateJobAsync(
new CreateJobRequest(JobWire.Kind(JobKind.DeepAnalyse), [sequence.Id], null), context.Cancellation)));
Assert.Equal(JobKind.DeepAnalyse, analysis.Kind);
await handler.Started.Task.WaitAsync(TimeSpan.FromSeconds(10));
handler.Release();
for (var i = 0; i < 200 && JobWire.FromDto(await client.GetJobAsync(analysis.Id, context.Cancellation))!.State != JobState.Done; i++)
await Task.Delay(50);
var done = Assert.NotNull(JobWire.FromDto(await client.GetJobAsync(analysis.Id, context.Cancellation)));
Assert.Equal(JobState.Done, done.State);
Assert.Equal((4L, 4L), (done.ProgressDone, done.ProgressTotal));
Assert.NotNull(done.Finished);
var queued = (await client.ListJobsAsync("queued", null, context.Cancellation)).Items.Select(JobWire.FromDto).OfType<Job>().ToList();
Assert.SequenceEqual(posted.Select(j => j.Id).Order(), queued.Where(j => j.Kind == JobKind.Render).Select(j => j.Id).Order());
}
[Test]
public async Task TheJobListFiltersByKindAndGoesOnPastThePage()
{
await using var server = await TestServer.StartAsync(context);
var (_, _, token) = await server.UserAsync("alberto", "editor");
using var client = Client(server, token);
var target = Guid.CreateVersion7();
var created = DateTimeOffset.UtcNow;
// Paused, so no worker claims them: a render of the editor's sequence behind a busy server's thumbnails.
Job Paused(JobKind kind, int age) => new()
{
Id = Guid.CreateVersion7(),
Kind = kind,
TargetIds = [target],
State = JobState.Paused,
Created = created.AddSeconds(-age),
};
var render = Paused(JobKind.Render, 300);
await server.Database.Jobs.EnqueueAsync(render);
for (var i = 0; i < 205; i++) await server.Database.Jobs.EnqueueAsync(Paused(JobKind.Thumbs, i));
var renders = await client.ListJobsAsync("paused", "render", null, context.Cancellation);
Assert.SequenceEqual([render.Id], renders.Items.Select(j => j.Id));
Assert.Null(renders.NextCursor);
var first = await client.ListJobsAsync("paused", null, null, context.Cancellation);
Assert.NotNull(first.NextCursor, "more than a page");
Assert.False(first.Items.Any(j => j.Id == render.Id), "the oldest job is past the first page");
var rest = await client.ListJobsAsync("paused", null, first.NextCursor, context.Cancellation);
Assert.Null(rest.NextCursor);
Assert.Equal(206, first.Items.Concat(rest.Items).Select(j => j.Id).Distinct().Count());
}
[Test]
public async Task AnEditorHearsFramesAddedAndSettingsChangedOverItsEventSocket()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, token) = await server.UserAsync("alberto", "editor");
using var client = Client(server, token);
var first = await Uploads.UploadAsync(editor, Uploads.Photo(2000, 48), "a.CR3", sessionKey: "quay");
var id = first.SequenceId;
var opened = await client.GetManifestAsync(id, context.Cancellation);
using var listening = CancellationTokenSource.CreateLinkedTokenSource(context.Cancellation);
listening.CancelAfter(TimeSpan.FromSeconds(20));
var received = new List<SequenceChangedEvent>();
var reader = Task.Run(async () =>
{
await foreach (var e in client.EventsAsync(listening.Token))
{
if (e is not SequenceChangedEvent changed || changed.SequenceId != id) continue;
received.Add(changed);
if (changed.Change == "settings") return;
}
});
var hub = server.Services.GetRequiredService<Chronos.Server.Events.EventHub>();
for (var i = 0; i < 200 && hub.SubscriberCount == 0; i++) await Task.Delay(25);
// Someone uploads another frame, then someone edits the project: the editor checks its frames, then its settings.
await Uploads.UploadAsync(editor, Uploads.Photo(2000, 49), "b.CR3", sessionKey: "quay");
var read = await client.GetSequenceAsync(id, context.Cancellation);
await client.UpdateSequenceAsync(id, new UpdateSequenceRequest(null, null, null, null, new ProjectSettings { HeroFrame = 1 }.ToJson(), read.SettingsVersion),
context.Cancellation);
await reader.WaitAsync(TimeSpan.FromSeconds(20));
var now = await client.GetManifestAsync(id, context.Cancellation);
var frames = Assert.Contains(received, e => e.Change == "frames");
Assert.Equal(now.FramesVersion, frames.FramesVersion);
Assert.True(frames.FramesVersion > opened.FramesVersion, "a frames version the editor has not seen");
Assert.Count(2, now.Frames);
Assert.Equal(("settings", now.SettingsVersion), (received[^1].Change, received[^1].SettingsVersion));
}
private static ChronosClient Client(TestServer server, string token) => new(server.HttpBase, new CertificatePinning([]), "tests") { Token = token };
}
@@ -0,0 +1,349 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using Chronos.Data;
using Chronos.Protocol;
using Chronos.Server.Api;
using Chronos.Testing;
namespace Chronos.Server.Tests.Api;
[Category("server")]
public sealed class SequenceTests(TestContext context)
{
[Test]
public async Task ConcurrentSettingsEditsConflict()
{
await using var server = await TestServer.StartAsync(context);
var (alberto, _, _) = await server.UserAsync("alberto", "editor");
var (giulia, _, _) = await server.UserAsync("giulia", "editor");
using var created = await alberto.PostAsJsonAsync("/api/v1/sequences", new CreateSequenceRequest("Harbour sunset", null), ProtocolJson.Default.CreateSequenceRequest);
await created.ExpectAsync(HttpStatusCode.Created);
var sequence = await created.ReadAsync(ProtocolJson.Default.SequenceDto);
Assert.Equal(0, sequence.SettingsVersion);
using (var first = await alberto.PatchAsJsonAsync($"/api/v1/sequences/{sequence.Id}",
new UpdateSequenceRequest(null, ["sunset", "harbour"], 4, null, """{"deflicker":{"strength":0.8}}""", 0), ProtocolJson.Default.UpdateSequenceRequest))
{
await first.ExpectAsync(HttpStatusCode.OK);
var updated = await first.ReadAsync(ProtocolJson.Default.SequenceDto);
Assert.Equal(1, updated.SettingsVersion);
Assert.SequenceEqual(["harbour", "sunset"], updated.Tags);
Assert.Equal(4, updated.Rating);
}
using (var stale = await giulia.PatchAsJsonAsync($"/api/v1/sequences/{sequence.Id}",
new UpdateSequenceRequest(null, null, null, null, """{"deflicker":{"strength":0.2}}""", 0), ProtocolJson.Default.UpdateSequenceRequest))
{
var error = await stale.ExpectErrorAsync(HttpStatusCode.Conflict, "settings_conflict");
Assert.Equal("1", error.Details);
}
// The ETag of a fresh read works as If-Match.
using var read = await giulia.GetAsync($"/api/v1/sequences/{sequence.Id}");
var etag = Assert.NotNull(read.Headers.ETag);
using var request = new HttpRequestMessage(HttpMethod.Patch, $"/api/v1/sequences/{sequence.Id}")
{
Content = JsonContent.Create(new UpdateSequenceRequest(null, null, null, null, """{"deflicker":{"strength":0.2}}""", null), ProtocolJson.Default.UpdateSequenceRequest),
};
request.Headers.IfMatch.Add(etag);
using (var retried = await giulia.SendAsync(request))
{
await retried.ExpectAsync(HttpStatusCode.OK);
Assert.Equal(2, (await retried.ReadAsync(ProtocolJson.Default.SequenceDto)).SettingsVersion);
}
using var notModified = new HttpRequestMessage(HttpMethod.Get, $"/api/v1/sequences/{sequence.Id}");
notModified.Headers.IfNoneMatch.Add(etag);
using (var changed = await giulia.SendAsync(notModified)) await changed.ExpectAsync(HttpStatusCode.OK);
using var invalid = await giulia.PatchAsJsonAsync($"/api/v1/sequences/{sequence.Id}",
new UpdateSequenceRequest(null, null, null, null, "{ broken", null), ProtocolJson.Default.UpdateSequenceRequest);
await invalid.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_settings");
}
[Test]
public async Task SettingsWrittenAgainstFramesThatChangedAreRefused()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var first = await Uploads.UploadAsync(editor, Uploads.Photo(2000, 41), "a.CR3", sessionKey: "k");
using var read = await editor.GetAsync($"/api/v1/sequences/{first.SequenceId}");
var sequence = await read.ReadAsync(ProtocolJson.Default.SequenceDto);
// Another photo arrives after this client read the frames its positions name.
await Uploads.UploadAsync(editor, Uploads.Photo(2000, 42), "b.CR3", sessionKey: "k");
using (var stale = await editor.PatchAsJsonAsync($"/api/v1/sequences/{sequence.Id}",
new UpdateSequenceRequest(null, null, null, null, """{"excludedFrames":[0]}""", sequence.SettingsVersion, ExpectedFramesVersion: sequence.FramesVersion),
ProtocolJson.Default.UpdateSequenceRequest))
{
var error = await stale.ExpectErrorAsync(HttpStatusCode.Conflict, "frames_conflict");
Assert.Equal((sequence.FramesVersion + 1).ToString(System.Globalization.CultureInfo.InvariantCulture), error.Details);
}
using var fresh = await editor.PatchAsJsonAsync($"/api/v1/sequences/{sequence.Id}",
new UpdateSequenceRequest(null, null, null, null, """{"excludedFrames":[1]}""", sequence.SettingsVersion, ExpectedFramesVersion: sequence.FramesVersion + 1),
ProtocolJson.Default.UpdateSequenceRequest);
await fresh.ExpectAsync(HttpStatusCode.OK);
Assert.Equal(sequence.SettingsVersion + 1, (await fresh.ReadAsync(ProtocolJson.Default.SequenceDto)).SettingsVersion);
}
[Test]
public async Task TheManifestCarriesHashesAndAnEtag()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var a = Uploads.Photo(2000, 31);
var b = Uploads.Photo(2000, 32);
var first = await Uploads.UploadAsync(editor, a, "a.CR3", sessionKey: "k");
await Uploads.UploadAsync(editor, b, "b.CR3", sessionKey: "k");
using var response = await editor.GetAsync($"/api/v1/sequences/{first.SequenceId}/manifest");
await response.ExpectAsync(HttpStatusCode.OK);
var manifest = await response.ReadAsync(ProtocolJson.Default.SequenceManifest);
Assert.SequenceEqual([Uploads.Sha(a), Uploads.Sha(b)], manifest.Frames.Select(f => f.Sha256));
Assert.Equal(2, manifest.FramesVersion);
using var cached = new HttpRequestMessage(HttpMethod.Get, $"/api/v1/sequences/{first.SequenceId}/manifest");
cached.Headers.IfNoneMatch.Add(response.Headers.ETag!);
using (var unchanged = await editor.SendAsync(cached)) await unchanged.ExpectAsync(HttpStatusCode.NotModified);
await Uploads.UploadAsync(editor, Uploads.Photo(2000, 33), "c.CR3", sessionKey: "k");
using var again = new HttpRequestMessage(HttpMethod.Get, $"/api/v1/sequences/{first.SequenceId}/manifest");
again.Headers.IfNoneMatch.Add(response.Headers.ETag!);
using var changed = await editor.SendAsync(again);
await changed.ExpectAsync(HttpStatusCode.OK);
Assert.Count(3, (await changed.ReadAsync(ProtocolJson.Default.SequenceManifest)).Frames);
}
[Test]
public async Task TheManifestListsTheFramesOfOneFramesVersion()
{
await using var server = await TestServer.StartAsync(context);
await FramesOfOneVersionAsync(server);
}
/// <summary>The manifest's frames are read again while frames are committed, then under the row lock (also run on PostgreSQL).</summary>
internal static async Task FramesOfOneVersionAsync(TestServer server)
{
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var first = await Uploads.UploadAsync(editor, Uploads.Photo(2000, 51), "a.CR3", sessionKey: "k");
var db = server.Database;
var id = first.SequenceId;
var start = (await db.Sequences.GetAsync(id))!.FramesVersion;
// Frames are committed while the first listing is read: it is read again.
var listings = new List<int>();
var snapshot = await SequenceEndpoints.SnapshotAsync(db, id, async (_, sequence, ct) =>
{
listings.Add(sequence.FramesVersion);
if (listings.Count == 1) await db.Sequences.RefreshStatsAsync(id, ct);
return [];
}, CancellationToken.None);
Assert.SequenceEqual([start, start + 1], listings);
Assert.Equal(start + 1, Assert.NotNull(snapshot).Sequence.FramesVersion);
// Commits keep landing: the last listing is read while none can.
Task? waiting = null;
listings.Clear();
var locked = await SequenceEndpoints.SnapshotAsync(db, id, async (on, sequence, ct) =>
{
listings.Add(sequence.FramesVersion);
if (listings.Count <= 3)
{
await db.Sequences.RefreshStatsAsync(id, ct);
return [];
}
// Listed on the transaction that holds the row (on SQLite, the only connection that may while it writes).
Assert.True(on is ChronosTransaction, "the frames are listed inside the locking transaction");
Assert.Count(1, await on.Frames.ListBySequenceAsync(id, cancellationToken: ct));
waiting = db.Sequences.RefreshStatsAsync(id, ct);
await Task.WhenAny(waiting, Task.Delay(300, ct));
Assert.False(waiting.IsCompleted, "a commit of frames waits until the frames are listed");
return [];
}, CancellationToken.None);
await Assert.NotNull(waiting);
Assert.SequenceEqual([start + 1, start + 2, start + 3, start + 4], listings);
Assert.Equal(start + 4, Assert.NotNull(locked).Sequence.FramesVersion);
Assert.Equal(start + 5, (await db.Sequences.GetAsync(id))!.FramesVersion);
Assert.Null(await SequenceEndpoints.SnapshotAsync(db, Guid.NewGuid(), (_, _, _) => Task.FromResult(new List<ManifestFrame>()), CancellationToken.None));
}
[Test]
public async Task ListingFiltersAndPagesWithACursor()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
for (var i = 0; i < 5; i++)
{
using var created = await editor.PostAsJsonAsync("/api/v1/sequences", new CreateSequenceRequest($"Shoot {i}", null), ProtocolJson.Default.CreateSequenceRequest);
await created.ExpectAsync(HttpStatusCode.Created);
}
var seen = new List<string>();
string? cursor = null;
long? total = null;
do
{
using var page = await editor.GetAsync($"/api/v1/sequences?sort=title&limit=2{(cursor is null ? string.Empty : "&cursor=" + Uri.EscapeDataString(cursor))}");
await page.ExpectAsync(HttpStatusCode.OK);
var items = await page.ReadAsync(ProtocolJson.Default.PageSequenceDto);
total ??= items.Total;
seen.AddRange(items.Items.Select(s => s.DisplayTitle));
cursor = items.NextCursor;
}
while (cursor is not null);
Assert.Equal(5L, total);
Assert.SequenceEqual(["Shoot 0", "Shoot 1", "Shoot 2", "Shoot 3", "Shoot 4"], seen);
using (var search = await editor.GetAsync("/api/v1/sequences?q=shoot%203")) Assert.Count(1, (await search.ReadAsync(ProtocolJson.Default.PageSequenceDto)).Items);
using (var badCursor = await editor.GetAsync("/api/v1/sequences?cursor=bm9wZQ")) await badCursor.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_cursor");
using var badStatus = await editor.GetAsync("/api/v1/sequences?status=shiny");
await badStatus.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_filter");
}
[Test]
public async Task DeletingPlansFirstAndMovesTheFolderToTrash()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var (other, _, _) = await server.UserAsync("giulia", "editor");
var frame = await Uploads.UploadAsync(editor, Uploads.Photo(3000, 34));
var sequence = (await server.Database.Sequences.GetAsync(frame.SequenceId))!;
var folder = Path.Combine(server.Options.ArchivePath, sequence.Folder);
using (var notOwner = await other.DeleteAsync($"/api/v1/sequences/{sequence.Id}")) await notOwner.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var plan = await editor.DeleteAsync($"/api/v1/sequences/{sequence.Id}?dryRun=true"))
{
var dryRun = await plan.ReadAsync(ProtocolJson.Default.SequenceDeletePlan);
Assert.True(dryRun.DryRun);
Assert.Equal(1, dryRun.FrameCount);
Assert.Equal($".chronos/trash/{sequence.Id:N}", dryRun.TrashFolder);
}
Assert.True(Directory.Exists(folder), "a dry run changes nothing");
Assert.NotNull(await server.Database.Sequences.GetAsync(sequence.Id));
using (var deleted = await editor.DeleteAsync($"/api/v1/sequences/{sequence.Id}")) await deleted.ExpectAsync(HttpStatusCode.OK);
Assert.False(Directory.Exists(folder));
Assert.True(Directory.Exists(Path.Combine(server.Options.TrashPath, sequence.Id.ToString("N"))), "the files are kept in the trash");
Assert.Null(await server.Database.Sequences.GetAsync(sequence.Id));
using var gone = await editor.GetAsync($"/api/v1/sequences/{sequence.Id}");
await gone.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
}
[Test]
public async Task ASequenceAJobWorksOnIsNotDeleted()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var frame = await Uploads.UploadAsync(editor, Uploads.Photo(3000, 35));
var sequence = (await server.Database.Sequences.GetAsync(frame.SequenceId))!;
await server.Database.Jobs.EnqueueAsync(new Chronos.Core.Model.Job
{
Id = Guid.CreateVersion7(),
Kind = Chronos.Core.Model.JobKind.Render,
TargetIds = [sequence.Id],
State = Chronos.Core.Model.JobState.Running,
NodeId = "node#0",
Created = DateTimeOffset.UtcNow,
Started = DateTimeOffset.UtcNow,
});
using (var plan = await editor.DeleteAsync($"/api/v1/sequences/{sequence.Id}?dryRun=true")) await plan.ExpectErrorAsync(HttpStatusCode.Conflict, "sequence_busy");
using (var deleted = await editor.DeleteAsync($"/api/v1/sequences/{sequence.Id}")) await deleted.ExpectErrorAsync(HttpStatusCode.Conflict, "sequence_busy");
Assert.True(Directory.Exists(Path.Combine(server.Options.ArchivePath, sequence.Folder)));
Assert.NotNull(await server.Database.Sequences.GetAsync(sequence.Id));
}
[Test]
public async Task ADeleteThatCannotMoveSaysWhy()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var a = (await server.Database.Sequences.GetAsync((await Uploads.UploadAsync(editor, Uploads.Photo(3000, 36), "a.jpg", sessionKey: "a")).SequenceId))!;
var b = (await server.Database.Sequences.GetAsync((await Uploads.UploadAsync(editor, Uploads.Photo(3000, 37), "b.jpg", sessionKey: "b")).SequenceId))!;
Assert.NotEqual(a.Folder, b.Folder);
var archive = new Chronos.Core.Archiving.ArchivePaths(server.Options.ArchivePath);
// The folder of b now holds a sidecar naming another sequence (copied over by hand): the index is out of date.
var sidecar = archive.Sequence(b.Folder).ManifestPath;
Directory.CreateDirectory(Path.GetDirectoryName(sidecar)!);
File.WriteAllText(sidecar, $$"""{"schemaVersion":1,"id":"{{a.Id}}"}""");
await RefusedAsync(editor, b.Id, "sidecar_mismatch");
Directory.Delete(archive.Sequence(a.Folder).Folder, recursive: true);
await RefusedAsync(editor, a.Id, "folder_missing");
Assert.NotNull(await server.Database.Sequences.GetAsync(a.Id));
Assert.NotNull(await server.Database.Sequences.GetAsync(b.Id));
// A sequence still waiting for its first photo has no folder: only its row goes.
using var created = await editor.PostAsJsonAsync("/api/v1/sequences", new CreateSequenceRequest("Waiting", null), ProtocolJson.Default.CreateSequenceRequest);
var empty = await created.ReadAsync(ProtocolJson.Default.SequenceDto);
using (var deleted = await editor.DeleteAsync($"/api/v1/sequences/{empty.Id}")) Assert.Null((await deleted.ReadAsync(ProtocolJson.Default.SequenceDeletePlan)).TrashFolder);
Assert.Null(await server.Database.Sequences.GetAsync(empty.Id));
static async Task RefusedAsync(HttpClient client, Guid id, string code)
{
using var response = await client.DeleteAsync($"/api/v1/sequences/{id}");
var error = await response.ExpectErrorAsync(HttpStatusCode.Conflict, code);
Assert.NotEqual(code, error.Message, "the code has a sentence");
}
}
[Test]
public async Task FramesAndStatsArePaged()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var first = await Uploads.UploadAsync(editor, Uploads.Photo(1000, 40), "f0.jpg", sessionKey: "p");
for (var i = 1; i < 4; i++) await Uploads.UploadAsync(editor, Uploads.Photo(1000 + i, 40 + i), $"f{i}.jpg", sessionKey: "p");
var id = first.SequenceId;
using var page1 = await editor.GetAsync($"/api/v1/sequences/{id}/frames?limit=2");
var frames = await page1.ReadAsync(ProtocolJson.Default.PageFrameDto);
Assert.SequenceEqual([0, 1], frames.Items.Select(f => f.Index));
using var page2 = await editor.GetAsync($"/api/v1/sequences/{id}/frames?limit=2&cursor={Uri.EscapeDataString(frames.NextCursor!)}");
Assert.SequenceEqual([2, 3], (await page2.ReadAsync(ProtocolJson.Default.PageFrameDto)).Items.Select(f => f.Index));
using var stats = await editor.GetAsync($"/api/v1/sequences/{id}/stats");
var dto = await stats.ReadAsync(ProtocolJson.Default.SequenceStatsDto);
Assert.Equal(4, dto.FrameCount);
Assert.Equal(4L, dto.ByFormat.Sum(f => f.Count));
using var analysis = await editor.GetAsync($"/api/v1/sequences/{id}/analysis");
Assert.Equal("analysis", (await analysis.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found")).Details);
}
[Test]
public async Task CardsAndFramesCarryTheDecodeTierFields()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var first = await Uploads.UploadAsync(editor, Uploads.Photo(1000, 50), "t0.CR3", sessionKey: "t");
await Uploads.UploadAsync(editor, Uploads.Photo(1001, 51), "t1.CR3", sessionKey: "t");
var db = server.Database;
// The follow-up jobs of the upload (thumbnails, proxies, light analysis) rewrite the rows: let them finish first.
for (var waited = 0; waited < 600; waited++)
{
if ((await db.Jobs.ListAsync(Chronos.Core.Model.JobState.Queued)).Items.Count == 0
&& (await db.Jobs.ListAsync(Chronos.Core.Model.JobState.Running)).Items.Count == 0) break;
await Task.Delay(50, context.Cancellation);
}
// What a light analysis on the server records for CR3s it reads only through their previews.
var frames = await db.Frames.ListBySequenceAsync(first.SequenceId);
await db.Frames.UpdateTiersAsync([.. frames.Select(f => new Chronos.Data.Repositories.FrameTierFields(f.Id, Chronos.Core.Model.FrameFlags.PreviewOnly, 1620, 1080, f.Format))]);
var sequence = (await db.Sequences.GetAsync(first.SequenceId))!;
await db.Sequences.UpsertAsync(sequence with { PreviewOnlyCount = 2 });
// The Library cards read the count (the chip), the remote editor the preview size (the output cap).
using var list = await editor.GetAsync("/api/v1/sequences");
await list.ExpectAsync(HttpStatusCode.OK);
Assert.Contains("\"previewOnlyCount\":2", await list.Content.ReadAsStringAsync());
using var listed = await editor.GetAsync("/api/v1/sequences");
Assert.Equal(2, (await listed.ReadAsync(ProtocolJson.Default.PageSequenceDto)).Items.Single(s => s.Id == first.SequenceId).PreviewOnlyCount);
using var page = await editor.GetAsync($"/api/v1/sequences/{first.SequenceId}/frames");
await page.ExpectAsync(HttpStatusCode.OK);
var json = await page.Content.ReadAsStringAsync();
Assert.Contains("\"previewWidth\":1620", json);
Assert.Contains("\"previewHeight\":1080", json);
using var typed = await editor.GetAsync($"/api/v1/sequences/{first.SequenceId}/frames");
var dtos = (await typed.ReadAsync(ProtocolJson.Default.PageFrameDto)).Items;
Assert.True(dtos.All(f => (f.PreviewWidth, f.PreviewHeight, f.Flags) == (1620, 1080, (long)Chronos.Core.Model.FrameFlags.PreviewOnly)), "frame DTOs");
}
}
+103
View File
@@ -0,0 +1,103 @@
using System.Net;
using System.Net.Http.Json;
using Chronos.Core.Model;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Server.Tests.Api;
[Category("server")]
public sealed class UserTests(TestContext context)
{
[Test]
public async Task AdminsManageAccountsAndTemporaryPasswords()
{
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
using var created = await admin.PostAsJsonAsync("/api/v1/users", new CreateUserRequest("lucia", "Lucia", "editor", 2_000_000_000_000, null, AllowRenderNode: false),
ProtocolJson.Default.CreateUserRequest);
await created.ExpectAsync(HttpStatusCode.Created);
var account = await created.ReadAsync(ProtocolJson.Default.TemporaryPasswordResponse);
Assert.True(account.User.MustChangePassword);
Assert.Equal(14, account.TemporaryPassword.Length);
Assert.Equal(0L, account.User.Permissions & (long)Permissions.RenderNode);
using (var taken = await admin.PostAsJsonAsync("/api/v1/users", new CreateUserRequest("LUCIA", null, "viewer", 0, null, false), ProtocolJson.Default.CreateUserRequest))
await taken.ExpectErrorAsync(HttpStatusCode.Conflict, "username_taken");
using (var badName = await admin.PostAsJsonAsync("/api/v1/users", new CreateUserRequest("lu cia", null, "viewer", 0, null, false), ProtocolJson.Default.CreateUserRequest))
await badName.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_username");
using (var badRole = await admin.PostAsJsonAsync("/api/v1/users", new CreateUserRequest("lucio", null, "owner", 0, null, false), ProtocolJson.Default.CreateUserRequest))
await badRole.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_role");
using (var promoted = await admin.PatchAsJsonAsync($"/api/v1/users/{account.User.Id}", new UpdateUserRequest(null, "uploader", 5, null, true), ProtocolJson.Default.UpdateUserRequest))
{
var user = await promoted.ReadAsync(ProtocolJson.Default.UserDto);
Assert.Equal(("uploader", 5L), (user.Role, user.QuotaBytes));
Assert.Equal((long)(RolePermissions.Default(UserRole.Uploader) | Permissions.RenderNode), user.Permissions);
}
using var reset = await admin.PostAsJsonAsync($"/api/v1/users/{account.User.Id}/reset-password", new ResetPasswordRequest(null), ProtocolJson.Default.ResetPasswordRequest);
var temporary = await reset.ReadAsync(ProtocolJson.Default.TemporaryPasswordResponse);
var login = await server.LoginAsync("lucia", temporary.TemporaryPassword);
Assert.True(login.MustChangePassword);
using var list = await admin.GetAsync("/api/v1/users");
var rows = await list.ReadAsync(ProtocolJson.Default.ListUserSummaryDto);
var lucia = rows.Single(r => r.User.Username == "lucia");
Assert.Equal("tests", lucia.LastClient);
Assert.NotNull(lucia.LastSeen);
}
[Test]
public async Task TheLastAdministratorStays()
{
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
using var me = await admin.GetAsync("/api/v1/auth/me");
var self = await me.ReadAsync(ProtocolJson.Default.UserDto);
using (var demote = await admin.PatchAsJsonAsync($"/api/v1/users/{self.Id}", new UpdateUserRequest(null, "editor", null, null, null), ProtocolJson.Default.UpdateUserRequest))
await demote.ExpectErrorAsync(HttpStatusCode.Conflict, "self");
using (var delete = await admin.DeleteAsync($"/api/v1/users/{self.Id}")) await delete.ExpectErrorAsync(HttpStatusCode.Conflict, "self");
}
[Test]
public async Task ResettingOnesOwnPasswordIsRefusedAndTheSessionSurvives()
{
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
using var me = await admin.GetAsync("/api/v1/auth/me");
var self = await me.ReadAsync(ProtocolJson.Default.UserDto);
using (var reset = await admin.PostAsJsonAsync($"/api/v1/users/{self.Id}/reset-password", new ResetPasswordRequest(null), ProtocolJson.Default.ResetPasswordRequest))
await reset.ExpectErrorAsync(HttpStatusCode.Conflict, "self");
using var still = await admin.GetAsync("/api/v1/auth/me");
Assert.False((await still.ReadAsync(ProtocolJson.Default.UserDto)).MustChangePassword);
}
[Test]
public async Task TheSignInLogListsFailedAttemptsToo()
{
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
using (var wrong = await server.Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", "not-the-password", "tests"), ProtocolJson.Default.LoginRequest))
Assert.Equal(HttpStatusCode.Unauthorized, wrong.StatusCode);
using var log = await admin.GetAsync("/api/v1/audit?action=login,login_failed");
var actions = (await log.ReadAsync(ProtocolJson.Default.PageAuditEntryDto)).Items.Select(e => e.Action).ToHashSet();
Assert.True(actions.SetEquals(["login", "login_failed"]), string.Join(",", actions));
}
[Test]
public async Task DeletingAUserHandsTheirSequencesToTheAdmin()
{
await using var server = await TestServer.StartAsync(context);
var (editor, user, _) = await server.UserAsync("simone", "editor");
using var created = await editor.PostAsJsonAsync("/api/v1/sequences", new CreateSequenceRequest("Comet", null), ProtocolJson.Default.CreateSequenceRequest);
var sequence = await created.ReadAsync(ProtocolJson.Default.SequenceDto);
var admin = await server.AdminAsync();
using (var deleted = await admin.DeleteAsync($"/api/v1/users/{user.Id}")) await deleted.ExpectAsync(HttpStatusCode.NoContent);
using var me = await admin.GetAsync("/api/v1/auth/me");
var adminId = (await me.ReadAsync(ProtocolJson.Default.UserDto)).Id;
Assert.Equal(adminId, (await server.Database.Sequences.GetAsync(sequence.Id))!.OwnerUserId);
using var audit = await admin.GetAsync("/api/v1/audit?action=user_deleted");
Assert.Count(1, (await audit.ReadAsync(ProtocolJson.Default.PageAuditEntryDto)).Items);
}
}
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>Chronos.Server.Tests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<ProjectReference Include="..\Chronos.Testing\Chronos.Testing.csproj" />
<ProjectReference Include="..\..\src\Chronos.Server\Chronos.Server.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,197 @@
using System.Net;
using System.Net.Http.Json;
using System.Net.WebSockets;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using Chronos.Server.Tests.Jobs;
using Chronos.Testing;
namespace Chronos.Server.Tests.Events;
[Category("server")]
public sealed class EventTests(TestContext context)
{
[Test]
public async Task AWebSocketClientReceivesJobProgressAndStates()
{
var handler = new BlockingJobHandler(JobKind.DeepAnalyse);
await using var server = await TestServer.StartAsync(context, services: s => s.AddSingleton<IJobHandler>(handler));
var (editor, _, token) = await server.UserAsync("alberto", "editor");
var sequence = await JobApiTests.CreateSequenceAsync(editor);
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "tests") { Token = token };
using var listening = CancellationTokenSource.CreateLinkedTokenSource(context.Cancellation);
listening.CancelAfter(TimeSpan.FromSeconds(20));
var received = new List<ServerEvent>();
var connected = new TaskCompletionSource();
var reader = Task.Run(async () =>
{
var events = client.EventsAsync(listening.Token).GetAsyncEnumerator(listening.Token);
var first = events.MoveNextAsync();
connected.TrySetResult();
try
{
if (!await first) return;
do
{
received.Add(events.Current);
if (events.Current is JobStateEvent { State: "done" }) return;
}
while (await events.MoveNextAsync());
}
finally
{
await events.DisposeAsync();
}
});
await connected.Task;
await WaitForSubscriberAsync(server);
var job = await JobApiTests.CreateAsync(editor, "deep-analyse", sequence);
await handler.Started.Task.WaitAsync(TimeSpan.FromSeconds(10));
handler.Release();
await reader.WaitAsync(TimeSpan.FromSeconds(20));
Assert.Contains(received, e => e is JobProgressEvent p && p.JobId == job.Id && p.Total == 4);
Assert.Contains(received, e => e is JobStateEvent { State: "running" } s && s.JobId == job.Id);
Assert.Contains(received, e => e is JobStateEvent { State: "done" } s && s.JobId == job.Id);
}
[Test]
public async Task TheEventSocketNeedsAValidToken()
{
await using var server = await TestServer.StartAsync(context);
var ws = new UriBuilder(new Uri(server.HttpBase, "/api/v1/events")) { Scheme = "ws" }.Uri;
using (var anonymous = new ClientWebSocket())
{
var error = await Assert.ThrowsAsync<WebSocketException>(() => anonymous.ConnectAsync(ws, context.Cancellation));
Assert.Contains("401", error.Message);
}
var admin = await server.AdminAsync();
using var plain = await admin.GetAsync("/api/v1/events");
await plain.ExpectErrorAsync(HttpStatusCode.BadRequest, "websocket_required");
}
[Test]
public async Task ACardImportReportedByOneClientReachesTheOthersAsCardEvents()
{
await using var server = await TestServer.StartAsync(context);
var (uploaderHttp, _, uploaderToken) = await server.UserAsync("studio-pc", "uploader");
var (_, _, editorToken) = await server.UserAsync("alberto", "editor");
using var listener = new ChronosClient(server.HttpBase, new CertificatePinning([]), "laptop") { Token = editorToken };
using var listening = CancellationTokenSource.CreateLinkedTokenSource(context.Cancellation);
listening.CancelAfter(TimeSpan.FromSeconds(20));
var received = new List<CardEvent>();
var connected = new TaskCompletionSource();
var reader = Task.Run(async () =>
{
var events = listener.EventsAsync(listening.Token).GetAsyncEnumerator(listening.Token);
var first = events.MoveNextAsync();
connected.TrySetResult();
try
{
if (!await first) return;
do
{
if (events.Current is CardEvent card) received.Add(card);
if (events.Current is CardEvent { State: CardImportStates.Finished }) return;
}
while (await events.MoveNextAsync());
}
finally
{
await events.DisposeAsync();
}
});
await connected.Task;
await WaitForSubscriberAsync(server);
// The importing client (an upload-only account is enough) reports through the protocol client.
using var importer = new ChronosClient(server.HttpBase, new CertificatePinning([]), "Chronos (STUDIO)") { Token = uploaderToken };
var importId = Guid.CreateVersion7();
await importer.ReportCardAsync(new CardImportReport(importId, "EOS R5 · card A", CardImportStates.Started, 0, 120, 0), context.Cancellation);
await importer.ReportCardAsync(new CardImportReport(importId, "EOS R5 · card A", CardImportStates.Progress, 60, 120, 1), context.Cancellation);
await importer.ReportCardAsync(new CardImportReport(importId, "EOS R5 · card A", CardImportStates.Finished, 120, 120, 2), context.Cancellation);
await reader.WaitAsync(TimeSpan.FromSeconds(20));
Assert.SequenceEqual([CardImportStates.Started, CardImportStates.Progress, CardImportStates.Finished], received.Select(e => e.State));
Assert.True(received.All(e => e.ImportId == importId && e.Card == "EOS R5 · card A" && e.Total == 120), "every event names the import");
Assert.Equal((60, 1), (received[1].Done, received[1].Failed));
// Who imports: the account and the client name it signed in with.
Assert.Equal(("studio-pc", "tests"), (received[2].User, received[2].ClientName));
// Reports are checked like any request.
foreach (var (report, field) in new[]
{
(new CardImportReport(Guid.Empty, "card", CardImportStates.Started, 0, 1, 0), "importId"),
(new CardImportReport(importId, " ", CardImportStates.Started, 0, 1, 0), "card"),
(new CardImportReport(importId, "card", "paused", 0, 1, 0), "state"),
(new CardImportReport(importId, "card", CardImportStates.Progress, 2, 1, 0), "done"),
})
{
using var refused = await uploaderHttp.PostAsJsonAsync("/api/v1/uploads/cards", report, ProtocolJson.Default.CardImportReport);
Assert.Equal(field, (await refused.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request")).Details);
}
var (viewer, _, _) = await server.UserAsync("guest", "viewer");
using var forbidden = await viewer.PostAsJsonAsync("/api/v1/uploads/cards", new CardImportReport(importId, "card", CardImportStates.Started, 0, 1, 0),
ProtocolJson.Default.CardImportReport);
await forbidden.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
}
[Test]
public async Task OneAccountsCardReportsCannotCrowdTheEventQueues()
{
var clock = new ManualTimeProvider();
await using var server = await TestServer.StartAsync(context, services: s => s.AddSingleton<TimeProvider>(clock));
var (uploader, _, _) = await server.UserAsync("studio-pc", "uploader");
var (other, _, _) = await server.UserAsync("roof-pc", "uploader");
using var subscription = server.Services.GetRequiredService<Chronos.Server.Events.EventHub>().Subscribe();
var importId = Guid.CreateVersion7();
// Progress goes out at most once a second; the reports in between are taken and dropped.
for (var done = 1; done <= 5; done++) await ReportCardAsync(uploader, new CardImportReport(importId, "card", CardImportStates.Progress, done, 100, 0));
clock.Advance(TimeSpan.FromSeconds(1));
await ReportCardAsync(uploader, new CardImportReport(importId, "card", CardImportStates.Progress, 6, 100, 0));
Assert.SequenceEqual([1, 6], CardEvents(subscription).Select(e => e.Done));
// Starts and ends always go out, up to 120 events of one account a minute.
for (var i = 0; i < 118; i++) await ReportCardAsync(uploader, new CardImportReport(Guid.CreateVersion7(), "card", CardImportStates.Started, 0, 100, 0));
using (var refused = await uploader.PostAsJsonAsync("/api/v1/uploads/cards",
new CardImportReport(importId, "card", CardImportStates.Finished, 100, 100, 0), ProtocolJson.Default.CardImportReport))
Assert.Equal("59", (await refused.ExpectErrorAsync(HttpStatusCode.TooManyRequests, "rate_limited")).Details);
await ReportCardAsync(other, new CardImportReport(Guid.CreateVersion7(), "card", CardImportStates.Started, 0, 100, 0));
Assert.Count(119, CardEvents(subscription));
clock.Advance(TimeSpan.FromMinutes(1));
await ReportCardAsync(uploader, new CardImportReport(importId, "card", CardImportStates.Finished, 100, 100, 0));
Assert.SequenceEqual([CardImportStates.Finished], CardEvents(subscription).Select(e => e.State));
}
private static async Task ReportCardAsync(HttpClient client, CardImportReport report)
{
using var response = await client.PostAsJsonAsync("/api/v1/uploads/cards", report, ProtocolJson.Default.CardImportReport);
await response.ExpectAsync(HttpStatusCode.NoContent);
}
/// <summary>The card events published since the last call.</summary>
private static List<CardEvent> CardEvents(Chronos.Server.Events.EventHub.Subscription subscription)
{
var events = new List<CardEvent>();
while (subscription.Reader.TryRead(out var e))
{
if (e is CardEvent card) events.Add(card);
}
return events;
}
private static async Task WaitForSubscriberAsync(TestServer server)
{
var hub = server.Services.GetRequiredService<Chronos.Server.Events.EventHub>();
for (var i = 0; i < 200 && hub.SubscriberCount == 0; i++) await Task.Delay(25);
Assert.Equal(1, hub.SubscriberCount);
}
}
+147
View File
@@ -0,0 +1,147 @@
using System.Collections.Concurrent;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Server.Storage;
namespace Chronos.Server.Tests;
/// <summary>
/// Stand-in for the archive module's ingest: files staged uploads as <c>&lt;folder&gt;/originals/&lt;name&gt;</c>, one
/// sequence per session key, and records every request it received.
/// </summary>
public sealed class FakeArchiveIngest(ChronosDatabase db) : IArchiveIngest
{
private readonly ConcurrentDictionary<string, Guid> _sessions = new(StringComparer.Ordinal);
private readonly SemaphoreSlim _gate = new(1, 1);
public ConcurrentQueue<IngestRequest> Requests { get; } = new();
public async Task<IngestResult> CommitAsync(IngestRequest request, CancellationToken cancellationToken = default)
{
Requests.Enqueue(request);
await _gate.WaitAsync(cancellationToken);
try
{
var archive = (await db.Archives.GetAsync(request.ArchiveId, cancellationToken))!;
var sequence = await SequenceForAsync(request, archive, cancellationToken);
var existing = (await db.Frames.FindBySha256Async(request.Sha256, cancellationToken)).FirstOrDefault(f => f.SequenceId == sequence.Id);
if (existing is not null)
{
File.Delete(request.StagedPath);
return new IngestResult(sequence.Id, existing.Id, existing.Index, existing.RelativePath, Duplicate: true);
}
var index = sequence.FrameCount;
var relative = $"{sequence.Folder}/originals/{index:D4}_{request.OriginalFileName}";
var target = Path.Combine(archive.RootPath, relative);
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
File.Move(request.StagedPath, target);
var frame = new Frame
{
Id = Guid.CreateVersion7(),
SequenceId = sequence.Id,
Index = index,
RelativePath = relative,
FileName = Path.GetFileName(relative),
OriginalFileName = request.OriginalFileName,
Size = request.Size,
Sha256 = request.Sha256,
CapturedAt = request.ClientCapturedAt,
};
await db.Frames.InsertAsync(frame, cancellationToken);
await db.Sequences.RefreshStatsAsync(sequence.Id, cancellationToken);
return new IngestResult(sequence.Id, frame.Id, index, relative, Duplicate: false);
}
finally
{
_gate.Release();
}
}
private async Task<Sequence> SequenceForAsync(IngestRequest request, Archive archive, CancellationToken cancellationToken)
{
Sequence? sequence = null;
if (request.SequenceId is { } id) sequence = await db.Sequences.GetAsync(id, cancellationToken);
else if (request.SessionKey is { } key && _sessions.TryGetValue(key, out var known)) sequence = await db.Sequences.GetAsync(known, cancellationToken);
if (sequence is null)
{
sequence = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = archive.Id, Folder = string.Empty, Title = request.NewSequenceTitle, OwnerUserId = request.UserId };
if (request.SessionKey is { } key) _sessions[key] = sequence.Id;
}
if (string.IsNullOrEmpty(sequence.Folder))
{
sequence = sequence with { Folder = $"2026/{sequence.Id:N}", UpdatedAt = DateTimeOffset.UtcNow };
await db.Sequences.UpsertAsync(sequence, cancellationToken);
}
return sequence;
}
}
/// <summary>Proxies at <c>&lt;folder&gt;/proxies/NNNN.jpg</c>; thumbnails as 64-byte slots of <c>&lt;folder&gt;/.chronos/thumbs.pack</c>.</summary>
public sealed class FakeAssetLocator : IFrameAssetLocator
{
public const int ThumbnailSize = 64;
/// <summary>When set, every lookup answers this location (path traversal tests).</summary>
public AssetLocation? Override { get; set; }
public ValueTask<AssetLocation?> LocateAsync(Archive archive, Sequence sequence, Frame frame, FrameAsset asset, CancellationToken cancellationToken)
{
if (Override is not null) return ValueTask.FromResult<AssetLocation?>(Override);
var folder = Path.Combine(archive.RootPath, sequence.Folder);
AssetLocation? location = asset == FrameAsset.Proxy
? new AssetLocation(Path.Combine(folder, "proxies", $"{frame.Index:D4}.jpg"), 0, -1, "image/jpeg")
: new AssetLocation(Path.Combine(folder, ".chronos", "thumbs.pack"), (long)frame.Index * ThumbnailSize, ThumbnailSize, "image/jpeg");
if (!File.Exists(location.Path)) return ValueTask.FromResult<AssetLocation?>(null);
if (location.Length < 0) location = location with { Length = new FileInfo(location.Path).Length };
return ValueTask.FromResult<AssetLocation?>(location);
}
}
/// <summary>A clock tests move by hand (token expiry, heartbeat timeouts).</summary>
public sealed class ManualTimeProvider : TimeProvider
{
private long _ticks = DateTimeOffset.UtcNow.UtcTicks;
public override DateTimeOffset GetUtcNow() => new(Interlocked.Read(ref _ticks), TimeSpan.Zero);
public void Advance(TimeSpan by) => Interlocked.Add(ref _ticks, by.Ticks);
}
/// <summary>
/// A job handler that reports progress and then waits until <see cref="Release"/> (or cancellation), so tests can
/// observe running, paused and cancelled states.
/// </summary>
public sealed class BlockingJobHandler(JobKind kind) : IJobHandler
{
private TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
public JobKind Kind => kind;
public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
/// <summary>When set, the next run fails with this message.</summary>
public string? FailWith { get; set; }
public void Release() => _release.TrySetResult();
public async Task RunAsync(JobContext context)
{
await context.ReportAsync(1, 4, "started");
Started.TrySetResult();
if (FailWith is { } message)
{
FailWith = null;
throw new InvalidOperationException(message);
}
for (var i = 2; i <= 3; i++)
{
await Task.Delay(50, context.Cancellation);
await context.ReportAsync(i, 4);
}
await _release.Task.WaitAsync(context.Cancellation);
_release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await context.ReportAsync(4, 4);
}
}
@@ -0,0 +1,284 @@
using System.Runtime.Versioning;
using System.Security.AccessControl;
using System.Security.Principal;
using Chronos.Server.Hosting;
using Chronos.Testing;
namespace Chronos.Server.Tests.Hosting;
/// <summary>
/// The data folder and its secrets are private (BRIEF §14.2): mode 0600 off Windows; on Windows a protected ACL that no
/// ordinary user appears in, where %ProgramData% would otherwise let every local user read the folder, with owners the
/// server trusts and no links. On Windows a new archive folder lets other users only read it.
/// </summary>
[Category("server")]
public sealed class DataFolderAccessTests(TestContext context)
{
private const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite;
[Test]
public async Task TheTlsKeyAndTheFirstAdminPasswordAreReadableOnlyByTheServer()
{
await using var server = await TestServer.StartAsync(context, o => o.AdminPassword = null);
foreach (var file in new[] { Path.Combine(server.Options.TlsPath, "server.pfx"), Path.Combine(server.Options.DataPath, "initial-admin-password.txt") })
{
Assert.FileExists(file);
if (OperatingSystem.IsWindows()) Assert.True(DataFolderAccess.IsPrivate(new FileInfo(file).GetAccessControl()), file);
else Assert.Equal(OwnerOnly, File.GetUnixFileMode(file));
}
if (OperatingSystem.IsWindows()) Assert.True(DataFolderAccess.IsPrivate(new DirectoryInfo(server.Options.DataPath).GetAccessControl()));
}
[Test]
public void ARewrittenSecretLosesTheAccessItHad()
{
var file = Path.Combine(context.CreateTempDirectory("secret"), "server.pfx");
File.WriteAllBytes(file, [1]);
if (OperatingSystem.IsWindows()) GrantUsersRead(new FileInfo(file));
else File.SetUnixFileMode(file, OwnerOnly | UnixFileMode.GroupRead | UnixFileMode.OtherRead);
DataFolderAccess.WritePrivateFile(file, [1, 2, 3]);
Assert.BytesEqual([1, 2, 3], File.ReadAllBytes(file));
if (OperatingSystem.IsWindows()) Assert.True(DataFolderAccess.IsPrivate(new FileInfo(file).GetAccessControl()));
else Assert.Equal(OwnerOnly, File.GetUnixFileMode(file));
}
[Test]
[WindowsOnly]
public void AFolderEveryUserCouldReadBecomesPrivateWithItsFiles()
{
if (!OperatingSystem.IsWindows()) return;
var folder = new DirectoryInfo(context.CreateTempDirectory("programdata"));
// What %ProgramData% hands down to a new folder: every local user may read it and create files in it.
var open = folder.GetAccessControl();
open.AddAccessRule(new FileSystemAccessRule(Users, FileSystemRights.ReadAndExecute | FileSystemRights.CreateFiles,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
folder.SetAccessControl(open);
var database = new FileInfo(Path.Combine(folder.FullName, "chronos.db"));
File.WriteAllText(database.FullName, "rows");
Assert.True(NamesUsers(database.GetAccessControl()), "the file inherited the users' entry");
DataFolderAccess.Restrict(folder.FullName);
Assert.True(DataFolderAccess.IsPrivate(folder.GetAccessControl()));
Assert.False(NamesUsers(folder.GetAccessControl()));
Assert.False(NamesUsers(database.GetAccessControl()), "the file still lets every user read it");
Assert.Equal("rows", File.ReadAllText(database.FullName));
// Once private, a later start leaves it as it is.
DataFolderAccess.Restrict(folder.FullName);
Assert.True(DataFolderAccess.IsPrivate(folder.GetAccessControl()));
}
[Test]
[WindowsOnly]
public void ANewDataFolderIsCreatedPrivate()
{
if (!OperatingSystem.IsWindows()) return;
var folder = new DirectoryInfo(Path.Combine(context.CreateTempDirectory("new"), "Chronos Server"));
DataFolderAccess.Restrict(folder.FullName);
Assert.True(DataFolderAccess.IsPrivate(folder.GetAccessControl()));
var settings = new FileInfo(Path.Combine(folder.FullName, "server.json"));
File.WriteAllText(settings.FullName, "{}");
Assert.False(NamesUsers(settings.GetAccessControl()));
}
[Test]
[WindowsOnly]
public void ASecretAnotherAccountOwnedIsReplacedByOneTheServerOwns()
{
if (!OperatingSystem.IsWindows()) return;
var folder = context.CreateTempDirectory("planted");
var own = OwnerOf(NewFile(Path.Combine(folder, "probe.txt")));
// Planted before the first start: whoever owns it keeps the right to change its ACL, whatever the server sets.
var secret = NewFile(Path.Combine(folder, "initial-admin-password.txt"));
if (!TrySetOwner(secret, OtherOwner(own))) Assert.Inconclusive("giving a file to another owner needs an elevated administrator");
GrantUsersRead(secret);
DataFolderAccess.WritePrivateFile(secret.FullName, [1, 2, 3]);
secret.Refresh();
Assert.Equal(own, OwnerOf(secret));
Assert.True(DataFolderAccess.IsPrivate(secret.GetAccessControl()));
Assert.False(NamesUsers(secret.GetAccessControl()));
Assert.BytesEqual([1, 2, 3], File.ReadAllBytes(secret.FullName));
}
[Test]
[WindowsOnly]
public void AnythingAnotherAccountOwnsIsFound()
{
if (!OperatingSystem.IsWindows()) return;
var folder = new DirectoryInfo(context.CreateTempDirectory("squatted"));
var key = NewFile(Path.Combine(folder.CreateSubdirectory("tls").FullName, "server.pfx"));
var own = OwnerOf(key);
Assert.Null(DataFolderAccess.FindUntrusted(folder, new HashSet<SecurityIdentifier> { own }));
// A folder someone else created before the first start is reported before anything inside it.
Assert.Contains(folder.FullName, Assert.NotNull(DataFolderAccess.FindUntrusted(folder, new HashSet<SecurityIdentifier> { LocalSystem })));
if (!TrySetOwner(key, OtherOwner(own))) Assert.Inconclusive("giving a file to another owner needs an elevated administrator");
Assert.Contains(key.FullName, Assert.NotNull(DataFolderAccess.FindUntrusted(folder, new HashSet<SecurityIdentifier> { own })));
}
[Test]
[WindowsOnly]
public void ALinkInTheDataFolderStopsTheServerBeforeTheAclChanges()
{
if (!OperatingSystem.IsWindows()) return;
var folder = new DirectoryInfo(context.CreateTempDirectory("linked"));
var link = Path.Combine(folder.FullName, "logs");
try
{
Directory.CreateSymbolicLink(link, context.CreateTempDirectory("elsewhere"));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Assert.Inconclusive("creating a symbolic link needs an elevated administrator or developer mode");
}
var refused = Assert.Throws<InvalidOperationException>(() => DataFolderAccess.Restrict(folder.FullName));
Assert.Contains(link, refused.Message);
// The ACL change would have followed the link; it never started.
Assert.False(folder.GetAccessControl().AreAccessRulesProtected);
}
[Test]
[WindowsOnly]
public void SettingsAnotherAccountOwnsAreNotRead()
{
if (!OperatingSystem.IsWindows()) return;
var settings = NewFile(Path.Combine(context.CreateTempDirectory("settings"), "server.json"), """{ "ArchivePath": "D:\\Elsewhere" }""");
Assert.Contains("Elsewhere", DataFolderAccess.ReadTrustedText(settings.FullName));
// As if another account had planted it: the owner is not among those the server trusts.
InvalidOperationException? refused = null;
try
{
DataFolderAccess.ReadTrustedText(settings.FullName, new HashSet<SecurityIdentifier> { LocalSystem });
}
catch (InvalidOperationException ex)
{
refused = ex;
}
Assert.Contains(settings.FullName, Assert.NotNull(refused).Message);
}
[Test]
public void AMissingArchiveFolderIsCreated()
{
var root = Path.Combine(context.CreateTempDirectory("archive"), "ChronosArchive");
Assert.False(DataFolderAccess.PrepareArchive(root));
Assert.True(Directory.Exists(root));
// An existing folder is left as it is.
Assert.False(DataFolderAccess.PrepareArchive(root));
}
[Test]
[WindowsOnly]
public void ANewArchiveIsReadableByUsersButOnlyTheServerChangesIt()
{
if (!OperatingSystem.IsWindows()) return;
// Under C:\ a new folder would inherit "Authenticated Users: modify" and every local user could plant links
// where the service moves uploads.
var root = new DirectoryInfo(Path.Combine(context.CreateTempDirectory("archive"), "ChronosArchive"));
Assert.False(DataFolderAccess.PrepareArchive(root.FullName));
var security = root.GetAccessControl();
Assert.True(security.AreAccessRulesProtected);
Assert.Equal(FileSystemRights.ReadAndExecute, RightsOf(security, Users) & FileSystemRights.ReadAndExecute);
Assert.Equal((FileSystemRights)0, RightsOf(security, Users) & (FileSystemRights.Write | FileSystemRights.Delete | FileSystemRights.ChangePermissions));
// Staging and trash are the server's alone.
var meta = new DirectoryInfo(Path.Combine(root.FullName, ".chronos"));
Assert.True(DataFolderAccess.IsPrivate(meta.GetAccessControl()));
Assert.False(NamesUsers(meta.CreateSubdirectory("staging").GetAccessControl()));
}
[Test]
[WindowsOnly]
public void AnArchiveOtherUsersCanChangeIsReportedButLeftAsItIs()
{
if (!OperatingSystem.IsWindows()) return;
var root = new DirectoryInfo(context.CreateTempDirectory("shared"));
DataFolderAccess.PrepareArchive(root.FullName);
var open = root.GetAccessControl();
open.AddAccessRule(new FileSystemAccessRule(Users, FileSystemRights.Modify,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
root.SetAccessControl(open);
Assert.True(DataFolderAccess.PrepareArchive(root.FullName));
Assert.Equal(FileSystemRights.Modify, RightsOf(root.GetAccessControl(), Users) & FileSystemRights.Modify);
// The .chronos folder the server added at the first start stays its own.
Assert.True(DataFolderAccess.IsPrivate(new DirectoryInfo(Path.Combine(root.FullName, ".chronos")).GetAccessControl()));
}
[SupportedOSPlatform("windows")]
private static SecurityIdentifier Users => new(WellKnownSidType.BuiltinUsersSid, null);
[SupportedOSPlatform("windows")]
private static SecurityIdentifier LocalSystem => new(WellKnownSidType.LocalSystemSid, null);
[SupportedOSPlatform("windows")]
private static SecurityIdentifier Administrators => new(WellKnownSidType.BuiltinAdministratorsSid, null);
private static FileInfo NewFile(string path, string contents = "x")
{
File.WriteAllText(path, contents);
return new FileInfo(path);
}
[SupportedOSPlatform("windows")]
private static SecurityIdentifier OwnerOf(FileInfo file) => (SecurityIdentifier)file.GetAccessControl().GetOwner(typeof(SecurityIdentifier))!;
/// <summary>An owner this process may give a file that its new files do not get: its own account or Administrators.</summary>
[SupportedOSPlatform("windows")]
private static SecurityIdentifier OtherOwner(SecurityIdentifier own)
{
using var identity = WindowsIdentity.GetCurrent();
return own == Administrators ? identity.User! : Administrators;
}
[SupportedOSPlatform("windows")]
private static bool TrySetOwner(FileInfo file, SecurityIdentifier owner)
{
var security = new FileSecurity();
security.SetOwner(owner);
try
{
file.SetAccessControl(security);
return true;
}
catch (Exception ex) when (ex is InvalidOperationException or UnauthorizedAccessException)
{
return false;
}
}
/// <summary>The rights allow entries give <paramref name="account"/>.</summary>
[SupportedOSPlatform("windows")]
private static FileSystemRights RightsOf(FileSystemSecurity security, SecurityIdentifier account)
{
FileSystemRights rights = 0;
foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)))
{
if (rule.AccessControlType == AccessControlType.Allow && rule.IdentityReference.Equals(account)) rights |= rule.FileSystemRights;
}
return rights;
}
/// <summary>True when Users, Authenticated Users or Everyone have any allow entry.</summary>
[SupportedOSPlatform("windows")]
private static bool NamesUsers(FileSystemSecurity security)
{
SecurityIdentifier[] ordinary = [Users, new(WellKnownSidType.AuthenticatedUserSid, null), new(WellKnownSidType.WorldSid, null)];
foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)))
{
if (rule.AccessControlType == AccessControlType.Allow && ordinary.Contains((SecurityIdentifier)rule.IdentityReference)) return true;
}
return false;
}
[SupportedOSPlatform("windows")]
private static void GrantUsersRead(FileInfo file)
{
var security = file.GetAccessControl();
security.AddAccessRule(new FileSystemAccessRule(Users, FileSystemRights.Read, AccessControlType.Allow));
file.SetAccessControl(security);
}
}
@@ -0,0 +1,54 @@
using System.Net;
using System.Net.Sockets;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Protocol;
using Chronos.Server.Api;
using Chronos.Server.Hosting;
using Chronos.Testing;
namespace Chronos.Server.Tests.Hosting;
[Category("server")]
public sealed class DiscoveryTests(TestContext context)
{
[Test]
public async Task TheBeaconTravelsOverUdpAndParses()
{
await using var server = await TestServer.StartAsync(context, o => o.ServerName = "Studio NAS");
var service = server.Services.GetRequiredService<DiscoveryBeaconService>();
using var listener = new UdpClient(new IPEndPoint(IPAddress.Loopback, 0));
using var sender = new UdpClient(AddressFamily.InterNetwork);
await service.SendOnceAsync(sender, [(IPEndPoint)listener.Client.LocalEndPoint!], context.Cancellation);
var datagram = await listener.ReceiveAsync(context.Cancellation).AsTask().WaitAsync(TimeSpan.FromSeconds(5));
var beacon = Assert.NotNull(DiscoveryBeacon.TryParse(datagram.Buffer));
Assert.Equal("Studio NAS", beacon.Name);
Assert.Equal(SystemEndpoints.Version, beacon.Version);
Assert.Equal(server.HttpBase.Port, beacon.HttpPort);
Assert.Equal(server.HttpsBase!.Port, beacon.HttpsPort);
using var info = await server.Client.GetAsync("/api/v1/server/info");
Assert.Equal((await info.ReadAsync(ProtocolJson.Default.ServerInfo)).TlsFingerprint, beacon.TlsFingerprint);
}
[Test]
public async Task TheBeaconAdvertisesThePortsClientsReach()
{
// Container ports published as other host ports: a client on the LAN must use the host's.
await using var server = await TestServer.StartAsync(context, o =>
{
o.PublicHttpPort = 18080;
o.PublicHttpsPort = 18443;
});
var beacon = server.Services.GetRequiredService<DiscoveryBeaconService>().CreateBeacon();
Assert.Equal((18080, 18443), (beacon.HttpPort, beacon.HttpsPort));
}
[Test]
public void ForeignDatagramsAreIgnored()
{
Assert.Null(DiscoveryBeacon.TryParse(Encoding.UTF8.GetBytes("HELLO {}")));
Assert.Null(DiscoveryBeacon.TryParse(Encoding.UTF8.GetBytes("CHRONOS1 {not json")));
Assert.Null(DiscoveryBeacon.TryParse(new byte[4096]));
}
}
@@ -0,0 +1,186 @@
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Chronos.Core.Localization;
using Chronos.Protocol;
using Chronos.Server.Api;
using Chronos.Server.Configuration;
using Chronos.Testing;
namespace Chronos.Server.Tests.Hosting;
/// <summary>TLS mode proxy (BRIEF §14.2): forwarded headers count only from trusted proxies, and the admin warns otherwise.</summary>
[Category("server")]
public sealed class ProxyModeTests(TestContext context)
{
/// <summary>A documentation network (RFC 5737) the test client never connects from.</summary>
private const string ElsewhereOnly = "192.0.2.0/24";
[Test]
public async Task AClientOutsideTheTrustedProxiesCannotChooseItsAddress()
{
await using var server = await TestServer.StartAsync(context, o =>
{
o.TlsMode = TlsMode.Proxy;
o.TrustedProxies = ElsewhereOnly;
o.LoginAttemptsPerMinute = 5;
});
for (var i = 0; i < 5; i++)
{
using var failed = await LoginAsync(server, "user" + i, $"203.0.113.{i + 1}");
await failed.ExpectErrorAsync(HttpStatusCode.Unauthorized, "invalid_credentials");
}
// A new X-Forwarded-For per attempt does not buy a new budget: the limit stays on the real address.
using var limited = await LoginAsync(server, "admin", "203.0.113.99");
await limited.ExpectErrorAsync(HttpStatusCode.TooManyRequests, "rate_limited");
var audit = await server.Database.Audit.ListAsync(null, "login_failed", 50, null, context.Cancellation);
Assert.Count(5, audit.Items);
Assert.True(audit.Items.All(e => IsLoopback(e.RemoteAddress)), string.Join(", ", audit.Items.Select(e => e.RemoteAddress)));
}
[Test]
public async Task ATrustedProxyReportsTheClientAddress()
{
// The default trusts loopback, where a proxy on the same machine (and this test) connects from.
await using var server = await TestServer.StartAsync(context, o =>
{
o.TlsMode = TlsMode.Proxy;
o.LoginAttemptsPerMinute = 5;
});
for (var i = 0; i < 8; i++)
{
using var failed = await LoginAsync(server, "user" + i, $"203.0.113.{i + 1}");
await failed.ExpectErrorAsync(HttpStatusCode.Unauthorized, "invalid_credentials");
}
var audit = await server.Database.Audit.ListAsync(null, "login_failed", 50, null, context.Cancellation);
Assert.Contains("203.0.113.8", audit.Items.Select(e => e.RemoteAddress));
}
[Test]
public async Task ByDefaultAMachineOfTheHomeNetworkIsNoProxy()
{
// The machines of a home network reach the HTTP port directly from private addresses, also through Docker's
// port publishing (which keeps the client's address): none of them may choose its own address.
await using var server = await TestServer.StartAsync(context, o => o.TlsMode = TlsMode.Proxy);
foreach (var peer in new[] { "192.168.1.50", "10.0.0.7", "172.17.0.1", "fd00::7" })
Assert.Equal((peer, false), await ForwardAsync(server, peer));
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "127.0.0.1"));
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "::ffff:127.0.0.1"));
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "::1"));
}
[Test]
public async Task AProxyNetworkCountsOnceListed()
{
await using var server = await TestServer.StartAsync(context, o =>
{
o.TlsMode = TlsMode.Proxy;
o.TrustedProxies = "172.18.0.0/16";
});
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "172.18.0.5"));
Assert.Equal(("192.168.1.50", false), await ForwardAsync(server, "192.168.1.50"));
}
[Test]
public void AnAdminSignInThroughAnUntrustedProxyNamesTheSetting()
{
// The warning chip needs a session first: the sign-in refusal itself points at CHRONOS_TRUSTED_PROXIES.
var request = new DefaultHttpContext();
request.Connection.RemoteIpAddress = IPAddress.Parse("172.18.0.5");
request.Request.Scheme = "http";
Assert.Equal("proxy_untrusted", AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Proxy }));
Assert.Equal("https_required", AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Auto }));
Assert.Contains("CHRONOS_TRUSTED_PROXIES", Loc.L("Server.Error.ProxyUntrusted"));
request.Request.Scheme = "https";
Assert.Null(AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Proxy }));
request.Request.Scheme = "http";
request.Connection.RemoteIpAddress = IPAddress.Loopback;
Assert.Null(AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Proxy }));
}
[Test]
public async Task TheAdminWarnsWhenAPageDidNotComeThroughATrustedProxyOverHttps()
{
await using var server = await TestServer.StartAsync(context, o => o.TlsMode = TlsMode.Proxy);
var admin = await server.AdminAsync();
Assert.True((await DashboardAsync(admin, forwardedProto: null)).ProxyWarning, "plain HTTP to the server's own port");
Assert.False((await DashboardAsync(admin, "https")).ProxyWarning, "HTTPS through a trusted proxy");
Assert.True((await DashboardAsync(admin, "http")).ProxyWarning, "plain HTTP through the proxy");
Assert.True((await SettingsAsync(admin, forwardedProto: null)).ProxyWarning);
Assert.False((await SettingsAsync(admin, "https")).ProxyWarning);
await using var untrusted = await TestServer.StartAsync(context, o =>
{
o.TlsMode = TlsMode.Proxy;
o.TrustedProxies = ElsewhereOnly;
});
var other = await untrusted.AdminAsync();
Assert.True((await DashboardAsync(other, "https")).ProxyWarning, "a claim of HTTPS from a peer that is no trusted proxy");
}
[Test]
public async Task OtherTlsModesNeverWarn()
{
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
Assert.False((await DashboardAsync(admin, forwardedProto: null)).ProxyWarning);
Assert.False((await SettingsAsync(admin, forwardedProto: null)).ProxyWarning);
}
/// <summary>
/// Runs the server's own forwarded-headers step on a request from <paramref name="peer"/> that claims to forward a
/// client at 203.0.113.7 over HTTPS: the address and scheme the rest of the server then sees.
/// </summary>
private static async Task<(string? Address, bool Https)> ForwardAsync(TestServer server, string peer)
{
var request = new DefaultHttpContext();
request.Connection.RemoteIpAddress = IPAddress.Parse(peer);
request.Request.Scheme = "http";
request.Request.Headers["X-Forwarded-For"] = "203.0.113.7";
request.Request.Headers["X-Forwarded-Proto"] = "https";
var forwarded = new ForwardedHeadersMiddleware(_ => Task.CompletedTask, NullLoggerFactory.Instance,
server.Services.GetRequiredService<IOptions<ForwardedHeadersOptions>>());
await forwarded.Invoke(request);
var address = request.Connection.RemoteIpAddress;
return ((address is { IsIPv4MappedToIPv6: true } ? address.MapToIPv4() : address)?.ToString(), request.Request.IsHttps);
}
private static bool IsLoopback(string? address) =>
IPAddress.TryParse(address, out var ip) && IPAddress.IsLoopback(ip.IsIPv4MappedToIPv6 ? ip.MapToIPv4() : ip);
private static async Task<HttpResponseMessage> LoginAsync(TestServer server, string username, string forwardedFor)
{
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/auth/login")
{
Content = JsonContent.Create(new LoginRequest(username, "wrong-password-x", "tests"), ProtocolJson.Default.LoginRequest),
};
request.Headers.Add("X-Forwarded-For", forwardedFor);
return await server.Client.SendAsync(request);
}
private static async Task<DashboardDto> DashboardAsync(HttpClient admin, string? forwardedProto)
{
using var response = await SendAsync(admin, "/api/v1/server/dashboard", forwardedProto);
return await response.ReadAsync(ProtocolJson.Default.DashboardDto);
}
private static async Task<ServerSettingsDto> SettingsAsync(HttpClient admin, string? forwardedProto)
{
using var response = await SendAsync(admin, "/api/v1/server/settings", forwardedProto);
return await response.ReadAsync(ProtocolJson.Default.ServerSettingsDto);
}
private static async Task<HttpResponseMessage> SendAsync(HttpClient client, string path, string? forwardedProto)
{
using var request = new HttpRequestMessage(HttpMethod.Get, path);
if (forwardedProto is not null) request.Headers.Add("X-Forwarded-Proto", forwardedProto);
return await client.SendAsync(request);
}
}
@@ -0,0 +1,163 @@
using System.Net;
using System.Text.RegularExpressions;
using Chronos.Data;
using Chronos.Server.Configuration;
using Chronos.Server.Hosting;
using Chronos.Testing;
namespace Chronos.Server.Tests.Hosting;
[Category("server")]
public sealed class StartupTests(TestContext context)
{
[Test]
public void TheServerRefusesToStartWithoutTheArchiveModule()
{
var root = context.CreateTempDirectory("bare");
var options = new ServerOptions
{
DataPath = Path.Combine(root, "data"),
ArchivePath = Path.Combine(root, "archive"),
HttpPort = 0,
HttpsPort = 0,
Database = DatabaseKind.Sqlite,
Discovery = false,
};
var error = Assert.Throws<InvalidOperationException>(() => ServerHost.Build(options, []));
Assert.Contains("IArchiveIngest", error.Message);
Assert.Contains("IFrameAssetLocator", error.Message);
}
[Test]
public void ChronosDbAcceptsAConnectionString()
{
var root = context.CreateTempDirectory("env");
var options = ServerOptions.Load(new Dictionary<string, string?>
{
["CHRONOS_DATA_PATH"] = root,
["CHRONOS_DB"] = "Host=db.lan;Port=6543;Database=archive;Username=chronos;Password=secret",
});
Assert.Equal(DatabaseKind.Postgres, options.Database);
var database = options.ToDatabaseOptions();
Assert.Equal(Dialect.Postgres, database.Dialect);
Assert.Equal(6543, Chronos.Data.Postgres.PostgresSettings.Parse(database.ConnectionString).Port);
}
[Test]
public void PartsBuildAQuotedPostgresConnectionString()
{
var options = new ServerOptions
{
Database = DatabaseKind.Postgres, // the Windows default is SQLite
DbHost = "postgres",
DbName = "chronos",
DbUser = "chronos",
DbPassword = "it's;secret",
DbSslMode = "disable",
};
var settings = Chronos.Data.Postgres.PostgresSettings.Parse(options.ToDatabaseOptions().ConnectionString);
Assert.Equal(("postgres", "chronos", "it's;secret"), (settings.Host, settings.Database, settings.Password));
Assert.Equal(Chronos.Data.Postgres.SslMode.Disable, settings.SslMode);
}
[Test]
public void EnvironmentVariablesLockTheirSettings()
{
var root = context.CreateTempDirectory("locked");
var options = ServerOptions.Load(new Dictionary<string, string?>
{
["CHRONOS_DATA_PATH"] = root,
["CHRONOS_DB"] = "postgres",
["CHRONOS_HTTP_PORT"] = "9090",
["CHRONOS_DISCOVERY"] = "false",
});
Assert.SequenceEqual(["Database", "HttpPort", "Discovery"], options.Locked);
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_WORKERS"] = "many" }));
}
[Test]
public void TheFormerWorkersSettingStillSetsTheParallelism()
{
// Owner review 1: "workers" (jobs at once) became the parallelism (photos the running job processes at once).
var root = context.CreateTempDirectory("workers");
File.WriteAllText(Path.Combine(root, "server.json"), """{ "Workers": 6 }""");
Assert.Equal(6, ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres" }).Parallelism);
var former = ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_WORKERS"] = "5" });
Assert.Equal((5, true), (former.Parallelism, former.FormerWorkersVariable));
Assert.SequenceEqual(["Database", "Parallelism"], former.Locked);
var both = ServerOptions.Load(new Dictionary<string, string?>
{
["CHRONOS_DATA_PATH"] = root,
["CHRONOS_DB"] = "postgres",
["CHRONOS_WORKERS"] = "5",
["CHRONOS_PARALLELISM"] = "7",
["CHRONOS_PRIORITY_QUEUE"] = "true",
});
Assert.Equal((7, true), (both.Parallelism, both.PriorityQueue));
Assert.SequenceEqual(["Database", "Parallelism", "PriorityQueue"], both.Locked);
Assert.False(ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_PARALLELISM"] = "2" })
.FormerWorkersVariable);
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_PRIORITY_QUEUE"] = "often" }));
// A value the admin panel would refuse is brought within its range, so the panel can still save the other settings.
Assert.Equal(ServerOptions.MaxParallelism,
ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_PARALLELISM"] = "96" }).Parallelism);
Assert.Equal(1, ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_WORKERS"] = "0" }).Parallelism);
Assert.InRange(new ServerOptions().Parallelism, 1, ServerOptions.MaxParallelism);
}
[Test]
public void TrustedProxiesAreAddressesOrNetworks()
{
var root = context.CreateTempDirectory("proxies");
// Loopback only: machines of the home network reach the HTTP port directly from private addresses.
var defaults = ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres" }).TrustedProxyNetworks();
foreach (var address in new[] { "127.0.0.1", "127.0.0.53", "::1" })
Assert.True(defaults.Any(n => n.Contains(IPAddress.Parse(address))), address);
foreach (var address in new[] { "10.20.30.40", "172.18.0.3", "192.168.1.2", "fd00::7", "203.0.113.5" })
Assert.False(defaults.Any(n => n.Contains(IPAddress.Parse(address))), address);
var options = ServerOptions.Load(new Dictionary<string, string?>
{
["CHRONOS_DATA_PATH"] = root,
["CHRONOS_DB"] = "postgres",
["CHRONOS_TRUSTED_PROXIES"] = "10.1.2.3, 2001:db8::/32;172.20.0.5/16",
});
Assert.Contains("TrustedProxies", options.Locked);
Assert.SequenceEqual(["10.1.2.3/32", "2001:db8::/32", "172.20.0.0/16"], options.TrustedProxyNetworks().Select(n => n.ToString()));
foreach (var invalid in new[] { "proxy.lan", "10.0.0.0/33", "fe80::1%2" })
{
var error = Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?>
{
["CHRONOS_DATA_PATH"] = root,
["CHRONOS_DB"] = "postgres",
["CHRONOS_TRUSTED_PROXIES"] = "127.0.0.1," + invalid,
}));
Assert.Contains(invalid, error.Message);
}
}
[Test]
public void PublicPortsComeFromTheEnvironment()
{
var root = context.CreateTempDirectory("public");
var options = ServerOptions.Load(new Dictionary<string, string?>
{
["CHRONOS_DATA_PATH"] = root,
["CHRONOS_DB"] = "postgres",
["CHRONOS_PUBLIC_HTTP_PORT"] = "18080",
["CHRONOS_PUBLIC_HTTPS_PORT"] = "18443",
});
Assert.Equal((18080, 18443), (options.PublicHttpPort, options.PublicHttpsPort));
Assert.Null(ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres" }).PublicHttpsPort);
foreach (var invalid in new[] { "0", "70000", "https" })
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_PUBLIC_HTTPS_PORT"] = invalid }));
}
[Test]
public void HelpListsEveryVariable()
{
foreach (var variable in ServerOptions.EnvironmentVariables.Concat(["PUID", "PGID", "TZ"]))
Assert.True(Regex.IsMatch(ServerCommandLine.Usage, $@"\b{variable}\b"), variable);
}
}
@@ -0,0 +1,219 @@
using System.Net;
using System.Net.Http.Json;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Protocol;
using Chronos.Server.Hosting;
using Chronos.Testing;
namespace Chronos.Server.Tests.Hosting;
[Category("server")]
public sealed class SystemEndpointTests(TestContext context)
{
[Test]
public async Task HealthReportsOk()
{
await using var server = await TestServer.StartAsync(context);
var health = await server.Client.GetFromJsonAsync("/health", ProtocolJson.Default.HealthStatus);
Assert.Equal("ok", Assert.NotNull(health).Status);
Assert.Equal("ok", health.Checks["archive"]);
}
[Test]
public async Task ServerInfoCarriesFingerprintAndApiHeader()
{
await using var server = await TestServer.StartAsync(context);
using var response = await server.Client.GetAsync("/api/v1/server/info");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("1", response.Headers.GetValues(ApiVersion.Header).Single());
var info = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ServerInfo);
Assert.Equal(1, Assert.NotNull(info).ApiVersion);
Assert.Equal(95, Assert.NotNull(info.TlsFingerprint).Length); // 32 bytes as XX: pairs
}
[Test]
public async Task HttpsServesTheAdvertisedCertificate()
{
await using var server = await TestServer.StartAsync(context);
var info = await server.Client.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo);
string? seen = null;
using var handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (_, cert, _, _) =>
{
seen = cert is null ? null : string.Join(':', cert.GetCertHash(System.Security.Cryptography.HashAlgorithmName.SHA256).Select(b => b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture)));
return true;
},
};
using var https = new HttpClient(handler) { BaseAddress = Assert.NotNull(server.HttpsBase) };
using var response = await https.GetAsync("/health");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(Assert.NotNull(info).TlsFingerprint, seen);
}
[Test]
public async Task CertificateIsReusedAcrossRestarts()
{
var root = context.CreateTempDirectory("restart");
string? first;
await using (var a = await TestServer.StartAsync(context, o => o.DataPath = Path.Combine(root, "data")))
first = (await a.Client.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo))!.TlsFingerprint;
await using var b = await TestServer.StartAsync(context, o => o.DataPath = Path.Combine(root, "data"));
var second = (await b.Client.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo))!.TlsFingerprint;
Assert.Equal(first, second);
}
[Test]
public async Task UnknownApiRouteReturnsJsonError()
{
await using var server = await TestServer.StartAsync(context);
using var response = await server.Client.GetAsync("/api/v1/does-not-exist");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
var error = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ApiError);
Assert.Equal("not_found", Assert.NotNull(error).Code);
}
[Test]
public async Task AdminPanelIsServedWithEtags()
{
await using var server = await TestServer.StartAsync(context);
using var redirect = await new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { BaseAddress = server.HttpBase }.GetAsync("/admin");
Assert.Equal(HttpStatusCode.Redirect, redirect.StatusCode);
using var page = await server.Client.GetAsync("/admin/");
Assert.Equal(HttpStatusCode.OK, page.StatusCode);
Assert.Contains("app.js", await page.Content.ReadAsStringAsync());
var etag = page.Headers.ETag;
using var request = new HttpRequestMessage(HttpMethod.Get, "/admin/");
request.Headers.IfNoneMatch.Add(Assert.NotNull(etag));
using var cached = await server.Client.SendAsync(request);
Assert.Equal(HttpStatusCode.NotModified, cached.StatusCode);
}
[Test]
public async Task PlainHttpFromAnotherMachineGoesToThePublicHttpsPort()
{
// The container listens on 8443, published on the host as 18443 (BRIEF §19.6: the template's ports are editable).
await using var server = await TestServer.StartAsync(context, o => o.PublicHttpsPort = 18443);
var kestrel = server.Services.GetRequiredService<IServer>();
var request = AdminRequest(IPAddress.Parse("10.0.0.7"));
Assert.Equal("https://10.0.0.5:18443/admin/?page=jobs", AdminPanel.HttpsLocation(request, server.Options, kestrel));
server.Options.PublicHttpsPort = null;
Assert.Equal($"https://10.0.0.5:{Assert.NotNull(server.HttpsBase).Port}/admin/?page=jobs", AdminPanel.HttpsLocation(request, server.Options, kestrel));
Assert.Null(AdminPanel.HttpsLocation(AdminRequest(IPAddress.Loopback), server.Options, kestrel));
}
private static DefaultHttpContext AdminRequest(IPAddress from)
{
var request = new DefaultHttpContext();
request.Connection.RemoteIpAddress = from;
request.Request.Scheme = "http";
request.Request.Host = new HostString("10.0.0.5", 18080);
request.Request.Path = "/admin/";
request.Request.QueryString = new QueryString("?page=jobs");
return request;
}
[Test]
public async Task AdminPanelRunsUnderAStrictPolicyAndIsNeverFramed()
{
await using var server = await TestServer.StartAsync(context);
foreach (var path in new[] { "/admin/", "/admin/app.js", "/admin/admin.css" })
{
using var response = await server.Client.GetAsync(path);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var policy = string.Join(' ', response.Headers.GetValues("Content-Security-Policy"));
foreach (var directive in new[] { "default-src 'self'", "script-src 'self'", "style-src 'self'", "frame-ancestors 'none'" })
Assert.Contains(directive, policy);
Assert.True(!policy.Contains("unsafe-inline", StringComparison.Ordinal), policy);
Assert.Equal("DENY", response.Headers.GetValues("X-Frame-Options").Single());
}
}
[Test]
public async Task AdminPanelModulesAllResolve()
{
await using var server = await TestServer.StartAsync(context);
var index = await server.Client.GetStringAsync("/admin/");
// The page container is not a live region: only toasts and form errors announce themselves.
Assert.True(!index.Contains("aria-live", StringComparison.Ordinal), index);
var app = await server.Client.GetStringAsync("/admin/app.js");
var pages = Regex.Match(app, @"const pages = \[([^\]]*)\]").Groups[1].Value.Split(',').Select(p => p.Trim().Trim('"'));
var pending = new Queue<string>(pages.Select(p => $"pages/{p}.js").Prepend("app.js"));
var seen = new HashSet<string>(StringComparer.Ordinal);
while (pending.TryDequeue(out var module))
{
if (!seen.Add(module)) continue;
using var response = await server.Client.GetAsync("/admin/" + module);
Assert.Equal(HttpStatusCode.OK, response.StatusCode, module);
var folder = module.Contains('/', StringComparison.Ordinal) ? module[..(module.LastIndexOf('/') + 1)] : string.Empty;
foreach (Match import in Regex.Matches(await response.Content.ReadAsStringAsync(), @"from ""(\.{1,2}/[^""]+)"""))
pending.Enqueue(Resolve(folder, import.Groups[1].Value));
}
Assert.True(seen.Count >= 14, string.Join(", ", seen));
}
private static string Resolve(string folder, string relative)
{
var parts = (folder + relative).Split('/').ToList();
for (var i = 0; i < parts.Count; i++)
{
if (parts[i] == ".") parts.RemoveAt(i--);
else if (parts[i] == ".." && i > 0) parts.RemoveRange(--i, 2);
}
return string.Join('/', parts.Where(p => p.Length > 0));
}
[Test]
public async Task I18nEndpointFallsBackToEnglish()
{
await using var server = await TestServer.StartAsync(context);
var it = await server.Client.GetFromJsonAsync("/api/v1/i18n/it-IT", ProtocolJson.Default.DictionaryStringString);
Assert.Equal("Accedi", Assert.NotNull(it)["Admin.Login.SignIn"]);
var unknown = await server.Client.GetFromJsonAsync("/api/v1/i18n/xx", ProtocolJson.Default.DictionaryStringString);
Assert.Equal("Sign in", Assert.NotNull(unknown)["Admin.Login.SignIn"]);
}
[Test]
public async Task I18nEndpointMarksRightToLeftLanguages()
{
await using var server = await TestServer.StartAsync(context);
foreach (var (culture, rtl) in new[] { ("ar", "true"), ("he", "true"), ("it", "false"), ("en", "false") })
{
var strings = Assert.NotNull(await server.Client.GetFromJsonAsync($"/api/v1/i18n/{culture}", ProtocolJson.Default.DictionaryStringString));
Assert.Equal((culture, rtl), (strings["$culture"], strings["$rtl"]));
// Count strings reach the panel in their plural forms.
Assert.True(strings.ContainsKey("Admin.Users.Accounts.one") && strings.ContainsKey("Admin.Users.Accounts.other"), culture);
}
}
[Test]
public void LinuxRefusesSqlite()
{
if (OperatingSystem.IsWindows()) TestContext.Skip("SQLite is allowed on Windows");
var options = new Chronos.Server.Configuration.ServerOptions { Database = Chronos.Server.Configuration.DatabaseKind.Sqlite };
Assert.Throws<InvalidOperationException>(options.Validate);
}
[Test]
public void EnvironmentOverridesDefaults()
{
var root = context.CreateTempDirectory("env");
var env = new Dictionary<string, string?>
{
["CHRONOS_DATA_PATH"] = root,
["CHRONOS_HTTP_PORT"] = "9090",
["CHRONOS_TLS_MODE"] = "proxy",
["CHRONOS_DB"] = "postgres",
["CHRONOS_SERVER_NAME"] = "Studio NAS",
};
var options = Chronos.Server.Configuration.ServerOptions.Load(env);
Assert.Equal(9090, options.HttpPort);
Assert.Equal(Chronos.Server.Configuration.TlsMode.Proxy, options.TlsMode);
Assert.Equal("Studio NAS", options.ServerName);
}
}
@@ -0,0 +1,152 @@
using System.Diagnostics.Eventing.Reader;
using System.Security.AccessControl;
using System.Security.Principal;
using Chronos.Server.Hosting;
using Chronos.Server.Hosting.Windows;
using Chronos.Testing;
namespace Chronos.Server.Tests.Hosting;
public sealed class WindowsServiceTests(TestContext context)
{
[Test]
public void CommandSwitchesAreParsedAndTheRestPassedOn()
{
Assert.Equal(ServerCommand.Run, ServerCommandLine.Parse([]).Command);
var service = ServerCommandLine.Parse(["--service", "--urls", "x"]);
Assert.Equal(ServerCommand.Service, service.Command);
Assert.SequenceEqual(["--urls", "x"], service.HostArguments);
Assert.Equal(ServerCommand.InstallService, ServerCommandLine.Parse(["--install-service"]).Command);
Assert.Equal(ServerCommand.UninstallService, ServerCommandLine.Parse(["--uninstall-service"]).Command);
Assert.Equal(ServerCommand.HealthCheck, ServerCommandLine.Parse(["--healthcheck"]).Command);
Assert.Equal(ServerCommand.Help, ServerCommandLine.Parse(["/?"]).Command);
Assert.NotNull(ServerCommandLine.Parse(["--install-service", "--uninstall-service"]).Error);
Assert.Null(ServerCommandLine.Parse(["--service", "--service"]).Error);
}
[Test]
public void StatusReportsFollowTheServiceControlManagerRules()
{
var tracker = new ServiceStatusTracker();
var start = tracker.StartPending(60_000);
Assert.Equal((ServiceState.StartPending, 0u, 1u, 60_000u), (start.State, start.ControlsAccepted, start.CheckPoint, start.WaitHintMilliseconds));
Assert.Equal(2u, tracker.StartPending(60_000).CheckPoint);
var running = tracker.Running();
Assert.Equal((ServiceState.Running, ServiceStatusTracker.AcceptStop | ServiceStatusTracker.AcceptShutdown, 0u), (running.State, running.ControlsAccepted, running.CheckPoint));
Assert.Throws<InvalidOperationException>(() => tracker.Running());
Assert.Equal(1u, tracker.StopPending(35_000).CheckPoint);
Assert.Equal(2u, tracker.StopPending(35_000).CheckPoint);
var stopped = tracker.Stopped(0);
Assert.Equal((ServiceState.Stopped, 0u, 0u), (stopped.State, stopped.ControlsAccepted, stopped.CheckPoint));
Assert.Throws<InvalidOperationException>(() => tracker.StopPending(1));
Assert.Equal(1064u, new ServiceStatusTracker().Stopped(1064).ExitCode);
}
[Test]
public void AServiceFailureLeadsWithTheReasonTheServerGave()
{
var refused = new InvalidOperationException(@"C:\ProgramData\Chronos Server belongs to PC\ada, not to SYSTEM, Administrators or the account Chronos Server runs as.");
var text = ServiceEventLog.Describe("Chronos Server did not start:", refused);
Assert.True(text.StartsWith(@"Chronos Server did not start: C:\ProgramData\Chronos Server belongs to PC\ada", StringComparison.Ordinal), text);
Assert.Contains("System.InvalidOperationException", text);
// ReportEvent refuses a longer string: the text is cut, never between the halves of a surrogate pair.
var cut = ServiceEventLog.Describe("x", new InvalidOperationException(new string('a', ServiceEventLog.MaxLength)));
Assert.Equal(ServiceEventLog.MaxLength, cut.Length);
Assert.True(cut.EndsWith("a\u2026", StringComparison.Ordinal), cut[^5..]);
var pair = ServiceEventLog.Describe("x", new InvalidOperationException(new string('a', ServiceEventLog.MaxLength - 4) + "\uD83D\uDE00" + new string('b', 99)));
Assert.Equal(ServiceEventLog.MaxLength - 1, pair.Length);
Assert.True(pair.EndsWith("a\u2026", StringComparison.Ordinal), pair[^5..]);
}
[Test]
[WindowsOnly]
public void AServiceFailureReachesTheApplicationEventLog()
{
if (!OperatingSystem.IsWindows()) return;
// Written as a source of its own, so a test run never looks like a failed service in Event Viewer.
const string source = "Chronos.Server.Tests";
var marker = source + " " + Guid.NewGuid().ToString("N");
Assert.True(ServiceEventLog.Error(source, ServiceEventLog.StartFailed, marker), "the Application log takes the event");
var filter = $"*[System[Provider[@Name='{source}'] and EventID={ServiceEventLog.StartFailed}]]";
var query = new EventLogQuery("Application", PathType.LogName, filter) { ReverseDirection = true };
for (var attempt = 0; attempt < 50; attempt++)
{
using (var reader = new EventLogReader(query))
{
for (var read = 0; read < 100 && reader.ReadEvent() is { } record; read++)
{
using (record)
{
// The event's one string, which Event Viewer shows whole.
if (record.Properties.Count != 1 || record.Properties[0].Value as string != marker) continue;
Assert.Equal((byte?)2, record.Level, "an error");
return;
}
}
}
Thread.Sleep(100);
}
Assert.Fail($"No {source} event carries '{marker}'.");
}
[Test]
[WindowsOnly]
public void TheServiceIsRegisteredOnlyFromInsideProgramFiles()
{
if (!OperatingSystem.IsWindows()) return;
var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
Assert.True(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "Chronos", "Chronos.Server.exe")));
Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles));
Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles + " Tools\\Chronos"));
Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Chronos")));
Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "..", "Chronos")));
// The test build is not under Program Files: registering it is refused, naming the folder.
Assert.Contains(Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory), Assert.NotNull(ServiceInstaller.UnsafeLocation()));
}
[Test]
[WindowsOnly]
public void AnyFileOrdinaryUsersCanChangeIsFound()
{
if (!OperatingSystem.IsWindows()) return;
using var identity = WindowsIdentity.GetCurrent();
if (!new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) Assert.Inconclusive("registering a service needs an administrator");
var folder = new DirectoryInfo(context.CreateTempDirectory("program"));
File.WriteAllBytes(Path.Combine(folder.FullName, "Chronos.Server.exe"), [1]);
var satellite = new FileInfo(Path.Combine(folder.CreateSubdirectory("it").FullName, "Chronos.Core.resources.dll"));
File.WriteAllBytes(satellite.FullName, [1]);
// Like Program Files: administrators may change the folder, users only read it.
var locked = new DirectorySecurity();
locked.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
var everything = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
foreach (var account in new[] { new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), identity.User! })
locked.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl, everything, PropagationFlags.None, AccessControlType.Allow));
locked.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.ReadAndExecute, everything,
PropagationFlags.None, AccessControlType.Allow));
folder.SetAccessControl(locked);
Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: true));
// One satellite assembly users may replace is enough: the service would load it as SYSTEM.
var open = satellite.GetAccessControl();
open.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.Modify, AccessControlType.Allow));
satellite.SetAccessControl(open);
Assert.Equal(satellite.FullName, ServiceInstaller.FindChangeable(folder, recursive: true));
Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: false));
}
[Test]
[WindowsOnly]
public void TheDispatcherDeclinesAConsoleProcess()
{
if (!OperatingSystem.IsWindows()) return;
var built = false;
Assert.False(WindowsServiceHost.Run(() =>
{
built = true;
throw new InvalidOperationException("never built outside the SCM");
}));
Assert.False(built);
}
}
+41
View File
@@ -0,0 +1,41 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json.Serialization.Metadata;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Server.Tests;
/// <summary>Assertions and JSON helpers for API calls.</summary>
internal static class Http
{
/// <summary>The body of a successful response (an error response fails the test with its body).</summary>
public static async Task<T> ReadAsync<T>(this HttpResponseMessage response, JsonTypeInfo<T> type) where T : class
{
if (!response.IsSuccessStatusCode) Assert.Fail($"Expected success, got {(int)response.StatusCode}: {await response.Content.ReadAsStringAsync()}");
return Assert.NotNull(await response.Content.ReadFromJsonAsync(type));
}
/// <summary>Asserts the status, the <c>{ code, message, details }</c> body with <paramref name="code"/>, and the API header.</summary>
public static async Task<ApiError> ExpectErrorAsync(this HttpResponseMessage response, HttpStatusCode status, string code)
{
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(status, response.StatusCode, body);
Assert.Equal("1", response.Headers.GetValues(ApiVersion.Header).Single());
var error = Assert.NotNull(System.Text.Json.JsonSerializer.Deserialize(body, ProtocolJson.Default.ApiError));
Assert.Equal(code, error.Code, body);
Assert.False(string.IsNullOrWhiteSpace(error.Message), "message is empty");
return error;
}
public static async Task BytesEqualAsync(byte[] expected, Task<byte[]> actual)
{
var bytes = await actual;
Assert.BytesEqual(expected, bytes);
}
public static async Task ExpectAsync(this HttpResponseMessage response, HttpStatusCode status)
{
if (response.StatusCode != status) Assert.Fail($"Expected {(int)status}, got {(int)response.StatusCode}: {await response.Content.ReadAsStringAsync()}");
}
}
@@ -0,0 +1,139 @@
using System.Net;
using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.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.Parallelism = 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,454 @@
using System.Collections.Concurrent;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Processing;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using Chronos.Server.Jobs;
using Chronos.Testing;
namespace Chronos.Server.Tests.Jobs;
/// <summary>The desktop client's render node (managed encoders here) against the in-process server.</summary>
[Category("processing")]
public sealed class RenderNodeClientTests(TestContext context)
{
private const int Frames = 12;
private static readonly ExportSettings Mjpeg = new()
{
Preset = new Auto<string>().WithManual("mjpeg-avi"),
Overrides = new ExportOverrides { Width = 96, Height = 64 },
NameTemplate = "{title} - {codec}",
};
[Test]
public async Task ANodeClaimsRendersWithManagedEncodersAndUploadsTheResult()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
var sequenceId = await UploadSequenceAsync(editor, Photos());
var job = await CreateRenderAsync(server, editor, sequenceId);
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "studio-pc") { Token = token };
var cache = context.CreateTempDirectory("node");
await using var node = Node(client, cache);
Assert.True(await node.RunOnceAsync(context.Cancellation), "a job was claimed");
Assert.False(await node.RunOnceAsync(context.Cancellation), "the queue is empty");
var done = await JobApiTests.GetAsync(editor, job.Id);
Assert.Equal("done", done.State);
var render = (await server.Database.Renders.ListBySequenceAsync(sequenceId)).Single();
Assert.Equal(("studio-pc", "mjpeg", 96, 64), (render.ProducedBy, render.Codec, render.Width, render.Height));
var sequence = (await server.Database.Sequences.GetAsync(sequenceId))!;
var file = await File.ReadAllBytesAsync(Path.Combine(server.Options.ArchivePath, render.OutputPath));
Assert.Equal(("RIFF", "AVI "), (Encoding.ASCII.GetString(file, 0, 4), Encoding.ASCII.GetString(file, 8, 4)));
Assert.Equal($"{sequence.Folder}/exports/{sequence.DisplayTitle} - MJPEG.avi", render.OutputPath);
Assert.Equal(1, sequence.RenderedCount);
// Originals stay cached by content for the next job; the job's own folder is gone.
Assert.Count(Frames, Directory.GetFiles(Path.Combine(cache, "originals"), "*.jpg", SearchOption.AllDirectories));
Assert.False(Directory.EnumerateFileSystemEntries(Path.Combine(cache, "jobs")).Any(), "job folder removed");
}
[Test]
public async Task ANodeSkipsMissingFramesFetchesUnhashedOnesAndSendsTheProxiesAskedFor()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
var sequenceId = await UploadSequenceAsync(editor, Photos()[..3]);
await Uploads.UploadAsync(editor, [0, 0, 0, 24, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8, .. Uploads.Photo(2000, 9)], "IMG_0004.HEIC", sequenceId);
var frames = await server.Database.Frames.ListBySequenceAsync(sequenceId);
// Frame 1 is gone from the server, frame 2 was adopted and never hashed, frame 3 is damaged (the server could not
// decode it) and frame 4 is a HEIF the server cannot decode.
File.Delete(Path.Combine(server.Options.ArchivePath, frames[0].RelativePath));
await server.Database.Frames.UpdateFlagsAsync([frames[0].Id], FrameFlags.Missing, FrameFlags.None);
await server.Database.Frames.UpdateFlagsAsync([frames[2].Id, frames[3].Id], FrameFlags.Undecodable, FrameFlags.None);
await using (var session = await server.Database.Database.OpenAsync(context.Cancellation))
{
await session.ExecuteAsync("UPDATE frames SET sha256 = NULL WHERE id = $1", [frames[1].Id], context.Cancellation);
await session.ExecuteAsync("UPDATE frames SET format = $1 WHERE id = $2", [(int)ImageFileFormat.Heif, frames[3].Id], context.Cancellation);
}
var job = await CreateRenderAsync(server, editor, sequenceId);
var requests = new RecordPaths(new SocketsHttpHandler());
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "studio-pc", requests) { Token = token };
// This PC decodes HEIF (WIC with the HEIF extension on Windows).
await using var node = Node(client, context.CreateTempDirectory("node"), decoder: new ImageDecoder([new SolidHeif(), new ManagedDecoderProvider()]));
Assert.True(await node.RunOnceAsync(context.Cancellation), "a job was claimed");
var done = await JobApiTests.GetAsync(editor, job.Id);
Assert.Equal("done", done.State, done.Error);
Assert.DoesNotContain($"/api/v1/frames/{frames[0].Id}/original", requests.Paths);
Assert.Contains($"/api/v1/frames/{frames[1].Id}/original", requests.Paths);
// The damaged frame stays out, as in the server's own render; the HEIF renders from its original here.
Assert.DoesNotContain($"/api/v1/frames/{frames[2].Id}/original", requests.Paths);
Assert.Contains($"/api/v1/frames/{frames[3].Id}/original", requests.Paths);
var sequence = (await server.Database.Sequences.GetAsync(sequenceId))!;
var proxy = new ArchivePaths(server.Options.ArchivePath).Sequence(sequence.Folder).Proxy(frames[3].Index);
Assert.Equal(frames[3].CapturedAt, MetadataReader.Read(proxy).CapturedAt, "the proxy the server asked for, with the frame's capture time");
Assert.Equal((96, 64), MetadataReader.Read(proxy).OrientedSize);
}
[Test]
public async Task ANodeReportsWhyItCouldNotRender()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
// Uploads are opaque to the server's fake ingest: these "photos" decode to nothing.
var sequenceId = await UploadSequenceAsync(editor, [Uploads.Photo(4000, 1), Uploads.Photo(4000, 2)]);
var job = await CreateRenderAsync(server, editor, sequenceId);
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "studio-pc") { Token = token };
await using var node = Node(client, context.CreateTempDirectory("node"));
Assert.True(await node.RunOnceAsync(context.Cancellation), "a job was claimed");
var failed = await JobApiTests.GetAsync(editor, job.Id);
var first = (await server.Database.Frames.ListBySequenceAsync(sequenceId))[0];
Assert.Equal(("failed", Loc.L("Export.Render.FrameUnreadable", "1", first.FileName)), (failed.State, failed.Error));
Assert.Empty(await server.Database.Renders.ListBySequenceAsync(sequenceId));
}
[Test]
public async Task ANodeOffersOnlyEncodersWhoseOutputIsOneFile()
{
await using var server = await TestServer.StartAsync(context);
var (_, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "studio-pc") { Token = token };
await using var node = Node(client, context.CreateTempDirectory("node"));
var id = await node.RegisterAsync(context.Cancellation);
var registered = (await client.ListNodesAsync(context.Cancellation)).Single(n => n.Id == id);
Assert.SequenceEqual(["apng", "gif", "mjpeg"], registered.Encoders.Select(e => e.Codec).Order(StringComparer.Ordinal));
// Each encoder announces its own largest output, so the server matches job sizes per codec.
Assert.True(registered.Encoders.All(e => (e.MaxWidth, e.MaxHeight) == (65535, 65535)), "per-encoder limits");
}
[Test]
public async Task AStartedNodeRegistersBeatsClaimsAndStopsCleanly()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
var sequenceId = await UploadSequenceAsync(editor, Photos());
// A posted batch becomes one job per preset, so each output travels back on its own.
var job = await CreateRenderAsync(server, editor, sequenceId, Mjpeg with { Batch = ["gif-preview"] });
var gif = (await server.Database.Jobs.ListAsync(JobState.Queued, JobKind.Render)).Items.Single(j => j.Id != job.Id);
var claims = new CountClaims(new SocketsHttpHandler());
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "studio-pc", claims) { Token = token };
var cache = context.CreateTempDirectory("node");
// Claims only when started and after each job: between them only heartbeats reach the server.
var node = Node(client, cache, poll: TimeSpan.FromMinutes(5), heartbeat: TimeSpan.FromMilliseconds(100));
node.Start();
await JobApiTests.WaitForAsync(editor, job.Id, "done");
await JobApiTests.WaitForAsync(editor, gif.Id, "done");
// Past the claim that found the queue empty (the server touched the node before answering it), only heartbeats
// move the node's last sign of life.
await UntilAsync(() => Task.FromResult(claims.Answered >= 3), "the claim that found the queue empty");
var beat = (await server.Database.RenderNodes.ListAsync()).Single().LastHeartbeat;
await UntilAsync(async () => (await server.Database.RenderNodes.ListAsync()).Single().LastHeartbeat > beat, "a heartbeat");
Assert.Equal(3, claims.Answered, "no claim since the queue was empty");
await node.DisposeAsync();
Assert.True(node.Completion.IsCompleted, "stopped");
Assert.SequenceEqual(["gif", "mjpeg"], (await server.Database.Renders.ListBySequenceAsync(sequenceId)).Select(r => r.Codec!).Order(StringComparer.Ordinal));
Assert.False(Directory.EnumerateFileSystemEntries(Path.Combine(cache, "jobs")).Any(), "job folder removed");
}
[Test]
public async Task ANodeRestartedDuringAJobDoesNotLeaveItRunning()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
var sequenceId = await UploadSequenceAsync(editor, Photos());
var job = await CreateRenderAsync(server, editor, sequenceId);
var cache = context.CreateTempDirectory("node");
// The first run stops while downloading (sign-out, exit): the job is still running on the server.
var held = new HoldDownloads(new SocketsHttpHandler());
using (var slow = new ChronosClient(server.HttpBase, new CertificatePinning([]), "studio-pc", held) { Token = token })
{
await using var first = Node(slow, cache);
using var stopping = new CancellationTokenSource();
var run = first.RunOnceAsync(stopping.Token);
await held.Holding.Task.WaitAsync(TimeSpan.FromSeconds(30));
Assert.Equal("running", (await JobApiTests.GetAsync(editor, job.Id)).State);
await stopping.CancelAsync();
Assert.True(await run, "the job was claimed");
}
Assert.Equal("running", (await JobApiTests.GetAsync(editor, job.Id)).State);
// Started again within the heartbeat timeout under the same name: registering gives the job back to the queue.
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "studio-pc") { Token = token };
await using var second = Node(client, cache);
Assert.True(await second.RunOnceAsync(context.Cancellation), "the abandoned job was claimed again");
var done = await JobApiTests.GetAsync(editor, job.Id);
Assert.Equal("done", done.State);
Assert.Contains("Render node studio-pc restarted.", done.LogTail);
Assert.Count(1, await server.Database.Renders.ListBySequenceAsync(sequenceId));
}
[Test]
public async Task ADroppedDownloadIsResumedNotFailed()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
var sequenceId = await UploadSequenceAsync(editor, Photos());
var job = await CreateRenderAsync(server, editor, sequenceId);
var cut = new CutFirst("original", new SocketsHttpHandler());
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "studio-pc", cut) { Token = token };
await using var node = Node(client, context.CreateTempDirectory("node"));
Assert.True(await node.RunOnceAsync(context.Cancellation), "a job was claimed");
Assert.Equal("done", (await JobApiTests.GetAsync(editor, job.Id)).State);
Assert.Equal(1, cut.Cuts);
Assert.Equal(1, cut.Resumed);
}
[Test]
public async Task ADroppedProxyIsFetchedWholeAgain()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
var photos = Photos();
var sequence = (await server.Database.Sequences.GetAsync(await UploadSequenceAsync(editor, photos)))!;
// The archive has proxies of every frame (the test locator serves <folder>/proxies/NNNN.jpg).
var proxies = Path.Combine(server.Options.ArchivePath, sequence.Folder, "proxies");
Directory.CreateDirectory(proxies);
foreach (var frame in await server.Database.Frames.ListBySequenceAsync(sequence.Id))
await File.WriteAllBytesAsync(Path.Combine(proxies, $"{frame.Index:D4}.jpg"), photos[frame.Index]);
await server.Database.Sequences.UpsertAsync(sequence with { Status = sequence.Status | SequenceStatus.ProxiesBuilt });
var job = await JobApiTests.CreateAsync(editor, "render", sequence.Id, ProcessingJobs.Render(sequence, Mjpeg, 96, 64, useProxies: true).ParametersJson);
var cut = new CutFirst("proxy", new SocketsHttpHandler());
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "studio-pc", cut) { Token = token };
var cache = context.CreateTempDirectory("node");
await using var node = Node(client, cache);
Assert.True(await node.RunOnceAsync(context.Cancellation), "a job was claimed");
Assert.Equal("done", (await JobApiTests.GetAsync(editor, job.Id)).State);
// Nothing verifies a proxy against a hash, so a retry never appends to what the dropped attempt left.
Assert.Equal((1, 0), (cut.Cuts, cut.Resumed));
Assert.False(Directory.Exists(Path.Combine(cache, "originals")), "no original needed");
}
[Test]
public async Task ANodeLeavesARenderTheServerStartedToTheServer()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
var sequenceId = await UploadSequenceAsync(editor, Photos());
var job = await CreateRenderAsync(server, editor, sequenceId);
// The server's own engine was rendering it when it crashed: its checkpoint names its leftovers.
Assert.NotNull(await server.Database.Jobs.TryClaimAsync(job.Id, "server:test#0"));
Assert.True(await server.Database.Jobs.UpdateProgressAsync(job.Id, 3, 12, null, null, """{"done":[],"pending":0}""", null));
await server.Database.Jobs.RequeueRunningAsync("server:test");
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "studio-pc") { Token = token };
await using var node = Node(client, context.CreateTempDirectory("node"));
Assert.False(await node.RunOnceAsync(context.Cancellation), "nothing for the node");
Assert.Equal("queued", (await JobApiTests.GetAsync(editor, job.Id)).State);
}
[Test]
public async Task ANodeRefusesABatchItCannotSendBack()
{
await using var server = await TestServer.StartAsync(context);
var (editor, user, token) = await server.UserAsync("alberto", "editor", renderNode: true);
var sequence = (await server.Database.Sequences.GetAsync(await UploadSequenceAsync(editor, Photos())))!;
// Queued as one job (an older server did not split batches).
var request = ProcessingJobs.Render(sequence, Mjpeg with { Batch = ["gif-preview"] }, 96, 64);
var job = await server.Services.GetRequiredService<JobEngineHost>().Engine
.EnqueueAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority, user.Id);
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "studio-pc") { Token = token };
await using var node = Node(client, context.CreateTempDirectory("node"));
Assert.True(await node.RunOnceAsync(context.Cancellation), "a job was claimed");
var failed = await JobApiTests.GetAsync(editor, job.Id);
Assert.Equal(("failed", Loc.L("Errors.Render.NodeBatch")), (failed.State, failed.Error));
Assert.Empty(await server.Database.Renders.ListBySequenceAsync(sequence.Id));
}
[Test]
public async Task ADownloadThatEndedBeforeItsCheckIsVerifiedNotFetchedAgain()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
var photos = Photos();
var sequenceId = await UploadSequenceAsync(editor, photos);
await CreateRenderAsync(server, editor, sequenceId, Mjpeg);
// A crash after the last byte arrived but before the hash check left a complete part file.
var cache = context.CreateTempDirectory("node");
var sha = Uploads.Sha(photos[0]);
var part = Path.Combine(cache, "originals", sha[..2], sha + ".jpg.part");
Directory.CreateDirectory(Path.GetDirectoryName(part)!);
await File.WriteAllBytesAsync(part, photos[0]);
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "studio-pc") { Token = token };
await using var node = Node(client, cache);
Assert.True(await node.RunOnceAsync(context.Cancellation), "a job was claimed");
Assert.Count(1, await server.Database.Renders.ListBySequenceAsync(sequenceId));
Assert.FileMissing(part);
Assert.FileExists(part[..^".part".Length]);
}
private static RenderNodeClient Node(ChronosClient client, string cache, TimeSpan? poll = null, TimeSpan? heartbeat = null, ImageDecoder? decoder = null) =>
new(client, new ProcessingOptions { Archive = new ArchiveServiceOptions { Decoder = decoder ?? DecoderFactory.CreateServer() } },
new RenderNodeOptions
{
ClientName = "studio-pc",
CacheDirectory = cache,
ProgressInterval = TimeSpan.Zero,
PollInterval = poll ?? TimeSpan.FromSeconds(10),
HeartbeatInterval = heartbeat ?? TimeSpan.FromSeconds(30),
RetryDelay = TimeSpan.FromMilliseconds(10),
});
/// <summary>Holds every frame download until the request is cancelled.</summary>
private sealed class HoldDownloads(HttpMessageHandler inner) : DelegatingHandler(inner)
{
public TaskCompletionSource Holding { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.RequestUri!.AbsolutePath.StartsWith("/api/v1/frames/", StringComparison.Ordinal))
{
Holding.TrySetResult();
await Task.Delay(Timeout.Infinite, cancellationToken);
}
return await base.SendAsync(request, cancellationToken);
}
}
/// <summary>Drops the connection halfway through the first resource of <paramref name="kind"/> it serves; counts the downloads resumed with a range.</summary>
private sealed class CutFirst(string kind, HttpMessageHandler inner) : DelegatingHandler(inner)
{
private int _cuts;
private int _resumed;
public int Cuts => _cuts;
public int Resumed => _resumed;
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Headers.Range is not null) Interlocked.Increment(ref _resumed);
var response = await base.SendAsync(request, cancellationToken);
if (!request.RequestUri!.AbsolutePath.EndsWith("/" + kind, StringComparison.Ordinal) || Interlocked.CompareExchange(ref _cuts, 1, 0) != 0)
return response;
var body = await response.Content.ReadAsByteArrayAsync(cancellationToken);
var content = new StreamContent(new CutStream(body, body.Length / 2));
foreach (var header in response.Content.Headers) content.Headers.TryAddWithoutValidation(header.Key, header.Value);
response.Content = content;
return response;
}
}
/// <summary>Records the path of every request.</summary>
private sealed class RecordPaths(HttpMessageHandler inner) : DelegatingHandler(inner)
{
private readonly ConcurrentQueue<string> _paths = new();
public IReadOnlyCollection<string> Paths => _paths;
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
_paths.Enqueue(request.RequestUri!.AbsolutePath);
return base.SendAsync(request, cancellationToken);
}
}
/// <summary>Decodes every HEIF as a mid-grey 96 × 64 frame, as a native HEIF decoder would decode a real one.</summary>
private sealed class SolidHeif : IImageDecoderProvider
{
public string Name => "heif-test";
public DecodeTier? TierFor(ImageFileFormat format) => format == ImageFileFormat.Heif ? DecodeTier.Native : null;
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default)
{
var image = new ImageBuffer(96, 64);
for (var c = 0; c < 3; c++) image.Plane(c).Fill(0.2f);
return new DecodedImage(image, DecodeTier.Native, Name, 96, 64);
}
}
/// <summary>Counts the node's claims the server answered.</summary>
private sealed class CountClaims(HttpMessageHandler inner) : DelegatingHandler(inner)
{
private int _answered;
public int Answered => Volatile.Read(ref _answered);
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
if (request.RequestUri!.AbsolutePath.EndsWith("/claim", StringComparison.Ordinal)) Interlocked.Increment(ref _answered);
return response;
}
}
/// <summary>The first <c>cut</c> bytes, then a reset connection.</summary>
private sealed class CutStream(byte[] data, int cut) : MemoryStream(data, 0, cut)
{
public override int Read(byte[] buffer, int offset, int count) => Check(base.Read(buffer, offset, count));
public override int Read(Span<byte> buffer) => Check(base.Read(buffer));
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) =>
Check(await base.ReadAsync(buffer, cancellationToken));
private static int Check(int read) => read > 0 ? read : throw new IOException("Connection reset by peer");
}
private static async Task UntilAsync(Func<Task<bool>> condition, string what)
{
var until = DateTime.UtcNow.AddSeconds(30);
while (!await condition())
{
if (DateTime.UtcNow > until) Assert.Fail("Timed out waiting for " + what);
await Task.Delay(25);
}
}
private static async Task<JobDto> CreateRenderAsync(TestServer server, HttpClient editor, Guid sequenceId, ExportSettings? export = null)
{
var sequence = (await server.Database.Sequences.GetAsync(sequenceId))!;
var request = ProcessingJobs.Render(sequence, export ?? Mjpeg, 96, 64);
return await JobApiTests.CreateAsync(editor, "render", sequenceId, request.ParametersJson);
}
/// <summary>Uploads the photos as IMG_0001.JPG… into one new sequence; returns its id.</summary>
private static async Task<Guid> UploadSequenceAsync(HttpClient client, IReadOnlyList<byte[]> photos)
{
Guid? sequenceId = null;
for (var i = 0; i < photos.Count; i++)
sequenceId = (await Uploads.UploadAsync(client, photos[i], $"IMG_{i + 1:0000}.JPG", sequenceId)).SequenceId;
return sequenceId!.Value;
}
private static List<byte[]> Photos()
{
var scene = SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = Frames, StartEv = 0.5, EndEv = -0.5 });
var photos = new List<byte[]>(Frames);
for (var i = 0; i < Frames; i++)
{
using var image = scene.Render(i);
photos.Add(JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90 }));
}
return photos;
}
}
@@ -0,0 +1,157 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using Chronos.Server.Jobs;
using Chronos.Testing;
namespace Chronos.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 EachEncoderTakesOnlyJobsWithinItsOwnSizeLimit()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, _) = await server.UserAsync("alberto", "editor", renderNode: true);
var sequence = await JobApiTests.CreateSequenceAsync(editor);
// The software H.264 encoder stops at 4096 px although the node's MJPEG encoder writes far larger frames.
using var registered = await editor.PostAsJsonAsync("/api/v1/nodes/register", new RegisterNodeRequest("studio-pc",
[new NodeEncoder("h264", "H.264 Encoder MFT", false, false, 4096, 2304), new NodeEncoder("mjpeg", "Managed MJPEG", false, false, 65535, 65535)],
65535, 65535), ProtocolJson.Default.RegisterNodeRequest);
var node = await registered.ReadAsync(ProtocolJson.Default.RenderNodeDto);
Assert.Equal((4096, 2304), (node.Encoders[0].MaxWidth, node.Encoders[0].MaxHeight));
await JobApiTests.CreateAsync(editor, "render", sequence, H264Job(6144, 3456));
using (var none = await editor.PostAsync($"/api/v1/nodes/{node.Id}/claim", null)) await none.ExpectAsync(HttpStatusCode.NoContent);
var uhd = await JobApiTests.CreateAsync(editor, "render", sequence, H264Job(3840, 2160));
using var claim = await editor.PostAsync($"/api/v1/nodes/{node.Id}/claim", null);
Assert.Equal(uhd.Id, (await claim.ReadAsync(ProtocolJson.Default.ClaimedJob)).Job.Id);
}
[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 ChronosClient(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 string H264Job(int width, int height) => JsonSerializer.Serialize(
new RenderJobParameters("H.264", """{"preset":{"isAuto":false,"manual":"4k-h264"}}""", "h264", width, height, UseProxies: false, null),
ProtocolJson.Default.RenderJobParameters);
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);
}
}
@@ -0,0 +1,102 @@
using System.Net;
using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Jobs;
using Chronos.Protocol;
using Chronos.Server.Configuration;
using Chronos.Server.Tests.Jobs;
using Chronos.Testing;
namespace Chronos.Server.Tests.Postgres;
/// <summary>The server on PostgreSQL (<c>CHRONOS_TEST_PG</c>), each test in a private schema.</summary>
[Category("server")]
[RequiresEnvironment("CHRONOS_TEST_PG")]
public sealed class PostgresServerTests(TestContext context)
{
[Test]
public async Task SignInUploadSyncAndJobsWorkOnPostgres()
{
await using var schema = await Schema.CreateAsync(context);
var handler = new BlockingJobHandler(JobKind.Thumbs);
await using var server = await TestServer.StartAsync(context, o =>
{
o.Database = DatabaseKind.Postgres;
o.DbConnectionString = schema.ConnectionString;
o.ChunkSizeBytes = 64 * 1024;
}, s => s.AddSingleton<IJobHandler>(handler));
Assert.Equal(Dialect.Postgres, server.Database.Dialect);
var (editor, _, _) = await server.UserAsync("alberto", "editor", quotaBytes: 10_000_000);
var data = Uploads.Photo(150_000, 71);
var frame = await Uploads.UploadAsync(editor, data, sessionKey: "pg");
using (var manifest = await editor.GetAsync($"/api/v1/sequences/{frame.SequenceId}/manifest"))
Assert.Equal(Uploads.Sha(data), (await manifest.ReadAsync(ProtocolJson.Default.SequenceManifest)).Frames.Single().Sha256);
using (var me = await editor.GetAsync("/api/v1/auth/me")) Assert.Equal(data.Length, (await me.ReadAsync(ProtocolJson.Default.UserDto)).UsedBytes);
using (var stale = await editor.PatchAsJsonAsync($"/api/v1/sequences/{frame.SequenceId}", new UpdateSequenceRequest(null, ["pg"], null, null, "{}", 99),
ProtocolJson.Default.UpdateSequenceRequest))
await stale.ExpectErrorAsync(HttpStatusCode.Conflict, "settings_conflict");
// Uploading queued a background thumbnail job for the sequence; it runs on the server's engine.
using var queued = await editor.GetAsync("/api/v1/jobs?kind=thumbs");
var job = (await queued.ReadAsync(ProtocolJson.Default.PageJobDto)).Items.Single();
await JobApiTests.WaitForAsync(editor, job.Id, "running");
handler.Release();
await JobApiTests.WaitForAsync(editor, job.Id, "done");
var admin = await server.AdminAsync();
using var dashboard = await admin.GetAsync("/api/v1/server/dashboard");
Assert.True((await dashboard.ReadAsync(ProtocolJson.Default.DashboardDto)).Database.StartsWith("PostgreSQL ", StringComparison.Ordinal));
using var health = await server.Client.GetAsync("/health");
Assert.Equal("ok", (await health.ReadAsync(ProtocolJson.Default.HealthStatus)).Checks["database"]);
}
[Test]
public async Task TheManifestListsTheFramesOfOneFramesVersionOnPostgres()
{
await using var schema = await Schema.CreateAsync(context);
await using var server = await TestServer.StartAsync(context, o =>
{
o.Database = DatabaseKind.Postgres;
o.DbConnectionString = schema.ConnectionString;
});
Assert.Equal(Dialect.Postgres, server.Database.Dialect);
await Api.SequenceTests.FramesOfOneVersionAsync(server);
}
/// <summary>A throw-away schema on the test server, selected through <c>Search Path</c>.</summary>
private sealed class Schema : IAsyncDisposable
{
private readonly IDatabase _admin;
private readonly string _name;
private Schema(IDatabase admin, string name, string connectionString)
{
_admin = admin;
_name = name;
ConnectionString = connectionString;
}
public string ConnectionString { get; }
public static async Task<Schema> CreateAsync(TestContext context)
{
var baseConnection = Environment.GetEnvironmentVariable("CHRONOS_TEST_PG")!;
var admin = DatabaseFactory.Open(DatabaseOptions.Postgres(baseConnection));
var name = "chronos_s_" + Guid.NewGuid().ToString("N")[..16];
await using (var session = await admin.OpenAsync(context.Cancellation))
await session.ExecuteScriptAsync($"CREATE SCHEMA {name}", context.Cancellation);
return new Schema(admin, name, baseConnection.TrimEnd(';', ' ') + $";Search Path={name}");
}
public async ValueTask DisposeAsync()
{
await using (var session = await _admin.OpenAsync(CancellationToken.None))
await session.ExecuteScriptAsync($"DROP SCHEMA IF EXISTS {_name} CASCADE", CancellationToken.None);
await _admin.DisposeAsync();
}
}
}
+8
View File
@@ -0,0 +1,8 @@
using Chronos.Testing;
namespace Chronos.Server.Tests;
internal static class TestMain
{
public static Task<int> Main(string[] args) => TestRunner.RunAsync(args, typeof(TestMain).Assembly);
}
+20
View File
@@ -0,0 +1,20 @@
using Chronos.Core.Analysis.Deep;
namespace Chronos.Server.Tests;
/// <summary>Deep-analysis reports as a server keeps them in <c>.chronos/analysis.json</c>.</summary>
internal static class Reports
{
/// <summary>A report of <paramref name="frames"/> frames that found <paramref name="undecodable"/> unreadable and measured nothing else.</summary>
public static DeepAnalysisReport Minimal(int frames, params int[] undecodable) => new()
{
FrameCount = frames,
Flicker = new FlickerSummary(0, 0, null, 0, 0, 1),
Exposure = new ExposureSummary(0, 0, null, null, 0, []),
WhiteBalance = new WhiteBalanceSummary(0, 0, null, null),
Shake = new ShakeSummary(0, 0, 0, 0, false, 0),
Motion = new MotionSummary(0, null, null, null),
Sky = new SkySummary(DayNight.Unknown, 0, 0, 0, null, false, null),
Issues = new FrameIssues(undecodable, [], [], [], []),
};
}
@@ -0,0 +1,227 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Server.Tests.Security;
[Category("server")]
public sealed class AuthTests(TestContext context)
{
[Test]
public async Task BootstrapAdminMustChangePasswordBeforeAnythingElse()
{
await using var server = await TestServer.StartAsync(context);
var login = await server.LoginAsync("admin", TestServer.AdminPassword);
Assert.True(login.MustChangePassword);
Assert.Equal("admin", login.User.Role);
var client = server.NewClient(login.Token);
using (var blocked = await client.GetAsync("/api/v1/users")) await blocked.ExpectErrorAsync(HttpStatusCode.Forbidden, "password_change_required");
using (var me = await client.GetAsync("/api/v1/auth/me")) await me.ExpectAsync(HttpStatusCode.OK);
using (var weak = await client.PostAsJsonAsync("/api/v1/auth/password", new ChangePasswordRequest(TestServer.AdminPassword, "short"),
ProtocolJson.Default.ChangePasswordRequest))
await weak.ExpectErrorAsync(HttpStatusCode.BadRequest, "weak_password");
using (var changed = await client.PostAsJsonAsync("/api/v1/auth/password", new ChangePasswordRequest(TestServer.AdminPassword, TestServer.Password),
ProtocolJson.Default.ChangePasswordRequest))
await changed.ExpectAsync(HttpStatusCode.NoContent);
using var users = await client.GetAsync("/api/v1/users");
await users.ExpectAsync(HttpStatusCode.OK);
Assert.Count(1, await users.ReadAsync(ProtocolJson.Default.ListUserSummaryDto));
}
[Test]
public async Task BootstrapWithoutPasswordWritesItToAFileNeverToTheLog()
{
await using var server = await TestServer.StartAsync(context, o => o.AdminPassword = null);
var file = Path.Combine(server.Options.DataPath, "initial-admin-password.txt");
Assert.FileExists(file);
var password = File.ReadAllText(file).Trim();
if (!OperatingSystem.IsWindows()) Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(file));
var login = await server.LoginAsync("admin", password);
Assert.True(login.MustChangePassword);
foreach (var log in Directory.EnumerateFiles(server.Options.LogPath))
{
using var reader = new StreamReader(new FileStream(log, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
Assert.False((await reader.ReadToEndAsync()).Contains(password, StringComparison.Ordinal), "the password reached the log");
}
var client = server.NewClient(login.Token);
using var changed = await client.PostAsJsonAsync("/api/v1/auth/password", new ChangePasswordRequest(password, TestServer.Password),
ProtocolJson.Default.ChangePasswordRequest);
await changed.ExpectAsync(HttpStatusCode.NoContent);
Assert.FileMissing(file);
}
[Test]
public async Task WrongPasswordAndUnknownUserFailAlike()
{
await using var server = await TestServer.StartAsync(context);
using var wrong = await server.Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", "not-the-password", "tests"), ProtocolJson.Default.LoginRequest);
var a = await wrong.ExpectErrorAsync(HttpStatusCode.Unauthorized, "invalid_credentials");
using var unknown = await server.Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("nobody", "not-the-password", "tests"), ProtocolJson.Default.LoginRequest);
var b = await unknown.ExpectErrorAsync(HttpStatusCode.Unauthorized, "invalid_credentials");
Assert.Equal(a.Message, b.Message);
}
[Test]
public async Task RepeatedFailuresLockTheAccountNameEvenWithTheRightPassword()
{
await using var server = await TestServer.StartAsync(context, o =>
{
o.LoginAttemptsPerMinute = 100;
o.LockoutThreshold = 3;
});
for (var i = 0; i < 3; i++)
{
using var failed = await server.Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", "wrong-password-x", "tests"), ProtocolJson.Default.LoginRequest);
await failed.ExpectErrorAsync(HttpStatusCode.Unauthorized, "invalid_credentials");
}
using var locked = await server.Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", TestServer.AdminPassword, "tests"), ProtocolJson.Default.LoginRequest);
await locked.ExpectErrorAsync(HttpStatusCode.TooManyRequests, "account_locked");
Assert.True(locked.Headers.RetryAfter?.Delta > TimeSpan.Zero);
for (var i = 0; i < 3; i++)
(await server.Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("ghost", "wrong-password-x", "tests"), ProtocolJson.Default.LoginRequest)).Dispose();
using var ghost = await server.Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("ghost", "wrong-password-x", "tests"), ProtocolJson.Default.LoginRequest);
await ghost.ExpectErrorAsync(HttpStatusCode.TooManyRequests, "account_locked");
}
[Test]
public async Task SignInsAreRateLimitedPerAddress()
{
await using var server = await TestServer.StartAsync(context, o => o.LoginAttemptsPerMinute = 5);
for (var i = 0; i < 5; i++)
(await server.Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("user" + i, "wrong-password-x", "tests"), ProtocolJson.Default.LoginRequest)).Dispose();
using var limited = await server.Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", TestServer.AdminPassword, "tests"), ProtocolJson.Default.LoginRequest);
await limited.ExpectErrorAsync(HttpStatusCode.TooManyRequests, "rate_limited");
}
[Test]
public async Task LogoutRevokesTheToken()
{
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
using (var me = await admin.GetAsync("/api/v1/auth/me")) await me.ExpectAsync(HttpStatusCode.OK);
using (var logout = await admin.PostAsync("/api/v1/auth/logout", null)) await logout.ExpectAsync(HttpStatusCode.NoContent);
using var after = await admin.GetAsync("/api/v1/auth/me");
await after.ExpectErrorAsync(HttpStatusCode.Unauthorized, "unauthorized");
Assert.Equal("Bearer", after.Headers.WwwAuthenticate.Single().Scheme);
}
[Test]
public async Task TokensExpireUnlessUsedWithinTheirLifetime()
{
var clock = new ManualTimeProvider();
await using var server = await TestServer.StartAsync(context, o => o.TokenLifetimeDays = 30, s => s.AddSingleton<TimeProvider>(clock));
var admin = await server.AdminAsync();
clock.Advance(TimeSpan.FromDays(20));
using (var used = await admin.GetAsync("/api/v1/auth/me")) await used.ExpectAsync(HttpStatusCode.OK);
clock.Advance(TimeSpan.FromDays(20));
using (var slid = await admin.GetAsync("/api/v1/auth/me")) await slid.ExpectAsync(HttpStatusCode.OK);
clock.Advance(TimeSpan.FromDays(31));
using var expired = await admin.GetAsync("/api/v1/auth/me");
await expired.ExpectErrorAsync(HttpStatusCode.Unauthorized, "unauthorized");
}
[Test]
public async Task TokensAreStoredOnlyAsHashes()
{
await using var server = await TestServer.StartAsync(context);
var login = await server.LoginAsync("admin", TestServer.AdminPassword);
await using var session = await server.Database.Database.OpenAsync(context.Cancellation);
var hashes = new List<string>();
await foreach (var row in session.QueryAsync("SELECT token_hash FROM tokens", [], context.Cancellation)) hashes.Add(row.GetString(0));
Assert.Contains(Chronos.Server.Security.TokenService.HashOf(login.Token!), hashes);
Assert.DoesNotContain(login.Token!, hashes);
}
[Test]
public async Task DisablingAUserEndsTheirSessions()
{
await using var server = await TestServer.StartAsync(context);
var (editor, user, _) = await server.UserAsync("giulia", "editor");
var admin = await server.AdminAsync();
using (var disable = await admin.PatchAsJsonAsync($"/api/v1/users/{user.Id}", new UpdateUserRequest(null, null, null, true, null), ProtocolJson.Default.UpdateUserRequest))
await disable.ExpectAsync(HttpStatusCode.OK);
using var me = await editor.GetAsync("/api/v1/auth/me");
await me.ExpectErrorAsync(HttpStatusCode.Unauthorized, "unauthorized");
using var login = await server.Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("giulia", TestServer.Password, "tests"), ProtocolJson.Default.LoginRequest);
await login.ExpectErrorAsync(HttpStatusCode.Unauthorized, "invalid_credentials");
}
[Test]
public async Task PermissionsSeparateMissingSignInFromMissingRights()
{
await using var server = await TestServer.StartAsync(context);
using (var anonymous = await server.Client.GetAsync("/api/v1/users")) await anonymous.ExpectErrorAsync(HttpStatusCode.Unauthorized, "unauthorized");
using (var anonymousSequences = await server.Client.GetAsync("/api/v1/sequences")) await anonymousSequences.ExpectErrorAsync(HttpStatusCode.Unauthorized, "unauthorized");
var (viewer, _, _) = await server.UserAsync("marco", "viewer");
using (var users = await viewer.GetAsync("/api/v1/users")) await users.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var sequences = await viewer.GetAsync("/api/v1/sequences")) await sequences.ExpectAsync(HttpStatusCode.OK);
using (var upload = await viewer.PostAsJsonAsync("/api/v1/uploads", new StartUploadRequest(null, "a.jpg", 10, new string('a', 64), null, null),
ProtocolJson.Default.StartUploadRequest))
await upload.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var settings = await viewer.GetAsync("/api/v1/server/settings")) await settings.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
using (var start = await uploader.PostAsJsonAsync("/api/v1/uploads", new StartUploadRequest(null, "a.jpg", 10, new string('a', 64), null, null),
ProtocolJson.Default.StartUploadRequest))
await start.ExpectAsync(HttpStatusCode.Created);
using var edit = await uploader.PatchAsJsonAsync($"/api/v1/sequences/{Guid.NewGuid()}", new UpdateSequenceRequest("x", null, null, null, null, null),
ProtocolJson.Default.UpdateSequenceRequest);
await edit.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
}
[Test]
public async Task CookieSessionsNeedTheCsrfHeaderForChanges()
{
await using var server = await TestServer.StartAsync(context);
await server.AdminAsync();
var cookies = new CookieContainer();
var browser = server.NewCookieClient(cookies);
using (var login = await browser.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", TestServer.Password, "admin-web", Cookie: true),
ProtocolJson.Default.LoginRequest))
{
await login.ExpectAsync(HttpStatusCode.OK);
Assert.Null((await login.ReadAsync(ProtocolJson.Default.LoginResponse)).Token);
var session = login.Headers.GetValues("Set-Cookie").Single(c => c.StartsWith("chronos_session=", StringComparison.Ordinal));
Assert.Contains("httponly", session.ToLowerInvariant());
Assert.Contains("secure", session.ToLowerInvariant());
Assert.Contains("samesite=strict", session.ToLowerInvariant());
}
using (var me = await browser.GetAsync("/api/v1/auth/me")) await me.ExpectAsync(HttpStatusCode.OK);
using (var forged = await browser.PostAsJsonAsync("/api/v1/sequences", new CreateSequenceRequest("x", null), ProtocolJson.Default.CreateSequenceRequest))
await forged.ExpectErrorAsync(HttpStatusCode.Forbidden, "csrf_failed");
using (var wrong = new HttpRequestMessage(HttpMethod.Post, "/api/v1/sequences") { Content = JsonContent.Create(new CreateSequenceRequest("x", null), ProtocolJson.Default.CreateSequenceRequest) })
{
wrong.Headers.Add("X-CSRF-Token", "not-the-token");
using var response = await browser.SendAsync(wrong);
await response.ExpectErrorAsync(HttpStatusCode.Forbidden, "csrf_failed");
}
var csrf = cookies.GetCookies(server.HttpsBase!)["chronos_csrf"]!.Value;
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/sequences") { Content = JsonContent.Create(new CreateSequenceRequest("x", null), ProtocolJson.Default.CreateSequenceRequest) };
request.Headers.Add("X-CSRF-Token", csrf);
using var created = await browser.SendAsync(request);
await created.ExpectAsync(HttpStatusCode.Created);
}
[Test]
public async Task ErrorsHaveTheApiShapeAndHeader()
{
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
using (var missing = await server.Client.GetAsync("/api/v1/nothing-here")) await missing.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
using (var badJson = await admin.PostAsync("/api/v1/sequences", new StringContent("{ not json", MediaTypeHeaderValue.Parse("application/json"))))
await badJson.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request");
using (var badGuid = await admin.GetAsync($"/api/v1/sequences/{Guid.NewGuid()}")) await badGuid.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
using var italian = new HttpRequestMessage(HttpMethod.Get, "/api/v1/users");
italian.Headers.AcceptLanguage.ParseAdd("it-IT");
using var response = await server.Client.SendAsync(italian);
var error = await response.ExpectErrorAsync(HttpStatusCode.Unauthorized, "unauthorized");
Assert.Equal("Accedi per continuare.", error.Message);
}
}
@@ -0,0 +1,402 @@
using System.Net;
using System.Security.Cryptography;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using Chronos.Server.Jobs;
using Chronos.Server.Storage;
using Chronos.Testing;
using UploadState = Chronos.Data.Repositories.UploadState;
namespace Chronos.Server.Tests.Storage;
/// <summary>The production composition: uploads committed by the real archive engine, thumbnails built by its job.</summary>
[Category("server")]
public sealed class ArchiveModuleTests(TestContext context)
{
[Test]
public async Task UploadsLandInTheArchiveLayoutAndGetThumbnails()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var photo = Photo();
var frame = await Uploads.UploadAsync(editor, photo, "IMG_0001.JPG", sessionKey: "roof");
var row = Assert.NotNull(await server.Database.Frames.GetAsync(frame.FrameId));
var sequence = Assert.NotNull(await server.Database.Sequences.GetAsync(frame.SequenceId));
var paths = new ArchivePaths(server.Options.ArchivePath).Sequence(sequence.Folder);
Assert.True(File.Exists(paths.ManifestPath), "sequence.json");
Assert.SequenceEqual(photo, await File.ReadAllBytesAsync(Path.Combine(server.Options.ArchivePath, row.RelativePath)));
Assert.Count(0, Directory.GetFiles(Path.Combine(server.Options.ArchivePath, ".chronos", "staging")));
// The commit queues a thumbnail job; its handler comes from the archive module.
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while (true)
{
using var thumb = await editor.GetAsync($"/api/v1/frames/{frame.FrameId}/thumb");
if (thumb.StatusCode == HttpStatusCode.OK)
{
var jpeg = await thumb.Content.ReadAsByteArrayAsync();
Assert.True(jpeg is [0xFF, 0xD8, ..], "a JPEG thumbnail");
break;
}
Assert.True(DateTime.UtcNow < until, $"thumbnail not built: {(int)thumb.StatusCode}");
await Task.Delay(100);
}
}
[Test]
public async Task AServerOnSqliteBacksUpItsIndexOnStart()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var backups = Path.Combine(server.Options.DataPath, "backups");
// No copy yet, so the first one is made at once (BRIEF §6.2), named after the index it copies.
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while (!Directory.Exists(backups) || Directory.GetFiles(backups, "*.db").Length == 0)
{
Assert.True(DateTime.UtcNow < until, "no backup of the index");
await Task.Delay(50);
}
var path = Assert.NotNull(((Chronos.Data.Sqlite.SqliteDatabase)server.Database.Database).Path);
var backup = Chronos.Data.DatabaseBackups.List(backups, path).Single();
var summary = await Chronos.Data.DatabaseBackups.SummarizeBackupAsync(backup.Path, context.CreateTempDirectory("scratch"), context.Cancellation);
Assert.Equal(server.Database.SchemaVersion, summary.SchemaVersion);
}
[Test]
public async Task PhotosAlreadyInTheArchiveAndAddedLaterAreIndexedByPollingWithThumbnailsAndProxies()
{
var photo = Photo();
// An adopted folder that already holds photos.
await using var server = await TestServer.StartAsync(context, options =>
{
Directory.CreateDirectory(Path.Combine(options.ArchivePath, "roof"));
File.WriteAllBytes(Path.Combine(options.ArchivePath, "roof", "IMG_0001.JPG"), photo);
}, ArchiveModule.Register);
var archive = server.Services.GetRequiredService<ServerArchive>();
var (editor, _, _) = await server.UserAsync("alberto", "editor");
await UntilIndexedAsync(server, archive.Id, "roof");
await UntilScannedAsync(server);
// The scan queues the thumbnails and proxies clients load from the server, as an upload does.
await UntilImagesAsync(server, editor, archive.Id, "roof");
// Another writer adds a folder: the next poll queues a scan, but not while one is pending.
Directory.CreateDirectory(Path.Combine(server.Options.ArchivePath, "garden"));
File.WriteAllBytes(Path.Combine(server.Options.ArchivePath, "garden", "IMG_0002.JPG"), Photo(seed: 3));
var polling = server.Services.GetRequiredService<ArchivePolling>();
var paused = new Job
{
Id = Guid.CreateVersion7(),
Kind = JobKind.Scan,
TargetIds = [archive.Id],
State = JobState.Paused,
Created = DateTimeOffset.UtcNow,
};
await server.Database.Jobs.EnqueueAsync(paused, context.Cancellation);
Assert.Null(await polling.PollAsync(context.Cancellation));
await server.Services.GetRequiredService<JobEngineHost>().Engine.CancelAsync(paused.Id, context.Cancellation);
var scan = Assert.NotNull(await polling.PollAsync(context.Cancellation));
Assert.Equal(JobPriority.Background, scan.Priority);
await UntilIndexedAsync(server, archive.Id, "garden");
await UntilImagesAsync(server, editor, archive.Id, "garden");
}
[Test]
public async Task FramesADesktopSharingTheArchiveAddsToASequenceGetThumbnailsAndProxiesAfterThePoll()
{
await using var server = await TestServer.StartAsync(context, options =>
{
Directory.CreateDirectory(Path.Combine(options.ArchivePath, "roof"));
File.WriteAllBytes(Path.Combine(options.ArchivePath, "roof", "IMG_0002.JPG"), Photo());
}, ArchiveModule.Register);
var archive = server.Services.GetRequiredService<ServerArchive>();
var (editor, _, _) = await server.UserAsync("alberto", "editor");
await UntilIndexedAsync(server, archive.Id, "roof");
await UntilScannedAsync(server);
await UntilImagesAsync(server, editor, archive.Id, "roof");
await UntilIdleAsync(server);
var roof = (await server.Database.Sequences.ListLocationsAsync(archive.Id)).Single(l => l.Folder == "roof");
// A desktop sharing the archive, with an index of its own, imports a photo taken earlier into the sequence: it files
// the photo and lists it in the sidecar itself, keeping the sidecar's ThumbsBuilt and ProxiesBuilt.
var desktopFolder = context.CreateTempDirectory("desktop");
await using (var desktopIndex = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(desktopFolder, "chronos.db")), context.Cancellation))
{
var desktop = new ArchiveService(desktopIndex, new ArchiveServiceOptions { Owner = "desktop" });
var shared = await desktop.OpenAsync(server.Options.ArchivePath, context.Cancellation);
await desktop.Indexer.ScanAsync(shared, ScanMode.Incremental, null, _ => ValueTask.CompletedTask, context.Cancellation);
var photo = Photo(seed: 5);
var staged = Path.Combine(desktopFolder, "IMG_0001.JPG");
await File.WriteAllBytesAsync(staged, photo);
await desktop.Ingest.CommitAsync(new IngestRequest(shared.Id, roof.Id, null, null, staged, "IMG_0001.JPG", photo.Length,
Convert.ToHexStringLower(SHA256.HashData(photo)), new DateTime(2026, 9, 28, 18, 0, 0), null), context.Cancellation);
}
Assert.Equal(1, Assert.NotNull(await server.Database.Sequences.GetAsync(roof.Id)).FrameCount);
// The next poll indexes it and queues the images: the new frame and the one it moved get theirs.
Assert.NotNull(await server.Services.GetRequiredService<ArchivePolling>().PollAsync(context.Cancellation));
await UntilScannedAsync(server);
Assert.Equal(2, Assert.NotNull(await server.Database.Sequences.GetAsync(roof.Id)).FrameCount);
await UntilImagesAsync(server, editor, archive.Id, "roof");
}
[Test]
public async Task AThumbnailDrawnBeforeAVerifyHashedThePhotoIsStillServed()
{
await using var server = await TestServer.StartAsync(context, options =>
{
Directory.CreateDirectory(Path.Combine(options.ArchivePath, "roof"));
File.WriteAllBytes(Path.Combine(options.ArchivePath, "roof", "IMG_0001.JPG"), Photo());
}, ArchiveModule.Register);
var archive = server.Services.GetRequiredService<ServerArchive>();
var (editor, _, _) = await server.UserAsync("alberto", "editor");
await UntilIndexedAsync(server, archive.Id, "roof");
await UntilScannedAsync(server);
await UntilImagesAsync(server, editor, archive.Id, "roof");
await UntilIdleAsync(server);
var roof = (await server.Database.Sequences.ListLocationsAsync(archive.Id)).Single(l => l.Folder == "roof");
var frame = (await server.Database.Frames.ListBySequenceAsync(roof.Id)).Single();
Assert.Null(frame.Sha256);
// A verify gives the photo the scan adopted its first hash; the thumbnail drawn from it before is still its own.
var verified = await server.Services.GetRequiredService<ArchiveService>().Verifier.VerifyAsync(
Assert.NotNull(await server.Database.Archives.GetAsync(archive.Id)), [roof.Id], default, (_, _, _) => ValueTask.CompletedTask, null,
context.Cancellation);
Assert.Equal(1L, verified.Hashed);
Assert.NotNull(Assert.NotNull(await server.Database.Frames.GetAsync(frame.Id)).Sha256);
using var thumb = await editor.GetAsync($"/api/v1/frames/{frame.Id}/thumb");
Assert.Equal(HttpStatusCode.OK, thumb.StatusCode);
Assert.True(Assert.NotNull(await server.Database.Sequences.GetAsync(roof.Id)).Status.HasFlag(SequenceStatus.ThumbsBuilt), "built");
}
[Test]
public async Task SettingsADesktopChangedInArchiveJsonReachUploadsAndTheAdminPanel()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var archive = server.Services.GetRequiredService<ServerArchive>();
var polling = server.Services.GetRequiredService<ArchivePolling>();
// Nothing changed: the served archive (the one an administrator's edit put there) is not replaced by a row read again.
var served = archive.Current;
await polling.PollAsync(context.Cancellation);
Assert.True(ReferenceEquals(served, archive.Current), "a poll that registered nothing keeps the served archive");
// A desktop sharing the archive changed its folder template and proxy size in archive.json.
var path = new ArchivePaths(archive.Root).ManifestPath;
var manifest = ManifestStore.ReadArchive(path);
ManifestStore.WriteArchive(path, manifest with
{
LayoutTemplates = manifest.LayoutTemplates with { Folder = "{camera}/{date}" },
ProxyPolicy = manifest.ProxyPolicy with { LongEdge = 2560 },
});
await polling.PollAsync(context.Cancellation);
// Uploads (the index row) and the admin panel (the served archive) follow it.
Assert.Equal(("{camera}/{date}", 2560), (archive.Current.FolderTemplate, archive.Current.ProxyLongEdge));
var row = Assert.NotNull(await server.Database.Archives.GetAsync(archive.Id, context.Cancellation));
Assert.Equal(("{camera}/{date}", 2560), (row.FolderTemplate, row.ProxyLongEdge));
// The admin panel opens before the next poll: its form, which saves every field, starts from the desktop's change.
ManifestStore.WriteArchive(path, ManifestStore.ReadArchive(path) with { LayoutTemplates = manifest.LayoutTemplates with { Folder = "{year}/{camera}" } });
var admin = await server.AdminAsync();
using (var read = await admin.GetAsync("/api/v1/archive/settings"))
Assert.Equal("{year}/{camera}", (await read.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto)).FolderTemplate);
Assert.Equal("{year}/{camera}", archive.Current.FolderTemplate);
// A refresh that read the archive before an administrator saved an edit never puts it back over that edit.
var before = archive.Current;
archive.Current = before with { Name = "Edited" };
Assert.False(archive.TryReplace(before, before with { Name = "Stale" }), "the edit saved meanwhile stays");
Assert.Equal("Edited", archive.Current.Name);
}
private static async Task UntilIndexedAsync(TestServer server, Guid archiveId, string folder)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while (!(await server.Database.Sequences.ListLocationsAsync(archiveId)).Any(l => l.Folder == folder))
{
Assert.True(DateTime.UtcNow < until, $"{folder} was not indexed");
await Task.Delay(50);
}
}
/// <summary>
/// Waits until every frame of the sequence in <paramref name="folder"/> has its thumbnail and proxy served and the
/// passes that made them have marked the sequence (a pass writes its files before it marks).
/// </summary>
private static async Task UntilImagesAsync(TestServer server, HttpClient client, Guid archiveId, string folder)
{
var sequence = (await server.Database.Sequences.ListLocationsAsync(archiveId)).Single(l => l.Folder == folder);
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
foreach (var frame in await server.Database.Frames.ListBySequenceAsync(sequence.Id))
{
foreach (var asset in new[] { "thumb", "proxy" })
{
while (true)
{
using var response = await client.GetAsync($"/api/v1/frames/{frame.Id}/{asset}");
if (response.StatusCode == HttpStatusCode.OK)
{
Assert.True(await response.Content.ReadAsByteArrayAsync() is [0xFF, 0xD8, ..], $"a JPEG {asset} of {frame.FileName}");
break;
}
Assert.True(DateTime.UtcNow < until, $"no {asset} of {frame.FileName} in {folder}: {(int)response.StatusCode}");
await Task.Delay(100);
}
}
}
while (Assert.NotNull(await server.Database.Sequences.GetAsync(sequence.Id)).Status is var built
&& !(built.HasFlag(SequenceStatus.ThumbsBuilt) && built.HasFlag(SequenceStatus.ProxiesBuilt)))
{
Assert.True(DateTime.UtcNow < until, $"{folder}: {built}");
await Task.Delay(50);
}
}
/// <summary>Waits until no job is waiting or running.</summary>
private static async Task UntilIdleAsync(TestServer server)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
foreach (var state in new[] { JobState.Queued, JobState.Running, JobState.Queued })
{
while ((await server.Database.Jobs.ListAsync(state)).Items.Count > 0)
{
Assert.True(DateTime.UtcNow < until, $"jobs still {state}");
await Task.Delay(50);
}
}
}
/// <summary>Waits for the scan queued at start to finish: its sequences are indexed before it ends.</summary>
private static async Task UntilScannedAsync(TestServer server)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
foreach (var state in new[] { JobState.Queued, JobState.Running })
{
while ((await server.Database.Jobs.ListAsync(state, JobKind.Scan)).Items.Count > 0)
{
Assert.True(DateTime.UtcNow < until, "the scan at start did not finish");
await Task.Delay(50);
}
}
}
[Test]
public async Task ASequenceCreatedThroughTheApiTakesUploadsIntoAFolderOfItsOwn()
{
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = 64 * 1024, ArchiveModule.Register);
var (_, _, token) = await server.UserAsync("alberto", "editor");
var source = context.CreateTempDirectory("source");
var photos = new List<(string Path, byte[] Bytes)>();
for (var i = 0; i < 2; i++)
{
var path = Path.Combine(source, $"IMG_000{i + 1}.JPG");
var bytes = Photo(i + 1);
await File.WriteAllBytesAsync(path, bytes);
photos.Add((path, bytes));
}
// The Uploader's "New sequence" target: create it, then upload into it (BRIEF §15).
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "Chronos Uploader (tests)") { Token = token };
var created = await client.CreateSequenceAsync(new CreateSequenceRequest("Harbour sunset", null), context.Cancellation);
var first = Assert.NotNull(await client.UploadFileAsync(photos[0].Path, created.Id, new DateTime(2026, 9, 28, 18, 2, 11), ct: context.Cancellation));
var second = Assert.NotNull(await client.UploadFileAsync(photos[1].Path, created.Id, new DateTime(2026, 9, 28, 18, 2, 21), ct: context.Cancellation));
Assert.Equal((created.Id, created.Id, 0, 1), (first.SequenceId, second.SequenceId, first.Index, second.Index));
var row = Assert.NotNull(await server.Database.Sequences.GetAsync(created.Id));
Assert.True(row.Folder.StartsWith("2026/2026-09-28", StringComparison.Ordinal), row.Folder);
Assert.Equal(("Harbour sunset", 2), (row.Title, row.FrameCount));
var sidecar = ManifestStore.ReadSequence(new ArchivePaths(server.Options.ArchivePath).Sequence(row.Folder).ManifestPath);
Assert.Equal((created.Id, "Harbour sunset"), (sidecar.Id, sidecar.Title));
Assert.SequenceEqual([first.FrameId, second.FrameId], sidecar.Frames.Select(f => f.Id));
Assert.FileMissing(Path.Combine(server.Options.ArchivePath, ".chronos", "sequence.json"));
for (var i = 0; i < 2; i++)
{
using var downloaded = new MemoryStream();
await client.DownloadFrameAsync(i == 0 ? first.FrameId : second.FrameId, "original", downloaded, ct: context.Cancellation);
Assert.BytesEqual(photos[i].Bytes, downloaded.ToArray());
}
}
[Test]
public async Task AnOriginalWhoseFileIsGoneIsUploadedAgainIntoItsPlace()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var photo = Photo(3);
// Room for the photo once: a repair puts back bytes the archive already counts.
var (editor, _, _) = await server.UserAsync("alberto", "editor", quotaBytes: photo.Length + 1000);
var frame = await Uploads.UploadAsync(editor, photo, "IMG_0001.JPG", sessionKey: "roof");
var row = Assert.NotNull(await server.Database.Frames.GetAsync(frame.FrameId));
var path = Path.Combine(server.Options.ArchivePath, row.RelativePath);
var known = await Uploads.StartAsync(editor, photo, "IMG_0001.JPG", sessionKey: "roof", expected: HttpStatusCode.OK);
Assert.Equal((true, frame.FrameId), (known.AlreadyExists, known.FrameId));
File.Delete(path);
// No "already exists" for a copy that is gone: the bytes come again and the frame gets its file back.
var again = await Uploads.UploadAsync(editor, photo, "IMG_0001.JPG", sessionKey: "roof");
Assert.Equal((frame.FrameId, frame.SequenceId, frame.Index), (again.FrameId, again.SequenceId, again.Index));
Assert.SequenceEqual(photo, await File.ReadAllBytesAsync(path));
Assert.Equal(1, Assert.NotNull(await server.Database.Sequences.GetAsync(frame.SequenceId)).FrameCount);
using var me = await editor.GetAsync("/api/v1/auth/me");
Assert.Equal(photo.Length, (await me.ReadAsync(ProtocolJson.Default.UserDto)).UsedBytes);
}
[Test]
public async Task AnIntactCopyElsewhereDoesNotStandForTheDamagedOneOfTheTargetSequence()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var photo = Photo(4);
var roof = await Uploads.UploadAsync(editor, photo, "IMG_0001.JPG", sessionKey: "roof");
var path = Path.Combine(server.Options.ArchivePath, Assert.NotNull(await server.Database.Frames.GetAsync(roof.FrameId)).RelativePath);
File.Delete(path);
// With the roof's copy gone, the same photo is filed into a second sequence.
var yard = await Uploads.UploadAsync(editor, photo, "IMG_0001.JPG", sessionKey: "yard");
Assert.NotEqual(roof.SequenceId, yard.SequenceId);
// Into the roof sequence the yard's copy is no shortcut, not even for a commit a crash interrupted: the bytes come
// and the roof's frame gets its file back.
var start = await Uploads.StartAsync(editor, photo, "IMG_0001.JPG", roof.SequenceId);
var id = Assert.NotNull(start.UploadId);
Assert.Equal((true, yard.FrameId), await ShortcutAsync(editor, photo, "yard"));
for (var i = 0; i * start.ChunkSize < photo.Length; i++)
{
using var put = await Uploads.PutChunkAsync(editor, id, i, Uploads.Chunk(photo, start.ChunkSize, i));
await put.ExpectAsync(HttpStatusCode.OK);
}
Assert.True(await server.Database.Uploads.TryTransitionAsync(id, UploadState.Receiving, UploadState.Committing, cancellationToken: context.Cancellation));
await server.Services.GetRequiredService<UploadMaintenance>().RecoverAsync(context.Cancellation);
using var complete = await editor.PostAsync($"/api/v1/uploads/{id}/complete", null);
await complete.ExpectAsync(HttpStatusCode.OK);
var again = await complete.ReadAsync(ProtocolJson.Default.CompleteUploadResponse);
Assert.Equal((roof.FrameId, roof.Index), (again.FrameId, again.Index));
Assert.SequenceEqual(photo, await File.ReadAllBytesAsync(path));
// Each sequence's own copy answers for it.
Assert.Equal((true, roof.FrameId), await ShortcutAsync(editor, photo, "roof"));
Assert.Equal((true, yard.FrameId), await ShortcutAsync(editor, photo, "yard"));
}
private static async Task<(bool AlreadyExists, Guid? FrameId)> ShortcutAsync(HttpClient client, byte[] photo, string sessionKey)
{
var start = await Uploads.StartAsync(client, photo, "IMG_0001.JPG", sessionKey: sessionKey, expected: HttpStatusCode.OK);
return (start.AlreadyExists, start.FrameId);
}
private static byte[] Photo(int seed = 0)
{
const int width = 96, height = 64;
var pixels = new byte[width * height * 3];
for (var i = 0; i < pixels.Length; i++) pixels[i] = (byte)((i * 7 + seed * 31) % 251);
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 90 });
}
}
@@ -0,0 +1,144 @@
using System.Net;
using System.Net.Http.Headers;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Model;
using Chronos.Server.Storage;
using Chronos.Testing;
namespace Chronos.Server.Tests.Storage;
[Category("server")]
public sealed class FileTests(TestContext context)
{
[Test]
public async Task OriginalsAreStreamedWithRangesAndEtags()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var data = Uploads.Photo(10_000, 21);
var frame = await Uploads.UploadAsync(editor, data);
using (var full = await editor.GetAsync($"/api/v1/frames/{frame.FrameId}/original"))
{
await full.ExpectAsync(HttpStatusCode.OK);
Assert.Equal("bytes", full.Headers.AcceptRanges.Single());
Assert.Equal($"\"{Uploads.Sha(data)}\"", full.Headers.ETag!.Tag);
await Http.BytesEqualAsync(data, full.Content.ReadAsByteArrayAsync());
}
using var range = new HttpRequestMessage(HttpMethod.Get, $"/api/v1/frames/{frame.FrameId}/original");
range.Headers.Range = new RangeHeaderValue(100, 199);
using (var partial = await editor.SendAsync(range))
{
await partial.ExpectAsync(HttpStatusCode.PartialContent);
Assert.Equal((100L, 199L, 10_000L), (partial.Content.Headers.ContentRange!.From!.Value, partial.Content.Headers.ContentRange.To!.Value,
partial.Content.Headers.ContentRange.Length!.Value));
await Http.BytesEqualAsync(data[100..200], partial.Content.ReadAsByteArrayAsync());
}
using var tail = new HttpRequestMessage(HttpMethod.Get, $"/api/v1/frames/{frame.FrameId}/original");
tail.Headers.Range = new RangeHeaderValue(9_990, null);
using (var end = await editor.SendAsync(tail)) await Http.BytesEqualAsync(data[9_990..], end.Content.ReadAsByteArrayAsync());
using var cached = new HttpRequestMessage(HttpMethod.Get, $"/api/v1/frames/{frame.FrameId}/original");
cached.Headers.IfNoneMatch.Add(new EntityTagHeaderValue($"\"{Uploads.Sha(data)}\""));
using (var notModified = await editor.SendAsync(cached)) await notModified.ExpectAsync(HttpStatusCode.NotModified);
var (viewer, _, _) = await server.UserAsync("marco", "viewer");
using var refused = await viewer.GetAsync($"/api/v1/frames/{frame.FrameId}/original");
await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
}
[Test]
public async Task ThumbnailsAndProxiesComeFromTheLocatedFiles()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var first = await Uploads.UploadAsync(editor, Uploads.Photo(3000, 22), "a.jpg", sessionKey: "s");
var second = await Uploads.UploadAsync(editor, Uploads.Photo(3000, 23), "b.jpg", sessionKey: "s");
var sequence = (await server.Database.Sequences.GetAsync(first.SequenceId))!;
var folder = Path.Combine(server.Options.ArchivePath, sequence.Folder);
var pack = Uploads.Photo(FakeAssetLocator.ThumbnailSize * 2, 24);
Directory.CreateDirectory(Path.Combine(folder, ".chronos"));
await File.WriteAllBytesAsync(Path.Combine(folder, ".chronos", "thumbs.pack"), pack);
using (var thumb = await editor.GetAsync($"/api/v1/frames/{second.FrameId}/thumb"))
{
await thumb.ExpectAsync(HttpStatusCode.OK);
Assert.Equal("image/jpeg", thumb.Content.Headers.ContentType!.MediaType);
await Http.BytesEqualAsync(pack[FakeAssetLocator.ThumbnailSize..(2 * FakeAssetLocator.ThumbnailSize)], thumb.Content.ReadAsByteArrayAsync());
}
using var range = new HttpRequestMessage(HttpMethod.Get, $"/api/v1/frames/{second.FrameId}/thumb");
range.Headers.Range = new RangeHeaderValue(0, 9);
using (var partial = await editor.SendAsync(range))
{
await partial.ExpectAsync(HttpStatusCode.PartialContent);
await Http.BytesEqualAsync(pack[FakeAssetLocator.ThumbnailSize..(FakeAssetLocator.ThumbnailSize + 10)], partial.Content.ReadAsByteArrayAsync());
}
using (var missing = await editor.GetAsync($"/api/v1/frames/{first.FrameId}/proxy"))
Assert.Equal("asset_missing", (await missing.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found")).Details);
var proxy = Uploads.Photo(500, 25);
Directory.CreateDirectory(Path.Combine(folder, "proxies"));
await File.WriteAllBytesAsync(Path.Combine(folder, "proxies", "0000.jpg"), proxy);
using var found = await editor.GetAsync($"/api/v1/frames/{first.FrameId}/proxy");
await Http.BytesEqualAsync(proxy, found.Content.ReadAsByteArrayAsync());
}
[Test]
public async Task PathsOutsideTheArchiveAreNeverServed()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var frame = await Uploads.UploadAsync(editor, Uploads.Photo(1000, 26));
var secret = Path.Combine(Path.GetDirectoryName(server.Options.ArchivePath)!, "secret.txt");
await File.WriteAllTextAsync(secret, "not for clients");
foreach (var hostile in new[] { "../secret.txt", "2026/../../secret.txt", "..\\secret.txt", secret, "/etc/passwd" })
{
await using (var session = await server.Database.Database.OpenAsync(context.Cancellation))
await session.ExecuteAsync("UPDATE frames SET relative_path = $1 WHERE id = $2", [hostile, frame.FrameId], context.Cancellation);
using var response = await editor.GetAsync($"/api/v1/frames/{frame.FrameId}/original");
await response.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
}
var locator = server.Services.GetRequiredService<FakeAssetLocator>();
locator.Override = new AssetLocation(secret, 0, 5, "text/plain");
using (var proxy = await editor.GetAsync($"/api/v1/frames/{frame.FrameId}/proxy")) await proxy.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
locator.Override = new AssetLocation(Path.Combine(server.Options.ArchivePath, "..", "secret.txt"), 0, 5, "text/plain");
using (var dotted = await editor.GetAsync($"/api/v1/frames/{frame.FrameId}/thumb")) await dotted.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
if (!OperatingSystem.IsWindows())
{
var link = Path.Combine(server.Options.ArchivePath, "link.jpg");
File.CreateSymbolicLink(link, secret);
await using (var session = await server.Database.Database.OpenAsync(context.Cancellation))
await session.ExecuteAsync("UPDATE frames SET relative_path = $1 WHERE id = $2", ["link.jpg", frame.FrameId], context.Cancellation);
using var linked = await editor.GetAsync($"/api/v1/frames/{frame.FrameId}/original");
await linked.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
}
}
[Test]
public async Task ExportsAreDownloadableWithRanges()
{
await using var server = await TestServer.StartAsync(context);
var (viewer, _, _) = await server.UserAsync("marco", "viewer");
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var frame = await Uploads.UploadAsync(editor, Uploads.Photo(1000, 27));
var sequence = (await server.Database.Sequences.GetAsync(frame.SequenceId))!;
var video = Uploads.Photo(4096, 28);
var relative = $"{sequence.Folder}/exports/Harbour sunset - 4K.mp4";
Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(server.Options.ArchivePath, relative))!);
await File.WriteAllBytesAsync(Path.Combine(server.Options.ArchivePath, relative), video);
var render = new Render { Id = Guid.CreateVersion7(), SequenceId = sequence.Id, PresetName = "4K HEVC", OutputPath = relative, Bytes = video.Length, Created = DateTimeOffset.UtcNow };
await server.Database.Renders.InsertAsync(render);
using var request = new HttpRequestMessage(HttpMethod.Get, $"/api/v1/renders/{render.Id}/file");
request.Headers.Range = new RangeHeaderValue(1000, 1999);
using var response = await viewer.SendAsync(request);
await response.ExpectAsync(HttpStatusCode.PartialContent);
Assert.Equal("video/mp4", response.Content.Headers.ContentType!.MediaType);
await Http.BytesEqualAsync(video[1000..2000], response.Content.ReadAsByteArrayAsync());
}
}
@@ -0,0 +1,263 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
using Chronos.Core.Localization;
using Chronos.Core.Project;
using Chronos.Data.Processing;
using Chronos.Protocol;
using Chronos.Server.Events;
using Chronos.Server.Jobs;
using Chronos.Server.Storage;
using Chronos.Server.Tests.Jobs;
using Chronos.Testing;
namespace Chronos.Server.Tests.Storage;
/// <summary>
/// The production composition: frames committed by the archive engine are light-analysed by the processing handlers,
/// and the server renders the managed formats itself.
/// </summary>
[Category("processing")]
public sealed class ProcessingModuleTests(TestContext context)
{
private const int Frames = 10;
/// <summary>The registrations of Program.cs.</summary>
private static void Production(IServiceCollection services)
{
ArchiveModule.Register(services);
ProcessingModule.Register(services);
}
[Test]
public async Task TheRunningJobHasTheParallelismAndTheHostsMemoryBudget()
{
// Owner review 1: one job at a time, the parallelism working inside it, its frame window sized to the host.
await using var server = await TestServer.StartAsync(context, o => o.Parallelism = 3, Production);
var processing = server.Services.GetRequiredService<ProcessingService>();
var tuned = processing.Options.Tune!(processing.Options);
Assert.Equal((3, 3, 3), (tuned.DeepAnalysis.MaxDegreeOfParallelism, tuned.FrameWindow.MaxConcurrentLoads, processing.Options.Archive.Parallelism()));
Assert.Equal(processing.Options.Archive.MemoryBudget(), tuned.FrameWindow.MemoryBudget);
Assert.True(tuned.FrameWindow.MemoryBudget >= 1L << 30, "at least the window's own default");
// A change in the admin panel applies to the next job.
server.Options.Parallelism = 5;
Assert.Equal(5, processing.Options.Tune!(processing.Options).FrameWindow.MaxConcurrentLoads);
}
[Test]
public async Task UploadedFramesAreLightAnalysedAndAdvised()
{
await using var server = await TestServer.StartAsync(context, services: Production);
using var events = server.Services.GetRequiredService<EventHub>().Subscribe();
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var sequenceId = await UploadSceneAsync(editor);
// The commits queue a light analysis; its handler comes from the processing module.
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
Sequence sequence;
while (true)
{
sequence = (await server.Database.Sequences.GetAsync(sequenceId))!;
if (sequence.Status.HasFlag(SequenceStatus.AnalyzedLight) && sequence.FrameCount == Frames
&& !await server.Database.Jobs.IsQueuedAsync(JobKind.LightAnalyse, sequenceId)) break;
Assert.True(DateTime.UtcNow < until, $"not analysed: {sequence.Status}, {sequence.FrameCount} frames");
await Task.Delay(100);
}
var project = ProjectSettings.FromJson(Assert.NotNull(sequence.SettingsJson));
Assert.True(project.Timing.Mode.HasAdvice, "timing mode advised");
var folder = new ArchivePaths(server.Options.ArchivePath).Sequence(sequence.Folder);
Assert.FileExists(folder.ProjectPath);
Assert.True(ManifestStore.ReadSequence(folder.ManifestPath).Status.HasFlag(SequenceStatus.AnalyzedLight), "sidecar status");
// Connected clients learn that the Auto values changed (BRIEF §14.3).
Assert.Contains(Drain(events), e => e is SequenceChangedEvent { Change: "settings" } changed && changed.SequenceId == sequenceId);
}
[Test]
public async Task AProxyThatArrivesHasTheSequenceAnalysedAgain()
{
await using var server = await TestServer.StartAsync(context, services: Production);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
// A HEIF original the server cannot decode (BRIEF §2.3): what it renders depends on the proxy a client sends.
var upload = await Uploads.UploadAsync(editor, [0, 0, 0, 24, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8, .. Uploads.Photo(2000, 1)], "IMG_0001.HEIC",
sessionKey: "roof");
await LightAnalysesAsync(server, upload.SequenceId, 1);
var frame = Assert.NotNull(await server.Database.Frames.GetAsync(upload.FrameId));
using var image = new Core.Imaging.ImageBuffer(320, 240);
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata { CapturedAt = frame.CapturedAt, Software = "Chronos" });
using var proxy = new ByteArrayContent(JpegEncoder.Encode(image, new JpegEncodeOptions { App1Segments = [exif[4..]] }));
proxy.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
using (var stored = await editor.PutAsync($"/api/v1/frames/{frame.Id}/proxy", proxy))
await stored.ExpectAsync(HttpStatusCode.NoContent);
// A frame read from its proxy is no longer preview-only, so the advisor's Auto values are worked out again.
await LightAnalysesAsync(server, upload.SequenceId, 2);
}
[Test]
public async Task TheServerRendersManagedFormatsAndLeavesMp4ToRenderNodes()
{
await using var server = await TestServer.StartAsync(context, services: Production);
using var events = server.Services.GetRequiredService<EventHub>().Subscribe();
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var sequence = (await server.Database.Sequences.GetAsync(await UploadSceneAsync(editor)))!;
// A client's export folder means nothing on the server: the output still goes to the sequence's exports.
var avi = new ExportSettings
{
Preset = new Auto<string>().WithManual("mjpeg-avi"),
Overrides = new ExportOverrides { Width = 96, Height = 64 },
NameTemplate = "clip",
Folder = context.CreateTempDirectory("elsewhere"),
};
var hevc = new ExportSettings { Preset = new Auto<string>().WithManual("4k-hevc") };
var mp4 = await JobApiTests.CreateAsync(editor, "render", sequence.Id, ProcessingJobs.Render(sequence, hevc, 96, 64).ParametersJson);
var managed = await JobApiTests.CreateAsync(editor, "render", sequence.Id, ProcessingJobs.Render(sequence, avi, 96, 64).ParametersJson);
var done = await JobApiTests.WaitForAsync(editor, managed.Id, "done");
Assert.Equal(JobEngineHost.WorkerId, done.NodeId?.Split('#')[0]);
var render = (await server.Database.Renders.ListBySequenceAsync(sequence.Id)).Single();
Assert.Equal(($"{sequence.Folder}/exports/clip.avi", server.Options.ServerName, "Mjpeg"), (render.OutputPath, render.ProducedBy, render.Codec));
Assert.FileExists(Path.Combine(server.Options.ArchivePath, render.OutputPath));
Assert.Empty(Directory.EnumerateFileSystemEntries(avi.Folder));
var waiting = await JobApiTests.GetAsync(editor, mp4.Id);
Assert.Equal(("queued", (string?)null), (waiting.State, waiting.NodeId));
Assert.Contains(Drain(events), e => e is SequenceChangedEvent { Change: "renders" } changed && changed.SequenceId == sequence.Id);
}
[Test]
public async Task Mp4JobsNoRenderNodeCanTakeAreRenderedAsMjpegAndTheLogSaysSo()
{
var clock = new ManualTimeProvider();
await using var server = await TestServer.StartAsync(context, o => o.NodeTimeoutSeconds = 60, s =>
{
Production(s);
s.AddSingleton<TimeProvider>(clock);
});
var engine = server.Services.GetRequiredService<JobEngineHost>().Engine;
var (editor, _, _) = await server.UserAsync("alberto", "editor", renderNode: true);
var sequence = (await server.Database.Sequences.GetAsync(await UploadSceneAsync(editor)))!;
var hevc = new ExportSettings
{
Preset = new Auto<string>().WithManual("4k-hevc"),
Overrides = new ExportOverrides { Width = 96, Height = 64 },
NameTemplate = "clip-{codec}",
};
var job = await JobApiTests.CreateAsync(editor, "render", sequence.Id, ProcessingJobs.Render(sequence, hevc, 96, 64).ParametersJson);
// A node that encodes HEVC is online: the job waits for it, however long it has been queued.
using (var registered = await editor.PostAsJsonAsync("/api/v1/nodes/register",
new RegisterNodeRequest("studio-pc", [new NodeEncoder("hevc", "NVENC HEVC", true, true, 8192, 8192)], 8192, 8192), ProtocolJson.Default.RegisterNodeRequest))
await registered.ExpectAsync(HttpStatusCode.OK);
clock.Advance(TimeSpan.FromSeconds(61));
var node = (await server.Database.RenderNodes.ListAsync()).Single();
Assert.True(await server.Database.RenderNodes.HeartbeatAsync(node.Id, "idle", clock.GetUtcNow()));
engine.Wake();
await Task.Delay(1500);
Assert.Equal("queued", (await JobApiTests.GetAsync(editor, job.Id)).State);
// The node goes silent: the server renders the job itself in a managed format.
clock.Advance(TimeSpan.FromSeconds(61));
engine.Wake();
var done = await JobApiTests.WaitForAsync(editor, job.Id, "done");
Assert.Equal(JobEngineHost.WorkerId, done.NodeId?.Split('#')[0]);
var render = (await server.Database.Renders.ListBySequenceAsync(sequence.Id)).Single();
Assert.Equal(($"{sequence.Folder}/exports/clip-MJPEG.avi", "Mjpeg", 96, 64), (render.OutputPath, render.Codec, render.Width, render.Height));
Assert.Contains(Loc.L("Export.Log.NoRenderNode", Loc.L("Export.Preset.Custom"), "HEVC", "MJPEG"), done.LogTail);
}
[Test]
public async Task APostedBatchBecomesOneJobPerPreset()
{
await using var server = await TestServer.StartAsync(context, services: Production);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var sequence = (await server.Database.Sequences.GetAsync(await UploadSceneAsync(editor)))!;
var batch = new ExportSettings
{
Preset = new Auto<string>().WithManual("mjpeg-avi"),
Overrides = new ExportOverrides { Width = 96, Height = 64 },
NameTemplate = "{title} - {codec}",
Batch = ["gif-preview", "1080p-h264"],
};
var main = await JobApiTests.CreateAsync(editor, "render", sequence.Id, ProcessingJobs.Render(sequence, batch, 96, 64).ParametersJson);
var jobs = (await server.Database.Jobs.ListAsync(null, JobKind.Render)).Items;
Assert.Count(3, jobs);
var mp4 = jobs.Single(j => j.TargetLabel!.EndsWith(Loc.L("Export.Preset.1080pShare"), StringComparison.Ordinal));
var gif = jobs.Single(j => j.TargetLabel!.EndsWith(Loc.L("Export.Preset.Gif"), StringComparison.Ordinal));
await JobApiTests.WaitForAsync(editor, main.Id, "done");
await JobApiTests.WaitForAsync(editor, gif.Id, "done");
// The server renders the managed presets; the MP4 one waits for a render node, at the preset's size.
Assert.SequenceEqual(["Gif", "Mjpeg"], (await server.Database.Renders.ListBySequenceAsync(sequence.Id)).Select(r => r.Codec!).Order(StringComparer.Ordinal));
Assert.Equal("queued", (await JobApiTests.GetAsync(editor, mp4.Id)).State);
var parameters = JsonSerializer.Deserialize(mp4.ParametersJson!, ProtocolJson.Default.RenderJobParameters)!;
Assert.Equal(("h264", 1920, 1080), (parameters.Codec, parameters.Width, parameters.Height));
}
[Test]
public async Task RenderJobsThatCannotBeReadNeverStopTheEngine()
{
await using var server = await TestServer.StartAsync(context, services: Production);
var (editor, user, _) = await server.UserAsync("alberto", "editor");
var sequence = (await server.Database.Sequences.GetAsync(await UploadSceneAsync(editor)))!;
const string mjpeg = """{"preset":{"isAuto":false,"manual":"mjpeg-avi"},"overrides":{"width":96,"height":64}""";
// The API refuses a preset that gives a member twice; one already queued fails with its reason.
using (var refused = await editor.PostAsJsonAsync("/api/v1/jobs",
new CreateJobRequest("render", [sequence.Id], Parameters(mjpeg + ""","Preset":{}}""")), ProtocolJson.Default.CreateJobRequest))
await refused.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_parameters");
var engine = server.Services.GetRequiredService<JobEngineHost>().Engine;
var broken = await engine.EnqueueAsync(JobKind.Render, [sequence.Id], "broken", Parameters(mjpeg + ""","Preset":{}}"""), JobPriority.User, user.Id);
var failed = await JobApiTests.WaitForAsync(editor, broken.Id, "failed");
Assert.Equal(Loc.L("Errors.Render.Parameters"), failed.Error);
// The workers carry on: a null batch is no batch.
var fine = await JobApiTests.CreateAsync(editor, "render", sequence.Id, Parameters(mjpeg + ""","batch":null}"""));
await JobApiTests.WaitForAsync(editor, fine.Id, "done");
}
private static string Parameters(string presetJson) =>
JsonSerializer.Serialize(new RenderJobParameters("MJPEG", presetJson, "mjpeg", 96, 64, false, null), ProtocolJson.Default.RenderJobParameters);
private static List<ServerEvent> Drain(EventHub.Subscription events)
{
var drained = new List<ServerEvent>();
while (events.Reader.TryRead(out var e)) drained.Add(e);
return drained;
}
/// <summary>Waits until <paramref name="count"/> light analyses of the sequence have finished.</summary>
private static async Task LightAnalysesAsync(TestServer server, Guid sequenceId, int count)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while (true)
{
var done = (await server.Database.Jobs.ListAsync(JobState.Done, JobKind.LightAnalyse, 200)).Items.Count(j => j.TargetIds.Contains(sequenceId));
if (done >= count) return;
Assert.True(DateTime.UtcNow < until, $"light analyses finished: {done} of {count}");
await Task.Delay(100);
}
}
/// <summary>Uploads a synthetic scene with Exif into one new sequence; returns its id.</summary>
private static async Task<Guid> UploadSceneAsync(HttpClient editor)
{
var scene = SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = Frames, StartEv = 0.5, EndEv = -0.5 });
Guid sequenceId = default;
for (var i = 0; i < scene.Count; i++)
{
using var image = scene.Render(i);
var exif = ExifWriter.BuildJpegApp1(scene.Metadata[i]);
var photo = JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] });
sequenceId = (await Uploads.UploadAsync(editor, photo, $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
}
return sequenceId;
}
}
@@ -0,0 +1,223 @@
using System.Net;
using System.Net.Http.Headers;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Imaging;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
using Chronos.Protocol;
using Chronos.Server.Storage;
using Chronos.Testing;
namespace Chronos.Server.Tests.Storage;
/// <summary>
/// Proxies of originals the server cannot decode (BRIEF §2.3: HEIF) arrive from clients and render nodes through
/// <c>PUT /api/v1/frames/{id}/proxy</c> and become the frame's proxy and thumbnail.
/// </summary>
[Category("server")]
public sealed class ProxyUploadTests(TestContext context)
{
[Test]
public async Task AProxySentForAFrameTheServerCannotDecodeIsCheckedKeptAndThumbnailed()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var (viewer, _, _) = await server.UserAsync("vera", "viewer");
var upload = await Uploads.UploadAsync(editor, Heif(1), "IMG_0001.HEIC", sessionKey: "roof");
var frame = Assert.NotNull(await server.Database.Frames.GetAsync(upload.FrameId));
Assert.Equal(ImageFileFormat.Heif, frame.Format);
var manifest = await ManifestAsync(editor, upload.SequenceId);
Assert.Equal((true, false), (manifest.Frames.Single().WantsProxy, manifest.Frames.Single().HasProxy));
Assert.Equal(new ProxySpec(1920, 92), manifest.Proxies);
using (var garbage = await PutAsync(editor, frame.Id, "not a photo"u8.ToArray()))
await garbage.ExpectErrorAsync(HttpStatusCode.UnprocessableEntity, "invalid_proxy");
using (var other = await PutAsync(editor, frame.Id, Proxy(frame.CapturedAt!.Value.AddSeconds(1))))
await other.ExpectErrorAsync(HttpStatusCode.UnprocessableEntity, "proxy_mismatch");
var proxy = Proxy(frame.CapturedAt!.Value);
using (var refused = await PutAsync(viewer, frame.Id, proxy))
await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var missing = await PutAsync(editor, Guid.CreateVersion7(), proxy))
await missing.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
using (var stored = await PutAsync(editor, frame.Id, proxy))
await stored.ExpectAsync(HttpStatusCode.NoContent);
await Http.BytesEqualAsync(proxy, editor.GetByteArrayAsync($"/api/v1/frames/{frame.Id}/proxy"));
var after = (await ManifestAsync(editor, upload.SequenceId)).Frames.Single();
Assert.Equal((false, true), (after.WantsProxy, after.HasProxy));
// The thumbnail job the proxy queued draws the frame from it.
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while (true)
{
using var thumb = await editor.GetAsync($"/api/v1/frames/{frame.Id}/thumb");
if (thumb.StatusCode == HttpStatusCode.OK)
{
var jpeg = await thumb.Content.ReadAsByteArrayAsync();
Assert.Equal((320, 240), (JpegDecoder.ReadInfo(jpeg).Width, JpegDecoder.ReadInfo(jpeg).Height));
break;
}
Assert.True(DateTime.UtcNow < until, $"thumbnail not built: {(int)thumb.StatusCode}");
await Task.Delay(100);
}
}
[Test]
public async Task AnotherPhotosProxyInTheFramesPlaceIsAskedForAgainAndNeverServed()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var upload = await Uploads.UploadAsync(editor, Heif(1), "IMG_0001.HEIC", sessionKey: "roof");
var frame = Assert.NotNull(await server.Database.Frames.GetAsync(upload.FrameId));
var sequence = Assert.NotNull(await server.Database.Sequences.GetAsync(upload.SequenceId));
// Proxies are named by frame index: after a frame was inserted before this one, its place holds another photo's.
var path = new Core.Archiving.ArchivePaths(server.Options.ArchivePath).Sequence(sequence.Folder).Proxy(frame.Index);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
await File.WriteAllBytesAsync(path, Proxy(frame.CapturedAt!.Value.AddSeconds(-10)));
Assert.Equal((true, false), Wanted((await ManifestAsync(editor, upload.SequenceId)).Frames.Single()));
using (var served = await editor.GetAsync($"/api/v1/frames/{frame.Id}/proxy"))
Assert.Equal("asset_missing", (await served.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found")).Details);
// The frame's own proxy takes its place.
var proxy = Proxy(frame.CapturedAt!.Value);
using (var stored = await PutAsync(editor, frame.Id, proxy))
await stored.ExpectAsync(HttpStatusCode.NoContent);
Assert.Equal((false, true), Wanted((await ManifestAsync(editor, upload.SequenceId)).Frames.Single()));
await Http.BytesEqualAsync(proxy, editor.GetByteArrayAsync($"/api/v1/frames/{frame.Id}/proxy"));
}
[Test]
public async Task FramesAddedAfterEveryProxyArrivedAreAskedForTheirs()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var first = await Uploads.UploadAsync(editor, Heif(1), "IMG_0001.HEIC", sessionKey: "roof");
var frame = Assert.NotNull(await server.Database.Frames.GetAsync(first.FrameId));
using (var stored = await PutAsync(editor, frame.Id, Proxy(frame.CapturedAt!.Value)))
await stored.ExpectAsync(HttpStatusCode.NoContent);
// A frame comes after the proxy pass found every proxy there: until the next pass the status still says so, yet
// the new frame is asked for its proxy and the first keeps its own.
var second = await Uploads.UploadAsync(editor, Heif(2), "IMG_0002.HEIC", sessionKey: "roof");
Assert.Equal(first.SequenceId, second.SequenceId);
await server.Database.Sequences.UpdateStatusAsync(first.SequenceId, SequenceStatus.ProxiesBuilt, SequenceStatus.None, context.Cancellation);
var frames = (await ManifestAsync(editor, first.SequenceId)).Frames;
Assert.Equal((false, true), Wanted(frames.Single(f => f.Id == first.FrameId)));
Assert.Equal((true, false), Wanted(frames.Single(f => f.Id == second.FrameId)));
}
[Test]
public async Task AProxyTheServerMadeIsServedForAFrameTimedToTheTick()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
// Seven sub-second digits: the sidecar, and the proxy made from it, keep them all; the index keeps six.
var upload = await Uploads.UploadAsync(editor, Proxy(new DateTime(2026, 9, 28, 18, 2, 11).AddTicks(1_234_567)), "IMG_0001.JPG", sessionKey: "roof");
// The proxy pass the upload queued makes the frame's proxy, and the server serves it.
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while (true)
{
using var proxy = await editor.GetAsync($"/api/v1/frames/{upload.FrameId}/proxy");
if (proxy.StatusCode == HttpStatusCode.OK) break;
Assert.True(DateTime.UtcNow < until, $"proxy not served: {(int)proxy.StatusCode}");
await Task.Delay(100);
}
}
[Test]
public async Task AReportThatFoundAFrameUnreadableBeforeItsProxyCameIsNotServed()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var upload = await Uploads.UploadAsync(editor, Heif(1), "IMG_0001.HEIC", sessionKey: "roof");
var frame = Assert.NotNull(await server.Database.Frames.GetAsync(upload.FrameId));
var sequence = Assert.NotNull(await server.Database.Sequences.GetAsync(upload.SequenceId));
// A deep analysis ran before the proxy came and found no pixels in the HEIF original.
var path = new Core.Archiving.ArchivePaths(server.Options.ArchivePath).Sequence(sequence.Folder).AnalysisPath;
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
Reports.Minimal(1, undecodable: 0).Save(path);
var url = $"/api/v1/sequences/{sequence.Id}/analysis/report";
using (var before = await editor.GetAsync(url))
await before.ExpectAsync(HttpStatusCode.OK);
// Once the frame is read from its proxy, that verdict and its advice to exclude the frame no longer hold, even
// before a light analysis has dropped the deep status.
using (var stored = await PutAsync(editor, frame.Id, Proxy(frame.CapturedAt!.Value)))
await stored.ExpectAsync(HttpStatusCode.NoContent);
using var after = await editor.GetAsync(url);
Assert.Equal("analysis", (await after.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found")).Details);
}
[Test]
public async Task FramesTheServerDecodesAskForNoProxy()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var upload = await Uploads.UploadAsync(editor, Proxy(new DateTime(2026, 9, 28, 18, 2, 11)), "IMG_0001.JPG", sessionKey: "roof");
Assert.False((await ManifestAsync(editor, upload.SequenceId)).Frames.Single().WantsProxy);
// Nor takes one: renders and remote views keep the proxy the server makes itself.
using var refused = await PutAsync(editor, upload.FrameId, Proxy(new DateTime(2026, 9, 28, 18, 2, 11)));
await refused.ExpectErrorAsync(HttpStatusCode.UnprocessableEntity, "proxy_not_wanted");
}
[Test]
public async Task AnswersThatLeaveALargeProxyUnreadReachTheClient()
{
// A full-size proxy is far above the 1 MiB other requests may send: more than the connection buffers while the
// server reads nothing.
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var heif = await Uploads.UploadAsync(editor, Heif(1), "IMG_0001.HEIC", sessionKey: "roof");
var jpeg = await Uploads.UploadAsync(editor, Proxy(new DateTime(2026, 9, 28, 18, 2, 12)), "IMG_0002.JPG", sessionKey: "roof");
var large = Uploads.Photo(24 * 1024 * 1024, 7);
// The handler answers before reading the body: a frame deleted since the manifest, and one the server decodes itself.
using (var missing = await PutAsync(editor, Guid.CreateVersion7(), large))
Assert.Equal("frame", (await missing.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found")).Details);
using (var unwanted = await PutAsync(editor, jpeg.FrameId, large))
await unwanted.ExpectErrorAsync(HttpStatusCode.UnprocessableEntity, "proxy_not_wanted");
// A body that may be the proxy is read whole, past the 1 MiB, before it is judged.
using (var invalid = await PutAsync(editor, heif.FrameId, large))
await invalid.ExpectErrorAsync(HttpStatusCode.UnprocessableEntity, "invalid_proxy");
// Authentication answers before the endpoint runs: an account that lost the Edit role, and a session signed out meanwhile.
var (viewer, _, _) = await server.UserAsync("vera", "viewer");
using (var forbidden = await PutAsync(viewer, heif.FrameId, large))
await forbidden.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var logout = await editor.PostAsync("/api/v1/auth/logout", null))
await logout.ExpectAsync(HttpStatusCode.NoContent);
using var revoked = await PutAsync(editor, heif.FrameId, large);
await revoked.ExpectErrorAsync(HttpStatusCode.Unauthorized, "unauthorized");
}
/// <summary>A HEIF file as far as signature sniffing goes (an <c>ftyp</c> box naming heic), with no pixels the server can read.</summary>
private static byte[] Heif(int seed) => [0, 0, 0, 24, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8, .. Uploads.Photo(2000, seed)];
/// <summary>A 320 × 240 JPEG with <paramref name="captured"/> in its Exif, as a client makes a proxy.</summary>
private static byte[] Proxy(DateTime captured)
{
using var image = new ImageBuffer(320, 240);
for (var c = 0; c < 3; c++) image.Plane(c).Fill(0.3f + c * 0.1f);
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata { CapturedAt = captured, Software = "Chronos" });
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [exif[4..]] });
}
private static (bool WantsProxy, bool HasProxy) Wanted(ManifestFrame frame) => (frame.WantsProxy, frame.HasProxy);
private static Task<HttpResponseMessage> PutAsync(HttpClient client, Guid frameId, byte[] body)
{
var content = new ByteArrayContent(body);
content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return client.PutAsync($"/api/v1/frames/{frameId}/proxy", content);
}
private static async Task<SequenceManifest> ManifestAsync(HttpClient client, Guid sequenceId)
{
using var response = await client.GetAsync($"/api/v1/sequences/{sequenceId}/manifest");
return await response.ReadAsync(ProtocolJson.Default.SequenceManifest);
}
}
@@ -0,0 +1,349 @@
using System.Net;
using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Model;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using Chronos.Server.Storage;
using Chronos.Testing;
namespace Chronos.Server.Tests.Storage;
[Category("server")]
public sealed class UploadTests(TestContext context)
{
private const int Chunk = 64 * 1024;
[Test]
public async Task ChunksInAnyOrderCommitAVerifiedFrame()
{
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk);
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
var data = Uploads.Photo(Chunk * 3 + 1234, 1);
var start = await Uploads.StartAsync(uploader, data, sessionKey: "roof-2026-09-28");
var id = Assert.NotNull(start.UploadId);
Assert.Equal(Chunk, start.ChunkSize);
Assert.Empty(start.Received);
foreach (var index in new[] { 3, 0, 2, 1, 0 })
{
using var put = await Uploads.PutChunkAsync(uploader, id, index, Uploads.Chunk(data, Chunk, index));
await put.ExpectAsync(HttpStatusCode.OK);
Assert.Equal(index, (await put.ReadAsync(ProtocolJson.Default.ChunkReceived)).Index);
}
using (var state = await uploader.GetAsync($"/api/v1/uploads/{id}"))
{
var resume = await state.ReadAsync(ProtocolJson.Default.UploadState);
Assert.SequenceEqual([0, 1, 2, 3], resume.Received);
Assert.Equal("receiving", resume.State);
}
using var complete = await uploader.PostAsync($"/api/v1/uploads/{id}/complete", null);
await complete.ExpectAsync(HttpStatusCode.OK);
var frame = await complete.ReadAsync(ProtocolJson.Default.CompleteUploadResponse);
var ingest = server.Services.GetRequiredService<FakeArchiveIngest>();
var request = Assert.NotNull(ingest.Requests.LastOrDefault());
Assert.Equal("roof-2026-09-28", request.SessionKey);
Assert.Null(request.SequenceId);
Assert.Equal(Uploads.Sha(data), request.Sha256);
Assert.True(request.StagedPath.StartsWith(server.Options.StagingPath, StringComparison.Ordinal), request.StagedPath);
var stored = Assert.NotNull(await server.Database.Frames.GetAsync(frame.FrameId));
await Http.BytesEqualAsync(data, File.ReadAllBytesAsync(Path.Combine(server.Options.ArchivePath, stored.RelativePath)));
Assert.False(server.Services.GetRequiredService<UploadStore>().Exists(id), "the partial file is gone");
Assert.Empty(Directory.EnumerateFiles(server.Options.StagingPath));
using (var me = await uploader.GetAsync("/api/v1/auth/me")) Assert.Equal(data.Length, (await me.ReadAsync(ProtocolJson.Default.UserDto)).UsedBytes);
// A completion whose response was lost can be repeated.
using var again = await uploader.PostAsync($"/api/v1/uploads/{id}/complete", null);
await again.ExpectAsync(HttpStatusCode.OK);
Assert.Equal(frame.FrameId, (await again.ReadAsync(ProtocolJson.Default.CompleteUploadResponse)).FrameId);
}
[Test]
public async Task AnInterruptedUploadResumesWithItsReceivedChunks()
{
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk);
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
var data = Uploads.Photo(Chunk * 4, 2);
var first = await Uploads.StartAsync(uploader, data);
foreach (var index in new[] { 0, 2 })
{
using var put = await Uploads.PutChunkAsync(uploader, first.UploadId!.Value, index, Uploads.Chunk(data, Chunk, index));
await put.ExpectAsync(HttpStatusCode.OK);
}
var resumed = await Uploads.StartAsync(uploader, data);
Assert.Equal(first.UploadId, resumed.UploadId);
Assert.SequenceEqual([0, 2], resumed.Received);
foreach (var index in new[] { 1, 3 })
{
using var put = await Uploads.PutChunkAsync(uploader, first.UploadId!.Value, index, Uploads.Chunk(data, Chunk, index));
await put.ExpectAsync(HttpStatusCode.OK);
}
using var complete = await uploader.PostAsync($"/api/v1/uploads/{first.UploadId}/complete", null);
await complete.ExpectAsync(HttpStatusCode.OK);
}
[Test]
public async Task AKnownHashShortCircuitsTheUpload()
{
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk);
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
var data = Uploads.Photo(5000, 3);
var frame = await Uploads.UploadAsync(uploader, data);
var again = await Uploads.StartAsync(uploader, data, expected: HttpStatusCode.OK);
Assert.True(again.AlreadyExists);
Assert.Null(again.UploadId);
Assert.Equal(frame.FrameId, again.FrameId);
}
[Test]
public async Task ACopyFlaggedOrGoneIsNoShortcut()
{
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk);
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
// A client may delete its file on "already exists": a damaged copy must ask for the bytes again.
var flagged = Uploads.Photo(5000, 11);
var first = await Uploads.UploadAsync(uploader, flagged);
await server.Database.Frames.UpdateFlagsAsync([first.FrameId], FrameFlags.Corrupt, FrameFlags.None);
Assert.False((await Uploads.StartAsync(uploader, flagged)).AlreadyExists);
var gone = Uploads.Photo(5000, 12);
var second = await Uploads.UploadAsync(uploader, gone);
File.Delete(Path.Combine(server.Options.ArchivePath, Assert.NotNull(await server.Database.Frames.GetAsync(second.FrameId)).RelativePath));
Assert.False((await Uploads.StartAsync(uploader, gone)).AlreadyExists);
}
[Test]
public async Task ACommitLeftByACrashIsSettledOnlyByAnIntactFrame()
{
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk);
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
var data = Uploads.Photo(Chunk + 100, 13);
var missing = await Uploads.UploadAsync(uploader, data);
await server.Database.Frames.UpdateFlagsAsync([missing.FrameId], FrameFlags.Missing, FrameFlags.None);
var start = await Uploads.StartAsync(uploader, data);
var id = Assert.NotNull(start.UploadId);
for (var i = 0; i < 2; i++)
{
using var put = await Uploads.PutChunkAsync(uploader, id, i, Uploads.Chunk(data, Chunk, i));
await put.ExpectAsync(HttpStatusCode.OK);
}
// The server stopped while committing it.
Assert.True(await server.Database.Uploads.TryTransitionAsync(id, Chronos.Data.Repositories.UploadState.Receiving,
Chronos.Data.Repositories.UploadState.Committing, cancellationToken: context.Cancellation));
await server.Services.GetRequiredService<UploadMaintenance>().RecoverAsync(context.Cancellation);
// The flagged frame does not stand for it: the client completes again with its part file intact.
using (var state = await uploader.GetAsync($"/api/v1/uploads/{id}")) Assert.Equal("receiving", (await state.ReadAsync(ProtocolJson.Default.UploadState)).State);
Assert.True(server.Services.GetRequiredService<UploadStore>().Exists(id));
}
[Test]
public async Task AnUploadKeepsItsChunkSizeWhenTheSettingShrinks()
{
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk * 2);
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
var data = Uploads.Photo(Chunk * 3, 14);
var start = await Uploads.StartAsync(uploader, data);
var id = Assert.NotNull(start.UploadId);
Assert.Equal(Chunk * 2, start.ChunkSize);
// An administrator lowers the chunk size; the upload resumes with the size it started with.
server.Options.ChunkSizeBytes = Chunk;
var resumed = await Uploads.StartAsync(uploader, data);
Assert.Equal((id, Chunk * 2), (resumed.UploadId!.Value, resumed.ChunkSize));
for (var i = 0; i < 2; i++)
{
using var put = await Uploads.PutChunkAsync(uploader, id, i, Uploads.Chunk(data, Chunk * 2, i));
await put.ExpectAsync(HttpStatusCode.OK);
}
using var complete = await uploader.PostAsync($"/api/v1/uploads/{id}/complete", null);
await complete.ExpectAsync(HttpStatusCode.OK);
// A new upload takes the new size, and a body above it is refused.
var next = Uploads.Photo(Chunk * 2, 15);
var small = await Uploads.StartAsync(uploader, next);
Assert.Equal(Chunk, small.ChunkSize);
using var oversized = await Uploads.PutChunkAsync(uploader, small.UploadId!.Value, 0, next);
await oversized.ExpectErrorAsync(HttpStatusCode.BadRequest, "chunk_size");
}
[Test]
public async Task AnswersThatLeaveALargeChunkUnreadReachTheClient()
{
// Chunks far above the 1 MiB other requests may send: more than the connection buffers while the server reads nothing.
const int large = 32 * 1024 * 1024;
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = large);
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
var data = Uploads.Photo(24 * 1024 * 1024, 16);
var id = (await Uploads.StartAsync(uploader, data)).UploadId!.Value;
using (var first = await Uploads.PutChunkAsync(uploader, id, 0, data)) await first.ExpectAsync(HttpStatusCode.OK);
// The client lost the answer and sends the chunk again: the same answer, not a closed connection.
using (var again = await Uploads.PutChunkAsync(uploader, id, 0, data))
{
await again.ExpectAsync(HttpStatusCode.OK);
Assert.SequenceEqual([0], (await again.ReadAsync(ProtocolJson.Default.ChunkReceived)).Received);
}
using (var unknown = await Uploads.PutChunkAsync(uploader, Guid.CreateVersion7(), 0, data)) await unknown.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
using (var complete = await uploader.PostAsync($"/api/v1/uploads/{id}/complete", null)) await complete.ExpectAsync(HttpStatusCode.OK);
using (var late = await Uploads.PutChunkAsync(uploader, id, 0, data)) await late.ExpectErrorAsync(HttpStatusCode.Conflict, "upload_state");
// Authentication answers before the endpoint runs: a user who may not upload, and a session signed out meanwhile.
var (viewer, _, _) = await server.UserAsync("marco", "viewer");
using (var forbidden = await Uploads.PutChunkAsync(viewer, id, 0, data)) await forbidden.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var logout = await uploader.PostAsync("/api/v1/auth/logout", null)) await logout.ExpectAsync(HttpStatusCode.NoContent);
using var revoked = await Uploads.PutChunkAsync(uploader, id, 0, data);
await revoked.ExpectErrorAsync(HttpStatusCode.Unauthorized, "unauthorized");
}
[Test]
public async Task RenderUploadsNeedTheEditPermission()
{
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk);
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var frame = await Uploads.UploadAsync(uploader, Uploads.Photo(5000, 16), sessionKey: "roof");
var output = Uploads.Photo(3000, 17);
var request = new RenderUploadRequest(Guid.CreateVersion7(), "Roof.mp4", output.Length, Uploads.Sha(output), "4K HEVC", "hevc", 3840, 2160, 30, 10, null);
// Render outputs count against no quota: an upload-only account cannot add them to any sequence.
using (var refused = await uploader.PostAsJsonAsync($"/api/v1/sequences/{frame.SequenceId}/renders", request, ProtocolJson.Default.RenderUploadRequest))
await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var complete = await uploader.PostAsync($"/api/v1/sequences/{frame.SequenceId}/renders/{Guid.CreateVersion7()}/complete", null))
await complete.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using var accepted = await editor.PostAsJsonAsync($"/api/v1/sequences/{frame.SequenceId}/renders", request, ProtocolJson.Default.RenderUploadRequest);
await accepted.ExpectAsync(HttpStatusCode.Created);
}
[Test]
public async Task TheProtocolClientUploadsAndDownloadsLikeTheUploader()
{
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk);
var (_, _, token) = await server.UserAsync("alberto", "editor");
var folder = context.CreateTempDirectory("source");
var path = Path.Combine(folder, "2026-09-28_18-02-11_0413.CR3");
var data = Uploads.Photo(Chunk * 2 + 77, 4);
await File.WriteAllBytesAsync(path, data);
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "Chronos Uploader (tests)") { Token = token };
var sequence = await client.CreateSequenceAsync(new CreateSequenceRequest("Harbour sunset", null));
var progress = new List<UploadProgress>();
var result = Assert.NotNull(await client.UploadFileAsync(path, sequence.Id, new DateTime(2026, 9, 28), progress: new SyncProgress<UploadProgress>(progress.Add)));
Assert.Equal(sequence.Id, result.SequenceId);
Assert.Equal(0, result.Index);
Assert.Equal(data.Length, progress[^1].BytesSent);
var duplicate = Assert.NotNull(await client.UploadFileAsync(path, sequence.Id, null));
Assert.Equal((result.FrameId, -1), (duplicate.FrameId, duplicate.Index));
using var downloaded = new MemoryStream();
await client.DownloadFrameAsync(result.FrameId, "original", downloaded);
Assert.BytesEqual(data, downloaded.ToArray());
var manifest = await client.GetManifestAsync(sequence.Id);
Assert.Equal(Uploads.Sha(data), manifest.Frames.Single().Sha256);
}
[Test]
public async Task ADamagedChunkFailsTheHashCheck()
{
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk);
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
var data = Uploads.Photo(Chunk * 2, 5);
var start = await Uploads.StartAsync(uploader, data);
var id = start.UploadId!.Value;
var damaged = Uploads.Chunk(data, Chunk, 1).ToArray();
damaged[100] ^= 0xFF;
using (var a = await Uploads.PutChunkAsync(uploader, id, 0, Uploads.Chunk(data, Chunk, 0))) await a.ExpectAsync(HttpStatusCode.OK);
using (var b = await Uploads.PutChunkAsync(uploader, id, 1, damaged)) await b.ExpectAsync(HttpStatusCode.OK);
using var complete = await uploader.PostAsync($"/api/v1/uploads/{id}/complete", null);
await complete.ExpectErrorAsync(HttpStatusCode.UnprocessableEntity, "hash_mismatch");
using (var state = await uploader.GetAsync($"/api/v1/uploads/{id}")) Assert.Equal("failed", (await state.ReadAsync(ProtocolJson.Default.UploadState)).State);
Assert.False(server.Services.GetRequiredService<UploadStore>().Exists(id));
Assert.Empty(await server.Database.Frames.FindBySha256Async(Uploads.Sha(data)));
Assert.Empty(server.Services.GetRequiredService<FakeArchiveIngest>().Requests);
var retry = await Uploads.StartAsync(uploader, data);
Assert.NotEqual(id, retry.UploadId!.Value);
}
[Test]
public async Task ChunksAndCompletionsAreValidated()
{
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk);
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
var data = Uploads.Photo(Chunk + 10, 6);
var id = (await Uploads.StartAsync(uploader, data)).UploadId!.Value;
using (var small = await Uploads.PutChunkAsync(uploader, id, 0, new byte[10])) await small.ExpectErrorAsync(HttpStatusCode.BadRequest, "chunk_size");
using (var range = await Uploads.PutChunkAsync(uploader, id, 2, new byte[10])) await range.ExpectErrorAsync(HttpStatusCode.BadRequest, "chunk_out_of_range");
using (var early = await uploader.PostAsync($"/api/v1/uploads/{id}/complete", null)) await early.ExpectErrorAsync(HttpStatusCode.Conflict, "incomplete");
using (var name = await uploader.PostAsJsonAsync("/api/v1/uploads", new StartUploadRequest(null, "../../etc/passwd", 10, Uploads.Sha(data), null, null),
ProtocolJson.Default.StartUploadRequest))
await name.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_file_name");
using (var hash = await uploader.PostAsJsonAsync("/api/v1/uploads", new StartUploadRequest(null, "a.jpg", 10, "abc", null, null), ProtocolJson.Default.StartUploadRequest))
await hash.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_hash");
var (other, _, _) = await server.UserAsync("intruder", "uploader");
using (var foreign = await Uploads.PutChunkAsync(other, id, 0, Uploads.Chunk(data, Chunk, 0))) await foreign.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
using (var cancel = await uploader.DeleteAsync($"/api/v1/uploads/{id}")) await cancel.ExpectAsync(HttpStatusCode.NoContent);
Assert.False(server.Services.GetRequiredService<UploadStore>().Exists(id));
using var late = await Uploads.PutChunkAsync(uploader, id, 0, Uploads.Chunk(data, Chunk, 0));
await late.ExpectErrorAsync(HttpStatusCode.Conflict, "upload_state");
}
[Test]
public async Task QuotaCountsCommittedAndPendingUploads()
{
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk);
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader", quotaBytes: 100_000);
var first = Uploads.Photo(80_000, 7);
var pending = await Uploads.StartAsync(uploader, first);
using (var over = await uploader.PostAsJsonAsync("/api/v1/uploads", new StartUploadRequest(null, "b.jpg", 40_000, Uploads.Sha(Uploads.Photo(40_000, 8)), null, null),
ProtocolJson.Default.StartUploadRequest))
await over.ExpectErrorAsync(HttpStatusCode.Forbidden, "quota_exceeded");
using (var cancel = await uploader.DeleteAsync($"/api/v1/uploads/{pending.UploadId}")) await cancel.ExpectAsync(HttpStatusCode.NoContent);
await Uploads.UploadAsync(uploader, first);
using var after = await uploader.PostAsJsonAsync("/api/v1/uploads", new StartUploadRequest(null, "c.jpg", 30_000, Uploads.Sha(Uploads.Photo(30_000, 9)), null, null),
ProtocolJson.Default.StartUploadRequest);
await after.ExpectErrorAsync(HttpStatusCode.Forbidden, "quota_exceeded");
}
[Test]
public async Task FilesAboveTheLimitAreRefused()
{
await using var server = await TestServer.StartAsync(context, o => o.MaxUploadBytes = 1000);
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
using var response = await uploader.PostAsJsonAsync("/api/v1/uploads", new StartUploadRequest(null, "big.jpg", 1001, new string('0', 64), null, null),
ProtocolJson.Default.StartUploadRequest);
var error = await response.ExpectErrorAsync(HttpStatusCode.RequestEntityTooLarge, "too_large");
Assert.Equal("1000", error.Details);
}
[Test]
public async Task AbandonedUploadsExpireAndLoseTheirFiles()
{
var clock = new ManualTimeProvider();
await using var server = await TestServer.StartAsync(context, o => o.UploadRetentionHours = 48, s => s.AddSingleton<TimeProvider>(clock));
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
var id = (await Uploads.StartAsync(uploader, Uploads.Photo(1000, 10))).UploadId!.Value;
var store = server.Services.GetRequiredService<UploadStore>();
Assert.True(store.Exists(id));
// Upload rows carry real timestamps; the sweep looks 48 h past the moved clock.
clock.Advance(TimeSpan.FromHours(49));
await server.Services.GetRequiredService<UploadMaintenance>().SweepAsync(context.Cancellation);
Assert.False(store.Exists(id));
using var state = await uploader.GetAsync($"/api/v1/uploads/{id}");
Assert.Equal("cancelled", (await state.ReadAsync(ProtocolJson.Default.UploadState)).State);
}
/// <summary>Reports synchronously (Progress&lt;T&gt; posts to the thread pool and may arrive late).</summary>
private sealed class SyncProgress<T>(Action<T> report) : IProgress<T>
{
public void Report(T value) => report(value);
}
}
@@ -0,0 +1,167 @@
using System.Security.Cryptography;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Sync;
using Chronos.Protocol.Client;
using Chronos.Testing;
namespace Chronos.Server.Tests.Sync;
/// <summary>A desktop client's sync side: its own index and archive, the sync engine and a job engine, signed in to a test server.</summary>
internal sealed class SyncClient : IAsyncDisposable
{
private readonly TestContext _context;
private readonly ChronosClient _client;
private SyncClient(TestContext context, ChronosDatabase db, ArchiveService archives, Archive archive, SyncService sync, ChronosClient client, JobEngine engine)
{
_context = context;
Db = db;
Archives = archives;
Archive = archive;
Sync = sync;
_client = client;
Engine = engine;
Remote = new ChronosSyncRemote(client, ownsClient: false);
}
public ChronosDatabase Db { get; }
public ArchiveService Archives { get; }
public Archive Archive { get; }
public SyncService Sync { get; }
public JobEngine Engine { get; }
/// <summary>The connection the table and the agent use (jobs get their own from the connector).</summary>
public ChronosSyncRemote Remote { get; }
public string Server => Remote.Server;
private CancellationToken Ct => _context.Cancellation;
public static async Task<SyncClient> StartAsync(TestContext context, TestServer server, string token, string name)
{
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(name + "-db"), "chronos.db")), context.Cancellation);
var options = new ArchiveServiceOptions { Owner = name, LeaseWait = TimeSpan.FromSeconds(20) };
var archives = new ArchiveService(db, options);
var archive = await archives.CreateAsync(context.CreateTempDirectory(name + "-archive"), "Main", cancellationToken: context.Cancellation);
var sync = new SyncService(db, archives, new SyncOptions { Archive = options, ProxyCacheDirectory = context.CreateTempDirectory(name + "-proxies") });
var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), name) { Token = token };
var engine = new JobEngine(db, [.. archives.CreateJobHandlers(), .. sync.CreateJobHandlers(new Connector(client))],
new JobEngineOptions { Workers = 2, WorkerId = name, PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync(context.Cancellation);
return new SyncClient(context, db, archives, archive, sync, client, engine);
}
/// <summary>Distinct JPEGs larger than one 64 KiB chunk.</summary>
public static byte[] Photo(int seed)
{
const int width = 512, height = 384;
var pixels = new byte[width * height * 3];
new Random(seed).NextBytes(pixels);
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 95 });
}
public static string Sha(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
/// <summary>A local sequence committed through the archive ingest, optionally with project settings edited on this PC.</summary>
public async Task<Sequence> LocalAsync(string title, IReadOnlyList<byte[]> photos, string? settingsJson = null)
{
var staging = Path.Combine(Archive.RootPath, ".chronos", "staging", "test");
Directory.CreateDirectory(staging);
Guid? id = null;
for (var i = 0; i < photos.Count; i++)
{
var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part");
await File.WriteAllBytesAsync(path, photos[i], Ct);
var result = await Archives.Ingest.CommitAsync(new IngestRequest(Archive.Id, id, id is null ? title : null, null, path, $"IMG_{i + 1:0000}.JPG",
photos[i].Length, Sha(photos[i]), new DateTime(2026, 9, 28, 18, 0, 0).AddSeconds(10 * i), null), Ct);
id = result.SequenceId;
}
var sequence = (await Db.Sequences.GetAsync(id!.Value, Ct))!;
if (settingsJson is null) return sequence;
var edited = await Db.Sequences.EditAsync(sequence.Id, new Chronos.Data.Repositories.SequenceEdit { SettingsJson = settingsJson }, null, Ct);
return edited.Sequence!;
}
/// <summary>One more photo imported into a local sequence, captured at <paramref name="captured"/> (before others: it is inserted).</summary>
public async Task<IngestResult> AddPhotoAsync(Guid sequenceId, byte[] photo, DateTime captured)
{
var staging = Path.Combine(Archive.RootPath, ".chronos", "staging", "test");
Directory.CreateDirectory(staging);
var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part");
await File.WriteAllBytesAsync(path, photo, Ct);
return await Archives.Ingest.CommitAsync(new IngestRequest(Archive.Id, sequenceId, null, null, path, $"IMG_{captured:HHmmss}.JPG", photo.Length, Sha(photo),
captured, null), Ct);
}
/// <summary>An edit on this PC, as the editor makes it (project file and index, settings version + 1).</summary>
public async Task<Sequence> EditSettingsAsync(Guid sequenceId, string settingsJson)
{
var sequence = (await Db.Sequences.GetAsync(sequenceId, Ct))!;
await File.WriteAllTextAsync(new Chronos.Core.Archiving.ArchivePaths(Archive.RootPath).Sequence(sequence.Folder).ProjectPath, settingsJson, Ct);
return (await Db.Sequences.EditAsync(sequenceId, new Chronos.Data.Repositories.SequenceEdit { SettingsJson = settingsJson }, sequence.SettingsVersion, Ct))
.Sequence!;
}
/// <summary>A render of <paramref name="sequence"/> made on this PC: its file in the sequence's exports and its row.</summary>
public async Task<Render> RenderAsync(Sequence sequence, string fileName, byte[] bytes)
{
var exports = Path.Combine(Archive.RootPath, sequence.Folder, "exports");
Directory.CreateDirectory(exports);
await File.WriteAllBytesAsync(Path.Combine(exports, fileName), bytes, Ct);
var render = new Render
{
Id = Guid.CreateVersion7(),
SequenceId = sequence.Id,
PresetName = "4K HEVC",
OutputPath = sequence.Folder + "/exports/" + fileName,
Codec = "hevc",
Width = 3840,
Height = 2160,
Fps = 30,
DurationSeconds = 10,
Bytes = bytes.Length,
Created = DateTimeOffset.UtcNow,
ProducedBy = "studio",
};
await Db.Renders.InsertAsync(render, Ct);
return render;
}
public string RenderFile(Render render) => Path.Combine(Archive.RootPath, render.OutputPath);
public async Task<Job> WaitAsync(Guid jobId, JobState state = JobState.Done)
{
var until = DateTime.UtcNow.AddSeconds(60);
while (true)
{
var job = await Db.Jobs.GetAsync(jobId, Ct);
if (job?.State == state) return job;
if (job?.State is JobState.Failed && state != JobState.Failed) Assert.Fail($"Job failed: {job.Error}\n{job.LogTail}");
if (DateTime.UtcNow > until) Assert.Fail($"Job {jobId} did not reach {state} (now {job?.State})");
await Task.Delay(25, Ct);
}
}
public async Task<SyncEntry> EntryAsync(string title) => (await Sync.ListAsync(Server, Ct)).Single(e => e.Title == title);
public async ValueTask DisposeAsync()
{
await Engine.DisposeAsync();
Remote.Dispose();
_client.Dispose();
await Db.DisposeAsync();
}
/// <summary>Every job gets its own remote over the shared signed-in client.</summary>
private sealed class Connector(ChronosClient client) : ISyncConnector
{
public ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken)
{
ISyncRemote remote = new ChronosSyncRemote(client, ownsClient: false);
return ValueTask.FromResult<ISyncRemote?>(remote.Server == server ? remote : null);
}
}
}
@@ -0,0 +1,390 @@
using System.Net;
using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Repositories;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Server.Events;
using Chronos.Server.Storage;
using Chronos.Testing;
namespace Chronos.Server.Tests.Sync;
/// <summary>The client's sync engine against the real server: uploads, downloads, proxies and live events through the API.</summary>
[Category("server")]
[Timeout(180_000)]
public sealed class SyncServerTests(TestContext context)
{
private const string Window41 = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":41}}}""";
private const string Window33 = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":33}}}""";
/// <summary>How long any wait may take on a loaded runner; every wait ends as soon as what it waits for happened.</summary>
private static readonly TimeSpan Deadline = TimeSpan.FromSeconds(60);
[Test]
public async Task ASequenceUploadedFromOnePcDownloadsIdenticallyOnAnother()
{
await using var server = await StartServerAsync();
var (_, _, token) = await server.UserAsync("alberto", "editor");
await using var studio = await SyncClient.StartAsync(context, server, token, "studio");
await using var laptop = await SyncClient.StartAsync(context, server, token, "laptop");
var photos = Enumerable.Range(1, 3).Select(SyncClient.Photo).ToList();
var local = await studio.LocalAsync("Comet over the ridge", photos, Window41);
var upload = await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local);
await studio.WaitAsync(upload.Id);
var uploaded = await studio.EntryAsync("Comet over the ridge");
Assert.Equal((0, 0), (uploaded.Link!.MissingRemote, uploaded.Link.MissingLocal));
var remoteId = uploaded.Link!.RemoteId;
var onServer = Assert.NotNull(await server.Database.Sequences.GetAsync(remoteId));
Assert.Equal(41, ProjectSettings.FromJson(onServer.SettingsJson!).Exposure.DeflickerWindow.Manual, "settings travel with the originals");
var serverFrames = await server.Database.Frames.ListBySequenceAsync(remoteId);
Assert.True(serverFrames.Select(f => f.Sha256).ToHashSet().SetEquals(photos.Select(SyncClient.Sha)), "every original was committed");
await ServerIdleAsync(server);
await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation);
Assert.Equal(SyncStatus.RemoteOnly, (await laptop.EntryAsync("Comet over the ridge")).Status);
var download = await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Comet over the ridge", SyncDownloadMode.Originals,
laptop.Archive.Id);
await laptop.WaitAsync(download.Id);
var copy = await laptop.EntryAsync("Comet over the ridge");
Assert.Equal(SyncStatus.InSync, copy.Status);
Assert.Equal(SequenceOrigin.Server, copy.Local!.Origin);
// The server's analysis may have added its advice meanwhile; the copy has what the server has, the user's edit included.
Assert.True(SyncRules.SameSettings((await server.Database.Sequences.GetAsync(remoteId))!.SettingsJson, copy.Local.SettingsJson));
Assert.Equal(41, ProjectSettings.FromJson(copy.Local.SettingsJson!).Exposure.DeflickerWindow.Manual);
var files = (await laptop.Db.Frames.ListBySequenceAsync(copy.Local.Id))
.Select(f => File.ReadAllBytes(Path.Combine(laptop.Archive.RootPath, f.RelativePath))).ToList();
Assert.True(files.Select(SyncClient.Sha).ToHashSet().SetEquals(photos.Select(SyncClient.Sha)), "byte-identical originals");
await studio.Sync.RefreshAsync(studio.Remote, new SyncPolicy(), context.Cancellation);
Assert.Equal(SyncStatus.InSync, (await studio.EntryAsync("Comet over the ridge")).Status);
}
[Test]
public async Task AnUploadInterruptedMidFileResumesTheServersPartialUpload()
{
await using var server = await StartServerAsync();
var (http, _, token) = await server.UserAsync("alberto", "editor");
await using var studio = await SyncClient.StartAsync(context, server, token, "studio");
var photos = Enumerable.Range(10, 2).Select(SyncClient.Photo).ToList();
var local = await studio.LocalAsync("Clouds", photos);
// The crashed attempt had sent the first original (which created the server sequence) and one chunk of the second.
var first = await Uploads.UploadAsync(http, photos[0], "IMG_0001.JPG", sessionKey: "crashed-attempt");
var partial = await Uploads.StartAsync(http, photos[1], "IMG_0002.JPG", first.SequenceId);
Assert.True(photos[1].Length > partial.ChunkSize, "the photo spans several chunks");
using (var chunk = await Uploads.PutChunkAsync(http, partial.UploadId!.Value, 0, Uploads.Chunk(photos[1], partial.ChunkSize, 0)))
await chunk.ExpectAsync(HttpStatusCode.OK);
var job = new Job
{
Id = Guid.CreateVersion7(),
Kind = JobKind.UploadCommit,
TargetIds = [local.Id],
TargetLabel = "Clouds",
ParametersJson = $$"""{"server":"{{studio.Server}}"}""",
Checkpoint = first.SequenceId.ToString(),
State = JobState.Queued,
Created = DateTimeOffset.UtcNow,
};
await studio.Db.Jobs.EnqueueAsync(job, context.Cancellation);
studio.Engine.Wake();
await studio.WaitAsync(job.Id);
var resumed = Assert.NotNull(await server.Database.Uploads.GetAsync(partial.UploadId!.Value));
Assert.Equal(Chronos.Data.Repositories.UploadState.Committed, resumed.State);
Assert.Equal(2, (await server.Database.Frames.ListBySequenceAsync(first.SequenceId)).Count);
// Every original is on both sides (the server's analysis may still be editing the settings).
var link = (await studio.EntryAsync("Clouds")).Link!;
Assert.Equal((first.SequenceId, 0, 0), (link.RemoteId, link.MissingRemote, link.MissingLocal));
}
[Test]
public async Task ADownloadResumesPartialFilesAndRefusesDamagedOnes()
{
await using var server = await StartServerAsync();
var (_, _, token) = await server.UserAsync("alberto", "editor");
await using var studio = await SyncClient.StartAsync(context, server, token, "studio");
await using var laptop = await SyncClient.StartAsync(context, server, token, "laptop");
var photos = Enumerable.Range(20, 4).Select(SyncClient.Photo).ToList();
var local = await studio.LocalAsync("Aurora", photos);
await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id);
var remoteId = (await studio.EntryAsync("Aurora")).Link!.RemoteId;
// An earlier attempt left half of one original, a damaged half of another, a third complete (stopped while it was
// being hashed) and a fourth longer than the file: the server cannot resume either of the last two (416).
var staging = Path.Combine(laptop.Archive.RootPath, ".chronos", "staging", "sync-" + remoteId.ToString("N"));
Directory.CreateDirectory(staging);
await File.WriteAllBytesAsync(Path.Combine(staging, SyncClient.Sha(photos[0]) + ".jpg.part"), photos[0][..(photos[0].Length / 2)]);
await File.WriteAllBytesAsync(Path.Combine(staging, SyncClient.Sha(photos[1]) + ".jpg.part"), new byte[photos[1].Length / 2]);
await File.WriteAllBytesAsync(Path.Combine(staging, SyncClient.Sha(photos[2]) + ".jpg.part"), photos[2]);
await File.WriteAllBytesAsync(Path.Combine(staging, SyncClient.Sha(photos[3]) + ".jpg.part"), [.. photos[3], .. new byte[64]]);
await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation);
var download = await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Aurora", SyncDownloadMode.Originals, laptop.Archive.Id);
await laptop.WaitAsync(download.Id);
var copy = Assert.NotNull((await laptop.EntryAsync("Aurora")).Local);
var hashes = (await laptop.Db.Frames.ListBySequenceAsync(copy.Id))
.Select(f => SyncClient.Sha(File.ReadAllBytes(Path.Combine(laptop.Archive.RootPath, f.RelativePath)))).ToHashSet();
Assert.True(hashes.SetEquals(photos.Select(SyncClient.Sha)), "every original arrived intact");
Assert.False(Directory.Exists(staging), "staging cleaned up");
}
[Test]
public async Task ServerEventsUpdateThisPcWithoutWaitingForTheNextComparison()
{
await using var server = await StartServerAsync();
var (http, _, token) = await server.UserAsync("alberto", "editor");
await using var studio = await SyncClient.StartAsync(context, server, token, "studio");
var local = await studio.LocalAsync("Harbour sunset", [SyncClient.Photo(30)]);
await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id);
var remoteId = (await studio.EntryAsync("Harbour sunset")).Link!.RemoteId;
await ServerIdleAsync(server);
await using var agent = new SyncAgent(studio.Sync, studio.Remote, () => new SyncPolicy(), studio.Engine,
new SyncAgentOptions { RefreshInterval = TimeSpan.FromHours(1), EventDelay = TimeSpan.FromMilliseconds(50) });
agent.Start();
var hub = server.Services.GetRequiredService<EventHub>();
await UntilAsync(() => Task.FromResult(agent.Snapshot is not null && hub.SubscriberCount > 0), "the agent's first comparison and event socket");
// Someone edits the project on the server (web or another PC). The comparison its event starts writes the
// settings on this PC before the link that records the agreement: wait for the comparison, not for the settings.
var compared = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
studio.Sync.Changed += _ => compared.TrySetResult();
using (var patch = await http.PatchAsJsonAsync($"/api/v1/sequences/{remoteId}",
new UpdateSequenceRequest(null, null, null, null, Window33, null), ProtocolJson.Default.UpdateSequenceRequest))
await patch.ExpectAsync(HttpStatusCode.OK);
await SignalAsync(compared.Task, "the comparison of the edit");
Assert.Equal(33, ProjectSettings.FromJson((await studio.Db.Sequences.GetAsync(local.Id))!.SettingsJson ?? "{}").Exposure.DeflickerWindow.Manual,
"the edit reached this PC");
Assert.Equal(SyncStatus.InSync, (await studio.EntryAsync("Harbour sunset")).Status);
}
[Test]
public async Task ARemoteSequenceOpensWithProxiesOnly()
{
await using var server = await StartServerAsync();
var (_, _, token) = await server.UserAsync("alberto", "editor");
await using var studio = await SyncClient.StartAsync(context, server, token, "studio");
await using var laptop = await SyncClient.StartAsync(context, server, token, "laptop");
var photos = Enumerable.Range(40, 2).Select(SyncClient.Photo).ToList();
var local = await studio.LocalAsync("Milan skyline dusk", photos, Window41);
await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id);
var remoteId = (await studio.EntryAsync("Milan skyline dusk")).Link!.RemoteId;
await ServerIdleAsync(server);
Assert.True(((await server.Database.Sequences.GetAsync(remoteId))!.Status & SequenceStatus.ThumbsBuilt) != 0, "thumbnails on the server");
// A remote card without a hero frame shows its first frame, read as one row instead of the whole list.
ISyncRemote remote = laptop.Remote;
Assert.Equal((await remote.ListFramesAsync(remoteId, context.Cancellation))[0].Id, (await remote.FirstFrameAsync(remoteId, context.Cancellation))?.Id);
await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation);
var job = await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Milan skyline dusk", SyncDownloadMode.Proxies, null);
await laptop.WaitAsync(job.Id);
Assert.Equal(SyncStatus.ProxiesOnly, (await laptop.EntryAsync("Milan skyline dusk")).Status);
Assert.Empty((await laptop.Db.Sequences.ListAsync(new SequenceQuery())).Items);
var opened = Assert.NotNull(laptop.Sync.OpenRemote(laptop.Server, remoteId));
Assert.Equal(2, opened.CachedCount);
Assert.Equal(41, ProjectSettings.FromJson(opened.Sequence.SettingsJson!).Exposure.DeflickerWindow.Manual);
var source = opened.OpenFrames(DecoderFactory.CreateServer());
await using (source as IAsyncDisposable)
{
using var frame = await source.GetFrameAsync(0, 0, DecodePurpose.Render, context.Cancellation);
Assert.True(frame.Width > 0 && frame.Height > 0, "a proxy decodes");
}
}
[Test]
public async Task RendersTravelOnRequestWithTheirIdAndAreVerified()
{
await using var server = await StartServerAsync();
var (_, _, token) = await server.UserAsync("alberto", "editor");
await using var studio = await SyncClient.StartAsync(context, server, token, "studio");
await using var laptop = await SyncClient.StartAsync(context, server, token, "laptop");
var photos = Enumerable.Range(50, 2).Select(SyncClient.Photo).ToList();
var local = await studio.LocalAsync("Star trails", photos);
await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id);
var remoteId = (await studio.EntryAsync("Star trails")).Link!.RemoteId;
await ServerIdleAsync(server);
// A render made on the studio PC, larger than one chunk, is sent on request and keeps its id.
var output = Enumerable.Range(0, 200_000).Select(i => (byte)(i * 31)).ToArray();
var render = await studio.RenderAsync(local, "Star trails 4K.mp4", output);
await studio.Sync.RefreshAsync(studio.Remote, new SyncPolicy(), context.Cancellation);
Assert.Equal(1, (await studio.EntryAsync("Star trails")).Link!.ExportsToSend);
await studio.WaitAsync((await studio.Sync.EnqueueSendExportsAsync(studio.Engine, studio.Server, local)).Id);
var filed = Assert.NotNull(await server.Database.Renders.GetAsync(render.Id));
Assert.Equal(remoteId, filed.SequenceId);
Assert.SequenceEqual(output, await File.ReadAllBytesAsync(Path.Combine(server.Options.ArchivePath, filed.OutputPath)));
Assert.Equal(0, (await studio.EntryAsync("Star trails")).Link!.ExportsToSend);
Assert.Null(await studio.Remote.UploadRenderAsync(remoteId, studio.RenderFile(render), new RenderUploadRequest(render.Id, "Star trails 4K.mp4",
output.Length, SyncClient.Sha(output), "4K HEVC", "hevc", 3840, 2160, 30, 10, "studio"), context.Cancellation));
// A damaged transfer is refused at completion.
var bad = new RenderUploadRequest(Guid.CreateVersion7(), "Damaged.mp4", output.Length, SyncClient.Sha(output), "4K HEVC", "hevc", 3840, 2160, 30, 10, null);
var damaged = Path.Combine(context.CreateTempDirectory("damaged"), "Damaged.mp4");
await File.WriteAllBytesAsync(damaged, [.. output.Select(b => (byte)~b)]);
var refused = await Assert.ThrowsAsync<Chronos.Protocol.Client.ChronosApiException>(() =>
studio.Remote.UploadRenderAsync(remoteId, damaged, bad, context.Cancellation));
Assert.Equal(HttpStatusCode.UnprocessableEntity, refused.Status);
Assert.Null(await server.Database.Renders.GetAsync(bad.RenderId));
// Another PC with the originals gets the render into its own exports, byte-identical.
await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation);
await laptop.WaitAsync((await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Star trails", SyncDownloadMode.Originals,
laptop.Archive.Id)).Id);
Assert.Equal(1, (await laptop.EntryAsync("Star trails")).Link!.ExportsToGet);
await laptop.WaitAsync((await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Star trails", SyncDownloadMode.Exports, null)).Id);
var copy = (await laptop.EntryAsync("Star trails")).Local!;
var fetched = Assert.Contains(await laptop.Db.Renders.ListBySequenceAsync(copy.Id), r => r.Id == render.Id);
Assert.SequenceEqual(output, await File.ReadAllBytesAsync(Path.Combine(laptop.Archive.RootPath, fetched.OutputPath)));
Assert.Equal(0, (await laptop.EntryAsync("Star trails")).Link!.ExportsToGet);
}
[Test]
public async Task PositionsEditedOnTheServerStayOnTheirPhotosWhenAnotherPcDownloadsTheInsertedFrames()
{
await using var server = await StartServerAsync();
var (http, _, token) = await server.UserAsync("alberto", "editor");
await using var studio = await SyncClient.StartAsync(context, server, token, "studio");
await using var laptop = await SyncClient.StartAsync(context, server, token, "laptop");
var photos = Enumerable.Range(60, 5).Select(SyncClient.Photo).ToList();
// Both PCs hold the last four photos, the third of them excluded.
var local = await studio.LocalAsync("Harbour at dawn", photos[1..], new ProjectSettings { ExcludedFrames = [2] }.ToJson());
await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id);
var remoteId = (await studio.EntryAsync("Harbour at dawn")).Link!.RemoteId;
await ServerIdleAsync(server);
await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation);
await laptop.WaitAsync((await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Harbour at dawn", SyncDownloadMode.Originals,
laptop.Archive.Id)).Id);
var copy = (await laptop.EntryAsync("Harbour at dawn")).Local!;
// The studio files an earlier photo and uploads it: the server inserts it first and moves its own positions.
await studio.AddPhotoAsync(local.Id, photos[0], new DateTime(2026, 9, 28, 17, 59, 50));
await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id);
await ServerIdleAsync(server);
Assert.SequenceEqual([SyncClient.Sha(photos[3])], (await ServerNamedAsync(server, remoteId)).Excluded);
// An editor on the server excludes the new photo too, by the server's frames, and changes the deflicker window.
var row = (await server.Database.Sequences.GetAsync(remoteId))!;
var current = ProjectSettings.FromJson(row.SettingsJson!);
var edit = current with
{
ExcludedFrames = [0, .. current.ExcludedFrames],
Exposure = current.Exposure with { DeflickerWindow = new Auto<int>().WithManual(33) },
};
using (var patch = await http.PatchAsJsonAsync($"/api/v1/sequences/{remoteId}",
new UpdateSequenceRequest(null, null, null, null, edit.ToJson(), row.SettingsVersion), ProtocolJson.Default.UpdateSequenceRequest))
await patch.ExpectAsync(HttpStatusCode.OK);
// The laptop takes the edit while it still lacks the new photo, then downloads it.
await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation);
var taken = await LocalNamedAsync(laptop, copy.Id);
Assert.Equal(33, taken.Project.Exposure.DeflickerWindow.Manual);
Assert.SequenceEqual([SyncClient.Sha(photos[3])], taken.Excluded);
Assert.True(taken.Project.PendingFrames is [{ Excluded: true } waiting] && waiting.Sha256 == SyncClient.Sha(photos[0]), "the new photo's exclusion waits for it");
await laptop.WaitAsync((await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Harbour at dawn", SyncDownloadMode.Originals,
null)).Id);
var onServer = await ServerNamedAsync(server, remoteId);
var here = await LocalNamedAsync(laptop, copy.Id);
Assert.SequenceEqual([SyncClient.Sha(photos[0]), SyncClient.Sha(photos[3])], here.Excluded);
Assert.SequenceEqual(onServer.Excluded, here.Excluded);
Assert.Equal(onServer.Hero, here.Hero);
Assert.Null(here.Project.PendingFrames);
await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation);
Assert.Equal(SyncStatus.InSync, (await laptop.EntryAsync("Harbour at dawn")).Status);
}
[Test]
public async Task PositionsSentBeforeTheirPhotosStayOnThemWhenTheUploadArrives()
{
await using var server = await StartServerAsync();
var (_, _, token) = await server.UserAsync("alberto", "editor");
await using var studio = await SyncClient.StartAsync(context, server, token, "studio");
var photos = Enumerable.Range(70, 5).Select(SyncClient.Photo).ToList();
var local = await studio.LocalAsync("Pier", photos[1..]);
await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id);
var remoteId = (await studio.EntryAsync("Pier")).Link!.RemoteId;
await ServerIdleAsync(server);
await studio.Sync.RefreshAsync(studio.Remote, new SyncPolicy(), context.Cancellation);
// This PC files an earlier photo and, before uploading it, excludes it and a later one and picks the hero.
await studio.AddPhotoAsync(local.Id, photos[0], new DateTime(2026, 9, 28, 17, 59, 50));
var project = ProjectSettings.FromJson((await studio.Db.Sequences.GetAsync(local.Id))!.SettingsJson ?? "{}");
await studio.EditSettingsAsync(local.Id, (project with { ExcludedFrames = [0, 3], HeroFrame = 1 }).ToJson());
await studio.Sync.RefreshAsync(studio.Remote, new SyncPolicy(), context.Cancellation);
var sent = await ServerNamedAsync(server, remoteId);
Assert.SequenceEqual([SyncClient.Sha(photos[3])], sent.Excluded);
Assert.Equal(SyncClient.Sha(photos[1]), sent.Hero);
Assert.True(sent.Project.PendingFrames is [{ Excluded: true } waiting] && waiting.Sha256 == SyncClient.Sha(photos[0]), "the exclusion waits for its photo");
await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id);
await ServerIdleAsync(server);
var arrived = await ServerNamedAsync(server, remoteId);
Assert.SequenceEqual([SyncClient.Sha(photos[0]), SyncClient.Sha(photos[3])], arrived.Excluded);
Assert.Equal(SyncClient.Sha(photos[1]), arrived.Hero);
Assert.Null(arrived.Project.PendingFrames);
var heroFrame = (await server.Database.Sequences.GetAsync(remoteId))!.HeroFrameId;
Assert.Equal(SyncClient.Sha(photos[1]), (await server.Database.Frames.ListBySequenceAsync(remoteId)).Single(f => f.Id == heroFrame).Sha256);
var here = await LocalNamedAsync(studio, local.Id);
Assert.SequenceEqual(arrived.Excluded, here.Excluded);
Assert.Equal(arrived.Hero, here.Hero);
await studio.Sync.RefreshAsync(studio.Remote, new SyncPolicy(), context.Cancellation);
Assert.Equal(SyncStatus.InSync, (await studio.EntryAsync("Pier")).Status);
}
/// <summary>The server's project and the photos (SHA-256) it excludes and shows as hero.</summary>
private static async Task<(ProjectSettings Project, string?[] Excluded, string? Hero)> ServerNamedAsync(TestServer server, Guid remoteId)
{
var project = ProjectSettings.FromJson((await server.Database.Sequences.GetAsync(remoteId))!.SettingsJson ?? "{}");
var frames = await server.Database.Frames.ListBySequenceAsync(remoteId);
return (project, [.. project.ExcludedFrames.Select(i => frames[i].Sha256)], project.HeroFrame is { } hero ? frames[hero].Sha256 : null);
}
/// <summary>A PC's project and the photos (SHA-256) it excludes and shows as hero.</summary>
private static async Task<(ProjectSettings Project, string?[] Excluded, string? Hero)> LocalNamedAsync(SyncClient client, Guid localId)
{
var project = ProjectSettings.FromJson((await client.Db.Sequences.GetAsync(localId))!.SettingsJson ?? "{}");
var frames = await client.Db.Frames.ListBySequenceAsync(localId);
return (project, [.. project.ExcludedFrames.Select(i => frames[i].Sha256)], project.HeroFrame is { } hero ? frames[hero].Sha256 : null);
}
private Task<TestServer> StartServerAsync() => TestServer.StartAsync(context, o => o.ChunkSizeBytes = 64 * 1024, ArchiveModule.Register);
/// <summary>Waits until the server's engines finished what the commits queued (thumbnails, proxies, analysis, which may edit settings).</summary>
private Task ServerIdleAsync(TestServer server) =>
UntilAsync(async () => await server.Database.Jobs.CountAsync(DateTimeOffset.UtcNow) is { Queued: 0, Running: 0 }, "the server's jobs");
private async Task UntilAsync(Func<Task<bool>> condition, string what)
{
var until = DateTime.UtcNow + Deadline;
while (!await condition())
{
if (DateTime.UtcNow > until) Assert.Fail("Timed out waiting for " + what);
await Task.Delay(50, context.Cancellation);
}
}
private async Task SignalAsync(Task signal, string what)
{
try
{
await signal.WaitAsync(Deadline, context.Cancellation);
}
catch (TimeoutException)
{
Assert.Fail("Timed out waiting for " + what);
}
}
}
+153
View File
@@ -0,0 +1,153 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Protocol;
using Chronos.Server.Configuration;
using Chronos.Server.Hosting;
using Chronos.Server.Storage;
using Chronos.Testing;
namespace Chronos.Server.Tests;
/// <summary>
/// In-process Kestrel on ephemeral ports with temporary archive/data folders and a SQLite database (BRIEF §20.1).
/// The archive module is replaced by <see cref="FakeArchiveIngest"/> and <see cref="FakeAssetLocator"/>.
/// </summary>
public sealed class TestServer : IAsyncDisposable
{
public const string AdminPassword = "first-admin-pass";
public const string Password = "a-good-password-1";
private readonly WebApplication _app;
private readonly List<HttpClient> _clients = [];
private string _adminPassword = AdminPassword;
private TestServer(WebApplication app, ServerOptions options, Uri http, Uri? https)
{
_app = app;
Options = options;
HttpBase = http;
HttpsBase = https;
Client = NewClient();
}
public ServerOptions Options { get; }
public Uri HttpBase { get; }
public Uri? HttpsBase { get; }
/// <summary>An anonymous client.</summary>
public HttpClient Client { get; }
public IServiceProvider Services => _app.Services;
public ChronosDatabase Database => Services.GetRequiredService<ChronosDatabase>();
public static async Task<TestServer> StartAsync(TestContext context, Action<ServerOptions>? configure = null, Action<IServiceCollection>? services = null)
{
var root = context.CreateTempDirectory("server");
var options = new ServerOptions
{
DataPath = Path.Combine(root, "data"),
ArchivePath = Path.Combine(root, "archive"),
HttpPort = 0,
HttpsPort = 0,
TlsMode = TlsMode.Auto,
Database = DatabaseKind.Sqlite,
Discovery = false,
Parallelism = 2,
AdminUser = "admin",
AdminPassword = AdminPassword,
// Tests sign in many times from one address; the rate-limit test sets the production value.
LoginAttemptsPerMinute = 1000,
// Info lines of the ~55 servers the suite starts would bury failures in the CI log.
LogLevel = Microsoft.Extensions.Logging.LogLevel.Warning,
};
Directory.CreateDirectory(options.ArchivePath);
configure?.Invoke(options);
var app = ServerHost.Build(options, [], s =>
{
s.AddSingleton<FakeArchiveIngest>();
s.TryAddSingleton<IArchiveIngest>(sp => sp.GetRequiredService<FakeArchiveIngest>());
s.AddSingleton<FakeAssetLocator>();
s.TryAddSingleton<IFrameAssetLocator>(sp => sp.GetRequiredService<FakeAssetLocator>());
services?.Invoke(s);
});
await app.StartAsync(context.Cancellation);
var addresses = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses
.Select(a => new Uri(a.Replace("[::]", "127.0.0.1", StringComparison.Ordinal).Replace("0.0.0.0", "127.0.0.1", StringComparison.Ordinal)))
.ToList();
var http = addresses.First(a => a.Scheme == "http");
var https = addresses.FirstOrDefault(a => a.Scheme == "https");
return new TestServer(app, options, http, https);
}
/// <summary>A plain HTTP client (owned by the server, disposed with it).</summary>
public HttpClient NewClient(string? token = null)
{
var client = new HttpClient { BaseAddress = HttpBase, Timeout = TimeSpan.FromSeconds(60) };
if (token is not null) client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
_clients.Add(client);
return client;
}
/// <summary>An HTTPS client with a cookie jar that trusts the self-signed certificate (admin panel sessions).</summary>
public HttpClient NewCookieClient(CookieContainer cookies)
{
var handler = new HttpClientHandler { CookieContainer = cookies, ServerCertificateCustomValidationCallback = (_, _, _, _) => true };
var client = new HttpClient(handler) { BaseAddress = HttpsBase, Timeout = TimeSpan.FromSeconds(60) };
_clients.Add(client);
return client;
}
public async Task<LoginResponse> LoginAsync(string username, string password, string clientName = "tests")
{
using var response = await Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, password, clientName), ProtocolJson.Default.LoginRequest);
if (!response.IsSuccessStatusCode) throw new InvalidOperationException($"Login of {username} failed: {(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");
return (await response.Content.ReadFromJsonAsync(ProtocolJson.Default.LoginResponse))!;
}
/// <summary>The bootstrap administrator, signed in; its first sign-in replaces the bootstrap password with <see cref="Password"/>.</summary>
public async Task<HttpClient> AdminAsync()
{
var login = await LoginAsync("admin", _adminPassword);
var client = NewClient(login.Token);
if (login.MustChangePassword)
{
using var changed = await client.PostAsJsonAsync("/api/v1/auth/password", new ChangePasswordRequest(_adminPassword, Password),
ProtocolJson.Default.ChangePasswordRequest);
changed.EnsureSuccessStatusCode();
_adminPassword = Password;
}
return client;
}
/// <summary>Creates a user (through the admin API) who has set <see cref="Password"/>, and returns a client signed in as them.</summary>
public async Task<(HttpClient Client, UserDto User, string Token)> UserAsync(string username, string role, long quotaBytes = 0, bool renderNode = false)
{
var admin = await AdminAsync();
using var created = await admin.PostAsJsonAsync("/api/v1/users", new CreateUserRequest(username, null, role, quotaBytes, null, renderNode),
ProtocolJson.Default.CreateUserRequest);
created.EnsureSuccessStatusCode();
var temporary = (await created.Content.ReadFromJsonAsync(ProtocolJson.Default.TemporaryPasswordResponse))!;
var first = await LoginAsync(username, temporary.TemporaryPassword);
var client = NewClient(first.Token);
using var changed = await client.PostAsJsonAsync("/api/v1/auth/password", new ChangePasswordRequest(temporary.TemporaryPassword, Password),
ProtocolJson.Default.ChangePasswordRequest);
changed.EnsureSuccessStatusCode();
return (client, temporary.User, first.Token!);
}
public async ValueTask DisposeAsync()
{
foreach (var client in _clients) client.Dispose();
await _app.StopAsync();
await _app.DisposeAsync();
}
}
+57
View File
@@ -0,0 +1,57 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Security.Cryptography;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Server.Tests;
/// <summary>Raw-HTTP upload helpers (the protocol client is exercised separately).</summary>
internal static class Uploads
{
public static byte[] Photo(int size, int seed)
{
var bytes = new byte[size];
new Random(seed).NextBytes(bytes);
return bytes;
}
public static string Sha(byte[] data) => Convert.ToHexStringLower(SHA256.HashData(data));
public static async Task<StartUploadResponse> StartAsync(HttpClient client, byte[] data, string fileName = "IMG_0001.CR3", Guid? sequenceId = null,
string? sessionKey = null, HttpStatusCode expected = HttpStatusCode.Created)
{
using var response = await client.PostAsJsonAsync("/api/v1/uploads",
new StartUploadRequest(sequenceId, fileName, data.Length, Sha(data), new DateTime(2026, 9, 28, 18, 2, 11), sessionKey), ProtocolJson.Default.StartUploadRequest);
await response.ExpectAsync(expected);
return await response.ReadAsync(ProtocolJson.Default.StartUploadResponse);
}
public static async Task<HttpResponseMessage> PutChunkAsync(HttpClient client, Guid uploadId, int index, ReadOnlyMemory<byte> data)
{
var content = new ByteArrayContent(data.ToArray());
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return await client.PutAsync($"/api/v1/uploads/{uploadId}/chunks/{index}", content);
}
public static ReadOnlyMemory<byte> Chunk(byte[] data, int chunkSize, int index) =>
data.AsMemory(index * chunkSize, Math.Min(chunkSize, data.Length - index * chunkSize));
/// <summary>Start, every chunk, complete; returns the committed frame.</summary>
public static async Task<CompleteUploadResponse> UploadAsync(HttpClient client, byte[] data, string fileName = "IMG_0001.CR3", Guid? sequenceId = null,
string? sessionKey = null)
{
var start = await StartAsync(client, data, fileName, sequenceId, sessionKey);
var id = Assert.NotNull(start.UploadId);
var chunks = (data.Length + start.ChunkSize - 1) / start.ChunkSize;
for (var i = 0; i < chunks; i++)
{
using var put = await PutChunkAsync(client, id, i, Chunk(data, start.ChunkSize, i));
await put.ExpectAsync(HttpStatusCode.OK);
}
using var complete = await client.PostAsync($"/api/v1/uploads/{id}/complete", null);
await complete.ExpectAsync(HttpStatusCode.OK);
return await complete.ReadAsync(ProtocolJson.Default.CompleteUploadResponse);
}
}