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
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:
1 parent
9aa818ed47
commit
7e4a3b481d
416 files changed
+15304
-1572
No files matched your search
@@ -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;
|
||||
|
||||
@@ -156,6 +156,10 @@ public sealed class ArchiveIndexer
|
||||
if (row.HeroFrameId is { } hero && !manifest.Frames.Any(f => f.Id == hero)) row = row with { HeroFrameId = null };
|
||||
await tx.Sequences.UpsertAsync(row with { Status = row.Status & ~clear }, cancellationToken).ConfigureAwait(false);
|
||||
await tx.Frames.SyncSequenceAsync(manifest.Id, SequenceMapping.ToFrames(manifest, sequence), cancellationToken).ConfigureAwait(false);
|
||||
// Found in another folder (a Reorganize of another index of the archive, or a folder moved by hand): the exports
|
||||
// inside it moved with it.
|
||||
if (existing is not null && existing.Folder != sequence.RelativeFolder)
|
||||
await RebaseRendersAsync(tx, archive, manifest.Id, existing.Folder, sequence.RelativeFolder, cancellationToken).ConfigureAwait(false);
|
||||
await tx.FrameRemovals.SyncSequenceAsync(manifest.Id, SequenceMapping.ToRemovals(manifest), cancellationToken).ConfigureAwait(false);
|
||||
foreach (var key in manifest.SessionKeys)
|
||||
await tx.Sequences.MapSessionKeyAsync(archive.Id, key, manifest.Id, cancellationToken).ConfigureAwait(false);
|
||||
@@ -181,6 +185,35 @@ public sealed class ArchiveIndexer
|
||||
return manifest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The render rows of the archive that follow a sequence's folder from <paramref name="from"/> to <paramref name="to"/>,
|
||||
/// in the caller's transaction (<see cref="Repositories.RenderRepository.RebaseFolderAsync"/>). An export is a file, or
|
||||
/// a folder for an image sequence. It is at its old path still when it is there, the new path is not the same one (on
|
||||
/// a file system that ignores case it is, when only the case changed) and the old folder holds no other sequence now: a
|
||||
/// file there is that sequence's, which moved into the folder since and brought an export of that name. The sequence's
|
||||
/// own exports inside the folder follow unless they are at the old path still and not at the new one: written there
|
||||
/// after the move by a writer that read the old folder, which created it again, so the row keeps naming where the export
|
||||
/// is. An export of its own missing from both places follows too. Another sequence's export follows only when it moved
|
||||
/// with the folder (at its new path and no longer at the old one), and an export of the sequence the old folder holds
|
||||
/// now never does: that one is in its own folder, whatever the moving sequence took along under the same name.
|
||||
/// </summary>
|
||||
internal static Task<int> RebaseRendersAsync(ChronosRepositories tx, Archive archive, Guid sequenceId, string from, string to,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
// The sequence the old folder holds now, when another one: read once, and only when a row asks.
|
||||
var holder = new Lazy<Guid?>(() => SequenceFolders.OtherSequence(paths.Sequence(from), sequenceId), LazyThreadSafetyMode.None);
|
||||
return tx.Renders.RebaseFolderAsync(archive.Id, sequenceId, from, to, (before, after, owner) =>
|
||||
{
|
||||
var own = owner == sequenceId;
|
||||
if (!own && owner == holder.Value) return false;
|
||||
var moved = Path.Exists(paths.FromRelative(after));
|
||||
var behind = !string.Equals(before, after, StringComparison.OrdinalIgnoreCase) && Path.Exists(paths.FromRelative(before))
|
||||
&& holder.Value is null;
|
||||
return own ? moved || !behind : moved && !behind;
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remembers the current stamps of a folder whose sidecar and index were just updated together, so the next
|
||||
/// incremental scan does not re-read what is already indexed.
|
||||
|
||||
@@ -217,12 +217,17 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A new folder for <paramref name="manifest"/>: the plan's folder or the archive's folder template, made unique.</summary>
|
||||
/// <summary>
|
||||
/// A new folder for <paramref name="manifest"/>: the plan's folder or the archive's folder template, made unique. The
|
||||
/// template sees the first frame in its new sequence, as Reorganize sees a sequence's first frame (<see cref="FrameNaming.Context(SidecarFrame, SequenceManifest, string?)"/>).
|
||||
/// </summary>
|
||||
private async Task<SequencePaths> ClaimNewFolderAsync(Archive archive, ArchivePaths paths, string? preferredFolder, StagedFrame first,
|
||||
SequenceManifest manifest, CancellationToken cancellationToken)
|
||||
{
|
||||
var captured = CaptureTime(first);
|
||||
var wanted = preferredFolder ?? PathTemplate.Parse(archive.FolderTemplate).ExpandFolder(Naming(first, captured, captured, 1, manifest.Title));
|
||||
var frame = SequenceFrames.FromMetadata(Guid.Empty, first.OriginalFileName, first.OriginalFileName, first.Size, first.Sha256, first.Metadata,
|
||||
first.ClientCapturedAt);
|
||||
var wanted = preferredFolder
|
||||
?? PathTemplate.Parse(archive.FolderTemplate).ExpandFolder(FrameNaming.Context(frame, manifest with { Frames = [frame] }, manifest.Title));
|
||||
if (wanted.Length == 0) wanted = "Sequence";
|
||||
var taken = (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false))
|
||||
.Select(l => l.Folder).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
@@ -287,9 +292,9 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
?? throw new InvalidOperationException($"Sequence {sequenceId} is not indexed.");
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
var sequence = paths.Sequence(row.Folder);
|
||||
await using (await _writer.LockAsync(paths, sequenceId, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var sequence = await SequenceWriter.FolderAsync(_db, paths, row, cancellationToken).ConfigureAwait(false);
|
||||
var manifest = SequenceWriter.ReadLocked(sequence, sequenceId);
|
||||
// Asked before this batch changes the folder: whether this index holds it as it is (ArchiveIndexer.InStepAsync), and
|
||||
// when it does not, whether photos were copied in or removed by hand since the last scan, which this batch's
|
||||
@@ -411,7 +416,11 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
return left.Count == 0 ? null : left;
|
||||
}
|
||||
|
||||
/// <summary>Final file names, in capture order: the plan's name or the template with <c>{n}</c> = index + 1, made unique.</summary>
|
||||
/// <summary>
|
||||
/// Final file names, in capture order: the plan's name, or the template with each frame in the sequence it joins
|
||||
/// (<see cref="FrameNaming.Context(SidecarFrame, SequenceManifest, string?)"/>: <c>{n}</c> = index + 1, the sequence's
|
||||
/// camera and lens), the context Reorganize names it with; made unique.
|
||||
/// </summary>
|
||||
private static Dictionary<Guid, SidecarFrame> Name(Archive archive, SequencePaths sequence, SequenceManifest manifest,
|
||||
List<(Pending Pending, SidecarFrame Frame)> accepted)
|
||||
{
|
||||
@@ -428,17 +437,14 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
foreach (var file in Directory.EnumerateFiles(onDisk)) taken.Add(directory + Path.GetFileName(file));
|
||||
}
|
||||
var template = PathTemplate.Parse(archive.FileTemplate);
|
||||
var start = merged.Frames.Count > 0 ? merged.Frames[0].CapturedAt : null;
|
||||
var names = new UniqueNames(taken);
|
||||
var named = new Dictionary<Guid, SidecarFrame>();
|
||||
foreach (var frame in merged.Frames)
|
||||
{
|
||||
if (!incoming.TryGetValue(frame.Id, out var entry)) continue;
|
||||
var staged = entry.Pending.Frame;
|
||||
var captured = frame.CapturedAt ?? DateTime.Now;
|
||||
var name = staged.PlannedName ?? template.ExpandFile(Naming(staged, captured, start ?? captured, frame.I + 1, manifest.Title));
|
||||
var file = directory + name;
|
||||
var stem = Path.GetFileNameWithoutExtension(name);
|
||||
for (var n = 2; !taken.Add(file); n++) file = string.Create(CultureInfo.InvariantCulture, $"{directory}{stem}_{n}{Path.GetExtension(name)}");
|
||||
var file = entry.Pending.Frame.PlannedName is { } planned
|
||||
? names.Claim(directory + planned)
|
||||
: FrameNaming.FileName(template, FrameNaming.Context(frame, merged, manifest.Title), names, directory);
|
||||
named[frame.Id] = entry.Frame with { File = file };
|
||||
}
|
||||
return named;
|
||||
@@ -534,28 +540,6 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
private static IngestResult Result(Guid sequenceId, SequencePaths sequence, SidecarFrame frame, bool duplicate) =>
|
||||
new(sequenceId, frame.Id, frame.I, sequence.ArchiveRelative(frame.File), duplicate);
|
||||
|
||||
private static DateTime CaptureTime(StagedFrame frame) =>
|
||||
frame.Metadata.TimestampSource is TimestampSource.FileSystem or TimestampSource.Unknown && frame.ClientCapturedAt is { } client
|
||||
? client
|
||||
: frame.Metadata.CapturedAt ?? frame.ClientCapturedAt ?? DateTime.Now;
|
||||
|
||||
private static NamingContext Naming(StagedFrame frame, DateTime captured, DateTime sessionStart, int number, string? title) => new()
|
||||
{
|
||||
CapturedAt = captured,
|
||||
SessionStart = sessionStart,
|
||||
Number = number,
|
||||
NumberInSession = number,
|
||||
CameraMake = frame.Metadata.Make,
|
||||
CameraModel = frame.Metadata.Model,
|
||||
Lens = frame.Metadata.LensModel,
|
||||
Iso = frame.Metadata.Iso,
|
||||
ExposureTime = frame.Metadata.ExposureTime,
|
||||
FNumber = frame.Metadata.FNumber,
|
||||
OriginalName = Path.GetFileNameWithoutExtension(frame.OriginalFileName),
|
||||
Extension = Path.GetExtension(frame.OriginalFileName).TrimStart('.'),
|
||||
Title = title,
|
||||
};
|
||||
|
||||
private sealed class CommitQueue
|
||||
{
|
||||
public SemaphoreSlim Gate { get; } = new(1, 1);
|
||||
|
||||
@@ -230,7 +230,13 @@ public sealed class ArchiveMaintenance
|
||||
await using (await _writer.LockAsync(paths, location.Id, cancellationToken).ConfigureAwait(false))
|
||||
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{location.Id:N}", _writer.Options.Owner, _writer.Options.LeaseWait,
|
||||
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
|
||||
ThumbPackWriter.Compact(sequence.ThumbsPackPath);
|
||||
{
|
||||
// Where the pack is now: a Reorganize may have moved the folder since the listing, and compacting a pack
|
||||
// that is not there would create it (and the folder) again.
|
||||
var pack = paths.Sequence((await _db.Sequences.GetAsync(location.Id, cancellationToken).ConfigureAwait(false))?.Folder ?? location.Folder)
|
||||
.ThumbsPackPath;
|
||||
if (File.Exists(pack)) ThumbPackWriter.Compact(pack);
|
||||
}
|
||||
}
|
||||
return compacted;
|
||||
}
|
||||
@@ -251,9 +257,9 @@ public sealed class ArchiveMaintenance
|
||||
if (await _db.Sequences.GetAsync(bySequence.Key, cancellationToken).ConfigureAwait(false) is not { } sequence) continue;
|
||||
var changes = bySequence.ToDictionary(x => x.Key, x => (Func<SidecarFrame, SidecarFrame>)(f =>
|
||||
f with { Flags = x.Set ? f.Flags | FrameFlags.Duplicate : f.Flags & ~FrameFlags.Duplicate }));
|
||||
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);
|
||||
// The scan stamps follow only when the index held the folder as it was: frames another process listed in the
|
||||
// sidecar meanwhile are still indexed by the next scan.
|
||||
var manifest = SequenceWriter.ReadLocked(folder, sequence.Id);
|
||||
|
||||
@@ -2,6 +2,7 @@ using System.Text.Json;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Naming;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
@@ -73,8 +74,8 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
|
||||
/// <summary>
|
||||
/// Handlers for scan, rebuild, verify, import, thumbs, proxies and maintenance jobs, the read-only duplicates and orphans
|
||||
/// reports, index backups and clean-ups (owner review 2, R10) and the emptying of the trash (R6); register them on the
|
||||
/// <see cref="JobEngine"/>.
|
||||
/// reports, index backups and clean-ups (owner review 2, R10), the emptying of the trash (R6) and Reorganize (R7,
|
||||
/// <see cref="JobKind.Move"/>); register them on the <see cref="JobEngine"/>.
|
||||
/// </summary>
|
||||
public IReadOnlyList<IJobHandler> CreateJobHandlers() =>
|
||||
[
|
||||
@@ -90,6 +91,7 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
new Housekeeping.BackupJobHandler(_db, _writer.Options.BackupDirectory),
|
||||
new Housekeeping.CleanupJobHandler(_db, CleanupSteps, TimeProvider.System),
|
||||
new EmptyTrashJobHandler(_db, Trash),
|
||||
new MoveJobHandler(_db, Renamer, _writer.Options.SequenceChanged),
|
||||
];
|
||||
|
||||
/// <summary>Makes <paramref name="root"/> a new, empty archive and indexes it.</summary>
|
||||
@@ -103,13 +105,14 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
/// becomes the folder's name; a longer one than <see cref="ArchiveSettings.MaxNameLength"/> is shortened.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">The folder already is an archive (open it instead).</exception>
|
||||
/// <exception cref="ArgumentException">A template or policy is invalid (<see cref="ArgumentException.ParamName"/> names it).</exception>
|
||||
/// <exception cref="ArgumentException">A template or policy is invalid (<see cref="ArgumentException.ParamName"/> names it;
|
||||
/// <see cref="TemplateRuleException"/> for a template that breaks a rule).</exception>
|
||||
public async Task<Archive> CreateAsync(string root, ArchiveSettings settings, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
var paths = new ArchivePaths(root);
|
||||
settings = WithUsableName(settings, paths);
|
||||
if (settings.Problem() is { } field) throw new ArgumentException($"The archive setting {field} is invalid.", field);
|
||||
settings.Validate();
|
||||
if (File.Exists(paths.ManifestPath)) throw new InvalidOperationException($"{paths.Root} already is a Chronos archive.");
|
||||
Directory.CreateDirectory(paths.MetaDirectory);
|
||||
var manifest = new ArchiveManifest
|
||||
@@ -127,7 +130,8 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
|
||||
/// <summary>
|
||||
/// Registers an existing archive (or relinks a moved one: same id, new root) and completes renames a crash
|
||||
/// interrupted. An offline archive is registered as it was last seen.
|
||||
/// interrupted (each sequence they change is told to <see cref="ArchiveServiceOptions.SequenceChanged"/>); one that
|
||||
/// cannot be completed yet is logged and waits for the next open. An offline archive is registered as it was last seen.
|
||||
/// </summary>
|
||||
public async Task<Archive> OpenAsync(string root, CancellationToken cancellationToken = default)
|
||||
{
|
||||
@@ -138,9 +142,9 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
{
|
||||
await Renamer.ResumePendingAsync(archive, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or NewerFormatException)
|
||||
{
|
||||
// The journal stays; the next open tries again. The archive itself is usable meanwhile.
|
||||
// The journal stays; the next open tries again. The archive itself is usable meanwhile (a server starts all the same).
|
||||
Log.Warning("archive", $"Resuming an interrupted rename in {paths.Root} failed", ex);
|
||||
}
|
||||
return archive;
|
||||
@@ -209,9 +213,12 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
/// a client sharing the archive never undo each other's change; the file is replaced atomically. Folders and files
|
||||
/// already in the archive keep their names: templates and policies apply to the next imports, proxies and thumbnails.
|
||||
/// A blank or overlong name in the file (archives made at a drive root, or before names were checked) is made usable
|
||||
/// as <see cref="CreateAsync(string, ArchiveSettings, CancellationToken)"/> does, instead of failing every edit.
|
||||
/// as <see cref="CreateAsync(string, ArchiveSettings, CancellationToken)"/> does, instead of failing every edit. Likewise
|
||||
/// a template the file holds that breaks a rule of the archive's templates (saved before the rules existed) stays as it
|
||||
/// is through an edit of anything else: only a template the edit gives is held to them (<see cref="ArchiveSettings.Problem"/>).
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">An edited setting is invalid (<see cref="ArgumentException.ParamName"/> names it).</exception>
|
||||
/// <exception cref="ArgumentException">An edited setting is invalid (<see cref="ArgumentException.ParamName"/> names it;
|
||||
/// <see cref="TemplateRuleException"/> for a template that breaks a rule).</exception>
|
||||
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only.</exception>
|
||||
/// <exception cref="LeaseUnavailableException">Another process kept the archive's settings busy.</exception>
|
||||
public async Task<Archive> UpdateSettingsAsync(Guid archiveId, Func<ArchiveSettings, ArchiveSettings> edit, CancellationToken cancellationToken = default)
|
||||
@@ -228,7 +235,8 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
if (current.Id != archive.Id) throw new InvalidDataException($"{paths.ManifestPath} belongs to archive {current.Id}, not {archive.Id}.");
|
||||
// The name read is made usable before the edit sees it; a name the edit sets is checked as given.
|
||||
var settings = edit(WithUsableName(ArchiveSettings.Of(current), paths));
|
||||
if (settings.Problem() is { } field) throw new ArgumentException($"The archive setting {field} is invalid.", field);
|
||||
// A template the file already holds stays as it is, rules or not: only one the edit gives is held to them.
|
||||
settings.Validate(current.LayoutTemplates);
|
||||
var manifest = current with
|
||||
{
|
||||
Name = settings.Name.Trim(),
|
||||
@@ -267,9 +275,9 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
var (archive, sequence) = await LoadSequenceAsync(sequenceId, cancellationToken).ConfigureAwait(false);
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
var folder = paths.Sequence(sequence.Folder);
|
||||
await using (await _writer.LockAsync(paths, sequenceId, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var folder = await SequenceWriter.FolderAsync(_db, paths, sequence, cancellationToken).ConfigureAwait(false);
|
||||
var manifest = SequenceWriter.ReadLocked(folder, sequenceId);
|
||||
var inStep = await Indexer.InStepAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false);
|
||||
for (var attempt = 1; ; attempt++)
|
||||
@@ -303,6 +311,25 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs <paramref name="write"/> under the lease of <paramref name="sequence"/>, with its index row read under it (null
|
||||
/// when the sequence left the index). A Reorganize moves a folder, its row and the paths of the renders inside it under
|
||||
/// that lease, so a writer that files into the folder and records what it filed (a render a client or render node sends)
|
||||
/// does both where the sequence is then, never in a folder it left, and what it records follows a later move.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">The sequence's archive is not in the index.</exception>
|
||||
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only.</exception>
|
||||
/// <exception cref="LeaseUnavailableException">Another writer held the sequence for longer than the lease wait.</exception>
|
||||
public async Task<T> UnderLeaseAsync<T>(Sequence sequence, Func<Sequence?, Task<T>> write, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sequence);
|
||||
ArgumentNullException.ThrowIfNull(write);
|
||||
var paths = new ArchivePaths((await LoadArchiveAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false)).RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
await using (await _writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
|
||||
return await write(await _db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<DuplicateGroup>> FindDuplicatesAsync(Guid archiveId, CancellationToken cancellationToken = default) =>
|
||||
Maintenance.FindDuplicatesAsync(archiveId, cancellationToken);
|
||||
|
||||
@@ -351,7 +378,23 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
await Renamer.PlanAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), sequenceIds, folderTemplate, titleTemplate,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
public async Task ApplyRenameAsync(RenamePlan plan, IProgress<int>? progress = null, CancellationToken cancellationToken = default) =>
|
||||
/// <summary>
|
||||
/// The dry run of a Reorganize (owner review 2, R7): <paramref name="templates"/> over <paramref name="sequenceIds"/>, or
|
||||
/// over every sequence of the archive (by folder) when null. Apply it in a job (<see cref="ArchiveJobs.Reorganize"/>) or
|
||||
/// with <see cref="ApplyRenameAsync"/>.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">The archive is unknown, or a sequence is not in it.</exception>
|
||||
/// <exception cref="NestedRenameException">A new folder would lie inside a sequence's folder.</exception>
|
||||
public async Task<RenamePlan> PlanReorganizeAsync(Guid archiveId, IReadOnlyList<Guid>? sequenceIds, RenameTemplates templates,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(templates);
|
||||
var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false);
|
||||
var ids = sequenceIds ?? [.. (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false)).Select(l => l.Id)];
|
||||
return await Renamer.PlanAsync(archive, ids, templates, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task<RenameResult> ApplyRenameAsync(RenamePlan plan, IProgress<int>? progress = null, CancellationToken cancellationToken = default) =>
|
||||
await Renamer.ApplyAsync(await LoadArchiveAsync(plan.ArchiveId, cancellationToken).ConfigureAwait(false), plan, progress, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
@@ -497,17 +540,62 @@ public sealed record ArchiveSettings(string Name, LayoutTemplates Templates, Pro
|
||||
&& Proxies.LongEdge == archive.ProxyLongEdge;
|
||||
}
|
||||
|
||||
/// <summary>The first invalid field by its API name (<c>name</c>, <c>folderTemplate</c>, <c>fileTemplate</c>,
|
||||
/// <c>proxyLongEdge</c>, <c>thumbnailLongEdge</c>); null when every field is valid.</summary>
|
||||
public string? Problem()
|
||||
/// <summary>
|
||||
/// The first invalid field by its API name (<c>name</c>, <c>folderTemplate</c>, <c>fileTemplate</c>,
|
||||
/// <c>proxyLongEdge</c>, <c>thumbnailLongEdge</c>); null when every field is valid. A template has to be usable
|
||||
/// (<see cref="RenameTemplates.Check"/>), and one given anew is held to the rules it meets wherever it is typed
|
||||
/// (<see cref="TemplateRules"/>): a folder template may not write a level scans never enter, and a file template must
|
||||
/// keep the photo's extension, tell a session's photos apart and hold no slash.
|
||||
/// </summary>
|
||||
/// <param name="stored">The templates archive.json holds before an edit: one the edit leaves as it is, saved before the
|
||||
/// rules existed (0.1.0-rc.5 and earlier), never fails an edit of another setting. Null holds both to every rule (a new
|
||||
/// archive).</param>
|
||||
public string? Problem(LayoutTemplates? stored = null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(Name) || Name.Trim().Length > MaxNameLength) return "name";
|
||||
if (string.IsNullOrWhiteSpace(Templates.Folder) || !PathTemplate.Parse(Templates.Folder).IsValid) return "folderTemplate";
|
||||
if (string.IsNullOrWhiteSpace(Templates.File) || !PathTemplate.Parse(Templates.File).IsValid) return "fileTemplate";
|
||||
if (CheckTemplates(stored) is { } template) return template.Field;
|
||||
if (!ProxyPolicy.IsValidLongEdge(Proxies.LongEdge) || Proxies.Quality is < 1 or > 100) return "proxyLongEdge";
|
||||
if (!ThumbnailPolicy.IsValidLongEdge(Thumbnails.LongEdge) || Thumbnails.Quality is < 1 or > 100) return "thumbnailLongEdge";
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The first template that cannot be used (<see cref="Problem"/>), with the rule it breaks
|
||||
/// (<see cref="TemplateProblem.Rule"/>); null when both can. A rule broken by a template <paramref name="stored"/>
|
||||
/// already holds does not count.
|
||||
/// </summary>
|
||||
public TemplateProblem? CheckTemplates(LayoutTemplates? stored = null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(Templates.Folder)) return new TemplateProblem("folderTemplate", null);
|
||||
if (string.IsNullOrWhiteSpace(Templates.File)) return new TemplateProblem("fileTemplate", null);
|
||||
static TemplateProblem? Given(RenameTemplates template, bool kept) => template.Check() is { } problem && (problem.Rule is null || !kept) ? problem : null;
|
||||
return Given(new RenameTemplates(Folder: Templates.Folder), Templates.Folder == stored?.Folder)
|
||||
?? Given(new RenameTemplates(File: Templates.File), Templates.File == stored?.File);
|
||||
}
|
||||
|
||||
/// <summary>Refuses these settings when a field is invalid (<see cref="Problem"/>).</summary>
|
||||
/// <exception cref="TemplateRuleException">A template breaks a rule of the archive's templates.</exception>
|
||||
/// <exception cref="ArgumentException">Another field is invalid (<see cref="ArgumentException.ParamName"/> names it).</exception>
|
||||
internal void Validate(LayoutTemplates? stored = null)
|
||||
{
|
||||
if (Problem(stored) is not { } field) return;
|
||||
if (CheckTemplates(stored) is { Rule: { } rule } template && template.Field == field) throw new TemplateRuleException(field, rule);
|
||||
throw new ArgumentException($"The archive setting {field} is invalid.", field);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An archive setting's template breaks a rule of the archive's templates (<see cref="TemplateRules"/>): the message says
|
||||
/// which in one sentence (<c>Errors.Template.<Rule></c>, in the language of the moment it was refused), and
|
||||
/// <see cref="ParamName"/> names the template by its API name (<c>folderTemplate</c>, <c>fileTemplate</c>).
|
||||
/// </summary>
|
||||
public sealed class TemplateRuleException(string field, string rule) : ArgumentException(Loc.L("Errors.Template." + rule))
|
||||
{
|
||||
// Not the base's: its message would end in "(Parameter '…')".
|
||||
public override string? ParamName { get; } = field;
|
||||
|
||||
/// <summary>The rule broken (<see cref="TemplateProblem.Rule"/>).</summary>
|
||||
public string Rule { get; } = rule;
|
||||
}
|
||||
|
||||
/// <summary>Builds the archive jobs; enqueue with <see cref="EnqueueAsync"/>.</summary>
|
||||
@@ -567,6 +655,24 @@ public static class ArchiveJobs
|
||||
JobPriority.User);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Move"/>: applies the Reorganize <paramref name="plan"/> (the dry run of <paramref name="templates"/>,
|
||||
/// <see cref="ArchiveService.PlanReorganizeAsync"/>) as confirmed, refused when the archive changed since
|
||||
/// (<see cref="MoveJobParameters"/>; owner review 2, R7).
|
||||
/// </summary>
|
||||
public static ArchiveJobRequest Reorganize(Archive archive, RenamePlan plan, RenameTemplates templates)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
ArgumentNullException.ThrowIfNull(templates);
|
||||
// The sequences that have a step, in the order the plan was made for: the others change nothing, now or when planned again.
|
||||
var steps = plan.Steps.Select(s => s.SequenceId).ToHashSet();
|
||||
var sequences = plan.Subjects.Where(steps.Contains).Select(id => new MoveSequence(id)).ToList();
|
||||
return new(JobKind.Move, [archive.Id], archive.Name,
|
||||
Json(new MoveJobParameters(templates.Folder, templates.File, templates.Title, sequences, plan.Fingerprint()), ArchiveJobJson.Default.MoveJobParameters),
|
||||
JobPriority.User);
|
||||
}
|
||||
|
||||
public static Task<Job> EnqueueAsync(this JobEngine engine, ArchiveJobRequest request, Guid? createdBy = null, CancellationToken cancellationToken = default) =>
|
||||
engine.EnqueueAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority, createdBy, cancellationToken);
|
||||
|
||||
|
||||
@@ -112,9 +112,11 @@ public sealed class ArchiveVerifier
|
||||
private async Task FlushAsync(Archive archive, ArchivePaths paths, Sequence target, List<PendingCheck> pending, CancellationToken cancellationToken)
|
||||
{
|
||||
if (pending.Count == 0) return;
|
||||
var sequence = paths.Sequence(target.Folder);
|
||||
await using (await _writer.LockAsync(paths, target.Id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
// Where the sequence is now (a Reorganize may have moved it). A folder move keeps each file's size and time, so a
|
||||
// check made at the old place still applies; one that found a file missing while it moved does not (StillApplies).
|
||||
var sequence = await SequenceWriter.FolderAsync(_db, paths, target, cancellationToken).ConfigureAwait(false);
|
||||
var manifest = SequenceWriter.ReadLocked(sequence, target.Id);
|
||||
var current = manifest.Frames.ToDictionary(f => f.Id);
|
||||
var found = pending.Where(p => current.TryGetValue(p.Check.Frame.Id, out var now) && StillApplies(sequence, p, now)).Select(p => p.Check).ToList();
|
||||
@@ -164,9 +166,9 @@ public sealed class ArchiveVerifier
|
||||
/// </summary>
|
||||
private async Task StampAsync(Archive archive, ArchivePaths paths, Sequence target, CancellationToken cancellationToken)
|
||||
{
|
||||
var sequence = paths.Sequence(target.Folder);
|
||||
await using (await _writer.LockAsync(paths, target.Id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var sequence = await SequenceWriter.FolderAsync(_db, paths, target, cancellationToken).ConfigureAwait(false);
|
||||
var m = SequenceWriter.ReadLocked(sequence, target.Id);
|
||||
var inStep = await _indexer.InStepAsync(archive, sequence, m, cancellationToken).ConfigureAwait(false);
|
||||
var clean = m.Frames.All(f => (f.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) == 0);
|
||||
|
||||
@@ -79,9 +79,9 @@ internal sealed class FrameTiers(ChronosDatabase db, SequenceWriter writer, Arch
|
||||
if (tiers.Count == 0 && !proxies) return [];
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
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 m = SequenceWriter.ReadLocked(folder, sequence.Id);
|
||||
var changed = new List<SidecarFrame>();
|
||||
var gained = false;
|
||||
|
||||
@@ -150,13 +150,13 @@ public sealed partial class FrameTrash
|
||||
private async Task<(PhotoRestoreResult, List<Stay>)> IntoSequenceAsync(Archive archive, ArchivePaths paths, Sequence sequence, string recordPath,
|
||||
string entryFolder, string lease, List<TrashedPhoto> intact, CancellationToken cancellationToken)
|
||||
{
|
||||
var folder = paths.Sequence(sequence.Folder);
|
||||
var left = new List<Stay>();
|
||||
int restored;
|
||||
SequenceManifest updated;
|
||||
var indexed = true;
|
||||
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, lease);
|
||||
// A restore of another entry, busy now, is not settled yet: its journal is not written over.
|
||||
EnsureSettled(folder);
|
||||
@@ -176,7 +176,7 @@ public sealed partial class FrameTrash
|
||||
continue;
|
||||
}
|
||||
var original = photo.Files[0];
|
||||
var tails = photo.Files.Skip(1).Select(c => CompanionTail(c.From, original.From)).ToList();
|
||||
var tails = photo.Files.Skip(1).Select(c => FrameCompanions.Tail(c.From, original.From)).ToList();
|
||||
var file = FreeName(folder, original.From, tails, taken);
|
||||
var stem = file[..^Path.GetExtension(file).Length];
|
||||
taken.Add(file);
|
||||
@@ -417,7 +417,7 @@ public sealed partial class FrameTrash
|
||||
if (folder is null && sequenceId is { } known && await _db.Sequences.GetAsync(known, CancellationToken.None).ConfigureAwait(false) is { } row)
|
||||
folder = paths.Sequence(row.Folder);
|
||||
var original = photo.Files[0];
|
||||
var tails = photo.Files.Skip(1).Select(c => CompanionTail(c.From, original.From)).ToList();
|
||||
var tails = photo.Files.Skip(1).Select(c => FrameCompanions.Tail(c.From, original.From)).ToList();
|
||||
var planned = FreeName(folder, ArchiveLayout.OriginalsFolder + "/" + Path.GetFileName(original.From), tails, names);
|
||||
var inEntry = Path.Combine(entryFolder, original.Path);
|
||||
var path = Path.Combine(staging, original.Path);
|
||||
@@ -475,7 +475,7 @@ public sealed partial class FrameTrash
|
||||
names.Add(ArchiveLayout.OriginalsFolder + "/" + Path.GetFileName(placed));
|
||||
foreach (var companion in photo.Files.Skip(1))
|
||||
{
|
||||
var beside = stem + CompanionTail(companion.From, original.From);
|
||||
var beside = stem + FrameCompanions.Tail(companion.From, original.From);
|
||||
names.Add(ArchiveLayout.OriginalsFolder + "/" + Path.GetFileName(beside));
|
||||
try
|
||||
{
|
||||
@@ -563,14 +563,6 @@ public sealed partial class FrameTrash
|
||||
return all.Count > 0 ? all : null;
|
||||
}
|
||||
|
||||
/// <summary>What a companion's name adds to its photo's stem (<c>.xmp</c>, <c>.CR2.xmp</c>).</summary>
|
||||
private static string CompanionTail(string companion, string photo)
|
||||
{
|
||||
var stem = Path.GetFileNameWithoutExtension(Path.GetFileName(photo));
|
||||
var name = Path.GetFileName(companion);
|
||||
return name.StartsWith(stem, StringComparison.OrdinalIgnoreCase) ? name[stem.Length..] : Path.GetExtension(name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="file"/> when it and its companions' names (<paramref name="tails"/> after its stem) are free in
|
||||
/// <paramref name="taken"/> and on disk in <paramref name="folder"/> (none yet: in <paramref name="taken"/> only), else
|
||||
|
||||
@@ -229,6 +229,9 @@ public sealed partial class FrameTrash
|
||||
bool indexed;
|
||||
await using (await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
// A Reorganize moves the folder under this lease: moved since the plan, the plan names other paths.
|
||||
if ((await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false))?.Folder != revised.Sequence.Folder)
|
||||
throw new StaleDeletePlanException(id);
|
||||
var manifest = SequenceWriter.ReadLocked(folder, id);
|
||||
var plannedPaths = plan.Frames.ToDictionary(f => f.Id, f => f.RelativePath);
|
||||
var planned = plannedPaths.Keys.ToHashSet();
|
||||
@@ -347,7 +350,7 @@ public sealed partial class FrameTrash
|
||||
var used = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var claimed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var keptStems = kept.Select(f => Stem(f.File)).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var companions = new CompanionIndex(folder);
|
||||
var companions = new FrameCompanions.Index(folder);
|
||||
var photos = new List<TrashedPhoto>(removed.Count);
|
||||
foreach (var frame in removed)
|
||||
{
|
||||
@@ -431,35 +434,6 @@ public sealed partial class FrameTrash
|
||||
return Convert.ToHexStringLower(hash.GetHashAndReset());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The XMP files of a sequence's photo directories, each directory listed once (a deletion of thousands of photos does
|
||||
/// not list it again for each) and case-insensitively on every system (<c>IMG_0001.XMP</c> too).
|
||||
/// </summary>
|
||||
private sealed class CompanionIndex(SequencePaths folder)
|
||||
{
|
||||
private static readonly EnumerationOptions Listing = new() { MatchCasing = MatchCasing.CaseInsensitive, AttributesToSkip = 0 };
|
||||
private readonly Dictionary<string, ILookup<string, string>> _directories = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The XMP files beside a photo that name it (<c>stem.xmp</c> or <c>file.xmp</c>), relative to the sequence folder.</summary>
|
||||
public IEnumerable<string> Of(string file)
|
||||
{
|
||||
var prefix = file.Contains('/') ? file[..(file.LastIndexOf('/') + 1)] : string.Empty;
|
||||
if (!_directories.TryGetValue(prefix, out var named))
|
||||
{
|
||||
var directory = Path.GetDirectoryName(folder.File(file))!;
|
||||
named = (System.IO.Directory.Exists(directory) ? System.IO.Directory.EnumerateFiles(directory, "*.xmp", Listing) : [])
|
||||
.Select(p => Path.GetFileName(p))
|
||||
.Where(n => Path.GetExtension(n).Equals(".xmp", StringComparison.OrdinalIgnoreCase))
|
||||
.ToLookup(n => Path.GetFileNameWithoutExtension(n), StringComparer.OrdinalIgnoreCase);
|
||||
_directories[prefix] = named;
|
||||
}
|
||||
var name = Path.GetFileName(file);
|
||||
var stem = Path.GetFileNameWithoutExtension(name);
|
||||
var matches = stem.Equals(name, StringComparison.OrdinalIgnoreCase) ? named[stem] : named[stem].Concat(named[name]);
|
||||
return matches.Select(n => prefix + n);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A photo's stem with its folder (<c>originals/IMG_0001</c>): its companions share it.</summary>
|
||||
private static string Stem(string file)
|
||||
{
|
||||
@@ -610,8 +584,9 @@ public sealed partial class FrameTrash
|
||||
/// Moves the thumbnails of the frames whose index changed to their new index in <c>thumbs.pack</c> (BRIEF §8.5: the pack
|
||||
/// is keyed by frame index) and drops those of the frames removed, as <see cref="ShiftProxies"/> does for proxies, so the
|
||||
/// thumbnail pass queued afterwards reuses them instead of drawing the rest of the sequence again. Only the pack's index
|
||||
/// is rewritten. A thumbnail writer holding the pack meanwhile (its lease) leaves it as it is, and so does a failure
|
||||
/// (logged): each thumbnail carries its original's fingerprint, so one in the wrong place is drawn again.
|
||||
/// is rewritten. An image pass holding the thumbnail lease meanwhile (a thumbnail pass, or a batch of a proxy pass)
|
||||
/// leaves the pack as it is, and so does a failure (logged): each thumbnail carries its original's fingerprint, so one
|
||||
/// in the wrong place is drawn again.
|
||||
/// </summary>
|
||||
private void ShiftThumbnails(ArchivePaths paths, SequencePaths folder, Guid sequenceId, IReadOnlyList<SidecarFrame> before,
|
||||
IReadOnlyList<SidecarFrame> after)
|
||||
@@ -624,7 +599,7 @@ public sealed partial class FrameTrash
|
||||
using var lease = LeaseFile.TryAcquire(paths.LocksDirectory, $"thumbs-{sequenceId:N}", _writer.Options.Owner, _writer.Options.LeaseDuration);
|
||||
if (lease is null)
|
||||
{
|
||||
Log.Info("archive", $"Thumbnails of {folder.RelativeFolder} are being written; the thumbnail pass draws those that moved again");
|
||||
Log.Info("archive", $"An image pass holds the thumbnails of {folder.RelativeFolder}; the thumbnail pass draws those that moved again");
|
||||
return;
|
||||
}
|
||||
using var pack = ThumbPackWriter.Open(folder.ThumbsPackPath);
|
||||
|
||||
@@ -40,6 +40,17 @@ public sealed record EmptyTrashParameters(IReadOnlyList<EmptyTrashItem> Entries,
|
||||
/// <summary>One entry of a confirmed emptying: its name and fingerprint when it was planned.</summary>
|
||||
public sealed record EmptyTrashItem(string Name, string Fingerprint);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Move"/> (Reorganize, owner review 2, R7): target = the archive; the templates (null keeps that part),
|
||||
/// the sequences the confirmed plan changes in the order it was made for, and the plan's fingerprint
|
||||
/// (<see cref="Core.Archiving.RenamePlan.Fingerprint"/>, which pins every file rename by its digest). No file list: the job
|
||||
/// plans again and refuses when the plan is no longer the one confirmed.
|
||||
/// </summary>
|
||||
public sealed record MoveJobParameters(string? FolderTemplate, string? FileTemplate, string? TitleTemplate, IReadOnlyList<MoveSequence> Sequences, string Fingerprint);
|
||||
|
||||
/// <summary>A sequence of a <see cref="MoveJobParameters"/> (a job queued by an earlier build also names a frames version, which is ignored).</summary>
|
||||
public sealed record MoveSequence(Guid Id);
|
||||
|
||||
/// <summary>A job ready to enqueue.</summary>
|
||||
public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets, string? Label, string? ParametersJson, JobPriority Priority);
|
||||
|
||||
@@ -52,6 +63,7 @@ public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets
|
||||
[JsonSerializable(typeof(BackupParameters))]
|
||||
[JsonSerializable(typeof(CleanupParameters))]
|
||||
[JsonSerializable(typeof(EmptyTrashParameters))]
|
||||
[JsonSerializable(typeof(MoveJobParameters))]
|
||||
[JsonSerializable(typeof(CardProfile))]
|
||||
internal sealed partial class ArchiveJobJson : JsonSerializerContext
|
||||
{
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
|
||||
namespace Chronos.Data.Archiving.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Move"/>: a Reorganize (owner review 2, R7; BRIEF §12.5) of existing sequences with new folder, file
|
||||
/// and title templates (<see cref="MoveJobParameters"/>). The job plans again from the templates and applies the plan only
|
||||
/// when it is still the one confirmed (its fingerprint, which pins every file rename; <see cref="StaleRenamePlanException"/>
|
||||
/// otherwise, nothing changed; a sequence of it gone since is named in the log), through <see cref="MassRenamer"/>, whose
|
||||
/// journal makes every step resumable. Progress counts the plan's steps (sequences); checkpoint: <c>plan:<id></c> once
|
||||
/// the plan's journal is written, <c>applied</c> when the job fails once the plan is over (given up, or completed with
|
||||
/// sequences kept). Paused, cancelled or failed, the job stops between two sequences and holds the plan
|
||||
/// (<see cref="MassRenamer.Hold"/>), which an archive open then leaves to it (completing only file renames a step left
|
||||
/// half-way); resumed or retried, it completes the rest when it still fits. A plan whose journal is gone completed
|
||||
/// meanwhile (at an archive open), unless the archive cannot be reached: then no journal tells nothing, and the job fails
|
||||
/// as the archive does, keeping its checkpoint (so does a job that fails while the archive is offline and its plan's
|
||||
/// journal cannot be found). A job retried once its plan is over plans again, and applies only a plan that is still
|
||||
/// the one confirmed. Sequences left as they were, or that kept their title or file names, because they changed after
|
||||
/// the plan (one still receiving photos keeps its file names, and its title too when the templates now give it another
|
||||
/// folder or title, its folder then moving only before an interruption or with a folder around it), a newer Chronos
|
||||
/// wrote their sidecar, a photo was in use or its new name taken, or the folder around them stayed, are logged and fail
|
||||
/// the job at the end, after the others changed. Each sequence changed is told to
|
||||
/// <see cref="ArchiveServiceOptions.SequenceChanged"/> (<see cref="Change"/>)
|
||||
/// once its step is journaled, by this run or by an archive open that completed a plan an interruption left; those of a
|
||||
/// step that failed half-way (its folder moved, then a sidecar could not be read) are told at once. The log counts the
|
||||
/// whole plan, over every run of the job.
|
||||
/// </summary>
|
||||
internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Func<Guid, string, CancellationToken, Task>? sequenceChanged) : IJobHandler
|
||||
{
|
||||
/// <summary>The change a Reorganize tells about a sequence (a server's <c>sequenceChanged</c> event).</summary>
|
||||
public const string Change = MassRenamer.Change;
|
||||
|
||||
private const string Prefix = "plan:";
|
||||
|
||||
/// <summary>The checkpoint of a failed job whose plan is over (completed or given up): a retry plans again.</summary>
|
||||
private const string Applied = "applied";
|
||||
|
||||
public JobKind Kind => JobKind.Move;
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
{
|
||||
var archive = await JobArchive.LoadAsync(db, context.Job, context.Cancellation).ConfigureAwait(false);
|
||||
var parameters = ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.MoveJobParameters, new MoveJobParameters(null, null, null, [], string.Empty));
|
||||
if (parameters.Fingerprint.Length == 0) throw new InvalidOperationException($"Move job {context.Job.Id} has no confirmed plan.");
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var planId = PlanOf(context.Checkpoint);
|
||||
RenamePlan plan;
|
||||
RenameResult? result;
|
||||
try
|
||||
{
|
||||
if (planId is { } resumed)
|
||||
{
|
||||
var journal = RenameJournal.Read(paths, resumed);
|
||||
if (journal is null || await ResumeAsync(context, archive, journal).ConfigureAwait(false) is not { } done)
|
||||
{
|
||||
// No journal on an archive that cannot be reached tells nothing: the job fails as the archive does, and
|
||||
// keeps its checkpoint for a retry.
|
||||
if (ArchiveVolume.Probe(paths) == ArchiveAvailability.Offline) throw new ArchiveOfflineException(paths.Root, ArchiveAvailability.Offline);
|
||||
context.Log(Loc.L("Archive.Log.ReorganizedEarlier"));
|
||||
await context.ReportAsync(context.Total, context.Total).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
(plan, result) = (journal.Plan, done);
|
||||
}
|
||||
else
|
||||
{
|
||||
plan = await renamer.PlanAsync(archive, await PresentAsync(context, archive, parameters).ConfigureAwait(false),
|
||||
new RenameTemplates(parameters.FolderTemplate, parameters.FileTemplate, parameters.TitleTemplate), context.Cancellation).ConfigureAwait(false);
|
||||
if (!IsConfirmed(plan, parameters)) throw new StaleRenamePlanException(Guid.Empty);
|
||||
var total = Steps(plan);
|
||||
await context.ReportAsync(0, total).ConfigureAwait(false);
|
||||
result = await renamer.ApplyAsync(archive, plan, p =>
|
||||
{
|
||||
planId = p.Id;
|
||||
return context.CheckpointAsync(Checkpoint(p.Id), 0, total);
|
||||
}, (n, changed) => StepDoneAsync(context, plan.Id, n, total, changed), context.Cancellation).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (planId is { } id && context.Cancellation.IsCancellationRequested)
|
||||
{
|
||||
// Paused or cancelled by a user, not a yield to another job or the host stopping: the rest waits for this job.
|
||||
if (await db.Jobs.GetAsync(context.Job.Id, CancellationToken.None).ConfigureAwait(false) is { State: JobState.Paused or JobState.Cancelled }
|
||||
&& MassRenamer.Hold(archive, id))
|
||||
Log.Info("archive", $"Reorganize {id} held by its job {context.Job.Id}");
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (planId is { } id && !(ex is OperationCanceledException && context.Cancellation.IsCancellationRequested))
|
||||
{
|
||||
// Failed (a sequence changed, busy, or a folder that could not move): the rest waits for this job's retry, never
|
||||
// for an archive open. A plan given up has no rest: a retry plans again.
|
||||
if (!HoldFailed(context, archive, id)) await context.CheckpointAsync(Applied, context.Done, context.Total).ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
LogDone(context, plan, result);
|
||||
var kept = result.Dropped.Count + result.FilesKept.Count + result.TitlesKept.Count;
|
||||
var error = kept > 0 ? Loc.Plural("Archive.Error.ReorganizeKept", kept)
|
||||
: result.Newer.Count > 0 ? Loc.Plural("Archive.Error.ReorganizeNewer", result.Newer.Count)
|
||||
: result.FilesBusy.Count > 0 ? Loc.Plural("Archive.Error.ReorganizeBusy", result.FilesBusy.Count)
|
||||
: null;
|
||||
if (error is null) return;
|
||||
// The plan is over: a retry plans again instead of taking it for one an archive open completed.
|
||||
await context.CheckpointAsync(Applied, context.Total, context.Total).ConfigureAwait(false);
|
||||
throw new InvalidOperationException(error);
|
||||
}
|
||||
|
||||
/// <summary>Completes a plan this job started; null when its journal went meanwhile (completed at an archive open).</summary>
|
||||
private async Task<RenameResult?> ResumeAsync(JobContext context, Archive archive, RenameJournal journal)
|
||||
{
|
||||
var total = Steps(journal.Plan);
|
||||
await context.ReportAsync(journal.Completed.Count, total).ConfigureAwait(false);
|
||||
return await renamer.ResumeAsync(archive, journal.Plan.Id, (n, changed) => StepDoneAsync(context, journal.Plan.Id, n, total, changed), context.Cancellation)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sequences of the confirmed plan the index still has in the archive; each one gone since (deleted while the job
|
||||
/// waited in the queue) is named in the log, and the plan made without it is then not the one confirmed.
|
||||
/// </summary>
|
||||
private async Task<IReadOnlyList<Guid>> PresentAsync(JobContext context, Archive archive, MoveJobParameters parameters)
|
||||
{
|
||||
var present = new List<Guid>(parameters.Sequences.Count);
|
||||
foreach (var sequence in parameters.Sequences)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(sequence.Id, context.Cancellation).ConfigureAwait(false) is { } row && row.ArchiveId == archive.Id) present.Add(sequence.Id);
|
||||
else context.Log(Loc.L("Archive.Log.SequenceMissing", sequence.Id));
|
||||
}
|
||||
return present;
|
||||
}
|
||||
|
||||
/// <summary>After each step: the checkpoint, then the sequences that step changed are told.</summary>
|
||||
private async ValueTask StepDoneAsync(JobContext context, Guid planId, int done, int total, IReadOnlyList<Guid> changed)
|
||||
{
|
||||
await context.CheckpointAsync(Checkpoint(planId), done, total).ConfigureAwait(false);
|
||||
await MassRenamer.TellAsync(sequenceChanged, changed).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Holds the plan of a failed run and logs what its completed steps did; a hold that cannot be written is logged. False
|
||||
/// when the plan has no journal any more on an archive that can be reached (given up as no longer matching the
|
||||
/// archive). On one that cannot (an unplugged drive, a dropped share), a journal not found tells nothing: the checkpoint
|
||||
/// stays, so a retry resumes the plan once the archive is back.
|
||||
/// </summary>
|
||||
private static bool HoldFailed(JobContext context, Archive archive, Guid planId)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
try
|
||||
{
|
||||
if (!MassRenamer.Hold(archive, planId)) return ArchiveVolume.Probe(paths) == ArchiveAvailability.Offline;
|
||||
if (RenameJournal.Read(paths, planId) is not { } journal) return true;
|
||||
Log.Info("archive", $"Reorganize {planId} held by its failed job {context.Job.Id}");
|
||||
LogDone(context, journal.Plan, RenameResult.Of(journal.Done));
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException or InvalidDataException)
|
||||
{
|
||||
Log.Warning("archive", $"Reorganize {planId} could not be held after its job failed", ex);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The job log of what the plan did: the counts, then each sequence not changed as planned, and why.</summary>
|
||||
private static void LogDone(JobContext context, RenamePlan plan, RenameResult result)
|
||||
{
|
||||
context.Log(Loc.L("Archive.Log.Reorganized", result.Changed.Count, result.Files));
|
||||
foreach (var id in result.Dropped) context.Log(Loc.L("Archive.Log.ReorganizeDropped", Name(plan, id)));
|
||||
foreach (var id in result.TitlesKept) context.Log(Loc.L("Archive.Log.ReorganizeTitleKept", Name(plan, id)));
|
||||
foreach (var id in result.FilesKept) context.Log(Loc.L("Archive.Log.ReorganizeFilesKept", Name(plan, id)));
|
||||
foreach (var id in result.Newer) context.Log(Loc.L("Archive.Log.ReorganizeNewerKept", Name(plan, id)));
|
||||
foreach (var id in result.CarriedKept) context.Log(Loc.L("Archive.Log.ReorganizeCarriedKept", Name(plan, id)));
|
||||
foreach (var id in result.FilesBusy) context.Log(Loc.L("Archive.Log.ReorganizeFilesBusy", Name(plan, id)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the plan made now is the one confirmed: the same fingerprint, which pins every file rename by its digest
|
||||
/// (photos a sequence received since under the names the plan leaves them change nothing of it).
|
||||
/// </summary>
|
||||
private static bool IsConfirmed(RenamePlan plan, MoveJobParameters parameters) =>
|
||||
string.Equals(plan.Fingerprint(), parameters.Fingerprint, StringComparison.Ordinal);
|
||||
|
||||
private static int Steps(RenamePlan plan) => plan.Steps.Count(s => s.Changes);
|
||||
|
||||
/// <summary>How the job log names a sequence of the plan: its title, else its folder.</summary>
|
||||
private static string Name(RenamePlan plan, Guid id) =>
|
||||
plan.Steps.FirstOrDefault(s => s.SequenceId == id) is { } step ? step.ToTitle ?? step.FromTitle ?? step.FromFolder : id.ToString();
|
||||
|
||||
private static string Checkpoint(Guid planId) => Prefix + planId.ToString("N");
|
||||
|
||||
private static Guid? PlanOf(string? checkpoint) =>
|
||||
checkpoint is not null && checkpoint.StartsWith(Prefix, StringComparison.Ordinal) && Guid.TryParseExact(checkpoint[Prefix.Length..], "N", out var id)
|
||||
? id
|
||||
: null;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,24 @@
|
||||
using Chronos.Core.Archiving;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>Whether a sequence is in the folder the index has for it, as writers that file into that folder ask.</summary>
|
||||
public static class SequenceFolders
|
||||
{
|
||||
/// <summary>
|
||||
/// Whether <paramref name="folder"/>, the one the index has for sequence <paramref name="sequenceId"/>, holds it: the
|
||||
/// folder is there and its sidecar, when it has one, names no other sequence. Another index of the archive that moved
|
||||
/// the sequence away may have moved another one into the folder it left since; until this index's next scan finds both,
|
||||
/// a writer of the sequence files nothing there, exactly as when the folder is missing, so none of its writes lands in
|
||||
/// the other sequence's folder.
|
||||
/// </summary>
|
||||
public static bool Holds(SequencePaths folder, Guid sequenceId)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(folder);
|
||||
return Directory.Exists(folder.Folder) && OtherSequence(folder, sequenceId) is null;
|
||||
}
|
||||
|
||||
/// <summary>The sequence other than <paramref name="sequenceId"/> whose sidecar <paramref name="folder"/> holds; null when none does.</summary>
|
||||
internal static Guid? OtherSequence(SequencePaths folder, Guid sequenceId) =>
|
||||
File.Exists(folder.ManifestPath) && SequenceTrash.SidecarId(folder.ManifestPath) is { } id && id != sequenceId ? id : null;
|
||||
}
|
||||
@@ -511,7 +511,7 @@ public sealed partial class SequenceTrash
|
||||
/// The id a sidecar names, from its head (the id is written second), so checking a 35 MB sidecar does not parse it;
|
||||
/// the whole file is read only when the head does not hold the id. Null when the file is unreadable.
|
||||
/// </summary>
|
||||
private static Guid? SidecarId(string path)
|
||||
internal static Guid? SidecarId(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
@@ -51,6 +52,15 @@ public sealed record ArchiveServiceOptions
|
||||
/// </summary>
|
||||
public string? BackupDirectory { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Told after a Reorganize changed a sequence's folder, title or file names (change <c>reorganized</c>), once its step is
|
||||
/// journaled, or once its folder moved and its index row followed when the step then failed: by its job, or by an archive
|
||||
/// open that completed a plan an interruption left (<see cref="ArchiveService.OpenAsync"/>).
|
||||
/// A server tells its connected clients (BRIEF §14.3); the service it opens its archive with at start sets none, as no
|
||||
/// client is connected yet. The desktop reloads an editor open on the sequence. A failure is logged and never fails the job.
|
||||
/// </summary>
|
||||
public Func<Guid, string, CancellationToken, Task>? SequenceChanged { get; init; }
|
||||
|
||||
/// <summary>Half the logical cores, at least one: the parallelism when the host sets none.</summary>
|
||||
public static int DefaultParallelism => Math.Max(1, Environment.ProcessorCount / 2);
|
||||
|
||||
@@ -88,9 +98,11 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the sidecar of a locked sequence, undoing an interrupted photo deletion (<see cref="FrameRemovalJournal"/>),
|
||||
/// settling an interrupted restore from the trash (<see cref="FrameRestoreJournal"/>; left for later while its trash
|
||||
/// entry is busy) and completing an interrupted ingest batch first.
|
||||
/// Reads the sidecar of a locked sequence, completing an interrupted Reorganize of its files (<see cref="FileRenameJournal"/>),
|
||||
/// undoing an interrupted photo deletion (<see cref="FrameRemovalJournal"/>), settling an interrupted restore from the
|
||||
/// trash (<see cref="FrameRestoreJournal"/>; left for later while its trash entry is busy) and completing an interrupted
|
||||
/// ingest batch first. A sidecar a rename recovery rewrites leaves the index behind it until the rename resumes or the
|
||||
/// next scan reads it.
|
||||
/// </summary>
|
||||
/// <param name="heldEntryLease">The trash entry lease the caller holds already (a restore of that entry), if any.</param>
|
||||
/// <exception cref="InvalidDataException">The sidecar in the folder belongs to another sequence.</exception>
|
||||
@@ -99,6 +111,15 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options)
|
||||
var manifest = ManifestStore.ReadSequence(sequence.ManifestPath);
|
||||
if (manifest.Id != sequenceId)
|
||||
throw new InvalidDataException($"{sequence.ManifestPath} belongs to sequence {manifest.Id}, not {sequenceId}.");
|
||||
if (File.Exists(sequence.FileRenameJournalPath))
|
||||
{
|
||||
if (FileRenameJournal.Recover(sequence, manifest) is { } renamed)
|
||||
{
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, renamed);
|
||||
manifest = renamed;
|
||||
}
|
||||
FileRenameJournal.Delete(sequence);
|
||||
}
|
||||
FrameRemovalJournal.Recover(sequence, manifest);
|
||||
FrameTrash.RecoverRestore(sequence, manifest, heldEntryLease);
|
||||
if (IngestJournal.Recover(sequence, manifest) is { } recovered)
|
||||
@@ -110,6 +131,15 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options)
|
||||
return manifest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The folder of a sequence whose lock the caller holds, as the index has it now. A Reorganize moves a folder and
|
||||
/// updates its row under the sequence's lease (and its thumbnail lease), so a writer that read the row before taking
|
||||
/// the lease writes where the sequence is, never into the folder it left, which the write would create again. The
|
||||
/// folder of <paramref name="sequence"/> when the row is gone (reading its sidecar then fails as it did).
|
||||
/// </summary>
|
||||
public static async Task<SequencePaths> FolderAsync(ChronosDatabase db, ArchivePaths archive, Sequence sequence, CancellationToken cancellationToken) =>
|
||||
archive.Sequence((await db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false))?.Folder ?? sequence.Folder);
|
||||
|
||||
/// <summary>Applies <paramref name="edit"/> to the sidecar under the lock; a null result writes nothing.</summary>
|
||||
public async Task<SequenceManifest> UpdateAsync(ArchivePaths archive, Guid sequenceId, string folder,
|
||||
Func<SequenceManifest, SequenceManifest?> edit, CancellationToken cancellationToken)
|
||||
|
||||
Reference in new issue
Block a user