The project names frames by position (exclusions, hero, virtual-camera keyframes), and an upload, import, scan or sync download of earlier photos merges them by capture time and renumbers the frames after them; nothing moved the project, so a render excluded the wrong photo and the project's hero no longer matched the Library's. project.json keeps its format: when the index takes a sidecar in which frames were inserted before indexed ones, the index's copy of the project has its positions moved from the indexed order to the new one in the same transaction as the frame rows, and project.json mirrors it unless another writer changed it meanwhile. The JSON is edited in place, so members a newer Titano wrote survive; only an insertion is followed (if an indexed frame is gone, the positions stay). The settings version stays, so a synced copy receiving the same frames makes the same move (CD-2). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
283 lines
16 KiB
C#
283 lines
16 KiB
C#
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. Frames
|
|
/// inserted before indexed ones take the project's frame positions along (<see cref="ProjectPositions"/>).
|
|
/// </summary>
|
|
internal async Task SyncAsync(Archive archive, SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken)
|
|
{
|
|
(string Before, string Moved)? positions = null;
|
|
await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false))
|
|
{
|
|
var existing = await tx.Sequences.GetAsync(manifest.Id, cancellationToken).ConfigureAwait(false);
|
|
if (existing is not null)
|
|
{
|
|
positions = await ProjectPositions.MoveAsync(tx, existing, manifest, cancellationToken).ConfigureAwait(false);
|
|
if (positions is { } project) existing = existing with { SettingsJson = project.Moved };
|
|
}
|
|
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);
|
|
}
|
|
if (positions is { } moved) ProjectPositions.WriteProject(sequence, moved.Before, moved.Moved);
|
|
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;
|
|
// Photos added, gone or back: the light analysis no longer describes the frames, so the scan's follow-up runs it again.
|
|
manifest = await _writer.UpdateAsync(paths, manifest.Id, folder.RelativeFolder,
|
|
m => SequenceAdopter.Reconcile(sequence, m, cancellationToken) is { } reconciled
|
|
? reconciled with { Status = reconciled.Status & ~SequenceStatus.AnalyzedLight }
|
|
: null,
|
|
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;
|
|
}
|
|
}
|
|
}
|