Merge branch 'fix/proxies-render-sync': proxies from clients and nodes, node manifests, sync and mass-rename fixes, server polling
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
45 files changed
+1833
-179
No files matched your search
@@ -1,5 +1,8 @@
|
||||
using System.Diagnostics;
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Imaging.Decoders;
|
||||
using Titano.Core.IO;
|
||||
using Titano.Core.Metadata;
|
||||
using Titano.Core.Model;
|
||||
@@ -9,15 +12,40 @@ namespace Titano.Data.Archiving;
|
||||
/// <summary>Frames processed by one thumbnail or proxy pass over a sequence.</summary>
|
||||
public sealed record ImagePassResult(int Built, int Reused, int Undecodable);
|
||||
|
||||
/// <summary>What became of a proxy sent by a client or render node (<see cref="ArchiveImages.StoreProxy"/>).</summary>
|
||||
public enum ProxyStoreResult
|
||||
{
|
||||
Stored,
|
||||
|
||||
/// <summary>The archive's proxy policy makes no proxies.</summary>
|
||||
Disabled,
|
||||
|
||||
/// <summary>Not a JPEG that decodes, or larger than <see cref="ArchiveImages.MaxProxyBytes"/>.</summary>
|
||||
Invalid,
|
||||
|
||||
/// <summary>Its Exif capture time is not the frame's: it was made from another photo.</summary>
|
||||
WrongFrame,
|
||||
|
||||
/// <summary>Smaller than the archive's proxies of that frame: made from an embedded preview, not the original.</summary>
|
||||
TooSmall,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Thumbnails (<c>thumbs.pack</c>) and proxies (<c>proxies/0001.jpg</c>) of sequences (BRIEF §8.5). Both are
|
||||
/// 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.
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class ArchiveImages
|
||||
{
|
||||
/// <summary>Largest proxy a client or render node may send: a full-size proxy of a large sensor at q92 fits.</summary>
|
||||
public const long MaxProxyBytes = 64L << 20;
|
||||
|
||||
private const int CommitFrames = 200;
|
||||
private const int ProbeLongEdge = 64;
|
||||
private static readonly TimeSpan CommitInterval = TimeSpan.FromSeconds(10);
|
||||
private static readonly ImageDecoder ServerDecoders = DecoderFactory.CreateServer();
|
||||
|
||||
private readonly TitanoDatabase _db;
|
||||
private readonly SequenceWriter _writer;
|
||||
@@ -32,6 +60,91 @@ public sealed class ArchiveImages
|
||||
_renderer = new FrameImageRenderer(writer.Options.Decoder);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a host with <paramref name="decoder"/> takes the pixels of a <paramref name="format"/> original from its
|
||||
/// proxy: no decoder reads the format, or only previews of a HEIF, which embeds thumbnails at best (BRIEF §2.3,
|
||||
/// §8.1: the server keeps HEIF originals and relies on proxies made by a Windows client or render node). Never for a
|
||||
/// JPEG (proxies are JPEGs: a host that reads them reads it) or a file no format was recognised in.
|
||||
/// </summary>
|
||||
public static bool NeedsProxy(ImageDecoder decoder, ImageFileFormat format)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(decoder);
|
||||
if (format is ImageFileFormat.Unknown or ImageFileFormat.Jpeg) return false;
|
||||
var tier = decoder.TierFor(format);
|
||||
return tier == DecodeTier.Unavailable || (tier != DecodeTier.Native && ImageFormatInfo.Of(format).Family == ImageFamily.Heif);
|
||||
}
|
||||
|
||||
/// <summary><see cref="NeedsProxy(ImageDecoder, ImageFileFormat)"/> with this archive engine's decoders.</summary>
|
||||
public bool NeedsProxy(ImageFileFormat format) => NeedsProxy(_writer.Options.Decoder, format);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="NeedsProxy(ImageDecoder, ImageFileFormat)"/> on a Titano Server, whose decoders are managed only (BRIEF
|
||||
/// §4.2): it asks clients and render nodes for the proxies of those originals.
|
||||
/// </summary>
|
||||
public static bool ServerNeedsProxy(ImageFileFormat format) => NeedsProxy(ServerDecoders, format);
|
||||
|
||||
/// <summary>
|
||||
/// A proxy of the original at <paramref name="path"/> for a server that cannot decode it (<see cref="StoreProxy"/>):
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">The original cannot be read.</exception>
|
||||
public static byte[]? MakeProxy(ImageDecoder decoder, string path, Frame frame, SidecarCamera? camera, int longEdge, int quality,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(frame);
|
||||
if (NeedsProxy(decoder, frame.Format)) return null;
|
||||
// The original's folder stands in for a sequence folder: the renderer reads frames relative to one.
|
||||
var folder = new ArchivePaths(Path.GetDirectoryName(Path.GetFullPath(path))!).Sequence(string.Empty);
|
||||
var source = new SidecarFrame
|
||||
{
|
||||
Id = frame.Id,
|
||||
I = frame.Index,
|
||||
File = Path.GetFileName(path),
|
||||
Size = frame.Size,
|
||||
CapturedAt = frame.CapturedAt,
|
||||
UtcOffset = frame.UtcOffsetMinutes,
|
||||
Exposure = frame.ExposureTime,
|
||||
FNumber = frame.FNumber,
|
||||
Iso = frame.Iso,
|
||||
Focal = frame.FocalLength,
|
||||
Bias = frame.ExposureBias,
|
||||
Orientation = frame.Orientation,
|
||||
Format = frame.Format,
|
||||
};
|
||||
var policy = new ProxyPolicy { LongEdge = longEdge, Quality = quality };
|
||||
return new FrameImageRenderer(decoder).Proxy(folder, source, camera, policy, cancellationToken)?.Jpeg;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only.</exception>
|
||||
public ProxyStoreResult StoreProxy(Archive archive, Sequence sequence, Frame frame, byte[] jpeg)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(jpeg);
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
var policy = ManifestStore.ReadArchive(paths.ManifestPath).ProxyPolicy;
|
||||
if (policy.LongEdge == ProxyPolicy.Disabled) return ProxyStoreResult.Disabled;
|
||||
if (jpeg.Length is 0 or > (int)MaxProxyBytes || !Decodes(jpeg)) return ProxyStoreResult.Invalid;
|
||||
var info = JpegDecoder.ReadInfo(jpeg);
|
||||
if (TooSmall(System.Math.Max(info.Width, info.Height), frame.Width, frame.Height, policy)) return ProxyStoreResult.TooSmall;
|
||||
if (frame.CapturedAt is { } captured)
|
||||
{
|
||||
using var stream = new MemoryStream(jpeg, writable: false);
|
||||
if (MetadataReader.Read(stream, "proxy.jpg").CapturedAt != captured) return ProxyStoreResult.WrongFrame;
|
||||
}
|
||||
var folder = paths.Sequence(sequence.Folder);
|
||||
Directory.CreateDirectory(folder.Proxies);
|
||||
AtomicFile.WriteAllBytes(folder.Proxy(frame.Index), jpeg);
|
||||
return ProxyStoreResult.Stored;
|
||||
}
|
||||
|
||||
/// <param name="startFrame">Resume point inside the sequence (frames before it were done by an earlier run).</param>
|
||||
/// <param name="checkpoint">Called with the next frame index whenever the pack has been committed.</param>
|
||||
public async Task<ImagePassResult> BuildThumbnailsAsync(Archive archive, Sequence sequence, bool force, int startFrame,
|
||||
@@ -54,12 +167,22 @@ public sealed class ArchiveImages
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var frame = manifest.Frames[i];
|
||||
var fingerprint = ThumbPack.Fingerprint(frame.Sha256, frame.File, frame.Size);
|
||||
if (!force && pack.Entries.TryGetValue(frame.I, out var entry) && entry.SourceHash.AsSpan().SequenceEqual(fingerprint))
|
||||
var entry = pack.Entries.GetValueOrDefault(frame.I);
|
||||
var edge = entry is null ? 0 : System.Math.Max(entry.Width, entry.Height);
|
||||
var current = !force && entry is not null && entry.SourceHash.AsSpan().SequenceEqual(fingerprint);
|
||||
// A frame this host cannot decode shows its proxy once one arrived; until then its original's embedded
|
||||
// preview, whose smaller thumbnail the proxy's replaces.
|
||||
var fromProxy = false;
|
||||
if (NeedsProxy(frame.Format) && !(current && edge >= FrameImageRenderer.ThumbnailLongEdge)
|
||||
&& ReadProxy(folder.Proxy(frame.I), frame) is { Check: ProxyCheck.Current or ProxyCheck.Unverifiable } proxy)
|
||||
fromProxy = !current || edge < System.Math.Min(FrameImageRenderer.ThumbnailLongEdge, proxy.LongEdge);
|
||||
if (current && !fromProxy)
|
||||
{
|
||||
reused++;
|
||||
continue;
|
||||
}
|
||||
if (Render(() => _renderer.Thumbnail(folder, frame, policy, cancellationToken)) is { } image)
|
||||
var source = fromProxy ? ProxySource(frame) : frame;
|
||||
if (Render(() => _renderer.Thumbnail(folder, source, policy, cancellationToken)) is { } image)
|
||||
{
|
||||
pack.Append(frame.I, image.Width, image.Height, fingerprint, image.Jpeg);
|
||||
built++;
|
||||
@@ -98,12 +221,29 @@ public sealed class ArchiveImages
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var frame = manifest.Frames[i];
|
||||
var path = folder.Proxy(frame.I);
|
||||
if (!force && IsCurrent(path, frame))
|
||||
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, longEdge) = ReadProxy(path, frame);
|
||||
if (check is ProxyCheck.Current or ProxyCheck.Unverifiable && TooSmall(longEdge, frame.W, frame.H, policy)) check = ProxyCheck.Stale;
|
||||
if (check is ProxyCheck.Current or ProxyCheck.Unverifiable)
|
||||
{
|
||||
reused++;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (check == ProxyCheck.Stale) File.Delete(path);
|
||||
undecodable++;
|
||||
}
|
||||
}
|
||||
else if (!force && ReadProxy(path, frame).Check == ProxyCheck.Current)
|
||||
{
|
||||
reused++;
|
||||
continue;
|
||||
}
|
||||
if (Render(() => _renderer.Proxy(folder, frame, manifest.Camera, policy, cancellationToken)) is { } image)
|
||||
else if (Render(() => _renderer.Proxy(folder, frame, manifest.Camera, policy, cancellationToken)) is { } image)
|
||||
{
|
||||
AtomicFile.WriteAllBytes(path, image.Jpeg);
|
||||
built++;
|
||||
@@ -118,15 +258,73 @@ public sealed class ArchiveImages
|
||||
return new ImagePassResult(built, reused, undecodable);
|
||||
}
|
||||
|
||||
/// <summary>A proxy is current when its Exif capture time is the frame's (frames renumbered since make it stale).</summary>
|
||||
private static bool IsCurrent(string proxy, SidecarFrame frame)
|
||||
/// <summary>Where a frame's proxy stands; only a capture time tells whether it is the frame's.</summary>
|
||||
private enum ProxyCheck
|
||||
{
|
||||
if (!File.Exists(proxy)) return false;
|
||||
Missing,
|
||||
|
||||
/// <summary>Its Exif capture time is the frame's.</summary>
|
||||
Current,
|
||||
|
||||
/// <summary>The frame has no capture time to compare with.</summary>
|
||||
Unverifiable,
|
||||
|
||||
/// <summary>Made from another frame (frames were renumbered since).</summary>
|
||||
Stale,
|
||||
}
|
||||
|
||||
/// <summary>Where the proxy at <paramref name="proxy"/> stands for <paramref name="frame"/>, and its long edge.</summary>
|
||||
private static (ProxyCheck Check, int LongEdge) ReadProxy(string proxy, SidecarFrame frame)
|
||||
{
|
||||
if (!File.Exists(proxy)) return (ProxyCheck.Missing, 0);
|
||||
try
|
||||
{
|
||||
return MetadataReader.Read(proxy).CapturedAt == frame.CapturedAt && frame.CapturedAt is not null;
|
||||
var metadata = MetadataReader.Read(proxy);
|
||||
var (width, height) = metadata.OrientedSize;
|
||||
var check = frame.CapturedAt is null ? ProxyCheck.Unverifiable : metadata.CapturedAt == frame.CapturedAt ? ProxyCheck.Current : ProxyCheck.Stale;
|
||||
return (check, System.Math.Max(width, height));
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return (ProxyCheck.Missing, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a proxy whose long edge is <paramref name="longEdge"/> falls short of the policy's for a frame of
|
||||
/// <paramref name="width"/> × <paramref name="height"/> (the policy's long edge, or the frame's own when smaller or
|
||||
/// at full size): one made from an embedded preview. A frame of unknown size is never judged (a small original's
|
||||
/// proxy would be refused again and again); a tenth of slack spares decoders that crop a few pixels.
|
||||
/// </summary>
|
||||
private static bool TooSmall(int longEdge, int width, int height, ProxyPolicy policy)
|
||||
{
|
||||
var own = System.Math.Max(width, height);
|
||||
if (own <= 0) return false;
|
||||
var expected = policy.LongEdge == ProxyPolicy.FullSize ? own : System.Math.Min(own, policy.LongEdge);
|
||||
return longEdge * 10L < expected * 9L;
|
||||
}
|
||||
|
||||
/// <summary>The frame's proxy as the frame to draw: a JPEG already oriented, under <c>proxies/</c>.</summary>
|
||||
private static SidecarFrame ProxySource(SidecarFrame frame) => frame with
|
||||
{
|
||||
File = ArchiveLayout.ProxiesFolder + "/" + ArchiveLayout.ProxyFileName(frame.I),
|
||||
Format = ImageFileFormat.Jpeg,
|
||||
Orientation = 1,
|
||||
PreviewOffset = null,
|
||||
PreviewLength = null,
|
||||
};
|
||||
|
||||
/// <summary>A colour or grey JPEG whose headers parse and whose scans decode (at a small DCT-scaled size).</summary>
|
||||
private static bool Decodes(byte[] jpeg)
|
||||
{
|
||||
try
|
||||
{
|
||||
var info = JpegDecoder.ReadInfo(jpeg);
|
||||
if (info.Process == JpegProcess.Lossless || info.Components is not (1 or 3) || info.Width < 1 || info.Height < 1) return false;
|
||||
using var probe = JpegDecoder.DecodeToLinear(jpeg, new JpegDecodeOptions { MaxLongEdge = ProbeLongEdge });
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidDataException or NotSupportedException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -215,7 +215,11 @@ public sealed class ArchiveMaintenance
|
||||
if (length == 0 || garbage < length * CompactionRatio) continue;
|
||||
compacted.Add(location.Folder);
|
||||
if (dryRun) continue;
|
||||
// The thumbnail builder appends under the thumbs lease only: holding it too keeps the compacted pack from
|
||||
// replacing the file under a writer, whose later thumbnails would land in the orphaned one.
|
||||
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);
|
||||
}
|
||||
return compacted;
|
||||
|
||||
@@ -32,6 +32,8 @@ public sealed class MassRenamer
|
||||
|
||||
/// <param name="folderTemplate">New folder template (<c>{title}</c> = the new title), or null to keep folders.</param>
|
||||
/// <param name="titleTemplate">New title template (<c>{title}</c> = the current title), or null to keep titles.</param>
|
||||
/// <remarks>Sequences nested in a folder that moves are part of the plan (they move with it); see <see cref="RenamePlanner.Plan"/>.</remarks>
|
||||
/// <exception cref="NestedRenameException">A new folder would lie inside a sequence's folder.</exception>
|
||||
public async Task<RenamePlan> PlanAsync(Archive archive, IReadOnlyList<Guid> sequenceIds, string? folderTemplate, string? titleTemplate,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
@@ -42,12 +44,23 @@ public sealed class MassRenamer
|
||||
{
|
||||
if (await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } s || s.ArchiveId != archive.Id)
|
||||
throw new ArgumentException($"Sequence {id} is not in archive {archive.Id}.", nameof(sequenceIds));
|
||||
subjects.Add(new RenameSubject(s.Id, s.Folder, s.Title, s.FirstCapture, s.CameraMake, s.CameraModel, s.Lens));
|
||||
subjects.Add(Subject(s));
|
||||
}
|
||||
var nested = new List<RenameSubject>();
|
||||
if (folderTemplate is not null)
|
||||
{
|
||||
var selected = sequenceIds.ToHashSet();
|
||||
foreach (var location in locations.Where(l => !selected.Contains(l.Id) && subjects.Any(s => RenamePlanner.IsInside(s.Folder, l.Folder))))
|
||||
{
|
||||
if (await _db.Sequences.GetAsync(location.Id, cancellationToken).ConfigureAwait(false) is { } inner) nested.Add(Subject(inner));
|
||||
}
|
||||
}
|
||||
return RenamePlanner.Plan(archive.Id, subjects, folderTemplate, titleTemplate, locations.Select(l => l.Folder),
|
||||
folder => Directory.Exists(paths.Sequence(folder).Folder));
|
||||
folder => Directory.Exists(paths.Sequence(folder).Folder), nested);
|
||||
}
|
||||
|
||||
private static RenameSubject Subject(Sequence s) => new(s.Id, s.Folder, s.Title, s.FirstCapture, s.CameraMake, s.CameraModel, s.Lens);
|
||||
|
||||
/// <summary>Applies a plan; each completed step is journaled before the next starts.</summary>
|
||||
/// <exception cref="StaleRenamePlanException">A sequence is no longer where the plan expects it; nothing of that step was changed.</exception>
|
||||
public Task ApplyAsync(Archive archive, RenamePlan plan, IProgress<int>? progress = null, CancellationToken cancellationToken = default) =>
|
||||
@@ -80,55 +93,106 @@ public sealed class MassRenamer
|
||||
}
|
||||
}
|
||||
RenameJournal.Write(paths, journal);
|
||||
for (var i = 0; i < journal.Plan.Steps.Count; i++)
|
||||
var steps = journal.Plan.Steps;
|
||||
foreach (var step in steps)
|
||||
{
|
||||
var step = journal.Plan.Steps[i];
|
||||
if (completed.Contains(step.SequenceId)) continue;
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
await ApplyStepAsync(archive, paths, step, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (StaleRenamePlanException) when (resuming)
|
||||
{
|
||||
Log.Warning("archive", $"Rename of {step.FromFolder} dropped: the index no longer has that sequence there");
|
||||
}
|
||||
// A folder that moves carries the sequences inside it: they are locked, moved and recorded with it.
|
||||
IReadOnlyList<RenameStep> carried = step.MovesFolder && !step.Carried
|
||||
? [.. steps.Where(c => c.Carried && !completed.Contains(c.SequenceId) && Carrier(steps, c) == step)]
|
||||
: [];
|
||||
await ApplyStepAsync(archive, paths, step, carried, resuming, cancellationToken).ConfigureAwait(false);
|
||||
completed.Add(step.SequenceId);
|
||||
foreach (var c in carried) completed.Add(c.SequenceId);
|
||||
RenameJournal.Write(paths, journal with { Completed = [.. completed] });
|
||||
progress?.Report(i + 1);
|
||||
progress?.Report(completed.Count);
|
||||
}
|
||||
RenameJournal.Delete(paths, journal.Plan.Id);
|
||||
}
|
||||
|
||||
/// <summary>Folder, then sidecar title, then index; each part is idempotent so a resumed step can repeat it.</summary>
|
||||
private async Task ApplyStepAsync(Archive archive, ArchivePaths paths, RenameStep step, CancellationToken cancellationToken)
|
||||
/// <summary>The step whose folder move carries <paramref name="carried"/>: the nearest moving folder around it (as planned).</summary>
|
||||
private static RenameStep? Carrier(IReadOnlyList<RenameStep> steps, RenameStep carried) =>
|
||||
steps.Where(m => !m.Carried && m.MovesFolder && RenamePlanner.IsInside(m.FromFolder, carried.FromFolder)).MaxBy(m => m.FromFolder.Length);
|
||||
|
||||
/// <summary>
|
||||
/// Applies a step, and the steps of the sequences its folder carries, under all their leases: sequence leases, then
|
||||
/// for a move the thumbnail leases, each by sequence id (the order trash and pack compaction take them in). No
|
||||
/// writer of a carried sequence (ingest, an editor save, a thumbnail pass) works in the folder while it moves or
|
||||
/// before its index row follows.
|
||||
/// </summary>
|
||||
/// <param name="resuming">A step whose sequence the index no longer has where the plan says is dropped instead of
|
||||
/// failing the rename: its sidecar still carries the id, so the next scan indexes it wherever it ended up.</param>
|
||||
private async Task ApplyStepAsync(Archive archive, ArchivePaths paths, RenameStep step, IReadOnlyList<RenameStep> carried, bool resuming,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await using (await _writer.LockAsync(paths, step.SequenceId, cancellationToken).ConfigureAwait(false))
|
||||
var ids = carried.Select(c => c.SequenceId).Append(step.SequenceId).Order().ToList();
|
||||
var locks = new List<IAsyncDisposable>(ids.Count);
|
||||
var leases = new List<LeaseFile>(ids.Count);
|
||||
try
|
||||
{
|
||||
var row = await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
if (row is null || (row.Folder != step.FromFolder && row.Folder != step.ToFolder)) throw new StaleRenamePlanException(step.SequenceId);
|
||||
RenamePlanner.MoveFolder(paths, step);
|
||||
var sequence = paths.Sequence(step.ToFolder);
|
||||
var manifest = SequenceWriter.ReadLocked(sequence, step.SequenceId);
|
||||
if (manifest.Title != step.ToTitle)
|
||||
foreach (var id in ids) locks.Add(await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false));
|
||||
if (step.MovesFolder)
|
||||
{
|
||||
manifest = manifest with
|
||||
foreach (var id in ids)
|
||||
{
|
||||
Title = step.ToTitle,
|
||||
Versions = manifest.Versions with { Settings = manifest.Versions.Settings + 1 },
|
||||
UpdatedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, manifest);
|
||||
leases.Add(await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{id:N}", _writer.Options.Owner, _writer.Options.LeaseWait,
|
||||
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
}
|
||||
await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false))
|
||||
// Checked before anything moves; a dropped step drops the sequences it would have carried, which stay inside it.
|
||||
if (!await StandsAsync(step, resuming, cancellationToken).ConfigureAwait(false)) return;
|
||||
var follow = new List<RenameStep>(carried.Count);
|
||||
foreach (var c in carried)
|
||||
{
|
||||
var existing = await tx.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, existing), cancellationToken).ConfigureAwait(false);
|
||||
if (step.MovesFolder) await tx.Frames.RebaseFolderAsync(step.SequenceId, step.FromFolder, step.ToFolder, cancellationToken).ConfigureAwait(false);
|
||||
await tx.Archives.DeleteFolderStateAsync(archive.Id, step.FromFolder, cancellationToken).ConfigureAwait(false);
|
||||
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (await StandsAsync(c, resuming, cancellationToken).ConfigureAwait(false)) follow.Add(c);
|
||||
}
|
||||
await _indexer.RecordStampsAsync(archive, sequence, step.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
RenamePlanner.MoveFolder(paths, step);
|
||||
await RecordAsync(archive, paths, step, cancellationToken).ConfigureAwait(false);
|
||||
// Moved with their carrier: only their sidecars and index rows follow.
|
||||
foreach (var c in follow) await RecordAsync(archive, paths, c, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
for (var i = leases.Count - 1; i >= 0; i--) leases[i].Dispose();
|
||||
for (var i = locks.Count - 1; i >= 0; i--) await locks[i].DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The index still has the step's sequence where the plan says (or where it already took it); otherwise stale.</summary>
|
||||
/// <exception cref="StaleRenamePlanException">Not resuming, and the sequence moved or vanished since the plan was made.</exception>
|
||||
private async Task<bool> StandsAsync(RenameStep step, bool resuming, CancellationToken cancellationToken)
|
||||
{
|
||||
var row = await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
if (row is not null && (row.Folder == step.FromFolder || row.Folder == step.ToFolder)) return true;
|
||||
if (!resuming) throw new StaleRenamePlanException(step.SequenceId);
|
||||
Log.Warning("archive", $"Rename of {step.FromFolder} dropped: the index no longer has that sequence there");
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Sidecar title, then index (folder, frames' paths); each part is idempotent so a resumed step can repeat it.</summary>
|
||||
private async Task RecordAsync(Archive archive, ArchivePaths paths, RenameStep step, CancellationToken cancellationToken)
|
||||
{
|
||||
var sequence = paths.Sequence(step.ToFolder);
|
||||
var manifest = SequenceWriter.ReadLocked(sequence, step.SequenceId);
|
||||
if (manifest.Title != step.ToTitle)
|
||||
{
|
||||
manifest = manifest with
|
||||
{
|
||||
Title = step.ToTitle,
|
||||
Versions = manifest.Versions with { Settings = manifest.Versions.Settings + 1 },
|
||||
UpdatedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, manifest);
|
||||
}
|
||||
await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var existing = await tx.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, existing), cancellationToken).ConfigureAwait(false);
|
||||
if (step.MovesFolder) await tx.Frames.RebaseFolderAsync(step.SequenceId, step.FromFolder, step.ToFolder, cancellationToken).ConfigureAwait(false);
|
||||
await tx.Archives.DeleteFolderStateAsync(archive.Id, step.FromFolder, cancellationToken).ConfigureAwait(false);
|
||||
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
await _indexer.RecordStampsAsync(archive, sequence, step.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user