Files
Chronos/tests/Chronos.Server.Tests/Api/ReorganizeTests.cs
T
Alby96 765f0ad36b fix(archive): Reorganize never plans a move onto a folder of the exact name, keeps long names' extensions, says why a template is refused
Second fix round of owner review 2, phase 4a (planner findings).

- A sequence keeps a folder that differs from its own in case only while no
  other folder holds that exact name (RenamePlanner.ExistsExactly, every level
  compared exactly). On a case-sensitive file system a stray "Trip (2)" beside
  the sequence at "trip (2)" no longer gives a case-only step that MoveFolder
  refuses at every archive open: the plan gives "Trip", and a plan whose
  target appeared since is refused under the step's leases before anything
  moves (or dropped when it resumes). A change of case in an outer level no
  longer looks like two folders on Windows.
- A file name longer than 200 characters is shortened before the ".{ext}" the
  template ends with, never through it, so a long title never strips the
  photo's extension.
- The archive engine's own settings check applies the template rules the
  server and the desktop apply (a folder scans skip, a lost extension, names
  that repeat), so archive.json can no longer take such a template.
- The server's invalid_template answer names the rule after the field
  ("fileTemplate:extension") with the desktop's sentence as its message; both
  admin panels show it on the field.
- FrameNaming keeps only the naming overloads production uses.
- Comments about Unreadable say the whole sequence stays as it is.
- Tests pin filing against Reorganize: an upload without a capture time, a
  card's second session with {session}, a duplicate skipped mid-session, and a
  whole folder of two cameras named with the first one's camera.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 50fe59aec1e180daa1733bcb951892a79dceba6c)
2026-10-27 18:08:08 +01:00

571 lines
35 KiB
C#

