From ac9a15002792594c7eb2a4f2d7c687a17432ada0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 13:00:38 +0000 Subject: [PATCH] feat(server): run on the real archive engine ArchiveModule registers the archive engine as the server's ingest, its proxy/thumbnail locator and its job handlers (through the new IJobHandlerProvider); Program.cs passes it to ServerHost.Build. The server opens its archive through ArchiveService so archive.json always exists. The server's path-safety helper is renamed ArchivePathGuard to stop clashing with the archive layout's ArchivePaths, and the server migration is renumbered 0003. An end-to-end test uploads a photo, finds it in the layout and fetches the thumbnail built by the queued job. CI's PostgreSQL jobs now run the server tests too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .github/workflows/ci.yml | 2 + docs/DECISIONS.md | 9 ++++ src/Titano.Data/Archiving/ArchiveService.cs | 2 +- src/Titano.Data/Jobs/JobHandler.cs | 6 +++ src/Titano.Server/Api/FileEndpoints.cs | 6 +-- src/Titano.Server/Api/SequenceEndpoints.cs | 2 +- src/Titano.Server/Hosting/ServerHost.cs | 2 +- src/Titano.Server/Jobs/JobEngineHost.cs | 8 +-- src/Titano.Server/Program.cs | 5 +- .../Storage/ArchiveAssetLocator.cs | 34 ++++++++++++ src/Titano.Server/Storage/ArchiveModule.cs | 23 ++++++++ .../{ArchivePaths.cs => ArchivePathGuard.cs} | 2 +- src/Titano.Server/Storage/RenderStore.cs | 2 +- src/Titano.Server/Storage/ServerArchive.cs | 17 +++--- .../Storage/ArchiveModuleTests.cs | 52 +++++++++++++++++++ 15 files changed, 150 insertions(+), 22 deletions(-) create mode 100644 src/Titano.Server/Storage/ArchiveAssetLocator.cs create mode 100644 src/Titano.Server/Storage/ArchiveModule.cs rename src/Titano.Server/Storage/{ArchivePaths.cs => ArchivePathGuard.cs} (98%) create mode 100644 tests/Titano.Server.Tests/Storage/ArchiveModuleTests.cs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8de0e028..926ad0c4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -188,6 +188,8 @@ jobs: global-json-file: global.json - name: Test · Data (PostgreSQL) run: dotnet run --project tests/Titano.Data.Tests -c Release -- --junit out/junit/data-pg${{ matrix.pg }}.xml + - name: Test · Server (PostgreSQL) + run: dotnet run --project tests/Titano.Server.Tests -c Release -- --junit out/junit/server-pg${{ matrix.pg }}.xml - name: Upload test results if: always() uses: actions/upload-artifact@v4 diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index f797779d..139d93f8 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -113,3 +113,12 @@ One line per decision: date · decision · alternative · reason. | 2026-10-02 | Desktop thumbnails: widths rounded up to 64 px, LRU of 2000 items, at most cores/2 (2–6) decodes, "no image" cached but failures not, a decode is cancelled when its card scrolls away; job list updates batched to ~10 Hz keeping the latest per job. | Fixed size per card / update per event | Fewer decodes, bounded memory, a free UI thread during fast renders. | | 2026-10-02 | Server sign-in in the client: an unknown certificate fingerprint is confirmed before any password is sent, a changed certificate never receives the saved token, the token is stored only DPAPI-encrypted. | Trust on login | BRIEF §14.2. | | 2026-10-02 | The client update check reads the latest non-draft, non-prerelease GitHub release of `TitanoReleasesRepo` and only opens its page; Clear cache deletes only folders carrying a `.titano-cache` marker, after confirmation; `--capture` runs on a temporary data folder with fake server, encoders and update check. | Download updates / clear any folder / real data | No external processes; never delete user data; CI never touches user data. | +| 2026-10-02 | The server registers the archive engine in `ArchiveModule` (ingest, asset locator, job handlers through `IJobHandlerProvider`) and opens its archive through `ArchiveService.AdoptAsync`; `ServerHost.Build` keeps the registration callback so tests can substitute fakes, and still refuses to start without ingest and locator. | Hard-wired registrations / DB row only | Tests stay isolated; the archive always has `.titano/archive.json`, so scans and ingest work from the first start. | +| 2026-10-02 | Admin cookies are `Secure`: cookie sign-in over plain HTTP only from loopback, `/admin` over HTTP from other hosts redirects to HTTPS; CSRF token derived from the session token's hash, cookie WebSocket upgrades must be same-origin. | Drop `Secure` / random double-submit cookie | BRIEF §14.2; a planted cookie pair cannot forge the token. | +| 2026-10-02 | Sign-in rate limit and lockout live in memory and apply to unknown names too; the generated first admin password goes to an owner-only file deleted once an admin sets a password; minimum password length 10; admin-created users must change their password; resets give a temporary password. | DB columns / log the password / email links | No user enumeration; secrets never logged; no mail infrastructure. | +| 2026-10-02 | API errors are localised through `Accept-Language` (fallback `TITANO_LANG`); ETags on sequences, manifests and originals (SHA-256) with `If-Match` doubling as the expected settings version. | English only / version in body only | Every user-visible string is a resource; standard HTTP caching and concurrency. | +| 2026-10-02 | Deleting a sequence moves its folder to `/.titano/trash/` (with dry run); upload completion is synchronous and idempotent, survives client disconnect, and a failed ingest returns the upload to receiving (503). | Erase files / async commit job | User data rule 8 and undo; clients need the frame id at once and retries stay safe. | +| 2026-10-02 | Quota = used + pending uploads + new size, checked at start and at commit (render outputs not counted); the duplicate short-circuit matches a hash anywhere, preferring the target sequence; at most 8 concurrent chunk uploads per user (429), bodies capped at 1 MiB except chunks. | Committed bytes only / per-sequence only / request-rate limiter | Parallel uploads cannot slip past the quota; the brief's wording; simplest effective limit. | +| 2026-10-02 | Render jobs never run on the server engine: render nodes claim them by codec and resolution, report failures, and a job fails after losing its node 5 times. | Managed rendering on the server | No server render handler yet. | +| 2026-10-02 | Server settings page writes only edited keys to `server.json`; environment-fixed settings are locked; restart-only keys are flagged. Windows service: LocalSystem, automatic start, name `TitanoServer`. Admin panel: strict CSP (SVG charts, no inline styles), light theme only. | Rewrite the whole file / theme toggle | Secrets never written; DESIGN.md wins over the mockup toggle. | +| 2026-10-02 | Migrations are numbered without gaps (0001 initial, 0002 archive index, 0003 server uploads). | Keep 0005 | Parallel workstreams picked numbers to avoid collisions; renumbered at merge. | diff --git a/src/Titano.Data/Archiving/ArchiveService.cs b/src/Titano.Data/Archiving/ArchiveService.cs index 9463c422..96a62969 100644 --- a/src/Titano.Data/Archiving/ArchiveService.cs +++ b/src/Titano.Data/Archiving/ArchiveService.cs @@ -13,7 +13,7 @@ namespace Titano.Data.Archiving; /// or adopt an archive, plan and apply mass renames, plan imports and card erases, query duplicates and orphans, and /// the job handlers for the long operations (enqueue them with ). /// -public sealed class ArchiveService +public sealed class ArchiveService : IJobHandlerProvider { private readonly TitanoDatabase _db; private readonly SequenceWriter _writer; diff --git a/src/Titano.Data/Jobs/JobHandler.cs b/src/Titano.Data/Jobs/JobHandler.cs index a8c18705..52539c9a 100644 --- a/src/Titano.Data/Jobs/JobHandler.cs +++ b/src/Titano.Data/Jobs/JobHandler.cs @@ -13,6 +13,12 @@ public interface IJobHandler Task RunAsync(JobContext context); } +/// A component that brings several handlers (the archive engine: scan, rebuild, verify, import, images, maintenance). +public interface IJobHandlerProvider +{ + IReadOnlyList CreateJobHandlers(); +} + /// Live progress of a running job (pushed to the job bar, the Jobs screen and WebSocket clients). public sealed record JobProgressInfo(Guid JobId, JobKind Kind, string? TargetLabel, long Done, long Total, double? ItemsPerSecond, TimeSpan? Eta, string? Message); diff --git a/src/Titano.Server/Api/FileEndpoints.cs b/src/Titano.Server/Api/FileEndpoints.cs index 71bfc53e..76cf182f 100644 --- a/src/Titano.Server/Api/FileEndpoints.cs +++ b/src/Titano.Server/Api/FileEndpoints.cs @@ -29,7 +29,7 @@ public static class FileEndpoints private static async Task OriginalAsync(HttpContext context, Guid id, TitanoDatabase db, ServerArchive archive) { if (await db.Frames.GetAsync(id, context.RequestAborted) is not { } frame) return ApiErrors.NotFound(context, "frame"); - if (ArchivePaths.ExistingFile(archive.Root, frame.RelativePath) is not { } file) return ApiErrors.NotFound(context, "file_missing"); + if (ArchivePathGuard.ExistingFile(archive.Root, frame.RelativePath) is not { } file) return ApiErrors.NotFound(context, "file_missing"); return FileResponses.Serve(context, file, 0, file.Length, FileResponses.ContentTypeOf(frame.FileName), Immutable, frame.Sha256, frame.FileName) ?? ApiErrors.NotFound(context, "file_missing"); } @@ -40,7 +40,7 @@ public static class FileEndpoints if (await db.Frames.GetAsync(id, ct) is not { } frame || await db.Sequences.GetAsync(frame.SequenceId, ct) is not { } sequence) return ApiErrors.NotFound(context, "frame"); var location = await locator.LocateAsync(archive.Current, sequence, frame, kind, ct); - if (location is null || !ArchivePaths.IsInside(archive.Root, location.Path)) return ApiErrors.NotFound(context, "asset_missing"); + if (location is null || !ArchivePathGuard.IsInside(archive.Root, location.Path)) return ApiErrors.NotFound(context, "asset_missing"); var file = new FileInfo(location.Path); if (!file.Exists || file.LinkTarget is not null) return ApiErrors.NotFound(context, "asset_missing"); var etag = string.Create(CultureInfo.InvariantCulture, $"{kind}-{frame.Id:N}-{file.LastWriteTimeUtc.Ticks}-{location.Offset}"); @@ -51,7 +51,7 @@ public static class FileEndpoints private static async Task RenderAsync(HttpContext context, Guid id, TitanoDatabase db, ServerArchive archive) { if (await db.Renders.GetAsync(id, context.RequestAborted) is not { } render) return ApiErrors.NotFound(context, "render"); - if (ArchivePaths.ExistingFile(archive.Root, render.OutputPath) is not { } file) return ApiErrors.NotFound(context, "file_missing"); + if (ArchivePathGuard.ExistingFile(archive.Root, render.OutputPath) is not { } file) return ApiErrors.NotFound(context, "file_missing"); var etag = string.Create(CultureInfo.InvariantCulture, $"r-{render.Id:N}-{file.Length}-{file.LastWriteTimeUtc.Ticks}"); return FileResponses.Serve(context, file, 0, file.Length, FileResponses.ContentTypeOf(file.Name), Immutable, etag, file.Name) ?? ApiErrors.NotFound(context, "file_missing"); diff --git a/src/Titano.Server/Api/SequenceEndpoints.cs b/src/Titano.Server/Api/SequenceEndpoints.cs index dd687af4..dae6adf2 100644 --- a/src/Titano.Server/Api/SequenceEndpoints.cs +++ b/src/Titano.Server/Api/SequenceEndpoints.cs @@ -140,7 +140,7 @@ public static class SequenceEndpoints { if (await db.Sequences.GetAsync(id, context.RequestAborted) is not { } sequence) return ApiErrors.NotFound(context, "sequence"); if (!caller.IsAdmin && sequence.OwnerUserId != caller.Id) return ApiErrors.Forbidden(context); - var folder = string.IsNullOrEmpty(sequence.Folder) ? null : ArchivePaths.Resolve(archive.Root, sequence.Folder); + var folder = string.IsNullOrEmpty(sequence.Folder) ? null : ArchivePathGuard.Resolve(archive.Root, sequence.Folder); var trash = Path.Combine(options.TrashPath, id.ToString("N")); var hasFolder = folder is not null && Directory.Exists(folder); var plan = new SequenceDeletePlan(id, sequence.Folder, hasFolder ? Path.GetRelativePath(archive.Root, trash).Replace('\\', '/') : null, diff --git a/src/Titano.Server/Hosting/ServerHost.cs b/src/Titano.Server/Hosting/ServerHost.cs index 2f4cf173..96d8f237 100644 --- a/src/Titano.Server/Hosting/ServerHost.cs +++ b/src/Titano.Server/Hosting/ServerHost.cs @@ -51,7 +51,7 @@ public static class ServerHost var database = ServerDatabase.OpenAsync(options, bootLogger, CancellationToken.None).GetAwaiter().GetResult(); try { - var archive = ServerArchive.OpenAsync(database, options, TimeProvider.System, CancellationToken.None).GetAwaiter().GetResult(); + var archive = ServerArchive.OpenAsync(database, options, CancellationToken.None).GetAwaiter().GetResult(); AdminBootstrap.RunAsync(database, options, TimeProvider.System, bootLogger, CancellationToken.None).GetAwaiter().GetResult(); var state = new ServerState { diff --git a/src/Titano.Server/Jobs/JobEngineHost.cs b/src/Titano.Server/Jobs/JobEngineHost.cs index b2870592..e73b989b 100644 --- a/src/Titano.Server/Jobs/JobEngineHost.cs +++ b/src/Titano.Server/Jobs/JobEngineHost.cs @@ -10,7 +10,8 @@ using Titano.Server.Events; namespace Titano.Server.Jobs; /// -/// Hosts the server's (BRIEF §14.6) with the s registered in DI and +/// Hosts the server's (BRIEF §14.6) with the s registered in DI (directly or +/// through s) and /// relays its state changes and progress as WebSocket events. Render jobs are never run here: render nodes claim them /// (BRIEF §14.7). On shutdown running jobs stay marked running and are requeued from their checkpoints at the next start. /// @@ -24,11 +25,12 @@ public sealed class JobEngineHost : IHostedService private readonly Dictionary _lastProgress = []; private readonly Lock _gate = new(); - public JobEngineHost(TitanoDatabase db, IEnumerable handlers, ServerOptions options, EventHub events) + public JobEngineHost(TitanoDatabase db, IEnumerable handlers, IEnumerable providers, ServerOptions options, + EventHub events) { _db = db; _events = events; - var local = handlers.Where(h => h.Kind != JobKind.Render).ToList(); + var local = handlers.Concat(providers.SelectMany(p => p.CreateJobHandlers())).Where(h => h.Kind != JobKind.Render).ToList(); _kinds = [.. local.Select(h => h.Kind)]; // Without handlers no worker starts: an engine with an empty kind list would claim every kind. Workers = _kinds.Count == 0 ? 0 : options.Workers; diff --git a/src/Titano.Server/Program.cs b/src/Titano.Server/Program.cs index bb9e439f..06d2e08d 100644 --- a/src/Titano.Server/Program.cs +++ b/src/Titano.Server/Program.cs @@ -2,6 +2,7 @@ using System.ComponentModel; using Titano.Server.Configuration; using Titano.Server.Hosting; using Titano.Server.Hosting.Windows; +using Titano.Server.Storage; var command = ServerCommandLine.Parse(args); if (command.Error is not null) @@ -25,11 +26,11 @@ switch (command.Command) case ServerCommand.UninstallService when OperatingSystem.IsWindows(): return ServiceAction(ServiceInstaller.Uninstall, $"Removed the {WindowsServiceHost.ServiceName} service."); case ServerCommand.Service when OperatingSystem.IsWindows(): - if (WindowsServiceHost.Run(() => ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments]))) return 0; + if (WindowsServiceHost.Run(() => ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], ArchiveModule.Register))) return 0; await Console.Error.WriteLineAsync("--service is used by the Service Control Manager; start the service with 'sc start TitanoServer'."); return 1; default: - var app = ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments]); + var app = ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], ArchiveModule.Register); await app.RunAsync(); return 0; } diff --git a/src/Titano.Server/Storage/ArchiveAssetLocator.cs b/src/Titano.Server/Storage/ArchiveAssetLocator.cs new file mode 100644 index 00000000..513babac --- /dev/null +++ b/src/Titano.Server/Storage/ArchiveAssetLocator.cs @@ -0,0 +1,34 @@ +using Titano.Core.Archiving; +using Titano.Core.Model; + +namespace Titano.Server.Storage; + +/// +/// Proxies are files under the sequence's proxies/ folder; a thumbnail is the JPEG byte range of its entry in +/// thumbs.pack. A thumbnail made from a different original (the frame was renumbered or replaced) counts as not +/// built yet, like a missing one. +/// +internal sealed class ArchiveAssetLocator : IFrameAssetLocator +{ + private const string Jpeg = "image/jpeg"; + + public ValueTask LocateAsync(Archive archive, Sequence sequence, Frame frame, FrameAsset asset, CancellationToken cancellationToken) + { + var paths = new ArchivePaths(archive.RootPath).Sequence(sequence.Folder); + return ValueTask.FromResult(asset == FrameAsset.Proxy ? Proxy(paths, frame) : Thumbnail(paths, frame)); + } + + private static AssetLocation? Proxy(SequencePaths paths, Frame frame) + { + var file = new FileInfo(paths.Proxy(frame.Index)); + return file.Exists ? new AssetLocation(file.FullName, 0, file.Length, Jpeg) : null; + } + + private static AssetLocation? Thumbnail(SequencePaths paths, Frame frame) + { + using var pack = ThumbPackReader.Open(paths.ThumbsPackPath); + if (!pack.Entries.TryGetValue(frame.Index, out var entry) || entry.Offset + entry.Length > pack.Length) return null; + if (frame.Sha256 is { Length: ThumbPack.HashLength * 2 } sha && !entry.SourceHash.AsSpan().SequenceEqual(Convert.FromHexString(sha))) return null; + return new AssetLocation(paths.ThumbsPackPath, entry.Offset, entry.Length, Jpeg); + } +} diff --git a/src/Titano.Server/Storage/ArchiveModule.cs b/src/Titano.Server/Storage/ArchiveModule.cs new file mode 100644 index 00000000..d2152ec9 --- /dev/null +++ b/src/Titano.Server/Storage/ArchiveModule.cs @@ -0,0 +1,23 @@ +using Titano.Core.Imaging.Decoders; +using Titano.Data; +using Titano.Data.Archiving; +using Titano.Data.Jobs; + +namespace Titano.Server.Storage; + +/// +/// The archive engine behind the server (BRIEF §7, §14.4): ingest of verified uploads, lookup of proxies and +/// thumbnails, and its job handlers (scan, rebuild, verify, import, thumbnails, proxies, maintenance). Decoding is +/// managed only (BRIEF §4.2). +/// +public static class ArchiveModule +{ + public static void Register(IServiceCollection services) + { + services.AddSingleton(sp => new ArchiveService(sp.GetRequiredService(), + new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = "server@" + Environment.MachineName })); + services.AddSingleton(sp => sp.GetRequiredService().Ingest); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(); + } +} diff --git a/src/Titano.Server/Storage/ArchivePaths.cs b/src/Titano.Server/Storage/ArchivePathGuard.cs similarity index 98% rename from src/Titano.Server/Storage/ArchivePaths.cs rename to src/Titano.Server/Storage/ArchivePathGuard.cs index bb8e16f2..efb1abb4 100644 --- a/src/Titano.Server/Storage/ArchivePaths.cs +++ b/src/Titano.Server/Storage/ArchivePathGuard.cs @@ -4,7 +4,7 @@ namespace Titano.Server.Storage; /// Archive-relative paths from the database → absolute paths, refusing anything that would leave the archive root /// (BRIEF §14.2: path traversal impossible). Clients never send paths; only ids that the database maps to these. /// -public static class ArchivePaths +public static class ArchivePathGuard { private static readonly StringComparison PathComparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; diff --git a/src/Titano.Server/Storage/RenderStore.cs b/src/Titano.Server/Storage/RenderStore.cs index 9748accd..841e3f95 100644 --- a/src/Titano.Server/Storage/RenderStore.cs +++ b/src/Titano.Server/Storage/RenderStore.cs @@ -14,7 +14,7 @@ public sealed class RenderStore(TitanoDatabase db, ServerArchive archive, TimePr /// public async Task CommitAsync(Sequence sequence, string stagedFile, RenderResultRequest output, string producedBy, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(sequence.Folder) || ArchivePaths.Resolve(archive.Root, sequence.Folder.TrimEnd('/') + "/exports") is not { } exports) + if (string.IsNullOrEmpty(sequence.Folder) || ArchivePathGuard.Resolve(archive.Root, sequence.Folder.TrimEnd('/') + "/exports") is not { } exports) return null; Directory.CreateDirectory(exports); var target = Unique(exports, output.FileName); diff --git a/src/Titano.Server/Storage/ServerArchive.cs b/src/Titano.Server/Storage/ServerArchive.cs index d7e1ae8d..f6ca64b6 100644 --- a/src/Titano.Server/Storage/ServerArchive.cs +++ b/src/Titano.Server/Storage/ServerArchive.cs @@ -1,5 +1,6 @@ using Titano.Core.Model; using Titano.Data; +using Titano.Data.Archiving; using Titano.Server.Configuration; namespace Titano.Server.Storage; @@ -22,16 +23,14 @@ public sealed class ServerArchive(Archive archive) public string Root => _current.RootPath; - /// Finds the archive row for the configured root, or creates it with the default templates. - public static async Task OpenAsync(TitanoDatabase db, ServerOptions options, TimeProvider time, CancellationToken cancellationToken) + /// + /// Opens the archive at the configured root through the archive engine: an existing Titano archive is registered + /// (and relinked if it moved), any other folder becomes a new archive with the default templates. + /// + public static async Task OpenAsync(TitanoDatabase db, ServerOptions options, CancellationToken cancellationToken) { var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(options.ArchivePath)); - var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; - var existing = (await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false)) - .FirstOrDefault(a => string.Equals(Path.TrimEndingDirectorySeparator(a.RootPath), root, comparison)); - if (existing is not null) return new ServerArchive(existing); - var created = new Archive { Id = Guid.CreateVersion7(), Name = options.ServerName, RootPath = root, Created = time.GetUtcNow() }; - await db.Archives.UpsertAsync(created, cancellationToken).ConfigureAwait(false); - return new ServerArchive(created); + var archive = await new ArchiveService(db).AdoptAsync(root, options.ServerName, cancellationToken).ConfigureAwait(false); + return new ServerArchive(archive); } } diff --git a/tests/Titano.Server.Tests/Storage/ArchiveModuleTests.cs b/tests/Titano.Server.Tests/Storage/ArchiveModuleTests.cs new file mode 100644 index 00000000..172540f8 --- /dev/null +++ b/tests/Titano.Server.Tests/Storage/ArchiveModuleTests.cs @@ -0,0 +1,52 @@ +using System.Net; +using Titano.Core.Archiving; +using Titano.Core.Codecs.Jpeg; +using Titano.Server.Storage; +using Titano.Testing; + +namespace Titano.Server.Tests.Storage; + +/// The production composition: uploads committed by the real archive engine, thumbnails built by its job. +[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, ".titano", "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); + } + } + + private static byte[] Photo() + { + 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 % 251); + return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 90 }); + } +}