merge: server archive fixes (V-5, V-8, V-11, V-16, V-35, V-36)

Merge branch fix2/server-archive into the verification branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 16:54:04 +00:00
commit 61c7e9e7e3
19 files changed
+671 -39

No files matched your search

@@ -1,3 +1,4 @@
using System.Runtime.Versioning;
using System.Text.Json.Nodes;
using Titano.Core.Archiving;
using Titano.Core.IO;
@@ -17,6 +18,54 @@ public sealed class ArchiveIngestTests(TestContext context)
Guid? sequenceId = null, string? title = null, string name = "IMG_0001.JPG") =>
new(fx.Archive.Id, sequenceId, title, sequenceId is null && title is null ? sessionKey : null, staged.Path, name, staged.Size, staged.Sha256, null, null);
/// <summary>A sequence as <c>POST /api/v1/sequences</c> creates it: a row without a folder or frames.</summary>
private static async Task<Sequence> CreateWithoutPhotosAsync(ArchiveFixture fx, string title)
{
var created = new Sequence
{
Id = Guid.CreateVersion7(),
ArchiveId = fx.Archive.Id,
Title = title,
Folder = string.Empty,
Rating = 4,
Origin = SequenceOrigin.Server,
OwnerUserId = Guid.CreateVersion7(),
UpdatedAt = DateTimeOffset.UtcNow,
};
await fx.Db.Sequences.UpsertAsync(created, fx.Ct);
return created;
}
/// <summary>
/// Makes <paramref name="path"/> unreadable until disposed: without read permission where that stops the test process
/// (UnauthorizedAccessException), otherwise (Windows, root) held open without sharing (IOException).
/// </summary>
private static IDisposable Unreadable(string path)
{
if (!OperatingSystem.IsWindows())
{
var mode = File.GetUnixFileMode(path);
File.SetUnixFileMode(path, UnixFileMode.None);
try
{
File.OpenRead(path).Dispose();
File.SetUnixFileMode(path, mode);
}
catch (UnauthorizedAccessException)
{
return new UnixPermissions(path, mode);
}
}
return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None);
}
/// <summary>Gives a file its permissions back.</summary>
[UnsupportedOSPlatform("windows")]
private sealed class UnixPermissions(string path, UnixFileMode mode) : IDisposable
{
public void Dispose() => File.SetUnixFileMode(path, mode);
}
[Test]
public async Task ASessionKeyCreatesOneSequenceNamedByTheTemplates()
{
@@ -242,6 +291,166 @@ public sealed class ArchiveIngestTests(TestContext context)
Assert.FileExists(staged.Path);
}
[Test]
public async Task ASequenceWaitingForItsFirstFrameNeverLendsItsIdToTheArchiveRoot()
{
await using var fx = await CreateAsync(context);
var waiting = await CreateWithoutPhotosAsync(fx, "Harbour sunset");
// Loose photos at the root, which a scan adopts in place.
Photos.WriteSeries(fx.Archive.RootPath, Start.AddDays(-1), 2);
await fx.ScanAsync();
var root = ManifestStore.ReadSequence(fx.Paths.Sequence(string.Empty).ManifestPath);
Assert.NotEqual(waiting.Id, root.Id);
var rootRow = (await fx.Db.Sequences.GetAsync(root.Id))!;
Assert.Equal((string.Empty, 2), (rootRow.Folder, rootRow.FrameCount));
var row = (await fx.Db.Sequences.GetAsync(waiting.Id))!;
Assert.Equal((string.Empty, 0, "Harbour sunset"), (row.Folder, row.FrameCount, row.Title));
// Its first frame still gets a folder of its own, and the root keeps its photos.
var first = await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start, 1), sequenceId: waiting.Id), fx.Ct);
Assert.Equal(waiting.Id, first.SequenceId);
var placed = (await fx.Db.Sequences.GetAsync(waiting.Id))!;
Assert.Equal(("2026/2026-09-28 Canon EOS R5", 1), (placed.Folder, placed.FrameCount));
Assert.Equal(root.Id, ManifestStore.ReadSequence(fx.Paths.Sequence(string.Empty).ManifestPath).Id);
Assert.Equal(2, (await fx.Db.Sequences.GetAsync(root.Id))!.FrameCount);
}
[Test]
public async Task ARootSequenceWhoseSidecarIsGoneIsAdoptedAgainUnderItsOwnId()
{
await using var fx = await CreateAsync(context);
Photos.WriteSeries(fx.Archive.RootPath, Start, 2);
await fx.ScanAsync();
var adopted = Assert.NotNull((await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id, fx.Ct)).SingleOrDefault());
// Created later, so its id sorts after the root sequence's.
var waiting = await CreateWithoutPhotosAsync(fx, "Harbour sunset");
File.Delete(fx.Paths.Sequence(string.Empty).ManifestPath);
await fx.ScanAsync();
Assert.Equal(adopted.Id, ManifestStore.ReadSequence(fx.Paths.Sequence(string.Empty).ManifestPath).Id);
Assert.Equal(2, (await fx.Db.Sequences.GetAsync(adopted.Id))!.FrameCount);
var row = (await fx.Db.Sequences.GetAsync(waiting.Id))!;
Assert.Equal((string.Empty, 0), (row.Folder, row.FrameCount));
}
[Test]
public async Task RebuildOrphansAndVerifyLeaveASequenceWaitingForItsFirstFrame()
{
await using var fx = await CreateAsync(context);
Photos.WriteSeries(Path.Combine(fx.Archive.RootPath, "Trips", "Comet"), Start, 2);
await fx.ScanAsync();
var waiting = await CreateWithoutPhotosAsync(fx, "Harbour sunset");
// It has no sidecar yet, which is no reason to drop it.
var rebuilt = await fx.ScanAsync(ScanMode.Rebuild);
Assert.Equal(0, rebuilt.Removed);
var orphans = await fx.Service.FindOrphansAsync(fx.Archive.Id, fx.Ct);
Assert.Empty(orphans.MissingSequences);
Assert.Empty(orphans.UnindexedFolders);
Assert.Equal(0, await fx.Service.RemoveMissingSequencesAsync(fx.Archive.Id, [waiting.Id], fx.Ct));
var report = await fx.Service.Verifier.VerifyAsync(fx.Archive, null, default, (_, _, _) => ValueTask.CompletedTask, null, fx.Ct);
Assert.Equal((1, 2L), (report.Sequences, report.Checked));
var kept = Assert.NotNull(await fx.Db.Sequences.GetAsync(waiting.Id));
Assert.Equal(("Harbour sunset", 4), (kept.Title, kept.Rating));
// The archive root is not its folder: loose photos there are a folder the index does not know yet.
Photos.WriteSeries(fx.Archive.RootPath, Start.AddDays(-1), 1, firstSeed: 50);
Assert.SequenceEqual([string.Empty], (await fx.Service.FindOrphansAsync(fx.Archive.Id, fx.Ct)).UnindexedFolders);
var first = await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start.AddDays(1), 1), sequenceId: waiting.Id), fx.Ct);
Assert.Equal(waiting.Id, first.SequenceId);
Assert.Equal("2026/2026-09-29 Canon EOS R5", (await fx.Db.Sequences.GetAsync(waiting.Id))!.Folder);
}
[Test]
public async Task ADamagedRootSidecarIsRebuiltUnderTheRootSequenceNotOneWaitingForItsFirstFrame()
{
await using var fx = await CreateAsync(context);
Photos.WriteSeries(fx.Archive.RootPath, Start, 2);
await fx.ScanAsync();
var root = Assert.NotNull((await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id, fx.Ct)).SingleOrDefault());
// Created later, so its id sorts after the root sequence's; then another tool tears the root sidecar.
var waiting = await CreateWithoutPhotosAsync(fx, "Harbour sunset");
var sidecar = fx.Paths.Sequence(string.Empty).ManifestPath;
File.WriteAllText(sidecar, "{");
var summary = await fx.ScanAsync();
Assert.Empty(summary.Failed);
Assert.Equal(root.Id, ManifestStore.ReadSequence(sidecar).Id);
Assert.Count(1, Directory.GetFiles(Path.GetDirectoryName(sidecar)!, $"{Path.GetFileName(sidecar)}.damaged-*"));
Assert.Equal(2, (await fx.Db.Sequences.GetAsync(root.Id))!.FrameCount);
var row = (await fx.Db.Sequences.GetAsync(waiting.Id))!;
Assert.Equal((string.Empty, 0, "Harbour sunset"), (row.Folder, row.FrameCount, row.Title));
Assert.Empty(await fx.Db.Frames.ListBySequenceAsync(waiting.Id));
}
[Test]
public async Task ARootSidecarThatCannotBeReadFailsTheRootFolderAloneAndDropsNoSequence()
{
await using var fx = await CreateAsync(context);
Photos.WriteSeries(fx.Archive.RootPath, Start, 2);
await fx.ScanAsync();
var root = Assert.NotNull((await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id, fx.Ct)).SingleOrDefault());
var waiting = await CreateWithoutPhotosAsync(fx, "Harbour sunset");
Photos.WriteSeries(Path.Combine(fx.Archive.RootPath, "Trips", "Comet"), Start.AddDays(1), 2, firstSeed: 50);
var sidecar = fx.Paths.Sequence(string.Empty).ManifestPath;
ScanSummary rebuilt;
using (Unreadable(sidecar)) rebuilt = await fx.ScanAsync(ScanMode.Rebuild);
Assert.SequenceEqual([string.Empty], rebuilt.Failed.Select(f => f.Folder));
Assert.Equal(0, rebuilt.Removed);
var locations = await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id, fx.Ct);
Assert.SequenceEqual(new[] { root.Id, waiting.Id }.Order(), locations.Where(l => l.Folder.Length == 0).Select(l => l.Id).Order());
Assert.SequenceEqual(["Trips/Comet"], locations.Where(l => l.Folder.Length > 0).Select(l => l.Folder));
// Readable again, the root is indexed under its own sequence.
Assert.Empty((await fx.ScanAsync()).Failed);
Assert.Equal(root.Id, ManifestStore.ReadSequence(sidecar).Id);
var row = (await fx.Db.Sequences.GetAsync(waiting.Id))!;
Assert.Equal((string.Empty, 0), (row.Folder, row.FrameCount));
}
[Test]
public async Task MaintenanceCompactsTheRootPackUnderTheRootSequencesLeaseOnly()
{
await using var fx = await CreateAsync(context);
// Left over from before the root was adopted, so its id sorts before the root sequence's.
var waiting = await CreateWithoutPhotosAsync(fx, "Harbour sunset");
Photos.WriteSeries(fx.Archive.RootPath, Start, 2);
await fx.ScanAsync();
var root = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id, fx.Ct)).Single(l => l.Id != waiting.Id);
var packPath = fx.Paths.Sequence(string.Empty).ThumbsPackPath;
var hash = new byte[ThumbPack.HashLength];
using (var pack = ThumbPackWriter.Open(packPath))
{
// The same entry written again and again: everything but the last copy is garbage.
for (var i = 0; i < 4; i++) pack.Append(0, 48, 32, hash, Photos.Jpeg(Start, 70 + i));
pack.Commit();
}
var length = new FileInfo(packPath).Length;
// A thumbnail pass of the root sequence appends under its own lease: the pack waits for it.
Task<MaintenanceReport> maintenance;
using (await LeaseFile.AcquireAsync(fx.Paths.LocksDirectory, $"thumbs-{root.Id:N}", "thumbnails", TimeSpan.FromSeconds(5), cancellationToken: fx.Ct))
{
maintenance = fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: false, 0, _ => ValueTask.CompletedTask, fx.Ct);
await Task.Delay(500, fx.Ct);
Assert.False(maintenance.IsCompleted);
Assert.Equal(length, new FileInfo(packPath).Length);
}
var report = await maintenance;
Assert.SequenceEqual([string.Empty], report.CompactedPacks);
using var compacted = ThumbPackReader.Open(packPath);
Assert.Equal(0L, compacted.GarbageBytes);
Assert.NotNull(compacted.Read(0));
}
[Test]
public async Task FramesInsertedBeforeOthersTakeTheProjectPositionsAlong()
{
@@ -3,6 +3,7 @@ using Titano.Core.Import;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Data.Archiving.Jobs;
using Titano.Data.Jobs;
using Titano.Data.Repositories;
using Titano.Testing;
using static Titano.Data.Tests.Archiving.ArchiveFixture;
@@ -22,6 +23,23 @@ public sealed class ArchiveJobTests(TestContext context)
private static async Task<IReadOnlyList<SequenceLocation>> LocationsAsync(ArchiveFixture fx) =>
await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id);
/// <summary>The server's archive engine (ArchiveModule), not started; the desktop's scans queue no image passes.</summary>
private static JobEngine ServerEngine(ArchiveFixture fx, params IJobHandler[] others)
{
var service = new ArchiveService(fx.Db, new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20), ImagesAfterScan = true });
return new JobEngine(fx.Db, [.. service.CreateJobHandlers(), .. others],
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
}
private static bool Built(SequenceStatus status) => status.HasFlag(SequenceStatus.ThumbsBuilt) && status.HasFlag(SequenceStatus.ProxiesBuilt);
private sealed class CallbackHandler(JobKind kind, Func<JobContext, Task> run) : IJobHandler
{
public JobKind Kind => kind;
public Task RunAsync(JobContext context) => run(context);
}
[Test]
public async Task ScanAndRebuildJobsRunAndAScanResumesAfterItsCheckpoint()
{
@@ -40,6 +58,9 @@ public sealed class ArchiveJobTests(TestContext context)
var rebuild = await engine.EnqueueAsync(ArchiveJobs.Rebuild(fx.Archive), cancellationToken: fx.Ct);
await fx.WaitForAsync(rebuild.Id, JobState.Done);
Assert.Equal(2, (await LocationsAsync(fx)).Count);
// The desktop decodes its thumbnails on demand and makes proxies when asked.
Assert.Empty((await fx.Db.Jobs.ListAsync(null, JobKind.Thumbs, cancellationToken: fx.Ct)).Items);
Assert.Empty((await fx.Db.Jobs.ListAsync(null, JobKind.Proxies, cancellationToken: fx.Ct)).Items);
}
[Test]
@@ -88,6 +109,94 @@ public sealed class ArchiveJobTests(TestContext context)
Assert.Contains("made 3, reused 3", done.LogTail);
}
[Test]
public async Task AServerScanQueuesThumbnailsAndProxiesOfTheSequencesItIndexesWithoutThem()
{
await using var fx = await CreateAsync(context);
Populate(fx);
await using var engine = ServerEngine(fx);
await engine.StartAsync(fx.Ct);
var scan = await engine.EnqueueAsync(ArchiveJobs.Scan(fx.Archive), cancellationToken: fx.Ct);
await fx.WaitForAsync(scan.Id, JobState.Done);
var locations = await LocationsAsync(fx);
var first = new HashSet<Guid>();
foreach (var kind in new[] { JobKind.Thumbs, JobKind.Proxies })
{
// One pass per sequence, named after it, as after an upload.
var passes = (await fx.Db.Jobs.ListAsync(null, kind, cancellationToken: fx.Ct)).Items;
Assert.SequenceEqual(locations.Select(l => l.Id).Order(), passes.SelectMany(j => j.TargetIds).Order());
foreach (var pass in passes)
{
Assert.Count(1, pass.TargetIds);
var target = Assert.NotNull(await fx.Db.Sequences.GetAsync(pass.TargetIds[0]));
Assert.Equal((JobPriority.Background, target.DisplayTitle), (pass.Priority, pass.TargetLabel));
await fx.WaitForAsync(pass.Id, JobState.Done);
first.Add(pass.Id);
}
}
foreach (var location in locations) Assert.True(Built((await fx.Db.Sequences.GetAsync(location.Id))!.Status), location.Folder);
// Every folder indexed again, but none without its images: nothing is queued.
var full = await engine.EnqueueAsync(ArchiveJobs.Scan(fx.Archive, full: true), cancellationToken: fx.Ct);
await fx.WaitForAsync(full.Id, JobState.Done);
Assert.Count(2, (await fx.Db.Jobs.ListAsync(null, JobKind.Thumbs, cancellationToken: fx.Ct)).Items);
Assert.Count(2, (await fx.Db.Jobs.ListAsync(null, JobKind.Proxies, cancellationToken: fx.Ct)).Items);
// A photo added to a folder: its sequence lacks the images of that frame until the passes queued for it alone ran.
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "a"), Start.AddMinutes(5), 1, firstSeed: 90, firstNumber: 7);
var added = await engine.EnqueueAsync(ArchiveJobs.Scan(fx.Archive), cancellationToken: fx.Ct);
await fx.WaitForAsync(added.Id, JobState.Done);
var a = locations.Single(l => l.Folder == "a");
foreach (var kind in new[] { JobKind.Thumbs, JobKind.Proxies })
{
var pass = (await fx.Db.Jobs.ListAsync(null, kind, cancellationToken: fx.Ct)).Items.Single(j => !first.Contains(j.Id));
Assert.SequenceEqual([a.Id], pass.TargetIds);
await fx.WaitForAsync(pass.Id, JobState.Done);
}
Assert.True(Built((await fx.Db.Sequences.GetAsync(a.Id))!.Status), "built again");
using var pack = ThumbPackReader.Open(fx.Paths.Sequence("a").ThumbsPackPath);
Assert.Count(7, pack.Entries);
Assert.Count(7, Directory.GetFiles(fx.Paths.Sequence("a").Proxies));
}
[Test]
public async Task AFolderGoneBeforeItsImagePassesFailsThemAloneAndTheOtherSequencesGetTheirImages()
{
await using var fx = await CreateAsync(context);
Populate(fx);
// The only worker runs the scan, then this job ahead of the background passes the scan queued: the folder goes
// meanwhile, as when someone renames or deletes it on the NAS between a poll and its passes.
var holding = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var engine = ServerEngine(fx, new CallbackHandler(JobKind.Render, async c =>
{
holding.SetResult();
await release.Task.WaitAsync(c.Cancellation);
}));
var scan = await engine.EnqueueAsync(ArchiveJobs.Scan(fx.Archive), cancellationToken: fx.Ct);
var hold = await engine.EnqueueAsync(JobKind.Render, [fx.Archive.Id], priority: JobPriority.Normal, cancellationToken: fx.Ct);
await engine.StartAsync(fx.Ct);
await holding.Task.WaitAsync(TimeSpan.FromSeconds(30), fx.Ct);
Assert.Equal(JobState.Done, (await fx.Db.Jobs.GetAsync(scan.Id, fx.Ct))!.State);
var locations = await LocationsAsync(fx);
var (a, b) = (locations.Single(l => l.Folder == "a"), locations.Single(l => l.Folder == "b"));
Directory.Delete(Path.Combine(fx.Paths.Root, "a"), recursive: true);
release.SetResult();
await fx.WaitForAsync(hold.Id, JobState.Done);
foreach (var kind in new[] { JobKind.Thumbs, JobKind.Proxies })
{
var passes = (await fx.Db.Jobs.ListAsync(null, kind, cancellationToken: fx.Ct)).Items;
await fx.WaitForAsync(passes.Single(j => j.TargetIds.SequenceEqual([a.Id])).Id, JobState.Failed);
await fx.WaitForAsync(passes.Single(j => j.TargetIds.SequenceEqual([b.Id])).Id, JobState.Done);
}
Assert.True(Built((await fx.Db.Sequences.GetAsync(b.Id))!.Status), "b built");
using var pack = ThumbPackReader.Open(fx.Paths.Sequence("b").ThumbsPackPath);
Assert.Count(6, pack.Entries);
Assert.Count(6, Directory.GetFiles(fx.Paths.Sequence("b").Proxies));
}
[Test]
public async Task AThumbnailPassFlagsFramesNothingDecodesAndClearsThemOnceTheyDecode()
{
@@ -105,6 +105,57 @@ public sealed class MassRenameTests(TestContext context)
Assert.True(Directory.Exists(fx.Paths.FromRelative(other.Steps[0].ToFolder)));
}
[Test]
public async Task ASequenceIndexedInsideAMovingFolderAfterTheDryRunMakesThePlanStale()
{
await using var fx = await CreateAsync(context);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "trips"), Start, 2);
await fx.ScanAsync();
var trips = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single();
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [trips.Id], "moved/{date}", null, fx.Ct);
Assert.Count(1, plan.Steps);
// Photos copied into a subfolder and indexed by the next scan, after the dry run was shown.
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "trips", "day2"), Start.AddDays(1), 2, firstSeed: 10);
await fx.ScanAsync();
var day2 = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single(l => l.Folder == "trips/day2");
var stale = await Assert.ThrowsAsync<StaleRenamePlanException>(() => fx.Service.ApplyRenameAsync(plan, null, fx.Ct));
Assert.Equal(day2.Id, stale.SequenceId);
Assert.Empty(RenameJournal.ListPending(fx.Paths));
Assert.SequenceEqual(["trips|trips|trips/IMG_0001.JPG,trips/IMG_0002.JPG", "trips/day2|day2|trips/day2/IMG_0001.JPG,trips/day2/IMG_0002.JPG"],
await StateAsync(fx, [trips.Id, day2.Id]));
}
[Test]
public async Task AFolderThatGainedASequenceWhileTheRenameRanStaysWhereItIs()
{
await using var fx = await CreateAsync(context);
var ids = await PopulateAsync(fx);
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0], ids[1]], "renamed/{date}", null, fx.Ct);
Assert.SequenceEqual(["inbox/a", "inbox/b"], plan.Steps.Select(s => s.FromFolder));
// Once the first folder moved, a scan indexes photos copied into the second one.
var late = Path.Combine(fx.Paths.Root, "inbox", "b", "late");
var progress = new SyncProgress(done =>
{
if (done != 1) return;
Photos.WriteSeries(late, Start.AddDays(5), 2, firstSeed: 40);
fx.ScanAsync().GetAwaiter().GetResult();
});
await Assert.ThrowsAsync<StaleRenamePlanException>(() => fx.Service.ApplyRenameAsync(plan, progress, fx.Ct));
var newcomer = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single(l => l.Folder == "inbox/b/late");
Assert.True(Directory.Exists(late), "the folder did not move");
Assert.Count(1, RenameJournal.ListPending(fx.Paths).Single().Completed);
// Resumed, the rest of the plan runs but that step is dropped: every index row still names its files.
Assert.Equal(1, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
var state = await StateAsync(fx, [ids[0], ids[1], newcomer.Id]);
Assert.SequenceEqual(["renamed/2026-09-28", "inbox/b", "inbox/b/late"], state.Select(s => s.Split('|')[0]));
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
}
/// <summary>"trips" with photos of its own, "trips/day2" inside it and "trips/day2/dawn" inside that: three nested sequences.</summary>
private static async Task<List<Guid>> NestedAsync(ArchiveFixture fx)
{
@@ -177,5 +177,21 @@ public sealed class AdminTests(TestContext context)
{
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 = Titano.Core.Archiving.ManifestStore.ReadArchive(path);
foreach (var (odd, property) in new[]
{
(current with { ThumbnailPolicy = new Titano.Core.Archiving.ThumbnailPolicy { LongEdge = 2048 } }, "thumbnailPolicy"),
(current with { ProxyPolicy = current.ProxyPolicy with { Quality = 0 } }, "proxyPolicy"),
})
{
Titano.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);
}
}
@@ -68,7 +68,7 @@ public sealed class ArchiveModuleTests(TestContext context)
}
[Test]
public async Task PhotosAlreadyInTheArchiveAndAddedLaterAreIndexedByPolling()
public async Task PhotosAlreadyInTheArchiveAndAddedLaterAreIndexedByPollingWithThumbnailsAndProxies()
{
var photo = Photo();
// An adopted folder that already holds photos.
@@ -78,8 +78,11 @@ public sealed class ArchiveModuleTests(TestContext context)
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"));
@@ -100,6 +103,7 @@ public sealed class ArchiveModuleTests(TestContext context)
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");
}
private static async Task UntilIndexedAsync(TestServer server, Guid archiveId, string folder)
@@ -112,6 +116,30 @@ public sealed class ArchiveModuleTests(TestContext context)
}
}
/// <summary>Waits until the first frame of the sequence in <paramref name="folder"/> has its thumbnail and proxy served.</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 frame = (await server.Database.Frames.ListBySequenceAsync(sequence.Id)).First();
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
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 {folder}");
break;
}
Assert.True(DateTime.UtcNow < until, $"no {asset} of {folder}: {(int)response.StatusCode}");
await Task.Delay(100);
}
}
var built = Assert.NotNull(await server.Database.Sequences.GetAsync(sequence.Id)).Status;
Assert.True(built.HasFlag(SequenceStatus.ThumbsBuilt) && built.HasFlag(SequenceStatus.ProxiesBuilt), $"{folder}: {built}");
}
/// <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)
{
@@ -170,6 +170,35 @@ public sealed class UploadTests(TestContext context)
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()
{