using System.Net;
using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Model;
using Chronos.Protocol;
using Chronos.Server.Api;
using Chronos.Server.Events;
using Chronos.Server.Storage;
using Chronos.Testing;
namespace Chronos.Server.Tests.Api;
/// <summary>
/// Reorganize on the server (owner review 2, R7): <c>POST /api/v1/archive/reorganize</c>, its dry run and the plan kept from it
/// for the confirmation (<see cref="ReorganizePlanCache"/>), the <c>move</c> job that applies the confirmed plan (paused and
/// resumed too), and what the request may not do, against the real archive engine.
/// </summary>
[Category("server")]
public sealed class ReorganizeTests(TestContext context)
{
private const string Url = "/api/v1/archive/reorganize";
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(30));
[Test]
public async Task AReorganizeIsDryRunThenAppliedByAJob()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var admin = await server.AdminAsync();
Guid id = default;
for (var i = 0; i < 3; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
await UntilIdleAsync(server);
var before = await server.Database.Frames.ListBySequenceAsync(id);
var request = new ReorganizeRequest([id], false, "reorganized/{title}", "{title}_{n:000}", "Roof", DryRun: true);
ReorganizePlanDto plan;
using (var dry = await admin.PostAsJsonAsync(Url, request, ProtocolJson.Default.ReorganizeRequest))
plan = await dry.ReadAsync(ProtocolJson.Default.ReorganizePlanDto);
Assert.Equal((1, 3, 0), (plan.Sequences, plan.Files, plan.Kept));
var step = plan.Steps.Single();
Assert.Equal((id, "reorganized/Roof", "Roof", 3), (step.SequenceId, step.ToFolder, step.ToTitle, step.FileChanges));
Assert.SequenceEqual(["originals/Roof_001.JPG", "originals/Roof_002.JPG", "originals/Roof_003.JPG"], step.FileSamples.Select(f => f.To));
Assert.Equal(64, plan.Fingerprint.Length);
Assert.SequenceEqual(before.Select(f => f.RelativePath), (await server.Database.Frames.ListBySequenceAsync(id)).Select(f => f.RelativePath));
using (var missing = await admin.PostAsJsonAsync(Url, request with { DryRun = false }, ProtocolJson.Default.ReorganizeRequest))
Assert.Equal("fingerprint", (await missing.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request")).Details);
using (var wrong = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = "0123" }, ProtocolJson.Default.ReorganizeRequest))
Assert.Equal(plan.Fingerprint, (await wrong.ExpectErrorAsync(HttpStatusCode.Conflict, "plan_changed")).Details);
using var events = server.Services.GetRequiredService<EventHub>().Subscribe();
JobDto job;
using (var applied = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = plan.Fingerprint }, ProtocolJson.Default.ReorganizeRequest))
{
await applied.ExpectAsync(HttpStatusCode.Accepted);
job = await applied.ReadAsync(ProtocolJson.Default.JobDto);
}
Assert.Equal("move", job.Kind);
await UntilJobAsync(admin, job.Id, "done");
var sequence = (await server.Database.Sequences.GetAsync(id))!;
Assert.Equal(("reorganized/Roof", "Roof"), (sequence.Folder, sequence.Title));
var after = await server.Database.Frames.ListBySequenceAsync(id);
Assert.SequenceEqual(before.Select(f => f.Id), after.Select(f => f.Id));
Assert.SequenceEqual(["reorganized/Roof/originals/Roof_001.JPG", "reorganized/Roof/originals/Roof_002.JPG", "reorganized/Roof/originals/Roof_003.JPG"],
after.Select(f => f.RelativePath));
foreach (var (was, now) in before.Zip(after))
Assert.Equal(was.Sha256, Uploads.Sha(File.ReadAllBytes(Path.Combine(server.Options.ArchivePath, now.RelativePath))));
Assert.NotEmpty((await server.Database.Audit.ListAsync(null, "archive_reorganized", 10, null)).Items);
var until = DateTime.UtcNow + Wait;
while (true)
{
using var timeout = new CancellationTokenSource(until - DateTime.UtcNow);
var e = await events.Reader.ReadAsync(timeout.Token);
if (e is SequenceChangedEvent { Change: "reorganized" } changed && changed.SequenceId == id)
{
Assert.Equal(sequence.FramesVersion, changed.FramesVersion);
break;
}
}
}
[Test]
public async Task AnExportMovesWithItsFolderAndStaysDownloadable()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var admin = await server.AdminAsync();
var id = (await Uploads.UploadAsync(editor, Photo(1), "IMG_0001.JPG", sessionKey: "roof")).SequenceId;
await UntilIdleAsync(server);
var folder = (await server.Database.Sequences.GetAsync(id))!.Folder;
var video = Uploads.Photo(4096, 28);
var relative = $"{folder}/exports/Roof - 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 = id, PresetName = "4K HEVC", OutputPath = relative, Bytes = video.Length, Created = DateTimeOffset.UtcNow };
await server.Database.Renders.InsertAsync(render);
// A new folder and title, the files keep their names: the folder moves with its exports.
var request = new ReorganizeRequest([id], false, "reorganized/{title}", null, "Roof", DryRun: true);
ReorganizePlanDto plan;
using (var dry = await admin.PostAsJsonAsync(Url, request, ProtocolJson.Default.ReorganizeRequest))
plan = await dry.ReadAsync(ProtocolJson.Default.ReorganizePlanDto);
JobDto job;
using (var applied = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = plan.Fingerprint }, ProtocolJson.Default.ReorganizeRequest))
{
await applied.ExpectAsync(HttpStatusCode.Accepted);
job = await applied.ReadAsync(ProtocolJson.Default.JobDto);
}
await UntilJobAsync(admin, job.Id, "done");
Assert.Equal("reorganized/Roof", (await server.Database.Sequences.GetAsync(id))!.Folder);
Assert.Equal("reorganized/Roof/exports/Roof - 4K.mp4", (await server.Database.Renders.GetAsync(render.Id))!.OutputPath);
using var response = await editor.GetAsync($"/api/v1/renders/{render.Id}/file");
await response.ExpectAsync(HttpStatusCode.OK);
await Http.BytesEqualAsync(video, response.Content.ReadAsByteArrayAsync());
Assert.False(Directory.Exists(Path.Combine(server.Options.ArchivePath, folder)), "nothing is left at the old place");
}
[Test]
public async Task AReorganizeAsksForTheArchiveAndAValidRequest()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var admin = await server.AdminAsync();
var a = (await Uploads.UploadAsync(editor, Photo(1), "a.jpg", sessionKey: "a")).SequenceId;
var b = (await Uploads.UploadAsync(editor, Photo(2), "b.jpg", sessionKey: "b")).SequenceId;
await UntilIdleAsync(server);
var valid = new ReorganizeRequest([a], false, null, "{n:000}", null, DryRun: true);
using (var forbidden = await editor.PostAsJsonAsync(Url, valid, ProtocolJson.Default.ReorganizeRequest))
await forbidden.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
foreach (var (bad, details) in new[]
{
(valid with { All = true }, "sequenceIds"),
(valid with { SequenceIds = null }, "sequenceIds"),
(valid with { SequenceIds = [] }, "sequenceIds"),
(valid with { SequenceIds = [.. Enumerable.Range(0, LibraryEndpoints.MaxBulkIds + 1).Select(_ => Guid.NewGuid())] }, "sequenceIds"),
(valid with { FileTemplate = null }, "templates"),
})
{
using var response = await admin.PostAsJsonAsync(Url, bad, ProtocolJson.Default.ReorganizeRequest);
Assert.Equal(details, (await response.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request")).Details);
}
using (var template = await admin.PostAsJsonAsync(Url, valid with { FileTemplate = "{nope}" }, ProtocolJson.Default.ReorganizeRequest))
Assert.Equal("fileTemplate", (await template.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template")).Details);
// The desktop's rules: no lost extension, names that tell the photos apart, no folder scans skip; each named after the
// field, with the desktop's sentence.
foreach (var (bad, details, rule) in new[]
{
(valid with { FileTemplate = "{n}{ext}" }, "fileTemplate:extension", "Extension"),
(valid with { FileTemplate = "{title}" }, "fileTemplate:not_unique", "NotUnique"),
(valid with { FileTemplate = "{year}/{n}" }, "fileTemplate:file_separator", "FileSeparator"),
(valid with { FolderTemplate = "Exports/{title}" }, "folderTemplate:reserved_folder", "ReservedFolder"),
(valid with { FolderTemplate = ".hidden/{date}" }, "folderTemplate:reserved_folder", "ReservedFolder"),
})
{
using var refused = await admin.PostAsJsonAsync(Url, bad, ProtocolJson.Default.ReorganizeRequest);
var error = await refused.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template");
Assert.Equal(details, error.Details);
Assert.Equal(Chronos.Core.Localization.Loc.Get("Errors.Template." + rule, System.Globalization.CultureInfo.GetCultureInfo("en")), error.Message);
}
using (var blank = await admin.PostAsJsonAsync(Url, valid with { FolderTemplate = " " }, ProtocolJson.Default.ReorganizeRequest))
Assert.Equal("folderTemplate", (await blank.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template")).Details);
using (var unknown = await admin.PostAsJsonAsync(Url, valid with { SequenceIds = [Guid.NewGuid()] }, ProtocolJson.Default.ReorganizeRequest))
await unknown.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
// One sequence's new folder inside the other's: refused, nothing planned.
var host = (await server.Database.Sequences.GetAsync(a))!.Folder;
using (var nested = await admin.PostAsJsonAsync(Url, new ReorganizeRequest([b], false, host + "/inside", null, null, DryRun: true),
ProtocolJson.Default.ReorganizeRequest))
Assert.Equal(host + "/inside", (await nested.ExpectErrorAsync(HttpStatusCode.Conflict, "nested_target")).Details);
using (var all = await admin.PostAsJsonAsync(Url, valid with { SequenceIds = null, All = true }, ProtocolJson.Default.ReorganizeRequest))
{
var plan = await all.ReadAsync(ProtocolJson.Default.ReorganizePlanDto);
Assert.Equal((2, 2), (plan.Sequences, plan.Files));
Assert.SequenceEqual(new[] { a, b }.Order(), plan.Steps.Select(s => s.SequenceId).Order());
}
// The archive drive is gone: neither a dry run nor a plan kept from one is answered.
var manifest = new ArchivePaths(server.Options.ArchivePath).ManifestPath;
File.Move(manifest, manifest + ".away");
try
{
foreach (var request in new[] { valid, valid with { SequenceIds = null, All = true }, valid with { DryRun = false, Fingerprint = new string('0', 64) } })
{
using var offline = await admin.PostAsJsonAsync(Url, request, ProtocolJson.Default.ReorganizeRequest);
await offline.ExpectErrorAsync(HttpStatusCode.ServiceUnavailable, "archive_offline");
}
}
finally
{
File.Move(manifest + ".away", manifest);
}
Assert.Empty((await server.Database.Jobs.ListAsync(JobState.Queued, JobKind.Move)).Items);
}
[Test]
public async Task AReorganizeIsRefusedWhereNoJobCanApplyIt()
{
// Without the archive module the server plans, but no handler of move jobs runs here.
await using var server = await TestServer.StartAsync(context);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var admin = await server.AdminAsync();
var id = (await Uploads.UploadAsync(editor, Photo(1), "a.jpg", sessionKey: "a")).SequenceId;
var request = new ReorganizeRequest([id], false, "moved/{date}", null, null, DryRun: true);
string fingerprint;
using (var dry = await admin.PostAsJsonAsync(Url, request, ProtocolJson.Default.ReorganizeRequest))
{
var plan = await dry.ReadAsync(ProtocolJson.Default.ReorganizePlanDto);
Assert.Equal("moved/2026-09-28", plan.Steps.Single().ToFolder);
fingerprint = plan.Fingerprint;
}
using (var unavailable = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = fingerprint }, ProtocolJson.Default.ReorganizeRequest))
Assert.Equal("move", (await unavailable.ExpectErrorAsync(HttpStatusCode.Conflict, "job_unavailable")).Details);
Assert.Empty((await server.Database.Jobs.ListAsync(null, JobKind.Move)).Items);
Assert.Empty((await server.Database.Audit.ListAsync(null, "archive_reorganized", 10, null)).Items);
}
[Test]
public async Task EverySequenceIsReorganizedByAJobAroundThoseAlreadyInPlace()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var admin = await server.AdminAsync();
var days = new ReorganizeRequest(null, true, "days/{date}", null, null, DryRun: true);
// A sequence already where the template puts it: the others of that day go beside it.
var placed = (await Uploads.UploadAsync(editor, Photo(0), "IMG_0001.JPG", sessionKey: "placed")).SequenceId;
await UntilIdleAsync(server);
await UntilJobAsync(admin, await ConfirmAsync(admin, days with { All = false, SequenceIds = [placed] }), "done");
Assert.Equal("days/2026-09-28", (await server.Database.Sequences.GetAsync(placed))!.Folder);
var a = (await Uploads.UploadAsync(editor, Photo(1), "IMG_0002.JPG", sessionKey: "a")).SequenceId;
var b = (await Uploads.UploadAsync(editor, Photo(2), "IMG_0003.JPG", sessionKey: "b")).SequenceId;
await UntilIdleAsync(server);
ReorganizePlanDto plan;
using (var dry = await admin.PostAsJsonAsync(Url, days, ProtocolJson.Default.ReorganizeRequest))
plan = await dry.ReadAsync(ProtocolJson.Default.ReorganizePlanDto);
Assert.Equal((2, 0, 0), (plan.Sequences, plan.Files, plan.Kept));
Assert.SequenceEqual(new[] { a, b }.Order(), plan.Steps.Select(s => s.SequenceId).Order());
Assert.SequenceEqual(["days/2026-09-28 (2)", "days/2026-09-28 (3)"], plan.Steps.Select(s => s.ToFolder).Order(StringComparer.Ordinal));
// The job plans again over the sequences with a step only: the one left where it is still decides the " (n)".
using var events = server.Services.GetRequiredService<EventHub>().Subscribe();
var job = await ConfirmAsync(admin, days with { DryRun = false, Fingerprint = plan.Fingerprint });
await UntilJobAsync(admin, job, "done");
var folders = new Dictionary<Guid, string>();
foreach (var id in new[] { placed, a, b }) folders[id] = (await server.Database.Sequences.GetAsync(id))!.Folder;
Assert.Equal("days/2026-09-28", folders[placed]);
Assert.SequenceEqual(plan.Steps.Select(s => s.ToFolder), plan.Steps.Select(s => folders[s.SequenceId]));
foreach (var id in new[] { a, b })
Assert.True(Directory.Exists(Path.Combine(server.Options.ArchivePath, folders[id])), folders[id]);
Assert.SequenceEqual(new[] { a, b }.Order(), (await ReorganizedAsync(events, 2)).Order());
using var again = await admin.PostAsJsonAsync(Url, days, ProtocolJson.Default.ReorganizeRequest);
Assert.Equal(0, (await again.ReadAsync(ProtocolJson.Default.ReorganizePlanDto)).Sequences);
}
[Test]
public async Task AnUploadAfterTheDryRunChangesThePlanToConfirm()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var admin = await server.AdminAsync();
Guid id = default;
for (var i = 0; i < 2; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
await UntilIdleAsync(server);
var request = new ReorganizeRequest([id], false, null, "{n:000}", null, DryRun: true);
var shown = await DryRunAsync(admin, request);
Assert.Equal(2, shown.Files);
// A photo arrives before Apply: the plan confirmed is not the one now, which the answer carries.
await Uploads.UploadAsync(editor, Photo(2), "IMG_0003.JPG", sessionKey: "roof");
await UntilIdleAsync(server);
string now;
using (var changed = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = shown.Fingerprint }, ProtocolJson.Default.ReorganizeRequest))
now = Assert.NotNull((await changed.ExpectErrorAsync(HttpStatusCode.Conflict, "plan_changed")).Details);
Assert.NotEqual(shown.Fingerprint, now);
Assert.Empty((await server.Database.Jobs.ListAsync(null, JobKind.Move)).Items);
var replanned = await DryRunAsync(admin, request);
Assert.Equal((now, 3), (replanned.Fingerprint, replanned.Files));
await UntilJobAsync(admin, await ConfirmAsync(admin, request with { DryRun = false, Fingerprint = now }), "done");
Assert.SequenceEqual(["001.JPG", "002.JPG", "003.JPG"], (await server.Database.Frames.ListBySequenceAsync(id)).Select(f => f.FileName));
}
[Test]
public async Task AnUploadFiledUnderTheNameThePlanGivesLeavesThePlanToConfirm()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var admin = await server.AdminAsync();
Guid id = default;
for (var i = 0; i < 2; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
await UntilIdleAsync(server);
// The archive files new photos as the Reorganize names them; the two filed before do not follow it yet.
using (var read = await admin.GetAsync("/api/v1/archive/settings"))
{
var settings = await read.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto);
using var put = await admin.PutAsJsonAsync("/api/v1/archive/settings", settings with { FileTemplate = "{n:000}" }, ProtocolJson.Default.ArchiveSettingsDto);
await put.ExpectAsync(HttpStatusCode.OK);
}
var request = new ReorganizeRequest([id], false, null, "{n:000}", null, DryRun: true);
var shown = await DryRunAsync(admin, request);
Assert.Equal(2, shown.Files);
// The camera still uploads before Apply, a photo after the others: it takes the name the plan leaves it, so the plan
// confirmed is the one now.
await Uploads.UploadAsync(editor, Photo(2), "IMG_0003.JPG", sessionKey: "roof", capturedAt: new DateTime(2026, 9, 28, 18, 3, 0));
await UntilIdleAsync(server);
Assert.Equal("003.JPG", (await server.Database.Frames.ListBySequenceAsync(id))[^1].FileName);
await UntilJobAsync(admin, await ConfirmAsync(admin, request with { DryRun = false, Fingerprint = shown.Fingerprint }), "done");
Assert.SequenceEqual(["001.JPG", "002.JPG", "003.JPG"], (await server.Database.Frames.ListBySequenceAsync(id)).Select(f => f.FileName));
}
[Test]
public async Task AMoveJobPausedBetweenTwoSequencesCompletesTheRestWhenResumed()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var admin = await server.AdminAsync();
var first = (await Uploads.UploadAsync(editor, Photo(0), "IMG_0001.JPG", sessionKey: "first")).SequenceId;
var second = (await Uploads.UploadAsync(editor, Photo(1), "IMG_0002.JPG", sessionKey: "second")).SequenceId;
await UntilIdleAsync(server);
var request = new ReorganizeRequest([first, second], false, "moved/{date}", null, null, DryRun: true);
var plan = await DryRunAsync(admin, request);
Assert.SequenceEqual([first, second], plan.Steps.Select(s => s.SequenceId));
var was = (await server.Database.Sequences.GetAsync(second))!.Folder;
// The second sequence is busy (an editor saving it): the job moves the first, then waits for it and is paused there.
var paths = new ArchivePaths(server.Options.ArchivePath);
var busy = Assert.NotNull(LeaseFile.TryAcquire(paths.LocksDirectory, $"seq-{second:N}", "tests"));
using var events = server.Services.GetRequiredService<EventHub>().Subscribe();
Guid job;
try
{
job = await ConfirmAsync(admin, request with { DryRun = false, Fingerprint = plan.Fingerprint });
await UntilAsync(admin, job, j => j is { State: "running", ProgressDone: 1 });
using (var pause = await admin.PostAsync($"/api/v1/jobs/{job}/pause", null)) await pause.ExpectAsync(HttpStatusCode.OK);
await UntilJobAsync(admin, job, "paused");
// The job is paused before its run stops: once stopped, the plan waits for it.
var until = DateTime.UtcNow + Wait;
while (!RenameJournal.ListPending(paths).Single().Held)
{
Assert.True(DateTime.UtcNow < until, "the plan is held");
await Task.Delay(50);
}
}
finally
{
busy.Dispose();
}
Assert.Equal(plan.Steps[0].ToFolder, (await server.Database.Sequences.GetAsync(first))!.Folder);
Assert.Equal(was, (await server.Database.Sequences.GetAsync(second))!.Folder);
// Resumed, it completes the plan it held and tells the sequence it changed then.
using (var resume = await admin.PostAsync($"/api/v1/jobs/{job}/resume", null)) await resume.ExpectAsync(HttpStatusCode.OK);
await UntilJobAsync(admin, job, "done");
Assert.Equal(plan.Steps[1].ToFolder, (await server.Database.Sequences.GetAsync(second))!.Folder);
Assert.Empty(RenameJournal.ListPending(paths));
Assert.Contains(second, await ReorganizedAsync(events, 1, second));
}
[Test]
public async Task ADryRunIsKeptForTheConfirmWhileTheIndexStaysAsItWas()
{
var clock = new ManualTimeProvider();
await using var server = await TestServer.StartAsync(context, services: s =>
{
ArchiveModule.Register(s);
s.AddSingleton<TimeProvider>(clock);
});
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var admin = await server.AdminAsync();
Guid id = default;
for (var i = 0; i < 2; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
await UntilIdleAsync(server);
var request = new ReorganizeRequest([id], false, "moved/{date}", "{n:000}", null, DryRun: true);
var target = Path.Combine(server.Options.ArchivePath, "moved", "2026-09-28");
var before = (await server.Database.Sequences.GetAsync(id))!.Folder;
// A folder made on disk alone is not in the index: the same dry run again is the plan made before.
var shown = await DryRunAsync(admin, request);
Assert.Equal(("moved/2026-09-28", 2), (shown.Steps.Single().ToFolder, shown.Files));
Directory.CreateDirectory(target);
Assert.Equal(shown.Fingerprint, (await DryRunAsync(admin, request)).Fingerprint);
// A change of the index plans again at once.
await Uploads.UploadAsync(editor, Photo(2), "IMG_0003.JPG", sessionKey: "roof");
await UntilIdleAsync(server);
var beside = await DryRunAsync(admin, request);
Assert.Equal(("moved/2026-09-28 (2)", 3), (beside.Steps.Single().ToFolder, beside.Files));
// The confirmation takes the plan kept; the job plans again and refuses what the kept plan could not see.
Directory.Delete(target);
Assert.Equal(beside.Fingerprint, (await DryRunAsync(admin, request)).Fingerprint);
Assert.Equal("failed", (await FinishedAsync(admin, await ConfirmAsync(admin, request with { DryRun = false, Fingerprint = beside.Fingerprint }))).State);
Assert.Equal(before, (await server.Database.Sequences.GetAsync(id))!.Folder);
Assert.False(Directory.Exists(target), "nothing moved");
Assert.Empty(RenameJournal.ListPending(new ArchivePaths(server.Options.ArchivePath)));
// A queued plan is no longer kept; a kept one lasts its lifetime.
var free = await DryRunAsync(admin, request);
Assert.Equal(("moved/2026-09-28", 3), (free.Steps.Single().ToFolder, free.Files));
Directory.CreateDirectory(target);
Assert.Equal(free.Fingerprint, (await DryRunAsync(admin, request)).Fingerprint);
await UntilIdleAsync(server);
clock.Advance(ReorganizePlanCache.Lifetime);
var later = await DryRunAsync(admin, request);
Assert.Equal("moved/2026-09-28 (2)", later.Steps.Single().ToFolder);
using (var changed = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = free.Fingerprint }, ProtocolJson.Default.ReorganizeRequest))
Assert.Equal(later.Fingerprint, (await changed.ExpectErrorAsync(HttpStatusCode.Conflict, "plan_changed")).Details);
await UntilJobAsync(admin, await ConfirmAsync(admin, request with { DryRun = false, Fingerprint = later.Fingerprint }), "done");
Assert.Equal("moved/2026-09-28 (2)", (await server.Database.Sequences.GetAsync(id))!.Folder);
}
[Test]
public async Task KeptPlansAreTheNewestFewWithinTheirLifetime()
{
var clock = new ManualTimeProvider();
var plans = new ReorganizePlanCache(clock);
var archive = Guid.NewGuid();
var templates = new RenameTemplates(Folder: "moved/{date}");
var made = 0;
Task<RenamePlan> Plan()
{
made++;
return Task.FromResult(new RenamePlan(Guid.NewGuid(), archive, []));
}
ReorganizePlanCache.Key Key(int i) => ReorganizePlanCache.Key.Of(archive, "stamp", [new Guid(i, 0, 0, new byte[8])], templates);
var kept = await plans.GetOrPlanAsync(Key(0), Plan);
Assert.True(ReferenceEquals(kept, await plans.GetOrPlanAsync(Key(0), Plan)), "kept");
Assert.Equal(1, made);
// Another order of the sequences, every sequence, another stamp or other templates is another plan.
var (x, y) = (Guid.NewGuid(), Guid.NewGuid());
Assert.NotEqual(ReorganizePlanCache.Key.Of(archive, "stamp", [x, y], templates), ReorganizePlanCache.Key.Of(archive, "stamp", [y, x], templates));
Assert.Equal(ReorganizePlanCache.Key.Of(archive, "stamp", [x, y], templates), ReorganizePlanCache.Key.Of(archive, "stamp", [x, y], templates with { }));
Assert.NotEqual(ReorganizePlanCache.Key.Of(archive, "stamp", null, templates), ReorganizePlanCache.Key.Of(archive, "stamp", [x], templates));
Assert.NotEqual(Key(0), ReorganizePlanCache.Key.Of(archive, "other", [new Guid(0, 0, 0, new byte[8])], templates));
Assert.NotEqual(Key(0), ReorganizePlanCache.Key.Of(archive, "stamp", [new Guid(0, 0, 0, new byte[8])], templates with { File = "{n}" }));
// At most Capacity plans: the oldest goes first.
for (var i = 1; i <= ReorganizePlanCache.Capacity; i++)
{
clock.Advance(TimeSpan.FromSeconds(1));
await plans.GetOrPlanAsync(Key(i), Plan);
}
Assert.Equal(1 + ReorganizePlanCache.Capacity, made);
await plans.GetOrPlanAsync(Key(ReorganizePlanCache.Capacity), Plan);
Assert.Equal(1 + ReorganizePlanCache.Capacity, made);
await plans.GetOrPlanAsync(Key(0), Plan);
Assert.Equal(2 + ReorganizePlanCache.Capacity, made);
// A plan is kept for its lifetime, from when its planning started.
clock.Advance(ReorganizePlanCache.Lifetime - TimeSpan.FromSeconds(1));
await plans.GetOrPlanAsync(Key(0), Plan);
Assert.Equal(2 + ReorganizePlanCache.Capacity, made);
clock.Advance(TimeSpan.FromSeconds(1));
await plans.GetOrPlanAsync(Key(0), Plan);
Assert.Equal(3 + ReorganizePlanCache.Capacity, made);
// A refusal is not kept, and a plan forgotten is made again.
await Assert.ThrowsAsync<NestedRenameException>(() => plans.GetOrPlanAsync(Key(99), () => throw new NestedRenameException("a/b", "a")));
await plans.GetOrPlanAsync(Key(99), Plan);
Assert.Equal(4 + ReorganizePlanCache.Capacity, made);
plans.Forget(Key(99));
await plans.GetOrPlanAsync(Key(99), Plan);
Assert.Equal(5 + ReorganizePlanCache.Capacity, made);
}
private static async Task<ReorganizePlanDto> DryRunAsync(HttpClient client, ReorganizeRequest request)
{
using var response = await client.PostAsJsonAsync(Url, request with { DryRun = true }, ProtocolJson.Default.ReorganizeRequest);
return await response.ReadAsync(ProtocolJson.Default.ReorganizePlanDto);
}
/// <summary>Confirms a plan; returns the move job queued.</summary>
private static async Task<Guid> ConfirmAsync(HttpClient client, ReorganizeRequest request)
{
if (request.DryRun) request = request with { DryRun = false, Fingerprint = (await DryRunAsync(client, request)).Fingerprint };
using var response = await client.PostAsJsonAsync(Url, request, ProtocolJson.Default.ReorganizeRequest);
await response.ExpectAsync(HttpStatusCode.Accepted);
return (await response.ReadAsync(ProtocolJson.Default.JobDto)).Id;
}
/// <summary>The sequences told reorganized, until <paramref name="count"/> were (or <paramref name="awaited"/> was).</summary>
private static async Task<List<Guid>> ReorganizedAsync(EventHub.Subscription events, int count, Guid? awaited = null)
{
var told = new List<Guid>();
var until = DateTime.UtcNow + Wait;
while (awaited is { } id ? !told.Contains(id) : told.Count < count)
{
using var timeout = new CancellationTokenSource(until - DateTime.UtcNow);
if (await events.Reader.ReadAsync(timeout.Token) is SequenceChangedEvent { Change: "reorganized" } changed) told.Add(changed.SequenceId);
}
return told;
}
[Test]
public async Task PhotosThatKeepTheirNamesAreToldWhy()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var admin = await server.AdminAsync();
// Photos copied into the archive by hand and found by a scan stay where they are.
var folder = Path.Combine(server.Options.ArchivePath, "trips");
Directory.CreateDirectory(folder);
for (var i = 0; i < 2; i++) await File.WriteAllBytesAsync(Path.Combine(folder, $"IMG_{i:0000}.JPG"), Photo(i));
using (var scan = await admin.PostAsync("/api/v1/archive/scan", null)) await scan.ExpectAsync(HttpStatusCode.Accepted);
await UntilIdleAsync(server);
var id = (await server.Database.Sequences.ListLocationsAsync((await server.Database.Archives.ListAsync()).Single().Id)).Single().Id;
var request = new ReorganizeRequest([id], false, null, "{n:000}", null, DryRun: true);
admin.DefaultRequestHeaders.AcceptLanguage.ParseAdd("it");
using var dry = await admin.PostAsJsonAsync(Url, request, ProtocolJson.Default.ReorganizeRequest);
var plan = await dry.ReadAsync(ProtocolJson.Default.ReorganizePlanDto);
Assert.Equal((0, 0, 2), (plan.Sequences, plan.Files, plan.Kept));
var blocked = plan.Steps.Single().Blocked.Single();
Assert.Equal(("in_place", 2), (blocked.Reason, blocked.Photos));
Assert.Equal(Chronos.Core.Localization.Loc.Get("Archive.Reorganize.Blocked.InPlace", System.Globalization.CultureInfo.GetCultureInfo("it")), blocked.Message);
}
private static async Task UntilJobAsync(HttpClient client, Guid id, string state)
{
var job = await UntilAsync(client, id, j => j.State == state || j.State is "failed" or "cancelled");
if (job.State != state) Assert.Fail($"job {job.Kind} {job.State}: {job.Error}\n{job.LogTail}");
}
/// <summary>The job once it ended: done, failed or cancelled.</summary>
private static Task<JobDto> FinishedAsync(HttpClient client, Guid id) => UntilAsync(client, id, j => j.State is "done" or "failed" or "cancelled");
private static async Task<JobDto> UntilAsync(HttpClient client, Guid id, Func<JobDto, bool> reached)
{
var until = DateTime.UtcNow + Wait;
while (true)
{
using var response = await client.GetAsync($"/api/v1/jobs/{id}");
var job = await response.ReadAsync(ProtocolJson.Default.JobDto);
if (reached(job)) return job;
Assert.True(DateTime.UtcNow < until, $"job {job.Kind} still {job.State} ({job.ProgressDone}/{job.ProgressTotal})");
await Task.Delay(50);
}
}
/// <summary>Waits until no job is queued or running (the thumbnails, proxies and analyses uploads queue).</summary>
private static async Task UntilIdleAsync(TestServer server)
{
var until = DateTime.UtcNow + Wait;
foreach (var state in new[] { JobState.Queued, JobState.Running, JobState.Queued, JobState.Running })
{
while ((await server.Database.Jobs.ListAsync(state)).Items.Count > 0)
{
Assert.True(DateTime.UtcNow < until, $"jobs still {state}");
await Task.Delay(50);
}
}
}
private static byte[] Photo(int seed)
{
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 });
}
}