feat: owner review 2 phase 4b: mass conversion after import #13
No files matched your search
@@ -85,7 +85,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
|
||||
| `Ui/Controls` | `ChronosWindow` (chrome, language direction), `NavRail`, `JobBar`, `ToastHost`, `Field` (placeholder, icon, error), `Chip`, `AutoSlider`, `StatusGlyph`, `EmptyState`, `Icon`, `Bidi` (right-to-left rules), `Motion` (animations off for screenshots) |
|
||||
| `Ui/Interop` | DWM calls of the window chrome; `TrayIcon` (`Shell_NotifyIconW`: the Uploader's tray, the client's Windows notifications) |
|
||||
| `Ui/Visuals` | `DrawingElement` (hover readout, item keyboard and activation) and its charts (`BarChart`, `SeriesChart`, `StackedBar`, `HeatmapStrip`, `TimelineBands`), `Filmstrip`, `PreviewViewport`, `CurveEditor`, `SequenceCard`, `VirtualizingWrapPanel`, `SegmentedControl`, `SplitButton` |
|
||||
| `Server/Api`, `Server/Events` | Endpoint groups (`XxxEndpoints.Map`; `ScheduleEndpoints`: `/api/v1/schedules`; `LibraryEndpoints`: the Library filters' facets, sequence thumbnail, photo delete, bulk delete/retag/jobs; `TrashEndpoints`: list, restore, empty; `ArchiveEndpoints`: settings, statistics, scan jobs, Reorganize's dry run and `move` job), API errors, the WebSocket `EventHub` |
|
||||
| `Server/Api`, `Server/Events` | Endpoint groups (`XxxEndpoints.Map`; `ScheduleEndpoints`: `/api/v1/schedules`; `LibraryEndpoints`: the Library filters' facets, sequence thumbnail, photo delete, bulk delete/retag/jobs; `TrashEndpoints`: list, restore, empty; `ArchiveEndpoints`: settings, statistics, scan jobs, Reorganize's dry run and `move` job, with `ReorganizePlanCache`: a dry run's plan kept a few minutes while the index's stamp stays, for the same dry run and its confirmation), API errors, the WebSocket `EventHub` |
|
||||
| `Server/Security` | Accounts, password hashing, tokens, session cookies, login guard, access rules, audit log |
|
||||
| `Server/Storage`, `Server/Jobs` | Archive and processing modules, uploads (`UploadMaintenance`: recovery at start, and the sweep that is the `uploads` clean-up step), render store; `JobEngineHost`, `SchedulerHost` (the `Scheduler` on the engine, started after it; archive.json read every 10 minutes whatever the scan schedule does; every schedule change and run published as a `scheduleChanged` event) and `ServerScheduleHost` (time zone, archive refreshed from archive.json, system schedules), render node service, monitor and availability |
|
||||
| `Server/Hosting`, `Server/Admin/web` | `ServerHost`, `ServerLogging` (console and file levels the logging filters read at every line, the file sink's limits, the engine's level; applied again when Settings › Logs is saved), certificates, discovery beacon, embedded static files (`EmbeddedStaticFiles`: `no-cache` and a content ETag, so an upgrade never mixes old and new modules), Windows service (start and stop failures in the Application event log); the admin panel (ES modules, one per page; `schedules.js` is the Jobs page's Scheduled tab; the Library's views in `pages/library/`: `sequence.js` a sequence and its photo viewer, `trash.js` the archive's trash, `shared.js` cards, selection, grid keyboard and the retry of thumbnails a finished job may have built; `upload.js` the upload dialog the Library opens on demand, hashing in the module worker `hash-worker.js` with the in-house incremental SHA-256 of `sha256.js`, self-tested before its first use, and sending the capture time `capture-time.js` reads: the Exif DateTimeOriginal of a JPEG or TIFF-based file, else the file's time; `reorganize.js` the Reorganize dialog of the Library's selection and of the Archive page's save toast: template switches and fields, a live dry run of `POST /archive/reorganize` one request at a time, Apply that sends the shown plan's fingerprint back) |
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
@@ -425,6 +427,24 @@ public sealed class SequenceRepository
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A digest of the index rows of <paramref name="archiveId"/> (owner review 2, R7): another value once a sequence is
|
||||
/// added or removed, or once a row changes in what a Reorganize plans from (folder, title, first capture, camera, lens,
|
||||
/// frame count) or in what every write of it moves (its versions, verify time and time of change). A change made on
|
||||
/// disk alone, which the index does not have yet, leaves it as it was.
|
||||
/// </summary>
|
||||
public async Task<string> GetStampAsync(Guid archiveId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var rows = await _db.ListAsync(
|
||||
"SELECT id, folder, title, first_capture, camera_make, camera_model, lens, frame_count, frames_version, settings_version, verified_at, updated_at " +
|
||||
"FROM sequences WHERE archive_id = $1 ORDER BY id", [archiveId],
|
||||
r => string.Create(CultureInfo.InvariantCulture,
|
||||
$"{r.GetGuid(0):N}\u001f{r.GetString(1)}\u001f{r.GetStringOrNull(2)}\u001f{r.GetDateTimeOrNull(3):O}\u001f{r.GetStringOrNull(4)}\u001f" +
|
||||
$"{r.GetStringOrNull(5)}\u001f{r.GetStringOrNull(6)}\u001f{r.GetInt32(7)}\u001f{r.GetInt32(8)}\u001f{r.GetInt32(9)}\u001f" +
|
||||
$"{r.GetDateTimeOffsetOrNull(10):O}\u001f{r.GetDateTimeOffset(11):O}"), cancellationToken).ConfigureAwait(false);
|
||||
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join('\n', rows))));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sequences of <paramref name="archiveId"/> a rolling verification checks next (owner review 2, R10): those never
|
||||
/// verified first, then the longest unverified, at most <paramref name="limit"/>. With <paramref name="verifiedBefore"/>
|
||||
|
||||
@@ -138,10 +138,11 @@ public static class ArchiveEndpoints
|
||||
/// <c>not_found</c> (<c>sequence</c>: not in the archive); 409 <c>nested_target</c> (details: the folder that would lie
|
||||
/// inside a sequence's folder), <c>plan_changed</c> (details: the fingerprint now), <c>job_unavailable</c>; 503
|
||||
/// <c>archive_offline</c>. Audited; the job tells every sequence it changes as <c>sequenceChanged</c>
|
||||
/// (<c>reorganized</c>).
|
||||
/// (<c>reorganized</c>). A dry run's plan is kept a few minutes while the index stays as it was
|
||||
/// (<see cref="ReorganizePlanCache"/>): the same dry run again, and its confirmation, take it instead of planning again.
|
||||
/// </summary>
|
||||
private static async Task<IResult> ReorganizeAsync(HttpContext context, Caller caller, ReorganizeRequest request, ChronosDatabase db, ServerArchive archive,
|
||||
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit)
|
||||
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit, ReorganizePlanCache plans)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (request.All == (request.SequenceIds is not null) || request.SequenceIds is { Count: 0 or > LibraryEndpoints.MaxBulkIds })
|
||||
@@ -152,10 +153,13 @@ public static class ArchiveEndpoints
|
||||
if (!request.DryRun && string.IsNullOrWhiteSpace(request.Fingerprint)) return ApiErrors.BadRequest(context, "bad_request", "fingerprint");
|
||||
if (ArchiveService.GetAvailability(archive.Current) != ArchiveAvailability.Online)
|
||||
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
|
||||
var sequences = request.All ? null : request.SequenceIds;
|
||||
// Stamped before planning: a change committed while the plan is made gives the next request another key.
|
||||
var key = ReorganizePlanCache.Key.Of(archive.Id, await db.Sequences.GetStampAsync(archive.Id, ct), sequences, templates);
|
||||
RenamePlan plan;
|
||||
try
|
||||
{
|
||||
plan = await LibraryEndpoints.Engine(archives, db).PlanReorganizeAsync(archive.Id, request.All ? null : request.SequenceIds, templates, ct);
|
||||
plan = await plans.GetOrPlanAsync(key, () => LibraryEndpoints.Engine(archives, db).PlanReorganizeAsync(archive.Id, sequences, templates, ct));
|
||||
}
|
||||
catch (NestedRenameException ex)
|
||||
{
|
||||
@@ -170,6 +174,7 @@ public static class ArchiveEndpoints
|
||||
if (!string.Equals(fingerprint, request.Fingerprint, StringComparison.Ordinal)) return ApiErrors.Conflict(context, "plan_changed", fingerprint);
|
||||
if (!host.CanRun(JobKind.Move)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(JobKind.Move));
|
||||
var job = await host.Engine.EnqueueAsync(ArchiveJobs.Reorganize(archive.Current, plan, templates), caller.Id, ct);
|
||||
plans.Forget(key);
|
||||
await audit.WriteAsync(caller, context, "archive_reorganized", "job", job.Id.ToString(),
|
||||
$"{plan.Steps.Count(s => s.Changes)} · {plan.Steps.Sum(s => s.FileChanges)} · {templates.Folder} · {templates.File} · {templates.Title}");
|
||||
return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Reorganize's dry runs kept a short while (owner review 2, R7): the same dry run asked again, and the confirmation that
|
||||
/// follows it, take the plan made then instead of reading every sidecar and photo folder of the selection again (with
|
||||
/// <c>all</c>, of the whole archive), while the archive's index is as it was then
|
||||
/// (<see cref="SequenceRepository.GetStampAsync"/>) and for at most <see cref="Lifetime"/>. A change made on disk alone,
|
||||
/// which the index does not have, is not seen by a kept plan: the <c>move</c> job plans again and refuses a plan that no
|
||||
/// longer matches the archive, so nothing changes that the dry run did not show.
|
||||
/// </summary>
|
||||
public sealed class ReorganizePlanCache(TimeProvider time)
|
||||
{
|
||||
/// <summary>How long a plan is kept, from when its planning started.</summary>
|
||||
public static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(5);
|
||||
|
||||
/// <summary>Plans kept at most (a plan of every sequence holds one step per sequence); the oldest goes first.</summary>
|
||||
public const int Capacity = 8;
|
||||
|
||||
private readonly Lock _gate = new();
|
||||
private readonly Dictionary<Key, (RenamePlan Plan, DateTimeOffset Started)> _plans = [];
|
||||
|
||||
/// <summary>
|
||||
/// What a plan is kept by: the archive, the stamp of its index, the sequences (all of them, or the ids in the order
|
||||
/// given, which decides the folder that gets " (2)") and the templates.
|
||||
/// </summary>
|
||||
public readonly record struct Key(Guid ArchiveId, string Stamp, string Sequences, RenameTemplates Templates)
|
||||
{
|
||||
/// <param name="sequenceIds">The sequences of the request; null for every sequence of the archive.</param>
|
||||
public static Key Of(Guid archiveId, string stamp, IReadOnlyList<Guid>? sequenceIds, RenameTemplates templates) =>
|
||||
new(archiveId, stamp, sequenceIds is null ? "*" : string.Join(',', sequenceIds.Select(id => id.ToString("N"))), templates);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The plan kept for <paramref name="key"/>, or the one <paramref name="plan"/> makes now, then kept; a refusal
|
||||
/// (<paramref name="plan"/> throws) is not kept.
|
||||
/// </summary>
|
||||
public async Task<RenamePlan> GetOrPlanAsync(Key key, Func<Task<RenamePlan>> plan)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
DateTimeOffset started;
|
||||
lock (_gate)
|
||||
{
|
||||
started = time.GetUtcNow();
|
||||
Expire(started);
|
||||
if (_plans.TryGetValue(key, out var kept)) return kept.Plan;
|
||||
}
|
||||
var made = await plan().ConfigureAwait(false);
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_plans.ContainsKey(key) && _plans.Count >= Capacity) _plans.Remove(_plans.MinBy(p => p.Value.Started).Key);
|
||||
_plans[key] = (made, started);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
/// <summary>Forgets the plan kept for <paramref name="key"/>: its job is queued, and what the job changes gives the index another stamp.</summary>
|
||||
public void Forget(Key key)
|
||||
{
|
||||
lock (_gate) _plans.Remove(key);
|
||||
}
|
||||
|
||||
private void Expire(DateTimeOffset now)
|
||||
{
|
||||
foreach (var key in _plans.Where(p => now - p.Value.Started >= Lifetime).Select(p => p.Key).ToList()) _plans.Remove(key);
|
||||
}
|
||||
}
|
||||
@@ -142,6 +142,7 @@ public static class ServerHost
|
||||
services.AddSingleton<RenderStore>();
|
||||
services.AddSingleton<RenderUploads>();
|
||||
services.AddSingleton<SequenceJobs>();
|
||||
services.AddSingleton<ReorganizePlanCache>();
|
||||
services.AddSingleton<RenderNodeService>();
|
||||
services.AddSingleton<JobEngineHost>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<JobEngineHost>());
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Data.Tests.Infrastructure;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Repositories;
|
||||
|
||||
/// <summary>
|
||||
/// The stamp of an archive's index rows (<see cref="SequenceRepository.GetStampAsync"/>) on both dialects: the server makes
|
||||
/// a kept Reorganize plan again once it is another one (owner review 2, R7).
|
||||
/// </summary>
|
||||
public abstract class SequenceStampTests(TestContext context) : RepositoryTest(context)
|
||||
{
|
||||
[Test]
|
||||
public async Task TheStampFollowsEveryChangeOfTheArchivesSequencesAndNoOtherArchives()
|
||||
{
|
||||
var db = await OpenChronosAsync();
|
||||
var archive = TestData.Archive();
|
||||
var other = TestData.Archive("Other");
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
await db.Archives.UpsertAsync(other, Ct);
|
||||
var empty = await db.Sequences.GetStampAsync(archive.Id, Ct);
|
||||
var sequence = TestData.Sequence(archive.Id, new DateTime(2026, 9, 28, 18, 0, 0), "Roof");
|
||||
await db.Sequences.UpsertAsync(sequence, Ct);
|
||||
var stamp = await db.Sequences.GetStampAsync(archive.Id, Ct);
|
||||
Assert.NotEqual(empty, stamp);
|
||||
Assert.Equal(stamp, await db.Sequences.GetStampAsync(archive.Id, Ct));
|
||||
|
||||
// The sequences of another archive are not in it.
|
||||
await db.Sequences.UpsertAsync(TestData.Sequence(other.Id), Ct);
|
||||
Assert.Equal(stamp, await db.Sequences.GetStampAsync(archive.Id, Ct));
|
||||
|
||||
// Every change of the row gives one never seen before.
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal) { empty, stamp };
|
||||
async Task ChangedAsync(string what) => Assert.True(seen.Add(await db.Sequences.GetStampAsync(archive.Id, Ct)), what);
|
||||
Assert.Equal(SequenceEditOutcome.Updated, (await db.Sequences.EditAsync(sequence.Id, new SequenceEdit { Title = "Ridge" }, null, Ct)).Outcome);
|
||||
await ChangedAsync("title");
|
||||
Assert.True(await db.Sequences.RelocateAsync(sequence.Id, "2026/moved", null, Ct));
|
||||
await ChangedAsync("folder");
|
||||
await db.Frames.BulkInsertAsync([TestData.Frame(sequence.Id, 0)], Ct);
|
||||
Assert.NotNull(await db.Sequences.RefreshStatsAsync(sequence.Id, Ct));
|
||||
await ChangedAsync("photos");
|
||||
// A row indexed again from its sidecar keeps the sidecar's time of change: its folder alone tells.
|
||||
var row = Assert.NotNull(await db.Sequences.GetAsync(sequence.Id, Ct));
|
||||
await db.Sequences.UpsertAsync(row with { Folder = "2026/elsewhere" }, Ct);
|
||||
await ChangedAsync("folder of a row written back");
|
||||
Assert.True(await db.Sequences.RecordVerifiedAsync(sequence.Id, SequenceStatus.None, SequenceStatus.None, TestData.Now, Ct));
|
||||
await ChangedAsync("verify");
|
||||
Assert.True(await db.Sequences.DeleteAsync(sequence.Id, Ct));
|
||||
Assert.Equal(empty, await db.Sequences.GetStampAsync(archive.Id, Ct));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SqliteSequenceStampTests(TestContext context) : SequenceStampTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteMemory;
|
||||
}
|
||||
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PostgresSequenceStampTests(TestContext context) : SequenceStampTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
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;
|
||||
@@ -11,8 +13,9 @@ 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, the <c>move</c> job that
|
||||
/// applies the confirmed plan, and what the request may not do, against the real archive engine.
|
||||
/// 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)
|
||||
@@ -135,6 +138,7 @@ public sealed class ReorganizeTests(TestContext context)
|
||||
(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"),
|
||||
})
|
||||
{
|
||||
@@ -172,9 +176,298 @@ public sealed class ReorganizeTests(TestContext context)
|
||||
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 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()
|
||||
{
|
||||
@@ -199,15 +492,23 @@ public sealed class ReorganizeTests(TestContext context)
|
||||
}
|
||||
|
||||
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 (job.State == state) return;
|
||||
if (job.State is "failed" or "cancelled") Assert.Fail($"job {job.Kind} {job.State}: {job.Error}\n{job.LogTail}");
|
||||
Assert.True(DateTime.UtcNow < until, $"job {job.Kind} still {job.State}");
|
||||
if (reached(job)) return job;
|
||||
Assert.True(DateTime.UtcNow < until, $"job {job.Kind} still {job.State} ({job.ProgressDone}/{job.ProgressTotal})");
|
||||
await Task.Delay(50);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user