feat: owner review 2 phase 4a: Reorganize sequences after import (#12)
CI / Build and test (push) Successful in 9m15s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 15m35s
CI / PostgreSQL 16 integration (push) Successful in 7m26s
CI / PostgreSQL 17 integration (push) Successful in 6m47s
CI / Docker image (push) Successful in 59s
Release / Server image (push) Successful in 1m24s

- Reorganize… on the web panel and the desktop: folder, file and title templates applied to existing sequences, with a dry run and an explicit Apply that runs as a job.
- One naming rule (FrameNaming) for import, upload and Reorganize.
- Crash-safe plan and file journals, held plans, stale-plan refusal; exports move with their folder.
- Writers refuse a folder another program moved or gave to another sequence.
- Server: POST /api/v1/archive/reorganize with a bounded plan cache; template rules.
- Phase 3 docs and translations merged; strings in all 38 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #12.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-27 21:58:39 +01:00
1 parent 9aa818ed47
commit 7e4a3b481d
416 files changed
+15304 -1572

No files matched your search

+143 -89
View File
@@ -5,6 +5,7 @@ using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.IO;
using Chronos.Core.Localization;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
@@ -15,7 +16,7 @@ namespace Chronos.Data.Archiving;
/// client or render node that can (BRIEF §2.3): unlike <paramref name="Undecodable"/> ones, nothing is wrong with them.</param>
public sealed record ImagePassResult(int Built, int Reused, int Undecodable, int Waiting = 0);
/// <summary>What became of a proxy sent by a client or render node (<see cref="ArchiveImages.StoreProxy"/>).</summary>
/// <summary>What became of a proxy sent by a client or render node (<see cref="ArchiveImages.StoreProxyAsync"/>).</summary>
public enum ProxyStoreResult
{
Stored,
@@ -31,6 +32,9 @@ public enum ProxyStoreResult
/// <summary>Smaller than the archive's proxies of that frame: made from an embedded preview, not the original.</summary>
TooSmall,
/// <summary>The frame's sequence left the index meanwhile (deleted), or its folder (moved by another index): nothing was written.</summary>
Gone,
}
/// <summary>
@@ -38,7 +42,7 @@ public enum ProxyStoreResult
/// regenerable and self-validating: a thumbnail carries its source fingerprint, a proxy its capture time, so after
/// frames were renumbered the stale ones are rebuilt and the rest reused. A frame whose original this host cannot
/// decode (<see cref="NeedsProxy(ImageDecoder, ImageFileFormat)"/>) gets its proxy from a client or render node that can
/// (<see cref="StoreProxy"/>, BRIEF §2.3) and its thumbnail from that proxy. A frame nothing decodes is flagged
/// (<see cref="StoreProxyAsync"/>, BRIEF §2.3) and its thumbnail from that proxy. A frame nothing decodes is flagged
/// undecodable (BRIEF §8.2 tier 3); one flagged so that decodes after all gets its tier probed again.
/// </summary>
public sealed class ArchiveImages
@@ -54,6 +58,9 @@ public sealed class ArchiveImages
private static readonly TimeSpan CommitInterval = TimeSpan.FromSeconds(10);
/// <summary>How long a proxy pass lets the thumbnail lease go between two batches: longer than a waiting writer sleeps between its tries.</summary>
private static readonly TimeSpan BatchGap = LeaseFile.LongestPoll * 1.5;
/// <summary>
/// Age of a proxy file under which its header is not kept: a file system's clock may give a file written again at
/// once (with the same length) the same write time, at a granularity of up to two seconds.
@@ -122,7 +129,7 @@ public sealed class ArchiveImages
Check(proxy, capturedAt, width, height, policy).Check is ProxyCheck.Current or ProxyCheck.Unverifiable;
/// <summary>
/// A proxy of the original at <paramref name="path"/> for a server that cannot decode it (<see cref="StoreProxy"/>):
/// A proxy of the original at <paramref name="path"/> for a server that cannot decode it (<see cref="StoreProxyAsync"/>):
/// at <paramref name="longEdge"/> (0 = full size) and <paramref name="quality"/>, with <paramref name="frame"/>'s capture
/// data (the server's record, which it checks) and <paramref name="camera"/> in its Exif. Null when
/// <paramref name="decoder"/> cannot decode the original either.
@@ -159,10 +166,14 @@ public sealed class ArchiveImages
/// Files a proxy made elsewhere (a client or render node whose decoders read the original) as the frame's proxy,
/// replacing the one there: a JPEG of at most <see cref="MaxProxyBytes"/> that decodes, whose Exif capture time is the
/// frame's (proxies carry it, so the proxy counts as current and cannot belong to another photo) and whose size is
/// the policy's (<see cref="TooSmall"/>), written atomically.
/// the policy's (<see cref="TooSmall"/>), written atomically under the sequence's lease into its folder as the index has
/// it then: a Reorganize moves the folder under that lease, and the folder it left is never created again (one another
/// index moved, which this index finds at its next scan, takes nothing, nor does that folder when it holds another
/// sequence now: <see cref="ProxyStoreResult.Gone"/>).
/// </summary>
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only.</exception>
public ProxyStoreResult StoreProxy(Archive archive, Sequence sequence, Frame frame, byte[] jpeg)
/// <exception cref="LeaseUnavailableException">Another writer held the sequence for longer than the lease wait.</exception>
public async Task<ProxyStoreResult> StoreProxyAsync(Archive archive, Sequence sequence, Frame frame, byte[] jpeg, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(jpeg);
var paths = new ArchivePaths(archive.RootPath);
@@ -177,11 +188,16 @@ public sealed class ArchiveImages
using var stream = new MemoryStream(jpeg, writable: false);
if (!SameCapture(MetadataReader.Read(stream, "proxy.jpg").CapturedAt, captured)) return ProxyStoreResult.WrongFrame;
}
var folder = paths.Sequence(sequence.Folder);
Directory.CreateDirectory(folder.Proxies);
var path = folder.Proxy(frame.Index);
AtomicFile.WriteAllBytes(path, jpeg);
Headers.TryRemove(path, out _);
await using (await _writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
{
if (await _db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false) is not { } row) return ProxyStoreResult.Gone;
var folder = paths.Sequence(row.Folder);
if (!SequenceFolders.Holds(folder, row.Id)) return ProxyStoreResult.Gone;
Directory.CreateDirectory(folder.Proxies);
var path = folder.Proxy(frame.Index);
AtomicFile.WriteAllBytes(path, jpeg);
Headers.TryRemove(path, out _);
}
return ProxyStoreResult.Stored;
}
@@ -199,17 +215,22 @@ public sealed class ArchiveImages
ArchiveVolume.EnsureWritable(paths);
var archiveManifest = ManifestStore.ReadArchive(paths.ManifestPath);
var policy = archiveManifest.ThumbnailPolicy;
var folder = paths.Sequence(sequence.Folder);
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
SequenceManifest manifest;
int built = 0, reused = 0, undecodable = 0;
var complete = true;
var tiers = new Dictionary<Guid, FileTier>();
var companions = await GprCompanions.FindAsync(_db, archive, manifest.Frames, cancellationToken).ConfigureAwait(false);
// Thumbnail writers exclude each other only; ingest keeps committing meanwhile.
// Image passes exclude each other only (a proxy pass holds this lease a batch at a time); ingest keeps committing
// meanwhile. A Reorganize moves the folder under this lease too, so the folder is the one the index has once it is
// held: the pack never opens in a folder the sequence left, which opening it would create again.
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{sequence.Id:N}", _writer.Options.Owner, _writer.Options.LeaseWait,
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
using (var pack = ThumbPackWriter.Open(folder.ThumbsPackPath))
{
var folder = await SequenceWriter.FolderAsync(_db, paths, sequence, cancellationToken).ConfigureAwait(false);
manifest = ManifestStore.ReadSequence(folder.ManifestPath);
// Another sequence's folder now (another index moved this one away and that one in): its pack is never opened.
if (manifest.Id != sequence.Id) throw new InvalidOperationException(Loc.L("Errors.Archive.FolderMoved"));
var companions = await GprCompanions.FindAsync(_db, archive, manifest.Frames, cancellationToken).ConfigureAwait(false);
using var pack = ThumbPackWriter.Open(folder.ThumbsPackPath);
for (var i = 0; i < startFrame && i < manifest.Frames.Count; i++)
{
var frame = manifest.Frames[i];
@@ -278,7 +299,10 @@ public sealed class ArchiveImages
/// proxies of the frames an earlier run did again (their headers only). The <see cref="FrameFlags.PreviewOnly"/> flag
/// of frames this host reads through their proxies follows whether they have one (<see cref="FrameTiers"/>). Several
/// originals are decoded at once (<see cref="PassParallelism"/>), and a checkpoint still means that every frame before
/// it has its proxy written (<see cref="OrderedWork{T}"/>).
/// it has its proxy written (<see cref="OrderedWork{T}"/>). The pass works in batches (<see cref="ProxyBatch"/>), each
/// under the thumbnail lease with the sequence's folder and sidecar read again; a folder that is not where the index
/// has it (another index moved it, until this index's next scan), or that holds another sequence now, stops the pass
/// with an <see cref="InvalidOperationException"/>, nothing written there.
/// </remarks>
public async Task<ImagePassResult> BuildProxiesAsync(Archive archive, Sequence sequence, bool force, int startFrame,
Func<int, int, ValueTask> checkpoint, CancellationToken cancellationToken = default)
@@ -287,91 +311,119 @@ public sealed class ArchiveImages
ArchiveVolume.EnsureWritable(paths);
var policy = ManifestStore.ReadArchive(paths.ManifestPath).ProxyPolicy;
if (policy.LongEdge == ProxyPolicy.Disabled) return new ImagePassResult(0, 0, 0);
var folder = paths.Sequence(sequence.Folder);
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
Directory.CreateDirectory(folder.Proxies);
SequenceManifest? manifest = null;
int built = 0, reused = 0, undecodable = 0, waiting = 0;
var complete = true;
var tiers = new Dictionary<Guid, FileTier>();
var companions = await GprCompanions.FindAsync(_db, archive, manifest.Frames, cancellationToken).ConfigureAwait(false);
var cadence = new Cadence();
await using (var work = new OrderedWork<Made>(ProxyParallelism(manifest.Frames, policy), made =>
{
switch (made.Outcome)
{
case ProxyOutcome.Built:
built++;
break;
case ProxyOutcome.Reused:
reused++;
break;
case ProxyOutcome.Waiting:
waiting++;
break;
case ProxyOutcome.Failed:
undecodable++;
complete = false;
break;
default:
undecodable++;
break;
}
if (made.Tier is { } tier) tiers[made.FrameId] = tier;
return cadence.Due() ? checkpoint(made.Index + 1, manifest.Frames.Count) : ValueTask.CompletedTask;
}, cancellationToken))
// Under the thumbnail lease, as the thumbnail pass: image passes exclude each other only, ingest keeps committing
// meanwhile, and a Reorganize waits for the batch, so the proxies go to the folder the index has once the lease is
// held, never into one the sequence left, which writing them would create again. Between two batches the lease is let
// go for longer than a waiting writer sleeps between its tries, so another process's Reorganize, sequence deletion or
// pack compaction waits for one batch, not for the whole pass.
for (var next = 0; ;)
{
for (var i = 0; i < manifest.Frames.Count; i++)
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{sequence.Id:N}", _writer.Options.Owner, _writer.Options.LeaseWait,
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
{
cancellationToken.ThrowIfCancellationRequested();
var frame = manifest.Frames[i];
var path = folder.Proxy(frame.I);
var done = i < startFrame;
if (NeedsProxy(frame.Format))
var folder = await SequenceWriter.FolderAsync(_db, paths, sequence, cancellationToken).ConfigureAwait(false);
if (!SequenceFolders.Holds(folder, sequence.Id)) throw new InvalidOperationException(Loc.L("Errors.Archive.FolderMoved"));
var read = ManifestStore.ReadSequence(folder.ManifestPath);
// Photos added, removed or renumbered since the last batch: what the earlier batches made may not be theirs.
if (manifest is not null && !SameFrames(read.Frames, manifest.Frames, names: false)) complete = false;
manifest = read;
Directory.CreateDirectory(folder.Proxies);
var companions = await GprCompanions.FindAsync(_db, archive, read.Frames, cancellationToken).ConfigureAwait(false);
var batch = Stopwatch.StartNew();
await using (var work = new OrderedWork<Made>(ProxyParallelism(read.Frames, policy), made =>
{
switch (made.Outcome)
{
case ProxyOutcome.Built:
built++;
break;
case ProxyOutcome.Reused:
reused++;
break;
case ProxyOutcome.Waiting:
waiting++;
break;
case ProxyOutcome.Failed:
undecodable++;
complete = false;
break;
default:
undecodable++;
break;
}
if (made.Tier is { } tier) tiers[made.FrameId] = tier;
return cadence.Due() ? checkpoint(made.Index + 1, read.Frames.Count) : ValueTask.CompletedTask;
}, cancellationToken))
{
// Only a client or render node that decodes the original makes this proxy: a preview would make one the
// size of a thumbnail here. One left from a frame renumbered since goes, so it is asked for again, and so
// does one smaller than the policy's (made here from a preview by an earlier version).
var check = Check(path, frame.CapturedAt, frame.W, frame.H, policy).Check;
var usable = check is ProxyCheck.Current or ProxyCheck.Unverifiable;
if (check == ProxyCheck.Stale) Delete(path);
complete &= usable;
if (done) continue;
var outcome = usable ? ProxyOutcome.Reused
: (frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0 ? ProxyOutcome.Unreadable
: ProxyOutcome.Waiting;
await work.AddAsync(new Made(i, frame.Id, outcome, null)).ConfigureAwait(false);
continue;
// At least one frame per batch, so the pass always moves on.
for (var first = next; next < read.Frames.Count && (next == first || batch.Elapsed < ProxyBatch); next++)
{
cancellationToken.ThrowIfCancellationRequested();
var frame = read.Frames[next];
var path = folder.Proxy(frame.I);
var done = next < startFrame;
if (NeedsProxy(frame.Format))
{
// Only a client or render node that decodes the original makes this proxy: a preview would make one the
// size of a thumbnail here. One left from a frame renumbered since goes, so it is asked for again, and so
// does one smaller than the policy's (made here from a preview by an earlier version).
var check = Check(path, frame.CapturedAt, frame.W, frame.H, policy).Check;
var usable = check is ProxyCheck.Current or ProxyCheck.Unverifiable;
if (check == ProxyCheck.Stale) Delete(path);
complete &= usable;
if (done) continue;
var outcome = usable ? ProxyOutcome.Reused
: (frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0 ? ProxyOutcome.Unreadable
: ProxyOutcome.Waiting;
await work.AddAsync(new Made(next, frame.Id, outcome, null)).ConfigureAwait(false);
continue;
}
if (done)
{
// Made by the earlier run, unless the frame did not decode then.
complete &= ReadProxy(path, frame.CapturedAt).Check is ProxyCheck.Current or ProxyCheck.Unverifiable;
continue;
}
if (!force && ReadProxy(path, frame.CapturedAt).Check == ProxyCheck.Current)
{
reused++;
continue;
}
var index = next;
var companion = companions.GetValueOrDefault(frame.Id);
await work.AddAsync(ct =>
{
var (image, tier) = Render(folder, frame, companion, recordTier: true,
() => _renderer.Proxy(folder, frame, read.Camera, policy, ct, companion));
if (image is null) return new Made(index, frame.Id, ProxyOutcome.Failed, tier);
AtomicFile.WriteAllBytes(path, image.Jpeg);
Headers.TryRemove(path, out _);
return new Made(index, frame.Id, ProxyOutcome.Built, tier);
}).ConfigureAwait(false);
}
await work.CompleteAsync().ConfigureAwait(false);
}
if (done)
{
// Made by the earlier run, unless the frame did not decode then.
complete &= ReadProxy(path, frame.CapturedAt).Check is ProxyCheck.Current or ProxyCheck.Unverifiable;
continue;
}
if (!force && ReadProxy(path, frame.CapturedAt).Check == ProxyCheck.Current)
{
reused++;
continue;
}
var index = i;
var companion = companions.GetValueOrDefault(frame.Id);
await work.AddAsync(ct =>
{
var (image, tier) = Render(folder, frame, companion, recordTier: true,
() => _renderer.Proxy(folder, frame, manifest.Camera, policy, ct, companion));
if (image is null) return new Made(index, frame.Id, ProxyOutcome.Failed, tier);
AtomicFile.WriteAllBytes(path, image.Jpeg);
Headers.TryRemove(path, out _);
return new Made(index, frame.Id, ProxyOutcome.Built, tier);
}).ConfigureAwait(false);
if (next >= read.Frames.Count) break;
}
await work.CompleteAsync().ConfigureAwait(false);
await Task.Delay(BatchGap, cancellationToken).ConfigureAwait(false);
}
await _tiers.RecordAsync(archive, sequence, tiers, proxies: true, cancellationToken).ConfigureAwait(false);
await MarkAsync(archive, paths, sequence, manifest, JobKind.Proxies, SequenceStatus.ProxiesBuilt, complete, cancellationToken).ConfigureAwait(false);
return new ImagePassResult(built, reused, undecodable, waiting);
}
/// <summary>
/// How long a proxy pass holds the thumbnail lease for one batch of frames: a quarter of the lease wait, so a writer of
/// another process waiting for the lease meanwhile gets it well before it gives up (the frames the batch started finish
/// first).
/// </summary>
private TimeSpan ProxyBatch => _writer.Options.LeaseWait / 4;
/// <summary>Photos a thumbnail pass draws at once (<see cref="PassParallelism"/>): previews of the thumbnail's size serve it.</summary>
private int ThumbnailParallelism(IReadOnlyList<SidecarFrame> frames, ThumbnailPolicy policy) =>
PassParallelism(_writer.Options.Parallelism(), _writer.Options.MemoryBudget(), frames, policy.LongEdge, preferPreview: true, _writer.Options.Decoder);
@@ -626,9 +678,9 @@ public sealed class ArchiveImages
private async Task MarkAsync(Archive archive, ArchivePaths paths, Sequence sequence, SequenceManifest read, JobKind pass, SequenceStatus flag,
bool complete, CancellationToken cancellationToken)
{
var folder = paths.Sequence(sequence.Folder);
await using (await _writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
{
var folder = await SequenceWriter.FolderAsync(_db, paths, sequence, cancellationToken).ConfigureAwait(false);
var manifest = SequenceWriter.ReadLocked(folder, sequence.Id);
var built = complete && (SameFrames(manifest.Frames, read.Frames)
|| await _db.Jobs.IsQueuedAsync(pass, sequence.Id, cancellationToken).ConfigureAwait(false));
@@ -651,13 +703,15 @@ public sealed class ArchiveImages
/// removed, renumbered or replaced since have none of what the pass made. A hash learnt since (a verify hashing a
/// photo the scan adopted) changes nothing about the photo, and its thumbnail stays its own (<see cref="ThumbPack.IsFrom"/>).
/// </summary>
private static bool SameFrames(IReadOnlyList<SidecarFrame> current, IReadOnlyList<SidecarFrame> read)
/// <param name="names">Whether a file renamed since counts as a change (a pass's own batches: it does not, a proxy is
/// kept by frame index and a Reorganize renames files).</param>
private static bool SameFrames(IReadOnlyList<SidecarFrame> current, IReadOnlyList<SidecarFrame> read, bool names = true)
{
if (current.Count != read.Count) return false;
for (var i = 0; i < current.Count; i++)
{
var (now, then) = (current[i], read[i]);
if (now.Id != then.Id || now.I != then.I || now.File != then.File || now.Size != then.Size || now.CapturedAt != then.CapturedAt
if (now.Id != then.Id || now.I != then.I || (names && now.File != then.File) || now.Size != then.Size || now.CapturedAt != then.CapturedAt
|| (then.Sha256 is not null && !string.Equals(now.Sha256, then.Sha256, StringComparison.OrdinalIgnoreCase))) return false;
}
return true;