refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
The owner renamed the product and moved the repository to the self-hosted Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control, and asked for Actions and a first automatic release with the server package and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md). - Chronos everywhere: a byte-exact rename of contents and paths, then a per-language review of the forms the old name's ending had dictated. - Gitea instead of GitHub: the update check, licence, issue and support links read ChronosReleasesUrl; the update check takes the highest stable version, offers a pre-release build its final release and reports a repository it cannot see as a failed check. EULA, security policy and Gitea issue forms live at the repository root. - Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release, nightly image and performance gates in the .NET SDK container with git checkout and the system SQLite. The release cross-compiles the Windows programs, checks their icon, version and DPI manifest, packs installers and zips, publishes the Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER). - New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the docker-exec script, which Gitea's service containers do not allow; the throw-away server runs without durability) and pe-check. - Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR, 3 on the shared runner; the weekly performance gates keep theirs). BREAKING CHANGE: programs, settings, data folders, file types, environment variables and the Docker image use the new name; nothing is migrated from Titano, which never had a release. 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 #6.
This commit is contained in:
1 parent
c99842cc86
commit
f2b58522b9
1801 files changed
+11804
-10676
No files matched your search
@@ -0,0 +1,665 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Imaging.Decoders;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Metadata;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>Frames processed by one thumbnail or proxy pass over a sequence.</summary>
|
||||
/// <param name="Waiting">Frames of a proxy pass whose originals this host cannot decode and whose proxy it waits for from a
|
||||
/// 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>
|
||||
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. 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
|
||||
/// undecodable (BRIEF §8.2 tier 3); one flagged so that decodes after all gets its tier probed again.
|
||||
/// </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;
|
||||
|
||||
/// <summary>Proxy headers kept at most (<see cref="Headers"/>): some 30 MB, the proxies of a few large sequences.</summary>
|
||||
private const int MaxHeaders = 1 << 17;
|
||||
|
||||
private static readonly TimeSpan CommitInterval = TimeSpan.FromSeconds(10);
|
||||
|
||||
/// <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.
|
||||
/// </summary>
|
||||
private static readonly TimeSpan Settling = TimeSpan.FromSeconds(3);
|
||||
|
||||
private static readonly ImageDecoder ServerDecoders = DecoderFactory.CreateServer();
|
||||
|
||||
/// <summary>
|
||||
/// The capture time and size of proxies read lately, by path, while the file keeps its length and write time: the
|
||||
/// server's manifests and tier records check every proxy of a sequence, so an unchanged one costs a stat.
|
||||
/// </summary>
|
||||
private static readonly ConcurrentDictionary<string, ProxyHeader> Headers = new(StringComparer.Ordinal);
|
||||
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly SequenceWriter _writer;
|
||||
private readonly ArchiveIndexer _indexer;
|
||||
private readonly FrameImageRenderer _renderer;
|
||||
private readonly FrameTiers _tiers;
|
||||
|
||||
internal ArchiveImages(ChronosDatabase db, SequenceWriter writer, ArchiveIndexer indexer)
|
||||
{
|
||||
_db = db;
|
||||
_writer = writer;
|
||||
_indexer = indexer;
|
||||
_renderer = new FrameImageRenderer(writer.Options.Decoder);
|
||||
_tiers = new FrameTiers(db, writer, indexer);
|
||||
}
|
||||
|
||||
/// <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 Chronos 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>
|
||||
/// Whether the file at <paramref name="proxy"/> (a sequence's <c>proxies/0001.jpg</c>) is the proxy of the frame
|
||||
/// captured at <paramref name="capturedAt"/>, of <paramref name="width"/> × <paramref name="height"/>: its Exif capture
|
||||
/// time is the frame's to the microsecond (the index's precision), or the frame has none to compare with; and, for a
|
||||
/// frame whose original this host takes from its proxy (<paramref name="policy"/> given: the archive's), it is not
|
||||
/// smaller than the policy's (<see cref="TooSmall"/>: one an earlier version made from an embedded preview). Proxies
|
||||
/// are named by frame index, so one left by a frame renumbered since (frames inserted before it) is another photo's.
|
||||
/// Renders, analyses, decode tiers and the server's manifests and downloads treat a proxy that fails this as missing,
|
||||
/// and the proxy pass removes it (<see cref="BuildProxiesAsync"/>).
|
||||
/// </summary>
|
||||
/// <param name="policy">The archive's proxy policy for a frame whose original this host cannot decode (its proxy comes
|
||||
/// from a client or render node); null for one this host decodes and makes the proxy of itself.</param>
|
||||
public static bool IsProxyOf(string proxy, DateTime? capturedAt, int width, int height, ProxyPolicy? policy) =>
|
||||
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"/>):
|
||||
/// 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 (!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 _);
|
||||
return ProxyStoreResult.Stored;
|
||||
}
|
||||
|
||||
/// <param name="startFrame">Resume point inside the sequence (frames before it were done by an earlier run: the
|
||||
/// sequence's built status counts them as they are now).</param>
|
||||
/// <param name="checkpoint">Called with the next frame index whenever the pack has been committed.</param>
|
||||
/// <remarks>
|
||||
/// Several frames are drawn at once (<see cref="ThumbnailParallelism"/>); the pack takes them in frame order
|
||||
/// (<see cref="OrderedWork{T}"/>), so a checkpoint still means that every frame before it is in the pack.
|
||||
/// </remarks>
|
||||
public async Task<ImagePassResult> BuildThumbnailsAsync(Archive archive, Sequence sequence, bool force, int startFrame,
|
||||
Func<int, int, ValueTask> checkpoint, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
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);
|
||||
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.
|
||||
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))
|
||||
{
|
||||
for (var i = 0; i < startFrame && i < manifest.Frames.Count; i++)
|
||||
{
|
||||
var frame = manifest.Frames[i];
|
||||
complete &= pack.Entries.GetValueOrDefault(frame.I) is { } entry && ThumbPack.IsFrom(entry.SourceHash, frame.Sha256, frame.File, frame.Size);
|
||||
}
|
||||
var cadence = new Cadence();
|
||||
await using (var work = new OrderedWork<Drawn>(ThumbnailParallelism(manifest.Frames, policy), drawn =>
|
||||
{
|
||||
if (drawn.Image is { } image)
|
||||
{
|
||||
pack.Append(drawn.Frame.I, image.Width, image.Height, drawn.Fingerprint, image.Jpeg);
|
||||
built++;
|
||||
}
|
||||
else
|
||||
{
|
||||
undecodable++;
|
||||
}
|
||||
if (drawn.Tier is { } tier) tiers[drawn.Frame.Id] = tier;
|
||||
if (!cadence.Due()) return ValueTask.CompletedTask;
|
||||
pack.Commit();
|
||||
return checkpoint(drawn.Index + 1, manifest.Frames.Count);
|
||||
}, cancellationToken))
|
||||
{
|
||||
for (var i = startFrame; i < manifest.Frames.Count; i++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var frame = manifest.Frames[i];
|
||||
var fingerprint = ThumbPack.Fingerprint(frame.Sha256, frame.File, frame.Size);
|
||||
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 && ThumbPack.IsFrom(entry.SourceHash, frame.Sha256, frame.File, frame.Size);
|
||||
// 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 >= policy.LongEdge)
|
||||
&& Check(folder.Proxy(frame.I), frame.CapturedAt, frame.W, frame.H, archiveManifest.ProxyPolicy) is { Check: ProxyCheck.Current or ProxyCheck.Unverifiable } proxy)
|
||||
fromProxy = !current || edge < System.Math.Min(policy.LongEdge, proxy.LongEdge);
|
||||
if (current && !fromProxy)
|
||||
{
|
||||
reused++;
|
||||
continue;
|
||||
}
|
||||
var companion = companions.GetValueOrDefault(frame.Id);
|
||||
var index = i;
|
||||
// A thumbnail drawn from the proxy says nothing about how this host decodes the original.
|
||||
await work.AddAsync(fromProxy
|
||||
? ct => Drawn.Of(index, frame, fingerprint, Render(folder, frame, null, recordTier: false,
|
||||
() => _renderer.Thumbnail(folder, ProxySource(frame), policy, ct)))
|
||||
: ct => Drawn.Of(index, frame, fingerprint, Render(folder, frame, companion, recordTier: true,
|
||||
() => _renderer.Thumbnail(folder, frame, policy, ct, companion)))).ConfigureAwait(false);
|
||||
}
|
||||
await work.CompleteAsync().ConfigureAwait(false);
|
||||
}
|
||||
pack.Commit();
|
||||
}
|
||||
await _tiers.RecordAsync(archive, sequence, tiers, proxies: false, cancellationToken).ConfigureAwait(false);
|
||||
await MarkAsync(archive, paths, sequence, manifest, JobKind.Thumbs, SequenceStatus.ThumbsBuilt, complete && undecodable == 0, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return new ImagePassResult(built, reused, undecodable);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="BuildThumbnailsAsync"/>
|
||||
/// <remarks>
|
||||
/// <see cref="SequenceStatus.ProxiesBuilt"/> is set only when every frame has its proxy: a server asks clients and
|
||||
/// render nodes for none while it is set (BRIEF §2.3), so a pass resumed at <paramref name="startFrame"/> checks the
|
||||
/// 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}"/>).
|
||||
/// </remarks>
|
||||
public async Task<ImagePassResult> BuildProxiesAsync(Archive archive, Sequence sequence, bool force, int startFrame,
|
||||
Func<int, int, ValueTask> checkpoint, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
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);
|
||||
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))
|
||||
{
|
||||
for (var i = 0; i < manifest.Frames.Count; i++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var frame = manifest.Frames[i];
|
||||
var path = folder.Proxy(frame.I);
|
||||
var done = i < 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(i, 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 = 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);
|
||||
}
|
||||
await work.CompleteAsync().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>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);
|
||||
|
||||
/// <summary>Originals a proxy pass decodes at once (<see cref="PassParallelism"/>): it develops RAWs, and decodes whole for a full-size policy.</summary>
|
||||
private int ProxyParallelism(IReadOnlyList<SidecarFrame> frames, ProxyPolicy policy) =>
|
||||
PassParallelism(_writer.Options.Parallelism(), _writer.Options.MemoryBudget(), frames, System.Math.Max(policy.LongEdge, 0), preferPreview: false,
|
||||
_writer.Options.Decoder);
|
||||
|
||||
/// <summary>
|
||||
/// Photos a pass decoding at <paramref name="edge"/> (0: full size) works on at once: the whole parallelism while no
|
||||
/// frame is developed whole (a JPEG at least twice the edge decodes scaled down; a frame this host reads through its
|
||||
/// proxy or preview develops nothing here, nor one whose embedded preview reaches the edge when previews serve), else
|
||||
/// <see cref="DecodeBudget.PhotosAtOnce"/> for the largest original developed (a TIFF, a PNG, a RAW).
|
||||
/// </summary>
|
||||
internal static int PassParallelism(int parallelism, long memoryBudget, IReadOnlyList<SidecarFrame> frames, int edge, bool preferPreview, ImageDecoder decoder)
|
||||
{
|
||||
parallelism = Math.Max(1, parallelism);
|
||||
long largest = 0;
|
||||
foreach (var frame in frames)
|
||||
{
|
||||
if (NeedsProxy(decoder, frame.Format)) continue;
|
||||
largest = System.Math.Max(largest, DecodeBudget.Developed(frame.Format, frame.W, frame.H, System.Math.Max(frame.PreviewW ?? 0, frame.PreviewH ?? 0),
|
||||
edge, preferPreview));
|
||||
}
|
||||
return largest == 0 ? parallelism : DecodeBudget.PhotosAtOnce(parallelism, memoryBudget, largest);
|
||||
}
|
||||
|
||||
/// <summary>A thumbnail drawn for the frame at <see cref="Index"/> of the pass (null: nothing decoded it) and what decoding found.</summary>
|
||||
private sealed record Drawn(int Index, SidecarFrame Frame, byte[] Fingerprint, EncodedImage? Image, FileTier? Tier)
|
||||
{
|
||||
public static Drawn Of(int index, SidecarFrame frame, byte[] fingerprint, (EncodedImage? Image, FileTier? Tier) rendered) =>
|
||||
new(index, frame, fingerprint, rendered.Image, rendered.Tier);
|
||||
}
|
||||
|
||||
/// <summary>What became of the proxy of a frame of a proxy pass.</summary>
|
||||
private enum ProxyOutcome
|
||||
{
|
||||
Built,
|
||||
|
||||
/// <summary>The frame this host cannot decode has its proxy from a client or render node.</summary>
|
||||
Reused,
|
||||
|
||||
/// <summary>The frame this host cannot decode waits for its proxy from a client or render node.</summary>
|
||||
Waiting,
|
||||
|
||||
/// <summary>The frame this host cannot decode is missing or damaged.</summary>
|
||||
Unreadable,
|
||||
|
||||
/// <summary>No decoder read the original.</summary>
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>The proxy outcome of the frame at <see cref="Index"/> of the pass, and what decoding found.</summary>
|
||||
private sealed record Made(int Index, Guid FrameId, ProxyOutcome Outcome, FileTier? Tier);
|
||||
|
||||
/// <summary>Where a frame's proxy stands; only a capture time tells whether it is the frame's.</summary>
|
||||
private enum ProxyCheck
|
||||
{
|
||||
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), or too small (<see cref="Check"/>).</summary>
|
||||
Stale,
|
||||
}
|
||||
|
||||
/// <summary>A proxy's Exif capture time and oriented long edge, read when the file had this length and write time.</summary>
|
||||
private readonly record struct ProxyHeader(long Length, long WriteTicks, DateTime? CapturedAt, int LongEdge);
|
||||
|
||||
/// <summary>
|
||||
/// Where the proxy at <paramref name="proxy"/> stands for the frame captured at <paramref name="capturedAt"/>, of
|
||||
/// <paramref name="width"/> × <paramref name="height"/>, and its long edge: <see cref="ProxyCheck.Stale"/> also when
|
||||
/// <paramref name="policy"/> is given and the proxy is <see cref="TooSmall"/> for it (<see cref="IsProxyOf"/>).
|
||||
/// </summary>
|
||||
private static (ProxyCheck Check, int LongEdge) Check(string proxy, DateTime? capturedAt, int width, int height, ProxyPolicy? policy)
|
||||
{
|
||||
var (check, longEdge) = ReadProxy(proxy, capturedAt);
|
||||
if (check is ProxyCheck.Current or ProxyCheck.Unverifiable && policy is not null && TooSmall(longEdge, width, height, policy)) check = ProxyCheck.Stale;
|
||||
return (check, longEdge);
|
||||
}
|
||||
|
||||
/// <summary>Where the proxy at <paramref name="proxy"/> stands for the frame captured at <paramref name="capturedAt"/>, and its long edge.</summary>
|
||||
private static (ProxyCheck Check, int LongEdge) ReadProxy(string proxy, DateTime? capturedAt)
|
||||
{
|
||||
if (ReadHeader(proxy) is not { } header) return (ProxyCheck.Missing, 0);
|
||||
var check = capturedAt is not { } captured ? ProxyCheck.Unverifiable : SameCapture(header.CapturedAt, captured) ? ProxyCheck.Current : ProxyCheck.Stale;
|
||||
return (check, header.LongEdge);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The header of the proxy at <paramref name="proxy"/>; null when there is none or it cannot be read. Kept in
|
||||
/// <see cref="Headers"/> while the file's length and write time stay as they were when it was read (taken first, so
|
||||
/// a file replaced meanwhile is read again next time), once the file is older than <see cref="Settling"/>; a full
|
||||
/// cache starts over.
|
||||
/// </summary>
|
||||
private static ProxyHeader? ReadHeader(string proxy)
|
||||
{
|
||||
try
|
||||
{
|
||||
var file = new FileInfo(proxy);
|
||||
if (!file.Exists) return null;
|
||||
var (length, written) = (file.Length, file.LastWriteTimeUtc);
|
||||
if (Headers.TryGetValue(proxy, out var cached) && cached.Length == length && cached.WriteTicks == written.Ticks) return cached;
|
||||
var metadata = MetadataReader.Read(proxy);
|
||||
var (width, height) = metadata.OrientedSize;
|
||||
var header = new ProxyHeader(length, written.Ticks, metadata.CapturedAt, System.Math.Max(width, height));
|
||||
if (DateTime.UtcNow - written < Settling)
|
||||
{
|
||||
Headers.TryRemove(proxy, out _);
|
||||
return header;
|
||||
}
|
||||
if (Headers.Count >= MaxHeaders) Headers.Clear();
|
||||
Headers[proxy] = header;
|
||||
return header;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a proxy's Exif capture time is the frame's <paramref name="captured"/> to the microsecond: the index keeps
|
||||
/// capture times to the microsecond, sidecars and Exif to the 100 ns tick, so a proxy made from either record of the
|
||||
/// frame (here from the sidecar, by a client from the server's index) matches both.
|
||||
/// </summary>
|
||||
private static bool SameCapture(DateTime? proxy, DateTime captured) =>
|
||||
proxy is { } time && time.Ticks / TimeSpan.TicksPerMicrosecond == captured.Ticks / TimeSpan.TicksPerMicrosecond;
|
||||
|
||||
/// <summary>Removes the proxy at <paramref name="path"/> and what is known of it.</summary>
|
||||
private static void Delete(string path)
|
||||
{
|
||||
File.Delete(path);
|
||||
Headers.TryRemove(path, out _);
|
||||
}
|
||||
|
||||
/// <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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A frame no decoder can read is skipped and counted; it never stops the pass. With <paramref name="recordTier"/>,
|
||||
/// what decoding found comes back with the image: unavailable when nothing decoded a file that is there (a read error
|
||||
/// proves nothing), and the probed tier when a frame flagged undecodable decoded after all. Runs on the pass's
|
||||
/// workers, so it shares nothing with the others.
|
||||
/// </summary>
|
||||
private (EncodedImage? Image, FileTier? Tier) Render(SequencePaths folder, SidecarFrame frame, string? companion, bool recordTier, Func<EncodedImage?> render)
|
||||
{
|
||||
var path = folder.File(frame.File);
|
||||
EncodedImage? image;
|
||||
try
|
||||
{
|
||||
image = render();
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("archive", "Frame image could not be rendered", ex);
|
||||
return (null, null);
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidDataException or NotSupportedException)
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("archive", "Frame image could not be rendered", ex);
|
||||
image = null;
|
||||
}
|
||||
if (!recordTier) return (image, null);
|
||||
if (image is null)
|
||||
return (null, File.Exists(path) ? new FileTier(frame.Format, DecodeTier.Unavailable, null, "no decoder produced pixels", 0, 0) : null);
|
||||
return (image, (frame.Flags & FrameFlags.Undecodable) != 0 ? Reprobe(path, frame, companion, image.Tier) : null);
|
||||
}
|
||||
|
||||
/// <summary>The tier of a frame that decoded after it was flagged undecodable (the image's own tier when probing finds none).</summary>
|
||||
private FileTier Reprobe(string path, SidecarFrame frame, string? companion, DecodeTier decoded)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_writer.Options.Decoder.Probe(path, frame.Format, companion) is { Tier: not DecodeTier.Unavailable } tier) return tier;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("archive", $"{path} could not be probed", ex);
|
||||
}
|
||||
return new FileTier(frame.Format, decoded, null, null, 0, 0);
|
||||
}
|
||||
|
||||
/// <summary>Commit/checkpoint rhythm: every <see cref="CommitFrames"/> rendered frames or <see cref="CommitInterval"/>.</summary>
|
||||
private sealed class Cadence
|
||||
{
|
||||
private readonly Stopwatch _clock = Stopwatch.StartNew();
|
||||
private int _frames;
|
||||
|
||||
public bool Due()
|
||||
{
|
||||
if (++_frames < CommitFrames && _clock.Elapsed < CommitInterval) return false;
|
||||
_frames = 0;
|
||||
_clock.Restart();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets <paramref name="flag"/> in the sidecar and the index when the pass covered every frame it read
|
||||
/// (<paramref name="complete"/>) and the sidecar, as it is under the lease, still lists those frames
|
||||
/// (<see cref="SameFrames"/>); clears it otherwise. Frames a scan's reconcile or an ingest added, removed or
|
||||
/// renumbered after the pass read <paramref name="read"/> have nothing of it, and a scan that cleared the flag for
|
||||
/// them queues the next pass only while the flag stays clear. A <paramref name="pass"/> of the same kind already
|
||||
/// queued for the sequence (an upload's, or a scan's) draws them when it runs, so the flag stays set meanwhile, as
|
||||
/// between an upload and its pass: a camera uploading faster than a pass ends would otherwise keep it clear, and a
|
||||
/// server would offer no thumbnail or proxy of the sequence at all until uploads paused. The index is written under
|
||||
/// the same lease, so the flag never lands there after a scan cleared it in both.
|
||||
/// </summary>
|
||||
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 manifest = SequenceWriter.ReadLocked(folder, sequence.Id);
|
||||
var built = complete && (SameFrames(manifest.Frames, read.Frames)
|
||||
|| await _db.Jobs.IsQueuedAsync(pass, sequence.Id, cancellationToken).ConfigureAwait(false));
|
||||
var inStep = await _indexer.InStepAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false);
|
||||
var status = built ? manifest.Status | flag : manifest.Status & ~flag;
|
||||
if (status != manifest.Status)
|
||||
{
|
||||
manifest = manifest with { Status = status, UpdatedAt = DateTimeOffset.UtcNow };
|
||||
ManifestStore.WriteSequence(folder.ManifestPath, manifest);
|
||||
}
|
||||
await _db.Sequences.UpdateStatusAsync(sequence.Id, built ? flag : SequenceStatus.None, built ? SequenceStatus.None : flag, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (inStep) await _indexer.RecordStampsAsync(archive, folder, sequence.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="current"/> lists the photos <paramref name="read"/> did, each at the same index with the
|
||||
/// same file, size, capture time and content hash: thumbnails and proxies are kept by frame index, so photos added,
|
||||
/// 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)
|
||||
{
|
||||
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
|
||||
|| (then.Sha256 is not null && !string.Equals(now.Sha256, then.Sha256, StringComparison.OrdinalIgnoreCase))) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,552 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
public enum ScanMode
|
||||
{
|
||||
/// <summary>Only folders whose sidecar or photo folder changed size or time since the last scan.</summary>
|
||||
Incremental,
|
||||
|
||||
/// <summary>Every folder: sidecars re-read and folders reconciled with their photos (manual rescan).</summary>
|
||||
Full,
|
||||
|
||||
/// <summary>The index rebuilt from sidecars alone; rows without a sidecar are dropped (BRIEF §12.5).</summary>
|
||||
Rebuild,
|
||||
}
|
||||
|
||||
public sealed record ScanProgress(int FoldersDone, int FoldersTotal, string Folder, bool Changed);
|
||||
|
||||
/// <param name="Failed">Folders that could not be indexed, with the reason; they are retried by the next scan.</param>
|
||||
/// <param name="Sequences">The sequences this run indexed (<paramref name="Indexed"/> of them), in folder order.</param>
|
||||
public sealed record ScanSummary(int Folders, int Indexed, int Adopted, int Removed, IReadOnlyList<(string Folder, string Error)> Failed,
|
||||
IReadOnlyList<Guid> Sequences);
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the database index in line with the archive on disk (BRIEF §7, §12.5): scans by size/time stamps, adopts
|
||||
/// folders without a sidecar, rebuilds from sidecars (using the index snapshot when it is fresh) and syncs one
|
||||
/// sequence after any service changed its sidecar. The sidecars are the truth; the index is derived.
|
||||
/// </summary>
|
||||
public sealed class ArchiveIndexer
|
||||
{
|
||||
/// <summary>What covers the frames as they were: a scan that finds them changed clears it, and its follow-ups make it again.</summary>
|
||||
private const SequenceStatus CoveringStatus = SequenceStatus.AnalyzedLight | SequenceStatus.ThumbsBuilt | SequenceStatus.ProxiesBuilt;
|
||||
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly SequenceWriter _writer;
|
||||
|
||||
internal ArchiveIndexer(ChronosDatabase db, SequenceWriter writer)
|
||||
{
|
||||
_db = db;
|
||||
_writer = writer;
|
||||
}
|
||||
|
||||
/// <param name="resumeAfter">Last folder completed by an interrupted run (job checkpoint), or null.</param>
|
||||
/// <param name="progress">Called after each folder; persist <see cref="ScanProgress.Folder"/> as the resume point.</param>
|
||||
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only; the index is left as it is.</exception>
|
||||
public async Task<ScanSummary> ScanAsync(Archive archive, ScanMode mode, string? resumeAfter, Func<ScanProgress, ValueTask> progress,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
if (mode == ScanMode.Rebuild && resumeAfter is null) await _db.Archives.ClearFolderStatesAsync(archive.Id, cancellationToken).ConfigureAwait(false);
|
||||
var folders = ArchiveScanner.FindSequenceFolders(paths, cancellationToken);
|
||||
var states = await _db.Archives.GetFolderStatesAsync(archive.Id, cancellationToken).ConfigureAwait(false);
|
||||
var rows = await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false);
|
||||
// A sequence waiting for its first frame has no folder yet: the archive root, adopted or re-adopted, never takes its id.
|
||||
var awaiting = await AwaitingFolderAsync(paths, rows, cancellationToken).ConfigureAwait(false);
|
||||
var locations = new Locations(rows.Where(r => !awaiting.Contains(r.Id)));
|
||||
var snapshot = mode == ScanMode.Rebuild ? IndexSnapshot.TryLoad(paths.SnapshotPath) : null;
|
||||
using var snapshotWriter = mode != ScanMode.Incremental && resumeAfter is null ? new IndexSnapshot.Writer(paths.SnapshotPath) : null;
|
||||
|
||||
int adopted = 0;
|
||||
var indexed = new List<Guid>();
|
||||
var failed = new List<(string, string)>();
|
||||
for (var i = 0; i < folders.Count; i++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var folder = folders[i];
|
||||
if (resumeAfter is not null && string.CompareOrdinal(folder.RelativeFolder, resumeAfter) <= 0) continue;
|
||||
states.TryGetValue(folder.RelativeFolder, out var state);
|
||||
var changed = mode != ScanMode.Incremental || state is null || state.Sidecar != folder.Sidecar || state.Photos != folder.Photos;
|
||||
if (changed)
|
||||
{
|
||||
try
|
||||
{
|
||||
var reconcile = mode == ScanMode.Full || (state is not null && state.Photos != folder.Photos);
|
||||
var (id, bytes) = await IndexFolderAsync(archive, paths, folder, reconcile, snapshot, locations, cancellationToken).ConfigureAwait(false);
|
||||
if (snapshotWriter is not null)
|
||||
{
|
||||
// Bytes go under the stamp they were read at (the listed one for the bytes indexed, else one taken before
|
||||
// reading): a sidecar rewritten meanwhile is never filed under its new stamp with its old content.
|
||||
var sidecar = paths.Sequence(folder.RelativeFolder).ManifestPath;
|
||||
var read = bytes is not null ? folder.Sidecar!.Value : FileStamp.Of(sidecar)!.Value;
|
||||
snapshotWriter.Add(folder.RelativeFolder, read, bytes ?? await AtomicFile.ReadAllBytesAsync(sidecar, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
indexed.Add(id);
|
||||
if (folder.Sidecar is null) adopted++;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"Indexing {folder.RelativeFolder} failed", ex);
|
||||
failed.Add((folder.RelativeFolder, ex.Message));
|
||||
}
|
||||
}
|
||||
await progress(new ScanProgress(i + 1, folders.Count, folder.RelativeFolder, changed)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var removed = mode == ScanMode.Rebuild ? await RemoveUnbackedAsync(archive, paths, folders, locations, cancellationToken).ConfigureAwait(false) : 0;
|
||||
if (failed.Count == 0) snapshotWriter?.Commit();
|
||||
return new ScanSummary(folders.Count, indexed.Count, adopted, removed, failed, indexed);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a sequence's sidecar into the index (row, frames, session keys) and records the folder stamps. Frames
|
||||
/// inserted before indexed ones take the project's frame positions along (<see cref="ProjectPositions"/>). The frames
|
||||
/// version never goes back, nor names other frames than it did: a sidecar read under the lease that is behind the
|
||||
/// locked row (an older copy put back by hand or by a file-sync tool), or at the row's version over other frames
|
||||
/// (another index of the archive bumped a copy put back to it, <see cref="OtherFramesAsync"/>), is written again one
|
||||
/// version past the row, so editors and clients holding the row's version see the change.
|
||||
/// </summary>
|
||||
/// <param name="listed">The folder as the scan listed it before reading <paramref name="manifest"/> without the sequence
|
||||
/// lease; null when the caller holds the lease and read the sidecar under it.</param>
|
||||
/// <param name="clear">Statuses cleared in this index's row only, never in the sidecar (<see cref="Uncovered"/>).</param>
|
||||
/// <param name="photosChanged">The caller, holding the lease, found the photo directory changed since this index recorded
|
||||
/// its stamp before it changed the folder itself (<see cref="PhotosChangedAsync"/>). This sync indexes the sidecar, not
|
||||
/// the photos, so the recorded photo stamp stays (none when none was) and the next incremental scan reconciles them.</param>
|
||||
/// <returns>The manifest indexed; null, with nothing written, when <paramref name="listed"/> is given and the sidecar is no
|
||||
/// longer the one listed or the locked row holds another frames version. Another writer then committed since the read
|
||||
/// (an ingest's frames, a tier or a verify), and the caller reads the sidecar again under the lease
|
||||
/// (<see cref="UpdateAndSyncAsync"/>) rather than write the older read over it and record stamps that hide it.</returns>
|
||||
internal async Task<SequenceManifest?> SyncAsync(Archive archive, SequencePaths sequence, SequenceManifest manifest, SequenceFolder? listed,
|
||||
SequenceStatus clear, bool photosChanged, CancellationToken cancellationToken)
|
||||
{
|
||||
PositionMove? positions = null;
|
||||
await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
// Locked: a settings edit committed after this read (the server's PATCH takes no lease) would be written back over,
|
||||
// and writers of the sequence's frames commit before or after this, never in between (GetForUpdateAsync).
|
||||
var existing = await tx.Sequences.GetForUpdateAsync(manifest.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (listed is not null && (FileStamp.Of(sequence.ManifestPath) != listed.Sidecar
|
||||
|| (existing is not null && existing.FramesVersion != manifest.Versions.Frames)))
|
||||
return null;
|
||||
// Under the lease, the row's own version may also name other frames: another index of the archive bumped a copy
|
||||
// put back to it (OtherFramesAsync). A caller without the lease compared them before its read (FramesMovedAsync).
|
||||
if (existing is not null && (existing.FramesVersion > manifest.Versions.Frames
|
||||
|| (listed is null && existing.FramesVersion == manifest.Versions.Frames
|
||||
&& await OtherFramesAsync(tx, existing, manifest, cancellationToken).ConfigureAwait(false))))
|
||||
{
|
||||
manifest = manifest with
|
||||
{
|
||||
Versions = manifest.Versions with { Frames = existing.FramesVersion + 1 },
|
||||
UpdatedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, manifest);
|
||||
}
|
||||
if (existing is not null)
|
||||
{
|
||||
positions = await ProjectPositions.MoveAsync(tx, existing, manifest, cancellationToken).ConfigureAwait(false);
|
||||
if (positions is not null) existing = positions.ApplyTo(existing);
|
||||
}
|
||||
var row = SequenceMapping.ToSequence(manifest, archive.Id, sequence, existing);
|
||||
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);
|
||||
foreach (var key in manifest.SessionKeys)
|
||||
await tx.Sequences.MapSessionKeyAsync(archive.Id, key, manifest.Id, cancellationToken).ConfigureAwait(false);
|
||||
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
if (positions is { } moved) ProjectPositions.WriteProject(sequence, moved.Before, moved.Moved);
|
||||
// Unleased, the stamps the sync was checked against: a sidecar or photos changed since keep the folder changed.
|
||||
if (listed is not null)
|
||||
{
|
||||
await RecordStampsAsync(archive, sequence.RelativeFolder, manifest.Id, listed.Sidecar, listed.Photos, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else if (photosChanged)
|
||||
{
|
||||
// The photo stamp as recorded: the photos this sync did not index keep the folder changed for the next scan.
|
||||
var recorded = await _db.Archives.GetFolderStateAsync(archive.Id, sequence.RelativeFolder, cancellationToken).ConfigureAwait(false);
|
||||
await RecordStampsAsync(archive, sequence.RelativeFolder, manifest.Id, FileStamp.Of(sequence.ManifestPath), recorded?.Photos, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await RecordStampsAsync(archive, sequence, manifest.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
return manifest;
|
||||
}
|
||||
|
||||
/// <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.
|
||||
/// </summary>
|
||||
internal Task RecordStampsAsync(Archive archive, SequencePaths sequence, Guid sequenceId, CancellationToken cancellationToken) =>
|
||||
RecordStampsAsync(archive, sequence.RelativeFolder, sequenceId, FileStamp.Of(sequence.ManifestPath), FileStamp.Of(ArchiveScanner.PhotoDirectory(sequence)),
|
||||
cancellationToken);
|
||||
|
||||
private Task RecordStampsAsync(Archive archive, string folder, Guid sequenceId, FileStamp? sidecar, FileStamp? photos, CancellationToken cancellationToken) =>
|
||||
_db.Archives.SetFolderStateAsync(archive.Id, new FolderScanState(folder, sequenceId, sidecar, photos), cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Whether this index holds the folder of <paramref name="manifest"/> (the sidecar read under the sequence lease) as it
|
||||
/// is now: the stamps it recorded when it last synced the folder are still the folder's, and its row holds the
|
||||
/// sidecar's frames. A writer that changes, under the lease, only what it owns of the sidecar and the index row
|
||||
/// (statuses, decode tiers, frame flags, title, tags, rating and notes, the folder) asks before its own write, and
|
||||
/// records the folder's new stamps after it only when this held (<see cref="RecordStampsAsync"/>). What another
|
||||
/// process (a desktop sharing the archive) changed in the sidecar alone, frames or a new title, then keeps the folder
|
||||
/// changed for the next incremental scan, which writes the whole row from the sidecar. An upload asks too, and
|
||||
/// appends its frames only when this held; otherwise it writes the whole row and every frame from the sidecar itself.
|
||||
/// </summary>
|
||||
internal Task<bool> InStepAsync(Archive archive, SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken) =>
|
||||
InStepAsync(archive, sequence.RelativeFolder, sequence, manifest, cancellationToken);
|
||||
|
||||
/// <inheritdoc cref="InStepAsync(Archive, SequencePaths, SequenceManifest, CancellationToken)"/>
|
||||
/// <param name="recordedFolder">The folder the stamps were recorded at: the one a rename just moved the sequence from,
|
||||
/// whose files keep their stamps.</param>
|
||||
internal async Task<bool> InStepAsync(Archive archive, string recordedFolder, SequencePaths sequence, SequenceManifest manifest,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (await _db.Archives.GetFolderStateAsync(archive.Id, recordedFolder, cancellationToken).ConfigureAwait(false) is not { } state
|
||||
|| state.SequenceId != manifest.Id || state.Sidecar != FileStamp.Of(sequence.ManifestPath)
|
||||
|| state.Photos != FileStamp.Of(ArchiveScanner.PhotoDirectory(sequence))) return false;
|
||||
// A sidecar rewritten within its file system's time resolution, at the same size, keeps its stamp.
|
||||
return await _db.Sequences.GetAsync(manifest.Id, cancellationToken).ConfigureAwait(false) is { } indexed
|
||||
&& indexed.FramesVersion == manifest.Versions.Frames;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the folder's photo directory no longer has the stamp this index recorded for it, or none was recorded:
|
||||
/// photos copied in or removed by hand or by another process since the last scan, which only a scan's reconcile
|
||||
/// indexes. An upload asks under the lease before it files its photos, which change the stamp, and its sync from the
|
||||
/// sidecar then keeps the recorded one (<see cref="SyncAsync"/>), so the next incremental scan still reconciles them.
|
||||
/// </summary>
|
||||
internal async Task<bool> PhotosChangedAsync(Archive archive, SequencePaths sequence, CancellationToken cancellationToken) =>
|
||||
(await _db.Archives.GetFolderStateAsync(archive.Id, sequence.RelativeFolder, cancellationToken).ConfigureAwait(false))?.Photos
|
||||
!= FileStamp.Of(ArchiveScanner.PhotoDirectory(sequence));
|
||||
|
||||
/// <summary>
|
||||
/// Indexes unindexed photos and flags missing files of one sequence (the orphans fix action), as a scan's reconcile
|
||||
/// does (<see cref="Reconcile"/>): what covered the frames is cleared in the sidecar and the row.
|
||||
/// </summary>
|
||||
/// <returns>Whether photos were added, gone or back: the light analysis, thumbnails and proxies are then to be made again
|
||||
/// (<see cref="ArchiveService.ReconcileAsync"/>). The folder's stamps are recorded, so no scan comes back to it and
|
||||
/// queues them.</returns>
|
||||
public async Task<bool> ReconcileAsync(Archive archive, Sequence sequence, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
var folder = paths.Sequence(sequence.Folder);
|
||||
var changed = false;
|
||||
await UpdateAndSyncAsync(archive, paths, folder, sequence.Id, m =>
|
||||
{
|
||||
var reconciled = Reconcile(folder, m, cancellationToken);
|
||||
changed = reconciled is not null;
|
||||
return reconciled;
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
return changed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sidecar brought in line with the folder's photos (<see cref="SequenceAdopter.Reconcile"/>); null when nothing
|
||||
/// changed. Photos added, gone or back: the light analysis, thumbnails and proxies no longer cover the frames, as the
|
||||
/// sidecar then tells every host, so the follow-ups make them again (the images on a server,
|
||||
/// <see cref="ArchiveServiceOptions.ImagesAfterScan"/>).
|
||||
/// </summary>
|
||||
private static SequenceManifest? Reconcile(SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken) =>
|
||||
SequenceAdopter.Reconcile(sequence, manifest, cancellationToken) is { } reconciled
|
||||
? reconciled with { Status = reconciled.Status & ~CoveringStatus }
|
||||
: null;
|
||||
|
||||
/// <summary>
|
||||
/// Applies <paramref name="edit"/> to the sidecar (null writes nothing) and indexes the result, both under the sequence
|
||||
/// lease. Frames inserted before indexed ones move the project's positions (<see cref="ProjectPositions"/>) without a
|
||||
/// new settings version; an editor saving its project holds the same lease, so it reads them moved and merges onto them
|
||||
/// rather than writing its old positions back. When the sidecar, as read under the lease, lists other frames than the
|
||||
/// index row (another process changed them together with their sidecar entries), the row is written without what
|
||||
/// this host makes for the frames (<see cref="Uncovered"/>).
|
||||
/// </summary>
|
||||
private async Task<SequenceManifest> UpdateAndSyncAsync(Archive archive, ArchivePaths paths, SequencePaths sequence, Guid sequenceId,
|
||||
Func<SequenceManifest, SequenceManifest?> edit, CancellationToken cancellationToken)
|
||||
{
|
||||
await using (await _writer.LockAsync(paths, sequenceId, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var manifest = SequenceWriter.ReadLocked(sequence, sequenceId);
|
||||
var moved = await FramesMovedAsync(manifest, cancellationToken).ConfigureAwait(false);
|
||||
if (edit(manifest) is { } updated)
|
||||
{
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, updated);
|
||||
manifest = updated;
|
||||
}
|
||||
return (await SyncAsync(archive, sequence, manifest, null, moved ? Uncovered : SequenceStatus.None, false, cancellationToken).ConfigureAwait(false))!;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What a scan clears in this host's own row, never in the shared sidecar, when another process added, removed or
|
||||
/// renumbered frames together with their sidecar entries: on a server (<see cref="ArchiveServiceOptions.ImagesAfterScan"/>),
|
||||
/// which analyses and draws what its clients load, the light analysis, thumbnails and proxies, so the scan's follow-ups
|
||||
/// make them for the frames as they are, and their passes set the flags in both places again. Nothing on a desktop:
|
||||
/// the flags in the sidecar are the writer's that added the frames (which analyses them, and on a server draws them
|
||||
/// after every upload), and clearing them there would have the server make everything again.
|
||||
/// </summary>
|
||||
private SequenceStatus Uncovered => _writer.Options.ImagesAfterScan ? CoveringStatus : SequenceStatus.None;
|
||||
|
||||
/// <summary>Indexes one folder; returns its sequence and the sidecar bytes when they were read and not rewritten since (for the snapshot).</summary>
|
||||
private async Task<(Guid Id, byte[]? Bytes)> IndexFolderAsync(Archive archive, ArchivePaths paths, SequenceFolder folder, bool reconcile, IndexSnapshot? snapshot,
|
||||
Locations locations, CancellationToken cancellationToken)
|
||||
{
|
||||
var sequence = paths.Sequence(folder.RelativeFolder);
|
||||
SequenceManifest manifest;
|
||||
byte[]? bytes = null;
|
||||
if (folder.Sidecar is not { } stamp)
|
||||
{
|
||||
manifest = await AdoptAsync(sequence, locations, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
bytes = snapshot?.TryGet(folder.RelativeFolder, stamp) ?? await AtomicFile.ReadAllBytesAsync(sequence.ManifestPath, cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
manifest = ManifestStore.ParseSequence(bytes, sequence.ManifestPath);
|
||||
}
|
||||
catch (InvalidDataException ex)
|
||||
{
|
||||
Log.Warning("archive", $"Damaged sidecar in {folder.RelativeFolder}; rebuilding it from the photos", ex);
|
||||
manifest = await ReplaceDamagedAsync(sequence, locations, cancellationToken).ConfigureAwait(false);
|
||||
bytes = null;
|
||||
}
|
||||
}
|
||||
if (locations.IsCopy(paths, manifest.Id, folder.RelativeFolder))
|
||||
{
|
||||
manifest = Reidentify(manifest);
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, manifest);
|
||||
bytes = null;
|
||||
}
|
||||
if (reconcile || File.Exists(sequence.IngestJournalPath))
|
||||
{
|
||||
// Photos added, gone or back clear what covered the frames, and the scan's follow-ups make it again.
|
||||
manifest = await UpdateAndSyncAsync(archive, paths, sequence, manifest.Id, m => Reconcile(sequence, m, cancellationToken), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
bytes = null;
|
||||
}
|
||||
else if (await FramesMovedAsync(manifest, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
// Another process (a desktop sharing the archive, or the server it shares it with) added, removed or renumbered
|
||||
// frames together with their sidecar entries: read again under the lease, under which the project's positions
|
||||
// move, and indexed without what this host makes for the frames (Uncovered).
|
||||
manifest = await UpdateAndSyncAsync(archive, paths, sequence, manifest.Id, _ => null, cancellationToken).ConfigureAwait(false);
|
||||
bytes = null;
|
||||
}
|
||||
else if (await SyncAsync(archive, sequence, manifest, folder, SequenceStatus.None, false, cancellationToken).ConfigureAwait(false) is null)
|
||||
{
|
||||
// Another writer committed between the read and the sync: read again under the lease, as it is now.
|
||||
manifest = await UpdateAndSyncAsync(archive, paths, sequence, manifest.Id, _ => null, cancellationToken).ConfigureAwait(false);
|
||||
bytes = null;
|
||||
}
|
||||
locations.Set(manifest.Id, folder.RelativeFolder);
|
||||
return (manifest.Id, bytes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sequences among <paramref name="locations"/> created without photos that still wait for their first frame: no
|
||||
/// folder, no frames, and not the sequence the archive root's sidecar names. Their empty folder is not the archive
|
||||
/// root: scans do not adopt or rebuild the root under their id, a rebuild keeps them although they have no sidecar yet,
|
||||
/// orphan checks do not count them missing, and maintenance leaves the root's files to the root's own sequence. Unlike
|
||||
/// <see cref="ArchiveIngest.AwaitsFolder"/>, whose commit reports it, a root sidecar that cannot be read names nobody
|
||||
/// here: a scan rebuilds a damaged one under the id of the sequence that holds the root's frames, and one it may not
|
||||
/// read fails the root folder alone rather than the whole scan or rebuild.
|
||||
/// </summary>
|
||||
internal async Task<HashSet<Guid>> AwaitingFolderAsync(ArchivePaths paths, IEnumerable<SequenceLocation> locations, CancellationToken cancellationToken)
|
||||
{
|
||||
var awaiting = new HashSet<Guid>();
|
||||
(Guid? Id, bool Read) root = (null, false);
|
||||
foreach (var location in locations.Where(l => l.Folder.Length == 0))
|
||||
{
|
||||
if (await _db.Sequences.GetAsync(location.Id, cancellationToken).ConfigureAwait(false) is not { Folder.Length: 0, FrameCount: 0 } sequence) continue;
|
||||
// Read once, and only when a row may be waiting: a root sidecar can list a hundred thousand frames.
|
||||
if (!root.Read) root = (RootSidecarId(paths), true);
|
||||
if (root.Id != sequence.Id) awaiting.Add(sequence.Id);
|
||||
}
|
||||
return awaiting;
|
||||
}
|
||||
|
||||
/// <summary>The id the archive root's sidecar names; null when there is none or it cannot be read.</summary>
|
||||
private static Guid? RootSidecarId(ArchivePaths paths)
|
||||
{
|
||||
var sidecar = paths.Sequence(string.Empty).ManifestPath;
|
||||
try
|
||||
{
|
||||
return File.Exists(sidecar) ? ManifestStore.ReadSequence(sidecar).Id : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
|
||||
{
|
||||
// Indexing the root reports it (a damaged sidecar is rebuilt, an unreadable one fails that folder alone).
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The index holds this sequence with other frames than the sidecar: another process changed them (its project's
|
||||
/// positions may move, and what covered the frames no longer does).
|
||||
/// </summary>
|
||||
private async Task<bool> FramesMovedAsync(SequenceManifest manifest, CancellationToken cancellationToken) =>
|
||||
await _db.Sequences.GetAsync(manifest.Id, cancellationToken).ConfigureAwait(false) is { } indexed
|
||||
&& await OtherFramesAsync(_db, indexed, manifest, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <summary>
|
||||
/// Whether the index row <paramref name="indexed"/> holds other frames than <paramref name="manifest"/>: another frames
|
||||
/// version, or the same version over other frames (ids, or their order). Each index of a shared archive bumps a sidecar
|
||||
/// put back behind its own row one version past that row (<see cref="SyncAsync"/>), and another index may hold that
|
||||
/// very version for the frames as they were before: that index still sees the change, and bumps past it in turn.
|
||||
/// </summary>
|
||||
private static async Task<bool> OtherFramesAsync(ChronosRepositories db, Sequence indexed, SequenceManifest manifest, CancellationToken cancellationToken)
|
||||
{
|
||||
if (indexed.FramesVersion != manifest.Versions.Frames) return true;
|
||||
var rows = await db.Frames.ListPositionsAsync(indexed.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (rows.Count != manifest.Frames.Count) return true;
|
||||
var listed = new Dictionary<int, Guid>(manifest.Frames.Count);
|
||||
foreach (var frame in manifest.Frames) listed[frame.I] = frame.Id;
|
||||
return rows.Any(row => !listed.TryGetValue(row.Index, out var id) || id != row.FrameId);
|
||||
}
|
||||
|
||||
/// <summary>A sidecar for a folder that has none; ids of a sequence the index already knew at this folder are kept.</summary>
|
||||
private async Task<SequenceManifest> AdoptAsync(SequencePaths sequence, Locations locations, CancellationToken cancellationToken)
|
||||
{
|
||||
var known = locations.AtFolder(sequence.RelativeFolder);
|
||||
var manifest = await WithKnownFrameIdsAsync(SequenceAdopter.Build(known ?? Guid.CreateVersion7(), sequence, _writer.Options.Owner, cancellationToken),
|
||||
sequence, cancellationToken).ConfigureAwait(false);
|
||||
Directory.CreateDirectory(sequence.MetaDirectory);
|
||||
// Another process may adopt the same folder at the same moment: the first sidecar wins.
|
||||
return ManifestStore.TryCreateSequence(sequence.ManifestPath, manifest) ? manifest : ManifestStore.ReadSequence(sequence.ManifestPath);
|
||||
}
|
||||
|
||||
/// <summary>Keeps the unreadable sidecar aside (never deleted) and builds a new one from the photos.</summary>
|
||||
private async Task<SequenceManifest> ReplaceDamagedAsync(SequencePaths sequence, Locations locations, CancellationToken cancellationToken)
|
||||
{
|
||||
File.Move(sequence.ManifestPath, $"{sequence.ManifestPath}.damaged-{DateTime.UtcNow:yyyyMMddHHmmss}");
|
||||
return await AdoptAsync(sequence, locations, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<SequenceManifest> WithKnownFrameIdsAsync(SequenceManifest manifest, SequencePaths sequence, CancellationToken cancellationToken)
|
||||
{
|
||||
var known = new Dictionary<string, Guid>(StringComparer.Ordinal);
|
||||
var prefix = sequence.ArchiveRelative(string.Empty);
|
||||
for (var after = -1; ;)
|
||||
{
|
||||
var page = await _db.Frames.ListBySequenceAsync(manifest.Id, after, 1000, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var f in page)
|
||||
{
|
||||
if (f.RelativePath.StartsWith(prefix, StringComparison.Ordinal)) known[f.RelativePath[prefix.Length..]] = f.Id;
|
||||
}
|
||||
if (page.Count < 1000) break;
|
||||
after = page[^1].Index;
|
||||
}
|
||||
if (known.Count == 0) return manifest;
|
||||
return manifest with { Frames = manifest.Frames.Select(f => known.TryGetValue(f.File, out var id) ? f with { Id = id } : f).ToList() };
|
||||
}
|
||||
|
||||
/// <summary>A copied sequence folder carries the ids of its source; the copy gets ids of its own.</summary>
|
||||
private static SequenceManifest Reidentify(SequenceManifest manifest) => manifest with
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Frames = manifest.Frames.Select(f => f with { Id = Guid.CreateVersion7() }).ToList(),
|
||||
SessionKeys = [],
|
||||
UpdatedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Rebuild only: rows whose folder no longer holds a sidecar leave the index (their files are untouched). A sequence
|
||||
/// waiting for its first frame has no sidecar yet and stays. A row the folders listed when the rebuild began do not
|
||||
/// back is looked at again under its lease, as it and its folder are when it would go (<see cref="BackedAsync"/>):
|
||||
/// uploads go on during a rebuild, which can take minutes, so a sequence that got its first frame or was created
|
||||
/// meanwhile has a folder the listing does not hold.
|
||||
/// </summary>
|
||||
private async Task<int> RemoveUnbackedAsync(Archive archive, ArchivePaths paths, IReadOnlyList<SequenceFolder> folders, Locations locations,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
var present = folders.Where(f => File.Exists(paths.Sequence(f.RelativeFolder).ManifestPath)).Select(f => f.RelativeFolder).ToHashSet(StringComparer.Ordinal);
|
||||
var rows = await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false);
|
||||
var awaiting = await AwaitingFolderAsync(paths, rows, cancellationToken).ConfigureAwait(false);
|
||||
var removed = 0;
|
||||
foreach (var location in rows)
|
||||
{
|
||||
if (awaiting.Contains(location.Id) || (present.Contains(location.Folder) && locations.AtFolder(location.Folder) == location.Id)) continue;
|
||||
IAsyncDisposable held;
|
||||
try
|
||||
{
|
||||
held = await _writer.LockAsync(paths, location.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (LeaseUnavailableException)
|
||||
{
|
||||
// Another process is writing the sequence, so it is there.
|
||||
continue;
|
||||
}
|
||||
await using (held)
|
||||
{
|
||||
if (await BackedAsync(paths, location.Id, cancellationToken).ConfigureAwait(false)) continue;
|
||||
if (await _db.Sequences.DeleteAsync(location.Id, cancellationToken).ConfigureAwait(false)) removed++;
|
||||
await _db.Archives.DeleteFolderStateAsync(archive.Id, location.Folder, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the index row of <paramref name="sequenceId"/> keeps its place as it is now: it waits for its first frame,
|
||||
/// its folder holds a sidecar naming it (one that cannot be read proves nothing), or it is gone already.
|
||||
/// </summary>
|
||||
private async Task<bool> BackedAsync(ArchivePaths paths, Guid sequenceId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) is not { } row) return true;
|
||||
if ((await AwaitingFolderAsync(paths, [new SequenceLocation(row.Id, row.Folder, row.Title)], cancellationToken).ConfigureAwait(false)).Count > 0)
|
||||
return true;
|
||||
var sidecar = paths.Sequence(row.Folder).ManifestPath;
|
||||
try
|
||||
{
|
||||
return File.Exists(sidecar) && ManifestStore.ReadSequence(sidecar).Id == sequenceId;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Which folder each indexed sequence id lives in, updated as the scan goes.</summary>
|
||||
private sealed class Locations
|
||||
{
|
||||
private readonly Dictionary<Guid, string> _byId = [];
|
||||
private readonly Dictionary<string, Guid> _byFolder = new(StringComparer.Ordinal);
|
||||
|
||||
public Locations(IEnumerable<SequenceLocation> rows)
|
||||
{
|
||||
foreach (var row in rows) Set(row.Id, row.Folder);
|
||||
}
|
||||
|
||||
public Guid? AtFolder(string folder) => _byFolder.TryGetValue(folder, out var id) ? id : null;
|
||||
|
||||
/// <summary>The id is indexed at another folder whose sidecar still carries it: this folder is a copy.</summary>
|
||||
public bool IsCopy(ArchivePaths paths, Guid id, string folder)
|
||||
{
|
||||
if (!_byId.TryGetValue(id, out var other) || other == folder) return false;
|
||||
var otherSidecar = paths.Sequence(other).ManifestPath;
|
||||
try
|
||||
{
|
||||
return File.Exists(otherSidecar) && ManifestStore.ReadSequence(otherSidecar).Id == id;
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void Set(Guid id, string folder)
|
||||
{
|
||||
if (_byId.TryGetValue(id, out var previous) && _byFolder.GetValueOrDefault(previous) == id) _byFolder.Remove(previous);
|
||||
_byId[id] = folder;
|
||||
_byFolder[folder] = id;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,541 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Metadata;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Naming;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>A verified staged file and how to name it.</summary>
|
||||
/// <param name="PlannedName">Name chosen by an import plan; null = the archive's file template.</param>
|
||||
internal sealed record StagedFrame(string StagedPath, string OriginalFileName, long Size, string Sha256, FrameMetadata Metadata,
|
||||
DateTime? ClientCapturedAt, string? PlannedName);
|
||||
|
||||
/// <summary>A sequence found or created by key (upload session, card session, or a new title).</summary>
|
||||
/// <param name="PreferredFolder">Folder of an import plan; null = the archive's folder template.</param>
|
||||
internal sealed record SequenceTarget(string Key, string? Title, string? PreferredFolder, string? CreatedBy);
|
||||
|
||||
/// <summary>
|
||||
/// Commits staged, verified files into sequences (BRIEF §4.3, §14.4): the file is renamed into the sequence folder
|
||||
/// under the naming template, the sidecar is rewritten atomically in capture order and the index follows. Commits
|
||||
/// to one sequence are serialised and batched (concurrent uploads share one sidecar write); a lease file keeps
|
||||
/// other processes out meanwhile, and a write-ahead journal repairs a batch interrupted by a crash. A file whose
|
||||
/// SHA-256 an intact frame of the sequence already holds is reported as a duplicate and left in staging; a frame with
|
||||
/// that SHA-256 that is flagged missing or corrupt, or whose file is gone or has another size, is repaired with it
|
||||
/// instead (its damaged file kept beside it). A sequence created without photos gets its folder with its first frame.
|
||||
/// </summary>
|
||||
public sealed class ArchiveIngest : IArchiveIngest
|
||||
{
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly SequenceWriter _writer;
|
||||
private readonly ArchiveIndexer _indexer;
|
||||
private readonly ConcurrentDictionary<Guid, CommitQueue> _queues = new();
|
||||
private readonly SemaphoreSlim _creation = new(1, 1);
|
||||
|
||||
internal ArchiveIngest(ChronosDatabase db, SequenceWriter writer, ArchiveIndexer indexer)
|
||||
{
|
||||
_db = db;
|
||||
_writer = writer;
|
||||
_indexer = indexer;
|
||||
}
|
||||
|
||||
public async Task<IngestResult> CommitAsync(IngestRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if ((request.SequenceId is null ? 0 : 1) + (request.NewSequenceTitle is null ? 0 : 1) + (request.SessionKey is null ? 0 : 1) != 1)
|
||||
throw new ArgumentException("Exactly one of SequenceId, NewSequenceTitle or SessionKey selects the target.", nameof(request));
|
||||
var archive = await _db.Archives.GetAsync(request.ArchiveId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ArgumentException($"Unknown archive {request.ArchiveId}.", nameof(request));
|
||||
var staged = new FileInfo(request.StagedPath);
|
||||
if (!staged.Exists || staged.Length != request.Size)
|
||||
throw new FileNotFoundException("The staged file is missing or has another size.", request.StagedPath);
|
||||
var frame = new StagedFrame(request.StagedPath, request.OriginalFileName, request.Size, request.Sha256,
|
||||
MetadataReader.Read(request.StagedPath, cancellationToken), request.ClientCapturedAt, null);
|
||||
|
||||
Guid sequenceId;
|
||||
if (request.SequenceId is { } id)
|
||||
{
|
||||
var sequence = await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
if (sequence?.ArchiveId != archive.Id) throw new ArgumentException($"Sequence {id} is not in archive {archive.Id}.", nameof(request));
|
||||
if (AwaitsFolder(sequence, new ArchivePaths(archive.RootPath))) await PlaceAsync(archive, id, frame, cancellationToken).ConfigureAwait(false);
|
||||
sequenceId = id;
|
||||
}
|
||||
else
|
||||
{
|
||||
// A title names one sequence per user: parallel uploads for "new sequence X" all land in the same one.
|
||||
var key = request.SessionKey ?? $"title:{request.UserId:N}:{request.NewSequenceTitle!.Trim().ToLowerInvariant()}";
|
||||
sequenceId = await FindOrCreateAsync(archive, new SequenceTarget(key, request.NewSequenceTitle?.Trim(), null, request.UserId?.ToString()),
|
||||
frame, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
return (await EnqueueAsync(archive, sequenceId, [frame], cancellationToken).ConfigureAwait(false))[0];
|
||||
}
|
||||
|
||||
/// <summary>Commits files of one import session into the sequence of its key (created on first use).</summary>
|
||||
internal async Task<IReadOnlyList<IngestResult>> CommitSessionAsync(Archive archive, SequenceTarget target, IReadOnlyList<StagedFrame> frames,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (frames.Count == 0) return [];
|
||||
var sequenceId = await FindOrCreateAsync(archive, target, frames[0], cancellationToken).ConfigureAwait(false);
|
||||
return await EnqueueAsync(archive, sequenceId, frames, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<Guid> FindOrCreateAsync(Archive archive, SequenceTarget target, StagedFrame first, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await _db.Sequences.FindBySessionKeyAsync(archive.Id, target.Key, cancellationToken).ConfigureAwait(false) is { } found) return found;
|
||||
await _creation.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (await _db.Sequences.FindBySessionKeyAsync(archive.Id, target.Key, cancellationToken).ConfigureAwait(false) is { } again) return again;
|
||||
return await CreateAsync(archive, target, first, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_creation.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<Guid> CreateAsync(Archive archive, SequenceTarget target, StagedFrame first, CancellationToken cancellationToken)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var m = first.Metadata;
|
||||
var manifest = new SequenceManifest
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Title = target.Title,
|
||||
Camera = new SidecarCamera { Make = m.Make, Model = m.Model, Serial = m.BodySerial },
|
||||
Lens = m.LensModel,
|
||||
SessionKeys = [target.Key],
|
||||
CreatedBy = target.CreatedBy,
|
||||
Created = now,
|
||||
UpdatedAt = now,
|
||||
};
|
||||
var sequence = await ClaimNewFolderAsync(archive, paths, target.PreferredFolder, first, manifest, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, null), cancellationToken).ConfigureAwait(false);
|
||||
var winner = await tx.Sequences.MapSessionKeyAsync(archive.Id, target.Key, manifest.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (winner != manifest.Id)
|
||||
{
|
||||
// Another process bound the key first: its sequence wins, ours was never used.
|
||||
await tx.RollbackAsync(cancellationToken).ConfigureAwait(false);
|
||||
ReleaseFolder(sequence);
|
||||
return winner;
|
||||
}
|
||||
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
await _indexer.RecordStampsAsync(archive, sequence, manifest.Id, cancellationToken).ConfigureAwait(false);
|
||||
return manifest.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A sequence created without photos (<c>POST /api/v1/sequences</c>, BRIEF §14.3) has no folder until its first frame.
|
||||
/// An empty folder otherwise means the archive root itself, adopted in place, whose sidecar names the sequence; one
|
||||
/// that holds frames is never moved elsewhere, even while its root sidecar is missing.
|
||||
/// </summary>
|
||||
internal static bool AwaitsFolder(Sequence sequence, ArchivePaths paths)
|
||||
{
|
||||
if (sequence.Folder.Length > 0 || sequence.FrameCount > 0) return false;
|
||||
var root = paths.Sequence(string.Empty);
|
||||
if (!File.Exists(root.ManifestPath)) return true;
|
||||
try
|
||||
{
|
||||
return ManifestStore.ReadSequence(root.ManifestPath).Id != sequence.Id;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException)
|
||||
{
|
||||
// An unreadable root sidecar: the commit reports it rather than placing the sequence elsewhere.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gives a sequence created without photos its folder, named from its first frame and title by the same rules as a
|
||||
/// sequence created by an upload, with a sidecar carrying the row's id, title, tags, rating and notes (and its project
|
||||
/// when one was saved); the index row takes the folder in one transaction. Serialised with the creation of sequences.
|
||||
/// </summary>
|
||||
private async Task PlaceAsync(Archive archive, Guid sequenceId, StagedFrame first, CancellationToken cancellationToken)
|
||||
{
|
||||
await _creation.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var row = await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException($"Sequence {sequenceId} is not indexed.");
|
||||
// A concurrent first frame placed it meanwhile.
|
||||
if (!AwaitsFolder(row, paths)) return;
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var m = first.Metadata;
|
||||
var manifest = new SequenceManifest
|
||||
{
|
||||
Id = row.Id,
|
||||
Title = row.Title,
|
||||
// The photo names its camera; the creator's hint stands in when it does not.
|
||||
Camera = m.Make is null && m.Model is null && row.CameraModel is not null
|
||||
? new SidecarCamera { Model = row.CameraModel }
|
||||
: new SidecarCamera { Make = m.Make, Model = m.Model, Serial = m.BodySerial },
|
||||
Lens = m.LensModel,
|
||||
Tags = row.Tags,
|
||||
Rating = row.Rating,
|
||||
Notes = row.Notes,
|
||||
Versions = new ManifestVersions { Settings = row.SettingsVersion, Frames = row.FramesVersion },
|
||||
CreatedBy = row.OwnerUserId?.ToString(),
|
||||
Created = now,
|
||||
UpdatedAt = now,
|
||||
};
|
||||
var sequence = await ClaimNewFolderAsync(archive, paths, null, first, manifest, cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (row.SettingsJson is { } settings) AtomicFile.WriteAllText(sequence.ProjectPath, settings);
|
||||
await using var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
// Locked, so an edit of the new sequence committed meanwhile is not written back over.
|
||||
var current = await tx.Sequences.GetForUpdateAsync(sequenceId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException($"Sequence {sequenceId} was deleted before its first frame.");
|
||||
await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, current), cancellationToken).ConfigureAwait(false);
|
||||
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Nothing was filed into the folder yet: it goes, and the next first frame claims one again.
|
||||
if (File.Exists(sequence.ProjectPath)) File.Delete(sequence.ProjectPath);
|
||||
ReleaseFolder(sequence);
|
||||
throw;
|
||||
}
|
||||
await _indexer.RecordStampsAsync(archive, sequence, manifest.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_creation.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A new folder for <paramref name="manifest"/>: the plan's folder or the archive's folder template, made unique.</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));
|
||||
if (wanted.Length == 0) wanted = "Sequence";
|
||||
var taken = (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false))
|
||||
.Select(l => l.Folder).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
return ClaimFolder(paths, wanted, taken, manifest);
|
||||
}
|
||||
|
||||
/// <summary>The first free variant of <paramref name="wanted"/>, claimed by creating its sidecar (first writer wins).</summary>
|
||||
private static SequencePaths ClaimFolder(ArchivePaths paths, string wanted, HashSet<string> taken, SequenceManifest manifest)
|
||||
{
|
||||
for (var n = 1; ; n++)
|
||||
{
|
||||
var folder = n == 1 ? wanted : string.Create(CultureInfo.InvariantCulture, $"{wanted} ({n})");
|
||||
if (taken.Contains(folder)) continue;
|
||||
var sequence = paths.Sequence(folder);
|
||||
if (Directory.Exists(sequence.Folder) && Directory.EnumerateFileSystemEntries(sequence.Folder).Any()) continue;
|
||||
Directory.CreateDirectory(sequence.MetaDirectory);
|
||||
if (ManifestStore.TryCreateSequence(sequence.ManifestPath, manifest)) return sequence;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Removes the empty sequence this process created and lost to a concurrent creator.</summary>
|
||||
private static void ReleaseFolder(SequencePaths sequence)
|
||||
{
|
||||
File.Delete(sequence.ManifestPath);
|
||||
if (!Directory.EnumerateFileSystemEntries(sequence.MetaDirectory).Any()) Directory.Delete(sequence.MetaDirectory);
|
||||
if (!Directory.EnumerateFileSystemEntries(sequence.Folder).Any()) Directory.Delete(sequence.Folder);
|
||||
}
|
||||
|
||||
/// <summary>Group commit: whoever gets the sequence's gate commits everything queued for it.</summary>
|
||||
private async Task<IngestResult[]> EnqueueAsync(Archive archive, Guid sequenceId, IReadOnlyList<StagedFrame> frames, CancellationToken cancellationToken)
|
||||
{
|
||||
var queue = _queues.GetOrAdd(sequenceId, _ => new CommitQueue());
|
||||
var pending = frames.Select(f => new Pending(f)).ToList();
|
||||
foreach (var p in pending) queue.Items.Enqueue(p);
|
||||
await queue.Gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (pending.Any(p => !p.Completion.Task.IsCompleted))
|
||||
{
|
||||
var batch = new List<Pending>();
|
||||
while (queue.Items.TryDequeue(out var p)) batch.Add(p);
|
||||
try
|
||||
{
|
||||
await CommitBatchAsync(archive, sequenceId, batch, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
foreach (var p in batch) p.Completion.TrySetException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
queue.Gate.Release();
|
||||
}
|
||||
return await Task.WhenAll(pending.Select(p => p.Completion.Task)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task CommitBatchAsync(Archive archive, Guid sequenceId, List<Pending> batch, CancellationToken cancellationToken)
|
||||
{
|
||||
var row = await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
|
||||
?? 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 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
|
||||
// resync leaves to the next one (ArchiveIndexer.PhotosChangedAsync).
|
||||
var inStep = await _indexer.InStepAsync(archive, sequence, manifest, cancellationToken).ConfigureAwait(false);
|
||||
var photosChanged = !inStep && await _indexer.PhotosChangedAsync(archive, sequence, cancellationToken).ConfigureAwait(false);
|
||||
var before = manifest.Frames.Count;
|
||||
var held = manifest.Frames.Where(f => f.Sha256 is not null).ToLookup(f => f.Sha256!, StringComparer.OrdinalIgnoreCase);
|
||||
// Content this batch files (new frames and repairs): another copy of it in the batch is a duplicate of that frame.
|
||||
var filed = new Dictionary<string, Guid>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
var accepted = new List<(Pending Pending, SidecarFrame Frame)>();
|
||||
var repairs = new List<(Pending Pending, SidecarFrame Frame)>();
|
||||
var duplicates = new List<(Pending Pending, Guid FrameId)>();
|
||||
foreach (var p in batch)
|
||||
{
|
||||
if (filed.TryGetValue(p.Frame.Sha256, out var same))
|
||||
{
|
||||
duplicates.Add((p, same));
|
||||
continue;
|
||||
}
|
||||
// Only a frame that still holds the content makes this copy a duplicate; a missing or damaged one is repaired with it.
|
||||
var holders = held[p.Frame.Sha256];
|
||||
if (holders.FirstOrDefault(f => IsIntact(sequence, f)) is { } intact)
|
||||
{
|
||||
duplicates.Add((p, intact.Id));
|
||||
continue;
|
||||
}
|
||||
if (holders.FirstOrDefault() is { } damaged)
|
||||
{
|
||||
filed[p.Frame.Sha256] = damaged.Id;
|
||||
repairs.Add((p, damaged));
|
||||
continue;
|
||||
}
|
||||
var frame = SequenceFrames.FromMetadata(Guid.CreateVersion7(), p.Frame.OriginalFileName, p.Frame.OriginalFileName, p.Frame.Size,
|
||||
p.Frame.Sha256, p.Frame.Metadata, p.Frame.ClientCapturedAt);
|
||||
filed[p.Frame.Sha256] = frame.Id;
|
||||
accepted.Add((p, frame));
|
||||
}
|
||||
|
||||
var named = Name(archive, sequence, manifest, accepted);
|
||||
IngestJournal.Write(sequence, new IngestJournal(named.Values.ToList()));
|
||||
var moved = new List<SidecarFrame>();
|
||||
foreach (var (p, frame) in accepted)
|
||||
{
|
||||
var final = named[frame.Id];
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(sequence.File(final.File))!);
|
||||
File.Move(p.Frame.StagedPath, sequence.File(final.File), overwrite: false);
|
||||
moved.Add(final);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
p.Completion.TrySetException(ex);
|
||||
}
|
||||
}
|
||||
var repaired = new HashSet<Guid>();
|
||||
foreach (var (p, frame) in repairs)
|
||||
{
|
||||
if (Repair(sequence, frame, p.Frame.StagedPath) is { } error) p.Completion.TrySetException(error);
|
||||
else repaired.Add(frame.Id);
|
||||
}
|
||||
var updated = SequenceFrames.Insert(manifest, moved);
|
||||
if (repaired.Count > 0)
|
||||
{
|
||||
updated = SequenceFrames.Update(updated, repaired.ToDictionary(id => id,
|
||||
_ => (Func<SidecarFrame, SidecarFrame>)(f => f with { Flags = f.Flags & ~(FrameFlags.Missing | FrameFlags.Corrupt) })));
|
||||
}
|
||||
if (moved.Count > 0 || repaired.Count > 0) ManifestStore.WriteSequence(sequence.ManifestPath, updated);
|
||||
IngestJournal.Delete(sequence);
|
||||
|
||||
var byId = updated.Frames.ToDictionary(f => f.Id);
|
||||
if (moved.Count > 0 || repaired.Count > 0)
|
||||
{
|
||||
await IndexAsync(archive, sequence, updated, inStep, photosChanged, before, moved.ConvertAll(m => byId[m.Id]), repaired.Count > 0,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
foreach (var (p, frame) in accepted.Where(a => byId.ContainsKey(a.Frame.Id)))
|
||||
p.Completion.TrySetResult(Result(sequenceId, sequence, byId[frame.Id], false));
|
||||
foreach (var (p, frame) in repairs.Where(r => repaired.Contains(r.Frame.Id)))
|
||||
p.Completion.TrySetResult(Result(sequenceId, sequence, byId[frame.Id], false) with { Repaired = true });
|
||||
var unrepaired = repairs.Select(r => r.Frame.Id).Where(id => !repaired.Contains(id)).ToHashSet();
|
||||
foreach (var (p, frameId) in duplicates)
|
||||
{
|
||||
// A copy of content this batch failed to file has nothing intact to stand for it.
|
||||
if (byId.TryGetValue(frameId, out var original) && !unrepaired.Contains(frameId))
|
||||
p.Completion.TrySetResult(Result(sequenceId, sequence, original, true));
|
||||
else p.Completion.TrySetException(new IOException(Loc.L("Archive.Error.DuplicateLost", p.Frame.OriginalFileName)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Final file names, in capture order: the plan's name or the template with <c>{n}</c> = index + 1, made unique.</summary>
|
||||
private static Dictionary<Guid, SidecarFrame> Name(Archive archive, SequencePaths sequence, SequenceManifest manifest,
|
||||
List<(Pending Pending, SidecarFrame Frame)> accepted)
|
||||
{
|
||||
var merged = SequenceFrames.Insert(manifest, accepted.ConvertAll(a => a.Frame));
|
||||
var incoming = accepted.ToDictionary(a => a.Frame.Id);
|
||||
// Photos adopted in place stay in place; everything else goes to originals/.
|
||||
var directory = Directory.Exists(sequence.Originals) || manifest.Frames.Count == 0 || manifest.Frames.Any(f => f.File.Contains('/'))
|
||||
? ArchiveLayout.OriginalsFolder + "/"
|
||||
: string.Empty;
|
||||
var taken = new HashSet<string>(manifest.Frames.Select(f => f.File), StringComparer.OrdinalIgnoreCase);
|
||||
var onDisk = Path.Combine(sequence.Folder, directory);
|
||||
if (Directory.Exists(onDisk))
|
||||
{
|
||||
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 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)}");
|
||||
named[frame.Id] = entry.Frame with { File = file };
|
||||
}
|
||||
return named;
|
||||
}
|
||||
|
||||
/// <summary>The frame still holds its content: not flagged missing or corrupt, and its file is there with its size.</summary>
|
||||
private static bool IsIntact(SequencePaths sequence, SidecarFrame frame)
|
||||
{
|
||||
if ((frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0) return false;
|
||||
var file = new FileInfo(sequence.File(frame.File));
|
||||
return file.Exists && file.Length == frame.Size;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts a verified copy where a damaged frame's file belongs. A file still there (corrupt, or another size) moves aside
|
||||
/// as <c>name.damaged-<time></c>, which no scan takes for a photo, and is never deleted (BRIEF §0.2 rule 8); it comes
|
||||
/// back when the copy cannot be moved in. Returns the failure, or null.
|
||||
/// </summary>
|
||||
private static Exception? Repair(SequencePaths sequence, SidecarFrame frame, string stagedPath)
|
||||
{
|
||||
var target = sequence.File(frame.File);
|
||||
string? aside = null;
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
||||
if (File.Exists(target))
|
||||
{
|
||||
aside = string.Create(CultureInfo.InvariantCulture, $"{target}.damaged-{DateTime.UtcNow:yyyyMMddHHmmss}");
|
||||
File.Move(target, aside, overwrite: false);
|
||||
}
|
||||
File.Move(stagedPath, target, overwrite: false);
|
||||
Log.Info("archive", $"Repaired {sequence.ArchiveRelative(frame.File)} with a verified copy");
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
if (aside is not null && !File.Exists(target) && File.Exists(aside))
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Move(aside, target);
|
||||
}
|
||||
catch (Exception again) when (again is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"{aside} stays beside {target}", again);
|
||||
}
|
||||
}
|
||||
return ex;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends the new rows when the index held the folder as it was before this batch and the batch only appended frames;
|
||||
/// otherwise resyncs the whole sequence from the sidecar, which also moves the project's frame positions after an
|
||||
/// insertion. That covers frames repaired (their flags change) and what another process changed in the sidecar alone
|
||||
/// (a desktop's verify, decode tiers, duplicates or title): the appended rows and the scan stamps recorded after them
|
||||
/// would otherwise keep it out of this index until a full scan. A project waiting for photos taken from another
|
||||
/// copy's settings places those that arrived either way.
|
||||
/// </summary>
|
||||
/// <param name="inStep">Whether the index held the folder as it was when the batch read the sidecar under the lease
|
||||
/// (<see cref="ArchiveIndexer.InStepAsync(Archive, SequencePaths, SequenceManifest, CancellationToken)"/>).</param>
|
||||
/// <param name="photosChanged">Whether the photo directory had changed since the last scan when the batch began
|
||||
/// (<see cref="ArchiveIndexer.PhotosChangedAsync"/>): the resync, which indexes the sidecar, keeps the recorded photo
|
||||
/// stamp so the next incremental scan reconciles those photos.</param>
|
||||
private async Task IndexAsync(Archive archive, SequencePaths sequence, SequenceManifest manifest, bool inStep, bool photosChanged, int before,
|
||||
List<SidecarFrame> appended, bool repaired, CancellationToken cancellationToken)
|
||||
{
|
||||
var append = inStep && !repaired && appended.All(f => f.I >= before)
|
||||
&& await _db.Frames.CountBySequenceAsync(manifest.Id, cancellationToken).ConfigureAwait(false) == before;
|
||||
if (!append)
|
||||
{
|
||||
await _indexer.SyncAsync(archive, sequence, manifest, null, SequenceStatus.None, photosChanged, cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
PositionMove? placed = null;
|
||||
await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
// Locked: a settings edit committed after this read (the server's PATCH takes no lease) would be written back over.
|
||||
var existing = await tx.Sequences.GetForUpdateAsync(manifest.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (existing is not null && ProjectPositions.Place(existing, manifest) is { } positions)
|
||||
{
|
||||
placed = positions;
|
||||
existing = positions.ApplyTo(existing);
|
||||
}
|
||||
await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, existing), cancellationToken).ConfigureAwait(false);
|
||||
await tx.Frames.BulkInsertAsync(appended.Select(f => SequenceMapping.ToFrame(f, manifest.Id, sequence)), cancellationToken).ConfigureAwait(false);
|
||||
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
if (placed is not null) ProjectPositions.WriteProject(sequence, placed.Before, placed.Moved);
|
||||
await _indexer.RecordStampsAsync(archive, sequence, manifest.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
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);
|
||||
public ConcurrentQueue<Pending> Items { get; } = new();
|
||||
}
|
||||
|
||||
private sealed class Pending(StagedFrame frame)
|
||||
{
|
||||
public StagedFrame Frame { get; } = frame;
|
||||
public TaskCompletionSource<IngestResult> Completion { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>Frames sharing one SHA-256; the first (earliest sequence, lowest index) counts as the original.</summary>
|
||||
public sealed record DuplicateGroup(string Sha256, IReadOnlyList<DuplicateFrame> Frames);
|
||||
|
||||
/// <summary>Index and disk out of step (BRIEF §12.5 Orphans).</summary>
|
||||
/// <param name="Sequences">Per indexed sequence: photos the sidecar does not list and frames whose file is gone.</param>
|
||||
/// <param name="MissingSequences">Index rows whose folder holds no sidecar any more.</param>
|
||||
/// <param name="UnindexedFolders">Folders with photos or a sidecar that the index does not know yet (a scan adopts them).</param>
|
||||
public sealed record OrphanReport(IReadOnlyList<SequenceOrphans> Sequences, IReadOnlyList<SequenceLocation> MissingSequences, IReadOnlyList<string> UnindexedFolders)
|
||||
{
|
||||
public int UnindexedFiles => Sequences.Sum(s => s.UnindexedFiles.Count);
|
||||
public int MissingFiles => Sequences.Sum(s => s.MissingFiles.Count);
|
||||
}
|
||||
|
||||
/// <summary>What a maintenance run removed or changed (or would, in a dry run).</summary>
|
||||
/// <param name="IndexReclaimable">Bytes of free pages in the SQLite index before the run; null on PostgreSQL (autovacuum) or
|
||||
/// when a resumed run had passed that step.</param>
|
||||
/// <param name="IndexReclaimed">Bytes the index vacuum gave back; 0 in a dry run or when too little was free to rewrite the file.</param>
|
||||
public sealed record MaintenanceReport(
|
||||
bool DryRun,
|
||||
IReadOnlyList<string> StaleLeases,
|
||||
IReadOnlyList<string> TemporaryFiles,
|
||||
IReadOnlyList<string> CompactedPacks,
|
||||
int DuplicateGroups,
|
||||
int DuplicateFlagChanges,
|
||||
int UnindexedFiles,
|
||||
int MissingFiles,
|
||||
long? IndexReclaimable = null,
|
||||
long IndexReclaimed = 0);
|
||||
|
||||
/// <summary>Duplicates, orphans and housekeeping of an archive (BRIEF §12.5). Originals are never touched.</summary>
|
||||
public sealed class ArchiveMaintenance
|
||||
{
|
||||
/// <summary>Staged copies older than this belong to no running import.</summary>
|
||||
private static readonly TimeSpan StagingAge = TimeSpan.FromHours(24);
|
||||
|
||||
/// <summary>Temporary files of atomic writes older than this were left by a crash.</summary>
|
||||
private static readonly TimeSpan TempAge = TimeSpan.FromHours(1);
|
||||
|
||||
/// <summary>Packs with more reclaimable bytes than this share are compacted.</summary>
|
||||
private const double CompactionRatio = 0.3;
|
||||
|
||||
/// <summary>The SQLite index is vacuumed when at least this share of it is free pages: rewriting a large index for a
|
||||
/// few pages would hold its writers for nothing.</summary>
|
||||
internal const double IndexVacuumRatio = 0.1;
|
||||
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly SequenceWriter _writer;
|
||||
private readonly ArchiveIndexer _indexer;
|
||||
|
||||
internal ArchiveMaintenance(ChronosDatabase db, SequenceWriter writer, ArchiveIndexer indexer)
|
||||
{
|
||||
_db = db;
|
||||
_writer = writer;
|
||||
_indexer = indexer;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<DuplicateGroup>> FindDuplicatesAsync(Guid archiveId, CancellationToken cancellationToken = default) =>
|
||||
(await _db.Frames.ListDuplicatesAsync(archiveId, cancellationToken).ConfigureAwait(false))
|
||||
.GroupBy(f => f.Sha256, StringComparer.Ordinal)
|
||||
.Select(g => new DuplicateGroup(g.Key, g.ToList()))
|
||||
.ToList();
|
||||
|
||||
public async Task<OrphanReport> FindOrphansAsync(Archive archive, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
if (ArchiveVolume.Probe(paths) == ArchiveAvailability.Offline) throw new ArchiveOfflineException(paths.Root, ArchiveAvailability.Offline);
|
||||
var all = await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false);
|
||||
// A sequence waiting for its first frame has no folder yet: none of it is missing, and the archive root is not its folder.
|
||||
var awaiting = await _indexer.AwaitingFolderAsync(paths, all, cancellationToken).ConfigureAwait(false);
|
||||
var locations = all.Where(l => !awaiting.Contains(l.Id)).ToList();
|
||||
var sequences = new List<SequenceOrphans>();
|
||||
var missing = new List<SequenceLocation>();
|
||||
foreach (var location in locations)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var sequence = paths.Sequence(location.Folder);
|
||||
if (!File.Exists(sequence.ManifestPath))
|
||||
{
|
||||
missing.Add(location);
|
||||
continue;
|
||||
}
|
||||
var orphans = SequenceAdopter.FindOrphans(sequence, ManifestStore.ReadSequence(sequence.ManifestPath));
|
||||
if (!orphans.IsEmpty) sequences.Add(orphans);
|
||||
}
|
||||
var known = locations.Select(l => l.Folder).ToHashSet(StringComparer.Ordinal);
|
||||
var unindexed = ArchiveScanner.FindSequenceFolders(paths, cancellationToken).Select(f => f.RelativeFolder).Where(f => !known.Contains(f)).ToList();
|
||||
return new OrphanReport(sequences, missing, unindexed);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Drops index rows of sequences whose sidecar is gone (an orphans fix action); rows whose sidecar is back are kept, and
|
||||
/// so are sequences waiting for their first frame (<see cref="ArchiveIngest.AwaitsFolder"/>), which have none yet.
|
||||
/// </summary>
|
||||
public async Task<int> RemoveMissingSequencesAsync(Archive archive, IReadOnlyList<Guid> sequenceIds, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
if (ArchiveVolume.Probe(paths) == ArchiveAvailability.Offline) throw new ArchiveOfflineException(paths.Root, ArchiveAvailability.Offline);
|
||||
var removed = 0;
|
||||
foreach (var id in sequenceIds)
|
||||
{
|
||||
if (await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } sequence || sequence.ArchiveId != archive.Id) continue;
|
||||
if (File.Exists(paths.Sequence(sequence.Folder).ManifestPath) || ArchiveIngest.AwaitsFolder(sequence, paths)) continue;
|
||||
if (await _db.Sequences.DeleteAsync(id, cancellationToken).ConfigureAwait(false)) removed++;
|
||||
await _db.Archives.DeleteFolderStateAsync(archive.Id, sequence.Folder, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
/// <summary>Number of maintenance steps (the job checkpoints after each).</summary>
|
||||
internal const int StepCount = 5;
|
||||
|
||||
/// <summary>Runs the maintenance steps from <paramref name="firstStep"/>: stale leases, leftover temporary files,
|
||||
/// thumbnail pack compaction, duplicate flags, index vacuum (SQLite). A dry run only reports.</summary>
|
||||
public async Task<MaintenanceReport> RunAsync(Archive archive, bool dryRun, int firstStep, Func<int, ValueTask> stepDone,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
if (!dryRun) ArchiveVolume.EnsureWritable(paths);
|
||||
var all = await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false);
|
||||
// A sequence waiting for its first frame has no folder yet: the archive root's pack is compacted under the leases of
|
||||
// the root's own sequence, which its thumbnail passes hold, never under another id's.
|
||||
var awaiting = await _indexer.AwaitingFolderAsync(paths, all, cancellationToken).ConfigureAwait(false);
|
||||
var locations = all.Where(l => !awaiting.Contains(l.Id)).ToList();
|
||||
IReadOnlyList<string> leases = [], temps = [], packs = [];
|
||||
int groups = 0, flagChanges = 0;
|
||||
long? reclaimable = null;
|
||||
long reclaimed = 0;
|
||||
for (var step = firstStep; step < StepCount; step++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
switch (step)
|
||||
{
|
||||
case 0:
|
||||
leases = LeaseFile.CleanupStale(paths.LocksDirectory, dryRun);
|
||||
break;
|
||||
case 1:
|
||||
temps = PurgeTemporaryFiles(paths, locations, dryRun);
|
||||
break;
|
||||
case 2:
|
||||
packs = await CompactPacksAsync(paths, locations, dryRun, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
case 3:
|
||||
(groups, flagChanges) = await FlagDuplicatesAsync(archive, paths, dryRun, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
case 4:
|
||||
(reclaimable, reclaimed) = await VacuumIndexAsync(dryRun, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
await stepDone(step + 1).ConfigureAwait(false);
|
||||
}
|
||||
var orphans = await FindOrphansAsync(archive, cancellationToken).ConfigureAwait(false);
|
||||
return new MaintenanceReport(dryRun, leases, temps, packs, groups, flagChanges, orphans.UnindexedFiles, orphans.MissingFiles, reclaimable, reclaimed);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The SQLite index's free pages, given back by a vacuum when they are at least <see cref="IndexVacuumRatio"/> of the
|
||||
/// file (BRIEF §12.5 "SQLite vacuum"); nothing on PostgreSQL, whose autovacuum does it.
|
||||
/// </summary>
|
||||
private async Task<(long? Reclaimable, long Reclaimed)> VacuumIndexAsync(bool dryRun, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await _db.SpaceAsync(cancellationToken).ConfigureAwait(false) is not { } space) return (null, 0);
|
||||
if (dryRun || space.ReclaimableBytes == 0 || space.ReclaimableBytes < space.FileBytes * IndexVacuumRatio) return (space.ReclaimableBytes, 0);
|
||||
var (before, after) = await _db.VacuumAsync(cancellationToken).ConfigureAwait(false);
|
||||
Log.Info("archive", $"Index vacuumed: {before.FileBytes} → {after.FileBytes} bytes");
|
||||
return (space.ReclaimableBytes, long.Max(0, before.FileBytes - after.FileBytes));
|
||||
}
|
||||
|
||||
/// <summary>Staging copies and atomic-write temporaries left behind by crashes (never originals).</summary>
|
||||
private static List<string> PurgeTemporaryFiles(ArchivePaths paths, IReadOnlyList<SequenceLocation> locations, bool dryRun)
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
var found = new List<string>();
|
||||
void Collect(string directory, string pattern, TimeSpan age, bool recursive)
|
||||
{
|
||||
if (!Directory.Exists(directory)) return;
|
||||
foreach (var file in Directory.EnumerateFiles(directory, pattern, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly))
|
||||
{
|
||||
if (now - File.GetLastWriteTimeUtc(file) > age) found.Add(file);
|
||||
}
|
||||
}
|
||||
Collect(paths.StagingDirectory, "*", StagingAge, recursive: true);
|
||||
Collect(paths.MetaDirectory, ".*.tmp", TempAge, recursive: false);
|
||||
foreach (var location in locations)
|
||||
{
|
||||
var sequence = paths.Sequence(location.Folder);
|
||||
Collect(sequence.MetaDirectory, ".*.tmp", TempAge, recursive: false);
|
||||
Collect(sequence.Proxies, ".*.tmp", TempAge, recursive: false);
|
||||
}
|
||||
if (!dryRun)
|
||||
{
|
||||
foreach (var file in found)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(file);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
Log.Warning("archive", $"Could not remove {file}", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
return found.ConvertAll(paths.ToRelative);
|
||||
}
|
||||
|
||||
private async Task<List<string>> CompactPacksAsync(ArchivePaths paths, IReadOnlyList<SequenceLocation> locations, bool dryRun, CancellationToken cancellationToken)
|
||||
{
|
||||
var compacted = new List<string>();
|
||||
foreach (var location in locations)
|
||||
{
|
||||
var sequence = paths.Sequence(location.Folder);
|
||||
long garbage, length;
|
||||
using (var reader = ThumbPackReader.Open(sequence.ThumbsPackPath))
|
||||
{
|
||||
garbage = reader.GarbageBytes;
|
||||
length = reader.Length;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Sets <see cref="FrameFlags.Duplicate"/> on every copy after the first of each hash and clears it elsewhere.</summary>
|
||||
private async Task<(int Groups, int Changes)> FlagDuplicatesAsync(Archive archive, ArchivePaths paths, bool dryRun, CancellationToken cancellationToken)
|
||||
{
|
||||
var groups = await FindDuplicatesAsync(archive.Id, cancellationToken).ConfigureAwait(false);
|
||||
var wanted = groups.SelectMany(g => g.Frames.Skip(1)).ToDictionary(f => f.FrameId, f => f.SequenceId);
|
||||
var flagged = (await _db.Frames.ListFlaggedAsync(archive.Id, FrameFlags.Duplicate, cancellationToken).ConfigureAwait(false))
|
||||
.ToDictionary(f => f.FrameId, f => f.SequenceId);
|
||||
var set = wanted.Where(w => !flagged.ContainsKey(w.Key)).ToList();
|
||||
var clear = flagged.Where(f => !wanted.ContainsKey(f.Key)).ToList();
|
||||
if (dryRun) return (groups.Count, set.Count + clear.Count);
|
||||
|
||||
foreach (var bySequence in set.Select(s => (s.Key, s.Value, Set: true)).Concat(clear.Select(c => (c.Key, c.Value, Set: false))).GroupBy(x => x.Value))
|
||||
{
|
||||
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))
|
||||
{
|
||||
// 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);
|
||||
var inStep = await _indexer.InStepAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false);
|
||||
ManifestStore.WriteSequence(folder.ManifestPath, SequenceFrames.Update(manifest, changes));
|
||||
var setIds = bySequence.Where(x => x.Set).Select(x => x.Key).ToList();
|
||||
var clearIds = bySequence.Where(x => !x.Set).Select(x => x.Key).ToList();
|
||||
await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
// The row before its frames (SequenceRepository.GetForUpdateAsync), so a scan writing them waits or is waited for.
|
||||
if (await tx.Sequences.GetForUpdateAsync(sequence.Id, cancellationToken).ConfigureAwait(false) is not null)
|
||||
{
|
||||
if (setIds.Count > 0) await tx.Frames.UpdateFlagsAsync(setIds, FrameFlags.Duplicate, FrameFlags.None, cancellationToken).ConfigureAwait(false);
|
||||
if (clearIds.Count > 0) await tx.Frames.UpdateFlagsAsync(clearIds, FrameFlags.None, FrameFlags.Duplicate, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
if (inStep) await _indexer.RecordStampsAsync(archive, folder, sequence.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
return (groups.Count, set.Count + clear.Count);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Naming;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// What the desktop client and the server call to work with archives (BRIEF §7, §12.4, §12.5, §14.4): open, create
|
||||
/// or adopt an archive, read and change its settings, plan and apply mass renames, plan imports and card erases, delete
|
||||
/// sequences into the trash and restore them, query duplicates and orphans, and
|
||||
/// the job handlers for the long operations (enqueue them with <see cref="ArchiveJobs"/>).
|
||||
/// </summary>
|
||||
public sealed class ArchiveService : IJobHandlerProvider
|
||||
{
|
||||
/// <summary>Lease serialising read-modify-write of <c>archive.json</c> between the processes sharing an archive.</summary>
|
||||
private const string SettingsLease = "archive-settings";
|
||||
|
||||
/// <summary>Times a title, tags, rating or notes edit is applied at the version it read before it writes regardless.</summary>
|
||||
private const int InfoEditAttempts = 3;
|
||||
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly SequenceWriter _writer;
|
||||
|
||||
public ArchiveService(ChronosDatabase db, ArchiveServiceOptions? options = null)
|
||||
{
|
||||
_db = db;
|
||||
_writer = new SequenceWriter(options ?? new ArchiveServiceOptions());
|
||||
Indexer = new ArchiveIndexer(db, _writer);
|
||||
Ingest = new ArchiveIngest(db, _writer, Indexer);
|
||||
Verifier = new ArchiveVerifier(db, _writer, Indexer);
|
||||
Maintenance = new ArchiveMaintenance(db, _writer, Indexer);
|
||||
Renamer = new MassRenamer(db, _writer, Indexer);
|
||||
Images = new ArchiveImages(db, _writer, Indexer);
|
||||
Imports = new ImportService(db, Ingest);
|
||||
Trash = new SequenceTrash(db, _writer, Indexer);
|
||||
}
|
||||
|
||||
public ArchiveIndexer Indexer { get; }
|
||||
|
||||
/// <summary>Commits staged files into sequences (server uploads, client card imports).</summary>
|
||||
public ArchiveIngest Ingest { get; }
|
||||
|
||||
public ArchiveVerifier Verifier { get; }
|
||||
public ArchiveMaintenance Maintenance { get; }
|
||||
public MassRenamer Renamer { get; }
|
||||
public ArchiveImages Images { get; }
|
||||
public ImportService Imports { get; }
|
||||
|
||||
/// <summary>Deletes sequences into the archive's trash and restores them.</summary>
|
||||
public SequenceTrash Trash { get; }
|
||||
|
||||
/// <summary>Handlers for scan, rebuild, verify, import, thumbs, proxies and maintenance jobs; register them on the <see cref="JobEngine"/>.</summary>
|
||||
public IReadOnlyList<IJobHandler> CreateJobHandlers() =>
|
||||
[
|
||||
new ScanJobHandler(_db, Indexer, JobKind.Scan, _writer.Options.ImagesAfterScan),
|
||||
new ScanJobHandler(_db, Indexer, JobKind.Rebuild, _writer.Options.ImagesAfterScan),
|
||||
new VerifyJobHandler(_db, Verifier),
|
||||
new ImportJobHandler(_db, Imports),
|
||||
new ImageJobHandler(_db, Images, JobKind.Thumbs),
|
||||
new ImageJobHandler(_db, Images, JobKind.Proxies),
|
||||
new MaintenanceJobHandler(_db, Maintenance),
|
||||
];
|
||||
|
||||
/// <summary>Makes <paramref name="root"/> a new, empty archive and indexes it.</summary>
|
||||
/// <exception cref="InvalidOperationException">The folder already is an archive (open it instead).</exception>
|
||||
public Task<Archive> CreateAsync(string root, string name, LayoutTemplates? templates = null, ProxyPolicy? proxies = null,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
CreateAsync(root, new ArchiveSettings(name, templates ?? new LayoutTemplates(), proxies ?? new ProxyPolicy(), new ThumbnailPolicy()), cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Makes <paramref name="root"/> a new, empty archive with <paramref name="settings"/> and indexes it. A blank name
|
||||
/// 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>
|
||||
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);
|
||||
if (File.Exists(paths.ManifestPath)) throw new InvalidOperationException($"{paths.Root} already is a Chronos archive.");
|
||||
Directory.CreateDirectory(paths.MetaDirectory);
|
||||
var manifest = new ArchiveManifest
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Name = settings.Name.Trim(),
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
LayoutTemplates = settings.Templates,
|
||||
ProxyPolicy = settings.Proxies,
|
||||
ThumbnailPolicy = settings.Thumbnails,
|
||||
};
|
||||
ManifestStore.WriteArchive(paths.ManifestPath, manifest);
|
||||
return await RegisterAsync(paths, manifest, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <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.
|
||||
/// </summary>
|
||||
public async Task<Archive> OpenAsync(string root, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var paths = new ArchivePaths(root);
|
||||
var archive = await RegisterAsync(paths, ManifestStore.ReadArchive(paths.ManifestPath), cancellationToken).ConfigureAwait(false);
|
||||
if (ArchiveVolume.Probe(paths) != ArchiveAvailability.Online) return archive;
|
||||
try
|
||||
{
|
||||
await Renamer.ResumePendingAsync(archive, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
|
||||
{
|
||||
// The journal stays; the next open tries again. The archive itself is usable meanwhile.
|
||||
Log.Warning("archive", $"Resuming an interrupted rename in {paths.Root} failed", ex);
|
||||
}
|
||||
return archive;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens a folder of photos as an archive in place (Welcome "adopt folder"): nothing is moved or renamed; enqueue
|
||||
/// <see cref="ArchiveJobs.Scan"/> with a full pass to write sidecars and index it.
|
||||
/// </summary>
|
||||
public Task<Archive> AdoptAsync(string root, string? name = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var paths = new ArchivePaths(root);
|
||||
return File.Exists(paths.ManifestPath)
|
||||
? OpenAsync(root, cancellationToken)
|
||||
: CreateAsync(root, name ?? Path.GetFileName(paths.Root), null, null, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="AdoptAsync(string, string?, CancellationToken)"/> for a folder that may become a new archive with
|
||||
/// <paramref name="defaults"/> (templates and policies; the folder's name when its name is blank). An existing
|
||||
/// archive keeps its own settings.
|
||||
/// </summary>
|
||||
public Task<Archive> AdoptAsync(string root, ArchiveSettings defaults, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(defaults);
|
||||
return File.Exists(new ArchivePaths(root).ManifestPath) ? OpenAsync(root, cancellationToken) : CreateAsync(root, defaults, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The settings in the archive's <c>archive.json</c>; those of the index (with the default thumbnail policy, which only
|
||||
/// the file keeps) while the file cannot be read.
|
||||
/// </summary>
|
||||
public async Task<ArchiveSettings> GetSettingsAsync(Guid archiveId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false);
|
||||
return TryReadManifest(archive) is { } manifest
|
||||
? ArchiveSettings.Of(manifest)
|
||||
: new ArchiveSettings(archive.Name, new LayoutTemplates { Folder = archive.FolderTemplate, File = archive.FileTemplate },
|
||||
new ProxyPolicy { LongEdge = archive.ProxyLongEdge }, new ThumbnailPolicy());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The settings in the archive's <c>archive.json</c>, with its index row brought up to them when another process
|
||||
/// sharing the archive changed the file (a server's admin panel, another PC's Settings): imports and uploads take their
|
||||
/// templates and proxy size from that row. Null while the file cannot be read (offline, damaged, newer, of another
|
||||
/// archive): the row stays as it is, and only <see cref="GetSettingsAsync"/>'s stand-ins are known.
|
||||
/// </summary>
|
||||
public async Task<ArchiveSettings?> RefreshSettingsAsync(Guid archiveId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false);
|
||||
if (TryReadManifest(archive) is not { } manifest) return null;
|
||||
var settings = ArchiveSettings.Of(manifest);
|
||||
if (!settings.IsRegisteredIn(archive))
|
||||
{
|
||||
// Read without the settings lease, as at open: an edit made meanwhile writes its own row, and the next refresh
|
||||
// settles a file that changes again.
|
||||
await RegisterAsync(new ArchivePaths(archive.RootPath), manifest, cancellationToken).ConfigureAwait(false);
|
||||
Log.Info("archive", $"Settings of {archive.RootPath} changed elsewhere: {manifest.LayoutTemplates.Folder} · {manifest.LayoutTemplates.File}, proxies {manifest.ProxyPolicy.LongEdge}");
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Changes an archive's settings in its <c>archive.json</c> (the source of truth, BRIEF §7), then in the index.
|
||||
/// <paramref name="edit"/> receives the settings read from the file under the archive's settings lease, so a server and
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">An edited setting is invalid (<see cref="ArgumentException.ParamName"/> names it).</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)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(edit);
|
||||
var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false);
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
// The index row is written under the same lease as the file, so two edits cannot leave them in opposite orders.
|
||||
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, SettingsLease, _writer.Options.Owner, _writer.Options.LeaseWait, _writer.Options.LeaseDuration,
|
||||
cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var current = ManifestStore.ReadArchive(paths.ManifestPath);
|
||||
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);
|
||||
var manifest = current with
|
||||
{
|
||||
Name = settings.Name.Trim(),
|
||||
LayoutTemplates = settings.Templates,
|
||||
ProxyPolicy = settings.Proxies,
|
||||
ThumbnailPolicy = settings.Thumbnails,
|
||||
};
|
||||
if (manifest != current) ManifestStore.WriteArchive(paths.ManifestPath, manifest);
|
||||
Log.Info("archive", $"Settings of {paths.Root}: {manifest.LayoutTemplates.Folder} · {manifest.LayoutTemplates.File}, proxies {manifest.ProxyPolicy.LongEdge}, thumbnails {manifest.ThumbnailPolicy.LongEdge}");
|
||||
return await RegisterAsync(paths, manifest, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public static ArchiveAvailability GetAvailability(Archive archive) => ArchiveVolume.Probe(new ArchivePaths(archive.RootPath));
|
||||
|
||||
/// <summary>Changes title, tags, rating and notes in the sidecar and the index together (settings version + 1).</summary>
|
||||
public Task<Sequence> SetSequenceInfoAsync(Guid sequenceId, string? title, IReadOnlyList<string> tags, int rating, string? notes,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
EditSequenceInfoAsync(sequenceId, _ => new SequenceInfo(title, tags, rating, notes), cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Changes some of title, tags, rating and notes from their current values — read under the sequence's lease from
|
||||
/// the sidecar, or from the index when it is ahead (an edit made there only) — so fields <paramref name="edit"/>
|
||||
/// leaves alone keep any change made since the caller read the sequence. Sidecar and index change together
|
||||
/// (settings version + 1), the index row in these fields only, at the settings version read under the lease
|
||||
/// (<see cref="SequenceRepository.EditAsync(Guid, SequenceEdit, int?, CancellationToken)"/>): a settings edit committed
|
||||
/// since the caller read the sequence (an analysis's Auto values, the server's PATCH, which takes no lease) stays, and
|
||||
/// so do frames another process listed in the sidecar, which the next scan indexes
|
||||
/// (<see cref="ArchiveIndexer.InStepAsync(Archive, SequencePaths, SequenceManifest, CancellationToken)"/>).
|
||||
/// <paramref name="edit"/> runs again on top of an edit the API committed meanwhile.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">The sequence is not in the index (or left it before the edit).</exception>
|
||||
public async Task<Sequence> EditSequenceInfoAsync(Guid sequenceId, Func<SequenceInfo, SequenceInfo> edit, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(edit);
|
||||
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 manifest = SequenceWriter.ReadLocked(folder, sequenceId);
|
||||
var inStep = await Indexer.InStepAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false);
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
var row = await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) ?? throw Unknown(sequenceId);
|
||||
var current = row.SettingsVersion > manifest.Versions.Settings
|
||||
? new SequenceInfo(row.Title, row.Tags, row.Rating, row.Notes)
|
||||
: new SequenceInfo(manifest.Title, manifest.Tags, manifest.Rating, manifest.Notes);
|
||||
var info = edit(current);
|
||||
var title = string.IsNullOrWhiteSpace(info.Title) ? null : info.Title.Trim();
|
||||
// The last attempt writes over whatever the index holds then rather than fail the user's edit.
|
||||
var result = await _db.Sequences.EditAsync(sequenceId,
|
||||
new SequenceEdit { Title = title ?? string.Empty, Tags = info.Tags, Rating = info.Rating, Notes = info.Notes ?? string.Empty },
|
||||
attempt < InfoEditAttempts ? row.SettingsVersion : null, cancellationToken).ConfigureAwait(false);
|
||||
// A conflict means the API changed the sequence after the read: the edit applies again on top of that.
|
||||
if (result.Outcome == SequenceEditOutcome.Conflict) continue;
|
||||
if (result.Sequence is not { } updated) throw Unknown(sequenceId);
|
||||
// The sidecar takes the fields as the index stored them (trimmed, tags without duplicates).
|
||||
ManifestStore.WriteSequence(folder.ManifestPath, manifest with
|
||||
{
|
||||
Title = updated.Title,
|
||||
Tags = updated.Tags,
|
||||
Rating = updated.Rating,
|
||||
Notes = updated.Notes,
|
||||
Versions = manifest.Versions with { Settings = System.Math.Max(manifest.Versions.Settings + 1, updated.SettingsVersion) },
|
||||
UpdatedAt = DateTimeOffset.UtcNow,
|
||||
});
|
||||
if (inStep) await Indexer.RecordStampsAsync(archive, folder, sequenceId, cancellationToken).ConfigureAwait(false);
|
||||
return updated;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<DuplicateGroup>> FindDuplicatesAsync(Guid archiveId, CancellationToken cancellationToken = default) =>
|
||||
Maintenance.FindDuplicatesAsync(archiveId, cancellationToken);
|
||||
|
||||
public async Task<OrphanReport> FindOrphansAsync(Guid archiveId, CancellationToken cancellationToken = default) =>
|
||||
await Maintenance.FindOrphansAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <summary>
|
||||
/// Orphans fix: index the unlisted photos of a sequence and flag its missing files. Photos added, gone or back clear
|
||||
/// what covered the frames, as a scan's reconcile does (<see cref="ArchiveIndexer.ReconcileAsync"/>), and what a scan's
|
||||
/// follow-ups would make again is queued on <paramref name="followUps"/> (null: nothing): the light analysis, a
|
||||
/// background deep analysis when <paramref name="deepAnalysis"/> asks (as <see cref="ScanParameters.DeepAnalysis"/>
|
||||
/// does for a scan) and, on a server (<see cref="ArchiveServiceOptions.ImagesAfterScan"/>), the thumbnails and proxies.
|
||||
/// A kind the engine does not run, or one a queued job of that kind already covers for the sequence, is left out.
|
||||
/// </summary>
|
||||
public async Task ReconcileAsync(Guid sequenceId, JobEngine? followUps, bool deepAnalysis, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var (archive, sequence) = await LoadSequenceAsync(sequenceId, cancellationToken).ConfigureAwait(false);
|
||||
if (!await Indexer.ReconcileAsync(archive, sequence, cancellationToken).ConfigureAwait(false) || followUps is null) return;
|
||||
List<ArchiveJobRequest> requests = [ProcessingJobs.LightAnalysis([sequenceId], sequence.DisplayTitle)];
|
||||
// BRIEF §10.2: background, low priority.
|
||||
if (deepAnalysis) requests.Add(ProcessingJobs.DeepAnalysis([sequenceId], sequence.DisplayTitle) with { Priority = JobPriority.Background });
|
||||
if (_writer.Options.ImagesAfterScan)
|
||||
{
|
||||
requests.Add(ArchiveJobs.Thumbnails([sequenceId], sequence.DisplayTitle));
|
||||
// An archive whose policy makes no proxies would get a pass that does nothing.
|
||||
if (archive.ProxyLongEdge != ProxyPolicy.Disabled) requests.Add(ArchiveJobs.Proxies([sequenceId], sequence.DisplayTitle));
|
||||
}
|
||||
foreach (var request in requests)
|
||||
{
|
||||
if (!followUps.Runs(request.Kind)) continue;
|
||||
// A queued job runs after the fix, on the frames as they are then, whatever else it targets (a scan's follow-ups).
|
||||
var queued = await _db.Jobs.ListQueuedAsync(request.Kind, 1000, cancellationToken).ConfigureAwait(false);
|
||||
if (queued.Any(j => j.TargetIds.Contains(sequenceId))) continue;
|
||||
await followUps.EnqueueAsync(request, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Orphans fix: drop index rows whose sidecar is gone.</summary>
|
||||
public async Task<int> RemoveMissingSequencesAsync(Guid archiveId, IReadOnlyList<Guid> sequenceIds, CancellationToken cancellationToken = default) =>
|
||||
await Maintenance.RemoveMissingSequencesAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), sequenceIds, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
/// <summary>Dry run of a mass rename.</summary>
|
||||
public async Task<RenamePlan> PlanRenameAsync(Guid archiveId, IReadOnlyList<Guid> sequenceIds, string? folderTemplate, string? titleTemplate,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
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) =>
|
||||
await Renamer.ApplyAsync(await LoadArchiveAsync(plan.ArchiveId, cancellationToken).ConfigureAwait(false), plan, progress, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
/// <summary>Dry run of moving sequences to their archive's trash; <paramref name="progress"/> counts the sequences checked.</summary>
|
||||
public Task<DeletePlan> PlanDeleteAsync(IReadOnlyList<Guid> sequenceIds, IProgress<int>? progress = null, CancellationToken cancellationToken = default) =>
|
||||
Trash.PlanAsync(sequenceIds, progress, cancellationToken);
|
||||
|
||||
/// <summary>Moves exactly the planned sequences to the trash; returns the trash entries made.</summary>
|
||||
public Task<IReadOnlyList<TrashEntry>> DeleteAsync(DeletePlan plan, string? deletedBy = null, IProgress<int>? progress = null,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
Trash.DeleteAsync(plan, deletedBy, progress, cancellationToken);
|
||||
|
||||
/// <summary>The sequences in an archive's trash, newest first.</summary>
|
||||
public async Task<IReadOnlyList<TrashEntry>> ListTrashAsync(Guid archiveId, CancellationToken cancellationToken = default) =>
|
||||
await Trash.ListAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <summary>Moves a sequence back from the trash and indexes it again.</summary>
|
||||
public async Task<Sequence> RestoreAsync(Guid archiveId, string entryName, CancellationToken cancellationToken = default) =>
|
||||
await Trash.RestoreAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), entryName, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <summary>Plans a card or folder import into an archive (nothing is copied).</summary>
|
||||
public async Task<ImportPlan> PlanImportAsync(Guid archiveId, string sourceRoot, ImportOptions options, Guid? cardId = null, IProgress<int>? progress = null,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
await Imports.PlanAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), sourceRoot, options, cardId, progress,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <summary>Dry run of "delete imported" for a card; pass the plan to <see cref="CardEraser.Execute"/> after the user confirms.</summary>
|
||||
public async Task<ErasePlan> PlanCardEraseAsync(Guid archiveId, Guid cardId, string sourceRoot, IProgress<int>? progress = null,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
await Imports.PlanEraseAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), cardId, sourceRoot, progress,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="settings"/> with a name an archive can keep: a blank one becomes the folder's name (the root itself
|
||||
/// for a drive root), one longer than <see cref="ArchiveSettings.MaxNameLength"/> is shortened.
|
||||
/// </summary>
|
||||
private static ArchiveSettings WithUsableName(ArchiveSettings settings, ArchivePaths paths)
|
||||
{
|
||||
var name = string.IsNullOrWhiteSpace(settings.Name) ? Path.GetFileName(paths.Root) is { Length: > 0 } folder ? folder : paths.Root : settings.Name.Trim();
|
||||
return settings with { Name = name.Length > ArchiveSettings.MaxNameLength ? name[..ArchiveSettings.MaxNameLength] : name };
|
||||
}
|
||||
|
||||
private async Task<Archive> RegisterAsync(ArchivePaths paths, ArchiveManifest manifest, CancellationToken cancellationToken)
|
||||
{
|
||||
var archive = new Archive
|
||||
{
|
||||
Id = manifest.Id,
|
||||
Name = manifest.Name,
|
||||
RootPath = paths.Root,
|
||||
FolderTemplate = manifest.LayoutTemplates.Folder,
|
||||
FileTemplate = manifest.LayoutTemplates.File,
|
||||
SchemaVersion = manifest.SchemaVersion,
|
||||
Created = manifest.Created,
|
||||
ProxyLongEdge = manifest.ProxyPolicy.LongEdge,
|
||||
};
|
||||
await _db.Archives.UpsertAsync(archive, cancellationToken).ConfigureAwait(false);
|
||||
return archive;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The archive's <c>archive.json</c>; null (logged) while it cannot be read, when a newer Chronos wrote it (this one
|
||||
/// would drop what it does not know) or when it belongs to another archive.
|
||||
/// </summary>
|
||||
private static ArchiveManifest? TryReadManifest(Archive archive)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
try
|
||||
{
|
||||
if (!File.Exists(paths.ManifestPath)) return null;
|
||||
var manifest = ManifestStore.ReadArchive(paths.ManifestPath);
|
||||
if (manifest.SchemaVersion > ArchiveManifest.CurrentSchemaVersion)
|
||||
Log.Warning("archive", $"{paths.ManifestPath} has schema version {manifest.SchemaVersion}, newer than this Chronos's; the index's settings are used");
|
||||
else if (manifest.Id == archive.Id) return manifest;
|
||||
else Log.Warning("archive", $"{paths.ManifestPath} belongs to archive {manifest.Id}, not {archive.Id}; the index's settings are used");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
|
||||
{
|
||||
Log.Warning("archive", $"The settings of {paths.Root} cannot be read; the index's are used", ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private async Task<Archive> LoadArchiveAsync(Guid archiveId, CancellationToken cancellationToken) =>
|
||||
await _db.Archives.GetAsync(archiveId, cancellationToken).ConfigureAwait(false) ?? throw new ArgumentException($"Unknown archive {archiveId}.", nameof(archiveId));
|
||||
|
||||
private async Task<(Archive, Sequence)> LoadSequenceAsync(Guid sequenceId, CancellationToken cancellationToken)
|
||||
{
|
||||
var sequence = await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) ?? throw Unknown(sequenceId);
|
||||
return (await LoadArchiveAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false), sequence);
|
||||
}
|
||||
|
||||
private static ArgumentException Unknown(Guid sequenceId) => new($"Unknown sequence {sequenceId}.", nameof(sequenceId));
|
||||
}
|
||||
|
||||
/// <summary>The fields of a sequence the user describes it with (sidecar and index).</summary>
|
||||
public sealed record SequenceInfo(string? Title, IReadOnlyList<string> Tags, int Rating, string? Notes);
|
||||
|
||||
/// <summary>
|
||||
/// The settings an archive keeps in <c>archive.json</c> (BRIEF §7, §8.5): its name, the naming templates of new imports
|
||||
/// and the policies of the proxies and thumbnails built from now on.
|
||||
/// </summary>
|
||||
public sealed record ArchiveSettings(string Name, LayoutTemplates Templates, ProxyPolicy Proxies, ThumbnailPolicy Thumbnails)
|
||||
{
|
||||
public const int MaxNameLength = 100;
|
||||
|
||||
public static ArchiveSettings Of(ArchiveManifest manifest) => new(manifest.Name, manifest.LayoutTemplates, manifest.ProxyPolicy, manifest.ThumbnailPolicy);
|
||||
|
||||
/// <summary>Whether the index row <paramref name="archive"/> holds these settings (all it keeps: not the thumbnail policy).</summary>
|
||||
public bool IsRegisteredIn(Archive archive)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
return Name == archive.Name && Templates.Folder == archive.FolderTemplate && Templates.File == archive.FileTemplate
|
||||
&& 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()
|
||||
{
|
||||
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 (!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>Builds the archive jobs; enqueue with <see cref="EnqueueAsync"/>.</summary>
|
||||
public static class ArchiveJobs
|
||||
{
|
||||
/// <param name="deepAnalysis">Also queue a background deep analysis of the sequences the scan indexes (see <see cref="ScanParameters"/>).</param>
|
||||
public static ArchiveJobRequest Scan(Archive archive, bool full = false, bool deepAnalysis = false) =>
|
||||
new(JobKind.Scan, [archive.Id], archive.Name, Json(new ScanParameters(full, deepAnalysis), ArchiveJobJson.Default.ScanParameters), JobPriority.User);
|
||||
|
||||
public static ArchiveJobRequest Rebuild(Archive archive) => new(JobKind.Rebuild, [archive.Id], archive.Name, null, JobPriority.User);
|
||||
|
||||
public static ArchiveJobRequest Verify(Archive archive, IReadOnlyList<Guid>? sequenceIds = null) =>
|
||||
new(JobKind.Verify, [archive.Id], archive.Name, Json(new VerifyParameters(sequenceIds), ArchiveJobJson.Default.VerifyParameters), JobPriority.User);
|
||||
|
||||
public static ArchiveJobRequest Import(Archive archive, ImportPlan plan, Guid? cardId, bool verify = true, Guid? userId = null) =>
|
||||
new(JobKind.Import, [archive.Id], archive.Name,
|
||||
Json(new ImportJobParameters(archive.Id, plan, cardId, verify, userId), ArchiveJobJson.Default.ImportJobParameters), JobPriority.User);
|
||||
|
||||
public static ArchiveJobRequest Thumbnails(IReadOnlyList<Guid> sequenceIds, string? label = null, bool force = false) =>
|
||||
new(JobKind.Thumbs, sequenceIds, label, Json(new ImageJobParameters(force), ArchiveJobJson.Default.ImageJobParameters), JobPriority.Background);
|
||||
|
||||
public static ArchiveJobRequest Proxies(IReadOnlyList<Guid> sequenceIds, string? label = null, bool force = false) =>
|
||||
new(JobKind.Proxies, sequenceIds, label, Json(new ImageJobParameters(force), ArchiveJobJson.Default.ImageJobParameters), JobPriority.Background);
|
||||
|
||||
public static ArchiveJobRequest Maintenance(Archive archive, bool dryRun = false) =>
|
||||
new(JobKind.Maintenance, [archive.Id], archive.Name, Json(new MaintenanceParameters(dryRun), ArchiveJobJson.Default.MaintenanceParameters),
|
||||
JobPriority.Normal);
|
||||
|
||||
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);
|
||||
|
||||
private static string Json<T>(T value, System.Text.Json.Serialization.Metadata.JsonTypeInfo<T> typeInfo) => JsonSerializer.Serialize(value, typeInfo);
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
using System.Diagnostics;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>A frame whose original is missing, changed or damaged.</summary>
|
||||
public sealed record VerifyProblem(Guid SequenceId, Guid FrameId, string RelativePath, FrameHealth Health);
|
||||
|
||||
/// <summary>Where a verify stands: the next sequence (ordinal in the run) and the next frame index in it.</summary>
|
||||
public readonly record struct VerifyPosition(int Sequence, int Frame);
|
||||
|
||||
/// <summary>Outcome of one verify run (frames before a resume point are counted by the run that checked them).</summary>
|
||||
public sealed record VerifyReport(int Sequences, long Checked, long Ok, long Hashed, IReadOnlyList<VerifyProblem> Problems);
|
||||
|
||||
/// <summary>
|
||||
/// Re-hashes originals against their sidecar SHA-256 (BRIEF §12.5 Verify): missing, changed and corrupt files get
|
||||
/// <see cref="FrameFlags.Missing"/>/<see cref="FrameFlags.Corrupt"/> in the sidecar and the index, adopted files get
|
||||
/// their first hash, and a clean sequence is stamped verified. Progress is flushed in batches so a resumed run
|
||||
/// continues where the last flush ended.
|
||||
/// </summary>
|
||||
public sealed class ArchiveVerifier
|
||||
{
|
||||
private const int FlushFrames = 512;
|
||||
private static readonly TimeSpan FlushInterval = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <summary>The flags a verify owns; the others belong to other writers.</summary>
|
||||
private const FrameFlags Integrity = FrameFlags.Missing | FrameFlags.Corrupt;
|
||||
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly SequenceWriter _writer;
|
||||
private readonly ArchiveIndexer _indexer;
|
||||
|
||||
internal ArchiveVerifier(ChronosDatabase db, SequenceWriter writer, ArchiveIndexer indexer)
|
||||
{
|
||||
_db = db;
|
||||
_writer = writer;
|
||||
_indexer = indexer;
|
||||
}
|
||||
|
||||
/// <param name="sequenceIds">Sequences to verify; null = the whole archive (ordered by folder).</param>
|
||||
/// <param name="checkpoint">Called after each flush with the resume position, bytes done and bytes total.</param>
|
||||
/// <param name="frameDone">Called after each frame with bytes done and bytes total (throughput and ETA).</param>
|
||||
public async Task<VerifyReport> VerifyAsync(Archive archive, IReadOnlyList<Guid>? sequenceIds, VerifyPosition resume,
|
||||
Func<VerifyPosition, long, long, ValueTask> checkpoint, Func<long, long, ValueTask>? frameDone = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
var targets = await TargetsAsync(archive, paths, sequenceIds, cancellationToken).ConfigureAwait(false);
|
||||
var bytesTotal = targets.Sum(t => t.TotalBytes);
|
||||
var bytesDone = targets.Take(resume.Sequence).Sum(t => t.TotalBytes);
|
||||
long checkedFrames = 0, ok = 0, hashed = 0;
|
||||
var problems = new List<VerifyProblem>();
|
||||
for (var s = resume.Sequence; s < targets.Count; s++)
|
||||
{
|
||||
var target = targets[s];
|
||||
var sequence = paths.Sequence(target.Folder);
|
||||
var manifest = ManifestStore.ReadSequence(sequence.ManifestPath);
|
||||
var pending = new List<PendingCheck>();
|
||||
var clock = Stopwatch.StartNew();
|
||||
var first = s == resume.Sequence ? System.Math.Min(resume.Frame, manifest.Frames.Count) : 0;
|
||||
bytesDone += manifest.Frames.Take(first).Sum(f => f.Size);
|
||||
for (var i = first; i < manifest.Frames.Count; i++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// Taken before the file is read: a file replaced while or after it was read no longer matches (FlushAsync).
|
||||
var file = FileStamp.Of(sequence.File(manifest.Frames[i].File));
|
||||
var check = await FrameVerifier.CheckAsync(sequence, manifest.Frames[i], read => bytesDone += read, cancellationToken).ConfigureAwait(false);
|
||||
checkedFrames++;
|
||||
if (frameDone is not null) await frameDone(bytesDone, bytesTotal).ConfigureAwait(false);
|
||||
if (check.Health == FrameHealth.Ok) ok++;
|
||||
else if (check.Health == FrameHealth.Hashed) hashed++;
|
||||
else problems.Add(new VerifyProblem(target.Id, check.Frame.Id, sequence.ArchiveRelative(check.Frame.File), check.Health));
|
||||
if (check.ChangesRecord) pending.Add(new PendingCheck(check, file));
|
||||
if (i + 1 < manifest.Frames.Count && (pending.Count >= FlushFrames || clock.Elapsed >= FlushInterval))
|
||||
{
|
||||
await FlushAsync(archive, paths, target, pending, cancellationToken).ConfigureAwait(false);
|
||||
await checkpoint(new VerifyPosition(s, i + 1), bytesDone, bytesTotal).ConfigureAwait(false);
|
||||
clock.Restart();
|
||||
}
|
||||
}
|
||||
await FlushAsync(archive, paths, target, pending, cancellationToken).ConfigureAwait(false);
|
||||
await StampAsync(archive, paths, target, cancellationToken).ConfigureAwait(false);
|
||||
await checkpoint(new VerifyPosition(s + 1, 0), bytesDone, bytesTotal).ConfigureAwait(false);
|
||||
}
|
||||
return new VerifyReport(targets.Count, checkedFrames, ok, hashed, problems);
|
||||
}
|
||||
|
||||
/// <summary>The sequences to check; one waiting for its first frame (<see cref="ArchiveIngest.AwaitsFolder"/>) has no sidecar to check yet.</summary>
|
||||
private async Task<List<Sequence>> TargetsAsync(Archive archive, ArchivePaths paths, IReadOnlyList<Guid>? sequenceIds, CancellationToken cancellationToken)
|
||||
{
|
||||
var ids = sequenceIds ?? (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false)).Select(l => l.Id).ToList();
|
||||
var targets = new List<Sequence>(ids.Count);
|
||||
foreach (var id in ids)
|
||||
{
|
||||
if (await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } s && s.ArchiveId == archive.Id && !ArchiveIngest.AwaitsFolder(s, paths))
|
||||
targets.Add(s);
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes what the checks found to the sidecar and the index, under one lease: the <see cref="FrameFlags.Missing"/> and
|
||||
/// <see cref="FrameFlags.Corrupt"/> bits merged into the frame's flags as the sidecar has them under the lease, and new
|
||||
/// hashes. Every other flag stays as its writer left it (decode tiers, duplicates, exclusions), in both places. A check
|
||||
/// whose frame or file changed since it was read is left for the next verify (<see cref="StillApplies"/>). The folder's
|
||||
/// scan stamps follow only when the index held the folder as it was
|
||||
/// (<see cref="ArchiveIndexer.InStepAsync(Archive, SequencePaths, SequenceManifest, CancellationToken)"/>), so frames
|
||||
/// another process listed in the sidecar meanwhile are still indexed by the next scan.
|
||||
/// </summary>
|
||||
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))
|
||||
{
|
||||
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();
|
||||
if (found.Count > 0)
|
||||
{
|
||||
var inStep = await _indexer.InStepAsync(archive, sequence, manifest, cancellationToken).ConfigureAwait(false);
|
||||
var changes = found.ToDictionary(c => c.Frame.Id, c => (Func<SidecarFrame, SidecarFrame>)(f => f with
|
||||
{
|
||||
Flags = (f.Flags & ~Integrity) | (c.Flags & Integrity),
|
||||
Sha256 = c.Health == FrameHealth.Hashed ? c.Sha256 : f.Sha256,
|
||||
}));
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, SequenceFrames.Update(manifest, changes));
|
||||
await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
// The row before its frames (SequenceRepository.GetForUpdateAsync), so a scan writing them waits or is waited for.
|
||||
if (await tx.Sequences.GetForUpdateAsync(target.Id, cancellationToken).ConfigureAwait(false) is not null)
|
||||
{
|
||||
await tx.Frames.UpdateIntegrityAsync(found.ConvertAll(c => new FrameIntegrity(c.Frame.Id, c.Flags, c.Health == FrameHealth.Hashed ? c.Sha256 : null)),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
if (inStep) await _indexer.RecordStampsAsync(archive, sequence, target.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
pending.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="check"/> still holds for the frame as the sidecar lists it under the lease: the record names
|
||||
/// the same file, size and hash as the one checked, and the file has the size and modification time it had before it
|
||||
/// was read. Otherwise another writer changed the frame or its file in between (an upload repaired a missing or
|
||||
/// changed file, another verify hashed it), and writing this verdict would undo that.
|
||||
/// </summary>
|
||||
private static bool StillApplies(SequencePaths sequence, PendingCheck check, SidecarFrame now)
|
||||
{
|
||||
var then = check.Check.Frame;
|
||||
return now.File == then.File && now.Size == then.Size && string.Equals(now.Sha256, then.Sha256, StringComparison.OrdinalIgnoreCase)
|
||||
&& FileStamp.Of(sequence.File(now.File)) == check.File;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stamps the verify time; the sequence counts as verified only when no frame is missing or corrupt, and has errors
|
||||
/// while one is. Sidecar and index are written under one lease, the index row with these fields only
|
||||
/// (<see cref="SequenceRepository.RecordVerifiedAsync"/>), so a settings edit or an ingest committed meanwhile stays;
|
||||
/// the scan stamps as in <see cref="FlushAsync"/>.
|
||||
/// </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 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);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var manifest = m with
|
||||
{
|
||||
Status = clean ? m.Status | SequenceStatus.Verified : m.Status & ~SequenceStatus.Verified,
|
||||
VerifiedAt = now,
|
||||
UpdatedAt = now,
|
||||
};
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, manifest);
|
||||
await _db.Sequences.RecordVerifiedAsync(target.Id, clean ? SequenceStatus.Verified : SequenceStatus.HasErrors,
|
||||
clean ? SequenceStatus.HasErrors : SequenceStatus.Verified, now, cancellationToken).ConfigureAwait(false);
|
||||
if (inStep) await _indexer.RecordStampsAsync(archive, sequence, target.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A frame's check with the stamp its file had before it was read (null: no file).</summary>
|
||||
private readonly record struct PendingCheck(FrameCheck Check, FileStamp? File);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using Chronos.Core.Imaging;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// How many photos a job decodes from their originals at once (owner review 1, R2): the host's parallelism, fewer when
|
||||
/// the memory budget cannot hold that many decodes of the largest original. A decode takes some
|
||||
/// <see cref="BytesPerPixel"/> per pixel of the original while it runs: a 16-bit mosaic, float RGB and a copy. Only decodes
|
||||
/// that develop an original whole count (<see cref="Developed"/>); thumbnail and proxy passes, deep analyses and every
|
||||
/// window of a render ask it.
|
||||
/// </summary>
|
||||
internal static class DecodeBudget
|
||||
{
|
||||
/// <summary>Memory one decode of an original may take per pixel: a 16-bit mosaic, float RGB and a copy.</summary>
|
||||
public const long BytesPerPixel = 32;
|
||||
|
||||
/// <summary>Pixels assumed for an original of unknown size (a 24 MP sensor).</summary>
|
||||
public const long UnknownPixels = 24_000_000;
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="parallelism"/> decodes, fewer when <paramref name="memoryBudget"/> cannot hold that many of an
|
||||
/// original of <paramref name="largestPixels"/> (unknown when 0 or less); at least one.
|
||||
/// </summary>
|
||||
public static int PhotosAtOnce(int parallelism, long memoryBudget, long largestPixels)
|
||||
{
|
||||
if (parallelism <= 1) return 1;
|
||||
// A size a damaged file claims never overflows the product.
|
||||
var pixels = largestPixels > 0 ? Math.Min(largestPixels, long.MaxValue / BytesPerPixel) : UnknownPixels;
|
||||
return (int)Math.Clamp(memoryBudget / (pixels * BytesPerPixel), 1, parallelism);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The pixels of an original that a decode at <paramref name="edge"/> (0: full size) develops whole, 0 when it takes a
|
||||
/// cheap path: a JPEG whose long edge is at least twice the edge decodes scaled down, and a RAW's embedded preview that
|
||||
/// reaches the edge serves a decode that prefers previews (<paramref name="preferPreview"/>: thumbnails, analyses, a
|
||||
/// render's preparation; never a render). Another format's stored preview is no shortcut: a JPEG-compressed TIFF strip
|
||||
/// may need the file's own tables and fall back to a full decode. Anything else (a TIFF, a PNG, a RAW developed) counts
|
||||
/// whole, an unknown size as <see cref="UnknownPixels"/>.
|
||||
/// </summary>
|
||||
public static long Developed(ImageFileFormat format, int width, int height, int previewLongEdge, int edge, bool preferPreview)
|
||||
{
|
||||
if (edge > 0 && format == ImageFileFormat.Jpeg && Math.Max(width, height) >= 2L * edge) return 0;
|
||||
if (edge > 0 && preferPreview && previewLongEdge >= edge && ImageFormatInfo.Of(format).IsRaw) return 0;
|
||||
var pixels = (long)Math.Max(width, 0) * Math.Max(height, 0);
|
||||
return pixels > 0 ? pixels : UnknownPixels;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// Decode tiers of archived frames (BRIEF §8.2) written to the sidecar and the index together: the tier, the
|
||||
/// <see cref="FrameFlags.PreviewOnly"/> and <see cref="FrameFlags.Undecodable"/> flags that follow it and the preview
|
||||
/// size, then the sequence row (its preview-only count for the Library chip). A sequence that gains undecodable frames
|
||||
/// shows a warning at once; its next light analysis lists them. Tiers describe the host that probed or decoded the files
|
||||
/// last. Only a file in a format this host decodes natively is flagged undecodable (it is damaged); one beyond this
|
||||
/// host's decoders (HEIF or an unsupported RAW without a preview on the server) keeps its tier but no flag, so render
|
||||
/// nodes and proxies can still provide its pixels, and a host that decodes a flagged frame clears the flag. A frame whose
|
||||
/// original this host reads through its proxy (<see cref="ArchiveImages.NeedsProxy(ImageFileFormat)"/>) is preview-only
|
||||
/// only while it has none: with its proxy it is not rendered from the embedded preview, so it caps nothing.
|
||||
/// </summary>
|
||||
internal sealed class FrameTiers(ChronosDatabase db, SequenceWriter writer, ArchiveIndexer indexer)
|
||||
{
|
||||
/// <summary>
|
||||
/// The tier of every frame of <paramref name="manifest"/> whose tier is not known yet, that decodes only through a
|
||||
/// preview whose size is not known (the output cap needs it), or that is a GPR whose JPEG in another sequence
|
||||
/// (<see cref="GprCompanions"/>; an upload may index it after the GPR was probed) is larger than its stored preview,
|
||||
/// or that is stored as GPR without the .gpr extension (indexed before GoPro DNGs converted by Adobe software counted as
|
||||
/// DNG; R4, owner review 1), probed with the host's decoders without decoding pixels, several at once
|
||||
/// (<see cref="ArchiveServiceOptions.Parallelism"/>); missing and unreadable files are left for later.
|
||||
/// </summary>
|
||||
public async Task<Dictionary<Guid, FileTier>> ProbeUnknownAsync(Archive archive, SequencePaths folder, SequenceManifest manifest,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var present = manifest.Frames.Where(f => (f.Flags & FrameFlags.Missing) == 0).ToList();
|
||||
var companions = await GprCompanions.FindWithSizesAsync(db, archive, present, cancellationToken).ConfigureAwait(false);
|
||||
var unknown = present.Where(f => f.Tier == 0 || (f.Tier == DecodeTier.EmbeddedPreview && f.PreviewW is null) || IsStaleGpr(f)
|
||||
|| (companions.TryGetValue(f.Id, out var jpeg)
|
||||
&& int.Max(f.PreviewW ?? 0, f.PreviewH ?? 0) < int.Max(jpeg.Width, jpeg.Height))).ToList();
|
||||
var tiers = new ConcurrentDictionary<Guid, FileTier>();
|
||||
var options = new ParallelOptions { MaxDegreeOfParallelism = Math.Max(1, writer.Options.Parallelism()), CancellationToken = cancellationToken };
|
||||
await Parallel.ForEachAsync(unknown, options, (frame, _) =>
|
||||
{
|
||||
var path = folder.File(frame.File);
|
||||
try
|
||||
{
|
||||
var tier = writer.Options.Decoder.Probe(path, frame.Format, companions.TryGetValue(frame.Id, out var companion) ? companion.Path : null);
|
||||
Core.Diagnostics.Log.Debug("archive", $"{frame.File}: {tier.Tier} via {tier.Decoder ?? "none"}{(tier.Reason is { } why ? $" ({why})" : "")}");
|
||||
tiers[frame.Id] = tier;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("archive", $"{path} could not be probed", ex);
|
||||
}
|
||||
return ValueTask.CompletedTask;
|
||||
}).ConfigureAwait(false);
|
||||
return new Dictionary<Guid, FileTier>(tiers);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records <paramref name="tiers"/> (by frame id) where they change what the sidecar says, and returns the sequence's
|
||||
/// frames as the sidecar has them afterwards (none when there was nothing to record). Frames no longer in the
|
||||
/// sequence are ignored. The <see cref="FrameFlags.PreviewOnly"/> flag of a frame whose original this host reads
|
||||
/// through its proxy follows whether its own proxy is there when the sidecar is written
|
||||
/// (<see cref="ArchiveImages.IsProxyOf"/>, <see cref="SequenceFrames.WithProxy"/>), not when the caller looked: proxies
|
||||
/// arrive while analyses and renders run, and another worker may have recorded them already.
|
||||
/// </summary>
|
||||
/// <param name="proxies">Whether every such frame follows its proxy even where no tier is recorded (analyses and the
|
||||
/// proxy pass); otherwise only the frames in <paramref name="tiers"/> do.</param>
|
||||
/// <remarks>
|
||||
/// The sidecar and the index are written under one lease, the index from the sidecar read under it, and the index
|
||||
/// row gets only what tiers change (<see cref="SequenceRepository.RecordTiersAsync"/>): a whole row written back
|
||||
/// would undo what another writer committed meanwhile, an ingest's frames or a settings edit (the server's PATCH
|
||||
/// takes no lease). The folder's scan stamps are recorded only when the index held the folder as it was
|
||||
/// (<see cref="ArchiveIndexer.InStepAsync(Archive, SequencePaths, SequenceManifest, CancellationToken)"/>).
|
||||
/// </remarks>
|
||||
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only.</exception>
|
||||
public async Task<IReadOnlyList<SidecarFrame>> RecordAsync(Archive archive, Sequence sequence, IReadOnlyDictionary<Guid, FileTier> tiers,
|
||||
bool proxies, CancellationToken cancellationToken)
|
||||
{
|
||||
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 m = SequenceWriter.ReadLocked(folder, sequence.Id);
|
||||
var changed = new List<SidecarFrame>();
|
||||
var gained = false;
|
||||
ProxyPolicy? policy = null;
|
||||
var frames = new SidecarFrame[m.Frames.Count];
|
||||
for (var i = 0; i < frames.Length; i++)
|
||||
{
|
||||
var frame = m.Frames[i];
|
||||
frames[i] = frame;
|
||||
var tier = tiers.GetValueOrDefault(frame.Id);
|
||||
if (tier is null && !proxies) continue;
|
||||
bool? proxied = (frame.Flags & FrameFlags.Missing) == 0 && ArchiveImages.NeedsProxy(writer.Options.Decoder, frame.Format)
|
||||
? ArchiveImages.IsProxyOf(folder.Proxy(frame.I), frame.CapturedAt, frame.W, frame.H,
|
||||
policy ??= ManifestStore.ReadArchive(paths.ManifestPath).ProxyPolicy)
|
||||
: null;
|
||||
SidecarFrame updated;
|
||||
if (tier is not null) updated = SequenceFrames.WithTier(frame, tier, DecodesNatively(frame.Format), proxied == true);
|
||||
else if (proxied is { } own) updated = SequenceFrames.WithProxy(frame, own);
|
||||
else continue;
|
||||
if (updated.Tier == frame.Tier && updated.Flags == frame.Flags && updated.PreviewW == frame.PreviewW && updated.PreviewH == frame.PreviewH
|
||||
&& updated.Format == frame.Format)
|
||||
continue;
|
||||
gained |= (updated.Flags & ~frame.Flags & FrameFlags.Undecodable) != 0;
|
||||
frames[i] = updated;
|
||||
changed.Add(updated);
|
||||
}
|
||||
if (changed.Count == 0) return m.Frames;
|
||||
var inStep = await indexer.InStepAsync(archive, folder, m, cancellationToken).ConfigureAwait(false);
|
||||
var manifest = m with
|
||||
{
|
||||
Frames = frames,
|
||||
Status = gained ? m.Status | SequenceStatus.HasWarnings : m.Status,
|
||||
UpdatedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
ManifestStore.WriteSequence(folder.ManifestPath, manifest);
|
||||
await using (var tx = await db.BeginAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
// The row before its frames (SequenceRepository.GetForUpdateAsync): a scan holding the row would otherwise wait
|
||||
// for these frames while this waits for the row, and PostgreSQL would abort one of them.
|
||||
await tx.Sequences.RecordTiersAsync(sequence.Id, gained ? SequenceStatus.HasWarnings : SequenceStatus.None,
|
||||
frames.Count(f => (f.Flags & FrameFlags.PreviewOnly) != 0), cancellationToken).ConfigureAwait(false);
|
||||
await tx.Frames.UpdateTiersAsync(changed.ConvertAll(f => new FrameTierFields(f.Id, f.Flags, f.PreviewW ?? 0, f.PreviewH ?? 0, f.Format)), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
if (inStep) await indexer.RecordStampsAsync(archive, folder, sequence.Id, cancellationToken).ConfigureAwait(false);
|
||||
return manifest.Frames;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A frame stored as GPR whose file is not a .gpr: before owner review 1 every DNG with Make=GoPro counted as GPR, so
|
||||
/// Adobe-converted GoPro DNGs were recorded preview-only; probing reads its signature again (<see cref="SequenceFrames.WithTier"/>
|
||||
/// then stores the format found).
|
||||
/// </summary>
|
||||
internal static bool IsStaleGpr(SidecarFrame frame) =>
|
||||
frame.Format == ImageFileFormat.Gpr && !frame.File.EndsWith(".gpr", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// Whether this host decodes <paramref name="format"/> natively, so a file of it that yields no pixels is damaged
|
||||
/// rather than beyond this host (JPEG always: the managed JPEG decoder is part of every host).
|
||||
/// </summary>
|
||||
private bool DecodesNatively(ImageFileFormat format) =>
|
||||
format == ImageFileFormat.Jpeg || writer.Options.Decoder.TierFor(format) == DecodeTier.Native;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>A GPR's JPEG: its absolute path and its size as the index has it (before orientation).</summary>
|
||||
internal readonly record struct GprCompanion(string Path, int Width, int Height);
|
||||
|
||||
/// <summary>
|
||||
/// The JPEG a GoPro writes with each GPR, the server's pixel source for GPR (BRIEF §8.1; VC-5 is out of scope). In a
|
||||
/// folder adopted in place it sits beside the GPR, where the decoder finds it itself. A card import or an upload splits
|
||||
/// sessions per file format (DECISIONS 2026-10-02), so there it is a frame of another sequence: the archive's JPEG frame
|
||||
/// whose original name has the GPR's stem and whose capture time is the GPR's (within a second). Looked up in the index
|
||||
/// when frames are decoded, so renaming or moving either sequence never breaks the pair.
|
||||
/// </summary>
|
||||
public static class GprCompanions
|
||||
{
|
||||
private static readonly TimeSpan Tolerance = TimeSpan.FromSeconds(1);
|
||||
|
||||
/// <summary>
|
||||
/// The absolute path of the JPEG of each GPR frame of <paramref name="frames"/> (index rows), by frame id; frames
|
||||
/// without one are left out. One index query, none when no frame is a GPR.
|
||||
/// </summary>
|
||||
public static async Task<IReadOnlyDictionary<Guid, string>> FindAsync(ChronosDatabase db, Archive archive, IReadOnlyList<Frame> frames,
|
||||
CancellationToken cancellationToken) =>
|
||||
Paths(await FindAsync(db, archive, [.. frames.Where(f => f.Format == ImageFileFormat.Gpr).Select(f => (f.Id, f.OriginalFileName ?? f.FileName, f.CapturedAt))],
|
||||
cancellationToken).ConfigureAwait(false));
|
||||
|
||||
/// <inheritdoc cref="FindAsync(ChronosDatabase, Archive, IReadOnlyList{Frame}, CancellationToken)"/>
|
||||
public static async Task<IReadOnlyDictionary<Guid, string>> FindAsync(ChronosDatabase db, Archive archive, IReadOnlyList<SidecarFrame> frames,
|
||||
CancellationToken cancellationToken) =>
|
||||
Paths(await FindWithSizesAsync(db, archive, frames, cancellationToken).ConfigureAwait(false));
|
||||
|
||||
/// <summary>The JPEG of each GPR frame of <paramref name="frames"/> (sidecar frames) with its indexed size, by frame id.</summary>
|
||||
internal static Task<Dictionary<Guid, GprCompanion>> FindWithSizesAsync(ChronosDatabase db, Archive archive, IReadOnlyList<SidecarFrame> frames,
|
||||
CancellationToken cancellationToken) =>
|
||||
FindAsync(db, archive, [.. frames.Where(f => f.Format == ImageFileFormat.Gpr).Select(f => (f.Id, f.Original ?? Path.GetFileName(f.File), f.CapturedAt))],
|
||||
cancellationToken);
|
||||
|
||||
private static async Task<Dictionary<Guid, GprCompanion>> FindAsync(ChronosDatabase db, Archive archive,
|
||||
List<(Guid Id, string Name, DateTime? CapturedAt)> gprs, CancellationToken cancellationToken)
|
||||
{
|
||||
var found = new Dictionary<Guid, GprCompanion>();
|
||||
var timed = gprs.Where(g => g.CapturedAt is not null).Select(g => (g.Id, Stem: Stem(g.Name), At: g.CapturedAt!.Value)).ToList();
|
||||
if (timed.Count == 0) return found;
|
||||
var jpegs = await db.Frames.ListByCaptureRangeAsync(archive.Id, ImageFileFormat.Jpeg, timed.Min(g => g.At) - Tolerance,
|
||||
timed.Max(g => g.At) + Tolerance, cancellationToken).ConfigureAwait(false);
|
||||
var byStem = jpegs.Where(j => (j.Flags & FrameFlags.Missing) == 0 && j.CapturedAt is not null)
|
||||
.ToLookup(j => Stem(j.OriginalFileName ?? j.FileName), StringComparer.OrdinalIgnoreCase);
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
foreach (var (id, stem, at) in timed)
|
||||
{
|
||||
var match = byStem[stem].Where(j => (j.CapturedAt!.Value - at).Duration() <= Tolerance).MinBy(j => (j.CapturedAt!.Value - at).Duration());
|
||||
if (match is not null) found[id] = new GprCompanion(paths.FromRelative(match.RelativePath), match.Width, match.Height);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
private static Dictionary<Guid, string> Paths(Dictionary<Guid, GprCompanion> companions) => companions.ToDictionary(kv => kv.Key, kv => kv.Value.Path);
|
||||
|
||||
private static string Stem(string fileName) => Path.GetFileNameWithoutExtension(fileName);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// A verified file waiting in a staging folder on the archive volume, ready to become a frame (BRIEF §4.3, §14.4).
|
||||
/// Exactly one of <see cref="SequenceId"/>, <see cref="NewSequenceTitle"/> or <see cref="SessionKey"/> selects the target:
|
||||
/// an existing sequence, a new one with that title, or the sequence grouped automatically by session.
|
||||
/// </summary>
|
||||
public sealed record IngestRequest(
|
||||
Guid ArchiveId,
|
||||
Guid? SequenceId,
|
||||
string? NewSequenceTitle,
|
||||
string? SessionKey,
|
||||
string StagedPath,
|
||||
string OriginalFileName,
|
||||
long Size,
|
||||
string Sha256,
|
||||
DateTime? ClientCapturedAt,
|
||||
Guid? UserId);
|
||||
|
||||
/// <summary>
|
||||
/// The committed frame; <see cref="Duplicate"/> when an intact frame of the sequence already held that SHA-256 (the file
|
||||
/// stays in staging). A frame with that SHA-256 that was missing or damaged is repaired with the file instead:
|
||||
/// <see cref="Repaired"/>, not a duplicate, and the archive holds no more bytes than before.
|
||||
/// </summary>
|
||||
public sealed record IngestResult(Guid SequenceId, Guid FrameId, int Index, string RelativePath, bool Duplicate, bool Repaired = false);
|
||||
|
||||
/// <summary>
|
||||
/// Commits staged files into the archive layout (originals folder, naming templates, <c>sequence.json</c> written
|
||||
/// atomically) and the index. Used by the server's upload completion and by the client's card import.
|
||||
/// </summary>
|
||||
public interface IArchiveIngest
|
||||
{
|
||||
Task<IngestResult> CommitAsync(IngestRequest request, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Metadata;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Naming;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>A card volume as the client sees it (BRIEF §13): identity <c>{serial}-{label}-{capacity}</c>.</summary>
|
||||
public sealed record CardVolume(string Identity, uint SerialNumber, string? Label, long Capacity);
|
||||
|
||||
public enum AfterImport
|
||||
{
|
||||
Keep,
|
||||
|
||||
/// <summary>Delete from the card the photos whose card file and archive copy both re-hash to the imported hash.</summary>
|
||||
DeleteImported,
|
||||
|
||||
/// <summary>Offer the operating system's format dialog (only after a fully verified import).</summary>
|
||||
FormatCard,
|
||||
}
|
||||
|
||||
/// <summary>Import defaults remembered per card (<see cref="MediaCard.ProfileJson"/>, BRIEF §12.4).</summary>
|
||||
public sealed record CardProfile
|
||||
{
|
||||
public string FolderTemplate { get; init; } = TemplateDefaults.Folder;
|
||||
public string FileTemplate { get; init; } = TemplateDefaults.File;
|
||||
public int SessionGapMinutes { get; init; } = 45;
|
||||
public int MinimumSessionFrames { get; init; } = 8;
|
||||
public bool IncludeSubfolders { get; init; } = true;
|
||||
public bool VerifyCopies { get; init; } = true;
|
||||
public DuplicatePolicy Duplicates { get; init; } = DuplicatePolicy.Skip;
|
||||
public AfterImport AfterImport { get; init; } = AfterImport.Keep;
|
||||
public bool Eject { get; init; } = true;
|
||||
public bool DeepAnalysis { get; init; } = true;
|
||||
|
||||
public ImportOptions ToOptions() => new()
|
||||
{
|
||||
FolderTemplate = FolderTemplate,
|
||||
FileTemplate = FileTemplate,
|
||||
SessionGap = TimeSpan.FromMinutes(SessionGapMinutes),
|
||||
MinimumSessionFrames = MinimumSessionFrames,
|
||||
IncludeSubfolders = IncludeSubfolders,
|
||||
VerifyCopies = VerifyCopies,
|
||||
Duplicates = Duplicates,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Card import over the archive index (BRIEF §12.4, §13): card profiles, planning with the archive's history and
|
||||
/// duplicates, execution into the archive through <see cref="ArchiveIngest"/>, and the verified card erase.
|
||||
/// </summary>
|
||||
public sealed class ImportService
|
||||
{
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly ArchiveIngest _ingest;
|
||||
|
||||
internal ImportService(ChronosDatabase db, ArchiveIngest ingest)
|
||||
{
|
||||
_db = db;
|
||||
_ingest = ingest;
|
||||
}
|
||||
|
||||
/// <summary>The card with this identity, registered on first sight (the UI then asks for a nickname).</summary>
|
||||
public async Task<MediaCard> RegisterCardAsync(CardVolume volume, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
if (await _db.MediaCards.FindByIdentityAsync(volume.Identity, cancellationToken).ConfigureAwait(false) is { } known)
|
||||
{
|
||||
await _db.MediaCards.TouchAsync(known.Id, now, cancellationToken).ConfigureAwait(false);
|
||||
return known with { LastSeen = now };
|
||||
}
|
||||
var card = new MediaCard
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Identity = volume.Identity,
|
||||
VolumeSerial = volume.SerialNumber,
|
||||
Label = volume.Label,
|
||||
Capacity = volume.Capacity,
|
||||
FirstSeen = now,
|
||||
LastSeen = now,
|
||||
};
|
||||
await _db.MediaCards.UpsertAsync(card, cancellationToken).ConfigureAwait(false);
|
||||
return card;
|
||||
}
|
||||
|
||||
public static CardProfile ProfileOf(MediaCard card) =>
|
||||
card.ProfileJson is { Length: > 0 } json ? JsonSerializer.Deserialize(json, ArchiveJobJson.Default.CardProfile) ?? new() : new();
|
||||
|
||||
/// <summary>Stores the nickname, defaults and auto-import choice of a card.</summary>
|
||||
public async Task<MediaCard> SaveCardAsync(Guid cardId, string? nickname, CardProfile profile, bool autoImport, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var card = await _db.MediaCards.GetAsync(cardId, cancellationToken).ConfigureAwait(false) ?? throw new ArgumentException($"Unknown card {cardId}.", nameof(cardId));
|
||||
var updated = card with
|
||||
{
|
||||
Nickname = string.IsNullOrWhiteSpace(nickname) ? null : nickname.Trim(),
|
||||
ProfileJson = JsonSerializer.Serialize(profile, ArchiveJobJson.Default.CardProfile),
|
||||
AutoImport = autoImport,
|
||||
};
|
||||
await _db.MediaCards.UpsertAsync(updated, cancellationToken).ConfigureAwait(false);
|
||||
return updated;
|
||||
}
|
||||
|
||||
/// <summary>Scans the source, reads light metadata and plans the import into the archive. Nothing is written
|
||||
/// except the card's camera identity on its first plan.</summary>
|
||||
/// <param name="progress">Photos read so far.</param>
|
||||
public async Task<ImportPlan> PlanAsync(Archive archive, string sourceRoot, ImportOptions options, Guid? cardId, IProgress<int>? progress = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var problems = new List<ImportProblem>();
|
||||
var files = CardScanner.Find(sourceRoot, options.IncludeSubfolders, cancellationToken);
|
||||
var photos = CardScanner.ReadMetadata(sourceRoot, files, problems, progress, cancellationToken);
|
||||
var card = cardId is { } id ? await _db.MediaCards.GetAsync(id, cancellationToken).ConfigureAwait(false) : null;
|
||||
if (card is { CameraModel: null } && photos.Count > 0)
|
||||
{
|
||||
var first = photos[0].Metadata;
|
||||
await _db.MediaCards.UpsertAsync(card with { CameraMake = first.Make, CameraModel = first.Model, CameraSerial = first.BodySerial },
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
var imported = card is null ? new HashSet<ImportKey>() : await _db.MediaCards.GetImportedKeysAsync(card.Id, cancellationToken).ConfigureAwait(false);
|
||||
var folders = (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false)).Select(l => l.Folder)
|
||||
.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var lookup = new IndexLookup(_db, archive.Id, paths, imported, folders);
|
||||
return await ImportPlanner.PlanAsync(sourceRoot, paths.Root, photos, problems, options, lookup, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Runs (or resumes) a confirmed plan; <paramref name="committed"/> sees each batch after its history is recorded.</summary>
|
||||
internal async Task<ImportProgress> ExecuteAsync(ImportJobParameters job, Guid jobId, int startAt, Func<ImportBatch, ValueTask> committed,
|
||||
Func<ImportProgress, ValueTask>? progress, CancellationToken cancellationToken)
|
||||
{
|
||||
var archive = await _db.Archives.GetAsync(job.ArchiveId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException($"Unknown archive {job.ArchiveId}.");
|
||||
ArchiveVolume.EnsureWritable(new ArchivePaths(archive.RootPath));
|
||||
var sink = new IngestSink(_ingest, archive, job.UserId?.ToString());
|
||||
return await new ImportExecutor(job.Plan, sink).RunAsync(startAt, job.Verify, async batch =>
|
||||
{
|
||||
if (job.CardId is { } card) await RecordHistoryAsync(card, jobId, batch, cancellationToken).ConfigureAwait(false);
|
||||
await committed(batch).ConfigureAwait(false);
|
||||
}, progress, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The sequences the sessions of an import went into (new or continued), as far as they exist.</summary>
|
||||
internal async Task<List<Guid>> SequencesOfAsync(ImportJobParameters job, CancellationToken cancellationToken)
|
||||
{
|
||||
var ids = new List<Guid>();
|
||||
foreach (var session in job.Plan.Sessions)
|
||||
{
|
||||
if (await _db.Sequences.FindBySessionKeyAsync(job.ArchiveId, session.SessionKey, cancellationToken).ConfigureAwait(false) is { } id
|
||||
&& !ids.Contains(id)) ids.Add(id);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/// <summary>Dry run of "delete imported": every card file with a recorded import, checked against its archive copy.</summary>
|
||||
public async Task<ErasePlan> PlanEraseAsync(Archive archive, Guid cardId, string sourceRoot, IProgress<int>? progress = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var candidates = new List<EraseCandidate>();
|
||||
foreach (var record in await _db.MediaCards.ListVerifiableImportsAsync(cardId, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (!File.Exists(Path.Combine(sourceRoot, record.Key.Path))) continue;
|
||||
if (await _db.Frames.GetAsync(record.FrameId!.Value, cancellationToken).ConfigureAwait(false) is not { } frame) continue;
|
||||
candidates.Add(new EraseCandidate(record.Key.Path, record.Key.Size, record.Sha256!, paths.FromRelative(frame.RelativePath)));
|
||||
}
|
||||
return await CardEraser.PlanAsync(sourceRoot, candidates, progress, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private Task RecordHistoryAsync(Guid cardId, Guid jobId, ImportBatch batch, CancellationToken cancellationToken)
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var records = new List<ImportRecord>();
|
||||
foreach (var r in batch.Results)
|
||||
{
|
||||
var key = new ImportKey(r.Item.SourcePath, r.Item.Size, new DateTimeOffset(DateTime.SpecifyKind(r.Item.ModifiedUtc, DateTimeKind.Utc)));
|
||||
switch (r.Status)
|
||||
{
|
||||
case ImportItemStatus.Copied or ImportItemStatus.Duplicate:
|
||||
records.Add(new ImportRecord(cardId, key, r.Sha256, r.Commit?.FrameId, jobId, now));
|
||||
break;
|
||||
case ImportItemStatus.Skipped when r.Item.Action == ImportAction.SkipInArchive:
|
||||
records.Add(new ImportRecord(cardId, key, r.Item.Sha256, r.Item.ExistingFrameId, jobId, now));
|
||||
break;
|
||||
}
|
||||
}
|
||||
return records.Count == 0 ? Task.CompletedTask : _db.MediaCards.RecordImportsAsync(records, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Planner questions answered from the index and the archive folder.</summary>
|
||||
private sealed class IndexLookup(ChronosDatabase db, Guid archiveId, ArchivePaths paths, IReadOnlySet<ImportKey> imported, HashSet<string> indexedFolders)
|
||||
: IImportLookup
|
||||
{
|
||||
public Task<bool> WasImportedAsync(CardFile file, CancellationToken cancellationToken) =>
|
||||
Task.FromResult(imported.Contains(new ImportKey(file.RelativePath, file.Size, new DateTimeOffset(DateTime.SpecifyKind(file.ModifiedUtc, DateTimeKind.Utc)))));
|
||||
|
||||
public async Task<IReadOnlyList<ArchiveMatch>> FindCandidatesAsync(long size, DateTime capturedAt, CancellationToken cancellationToken) =>
|
||||
(await db.Frames.FindBySizeAndCaptureAsync(archiveId, size, capturedAt, cancellationToken).ConfigureAwait(false))
|
||||
.Select(f => new ArchiveMatch(f.Id, f.Sha256)).ToList();
|
||||
|
||||
public async Task<string?> FindSessionFolderAsync(string sessionKey, CancellationToken cancellationToken) =>
|
||||
await db.Sequences.FindBySessionKeyAsync(archiveId, sessionKey, cancellationToken).ConfigureAwait(false) is { } id
|
||||
? (await db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false))?.Folder
|
||||
: null;
|
||||
|
||||
public bool IsFolderTaken(string folder)
|
||||
{
|
||||
if (indexedFolders.Contains(folder)) return true;
|
||||
var path = paths.Sequence(folder).Folder;
|
||||
return Directory.Exists(path) && Directory.EnumerateFileSystemEntries(path).Any();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Import destination "Archive": each plan session becomes (or continues) the sequence of its session key.</summary>
|
||||
private sealed class IngestSink(ArchiveIngest ingest, Archive archive, string? createdBy) : IImportSink
|
||||
{
|
||||
public string StagingDirectory { get; } = new ArchivePaths(archive.RootPath).StagingDirectory;
|
||||
|
||||
public async Task<IReadOnlyList<SinkCommit>> CommitAsync(PlannedSession session, IReadOnlyList<StagedFile> files, CancellationToken cancellationToken)
|
||||
{
|
||||
var frames = files.Select(f => new StagedFrame(f.StagedPath, Path.GetFileName(f.Item.SourcePath), f.Item.Size, f.Sha256,
|
||||
MetadataReader.Read(f.StagedPath, cancellationToken), f.Item.CapturedAt, f.Item.FileName)).ToList();
|
||||
var results = await ingest.CommitSessionAsync(archive, new SequenceTarget(session.SessionKey, session.Title, session.Folder, createdBy),
|
||||
frames, cancellationToken).ConfigureAwait(false);
|
||||
return results.Select(r => new SinkCommit(r.FrameId, r.RelativePath, r.Duplicate)).ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.Data.Archiving.Jobs;
|
||||
|
||||
/// <summary><see cref="JobKind.Scan"/>: target = the archive.</summary>
|
||||
/// <param name="DeepAnalysis">The sequences the scan brings into the index (or whose frames it changes) also get a deep
|
||||
/// analysis in the background, after their light one (Settings › Analysis on the desktop).</param>
|
||||
public sealed record ScanParameters(bool Full, bool DeepAnalysis = false);
|
||||
|
||||
/// <summary><see cref="JobKind.Verify"/>: target = the archive; null sequences = all of them.</summary>
|
||||
public sealed record VerifyParameters(IReadOnlyList<Guid>? SequenceIds);
|
||||
|
||||
/// <summary><see cref="JobKind.Thumbs"/> and <see cref="JobKind.Proxies"/>: targets = sequences.</summary>
|
||||
public sealed record ImageJobParameters(bool Force);
|
||||
|
||||
/// <summary><see cref="JobKind.Maintenance"/>: target = the archive.</summary>
|
||||
public sealed record MaintenanceParameters(bool DryRun);
|
||||
|
||||
/// <summary><see cref="JobKind.Import"/>: the exact plan the user confirmed.</summary>
|
||||
public sealed record ImportJobParameters(Guid ArchiveId, ImportPlan Plan, Guid? CardId, bool Verify, Guid? UserId);
|
||||
|
||||
/// <summary>A job ready to enqueue.</summary>
|
||||
public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets, string? Label, string? ParametersJson, JobPriority Priority);
|
||||
|
||||
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true)]
|
||||
[JsonSerializable(typeof(ScanParameters))]
|
||||
[JsonSerializable(typeof(VerifyParameters))]
|
||||
[JsonSerializable(typeof(ImageJobParameters))]
|
||||
[JsonSerializable(typeof(MaintenanceParameters))]
|
||||
[JsonSerializable(typeof(ImportJobParameters))]
|
||||
[JsonSerializable(typeof(CardProfile))]
|
||||
internal sealed partial class ArchiveJobJson : JsonSerializerContext
|
||||
{
|
||||
/// <summary>Parameters of a job, or <paramref name="fallback"/> when it has none.</summary>
|
||||
public static T Read<T>(Job job, System.Text.Json.Serialization.Metadata.JsonTypeInfo<T> typeInfo, T fallback) =>
|
||||
job.ParametersJson is { Length: > 0 } json ? JsonSerializer.Deserialize(json, typeInfo) ?? fallback : fallback;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
|
||||
namespace Chronos.Data.Archiving.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Thumbs"/> and <see cref="JobKind.Proxies"/> over the target sequences. Progress counts frames
|
||||
/// across all targets, so the speed and time left follow the photos even inside a long sequence; checkpoint:
|
||||
/// <c>sequence:frame</c>.
|
||||
/// </summary>
|
||||
internal sealed class ImageJobHandler(ChronosDatabase db, ArchiveImages images, JobKind kind) : IJobHandler
|
||||
{
|
||||
public JobKind Kind => kind;
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
{
|
||||
var force = ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.ImageJobParameters, new ImageJobParameters(false)).Force;
|
||||
var (first, firstFrame) = Parse(context.Checkpoint);
|
||||
var targets = context.Job.TargetIds;
|
||||
var sequences = new Sequence?[targets.Count];
|
||||
long total = 0;
|
||||
for (var s = 0; s < targets.Count; s++)
|
||||
{
|
||||
sequences[s] = await db.Sequences.GetAsync(targets[s], context.Cancellation).ConfigureAwait(false);
|
||||
total += sequences[s]?.FrameCount ?? 0;
|
||||
}
|
||||
long before = 0;
|
||||
for (var s = 0; s < Math.Min(first, targets.Count); s++) before += sequences[s]?.FrameCount ?? 0;
|
||||
for (var s = first; s < targets.Count; s++)
|
||||
{
|
||||
context.Cancellation.ThrowIfCancellationRequested();
|
||||
if (sequences[s] is not { } sequence
|
||||
|| await db.Archives.GetAsync(sequence.ArchiveId, context.Cancellation).ConfigureAwait(false) is not { } archive)
|
||||
{
|
||||
context.Log(Loc.L("Archive.Log.SequenceMissing", targets[s]));
|
||||
before += sequences[s]?.FrameCount ?? 0;
|
||||
continue;
|
||||
}
|
||||
var index = s;
|
||||
var offset = before;
|
||||
ValueTask Checkpoint(int nextFrame, int frames) =>
|
||||
context.CheckpointAsync(string.Create(CultureInfo.InvariantCulture, $"{index}:{nextFrame}"), Math.Min(total, offset + nextFrame), total);
|
||||
var start = s == first ? firstFrame : 0;
|
||||
var result = kind == JobKind.Thumbs
|
||||
? await images.BuildThumbnailsAsync(archive, sequence, force, start, Checkpoint, context.Cancellation).ConfigureAwait(false)
|
||||
: await images.BuildProxiesAsync(archive, sequence, force, start, Checkpoint, context.Cancellation).ConfigureAwait(false);
|
||||
context.Log(kind == JobKind.Thumbs
|
||||
? Loc.L("Archive.Log.ImagesDone", sequence.DisplayTitle, result.Built, result.Reused, result.Undecodable)
|
||||
: Loc.L("Archive.Log.ProxiesDone", sequence.DisplayTitle, result.Built, result.Reused, result.Undecodable, result.Waiting));
|
||||
before += sequence.FrameCount;
|
||||
await context.CheckpointAsync(string.Create(CultureInfo.InvariantCulture, $"{s + 1}:0"), Math.Min(total, before), total).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static (int Sequence, int Frame) Parse(string? checkpoint)
|
||||
{
|
||||
var parts = checkpoint?.Split(':');
|
||||
return parts is [var s, var f]
|
||||
&& int.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out var sequence)
|
||||
&& int.TryParse(f, NumberStyles.None, CultureInfo.InvariantCulture, out var frame)
|
||||
? (sequence, frame)
|
||||
: (0, 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
|
||||
namespace Chronos.Data.Archiving.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Import"/>: executes the confirmed plan in its parameters; progress in bytes. Checkpoint: the
|
||||
/// number of plan items done. A removed card fails the job at a batch boundary; resuming it after re-insertion
|
||||
/// continues there. The sequences the import went into are then queued for light analysis.
|
||||
/// </summary>
|
||||
internal sealed class ImportJobHandler(ChronosDatabase db, ImportService imports) : IJobHandler
|
||||
{
|
||||
public JobKind Kind => JobKind.Import;
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
{
|
||||
var parameters = (context.Job.ParametersJson is { Length: > 0 } json ? JsonSerializer.Deserialize(json, ArchiveJobJson.Default.ImportJobParameters) : null)
|
||||
?? throw new InvalidOperationException($"Import job {context.Job.Id} has no plan.");
|
||||
var start = int.TryParse(context.Checkpoint, NumberStyles.None, CultureInfo.InvariantCulture, out var next) ? next : 0;
|
||||
var final = await imports.ExecuteAsync(parameters, context.Job.Id, start, async batch =>
|
||||
{
|
||||
foreach (var failed in batch.Results.Where(r => r.Status == ImportItemStatus.Failed))
|
||||
context.Log(Loc.L("Archive.Log.ImportFailed", failed.Item.SourcePath, failed.Error));
|
||||
await context.CheckpointAsync(batch.NextItem.ToString(CultureInfo.InvariantCulture), batch.Progress.BytesDone, batch.Progress.BytesTotal)
|
||||
.ConfigureAwait(false);
|
||||
}, p => context.ReportAsync(p.BytesDone, p.BytesTotal, p.Current), context.Cancellation).ConfigureAwait(false);
|
||||
context.Log(Loc.L("Archive.Log.ImportDone", final.Copied, final.Skipped, final.Failed));
|
||||
await AnalysisFollowUp.QueueAsync(db, context, await imports.SequencesOfAsync(parameters, context.Cancellation).ConfigureAwait(false)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
|
||||
namespace Chronos.Data.Archiving.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Maintenance"/>: stale leases, leftover temporary files, thumbnail pack compaction, duplicate
|
||||
/// flags, the SQLite index vacuum (its reclaimable size in a dry run), then an orphan count. Checkpoint: the number of
|
||||
/// steps done.
|
||||
/// </summary>
|
||||
internal sealed class MaintenanceJobHandler(ChronosDatabase db, ArchiveMaintenance maintenance) : IJobHandler
|
||||
{
|
||||
public JobKind Kind => JobKind.Maintenance;
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
{
|
||||
var archive = await JobArchive.LoadAsync(db, context.Job, context.Cancellation).ConfigureAwait(false);
|
||||
var dryRun = ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.MaintenanceParameters, new MaintenanceParameters(false)).DryRun;
|
||||
var first = int.TryParse(context.Checkpoint, NumberStyles.None, CultureInfo.InvariantCulture, out var step) ? step : 0;
|
||||
var report = await maintenance.RunAsync(archive, dryRun, first,
|
||||
done => context.CheckpointAsync(done.ToString(CultureInfo.InvariantCulture), done, ArchiveMaintenance.StepCount),
|
||||
context.Cancellation).ConfigureAwait(false);
|
||||
if (dryRun) context.Log(Loc.L("Archive.Log.DryRun"));
|
||||
context.Log(Loc.L("Archive.Log.MaintenanceDone", report.StaleLeases.Count, report.TemporaryFiles.Count, report.CompactedPacks.Count,
|
||||
report.DuplicateFlagChanges));
|
||||
if (report.IndexReclaimed > 0) context.Log(Loc.L("Archive.Log.IndexVacuumed", Megabytes(report.IndexReclaimed)));
|
||||
else if (report.IndexReclaimable is { } reclaimable) context.Log(Loc.L("Archive.Log.IndexReclaimable", Megabytes(reclaimable)));
|
||||
context.Log(Loc.L("Archive.Log.Orphans", report.UnindexedFiles, report.MissingFiles));
|
||||
}
|
||||
|
||||
/// <summary>"12.4 MB" in the language of the log.</summary>
|
||||
private static string Megabytes(long bytes) => Loc.L("Common.Size.MB", (bytes / 1e6).ToString("0.#", Loc.Culture));
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.Data.Archiving.Jobs;
|
||||
|
||||
/// <summary>Resolves the archive a job targets (its first target id).</summary>
|
||||
internal static class JobArchive
|
||||
{
|
||||
public static async Task<Archive> LoadAsync(ChronosDatabase db, Job job, CancellationToken cancellationToken) =>
|
||||
job.TargetIds.Count > 0 && await db.Archives.GetAsync(job.TargetIds[0], cancellationToken).ConfigureAwait(false) is { } archive
|
||||
? archive
|
||||
: throw new InvalidOperationException($"{job.Kind} job {job.Id} does not target a known archive.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Scan"/> (incremental, or full with <see cref="ScanParameters.Full"/>) and
|
||||
/// <see cref="JobKind.Rebuild"/>. Checkpoint: <c>after:<folder></c>, the last folder indexed. When anything was
|
||||
/// indexed, the sequences without a current light analysis (adopted folders, new sidecars, photos added to a folder) are
|
||||
/// queued for it, and for a background deep analysis too when <see cref="ScanParameters.DeepAnalysis"/> asks. On the
|
||||
/// server (<paramref name="imagesAfterScan"/>, <see cref="ArchiveServiceOptions.ImagesAfterScan"/>) the sequences it indexed
|
||||
/// without thumbnails or proxies are queued for them too, one pass per sequence as after an upload. Sequences waiting for
|
||||
/// their first frame (<see cref="ArchiveIndexer.AwaitingFolderAsync"/>) have nothing to analyse or draw yet and are left out.
|
||||
/// </summary>
|
||||
internal sealed class ScanJobHandler(ChronosDatabase db, ArchiveIndexer indexer, JobKind kind, bool imagesAfterScan = false) : IJobHandler
|
||||
{
|
||||
private const string Prefix = "after:";
|
||||
|
||||
public JobKind Kind => kind;
|
||||
|
||||
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.ScanParameters, new ScanParameters(false));
|
||||
var mode = kind == JobKind.Rebuild ? ScanMode.Rebuild : parameters.Full ? ScanMode.Full : ScanMode.Incremental;
|
||||
var resume = context.Checkpoint is { } checkpoint && checkpoint.StartsWith(Prefix, StringComparison.Ordinal) ? checkpoint[Prefix.Length..] : null;
|
||||
var summary = await indexer.ScanAsync(archive, mode, resume, async p =>
|
||||
{
|
||||
if (p.Changed) await context.CheckpointAsync(Prefix + p.Folder, p.FoldersDone, p.FoldersTotal).ConfigureAwait(false);
|
||||
else await context.ReportAsync(p.FoldersDone, p.FoldersTotal, p.Folder).ConfigureAwait(false);
|
||||
}, context.Cancellation).ConfigureAwait(false);
|
||||
foreach (var (folder, error) in summary.Failed) context.Log(Loc.L("Archive.Log.FolderFailed", folder, error));
|
||||
context.Log(Loc.L("Archive.Log.ScanDone", summary.Folders, summary.Indexed, summary.Adopted, summary.Removed));
|
||||
// A resumed scan may have indexed its folders before the interruption.
|
||||
if (summary.Indexed > 0 || resume is not null)
|
||||
{
|
||||
var awaiting = await indexer.AwaitingFolderAsync(new ArchivePaths(archive.RootPath),
|
||||
await db.Sequences.ListLocationsAsync(archive.Id, context.Cancellation).ConfigureAwait(false), context.Cancellation).ConfigureAwait(false);
|
||||
var unanalysed = (await AnalysisFollowUp.UnanalysedAsync(db, archive.Id, context.Cancellation).ConfigureAwait(false))
|
||||
.Where(id => !awaiting.Contains(id)).ToList();
|
||||
await AnalysisFollowUp.QueueAsync(db, context, unanalysed).ConfigureAwait(false);
|
||||
if (kind == JobKind.Scan && parameters.DeepAnalysis) await AnalysisFollowUp.QueueDeepAsync(db, context, unanalysed).ConfigureAwait(false);
|
||||
if (imagesAfterScan)
|
||||
{
|
||||
var resumed = resume is not null;
|
||||
await QueueImagesAsync(context, archive, JobKind.Thumbs, SequenceStatus.ThumbsBuilt, summary.Sequences, resumed, awaiting).ConfigureAwait(false);
|
||||
// An archive whose policy makes no proxies would get a pass that does nothing.
|
||||
if (archive.ProxyLongEdge != ProxyPolicy.Disabled)
|
||||
await QueueImagesAsync(context, archive, JobKind.Proxies, SequenceStatus.ProxiesBuilt, summary.Sequences, resumed, awaiting).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues a background <paramref name="pass"/> (thumbnails or proxies) of each sequence this run indexed whose
|
||||
/// <paramref name="built"/> flag is clear: new and adopted sequences, and those whose photos changed (the scan clears the
|
||||
/// flag then, in this server's own row when another writer listed them in the sidecar itself). After a resumed run,
|
||||
/// which may have indexed sequences before the interruption, of every sequence of the archive without the flag but
|
||||
/// those in <paramref name="awaiting"/>. One pass per sequence, as after an upload: a folder renamed, deleted or
|
||||
/// damaged before its pass runs fails that pass alone, and the other sequences still get their images. A sequence
|
||||
/// whose own pass of that kind is already queued is left out.
|
||||
/// </summary>
|
||||
private async Task QueueImagesAsync(JobContext context, Archive archive, JobKind pass, SequenceStatus built, IReadOnlyList<Guid> indexed,
|
||||
bool resumed, IReadOnlySet<Guid> awaiting)
|
||||
{
|
||||
var missing = new Dictionary<Guid, Sequence>();
|
||||
var query = new SequenceQuery { ArchiveId = archive.Id, WithoutStatus = built, Sort = SequenceSort.Oldest, Limit = 1000 };
|
||||
do
|
||||
{
|
||||
var page = await db.Sequences.ListAsync(query, context.Cancellation).ConfigureAwait(false);
|
||||
foreach (var sequence in page.Items) missing[sequence.Id] = sequence;
|
||||
query = query with { Cursor = page.NextCursor };
|
||||
}
|
||||
while (query.Cursor is not null);
|
||||
var targets = resumed ? missing.Values.ToList() : indexed.Distinct().Where(missing.ContainsKey).Select(id => missing[id]).ToList();
|
||||
foreach (var sequence in targets)
|
||||
{
|
||||
if (awaiting.Contains(sequence.Id) || await db.Jobs.IsQueuedAsync(pass, sequence.Id, context.Cancellation).ConfigureAwait(false)) continue;
|
||||
var request = pass == JobKind.Thumbs
|
||||
? ArchiveJobs.Thumbnails([sequence.Id], sequence.DisplayTitle)
|
||||
: ArchiveJobs.Proxies([sequence.Id], sequence.DisplayTitle);
|
||||
await context.EnqueueFollowUpAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
|
||||
namespace Chronos.Data.Archiving.Jobs;
|
||||
|
||||
/// <summary><see cref="JobKind.Verify"/>; progress in bytes hashed. Checkpoint: <c>sequence:frame</c>.</summary>
|
||||
internal sealed class VerifyJobHandler(ChronosDatabase db, ArchiveVerifier verifier) : IJobHandler
|
||||
{
|
||||
/// <summary>Problems listed one per log line; the rest are counted (the index flags them all).</summary>
|
||||
private const int LoggedProblems = 25;
|
||||
|
||||
public JobKind Kind => JobKind.Verify;
|
||||
|
||||
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.VerifyParameters, new VerifyParameters(null));
|
||||
var report = await verifier.VerifyAsync(archive, parameters.SequenceIds, Parse(context.Checkpoint),
|
||||
(position, done, total) => context.CheckpointAsync(
|
||||
string.Create(CultureInfo.InvariantCulture, $"{position.Sequence}:{position.Frame}"), done, total),
|
||||
(done, total) => context.ReportAsync(done, total),
|
||||
context.Cancellation).ConfigureAwait(false);
|
||||
foreach (var problem in report.Problems.Take(LoggedProblems))
|
||||
{
|
||||
context.Log(problem.Health switch
|
||||
{
|
||||
FrameHealth.Missing => Loc.L("Archive.Log.FrameMissing", problem.RelativePath),
|
||||
FrameHealth.Changed => Loc.L("Archive.Log.FrameChanged", problem.RelativePath),
|
||||
_ => Loc.L("Archive.Log.FrameCorrupt", problem.RelativePath),
|
||||
});
|
||||
}
|
||||
context.Log(Loc.L("Archive.Log.VerifyDone", report.Checked, report.Ok, report.Hashed, report.Problems.Count));
|
||||
}
|
||||
|
||||
private static VerifyPosition Parse(string? checkpoint)
|
||||
{
|
||||
var parts = checkpoint?.Split(':');
|
||||
return parts is [var s, var f]
|
||||
&& int.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out var sequence)
|
||||
&& int.TryParse(f, NumberStyles.None, CultureInfo.InvariantCulture, out var frame)
|
||||
? new VerifyPosition(sequence, frame)
|
||||
: default;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// The plan no longer matches the archive: a sequence moved or vanished since it was made, or one was indexed inside a
|
||||
/// folder the plan moves.
|
||||
/// </summary>
|
||||
public sealed class StaleRenamePlanException(Guid sequenceId)
|
||||
: InvalidOperationException(Loc.L("Archive.Error.StalePlan"))
|
||||
{
|
||||
public Guid SequenceId { get; } = sequenceId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mass rename of sequence folders and titles (BRIEF §7, §12.5): <see cref="PlanAsync"/> is the dry run;
|
||||
/// <see cref="ApplyAsync"/> makes exactly the planned changes to folders, sidecars and the index, step by step, with a
|
||||
/// journal on the archive so an interrupted rename is completed by <see cref="ResumePendingAsync"/>.
|
||||
/// </summary>
|
||||
public sealed class MassRenamer
|
||||
{
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly SequenceWriter _writer;
|
||||
private readonly ArchiveIndexer _indexer;
|
||||
|
||||
internal MassRenamer(ChronosDatabase db, SequenceWriter writer, ArchiveIndexer indexer)
|
||||
{
|
||||
_db = db;
|
||||
_writer = writer;
|
||||
_indexer = indexer;
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var locations = await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false);
|
||||
var subjects = new List<RenameSubject>(sequenceIds.Count);
|
||||
foreach (var id in sequenceIds)
|
||||
{
|
||||
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(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), 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, or a folder that moves holds
|
||||
/// a sequence the plan does not take along; nothing of that step was changed.</exception>
|
||||
public Task ApplyAsync(Archive archive, RenamePlan plan, IProgress<int>? progress = null, CancellationToken cancellationToken = default) =>
|
||||
RunAsync(archive, new RenameJournal(plan, []), resuming: false, progress, cancellationToken);
|
||||
|
||||
/// <summary>Completes renames interrupted by a crash; returns how many plans were resumed.</summary>
|
||||
public async Task<int> ResumePendingAsync(Archive archive, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var pending = RenameJournal.ListPending(paths).Where(j => j.Plan.ArchiveId == archive.Id).ToList();
|
||||
foreach (var journal in pending) await RunAsync(archive, journal, resuming: true, null, cancellationToken).ConfigureAwait(false);
|
||||
return pending.Count;
|
||||
}
|
||||
|
||||
/// <param name="resuming">Steps whose sequence the index no longer knows are dropped instead of failing the rename:
|
||||
/// their sidecars still carry the ids, so the next scan indexes them wherever they ended up.</param>
|
||||
private async Task RunAsync(Archive archive, RenameJournal journal, bool resuming, IProgress<int>? progress, CancellationToken cancellationToken)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
if (journal.Plan.ArchiveId != archive.Id) throw new ArgumentException("The plan belongs to another archive.", nameof(journal));
|
||||
var completed = journal.Completed.ToHashSet();
|
||||
if (!resuming)
|
||||
{
|
||||
// A plan made before another change is refused before anything moves: a sequence moved, or one was indexed
|
||||
// inside a folder that moves (a scan adopted a subfolder copied in since the dry run).
|
||||
foreach (var step in journal.Plan.Steps)
|
||||
{
|
||||
if ((await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false))?.Folder != step.FromFolder)
|
||||
throw new StaleRenamePlanException(step.SequenceId);
|
||||
}
|
||||
var planned = journal.Plan.Steps.Select(s => s.SequenceId).ToHashSet();
|
||||
if (await StrangerInsideAsync(archive, journal.Plan.Steps.Where(s => s.MovesFolder && !s.Carried), planned, cancellationToken)
|
||||
.ConfigureAwait(false) is { } stranger)
|
||||
throw new StaleRenamePlanException(stranger.Id);
|
||||
}
|
||||
RenameJournal.Write(paths, journal);
|
||||
var steps = journal.Plan.Steps;
|
||||
foreach (var step in steps)
|
||||
{
|
||||
if (completed.Contains(step.SequenceId)) continue;
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// 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(completed.Count);
|
||||
}
|
||||
RenameJournal.Delete(paths, journal.Plan.Id);
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
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
|
||||
{
|
||||
foreach (var id in ids) locks.Add(await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false));
|
||||
if (step.MovesFolder)
|
||||
{
|
||||
foreach (var id in ids)
|
||||
{
|
||||
leases.Add(await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{id:N}", _writer.Options.Owner, _writer.Options.LeaseWait,
|
||||
_writer.Options.LeaseDuration, 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)
|
||||
{
|
||||
if (await StandsAsync(c, resuming, cancellationToken).ConfigureAwait(false)) follow.Add(c);
|
||||
}
|
||||
if (!await CarriesAllInsideAsync(archive, paths, step, carried, resuming, cancellationToken).ConfigureAwait(false)) return;
|
||||
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>
|
||||
/// Whether every sequence the index has inside the folder of a moving step moves with it as planned, checked again under
|
||||
/// the step's leases just before the folder moves. One indexed there since the dry run would move without its index
|
||||
/// row following, and was never shown in the plan: the step is refused, or dropped when resuming a folder that has not
|
||||
/// moved yet (a folder moved before the interruption goes on; the next scan indexes the newcomer where it ended up).
|
||||
/// </summary>
|
||||
/// <exception cref="StaleRenamePlanException">Not resuming, and such a sequence is inside the folder.</exception>
|
||||
private async Task<bool> CarriesAllInsideAsync(Archive archive, ArchivePaths paths, RenameStep step, IReadOnlyList<RenameStep> carried, bool resuming,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!step.MovesFolder) return true;
|
||||
var taken = carried.Select(c => c.SequenceId).ToHashSet();
|
||||
if (await StrangerInsideAsync(archive, [step], taken, cancellationToken).ConfigureAwait(false) is not { } stranger) return true;
|
||||
if (!resuming) throw new StaleRenamePlanException(stranger.Id);
|
||||
if (!Directory.Exists(paths.Sequence(step.FromFolder).Folder)) return true;
|
||||
Log.Warning("archive", $"Rename of {step.FromFolder} dropped: {stranger.Folder} was indexed inside it after the plan was made");
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>A sequence the index has inside the folder of one of <paramref name="moving"/> that is not in <paramref name="taken"/>; null when there is none.</summary>
|
||||
private async Task<SequenceLocation?> StrangerInsideAsync(Archive archive, IEnumerable<RenameStep> moving, IReadOnlySet<Guid> taken,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var folders = moving.Select(s => s.FromFolder).ToList();
|
||||
if (folders.Count == 0) return null;
|
||||
return (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false))
|
||||
.FirstOrDefault(l => !taken.Contains(l.Id) && folders.Any(f => RenamePlanner.IsInside(f, l.Folder)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sidecar title, then index (folder, title, frames' paths); each part is idempotent so a resumed step can repeat it.
|
||||
/// The index row changes in its folder and title only (<see cref="SequenceRepository.RelocateAsync"/>): a settings edit
|
||||
/// committed meanwhile stays, and frames another process listed in the sidecar are left to the next scan, for which
|
||||
/// the folder keeps no stamps unless the index held it as it was
|
||||
/// (<see cref="ArchiveIndexer.InStepAsync(Archive, string, SequencePaths, SequenceManifest, CancellationToken)"/>).
|
||||
/// </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);
|
||||
// The folder moved with its files' stamps, which the index recorded at its old place.
|
||||
var inStep = await _indexer.InStepAsync(archive, step.FromFolder, sequence, manifest, cancellationToken).ConfigureAwait(false);
|
||||
// A step that only moves the folder keeps the title, which an edit may have changed since the plan.
|
||||
var retitle = step.FromTitle != step.ToTitle;
|
||||
if (retitle && 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))
|
||||
{
|
||||
await tx.Sequences.RelocateAsync(step.SequenceId, step.ToFolder, retitle ? step.ToTitle : null, 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 (inStep) await _indexer.RecordStampsAsync(archive, sequence, step.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// The frames of a pass worked on several at once (owner review 1, R2: the parallelism decides how many photos the running
|
||||
/// job processes at once). Each item's work runs on the thread pool, at most <c>parallelism</c> at a time, and its result
|
||||
/// is handed to the consumer in the order the items were added, on the caller's flow: whatever the consumer writes (one
|
||||
/// thumbnail pack writer, counters, a checkpoint at a frame index, which then says that every frame before it is done)
|
||||
/// stays sequential and ordered, as in a pass that works on one frame at a time. With a parallelism of one the work runs
|
||||
/// inline. At most twice the parallelism of results wait to be consumed.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Dispose it in every case (<c>await using</c>): after a failure or a cancellation it stops the work still running and
|
||||
/// waits for it, so nothing a pass started outlives it.
|
||||
/// </remarks>
|
||||
internal sealed class OrderedWork<T> : IAsyncDisposable
|
||||
{
|
||||
private readonly Queue<Task<T>> _window = new();
|
||||
private readonly int _parallelism;
|
||||
private readonly Func<T, ValueTask> _consume;
|
||||
private readonly CancellationTokenSource _stop;
|
||||
private readonly SemaphoreSlim _slots;
|
||||
|
||||
public OrderedWork(int parallelism, Func<T, ValueTask> consume, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(parallelism, 1);
|
||||
_parallelism = parallelism;
|
||||
_consume = consume;
|
||||
_stop = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
_slots = new SemaphoreSlim(parallelism, parallelism);
|
||||
}
|
||||
|
||||
/// <summary>Starts <paramref name="work"/>, first consuming earlier results while too many wait.</summary>
|
||||
public async ValueTask AddAsync(Func<CancellationToken, T> work)
|
||||
{
|
||||
var token = _stop.Token;
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (_parallelism == 1)
|
||||
{
|
||||
await _consume(work(token)).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
while (_window.Count >= 2 * _parallelism) await ConsumeNextAsync().ConfigureAwait(false);
|
||||
_window.Enqueue(RunAsync(work, token));
|
||||
await ConsumeFinishedAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>A result known without work, consumed in its turn.</summary>
|
||||
public async ValueTask AddAsync(T ready)
|
||||
{
|
||||
_stop.Token.ThrowIfCancellationRequested();
|
||||
if (_window.Count == 0)
|
||||
{
|
||||
await _consume(ready).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
_window.Enqueue(Task.FromResult(ready));
|
||||
await ConsumeFinishedAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Waits for the work still running and consumes every result in order.</summary>
|
||||
public async ValueTask CompleteAsync()
|
||||
{
|
||||
while (_window.Count > 0) await ConsumeNextAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_window.Count > 0)
|
||||
{
|
||||
await _stop.CancelAsync().ConfigureAwait(false);
|
||||
foreach (var task in _window)
|
||||
{
|
||||
try
|
||||
{
|
||||
await task.ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// The pass already fails or stops with its own exception; the abandoned work's says nothing more.
|
||||
}
|
||||
}
|
||||
_window.Clear();
|
||||
}
|
||||
_stop.Dispose();
|
||||
_slots.Dispose();
|
||||
}
|
||||
|
||||
private async Task<T> RunAsync(Func<CancellationToken, T> work, CancellationToken token)
|
||||
{
|
||||
await _slots.WaitAsync(token).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
return await Task.Run(() => work(token), token).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_slots.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async ValueTask ConsumeNextAsync()
|
||||
{
|
||||
var result = await _window.Peek().ConfigureAwait(false);
|
||||
_ = _window.Dequeue();
|
||||
await _consume(result).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async ValueTask ConsumeFinishedAsync()
|
||||
{
|
||||
while (_window.TryPeek(out var next) && next.IsCompleted) await ConsumeNextAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// Keeps a project's frame positions (exclusions, hero, virtual-camera keyframes; BRIEF §5, §7) on their frames when the
|
||||
/// index takes a sidecar in which frames were inserted before others: an upload or import of earlier photos, photos a
|
||||
/// scan found, a sync download, a journalled batch completed after a crash. Positions name the frames in the indexed
|
||||
/// order (what editors, renders and the API read), so the old order comes from the index rows. Only an insertion is
|
||||
/// followed: when an indexed frame is no longer in the sidecar, positions cannot be mapped and stay as they are. The move
|
||||
/// is part of the frames change, not a settings edit, so the settings version stays. Settings synced from another copy
|
||||
/// arrive translated to this copy's frames (<see cref="ProjectSettings.TranslateFramePositions"/>); their positions on
|
||||
/// photos that were not here yet (<see cref="ProjectSettings.PendingFrames"/>) take their place when the photos arrive,
|
||||
/// wherever they land.
|
||||
/// </summary>
|
||||
internal static class ProjectPositions
|
||||
{
|
||||
/// <summary>
|
||||
/// The index's copy of the project (the one in force) with its positions moved to the order of
|
||||
/// <paramref name="manifest"/> and its pending frames placed; null when nothing changes. A <c>project.json</c> the
|
||||
/// index has no copy of was written by another process against its own frames, so it is left to that writer.
|
||||
/// </summary>
|
||||
public static async Task<PositionMove?> MoveAsync(ChronosRepositories db, Sequence indexed, SequenceManifest manifest,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// The sidecar's frames are the ones indexed: nothing was inserted.
|
||||
if (indexed.FramesVersion == manifest.Versions.Frames) return null;
|
||||
if (indexed.SettingsJson is not { } project) return null;
|
||||
var rows = await db.Frames.ListPositionsAsync(indexed.Id, cancellationToken).ConfigureAwait(false);
|
||||
var now = new Dictionary<Guid, int>(manifest.Frames.Count);
|
||||
foreach (var frame in manifest.Frames) now[frame.Id] = frame.I;
|
||||
Dictionary<int, int>? moves = [];
|
||||
foreach (var row in rows)
|
||||
{
|
||||
if (!now.TryGetValue(row.FrameId, out var index))
|
||||
{
|
||||
moves = null;
|
||||
break;
|
||||
}
|
||||
if (index != row.Index) moves[row.Index] = index;
|
||||
}
|
||||
return Placed(project, moves is null ? null : ProjectSettings.MoveFramePositions(project, moves), manifest);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The index's copy of the project with the pending frames whose photos <paramref name="manifest"/> now holds put in
|
||||
/// place: frames appended in step with the index, which moves no position. Null when nothing changes.
|
||||
/// </summary>
|
||||
public static PositionMove? Place(Sequence indexed, SequenceManifest manifest) =>
|
||||
indexed.SettingsJson is { } project ? Placed(project, null, manifest) : null;
|
||||
|
||||
private static PositionMove? Placed(string before, string? moved, SequenceManifest manifest)
|
||||
{
|
||||
var current = moved ?? before;
|
||||
// Most projects wait for no photo: the sidecar's photos are gathered only for those that do.
|
||||
var placed = current.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase)
|
||||
? ProjectSettings.TranslateFramePositions(current, null, new FramePhotos(manifest.Frames.Select(f => (f.I, new FramePhoto(f.Sha256, f.Size, f.CapturedAt)))))
|
||||
: null;
|
||||
if ((placed ?? moved) is not { } after) return null;
|
||||
// A hero that waited for its photo names a frame the Library shows too.
|
||||
var hero = placed is not null && HeroOf(current) is null && HeroOf(placed) is { } index ? manifest.Frames.FirstOrDefault(f => f.I == index)?.Id : null;
|
||||
return new PositionMove(before, after, hero);
|
||||
}
|
||||
|
||||
private static int? HeroOf(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonNode.Parse(json, new JsonNodeOptions { PropertyNameCaseInsensitive = true }) is JsonObject project
|
||||
&& project["heroFrame"] is JsonValue value && value.TryGetValue<int>(out var hero)
|
||||
? hero
|
||||
: null;
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or ArgumentException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mirrors moved positions into <c>project.json</c> once the index holds them, unless the file was written since
|
||||
/// (it then belongs to that writer, whose next save mirrors the index again). A failed write leaves the index right.
|
||||
/// </summary>
|
||||
public static void WriteProject(SequencePaths sequence, string before, string moved)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(sequence.ProjectPath) && !SameJson(AtomicFile.ReadAllText(sequence.ProjectPath), before)) return;
|
||||
Directory.CreateDirectory(sequence.MetaDirectory);
|
||||
AtomicFile.WriteAllText(sequence.ProjectPath, moved);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"Project of {sequence.RelativeFolder} keeps its old frame positions on disk", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Same JSON content whatever the layout (an index may store it normalised).</summary>
|
||||
private static bool SameJson(string a, string b)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonNode.DeepEquals(JsonNode.Parse(a), JsonNode.Parse(b));
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A project whose positions followed its frames: the index's copy before and after, and the frame a hero that waited
|
||||
/// for its photo now names (the index's hero frame follows it); null when the hero frame stays.
|
||||
/// </summary>
|
||||
internal sealed record PositionMove(string Before, string Moved, Guid? HeroFrameId)
|
||||
{
|
||||
/// <summary>The index row with the moved project.</summary>
|
||||
public Sequence ApplyTo(Sequence row) => row with { SettingsJson = Moved, HeroFrameId = HeroFrameId ?? row.HeroFrameId };
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>Sidecar records to index rows. Fields the sidecar does not carry are kept from the existing row.</summary>
|
||||
internal static class SequenceMapping
|
||||
{
|
||||
public static Frame ToFrame(SidecarFrame f, Guid sequenceId, SequencePaths sequence) => new()
|
||||
{
|
||||
Id = f.Id,
|
||||
SequenceId = sequenceId,
|
||||
Index = f.I,
|
||||
RelativePath = sequence.ArchiveRelative(f.File),
|
||||
FileName = Path.GetFileName(f.File),
|
||||
OriginalFileName = f.Original,
|
||||
Size = f.Size,
|
||||
Sha256 = f.Sha256,
|
||||
CapturedAt = f.CapturedAt,
|
||||
UtcOffsetMinutes = f.UtcOffset,
|
||||
TimestampSource = f.TimeSource,
|
||||
ExposureTime = f.Exposure,
|
||||
FNumber = f.FNumber,
|
||||
Iso = f.Iso,
|
||||
FocalLength = f.Focal,
|
||||
ExposureBias = f.Bias,
|
||||
WhiteBalance = f.Wb,
|
||||
Orientation = f.Orientation,
|
||||
Width = f.W,
|
||||
Height = f.H,
|
||||
Format = f.Format,
|
||||
PreviewOffset = f.PreviewOffset,
|
||||
PreviewLength = f.PreviewLength,
|
||||
PreviewWidth = f.PreviewW ?? 0,
|
||||
PreviewHeight = f.PreviewH ?? 0,
|
||||
Flags = f.Flags,
|
||||
};
|
||||
|
||||
public static List<Frame> ToFrames(SequenceManifest manifest, SequencePaths sequence) =>
|
||||
manifest.Frames.Select(f => ToFrame(f, manifest.Id, sequence)).ToList();
|
||||
|
||||
/// <param name="existing">The current row; its render, analysis, sync and ownership fields are kept, and so are its
|
||||
/// title, tags, rating and notes when its settings version is ahead of the sidecar's (edited in the index only).</param>
|
||||
public static Sequence ToSequence(SequenceManifest m, Guid archiveId, SequencePaths sequence, Sequence? existing)
|
||||
{
|
||||
var indexAhead = existing is not null && existing.SettingsVersion > m.Versions.Settings;
|
||||
var times = m.Frames.Where(f => f.CapturedAt is not null).Select(f => f.CapturedAt!.Value).Order().ToList();
|
||||
var flagged = m.Frames.Any(f => (f.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0);
|
||||
return new Sequence
|
||||
{
|
||||
Id = m.Id,
|
||||
ArchiveId = archiveId,
|
||||
Title = indexAhead ? existing!.Title : m.Title,
|
||||
Folder = sequence.RelativeFolder,
|
||||
CameraMake = m.Camera?.Make,
|
||||
CameraModel = m.Camera?.Model,
|
||||
CameraSerial = m.Camera?.Serial,
|
||||
Lens = m.Lens,
|
||||
FirstCapture = times.Count > 0 ? times[0] : null,
|
||||
LastCapture = times.Count > 0 ? times[^1] : null,
|
||||
FrameCount = m.Frames.Count,
|
||||
MedianInterval = MedianInterval(times),
|
||||
TotalBytes = m.Frames.Sum(f => f.Size),
|
||||
Status = flagged ? m.Status | SequenceStatus.HasErrors : m.Status & ~SequenceStatus.HasErrors,
|
||||
VerifiedAt = m.VerifiedAt,
|
||||
Tags = indexAhead ? existing!.Tags : m.Tags,
|
||||
Rating = indexAhead ? existing!.Rating : m.Rating,
|
||||
Notes = indexAhead ? existing!.Notes : m.Notes,
|
||||
SettingsVersion = indexAhead ? existing!.SettingsVersion : m.Versions.Settings,
|
||||
FramesVersion = m.Versions.Frames,
|
||||
UpdatedAt = m.UpdatedAt,
|
||||
RenderedCount = existing?.RenderedCount ?? 0,
|
||||
HeroFrameId = existing?.HeroFrameId,
|
||||
SettingsJson = existing?.SettingsJson ?? ReadProject(sequence),
|
||||
AnalysisJson = existing?.AnalysisJson,
|
||||
Origin = existing?.Origin ?? SequenceOrigin.Local,
|
||||
SyncState = existing?.SyncState ?? SyncState.LocalOnly,
|
||||
OwnerUserId = existing?.OwnerUserId ?? (Guid.TryParse(m.CreatedBy, out var owner) ? owner : null),
|
||||
WarningCount = existing?.WarningCount ?? 0,
|
||||
PreviewOnlyCount = m.Frames.Count(f => (f.Flags & FrameFlags.PreviewOnly) != 0),
|
||||
};
|
||||
}
|
||||
|
||||
private static double? MedianInterval(List<DateTime> times)
|
||||
{
|
||||
if (times.Count < 2) return null;
|
||||
var gaps = new double[times.Count - 1];
|
||||
for (var i = 1; i < times.Count; i++) gaps[i - 1] = (times[i] - times[i - 1]).TotalSeconds;
|
||||
Array.Sort(gaps);
|
||||
var mid = gaps.Length / 2;
|
||||
return gaps.Length % 2 == 1 ? gaps[mid] : (gaps[mid - 1] + gaps[mid]) / 2;
|
||||
}
|
||||
|
||||
/// <summary>The project file is owned by the editor; a rebuilt index takes its text as-is when it is valid JSON.</summary>
|
||||
private static string? ReadProject(SequencePaths sequence)
|
||||
{
|
||||
if (!File.Exists(sequence.ProjectPath)) return null;
|
||||
var text = AtomicFile.ReadAllText(sequence.ProjectPath);
|
||||
try
|
||||
{
|
||||
using (JsonDocument.Parse(text)) return text;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>Why a sequence cannot go to the trash; nothing of it is touched.</summary>
|
||||
public enum DeleteBlock
|
||||
{
|
||||
/// <summary>The archive is offline or read-only.</summary>
|
||||
Offline,
|
||||
|
||||
/// <summary>The photos lie in the archive root itself (a folder adopted in place): the root never moves.</summary>
|
||||
ArchiveRoot,
|
||||
|
||||
/// <summary>Other sequences live in folders below this one; moving it would take them along.</summary>
|
||||
ContainsSequences,
|
||||
|
||||
/// <summary>A running or paused job works on the sequence, or on its whole archive (a scan, a rebuild, an import, a verify, maintenance).</summary>
|
||||
Busy,
|
||||
|
||||
/// <summary>The folder's sidecar names another sequence: the index is out of date (a scan fixes it).</summary>
|
||||
ForeignSidecar,
|
||||
|
||||
/// <summary>The index names a folder that is not on disk: there is nothing to keep in the trash, so the Orphans check removes the row.</summary>
|
||||
FolderMissing,
|
||||
}
|
||||
|
||||
/// <summary>One sequence of a delete plan: its folder moves to <see cref="TrashFolder"/> and its index rows go.</summary>
|
||||
/// <param name="TrashFolder">Archive-relative folder the sequence folder moves to; null for a sequence that has no folder yet (created on the server, no photo received), of which only the rows go.</param>
|
||||
/// <param name="Files">Files under the folder (originals, proxies, exports, sidecars).</param>
|
||||
/// <param name="Bytes">Their size on disk.</param>
|
||||
public sealed record DeleteStep(Sequence Sequence, string? TrashFolder, int Files, long Bytes);
|
||||
|
||||
public sealed record BlockedDelete(Sequence Sequence, DeleteBlock Reason);
|
||||
|
||||
/// <summary>The dry run of moving sequences to their archive's trash (BRIEF §0.2 rule 8): what moves, and what cannot.</summary>
|
||||
public sealed record DeletePlan(IReadOnlyList<DeleteStep> Steps, IReadOnlyList<BlockedDelete> Blocked)
|
||||
{
|
||||
public int Frames => Steps.Sum(s => s.Sequence.FrameCount);
|
||||
public int Files => Steps.Sum(s => s.Files);
|
||||
public long Bytes => Steps.Sum(s => s.Bytes);
|
||||
public int Renders => Steps.Sum(s => s.Sequence.RenderedCount);
|
||||
}
|
||||
|
||||
/// <summary>A deleted sequence kept in an archive's trash, as <see cref="SequenceTrash.ListAsync"/> lists it.</summary>
|
||||
/// <param name="Name">Folder name inside the trash; pass it to <see cref="SequenceTrash.RestoreAsync"/>.</param>
|
||||
/// <param name="Folder">Archive-relative folder the sequence came from (and returns to when it is free).</param>
|
||||
public sealed record TrashEntry(Guid ArchiveId, string Name, Guid SequenceId, string Title, string Folder, int Frames, int Files, long Bytes,
|
||||
DateTimeOffset DeletedAt, string? DeletedBy);
|
||||
|
||||
/// <summary>The plan no longer matches the index or the jobs (a sequence moved, vanished or got busy since it was made); nothing was deleted.</summary>
|
||||
public sealed class StaleDeletePlanException(Guid sequenceId) : InvalidOperationException(Loc.L("Archive.Error.StalePlan"))
|
||||
{
|
||||
public Guid SequenceId { get; } = sequenceId;
|
||||
}
|
||||
|
||||
/// <summary>A trash entry cannot come back: the index already holds its sequence (restored before, or scanned again); nothing moved.</summary>
|
||||
public sealed class SequenceInLibraryException(Guid sequenceId, string title) : InvalidOperationException(Loc.L("Archive.Error.InLibrary", title))
|
||||
{
|
||||
public Guid SequenceId { get; } = sequenceId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deleting sequences without erasing anything (BRIEF §0.2 rule 8, §12.2, §12.5): <see cref="PlanAsync"/> is the dry
|
||||
/// run; <see cref="DeleteAsync"/> moves each sequence folder whole — originals, proxies, exports and its sidecars — into
|
||||
/// <c>.chronos/trash/<id></c> of its archive under the sequence's leases, next to a record of its index row and
|
||||
/// renders, then removes the index rows. <see cref="RestoreAsync"/> moves a folder back and indexes it again from its
|
||||
/// sidecar with the same ids. The trash is a hidden folder of the archive, so scans never index it. Once a folder has
|
||||
/// moved, its index step runs to the end whatever the caller cancels; when that step fails, the folder moves back, so
|
||||
/// the trash and the index never disagree.
|
||||
/// </summary>
|
||||
public sealed class SequenceTrash
|
||||
{
|
||||
/// <summary>Folder of the trash inside the archive's <c>.chronos</c>.</summary>
|
||||
public const string FolderName = "trash";
|
||||
|
||||
private const string RecordExtension = ".json";
|
||||
private const int JobPage = 200;
|
||||
|
||||
/// <summary>Bytes of a sidecar read to find its id (written second, after the schema version).</summary>
|
||||
private const int SidecarHead = 4096;
|
||||
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly SequenceWriter _writer;
|
||||
private readonly ArchiveIndexer _indexer;
|
||||
|
||||
/// <summary>A trash of its own (hosts without an <see cref="ArchiveService"/>); lease files keep it in step with other writers.</summary>
|
||||
public SequenceTrash(ChronosDatabase db, ArchiveServiceOptions? options = null)
|
||||
: this(db, new SequenceWriter(options ?? new ArchiveServiceOptions()), null)
|
||||
{
|
||||
}
|
||||
|
||||
internal SequenceTrash(ChronosDatabase db, SequenceWriter writer, ArchiveIndexer? indexer)
|
||||
{
|
||||
_db = db;
|
||||
_writer = writer;
|
||||
_indexer = indexer ?? new ArchiveIndexer(db, writer);
|
||||
}
|
||||
|
||||
/// <summary>The trash folder of an archive.</summary>
|
||||
public static string TrashDirectory(ArchivePaths archive) => Path.Combine(archive.MetaDirectory, FolderName);
|
||||
|
||||
/// <summary>The dry run: for each sequence, where its folder goes and how many files and bytes it holds, or why it cannot go.</summary>
|
||||
/// <param name="progress">Sequences checked so far.</param>
|
||||
/// <exception cref="ArgumentException">A sequence is not in the index.</exception>
|
||||
public async Task<DeletePlan> PlanAsync(IReadOnlyList<Guid> sequenceIds, IProgress<int>? progress = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var busy = await BusyAsync(cancellationToken).ConfigureAwait(false);
|
||||
var archives = new Dictionary<Guid, ArchiveContext?>();
|
||||
var steps = new List<DeleteStep>();
|
||||
var blocked = new List<BlockedDelete>();
|
||||
var claimed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var checkedCount = 0;
|
||||
foreach (var id in sequenceIds.Distinct())
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var sequence = await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ArgumentException($"Unknown sequence {id}.", nameof(sequenceIds));
|
||||
var context = await ContextAsync(archives, sequence.ArchiveId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ArgumentException($"Unknown archive {sequence.ArchiveId}.", nameof(sequenceIds));
|
||||
if (Block(sequence, context, busy) is { } reason)
|
||||
{
|
||||
blocked.Add(new BlockedDelete(sequence, reason));
|
||||
}
|
||||
else if (sequence.Folder.Length == 0)
|
||||
{
|
||||
steps.Add(new DeleteStep(sequence, null, 0, 0));
|
||||
}
|
||||
else
|
||||
{
|
||||
var folder = context.Paths.Sequence(sequence.Folder).Folder;
|
||||
var (files, bytes) = await Task.Run(() => Measure(folder, cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
var name = EntryName(context.Paths, sequence.Id, claimed);
|
||||
claimed.Add(name);
|
||||
steps.Add(new DeleteStep(sequence, context.Paths.ToRelative(Path.Combine(TrashDirectory(context.Paths), name)), files, bytes));
|
||||
}
|
||||
progress?.Report(++checkedCount);
|
||||
}
|
||||
return new DeletePlan(steps, blocked);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves the planned sequences to the trash, one at a time, each completely (folder, then index rows) before the
|
||||
/// next; cancelling stops between two sequences. Returns the trash entries made.
|
||||
/// </summary>
|
||||
/// <param name="deletedBy">Who asked (user name or client), kept in the trash record.</param>
|
||||
/// <param name="progress">Sequences moved so far.</param>
|
||||
/// <exception cref="StaleDeletePlanException">A sequence moved, vanished or got busy since the plan; nothing was deleted.</exception>
|
||||
/// <exception cref="ArchiveOfflineException">An archive is offline; sequences before it are in the trash.</exception>
|
||||
public async Task<IReadOnlyList<TrashEntry>> DeleteAsync(DeletePlan plan, string? deletedBy = null, IProgress<int>? progress = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
await RevalidateAsync(plan, cancellationToken).ConfigureAwait(false);
|
||||
var entries = new List<TrashEntry>(plan.Steps.Count);
|
||||
for (var i = 0; i < plan.Steps.Count; i++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (await DeleteOneAsync(plan.Steps[i], deletedBy, cancellationToken).ConfigureAwait(false) is { } entry) entries.Add(entry);
|
||||
progress?.Report(i + 1);
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <summary>The sequences in an archive's trash, newest first; records whose folder is gone are left out.</summary>
|
||||
public async Task<IReadOnlyList<TrashEntry>> ListAsync(Archive archive, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
var trash = TrashDirectory(new ArchivePaths(archive.RootPath));
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
if (!Directory.Exists(trash)) return (IReadOnlyList<TrashEntry>)[];
|
||||
var entries = new List<TrashEntry>();
|
||||
foreach (var path in Directory.EnumerateFiles(trash, "*" + RecordExtension))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var name = Path.GetFileNameWithoutExtension(path);
|
||||
if (!Directory.Exists(Path.Combine(trash, name)) || ReadRecord(path) is not { } record) continue;
|
||||
entries.Add(Entry(archive.Id, name, record));
|
||||
}
|
||||
return entries.OrderByDescending(e => e.DeletedAt).ToList();
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves a sequence back from the trash into its folder (or, when that is taken, a free one next to it) and indexes
|
||||
/// it again from its sidecar with its ids, settings and renders. A folder without a sidecar is adopted under the
|
||||
/// sequence's id, as a scan would adopt it, with the title, tags, rating and notes the record kept. Returns the
|
||||
/// restored row. When it cannot be indexed, the folder goes back into the trash with its record.
|
||||
/// </summary>
|
||||
/// <exception cref="SequenceInLibraryException">The index already holds that sequence.</exception>
|
||||
/// <exception cref="DirectoryNotFoundException">The entry is not in the trash.</exception>
|
||||
public async Task<Sequence> RestoreAsync(Archive archive, string name, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(name);
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
var trash = TrashDirectory(paths);
|
||||
var source = Path.Combine(trash, Path.GetFileName(name));
|
||||
var recordPath = source + RecordExtension;
|
||||
if (!Directory.Exists(source) || ReadRecord(recordPath) is not { } record)
|
||||
throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}.");
|
||||
var id = record.Sequence.Id;
|
||||
if (await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) is not null)
|
||||
throw new SequenceInLibraryException(id, record.Sequence.DisplayTitle);
|
||||
|
||||
var locations = (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false)).Select(l => l.Folder)
|
||||
.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var folder = FreeFolder(paths, record.Sequence.Folder, locations);
|
||||
var sequence = paths.Sequence(folder);
|
||||
await using (await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(sequence.Folder)!);
|
||||
Directory.Move(source, sequence.Folder);
|
||||
try
|
||||
{
|
||||
var manifest = File.Exists(sequence.ManifestPath) ? SequenceWriter.ReadLocked(sequence, id) : Adopt(sequence, record.Sequence, cancellationToken);
|
||||
// The index step runs to the end once it starts: a cancel cannot leave half the rows written.
|
||||
await IndexAsync(archive, sequence, manifest, record, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning("archive", $"{record.Sequence.DisplayTitle} could not be restored; its folder goes back into the trash", ex);
|
||||
MoveBack(sequence.Folder, source);
|
||||
throw;
|
||||
}
|
||||
Log.Info("archive", $"{record.Sequence.DisplayTitle} restored from the trash to {folder}");
|
||||
await RecordStampsAsync(archive, sequence, id).ConfigureAwait(false);
|
||||
File.Delete(recordPath);
|
||||
}
|
||||
return await _db.Sequences.GetAsync(id, CancellationToken.None).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException($"{record.Sequence.DisplayTitle} was restored but is not in the index.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A sidecar for a restored folder that lost its own, built as a scan adopts a folder: its frames get new ids, the
|
||||
/// sequence keeps its id, and the title, tags, rating and notes of the record go into it so sidecar and index agree.
|
||||
/// </summary>
|
||||
private SequenceManifest Adopt(SequencePaths sequence, Sequence kept, CancellationToken cancellationToken)
|
||||
{
|
||||
var built = SequenceAdopter.Build(kept.Id, sequence, _writer.Options.Owner, cancellationToken);
|
||||
var manifest = built with
|
||||
{
|
||||
Title = kept.Title,
|
||||
Tags = kept.Tags,
|
||||
Rating = kept.Rating,
|
||||
Notes = kept.Notes,
|
||||
Versions = built.Versions with { Settings = System.Math.Max(built.Versions.Settings, kept.SettingsVersion) },
|
||||
};
|
||||
Directory.CreateDirectory(sequence.MetaDirectory);
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, manifest);
|
||||
return manifest;
|
||||
}
|
||||
|
||||
/// <summary>The restored sequence's rows: the sidecar's frames, the record's row and renders; a hero frame the sidecar no longer has is dropped.</summary>
|
||||
private async Task IndexAsync(Archive archive, SequencePaths sequence, SequenceManifest manifest, TrashRecord record, CancellationToken cancellationToken)
|
||||
{
|
||||
var deleted = record.Sequence;
|
||||
var hero = deleted.HeroFrameId is { } frame && manifest.Frames.Any(f => f.Id == frame) ? frame : (Guid?)null;
|
||||
var kept = deleted with { ArchiveId = archive.Id, Folder = sequence.RelativeFolder, RenderedCount = 0, HeroFrameId = hero };
|
||||
await using var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, kept), cancellationToken).ConfigureAwait(false);
|
||||
await tx.Frames.SyncSequenceAsync(deleted.Id, SequenceMapping.ToFrames(manifest, sequence), cancellationToken).ConfigureAwait(false);
|
||||
foreach (var key in manifest.SessionKeys) await tx.Sequences.MapSessionKeyAsync(archive.Id, key, deleted.Id, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var render in record.Renders)
|
||||
{
|
||||
var moved = render with { OutputPath = Rebase(render.OutputPath, deleted.Folder, sequence.RelativeFolder) };
|
||||
await tx.Renders.InsertAsync(moved, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The next incremental scan skips the restored folder; when the stamps cannot be written it only reads the folder again.</summary>
|
||||
private async Task RecordStampsAsync(Archive archive, SequencePaths sequence, Guid id)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _indexer.RecordStampsAsync(archive, sequence, id, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
|
||||
{
|
||||
Log.Warning("archive", $"Scan stamps of {sequence.RelativeFolder} not recorded; the next scan reads it again", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Checks the plan again just before anything moves, without measuring the folders again; any change refuses it whole.</summary>
|
||||
private async Task RevalidateAsync(DeletePlan plan, CancellationToken cancellationToken)
|
||||
{
|
||||
var busy = await BusyAsync(cancellationToken).ConfigureAwait(false);
|
||||
var archives = new Dictionary<Guid, ArchiveContext?>();
|
||||
foreach (var step in plan.Steps)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var row = await _db.Sequences.GetAsync(step.Sequence.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (row is null || row.ArchiveId != step.Sequence.ArchiveId || row.Folder != step.Sequence.Folder) throw new StaleDeletePlanException(step.Sequence.Id);
|
||||
if (await ContextAsync(archives, row.ArchiveId, cancellationToken).ConfigureAwait(false) is not { } context) throw new StaleDeletePlanException(row.Id);
|
||||
switch (Block(row, context, busy))
|
||||
{
|
||||
case DeleteBlock.Offline:
|
||||
throw new ArchiveOfflineException(context.Paths.Root, context.Availability);
|
||||
case not null:
|
||||
throw new StaleDeletePlanException(row.Id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<TrashEntry?> DeleteOneAsync(DeleteStep step, string? deletedBy, CancellationToken cancellationToken)
|
||||
{
|
||||
var sequence = step.Sequence;
|
||||
var archive = await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new StaleDeletePlanException(sequence.Id);
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
await using (await _writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
|
||||
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{sequence.Id:N}", _writer.Options.Owner, _writer.Options.LeaseWait,
|
||||
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var row = await _db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (row is null || row.Folder != sequence.Folder) throw new StaleDeletePlanException(sequence.Id);
|
||||
if (step.TrashFolder is null)
|
||||
{
|
||||
await RemoveRowsAsync(archive.Id, row, cancellationToken).ConfigureAwait(false);
|
||||
Log.Info("archive", $"{row.DisplayTitle} removed from the index (no folder yet)");
|
||||
return null;
|
||||
}
|
||||
|
||||
var folder = paths.Sequence(sequence.Folder);
|
||||
if (!Directory.Exists(folder.Folder) || (File.Exists(folder.ManifestPath) && SidecarId(folder.ManifestPath) != sequence.Id))
|
||||
throw new StaleDeletePlanException(sequence.Id);
|
||||
var trash = TrashDirectory(paths);
|
||||
Directory.CreateDirectory(trash);
|
||||
var name = EntryName(paths, sequence.Id, new HashSet<string>());
|
||||
var target = Path.Combine(trash, name);
|
||||
var record = new TrashRecord(row, await _db.Renders.ListBySequenceAsync(sequence.Id, cancellationToken).ConfigureAwait(false), step.Files,
|
||||
step.Bytes, DateTimeOffset.UtcNow, deletedBy);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// The record first: a crash before the move leaves a record without a folder, which the listing ignores.
|
||||
var recordPath = target + RecordExtension;
|
||||
AtomicFile.WriteAllText(recordPath, JsonSerializer.Serialize(record, TrashJson.Default.TrashRecord));
|
||||
try
|
||||
{
|
||||
Directory.Move(folder.Folder, target);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// A file of the folder is open elsewhere: nothing moved, so the record goes and the rows stay.
|
||||
File.Delete(recordPath);
|
||||
throw;
|
||||
}
|
||||
try
|
||||
{
|
||||
// The folder has moved: its rows go too, to the end, whatever the caller cancels meanwhile.
|
||||
await RemoveRowsAsync(archive.Id, row, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning("archive", $"{row.DisplayTitle} could not leave the index; its folder goes back", ex);
|
||||
if (MoveBack(target, folder.Folder)) File.Delete(recordPath);
|
||||
throw;
|
||||
}
|
||||
Log.Info("archive", $"{row.DisplayTitle} moved to the trash: {row.Folder} → {name} ({step.Files} files, {step.Bytes} bytes)");
|
||||
return Entry(archive.Id, name, record);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RemoveRowsAsync(Guid archiveId, Sequence sequence, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
await tx.Sequences.DeleteAsync(sequence.Id, cancellationToken).ConfigureAwait(false);
|
||||
// A sequence without a folder has no scan state; the root's belongs to a folder adopted in place.
|
||||
if (sequence.Folder.Length > 0) await tx.Archives.DeleteFolderStateAsync(archiveId, sequence.Folder, cancellationToken).ConfigureAwait(false);
|
||||
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Undoes a folder move after a failed index step; false (logged) when the folder cannot move back either.</summary>
|
||||
private static bool MoveBack(string from, string to)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Move(from, to);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Error("archive", $"{from} could not move back to {to}; it stays where it is", ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<ArchiveContext?> ContextAsync(Dictionary<Guid, ArchiveContext?> known, Guid archiveId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (known.TryGetValue(archiveId, out var context)) return context;
|
||||
if (await _db.Archives.GetAsync(archiveId, cancellationToken).ConfigureAwait(false) is { } archive)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
context = new ArchiveContext(paths, ArchiveVolume.Probe(paths),
|
||||
await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
known[archiveId] = context;
|
||||
return context;
|
||||
}
|
||||
|
||||
private static DeleteBlock? Block(Sequence sequence, ArchiveContext context, IReadOnlySet<Guid> busy)
|
||||
{
|
||||
if (context.Availability != ArchiveAvailability.Online) return DeleteBlock.Offline;
|
||||
if (busy.Contains(sequence.Id) || busy.Contains(sequence.ArchiveId)) return DeleteBlock.Busy;
|
||||
// An empty folder is the archive root of a folder adopted in place, or a server sequence still waiting for its first frame.
|
||||
if (sequence.Folder.Length == 0) return sequence.FrameCount > 0 ? DeleteBlock.ArchiveRoot : null;
|
||||
var folder = context.Paths.Sequence(sequence.Folder);
|
||||
if (!Directory.Exists(folder.Folder)) return DeleteBlock.FolderMissing;
|
||||
var prefix = sequence.Folder + "/";
|
||||
if (context.Locations.Any(l => l.Id != sequence.Id && l.Folder.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))) return DeleteBlock.ContainsSequences;
|
||||
return File.Exists(folder.ManifestPath) && SidecarId(folder.ManifestPath) != sequence.Id ? DeleteBlock.ForeignSidecar : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What running and paused jobs hold: the sequences they target (renders, analyses, proxies, transfers) and the
|
||||
/// archives of archive-wide ones (scan, rebuild, import, maintenance, a verify of everything). An import's folders
|
||||
/// are known only to its plan, so it holds its whole archive; a verify of named sequences holds only those.
|
||||
/// </summary>
|
||||
private async Task<IReadOnlySet<Guid>> BusyAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var busy = new HashSet<Guid>();
|
||||
foreach (var state in new[] { JobState.Running, JobState.Paused })
|
||||
{
|
||||
string? cursor = null;
|
||||
do
|
||||
{
|
||||
var page = await _db.Jobs.ListAsync(state, JobPage, cursor, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var job in page.Items) busy.UnionWith(Holds(job));
|
||||
cursor = page.NextCursor;
|
||||
}
|
||||
while (cursor is not null);
|
||||
}
|
||||
return busy;
|
||||
}
|
||||
|
||||
private static IReadOnlyList<Guid> Holds(Job job)
|
||||
{
|
||||
if (job.Kind != JobKind.Verify) return job.TargetIds;
|
||||
try
|
||||
{
|
||||
return ArchiveJobJson.Read(job, ArchiveJobJson.Default.VerifyParameters, new VerifyParameters(null)).SequenceIds ?? job.TargetIds;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return job.TargetIds;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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)
|
||||
{
|
||||
try
|
||||
{
|
||||
var head = new byte[SidecarHead];
|
||||
int length;
|
||||
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
|
||||
length = stream.ReadAtLeast(head, head.Length, throwOnEndOfStream: false);
|
||||
var reader = new Utf8JsonReader(head.AsSpan(0, length), isFinalBlock: length < head.Length, state: default);
|
||||
while (reader.Read())
|
||||
{
|
||||
if (reader.TokenType != JsonTokenType.PropertyName || reader.CurrentDepth != 1) continue;
|
||||
if (reader.ValueTextEquals("id"u8))
|
||||
{
|
||||
if (!reader.Read()) break;
|
||||
return reader.TokenType == JsonTokenType.String && reader.TryGetGuid(out var id) ? id : null;
|
||||
}
|
||||
if (!reader.TrySkip()) break;
|
||||
}
|
||||
return ManifestStore.ReadSequence(path).Id;
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or InvalidDataException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static (int Files, long Bytes) Measure(string folder, CancellationToken cancellationToken)
|
||||
{
|
||||
int files = 0;
|
||||
long bytes = 0;
|
||||
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", new EnumerationOptions { RecurseSubdirectories = true, AttributesToSkip = 0 }))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
files++;
|
||||
bytes += file.Length;
|
||||
}
|
||||
return (files, bytes);
|
||||
}
|
||||
|
||||
/// <summary>The sequence id, or the id with a time stamp when an earlier deletion of the same sequence is still in the trash.</summary>
|
||||
private static string EntryName(ArchivePaths paths, Guid sequenceId, IReadOnlySet<string> claimed)
|
||||
{
|
||||
var trash = TrashDirectory(paths);
|
||||
var name = sequenceId.ToString("N");
|
||||
var stamp = DateTime.UtcNow.ToString("yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture);
|
||||
for (var n = 1; claimed.Contains(name) || Directory.Exists(Path.Combine(trash, name)); n++)
|
||||
name = $"{sequenceId:N}-{stamp}" + (n > 1 ? "-" + n.ToString(System.Globalization.CultureInfo.InvariantCulture) : string.Empty);
|
||||
return name;
|
||||
}
|
||||
|
||||
/// <summary>The original folder when it is free on disk and in the index, else "folder (2)", "folder (3)", …</summary>
|
||||
private static string FreeFolder(ArchivePaths paths, string folder, IReadOnlySet<string> indexed)
|
||||
{
|
||||
var candidate = folder;
|
||||
for (var n = 2; indexed.Contains(candidate) || Directory.Exists(paths.Sequence(candidate).Folder); n++)
|
||||
candidate = string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{folder} ({n})");
|
||||
return candidate;
|
||||
}
|
||||
|
||||
/// <summary>A render stored inside the old folder points into the folder it was restored to.</summary>
|
||||
private static string Rebase(string outputPath, string from, string to) =>
|
||||
from != to && outputPath.StartsWith(from + "/", StringComparison.Ordinal) ? to + outputPath[from.Length..] : outputPath;
|
||||
|
||||
private static TrashEntry Entry(Guid archiveId, string name, TrashRecord record) =>
|
||||
new(archiveId, name, record.Sequence.Id, record.Sequence.DisplayTitle, record.Sequence.Folder, record.Sequence.FrameCount, record.Files,
|
||||
record.Bytes, record.DeletedAt, record.DeletedBy);
|
||||
|
||||
private static TrashRecord? ReadRecord(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize(File.ReadAllText(path), TrashJson.Default.TrashRecord);
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"Trash record {path} is unreadable", ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An archive as the plan sees it: where it is, whether it can be written, and where its sequences are.</summary>
|
||||
private sealed record ArchiveContext(ArchivePaths Paths, ArchiveAvailability Availability, IReadOnlyList<Repositories.SequenceLocation> Locations);
|
||||
}
|
||||
|
||||
/// <summary>What the trash keeps next to a deleted folder: the index row and renders the sidecar does not carry.</summary>
|
||||
internal sealed record TrashRecord(Sequence Sequence, IReadOnlyList<Render> Renders, int Files, long Bytes, DateTimeOffset DeletedAt, string? DeletedBy);
|
||||
|
||||
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
UseStringEnumConverter = true, IgnoreReadOnlyProperties = true)]
|
||||
[JsonSerializable(typeof(TrashRecord))]
|
||||
internal sealed partial class TrashJson : JsonSerializerContext;
|
||||
@@ -0,0 +1,118 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Imaging;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>Settings shared by the archive services.</summary>
|
||||
public sealed record ArchiveServiceOptions
|
||||
{
|
||||
/// <summary>Decoders for thumbnails and proxies beyond embedded previews and JPEG (WIC on Windows).</summary>
|
||||
public ImageDecoder Decoder { get; init; } = new([]);
|
||||
|
||||
/// <summary>Name written into lease files so a waiting writer can say who holds a sequence.</summary>
|
||||
public string Owner { get; init; } = "chronos@" + Environment.MachineName;
|
||||
|
||||
/// <summary>How long a writer waits for a sequence held by another process before giving up.</summary>
|
||||
public TimeSpan LeaseWait { get; init; } = TimeSpan.FromMinutes(2);
|
||||
|
||||
public TimeSpan LeaseDuration { get; init; } = LeaseFile.DefaultDuration;
|
||||
|
||||
/// <summary>
|
||||
/// Scans queue thumbnails and proxies of the sequences they index without them, as an upload does (the server, whose
|
||||
/// clients load both from it: BRIEF §4.3, §14.4). The desktop decodes its thumbnails on demand and makes proxies when
|
||||
/// asked.
|
||||
/// </summary>
|
||||
public bool ImagesAfterScan { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Photos a pass works on at once, asked at the start of each sequence (owner review 1, R2: one job runs at a time and
|
||||
/// the host's parallelism decides how many photos it processes at once; Settings › Rendering › Parallelism on the
|
||||
/// desktop, <c>CHRONOS_PARALLELISM</c> on the server). Default: half the logical cores.
|
||||
/// </summary>
|
||||
public Func<int> Parallelism { get; init; } = () => DefaultParallelism;
|
||||
|
||||
/// <summary>
|
||||
/// Memory the photos a proxy pass decodes at once may take, in bytes, asked with <see cref="Parallelism"/>: fewer at once
|
||||
/// for large originals. Default: a quarter of the memory available, at least 1 GiB.
|
||||
/// </summary>
|
||||
public Func<long> MemoryBudget { get; init; } = () => DefaultMemoryBudget;
|
||||
|
||||
/// <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);
|
||||
|
||||
/// <summary>A quarter of the memory available to this process, at least 1 GiB.</summary>
|
||||
public static long DefaultMemoryBudget => Math.Max(1L << 30, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / 4);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read-modify-write of sidecars, serialised per sequence: an in-process gate for this process's writers plus a lease
|
||||
/// file for writers in other processes on the same share (server and client). Every edit sees the latest sidecar,
|
||||
/// with an interrupted ingest batch completed first.
|
||||
/// </summary>
|
||||
internal sealed class SequenceWriter(ArchiveServiceOptions options)
|
||||
{
|
||||
private readonly ConcurrentDictionary<Guid, SemaphoreSlim> _gates = new();
|
||||
|
||||
public ArchiveServiceOptions Options => options;
|
||||
|
||||
/// <summary>Holds the sequence exclusively until disposed.</summary>
|
||||
public async Task<IAsyncDisposable> LockAsync(ArchivePaths archive, Guid sequenceId, CancellationToken cancellationToken)
|
||||
{
|
||||
var gate = _gates.GetOrAdd(sequenceId, _ => new SemaphoreSlim(1, 1));
|
||||
await gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var lease = await LeaseFile.AcquireAsync(archive.LocksDirectory, $"seq-{sequenceId:N}", options.Owner, options.LeaseWait,
|
||||
options.LeaseDuration, cancellationToken).ConfigureAwait(false);
|
||||
return new Held(gate, lease);
|
||||
}
|
||||
catch
|
||||
{
|
||||
gate.Release();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the sidecar of a locked sequence, completing an interrupted ingest batch first.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidDataException">The sidecar in the folder belongs to another sequence.</exception>
|
||||
public static SequenceManifest ReadLocked(SequencePaths sequence, Guid sequenceId)
|
||||
{
|
||||
var manifest = ManifestStore.ReadSequence(sequence.ManifestPath);
|
||||
if (manifest.Id != sequenceId)
|
||||
throw new InvalidDataException($"{sequence.ManifestPath} belongs to sequence {manifest.Id}, not {sequenceId}.");
|
||||
if (IngestJournal.Recover(sequence, manifest) is { } recovered)
|
||||
{
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, recovered);
|
||||
manifest = recovered;
|
||||
}
|
||||
IngestJournal.Delete(sequence);
|
||||
return manifest;
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
var sequence = archive.Sequence(folder);
|
||||
await using (await LockAsync(archive, sequenceId, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var manifest = ReadLocked(sequence, sequenceId);
|
||||
if (edit(manifest) is not { } updated) return manifest;
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, updated);
|
||||
return updated;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Held(SemaphoreSlim gate, LeaseFile lease) : IAsyncDisposable
|
||||
{
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
lease.Dispose();
|
||||
gate.Release();
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user