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

+344
View File
@@ -0,0 +1,344 @@
using System.Collections.Concurrent;
using System.Globalization;
using Titano.Core.Archiving;
using Titano.Core.Localization;
using Titano.Core.Metadata;
using Titano.Core.Model;
using Titano.Core.Naming;
namespace Titano.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 the sequence already holds is reported as a duplicate and left in staging.
/// </summary>
public sealed class ArchiveIngest : IArchiveIngest
{
private readonly TitanoDatabase _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(TitanoDatabase 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));
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 captured = CaptureTime(first);
var wanted = target.PreferredFolder ?? PathTemplate.Parse(archive.FolderTemplate).ExpandFolder(Naming(first, captured, captured, 1, target.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);
var sequence = ClaimFolder(paths, wanted, taken, manifest);
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>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);
var before = manifest.Frames.Count;
var known = new Dictionary<string, SidecarFrame>(StringComparer.OrdinalIgnoreCase);
foreach (var f in manifest.Frames)
{
if (f.Sha256 is not null) known.TryAdd(f.Sha256, f);
}
var accepted = new List<(Pending Pending, SidecarFrame Frame)>();
var duplicates = new List<(Pending Pending, Guid FrameId)>();
foreach (var p in batch)
{
if (known.TryGetValue(p.Frame.Sha256, out var existing))
{
duplicates.Add((p, existing.Id));
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);
known[p.Frame.Sha256] = frame;
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 updated = SequenceFrames.Insert(manifest, moved);
if (moved.Count > 0) ManifestStore.WriteSequence(sequence.ManifestPath, updated);
IngestJournal.Delete(sequence);
var byId = updated.Frames.ToDictionary(f => f.Id);
if (moved.Count > 0) await IndexAsync(archive, sequence, updated, before, moved.ConvertAll(m => byId[m.Id]), 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, frameId) in duplicates)
{
if (byId.TryGetValue(frameId, out var original)) 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>Appends the new rows when the index was in step with the sidecar; otherwise resyncs the whole sequence.</summary>
private async Task IndexAsync(Archive archive, SequencePaths sequence, SequenceManifest manifest, int before, List<SidecarFrame> appended,
CancellationToken cancellationToken)
{
var inStep = appended.All(f => f.I >= before)
&& await _db.Frames.CountBySequenceAsync(manifest.Id, cancellationToken).ConfigureAwait(false) == before;
if (!inStep)
{
await _indexer.SyncAsync(archive, sequence, manifest, cancellationToken).ConfigureAwait(false);
return;
}
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.BulkInsertAsync(appended.Select(f => SequenceMapping.ToFrame(f, manifest.Id, sequence)), cancellationToken).ConfigureAwait(false);
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
}
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);
}
}