feat(data): archive services, ingest and job handlers

ArchiveService facade over indexer (scan, adopt, rebuild), ArchiveIngest
(IArchiveIngest with per-sequence group commit, leases and a write-ahead
journal), verifier, maintenance (duplicates, orphans, cleanup), mass rename
with resumable journal, thumbnails/proxies and card import; job handlers for
scan, rebuild, verify, import, thumbs, proxies and maintenance with checkpoints.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 12:30:15 +00:00
1 parent 33582a3617
commit 1c19b00a00
23 files changed
+3161

No files matched your search

+268
View File
@@ -0,0 +1,268 @@
using Titano.Core.Archiving;
using Titano.Core.Diagnostics;
using Titano.Core.Model;
using Titano.Data.Repositories;
namespace Titano.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>
public sealed record ScanSummary(int Folders, int Indexed, int Adopted, int Removed, IReadOnlyList<(string Folder, string Error)> Failed);
/// <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
{
private readonly TitanoDatabase _db;
private readonly SequenceWriter _writer;
internal ArchiveIndexer(TitanoDatabase 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 locations = new Locations(await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false));
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 indexed = 0, adopted = 0;
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 bytes = await IndexFolderAsync(archive, paths, folder, reconcile, snapshot, locations, cancellationToken).ConfigureAwait(false);
if (snapshotWriter is not null)
{
var sidecar = paths.Sequence(folder.RelativeFolder).ManifestPath;
snapshotWriter.Add(folder.RelativeFolder, FileStamp.Of(sidecar)!.Value,
bytes ?? await File.ReadAllBytesAsync(sidecar, cancellationToken).ConfigureAwait(false));
}
indexed++;
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, adopted, removed, failed);
}
/// <summary>Writes a sequence's sidecar into the index (row, frames, session keys) and records the folder stamps.</summary>
internal async Task SyncAsync(Archive archive, SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken)
{
await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false))
{
var existing = await tx.Sequences.GetAsync(manifest.Id, cancellationToken).ConfigureAwait(false);
await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, existing), 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);
}
await RecordStampsAsync(archive, sequence, manifest.Id, cancellationToken).ConfigureAwait(false);
}
/// <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) =>
_db.Archives.SetFolderStateAsync(archive.Id, new FolderScanState(sequence.RelativeFolder, sequenceId,
FileStamp.Of(sequence.ManifestPath), FileStamp.Of(ArchiveScanner.PhotoDirectory(sequence))), cancellationToken);
/// <summary>Indexes unindexed photos and flags missing files of one sequence (the orphans fix action).</summary>
public async Task<SequenceManifest> ReconcileAsync(Archive archive, Sequence sequence, CancellationToken cancellationToken = default)
{
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var folder = paths.Sequence(sequence.Folder);
var manifest = await _writer.UpdateAsync(paths, sequence.Id, sequence.Folder, m => SequenceAdopter.Reconcile(folder, m, cancellationToken),
cancellationToken).ConfigureAwait(false);
await SyncAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false);
return manifest;
}
/// <summary>Indexes one folder; returns the sidecar bytes when they were read and not rewritten since (for the snapshot).</summary>
private async Task<byte[]?> 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 File.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))
{
var before = manifest;
manifest = await _writer.UpdateAsync(paths, manifest.Id, folder.RelativeFolder, m => SequenceAdopter.Reconcile(sequence, m, cancellationToken),
cancellationToken).ConfigureAwait(false);
if (!ReferenceEquals(before, manifest)) bytes = null;
}
await SyncAsync(archive, sequence, manifest, cancellationToken).ConfigureAwait(false);
locations.Set(manifest.Id, folder.RelativeFolder);
return bytes;
}
/// <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).</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 removed = 0;
foreach (var location in await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false))
{
if (present.Contains(location.Folder) && locations.AtFolder(location.Folder) == location.Id) 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>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;
}
}
}