feat: owner review 2 phase 3: Library on the web panel, photo trash and web upload (#11)
CI / Build and test (push) Successful in 7m25s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 10s
CI / PostgreSQL 16 integration (push) Successful in 5m20s
CI / PostgreSQL 17 integration (push) Successful in 5m22s
CI / Docker image (push) Successful in 50s
Release / Build, test and publish (push) Successful in 12m1s
Release / Server image (push) Successful in 1m26s

- Web panel Library: browse, view, delete sequences and photos, mass operations (analyse, proxies, thumbnails, verify, retag, delete, CSV). It never edits the video.
- Photo trash with tombstones (migration 0008): crash-safe delete and restore, hash-checked restore with reasons, and emptying only by an explicit fingerprinted job. Sync and uploads keep deleted photos deleted; an explicit "Upload again" brings one back.
- Upload from the web panel: in-house SHA-256 in a worker with a fail-closed self-test, capture time from EXIF, chunked, resumable; no folders.
- Desktop trash dialog with photo entries and Empty.
- Admin files are revalidated (no-cache + ETag).

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 #11.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-27 15:08:39 +01:00
1 parent af9eeaab9b
commit 9aa818ed47
283 files changed
+24922 -293

No files matched your search

+22 -4
View File
@@ -152,8 +152,11 @@ public sealed class ArchiveIndexer
if (positions is not null) existing = positions.ApplyTo(existing);
}
var row = SequenceMapping.ToSequence(manifest, archive.Id, sequence, existing);
// A hero frame the sidecar no longer lists (a photo deleted) names nothing: the project's hero waits for its photo.
if (row.HeroFrameId is { } hero && !manifest.Frames.Any(f => f.Id == hero)) row = row with { HeroFrameId = null };
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);
await tx.FrameRemovals.SyncSequenceAsync(manifest.Id, SequenceMapping.ToRemovals(manifest), 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);
@@ -254,10 +257,19 @@ public sealed class ArchiveIndexer
/// 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
private static SequenceManifest? Reconcile(SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken)
{
// A restore from the trash that could not be settled yet (its entry busy) may have photos in the folder its sidecar
// does not list: they are its own, not photos to adopt, until a later writer settles it.
if (File.Exists(sequence.RestoreJournalPath))
{
Log.Info("archive", $"{sequence.RelativeFolder} is not reconciled while a restore from the trash into it waits");
return null;
}
return 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
@@ -324,7 +336,8 @@ public sealed class ArchiveIndexer
ManifestStore.WriteSequence(sequence.ManifestPath, manifest);
bytes = null;
}
if (reconcile || File.Exists(sequence.IngestJournalPath))
// A journal of an ingest, a photo deletion or a restore a crash interrupted is settled under the lease first (ReadLocked).
if (reconcile || File.Exists(sequence.IngestJournalPath) || File.Exists(sequence.RemovalJournalPath) || File.Exists(sequence.RestoreJournalPath))
{
// 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)
@@ -411,12 +424,17 @@ public sealed class ArchiveIndexer
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>
/// <summary>
/// A sidecar for a folder that has none; ids and tombstones of a sequence the index already knew at this folder are
/// kept, so a photo deleted from it is not offered back once the index is synced from the new sidecar.
/// </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);
if (known is { } id && await _db.FrameRemovals.ListBySequenceAsync(id, cancellationToken).ConfigureAwait(false) is { Count: > 0 } removals)
manifest = manifest with { Removed = SequenceMapping.ToTombstones(removals) };
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);
+33 -4
View File
@@ -12,8 +12,9 @@ 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>
/// <param name="RefuseRemoved">See <see cref="IngestRequest.RefuseRemoved"/>.</param>
internal sealed record StagedFrame(string StagedPath, string OriginalFileName, long Size, string Sha256, FrameMetadata Metadata,
DateTime? ClientCapturedAt, string? PlannedName);
DateTime? ClientCapturedAt, string? PlannedName, bool RefuseRemoved = false);
/// <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>
@@ -54,7 +55,7 @@ public sealed class ArchiveIngest : IArchiveIngest
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);
MetadataReader.Read(request.StagedPath, cancellationToken), request.ClientCapturedAt, null, request.RefuseRemoved);
Guid sequenceId;
if (request.SequenceId is { } id)
@@ -297,6 +298,7 @@ public sealed class ArchiveIngest : IArchiveIngest
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);
var tombstoned = (manifest.Removed ?? []).Select(r => r.Sha256).ToHashSet(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);
@@ -305,6 +307,13 @@ public sealed class ArchiveIngest : IArchiveIngest
var duplicates = new List<(Pending Pending, Guid FrameId)>();
foreach (var p in batch)
{
// Deleted from the sequence (its tombstone, and no frame holds the content) and not asked back: checked under the
// lease a deletion takes, so none lands between this check and the commit (owner review 2, R6).
if (p.Frame.RefuseRemoved && tombstoned.Contains(p.Frame.Sha256) && !held[p.Frame.Sha256].Any())
{
p.Completion.TrySetException(new PhotoRemovedException(sequenceId, p.Frame.Sha256));
continue;
}
if (filed.TryGetValue(p.Frame.Sha256, out var same))
{
duplicates.Add((p, same));
@@ -358,13 +367,17 @@ public sealed class ArchiveIngest : IArchiveIngest
updated = SequenceFrames.Update(updated, repaired.ToDictionary(id => id,
_ => (Func<SidecarFrame, SidecarFrame>)(f => f with { Flags = f.Flags & ~(FrameFlags.Missing | FrameFlags.Corrupt) })));
}
// A photo deleted from the sequence and filed into it again (a card imported again, a sync download) is back: its
// tombstone goes, so sync offers it like any other.
var back = Readded(updated, moved);
if (back) updated = updated with { Removed = Remaining(updated.Removed!, moved) };
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,
await IndexAsync(archive, sequence, updated, inStep, photosChanged, before, moved.ConvertAll(m => byId[m.Id]), repaired.Count > 0 || back,
cancellationToken).ConfigureAwait(false);
}
foreach (var (p, frame) in accepted.Where(a => byId.ContainsKey(a.Frame.Id)))
@@ -382,6 +395,22 @@ public sealed class ArchiveIngest : IArchiveIngest
}
}
/// <summary>Whether a frame filed by the batch holds content the sequence's tombstones name.</summary>
private static bool Readded(SequenceManifest manifest, List<SidecarFrame> moved)
{
if (manifest.Removed is not { Count: > 0 } removed || moved.Count == 0) return false;
var tombstoned = removed.Select(r => r.Sha256).ToHashSet(StringComparer.OrdinalIgnoreCase);
return moved.Any(f => f.Sha256 is { } sha && tombstoned.Contains(sha));
}
/// <summary>The tombstones without those of the content filed again; null when none is left.</summary>
private static IReadOnlyList<RemovedPhoto>? Remaining(IReadOnlyList<RemovedPhoto> removed, List<SidecarFrame> moved)
{
var filed = moved.Where(f => f.Sha256 is not null).Select(f => f.Sha256!).ToHashSet(StringComparer.OrdinalIgnoreCase);
var left = removed.Where(r => !filed.Contains(r.Sha256)).ToList();
return left.Count == 0 ? null : left;
}
/// <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)
@@ -416,7 +445,7 @@ public sealed class ArchiveIngest : IArchiveIngest
}
/// <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)
internal 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));
+54 -5
View File
@@ -40,6 +40,7 @@ public sealed class ArchiveService : IJobHandlerProvider
Images = new ArchiveImages(db, _writer, Indexer);
Imports = new ImportService(db, Ingest);
Trash = new SequenceTrash(db, _writer, Indexer);
FrameTrash = new FrameTrash(db, _writer, Indexer, Ingest, Trash);
var shared = Housekeeping.CleanupSteps.Shared(Trash);
CleanupSteps = [.. shared, .. _writer.Options.CleanupSteps.Where(s => !shared.Any(o => o.Name == s.Name))];
}
@@ -55,9 +56,12 @@ public sealed class ArchiveService : IJobHandlerProvider
public ArchiveImages Images { get; }
public ImportService Imports { get; }
/// <summary>Deletes sequences into the archive's trash and restores them.</summary>
/// <summary>Deletes sequences into the archive's trash and restores them; lists and empties the trash.</summary>
public SequenceTrash Trash { get; }
/// <summary>Deletes photos of a sequence into the archive's trash and restores them (owner review 2, R6).</summary>
public FrameTrash FrameTrash { get; }
/// <summary>
/// The steps this host's <see cref="JobKind.Cleanup"/> jobs can run: the shared ones (<see cref="Housekeeping.CleanupSteps.Shared"/>),
/// then the host's (<see cref="ArchiveServiceOptions.CleanupSteps"/>). A schedule host lists their names.
@@ -69,7 +73,8 @@ public sealed class ArchiveService : IJobHandlerProvider
/// <summary>
/// Handlers for scan, rebuild, verify, import, thumbs, proxies and maintenance jobs, the read-only duplicates and orphans
/// reports, index backups and clean-ups (owner review 2, R10); register them on the <see cref="JobEngine"/>.
/// reports, index backups and clean-ups (owner review 2, R10) and the emptying of the trash (R6); register them on the
/// <see cref="JobEngine"/>.
/// </summary>
public IReadOnlyList<IJobHandler> CreateJobHandlers() =>
[
@@ -84,6 +89,7 @@ public sealed class ArchiveService : IJobHandlerProvider
new OrphansJobHandler(_db, Maintenance),
new Housekeeping.BackupJobHandler(_db, _writer.Options.BackupDirectory),
new Housekeeping.CleanupJobHandler(_db, CleanupSteps, TimeProvider.System),
new EmptyTrashJobHandler(_db, Trash),
];
/// <summary>Makes <paramref name="root"/> a new, empty archive and indexes it.</summary>
@@ -358,13 +364,37 @@ public sealed class ArchiveService : IJobHandlerProvider
CancellationToken cancellationToken = default) =>
Trash.DeleteAsync(plan, deletedBy, progress, cancellationToken);
/// <summary>The sequences in an archive's trash, newest first.</summary>
/// <summary>The entries of an archive's trash, newest first: deleted sequences and photos deleted from sequences (<see cref="SequenceTrash.ListAsync"/>).</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>
/// <summary>Moves a sequence back from the trash and indexes it again (an entry of deleted photos: see <see cref="RestoreEntryAsync"/>).</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);
(await RestoreEntryAsync(archiveId, entryName, null, cancellationToken).ConfigureAwait(false)).Sequence;
/// <summary>
/// Brings a trash entry back: a sequence into its folder (<see cref="SequenceTrash.RestoreAsync"/>), or photos into
/// their sequence (<see cref="Archiving.FrameTrash.RestoreAsync"/>, which queues on <paramref name="followUps"/> what the
/// frames need again).
/// </summary>
/// <exception cref="DirectoryNotFoundException">The entry is not in the trash.</exception>
/// <exception cref="SequenceInLibraryException">A sequence entry whose sequence is in the index already.</exception>
/// <exception cref="TrashMismatchException">No file of a photo entry matches its record; nothing moved.</exception>
/// <exception cref="InvalidDataException">A sidecar is damaged or another sequence's (the trashed folder's own, or that of
/// the sequence the photos go back into); nothing moved.</exception>
public async Task<TrashRestoreResult> RestoreEntryAsync(Guid archiveId, string entryName, JobEngine? followUps = null,
CancellationToken cancellationToken = default)
{
var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false);
if (!Archiving.FrameTrash.IsPhotoEntry(entryName))
return new TrashRestoreResult(TrashKind.Sequence, await Trash.RestoreAsync(archive, entryName, cancellationToken).ConfigureAwait(false), 0, [], false);
var photos = await FrameTrash.RestoreAsync(archive, entryName, followUps, cancellationToken).ConfigureAwait(false);
return new TrashRestoreResult(TrashKind.Photos, photos.Sequence, photos.Restored, photos.Kept, photos.NewSequence);
}
/// <summary>The dry run of emptying an archive's trash: <paramref name="names"/> of the entries (null: all), measured, with the plan's fingerprint.</summary>
public async Task<TrashEmptyPlan> PlanEmptyTrashAsync(Guid archiveId, IReadOnlyList<string>? names = null, CancellationToken cancellationToken = default) =>
await Trash.PlanEmptyAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), names, 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,
@@ -440,6 +470,12 @@ public sealed class ArchiveService : IJobHandlerProvider
private static ArgumentException Unknown(Guid sequenceId) => new($"Unknown sequence {sequenceId}.", nameof(sequenceId));
}
/// <summary>
/// What a restore from the trash did: the kind of entry, the sequence restored (or the one the photos went back into),
/// and for photos how many came back, the photos kept in the trash (each with why) and whether they went into a new sequence.
/// </summary>
public sealed record TrashRestoreResult(TrashKind Kind, Sequence Sequence, int Photos, IReadOnlyList<KeptPhoto> Kept, bool NewSequence);
/// <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);
@@ -518,6 +554,19 @@ public static class ArchiveJobs
new(JobKind.Cleanup, archive is null ? [] : [archive.Id], archive?.Name,
Json(new CleanupParameters(steps, olderThanDays), ArchiveJobJson.Default.CleanupParameters), JobPriority.Normal);
/// <summary>
/// <see cref="JobKind.EmptyTrash"/>: erases exactly the entries of a confirmed <paramref name="plan"/>, refused when the
/// trash no longer matches its fingerprint (owner review 2, R6).
/// </summary>
public static ArchiveJobRequest EmptyTrash(Archive archive, TrashEmptyPlan plan)
{
ArgumentNullException.ThrowIfNull(archive);
ArgumentNullException.ThrowIfNull(plan);
var items = plan.Entries.OrderBy(e => e.Name, StringComparer.Ordinal).Select(e => new EmptyTrashItem(e.Name, SequenceTrash.EntryFingerprint(e))).ToList();
return new(JobKind.EmptyTrash, [archive.Id], archive.Name, Json(new EmptyTrashParameters(items, plan.Fingerprint), ArchiveJobJson.Default.EmptyTrashParameters),
JobPriority.User);
}
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);
@@ -0,0 +1,638 @@
using System.Globalization;
using System.Runtime.ExceptionServices;
using System.Text.Json;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using SequenceFrames = Chronos.Core.Archiving.SequenceFrames;
namespace Chronos.Data.Archiving;
public sealed partial class FrameTrash
{
/// <summary>
/// Folder inside a photo entry where a restore into a new sequence stages each original for the ingest: never a folder
/// another restore shares, never swept by maintenance (it is not the archive's staging), and emptied back into the entry
/// by the next restore of the entry when a crash left something there.
/// </summary>
private const string RestoringFolder = ".restoring";
/// <summary>Who takes an entry's lease while settling a restore another writer of its sequence finds (<see cref="Settle"/>).</summary>
private static readonly string SettleOwner = "chronos@" + Environment.MachineName;
/// <summary>
/// Brings the photos of a trash entry back. Each file is re-hashed against its record: a file that no longer matches
/// (or is missing) stays in the trash with its photo, which is reported, as is a photo whose content an intact frame of
/// the sequence holds again, and one whose files could not move. Each kept photo says why (<see cref="KeptReason"/>).
/// The others move back to their places (a name taken since, or one of its companions', gets <c>_2</c>, <c>_3</c>…)
/// with the same frame records, inserted by capture time, and their tombstones go; a journal
/// (<see cref="FrameRestoreJournal"/>) settles a restore a crash interrupted, and once the first file moves the restore
/// runs to its end whatever the caller cancels. When the sequence is gone (deleted, or never indexed in this archive),
/// they go into a new sequence through the archive ingest, titled and placed as theirs was, the record rewritten after
/// each photo filed; a cancel there stops before the next photo. The entry goes once nothing is left in it.
/// </summary>
/// <param name="name">The entry's <see cref="TrashEntry.Name"/> (<c>photos-…</c>).</param>
/// <exception cref="DirectoryNotFoundException">The entry is not in the trash.</exception>
/// <exception cref="TrashMismatchException">No file of the entry matches its record; nothing moved.</exception>
/// <exception cref="InvalidDataException">The sequence's sidecar is damaged or belongs to another sequence; nothing moved.</exception>
/// <exception cref="LeaseUnavailableException">The entry or the sequence is busy, or the sequence holds a restore of another
/// entry that is busy and not settled yet; nothing moved.</exception>
public async Task<PhotoRestoreResult> RestoreAsync(Archive archive, string name, JobEngine? followUps = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(archive);
ArgumentException.ThrowIfNullOrWhiteSpace(name);
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var entryFolder = Path.Combine(Directory(paths), DiskName(name));
var recordPath = entryFolder + RecordExtension;
// The entry's lease by the name the trash lists it under, the one an emptying and a settle take.
var lease = SequenceTrash.EntryLease(EntryPrefix + DiskName(name));
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, lease, _writer.Options.Owner, _writer.Options.LeaseWait, _writer.Options.LeaseDuration,
cancellationToken).ConfigureAwait(false))
{
if (!System.IO.Directory.Exists(entryFolder) || ReadRecord(recordPath) is not { } listed)
throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}.");
var sequence = await _db.Sequences.GetAsync(listed.SequenceId, cancellationToken).ConfigureAwait(false);
var into = sequence is not null && sequence.ArchiveId == archive.Id ? sequence : null;
// What an earlier restore a crash interrupted left half-way is settled first, so the record read next is true.
Unstage(entryFolder);
if (into is not null && File.Exists(paths.Sequence(into.Folder).RestoreJournalPath))
{
await using (await _writer.LockAsync(paths, into.Id, cancellationToken).ConfigureAwait(false))
SequenceWriter.ReadLocked(paths.Sequence(into.Folder), into.Id, lease);
}
if (!System.IO.Directory.Exists(entryFolder) || ReadRecord(recordPath) is not { } record)
throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}.");
var (intact, kept) = await CheckAsync(entryFolder, record, cancellationToken).ConfigureAwait(false);
// Nothing that matches its record: the entry stays as it is.
if (intact.Count == 0) throw new TrashMismatchException();
var had = into?.Status ?? SequenceStatus.None;
PhotoRestoreResult result;
List<Stay> stays;
var stopped = false;
if (into is not null)
{
// The record is settled under the sequence's lease, with the sidecar.
(result, var left) = await IntoSequenceAsync(archive, paths, into, recordPath, entryFolder, lease, intact, cancellationToken).ConfigureAwait(false);
stays = [.. kept, .. left];
}
else
{
var restore = await IntoNewSequenceAsync(archive, paths, record, recordPath, entryFolder, intact, cancellationToken).ConfigureAwait(false);
stays = [.. kept, .. restore.Left];
Rewrite(recordPath, entryFolder, record with { Photos = [.. stays.Select(s => s.Photo)], Leftovers = Merge(record.Leftovers, restore.Leftovers) });
restore.Failure?.Throw();
stopped = restore.Stopped;
if (stopped && restore.Restored == 0) throw new OperationCanceledException(cancellationToken);
if (restore.SequenceId is not { } id)
throw new IOException($"No photo of trash entry {Path.GetFileName(entryFolder)} could be filed into a new sequence; they stay in the trash.");
var row = await _db.Sequences.GetAsync(id, CancellationToken.None).ConfigureAwait(false)
?? throw new InvalidOperationException($"The photos of {record.SequenceTitle} were restored but their sequence is not indexed.");
result = new PhotoRestoreResult(row, restore.Restored, [], true);
}
Log.Info("archive", $"{record.SequenceTitle}: {result.Restored} photo(s) restored from the trash, {stays.Count} kept there");
var all = result with { Kept = [.. stays.Select(s => new KeptPhoto(s.Photo.Frame.Original ?? Path.GetFileName(s.Photo.Frame.File), s.Reason))] };
if (result.Restored > 0) await QueueAsync(followUps, archive, all.Sequence, had, CancellationToken.None).ConfigureAwait(false);
// A cancel stopped a restore into a new sequence before its last photo: those not done stay in the trash, listed.
if (stopped) throw new OperationCanceledException(cancellationToken);
return all;
}
}
/// <summary>A photo a restore leaves in its entry, and why.</summary>
private sealed record Stay(TrashedPhoto Photo, KeptReason Reason);
/// <summary>
/// Each photo whose files all match their record (size and SHA-256), and those that stay in the trash: a file that does
/// not match, or no file at all (its original was missing when it was deleted).
/// </summary>
private static async Task<(List<TrashedPhoto> Intact, List<Stay> Kept)> CheckAsync(string entryFolder, PhotoTrashRecord record,
CancellationToken cancellationToken)
{
var intact = new List<TrashedPhoto>();
var kept = new List<Stay>();
foreach (var photo in record.Photos)
{
if (photo.Files.Count == 0)
{
kept.Add(new Stay(photo, KeptReason.NoFile));
continue;
}
var ok = true;
foreach (var file in photo.Files)
{
var path = Path.Combine(entryFolder, file.Path);
var info = new FileInfo(path);
if (!info.Exists || info.Length != file.Size
|| (file.Sha256 is { } sha && !string.Equals(sha, await ContentHash.Sha256Async(path, null, cancellationToken).ConfigureAwait(false),
StringComparison.OrdinalIgnoreCase)))
{
Log.Warning("archive", $"{file.Path} of trash entry {Path.GetFileName(entryFolder)} does not match its record; it stays in the trash");
ok = false;
break;
}
}
if (ok) intact.Add(photo);
else kept.Add(new Stay(photo, KeptReason.Mismatch));
}
return (intact, kept);
}
/// <summary>
/// The photos back into their sequence, under its lease: the names chosen and the journal written before the first
/// move, then every move to its end, the sidecar, and the record settled (<see cref="Settle"/>). Returns what came
/// back and the photos left in the trash.
/// </summary>
/// <param name="lease">The entry's lease, which the caller holds.</param>
private async Task<(PhotoRestoreResult, List<Stay>)> IntoSequenceAsync(Archive archive, ArchivePaths paths, Sequence sequence, string recordPath,
string entryFolder, string lease, List<TrashedPhoto> intact, CancellationToken cancellationToken)
{
var folder = paths.Sequence(sequence.Folder);
var left = new List<Stay>();
int restored;
SequenceManifest updated;
var indexed = true;
await using (await _writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
{
var manifest = SequenceWriter.ReadLocked(folder, sequence.Id, lease);
// A restore of another entry, busy now, is not settled yet: its journal is not written over.
EnsureSettled(folder);
var inStep = await _indexer.InStepAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false);
var photosChanged = !inStep && await _indexer.PhotosChangedAsync(archive, folder, cancellationToken).ConfigureAwait(false);
var ids = manifest.Frames.Select(f => f.Id).ToHashSet();
var holders = manifest.Frames.Where(f => f.Sha256 is not null).ToLookup(f => f.Sha256!, StringComparer.OrdinalIgnoreCase);
var taken = manifest.Frames.Select(f => f.File).ToHashSet(StringComparer.OrdinalIgnoreCase);
var planned = new List<(TrashedPhoto Photo, SidecarFrame Frame, RestoredPhoto Moves)>();
foreach (var photo in intact)
{
// In the sequence again (restored before, or filed again since): the trash keeps its copy. Only a frame that
// still holds the content counts; a missing or damaged one leaves the trash's copy to come back.
if (ids.Contains(photo.Frame.Id) || (photo.Frame.Sha256 is { } sha && holders[sha].Any(f => ArchiveIngest.IsIntact(folder, f))))
{
left.Add(new Stay(photo, KeptReason.InSequence));
continue;
}
var original = photo.Files[0];
var tails = photo.Files.Skip(1).Select(c => CompanionTail(c.From, original.From)).ToList();
var file = FreeName(folder, original.From, tails, taken);
var stem = file[..^Path.GetExtension(file).Length];
taken.Add(file);
// A companion follows its photo's name: IMG_0001_2.xmp beside IMG_0001_2.JPG.
List<FrameRemovalMove> moves = [new(file, paths.ToRelative(Path.Combine(entryFolder, original.Path)))];
for (var c = 0; c < tails.Count; c++)
{
taken.Add(stem + tails[c]);
moves.Add(new FrameRemovalMove(stem + tails[c], paths.ToRelative(Path.Combine(entryFolder, photo.Files[c + 1].Path))));
}
planned.Add((photo, photo.Frame with { File = file, Flags = photo.Frame.Flags & ~FrameFlags.Missing }, new RestoredPhoto(photo.Frame.Id, moves)));
}
if (planned.Count == 0) return (new PhotoRestoreResult(sequence, 0, [], false), left);
// Checked once: from the journal on, the restore runs to its end whatever the caller cancels meanwhile.
cancellationToken.ThrowIfCancellationRequested();
var journal = new FrameRestoreJournal(paths.ToRelative(recordPath), paths.ToRelative(entryFolder), [.. planned.Select(p => p.Moves)]);
journal.Write(folder);
var back = new List<SidecarFrame>();
foreach (var (photo, frame, moves) in planned)
{
if (MoveIn(paths, folder, moves.Moves)) back.Add(frame);
else left.Add(new Stay(photo, KeptReason.NotMoved));
}
updated = manifest;
if (back.Count > 0)
{
var returned = back.Where(f => f.Sha256 is not null).Select(f => f.Sha256!).ToHashSet(StringComparer.OrdinalIgnoreCase);
var tombstones = manifest.Removed?.Where(r => !returned.Contains(r.Sha256)).ToList();
updated = SequenceFrames.Insert(manifest, back) with
{
Status = manifest.Status & ~Uncovered,
Removed = tombstones is { Count: > 0 } ? tombstones : null,
};
try
{
ManifestStore.WriteSequence(folder.ManifestPath, updated);
}
catch (Exception ex)
{
// The sidecar lists none of them: their files go back into the entry, whose record is as it was.
Log.Warning("archive", $"{sequence.DisplayTitle}: the sidecar could not take the photos restored; they go back into the trash", ex);
Settle(folder, manifest, journal, lease);
throw;
}
}
Settle(folder, updated, journal, lease);
restored = back.Count;
if (restored > 0)
{
indexed = await IndexAsync(archive, folder, updated, photosChanged, sequence.DisplayTitle).ConfigureAwait(false);
ShiftProxies(folder, manifest.Frames, updated.Frames, []);
ShiftThumbnails(paths, folder, sequence.Id, manifest.Frames, updated.Frames);
}
}
var row = restored > 0 ? await RowAsync(sequence, updated, indexed).ConfigureAwait(false) : sequence;
return (new PhotoRestoreResult(row, restored, [], false), left);
}
/// <summary>
/// Moves one photo's files from its entry into the sequence, the original first. When one cannot follow, those that
/// moved go back, the companions first, so the photo stays whole in the trash; an original that cannot go back either
/// stays restored, and its companions that are still in the entry then stay there (leftovers of its record). Returns
/// whether the original is in the sequence.
/// </summary>
private static bool MoveIn(ArchivePaths paths, SequencePaths folder, IReadOnlyList<FrameRemovalMove> moves)
{
var done = 0;
try
{
for (; done < moves.Count; done++) MoveFile(paths.FromRelative(moves[done].To), folder.File(moves[done].From));
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"{moves[done].To} could not move back into {folder.RelativeFolder}; its photo stays in the trash", ex);
for (var i = done - 1; i >= 0; i--)
{
try
{
MoveFile(folder.File(moves[i].From), paths.FromRelative(moves[i].To));
}
catch (Exception again) when (again is IOException or UnauthorizedAccessException)
{
Log.Error("archive", $"{folder.ArchiveRelative(moves[i].From)} could not go back into the trash; its photo stays restored", again);
return true;
}
}
return false;
}
}
/// <summary>
/// Settles a restore into a sequence (<see cref="FrameRestoreJournal"/>) as <paramref name="manifest"/>, the sidecar
/// read or written under the sequence's lease, has it: each photo the sidecar lists again leaves the entry's record (a
/// companion of it still in the entry stays there as one of the record's leftovers), and each file of the others that
/// reached the sequence goes back into the entry, whose record still lists it (unless the entry was emptied since: the
/// file then stays where it is, logged, for a scan to adopt). Then the journal goes. All of it under the entry's lease
/// as well, which an emptying holds: an entry busy now (or a failure, logged) keeps the journal, and the next writer of
/// the sequence settles it (<see cref="EnsureSettled"/> keeps writers that would add files from going on meanwhile).
/// </summary>
/// <param name="heldLease">The entry lease the caller holds already (its own restore), if any.</param>
internal static void Settle(SequencePaths sequence, SequenceManifest manifest, FrameRestoreJournal journal, string? heldLease = null)
{
var archive = sequence.Archive;
var recordPath = archive.FromRelative(journal.Record);
var entryFolder = archive.FromRelative(journal.Folder);
var listed = manifest.Frames.Select(f => f.Id).ToHashSet();
var lease = EntryLease(entryFolder);
LeaseFile? taken = null;
if (lease != heldLease)
{
taken = LeaseFile.TryAcquire(archive.LocksDirectory, lease, SettleOwner);
if (taken is null)
{
Log.Info("archive", $"A restore from the trash into {sequence.RelativeFolder} waits: its entry {Path.GetFileName(entryFolder)} is busy");
return;
}
}
using var held = taken;
try
{
var record = ReadRecord(recordPath);
var back = new HashSet<Guid>();
var leftovers = new HashSet<string>(StringComparer.Ordinal);
foreach (var photo in journal.Photos)
{
if (listed.Contains(photo.Frame))
{
back.Add(photo.Frame);
leftovers.UnionWith(photo.Moves.Where(m => File.Exists(archive.FromRelative(m.To))).Select(m => m.To));
continue;
}
foreach (var move in photo.Moves)
{
var place = sequence.File(move.From);
var trashed = archive.FromRelative(move.To);
if (!File.Exists(place) || File.Exists(trashed)) continue;
if (record is null)
{
Log.Warning("archive", $"{sequence.ArchiveRelative(move.From)} stays in its sequence: its trash entry is gone");
continue;
}
MoveFile(place, trashed);
}
}
if (record is not null && back.Count > 0)
{
var extra = record.Photos.Where(p => back.Contains(p.Frame.Id)).SelectMany(p => p.Files)
.Where(f => leftovers.Contains(archive.ToRelative(Path.Combine(entryFolder, f.Path))));
Rewrite(recordPath, entryFolder, record with
{
Photos = [.. record.Photos.Where(p => !back.Contains(p.Frame.Id))],
Leftovers = Merge(record.Leftovers, extra),
});
}
FrameRestoreJournal.Delete(sequence);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"A restore from the trash into {sequence.RelativeFolder} is not settled yet; the next writer of the sequence settles it", ex);
}
}
/// <summary>
/// Settles the restore a crash interrupted (<see cref="Settle"/>), if any; the caller holds the sequence's lease, and
/// <paramref name="heldLease"/> when it holds an entry's lease too.
/// </summary>
internal static void RecoverRestore(SequencePaths sequence, SequenceManifest manifest, string? heldLease = null)
{
if (!File.Exists(sequence.RestoreJournalPath)) return;
if (FrameRestoreJournal.Read(sequence) is { } journal)
{
Log.Warning("archive", $"An interrupted restore from the trash into {sequence.RelativeFolder} is settled unless its entry is busy");
Settle(sequence, manifest, journal, heldLease);
}
else
{
FrameRestoreJournal.Delete(sequence); // torn while being written: nothing was moved yet
}
}
/// <summary>
/// Refuses to go on while a restore into <paramref name="sequence"/> is still not settled after
/// <see cref="SequenceWriter.ReadLocked"/> (its entry was busy, or a file could not move): a writer that would write
/// another journal over it, or move the sequence's folder away with it, waits until it is. The caller holds the
/// sequence's lease.
/// </summary>
/// <exception cref="LeaseUnavailableException">The restore is not settled; nothing was changed.</exception>
internal static void EnsureSettled(SequencePaths sequence)
{
if (!File.Exists(sequence.RestoreJournalPath)) return;
var lease = FrameRestoreJournal.Read(sequence) is { } journal ? EntryLease(sequence.Archive.FromRelative(journal.Folder)) : "restore";
throw new LeaseUnavailableException(lease, LeaseFile.Holder(sequence.Archive.LocksDirectory, lease));
}
/// <summary>The lease of the photo entry in <paramref name="entryFolder"/>, as a restore and an emptying of it take it.</summary>
private static string EntryLease(string entryFolder) => SequenceTrash.EntryLease(EntryPrefix + Path.GetFileName(entryFolder));
/// <summary>
/// What a restore into a new sequence did: the photos left in the trash, the companions that did not follow theirs, and
/// what stopped it before its last photo (a failure other than a file's, or a cancel).
/// </summary>
private sealed record NewSequenceRestore(Guid? SequenceId, int Restored, List<Stay> Left, List<TrashedFile> Leftovers, ExceptionDispatchInfo? Failure,
bool Stopped);
/// <summary>
/// The photos of a sequence that is gone into a new one, through the archive ingest (naming templates, a sidecar of its
/// own), one photo at a time so one that fails stays in the trash alone: titled as theirs was, placed at its folder when
/// that is free, and keyed by its id, so every entry of that sequence comes back into the same new one. Each original
/// is staged inside its own entry (<see cref="RestoringFolder"/>); once it leaves the entry its commit runs to the end,
/// and when it is not filed, whatever the failure, it goes back. Companions follow their photo under a name chosen so
/// that theirs are free. The record is rewritten after each photo filed, so a crash or a failure later never leaves it
/// listing one that is back. A cancel, or a failure other than a file's, stops before the next photo.
/// </summary>
private async Task<NewSequenceRestore> IntoNewSequenceAsync(Archive archive, ArchivePaths paths, PhotoTrashRecord record, string recordPath,
string entryFolder, List<TrashedPhoto> intact, CancellationToken cancellationToken)
{
var left = new List<Stay>();
var leftovers = new List<TrashedFile>();
var filed = new HashSet<Guid>();
var staging = Path.Combine(entryFolder, RestoringFolder);
var key = $"trash:{record.SequenceId:N}";
var target = new SequenceTarget(key, record.SequenceTitle, record.SequenceFolder.Length > 0 ? record.SequenceFolder : null, null);
var sequenceId = await _db.Sequences.FindBySessionKeyAsync(archive.Id, key, cancellationToken).ConfigureAwait(false);
SequencePaths? folder = null;
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var restored = 0;
ExceptionDispatchInfo? failure = null;
var stopped = false;
foreach (var photo in intact)
{
stopped |= failure is null && cancellationToken.IsCancellationRequested;
if (failure is not null || stopped)
{
left.Add(new Stay(photo, KeptReason.NotMoved));
continue;
}
if (folder is null && sequenceId is { } known && await _db.Sequences.GetAsync(known, CancellationToken.None).ConfigureAwait(false) is { } row)
folder = paths.Sequence(row.Folder);
var original = photo.Files[0];
var tails = photo.Files.Skip(1).Select(c => CompanionTail(c.From, original.From)).ToList();
var planned = FreeName(folder, ArchiveLayout.OriginalsFolder + "/" + Path.GetFileName(original.From), tails, names);
var inEntry = Path.Combine(entryFolder, original.Path);
var path = Path.Combine(staging, original.Path);
try
{
MoveFile(inEntry, path);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"{original.Path} could not be staged for a restore; it stays in the trash", ex);
left.Add(new Stay(photo, KeptReason.NotMoved));
continue;
}
IngestResult? result = null;
try
{
var frame = new StagedFrame(path, photo.Frame.Original ?? Path.GetFileName(original.From), original.Size, photo.Frame.Sha256 ?? original.Sha256!,
MetadataReader.Read(path, CancellationToken.None), photo.Frame.CapturedAt, Path.GetFileName(planned));
// The original has left the entry: its commit runs to the end whatever the caller cancels meanwhile.
result = (await _ingest.CommitSessionAsync(archive, target, [frame], CancellationToken.None).ConfigureAwait(false))[0];
}
catch (Exception ex)
{
Log.Warning("archive", $"{original.Path} could not be restored into a new sequence", ex);
if (ex is not (IOException or UnauthorizedAccessException or InvalidDataException)) failure = ExceptionDispatchInfo.Capture(ex);
}
if (File.Exists(path))
{
// Not filed (a failure, or a duplicate of a photo the new sequence holds): it returns to the entry, or, when it
// cannot, the next restore of the entry puts it back.
try
{
MoveFile(path, inEntry);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Error("archive", $"{original.Path} stays staged in its trash entry; the next restore puts it back", ex);
}
left.Add(new Stay(photo, result is { Duplicate: true } ? KeptReason.InSequence : KeptReason.NotMoved));
continue;
}
restored++;
filed.Add(photo.Frame.Id);
if (result is null)
{
// Filed although its commit failed afterwards (the ingest's journal completes it): where is not known, so its
// companions stay in the trash.
leftovers.AddRange(photo.Files.Skip(1));
Follow();
continue;
}
sequenceId ??= result.SequenceId;
var placed = paths.FromRelative(result.RelativePath);
var stem = placed[..^Path.GetExtension(placed).Length];
names.Add(ArchiveLayout.OriginalsFolder + "/" + Path.GetFileName(placed));
foreach (var companion in photo.Files.Skip(1))
{
var beside = stem + CompanionTail(companion.From, original.From);
names.Add(ArchiveLayout.OriginalsFolder + "/" + Path.GetFileName(beside));
try
{
MoveFile(Path.Combine(entryFolder, companion.Path), beside);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Taken there since its name was chosen, or not movable: it stays in the trash, counted in the record.
Log.Warning("archive", $"{companion.Path} could not follow its photo to {result.RelativePath}; it stays in the trash", ex);
leftovers.Add(companion);
}
}
Follow();
}
// A photo filed by a commit that failed afterwards may be the first in the new sequence.
if (sequenceId is null && restored > 0)
sequenceId = await _db.Sequences.FindBySessionKeyAsync(archive.Id, key, CancellationToken.None).ConfigureAwait(false);
return new NewSequenceRestore(sequenceId, restored, left, leftovers, failure, stopped);
// The record without the photos filed so far, and with the companions that did not follow; a record that cannot be
// written now (logged) is written once more when the restore ends.
void Follow()
{
try
{
Rewrite(recordPath, entryFolder, record with
{
Photos = [.. record.Photos.Where(p => !filed.Contains(p.Frame.Id))],
Leftovers = Merge(record.Leftovers, leftovers),
});
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"Trash record {recordPath} does not follow the photos restored yet; it is written again at the end", ex);
}
}
}
/// <summary>Puts back into an entry what a restore into a new sequence left staged in it (a crash, or a file that could not move back).</summary>
private static void Unstage(string entryFolder)
{
var staging = Path.Combine(entryFolder, RestoringFolder);
if (!System.IO.Directory.Exists(staging)) return;
foreach (var file in System.IO.Directory.EnumerateFiles(staging, "*", SearchOption.AllDirectories).ToList())
{
var place = Path.Combine(entryFolder, Path.GetRelativePath(staging, file));
if (File.Exists(place))
{
Log.Warning("archive", $"{file} stays staged: {place} exists");
continue;
}
MoveFile(file, place);
Log.Warning("archive", $"{Path.GetRelativePath(entryFolder, place)} of trash entry {Path.GetFileName(entryFolder)} was staged by a restore that stopped; it is back");
}
FrameRemovalJournal.RemoveEmpty(staging);
}
/// <summary>
/// Rewrites an entry's record with what it still holds; when it lists nothing and nothing is left in its folder, the
/// record goes too. While it lists a photo, its folder stays (empty when only photos without a file are left), so the
/// entry stays listed and Empty can erase it.
/// </summary>
private static void Rewrite(string recordPath, string entryFolder, PhotoTrashRecord record)
{
var done = record.Photos.Count == 0 && record.Leftovers is not { Count: > 0 };
if (done) FrameRemovalJournal.RemoveEmpty(entryFolder);
else if (System.IO.Directory.Exists(entryFolder))
foreach (var child in System.IO.Directory.EnumerateDirectories(entryFolder).ToList()) FrameRemovalJournal.RemoveEmpty(child);
// Only an entry left without a file goes; anything still in its folder keeps it listed, never erased by a restore.
if (done && !System.IO.Directory.Exists(entryFolder))
{
File.Delete(recordPath);
return;
}
AtomicFile.WriteAllText(recordPath, JsonSerializer.Serialize(record with
{
Bytes = record.Photos.Sum(p => p.Files.Sum(f => f.Size)) + (record.Leftovers?.Sum(f => f.Size) ?? 0),
}, TrashJson.Default.PhotoTrashRecord));
}
/// <summary>The leftovers of a record with <paramref name="more"/>, each file once; null when there are none.</summary>
private static List<TrashedFile>? Merge(IReadOnlyList<TrashedFile>? leftovers, IEnumerable<TrashedFile> more)
{
var all = (leftovers ?? []).Concat(more).DistinctBy(f => f.Path, StringComparer.OrdinalIgnoreCase).ToList();
return all.Count > 0 ? all : null;
}
/// <summary>What a companion's name adds to its photo's stem (<c>.xmp</c>, <c>.CR2.xmp</c>).</summary>
private static string CompanionTail(string companion, string photo)
{
var stem = Path.GetFileNameWithoutExtension(Path.GetFileName(photo));
var name = Path.GetFileName(companion);
return name.StartsWith(stem, StringComparison.OrdinalIgnoreCase) ? name[stem.Length..] : Path.GetExtension(name);
}
/// <summary>
/// <paramref name="file"/> when it and its companions' names (<paramref name="tails"/> after its stem) are free in
/// <paramref name="taken"/> and on disk in <paramref name="folder"/> (none yet: in <paramref name="taken"/> only), else
/// <c>stem_2.ext</c>, <c>stem_3.ext</c>…
/// </summary>
private static string FreeName(SequencePaths? folder, string file, IReadOnlyList<string> tails, HashSet<string> taken)
{
var extension = Path.GetExtension(file);
var stem = file[..^extension.Length];
var candidate = file;
for (var n = 2; Taken(candidate); n++)
candidate = string.Create(CultureInfo.InvariantCulture, $"{stem}_{n}{extension}");
return candidate;
bool Taken(string name)
{
var named = name[..^extension.Length];
return Used(name) || tails.Any(t => Used(named + t));
}
bool Used(string name) => taken.Contains(name) || (folder is not null && File.Exists(folder.File(name)));
}
}
/// <summary>The files of one photo a restore moves from its trash entry into its sequence, the original first.</summary>
/// <param name="Frame">The photo's frame id, which the sidecar lists once the photo is back.</param>
/// <param name="Moves">Each file: <see cref="FrameRemovalMove.From"/> its place in the sequence folder, <see cref="FrameRemovalMove.To"/>
/// the file in the entry (relative to the archive root).</param>
internal sealed record RestoredPhoto(Guid Frame, IReadOnlyList<FrameRemovalMove> Moves);
/// <summary>
/// Write-ahead record of photos restored from the trash into their sequence (<c>.chronos/restore.pending.json</c>, owner
/// review 2, R6): the entry they come from and each photo's file moves. Written under the sequence's lease before the
/// first move and removed once the restore is settled (<see cref="FrameTrash.Settle"/>: the record without the photos the
/// sidecar lists, the files of the others back in the entry), so the next writer of the sequence settles a restore a crash
/// interrupted (<see cref="SequenceWriter.ReadLocked"/>).
/// </summary>
/// <param name="Record">The entry's record, relative to the archive root.</param>
/// <param name="Folder">The entry's folder, relative to the archive root.</param>
internal sealed record FrameRestoreJournal(string Record, string Folder, IReadOnlyList<RestoredPhoto> Photos)
{
public void Write(SequencePaths sequence)
{
System.IO.Directory.CreateDirectory(sequence.MetaDirectory);
AtomicFile.WriteAllBytes(sequence.RestoreJournalPath, JsonSerializer.SerializeToUtf8Bytes(this, TrashJson.Default.FrameRestoreJournal));
}
/// <summary>The journal of a sequence; null when it is torn (written by a process that died while writing it).</summary>
public static FrameRestoreJournal? Read(SequencePaths sequence)
{
try
{
return JsonSerializer.Deserialize(AtomicFile.ReadAllBytes(sequence.RestoreJournalPath), TrashJson.Default.FrameRestoreJournal);
}
catch (JsonException)
{
return null;
}
}
public static void Delete(SequencePaths sequence)
{
if (File.Exists(sequence.RestoreJournalPath)) File.Delete(sequence.RestoreJournalPath);
}
}
+717
View File
@@ -0,0 +1,717 @@
using System.Globalization;
using System.Text.Json;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
using Chronos.Core.Model;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using ProcessingJobs = Chronos.Data.Processing.ProcessingJobs;
using ProcessingFrames = Chronos.Data.Processing.SequenceFrames;
using SequenceFrames = Chronos.Core.Archiving.SequenceFrames;
namespace Chronos.Data.Archiving;
/// <summary>Why photos cannot leave their sequence; nothing is touched.</summary>
public enum FrameDeleteBlock
{
/// <summary>The archive is offline or read-only.</summary>
Offline,
/// <summary>A running or paused job works on the sequence or its whole archive (<see cref="SequenceTrash"/>'s rule).</summary>
Busy,
/// <summary>The sequence's frames changed since the caller read them (another version, or a frame named is gone).</summary>
FramesChanged,
/// <summary>Every frame of the sequence would go: delete the sequence instead, which keeps its settings and renders.</summary>
WouldEmpty,
/// <summary>
/// A photo named was never hashed and its original is on disk but cannot be read (another program holds it, or no
/// access; <see cref="FrameDeletePlan.Unhashable"/>): it is hashed as it goes, for the tombstone that tells sync it was
/// deleted, so it waits until it can be read. One whose original is missing is not blocked: it goes without a file and
/// without a tombstone, as there is no content left to name.
/// </summary>
Unhashable,
}
/// <summary>The dry run of deleting photos of one sequence into the archive's trash (owner review 2, R6).</summary>
/// <param name="Frames">The frames that go, in index order.</param>
/// <param name="Bytes">Their originals' size.</param>
/// <param name="Blocked">Why they cannot go; empty when they can.</param>
public sealed record FrameDeletePlan(Sequence Sequence, IReadOnlyList<Frame> Frames, long Bytes, IReadOnlyList<FrameDeleteBlock> Blocked)
{
public bool CanDelete => Blocked.Count == 0 && Frames.Count > 0;
/// <summary>The frames named that block the plan as <see cref="FrameDeleteBlock.Unhashable"/>, in index order.</summary>
public IReadOnlyList<Frame> Unhashable { get; init; } = [];
}
/// <summary>What a photo deletion did: the trash entry made and the sequence as it is now.</summary>
public sealed record FrameDeleteResult(TrashEntry Entry, Sequence Sequence);
/// <summary>Why a photo stayed in the trash when its entry was restored.</summary>
public enum KeptReason
{
/// <summary>A file of it no longer matches its record (changed, or gone from the entry).</summary>
Mismatch,
/// <summary>Its files match, but they could not be moved back (open elsewhere, no access, or the archive refused them).</summary>
NotMoved,
/// <summary>The sequence holds its content again (restored before, or filed again since): the trash keeps its copy.</summary>
InSequence,
/// <summary>Its original was already missing when it was deleted: the entry holds its record without a file.</summary>
NoFile,
}
/// <summary>A photo a restore left in the trash: its name (as on the card or upload source) and why.</summary>
public sealed record KeptPhoto(string Name, KeptReason Reason)
{
/// <summary>"2 photos stayed in the trash: they no longer match their record." in <paramref name="culture"/>.</summary>
public static string Sentence(KeptReason reason, int count, System.Globalization.CultureInfo culture) =>
Core.Localization.Loc.Text(reason switch
{
KeptReason.Mismatch => "Archive.Trash.Kept.Mismatch",
KeptReason.NotMoved => "Archive.Trash.Kept.NotMoved",
KeptReason.InSequence => "Archive.Trash.Kept.InSequence",
_ => "Archive.Trash.Kept.NoFile",
}, [count], culture);
/// <summary>One sentence per reason, in the order of <see cref="KeptReason"/>, each counting its photos.</summary>
public static IReadOnlyList<string> Sentences(IEnumerable<KeptPhoto> kept, System.Globalization.CultureInfo culture) =>
[.. kept.GroupBy(k => k.Reason).OrderBy(g => g.Key).Select(g => Sentence(g.Key, g.Count(), culture))];
}
/// <summary>
/// What a restore of photos did: the sequence they went back into (a new one when theirs is gone), how many came back, and
/// the photos kept in the trash, each with why (<see cref="KeptReason"/>).
/// </summary>
public sealed record PhotoRestoreResult(Sequence Sequence, int Restored, IReadOnlyList<KeptPhoto> Kept, bool NewSequence);
/// <summary>
/// Deleting photos of a sequence without erasing anything (owner review 2, R6; BRIEF §0.2 rule 8): <see cref="PlanDeleteAsync"/>
/// is the dry run; <see cref="DeleteAsync"/> moves each original (and its XMP companion) under the sequence's lease into
/// <c>.chronos/trash/photos/&lt;sequence&gt;-&lt;time&gt;/originals</c> next to a record of the frames, writes the sidecar
/// without them (frames version + 1) and with a tombstone of each (a photo never hashed is hashed first), and indexes it:
/// what covered the frames is cleared and queued again, the proxies and thumbnails of the frames that stay follow their
/// new index, and the project's positions follow their photos (those on the photos that went wait as pending frames).
/// A journal undoes a deletion a crash interrupted, whose entry the trash does not list meanwhile.
/// <see cref="RestoreAsync"/> re-hashes each file against its record and moves the matching ones back with the same frame
/// records, dropping their tombstones, under a journal of its own; into a new sequence through the archive ingest when
/// theirs is gone.
/// </summary>
public sealed partial class FrameTrash
{
/// <summary>Folder of the photo entries inside the trash.</summary>
public const string FolderName = "photos";
/// <summary>What <see cref="TrashEntry.Name"/> of a photo entry starts with (the folder name follows).</summary>
public const string EntryPrefix = "photos-";
private const string RecordExtension = ".json";
/// <summary>Statuses the frames removed or put back no longer let stand: the passes make them again.</summary>
private const SequenceStatus Uncovered = SequenceStatus.AnalyzedLight | SequenceStatus.AnalyzedDeep | SequenceStatus.ThumbsBuilt | SequenceStatus.ProxiesBuilt;
private readonly ChronosDatabase _db;
private readonly SequenceWriter _writer;
private readonly ArchiveIndexer _indexer;
private readonly ArchiveIngest _ingest;
private readonly SequenceTrash _trash;
internal FrameTrash(ChronosDatabase db, SequenceWriter writer, ArchiveIndexer indexer, ArchiveIngest ingest, SequenceTrash trash)
{
_db = db;
_writer = writer;
_indexer = indexer;
_ingest = ingest;
_trash = trash;
}
/// <summary>The folder of the photo entries of an archive's trash.</summary>
public static string Directory(ArchivePaths archive) => Path.Combine(SequenceTrash.TrashDirectory(archive), FolderName);
/// <summary>Whether <paramref name="name"/> names a photo entry (<see cref="EntryPrefix"/>).</summary>
public static bool IsPhotoEntry(string name) => name.StartsWith(EntryPrefix, StringComparison.Ordinal);
/// <summary>
/// The dry run: the frames of <paramref name="frameIds"/> that go and their size, or why they cannot go. With
/// <paramref name="expectedFramesVersion"/>, frames that changed since the caller read that version block the plan.
/// </summary>
/// <exception cref="ArgumentException">The sequence is not in the index, or no frame is named.</exception>
public async Task<FrameDeletePlan> PlanDeleteAsync(Guid sequenceId, IReadOnlyList<Guid> frameIds, int? expectedFramesVersion = null,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(frameIds);
if (frameIds.Count == 0) throw new ArgumentException("No frame is named.", nameof(frameIds));
var sequence = await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
?? throw new ArgumentException($"Unknown sequence {sequenceId}.", nameof(sequenceId));
var archive = await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false)
?? throw new ArgumentException($"Unknown archive {sequence.ArchiveId}.", nameof(sequenceId));
var all = await ProcessingFrames.ListAsync(_db, sequenceId, cancellationToken).ConfigureAwait(false);
var wanted = frameIds.ToHashSet();
var frames = all.Where(f => wanted.Contains(f.Id)).ToList();
var blocked = new List<FrameDeleteBlock>();
var paths = new ArchivePaths(archive.RootPath);
var online = ArchiveVolume.Probe(paths) == ArchiveAvailability.Online;
if (!online) blocked.Add(FrameDeleteBlock.Offline);
var busy = await _trash.BusyAsync(cancellationToken).ConfigureAwait(false);
if (busy.Contains(sequence.Id) || busy.Contains(sequence.ArchiveId)) blocked.Add(FrameDeleteBlock.Busy);
if (frames.Count != wanted.Count || (expectedFramesVersion is { } expected && expected != sequence.FramesVersion)) blocked.Add(FrameDeleteBlock.FramesChanged);
if (frames.Count > 0 && frames.Count == all.Count) blocked.Add(FrameDeleteBlock.WouldEmpty);
// A photo without a hash is hashed as it goes, for its tombstone: one whose original cannot be read waits.
var unhashable = online ? Unreadable(paths, frames) : [];
if (unhashable.Count > 0) blocked.Add(FrameDeleteBlock.Unhashable);
return new FrameDeletePlan(sequence, frames, frames.Sum(f => f.Size), blocked) { Unhashable = unhashable };
}
/// <summary>
/// The frames never hashed whose original is on disk but cannot be opened for reading, in index order: the first
/// <c>256</c> of them are opened (nothing is read), so a dry run of thousands stays quick on a share; one past those that
/// cannot be read refuses the deletion itself, which hashes them (an <see cref="IOException"/>, nothing moved). A missing
/// original is no reason: nothing is left to hash.
/// </summary>
private static List<Frame> Unreadable(ArchivePaths paths, IReadOnlyList<Frame> frames)
{
const int Probes = 256;
return [.. frames.Where(f => f.Sha256 is null).OrderBy(f => f.Index).Take(Probes).Where(f => !CanRead(paths.FromRelative(f.RelativePath)))];
}
/// <summary>Whether a file opens for reading; one that is not there counts as readable (there is nothing to read).</summary>
private static bool CanRead(string path)
{
try
{
using var handle = File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
return true;
}
catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException)
{
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return false;
}
}
/// <summary>
/// Moves exactly the planned photos into the trash and takes them out of the sequence, then queues on
/// <paramref name="followUps"/> (null: nothing) what the frames need again: the light analysis, a background deep analysis
/// when the sequence had one, and the thumbnails and proxies the host keeps (always on a server; on a desktop those it
/// had). A kind the engine does not run, or one already queued for the sequence, is left out. Once the sidecar is
/// written the deletion stands: an index that cannot follow (logged) is resynced by the next scan.
/// </summary>
/// <param name="deletedBy">Who asked (user name or client), kept in the trash record.</param>
/// <exception cref="StaleDeletePlanException">The plan is blocked, or the sequence changed since it was made; nothing moved.</exception>
/// <exception cref="ArchiveOfflineException">The archive went offline; nothing moved.</exception>
/// <exception cref="IOException">A file is open elsewhere, or the sidecar could not be written; nothing moved.</exception>
public async Task<FrameDeleteResult> DeleteAsync(FrameDeletePlan plan, string? deletedBy = null, JobEngine? followUps = null,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(plan);
var id = plan.Sequence.Id;
if (!plan.CanDelete) throw new StaleDeletePlanException(id);
var revised = await PlanDeleteAsync(id, [.. plan.Frames.Select(f => f.Id)], plan.Sequence.FramesVersion, cancellationToken).ConfigureAwait(false);
var archive = await ArchiveOfAsync(revised.Sequence, cancellationToken).ConfigureAwait(false);
var paths = new ArchivePaths(archive.RootPath);
// Offline since the plan: said as such (ArchiveOfflineException), not as a stale plan.
ArchiveVolume.EnsureWritable(paths);
if (!revised.CanDelete || revised.Sequence.Folder != plan.Sequence.Folder) throw new StaleDeletePlanException(id);
var folder = paths.Sequence(revised.Sequence.Folder);
var had = revised.Sequence.Status;
TrashEntry entry;
SequenceManifest updated;
bool indexed;
await using (await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false))
{
var manifest = SequenceWriter.ReadLocked(folder, id);
var plannedPaths = plan.Frames.ToDictionary(f => f.Id, f => f.RelativePath);
var planned = plannedPaths.Keys.ToHashSet();
var removed = manifest.Frames.Where(f => planned.Contains(f.Id)).ToList();
if (manifest.Versions.Frames != plan.Sequence.FramesVersion || removed.Count != planned.Count
|| removed.Any(f => plannedPaths[f.Id] != folder.ArchiveRelative(f.File)))
throw new StaleDeletePlanException(id);
var kept = manifest.Frames.Where(f => !planned.Contains(f.Id)).ToList();
if (kept.Count == 0) throw new StaleDeletePlanException(id);
var inStep = await _indexer.InStepAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false);
var photosChanged = !inStep && await _indexer.PhotosChangedAsync(archive, folder, cancellationToken).ConfigureAwait(false);
var trash = Directory(paths);
System.IO.Directory.CreateDirectory(trash);
var name = EntryName(trash, id);
var entryFolder = Path.Combine(trash, name);
var recordPath = entryFolder + RecordExtension;
var photos = await TrashedAsync(folder, removed, kept, cancellationToken).ConfigureAwait(false);
var (held, hashed) = await HeldAsync(folder, kept, photos, cancellationToken).ConfigureAwait(false);
// The hashes computed for frames that stay go into the sidecar with them: a later deletion does not read them again.
if (hashed.Count > 0) kept = [.. kept.Select(f => hashed.TryGetValue(f.Id, out var sha) ? f with { Sha256 = sha } : f)];
var now = DateTimeOffset.UtcNow;
var record = new PhotoTrashRecord(TrashKind.Photos, id, revised.Sequence.DisplayTitle, revised.Sequence.Folder, photos,
photos.Sum(p => p.Files.Sum(f => f.Size)), now, deletedBy);
var moves = photos.SelectMany(p => p.Files).Select(f => new FrameRemovalMove(f.From, paths.ToRelative(Path.Combine(entryFolder, f.Path)))).ToList();
updated = SequenceFrames.WithFrames(manifest, kept) with
{
Status = manifest.Status & ~Uncovered,
Removed = WithTombstones(manifest.Removed, photos, held, now),
};
cancellationToken.ThrowIfCancellationRequested();
// The journal first: a crash from here until the sidecar is written puts every file back (ReadLocked).
FrameRemovalJournal.Write(folder, new FrameRemovalJournal(paths.ToRelative(recordPath), paths.ToRelative(entryFolder), [.. planned], moves));
// Under a name the trash does not list until the sidecar is written: half an entry is never restored or emptied.
AtomicFile.WriteAllText(FrameRemovalJournal.PendingRecord(recordPath), JsonSerializer.Serialize(record, TrashJson.Default.PhotoTrashRecord));
System.IO.Directory.CreateDirectory(entryFolder);
var done = new List<FrameRemovalMove>();
try
{
foreach (var move in moves)
{
MoveFile(folder.File(move.From), paths.FromRelative(move.To));
done.Add(move);
}
ManifestStore.WriteSequence(folder.ManifestPath, updated);
}
catch (Exception ex)
{
// A file is open elsewhere, or the sidecar cannot be written: the ones that moved go back, and nothing changed.
Log.Warning("archive", $"{revised.Sequence.DisplayTitle}: photos could not move to the trash; those that moved go back", ex);
Undo(paths, folder, done, recordPath, entryFolder);
throw;
}
Publish(folder, recordPath);
Log.Info("archive", $"{revised.Sequence.DisplayTitle}: {removed.Count} photo(s) moved to the trash ({name}, {record.Bytes} bytes)");
// The files have moved: the index follows to the end, whatever the caller cancels meanwhile.
indexed = await IndexAsync(archive, folder, updated, photosChanged, revised.Sequence.DisplayTitle).ConfigureAwait(false);
ShiftProxies(folder, manifest.Frames, updated.Frames, removed);
ShiftThumbnails(paths, folder, id, manifest.Frames, updated.Frames);
entry = Entry(archive.Id, name, record);
}
var sequence = await RowAsync(revised.Sequence, updated, indexed).ConfigureAwait(false);
await QueueAsync(followUps, archive, sequence, had, CancellationToken.None).ConfigureAwait(false);
return new FrameDeleteResult(entry, sequence);
}
/// <summary>The photo entries of an archive's trash (records whose folder is gone, or of a deletion still under way, are left out).</summary>
internal static IReadOnlyList<TrashEntry> List(Archive archive, CancellationToken cancellationToken)
{
var folder = Directory(new ArchivePaths(archive.RootPath));
if (!System.IO.Directory.Exists(folder)) return [];
var entries = new List<TrashEntry>();
foreach (var path in System.IO.Directory.EnumerateFiles(folder, "*" + RecordExtension))
{
cancellationToken.ThrowIfCancellationRequested();
if (!path.EndsWith(RecordExtension, StringComparison.OrdinalIgnoreCase)) continue;
var name = Path.GetFileNameWithoutExtension(path);
if (!System.IO.Directory.Exists(Path.Combine(folder, name)) || ReadRecord(path) is not { } record) continue;
entries.Add(Entry(archive.Id, name, record));
}
return entries;
}
/// <summary>The record of a photo entry; null when it is not one or cannot be read.</summary>
internal static PhotoTrashRecord? ReadEntry(ArchivePaths paths, string name) =>
IsPhotoEntry(name) ? ReadRecord(Path.Combine(Directory(paths), DiskName(name)) + RecordExtension) : null;
/// <summary>A photo entry as the trash lists it, read from its record now; null when it is not one or cannot be read.</summary>
internal static TrashEntry? ReadListed(ArchivePaths paths, Guid archiveId, string name) =>
ReadEntry(paths, name) is { } record ? Entry(archiveId, DiskName(name), record) : null;
/// <summary>The entry's folder and record on disk.</summary>
internal static (string Folder, string Record) Location(ArchivePaths paths, string name)
{
var folder = Path.Combine(Directory(paths), DiskName(name));
return (folder, folder + RecordExtension);
}
/// <summary>The folder name of an entry: its name without <see cref="EntryPrefix"/>, never a path.</summary>
private static string DiskName(string name) => Path.GetFileName(IsPhotoEntry(name) ? name[EntryPrefix.Length..] : name);
private async Task<Archive> ArchiveOfAsync(Sequence sequence, CancellationToken cancellationToken) =>
await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false) ?? throw new StaleDeletePlanException(sequence.Id);
/// <summary>
/// The files of each frame that goes: its original (with the hash it was archived with, or one computed now for a frame
/// never hashed) under the entry's <c>originals/</c>, and an XMP companion (<c>IMG_0001.xmp</c>, <c>IMG_0001.CR2.xmp</c>)
/// no frame that stays shares. A frame whose original is missing goes without a file: its record stays in the entry,
/// which cannot bring it back, and one never hashed leaves no tombstone either, so a copy of it elsewhere (another PC,
/// a card) is not known to be deleted.
/// </summary>
/// <exception cref="IOException">An original never hashed cannot be read; nothing moved.</exception>
private static async Task<List<TrashedPhoto>> TrashedAsync(SequencePaths folder, List<SidecarFrame> removed, List<SidecarFrame> kept,
CancellationToken cancellationToken)
{
var used = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var claimed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var keptStems = kept.Select(f => Stem(f.File)).ToHashSet(StringComparer.OrdinalIgnoreCase);
var companions = new CompanionIndex(folder);
var photos = new List<TrashedPhoto>(removed.Count);
foreach (var frame in removed)
{
cancellationToken.ThrowIfCancellationRequested();
var files = new List<TrashedFile>();
var original = new FileInfo(folder.File(frame.File));
var sha = frame.Sha256;
if (original.Exists)
{
sha ??= await ContentHash.Sha256Async(original.FullName, null, cancellationToken).ConfigureAwait(false);
files.Add(new TrashedFile(frame.File, Unique(used, "originals/" + Inside(frame.File)), original.Length, sha));
if (!keptStems.Contains(Stem(frame.File)))
{
foreach (var companion in companions.Of(frame.File).Where(claimed.Add))
{
var path = folder.File(companion);
files.Add(new TrashedFile(companion, Unique(used, "originals/" + Inside(companion)), new FileInfo(path).Length,
await ContentHash.Sha256Async(path, null, cancellationToken).ConfigureAwait(false)));
}
}
}
photos.Add(new TrashedPhoto(frame with { Sha256 = sha }, files, null));
}
return photos;
}
/// <summary>
/// The SHA-256 the frames that stay hold, so a duplicate that stays keeps its content out of the tombstones: those of
/// their sidecar, and that of each one never hashed that may hold a deleted photo's content, hashed now (returned by
/// frame, for the sidecar). The work is bounded: only a frame with a deleted photo's size is looked at, and only one
/// whose first and last 64 KiB match that photo's (<see cref="EdgesAsync"/>) is read whole, so a sequence of raw files of
/// one size reads 128 KiB a frame, not every file.
/// </summary>
private static async Task<(HashSet<string> Held, Dictionary<Guid, string> Hashed)> HeldAsync(SequencePaths folder, List<SidecarFrame> kept,
List<TrashedPhoto> photos, CancellationToken cancellationToken)
{
var held = kept.Where(f => f.Sha256 is not null).Select(f => f.Sha256!).ToHashSet(StringComparer.OrdinalIgnoreCase);
var hashed = new Dictionary<Guid, string>();
var deleted = photos.Where(p => p.Files.Count > 0).GroupBy(p => p.Files[0].Size).ToDictionary(g => g.Key, g => g.Select(p => p.Files[0].From).ToList());
var edges = new Dictionary<long, HashSet<string>>();
foreach (var frame in kept.Where(f => f.Sha256 is null && deleted.ContainsKey(f.Size)))
{
cancellationToken.ThrowIfCancellationRequested();
var file = new FileInfo(folder.File(frame.File));
if (!file.Exists || file.Length != frame.Size) continue;
if (!edges.TryGetValue(frame.Size, out var known))
{
// The deleted photos of that size are still in place: the moves come later.
known = new HashSet<string>(StringComparer.Ordinal);
foreach (var from in deleted[frame.Size]) known.Add(await EdgesAsync(folder.File(from), cancellationToken).ConfigureAwait(false));
edges[frame.Size] = known;
}
if (!known.Contains(await EdgesAsync(file.FullName, cancellationToken).ConfigureAwait(false))) continue;
var sha = await ContentHash.Sha256Async(file.FullName, null, cancellationToken).ConfigureAwait(false);
hashed[frame.Id] = sha;
held.Add(sha);
}
return (held, hashed);
}
/// <summary>
/// SHA-256 of a file's first and last 64 KiB (the whole file when smaller): two files of one size whose edges differ
/// differ in content, so only those whose edges match need a full hash.
/// </summary>
private static async Task<string> EdgesAsync(string path, CancellationToken cancellationToken)
{
const int Edge = 64 * 1024;
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, 1,
FileOptions.Asynchronous | FileOptions.RandomAccess);
using var hash = System.Security.Cryptography.IncrementalHash.CreateHash(System.Security.Cryptography.HashAlgorithmName.SHA256);
var buffer = new byte[Edge];
var length = stream.Length;
var read = await stream.ReadAtLeastAsync(buffer, (int)System.Math.Min(Edge, length), throwOnEndOfStream: false, cancellationToken).ConfigureAwait(false);
hash.AppendData(buffer, 0, read);
if (length > Edge)
{
stream.Position = System.Math.Max(Edge, length - Edge);
read = await stream.ReadAtLeastAsync(buffer, (int)(length - stream.Position), throwOnEndOfStream: false, cancellationToken).ConfigureAwait(false);
hash.AppendData(buffer, 0, read);
}
return Convert.ToHexStringLower(hash.GetHashAndReset());
}
/// <summary>
/// The XMP files of a sequence's photo directories, each directory listed once (a deletion of thousands of photos does
/// not list it again for each) and case-insensitively on every system (<c>IMG_0001.XMP</c> too).
/// </summary>
private sealed class CompanionIndex(SequencePaths folder)
{
private static readonly EnumerationOptions Listing = new() { MatchCasing = MatchCasing.CaseInsensitive, AttributesToSkip = 0 };
private readonly Dictionary<string, ILookup<string, string>> _directories = new(StringComparer.Ordinal);
/// <summary>The XMP files beside a photo that name it (<c>stem.xmp</c> or <c>file.xmp</c>), relative to the sequence folder.</summary>
public IEnumerable<string> Of(string file)
{
var prefix = file.Contains('/') ? file[..(file.LastIndexOf('/') + 1)] : string.Empty;
if (!_directories.TryGetValue(prefix, out var named))
{
var directory = Path.GetDirectoryName(folder.File(file))!;
named = (System.IO.Directory.Exists(directory) ? System.IO.Directory.EnumerateFiles(directory, "*.xmp", Listing) : [])
.Select(p => Path.GetFileName(p))
.Where(n => Path.GetExtension(n).Equals(".xmp", StringComparison.OrdinalIgnoreCase))
.ToLookup(n => Path.GetFileNameWithoutExtension(n), StringComparer.OrdinalIgnoreCase);
_directories[prefix] = named;
}
var name = Path.GetFileName(file);
var stem = Path.GetFileNameWithoutExtension(name);
var matches = stem.Equals(name, StringComparison.OrdinalIgnoreCase) ? named[stem] : named[stem].Concat(named[name]);
return matches.Select(n => prefix + n);
}
}
/// <summary>A photo's stem with its folder (<c>originals/IMG_0001</c>): its companions share it.</summary>
private static string Stem(string file)
{
var slash = file.LastIndexOf('/');
var name = file[(slash + 1)..];
var dot = name.IndexOf('.', StringComparison.Ordinal);
return file[..(slash + 1)] + (dot > 0 ? name[..dot] : name);
}
/// <summary>A sequence-relative path without its leading <c>originals/</c>.</summary>
private static string Inside(string file) =>
file.StartsWith(ArchiveLayout.OriginalsFolder + "/", StringComparison.OrdinalIgnoreCase) ? file[(ArchiveLayout.OriginalsFolder.Length + 1)..] : file;
/// <summary><paramref name="path"/>, or with <c>_2</c>, <c>_3</c>… before its extension when another file of the entry has it.</summary>
private static string Unique(HashSet<string> used, string path)
{
var candidate = path;
for (var n = 2; !used.Add(candidate); n++)
candidate = string.Create(CultureInfo.InvariantCulture, $"{Path.ChangeExtension(path, null)}_{n}{Path.GetExtension(path)}");
return candidate;
}
/// <summary>
/// The tombstones after a deletion: those of before, and one per SHA-256 of the photos that went (hashed as they went
/// when the sidecar had none) that no frame staying holds (<paramref name="held"/>: a duplicate that stays keeps the
/// content in the sequence).
/// </summary>
private static List<RemovedPhoto>? WithTombstones(IReadOnlyList<RemovedPhoto>? before, List<TrashedPhoto> photos, HashSet<string> held, DateTimeOffset at)
{
var tombstones = new Dictionary<string, RemovedPhoto>(StringComparer.OrdinalIgnoreCase);
foreach (var tombstone in before ?? []) tombstones[tombstone.Sha256] = tombstone;
foreach (var sha in photos.Select(p => p.Frame.Sha256).OfType<string>())
{
if (!held.Contains(sha)) tombstones[sha] = new RemovedPhoto { Sha256 = sha.ToLowerInvariant(), Reason = RemovalReason.Deleted, At = at };
}
return tombstones.Count == 0 ? null : [.. tombstones.Values];
}
/// <summary>Puts back the files of a deletion that failed half-way, and removes its record, folder and journal.</summary>
private static void Undo(ArchivePaths paths, SequencePaths folder, List<FrameRemovalMove> done, string recordPath, string entryFolder)
{
foreach (var move in done)
{
try
{
File.Move(paths.FromRelative(move.To), folder.File(move.From), overwrite: false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Error("archive", $"{move.To} could not move back to {folder.ArchiveRelative(move.From)}; the journal puts it back later", ex);
return;
}
}
File.Delete(FrameRemovalJournal.PendingRecord(recordPath));
FrameRemovalJournal.RemoveEmpty(entryFolder);
FrameRemovalJournal.Delete(folder);
}
/// <summary>
/// Lists a deletion whose sidecar is written: its record takes its own name and the journal goes. A failure (logged)
/// keeps the journal, and the next writer of the sequence lists the entry (<see cref="FrameRemovalJournal.Recover"/>).
/// </summary>
private static void Publish(SequencePaths folder, string recordPath)
{
try
{
FrameRemovalJournal.Publish(recordPath);
FrameRemovalJournal.Delete(folder);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"Trash record {recordPath} keeps its pending name; the next writer of {folder.RelativeFolder} lists it", ex);
}
}
/// <summary>
/// Indexes a sidecar this class wrote, to the end whatever the caller cancels. False (logged) when the index cannot
/// follow: the files have moved and the sidecar says so, and the folder's stamps stay unrecorded, so the next scan
/// resyncs the sequence from it.
/// </summary>
private async Task<bool> IndexAsync(Archive archive, SequencePaths folder, SequenceManifest manifest, bool photosChanged, string title)
{
try
{
await _indexer.SyncAsync(archive, folder, manifest, null, Uncovered, photosChanged, CancellationToken.None).ConfigureAwait(false);
return true;
}
catch (Exception ex) when (ex is DatabaseException or IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"{title}: the index did not follow the photos moved; the next scan resyncs it", ex);
return false;
}
}
/// <summary>The sequence's row now; when the index did not follow (or cannot be read), the row as the sidecar has it.</summary>
private async Task<Sequence> RowAsync(Sequence before, SequenceManifest manifest, bool indexed)
{
var fallback = before with { FramesVersion = manifest.Versions.Frames, FrameCount = manifest.Frames.Count };
if (!indexed) return fallback;
try
{
return await _db.Sequences.GetAsync(before.Id, CancellationToken.None).ConfigureAwait(false) ?? fallback;
}
catch (DatabaseException ex)
{
Log.Warning("archive", $"{before.DisplayTitle}: its row could not be read again", ex);
return fallback;
}
}
/// <summary>
/// Renames the proxies of the frames whose index changed (BRIEF §8.5: proxies are named by frame index) so they stay
/// theirs, and deletes those of the frames removed: the passes queued afterwards reuse them instead of making the
/// sequence's proxies again. Proxies are regenerable and carry their frame's capture time, so one left in the wrong
/// place (a failure here, logged) is made again.
/// </summary>
internal static void ShiftProxies(SequencePaths folder, IReadOnlyList<SidecarFrame> before, IReadOnlyList<SidecarFrame> after,
IReadOnlyList<SidecarFrame> removed)
{
if (!System.IO.Directory.Exists(folder.Proxies)) return;
try
{
foreach (var frame in removed)
{
var stale = folder.Proxy(frame.I);
if (File.Exists(stale)) File.Delete(stale);
}
var now = after.ToDictionary(f => f.Id, f => f.I);
var moves = before.Where(f => now.TryGetValue(f.Id, out var to) && to != f.I).Select(f => (From: f.I, To: now[f.Id])).ToList();
if (moves.Count == 0) return;
// Downwards from the lowest when frames left, upwards from the highest when frames came: each target is free by then.
var ordered = moves[0].To < moves[0].From ? moves.OrderBy(m => m.From) : moves.OrderByDescending(m => m.From);
foreach (var (from, to) in ordered)
{
var source = folder.Proxy(from);
var target = folder.Proxy(to);
if (File.Exists(source)) File.Move(source, target, overwrite: true);
else if (File.Exists(target)) File.Delete(target);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"Proxies of {folder.RelativeFolder} did not follow their frames; the proxy pass makes them again", ex);
}
}
/// <summary>
/// Moves the thumbnails of the frames whose index changed to their new index in <c>thumbs.pack</c> (BRIEF §8.5: the pack
/// is keyed by frame index) and drops those of the frames removed, as <see cref="ShiftProxies"/> does for proxies, so the
/// thumbnail pass queued afterwards reuses them instead of drawing the rest of the sequence again. Only the pack's index
/// is rewritten. A thumbnail writer holding the pack meanwhile (its lease) leaves it as it is, and so does a failure
/// (logged): each thumbnail carries its original's fingerprint, so one in the wrong place is drawn again.
/// </summary>
private void ShiftThumbnails(ArchivePaths paths, SequencePaths folder, Guid sequenceId, IReadOnlyList<SidecarFrame> before,
IReadOnlyList<SidecarFrame> after)
{
if (!File.Exists(folder.ThumbsPackPath)) return;
var now = after.ToDictionary(f => f.Id, f => f.I);
var indices = before.Where(f => now.ContainsKey(f.Id)).ToDictionary(f => f.I, f => now[f.Id]);
try
{
using var lease = LeaseFile.TryAcquire(paths.LocksDirectory, $"thumbs-{sequenceId:N}", _writer.Options.Owner, _writer.Options.LeaseDuration);
if (lease is null)
{
Log.Info("archive", $"Thumbnails of {folder.RelativeFolder} are being written; the thumbnail pass draws those that moved again");
return;
}
using var pack = ThumbPackWriter.Open(folder.ThumbsPackPath);
pack.Rekey(indices);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"Thumbnails of {folder.RelativeFolder} did not follow their frames; the thumbnail pass draws them again", ex);
}
}
/// <summary>Queues what the frames need again (see <see cref="DeleteAsync"/>), as an orphans fix does; an index that cannot take them is logged.</summary>
private async Task QueueAsync(JobEngine? followUps, Archive archive, Sequence sequence, SequenceStatus had, CancellationToken cancellationToken)
{
if (followUps is null) return;
var label = sequence.DisplayTitle;
List<ArchiveJobRequest> requests = [ProcessingJobs.LightAnalysis([sequence.Id], label)];
if ((had & SequenceStatus.AnalyzedDeep) != 0) requests.Add(ProcessingJobs.DeepAnalysis([sequence.Id], label) with { Priority = JobPriority.Background });
var images = _writer.Options.ImagesAfterScan;
if (images || (had & SequenceStatus.ThumbsBuilt) != 0) requests.Add(ArchiveJobs.Thumbnails([sequence.Id], label));
if ((images || (had & SequenceStatus.ProxiesBuilt) != 0) && archive.ProxyLongEdge != ProxyPolicy.Disabled)
requests.Add(ArchiveJobs.Proxies([sequence.Id], label));
try
{
foreach (var request in requests)
{
if (!followUps.Runs(request.Kind) || await _db.Jobs.IsQueuedAsync(request.Kind, sequence.Id, cancellationToken).ConfigureAwait(false)) continue;
await followUps.EnqueueAsync(request, cancellationToken: cancellationToken).ConfigureAwait(false);
}
}
catch (DatabaseException ex)
{
Log.Warning("archive", $"{label}: the passes its frames need again were not queued; the next scan queues them", ex);
}
}
/// <summary>Moves a file, making its folder first; never over another file.</summary>
private static void MoveFile(string from, string to)
{
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(to)!);
File.Move(from, to, overwrite: false);
}
/// <summary>The sequence id and the time, with a number when an entry of that second exists already (or is being made).</summary>
private static string EntryName(string trash, Guid sequenceId)
{
var stamp = DateTime.UtcNow.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture);
var name = $"{sequenceId:N}-{stamp}";
for (var n = 2; Taken(Path.Combine(trash, name)); n++)
name = string.Create(CultureInfo.InvariantCulture, $"{sequenceId:N}-{stamp}-{n}");
return name;
static bool Taken(string entry) =>
System.IO.Directory.Exists(entry) || File.Exists(entry + RecordExtension) || File.Exists(FrameRemovalJournal.PendingRecord(entry + RecordExtension));
}
private static TrashEntry Entry(Guid archiveId, string folderName, PhotoTrashRecord record) =>
new(archiveId, EntryPrefix + folderName, record.SequenceId, record.SequenceTitle, record.SequenceFolder, record.Photos.Count,
record.Photos.Sum(p => p.Files.Count) + (record.Leftovers?.Count ?? 0), record.Bytes, record.DeletedAt, record.DeletedBy, record.Kind);
private static PhotoTrashRecord? ReadRecord(string path)
{
try
{
return File.Exists(path) ? JsonSerializer.Deserialize(File.ReadAllText(path), TrashJson.Default.PhotoTrashRecord) : null;
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"Trash record {path} is unreadable", ex);
return null;
}
}
}
/// <summary>
/// What the trash keeps next to deleted photos (owner review 2, R6): the frame records, where each file was and is, the
/// sequence they came from. <see cref="TrashKind.Replaced"/> entries (a later conversion) name each photo's replacement.
/// </summary>
/// <param name="Leftovers">Files of the entry whose photo is back in a sequence without them (a companion whose name was
/// taken there): counted and erased with the entry, never restored.</param>
internal sealed record PhotoTrashRecord(TrashKind Kind, Guid SequenceId, string SequenceTitle, string SequenceFolder, IReadOnlyList<TrashedPhoto> Photos,
long Bytes, DateTimeOffset DeletedAt, string? DeletedBy, IReadOnlyList<TrashedFile>? Leftovers = null);
/// <summary>One photo of a photo entry: its frame record, its files (the original first) and, when replaced, the replacement's SHA-256.</summary>
internal sealed record TrashedPhoto(SidecarFrame Frame, IReadOnlyList<TrashedFile> Files, string? Replacement);
/// <param name="From">Where the file was, relative to the sequence folder.</param>
/// <param name="Path">Where it is, relative to the entry's folder.</param>
/// <param name="Sha256">Its SHA-256 when it left the sequence; a restore re-hashes the file against it.</param>
internal sealed record TrashedFile(string From, string Path, long Size, string? Sha256);
+16 -1
View File
@@ -5,6 +5,10 @@ namespace Chronos.Data.Archiving;
/// 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>
/// <param name="RefuseRemoved">Content the target sequence tombstoned (a photo deleted from it, none of its frames holding
/// that content) is refused with <see cref="PhotoRemovedException"/>, checked under the sequence's lease with the commit, so
/// no deletion lands in between: an upload that does not ask to bring the photo back. Otherwise filing it drops the
/// tombstone (a card imported again, a sync download, an explicit upload again).</param>
public sealed record IngestRequest(
Guid ArchiveId,
Guid? SequenceId,
@@ -15,7 +19,18 @@ public sealed record IngestRequest(
long Size,
string Sha256,
DateTime? ClientCapturedAt,
Guid? UserId);
Guid? UserId,
bool RefuseRemoved = false);
/// <summary>
/// The target sequence tombstoned the content of an <see cref="IngestRequest"/> that refuses it
/// (<see cref="IngestRequest.RefuseRemoved"/>): the photo was deleted from it. Nothing was filed; the staged file stays.
/// </summary>
public sealed class PhotoRemovedException(Guid sequenceId, string sha256)
: InvalidOperationException($"Sequence {sequenceId} tombstoned {sha256}: the photo was deleted from it and is not filed again.")
{
public Guid SequenceId { get; } = sequenceId;
}
/// <summary>
/// The committed frame; <see cref="Duplicate"/> when an intact frame of the sequence already held that SHA-256 (the file
@@ -31,6 +31,15 @@ public sealed record BackupParameters(int Keep);
/// </summary>
public sealed record CleanupParameters(IReadOnlyList<string> Steps, int OlderThanDays);
/// <summary>
/// <see cref="JobKind.EmptyTrash"/>: target = the archive; the entries of the confirmed plan, each with its own fingerprint
/// (<see cref="SequenceTrash.EntryFingerprint"/>), and the plan's fingerprint (<see cref="TrashEmptyPlan.Fingerprint"/>).
/// </summary>
public sealed record EmptyTrashParameters(IReadOnlyList<EmptyTrashItem> Entries, string Fingerprint);
/// <summary>One entry of a confirmed emptying: its name and fingerprint when it was planned.</summary>
public sealed record EmptyTrashItem(string Name, string Fingerprint);
/// <summary>A job ready to enqueue.</summary>
public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets, string? Label, string? ParametersJson, JobPriority Priority);
@@ -42,6 +51,7 @@ public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets
[JsonSerializable(typeof(ImportJobParameters))]
[JsonSerializable(typeof(BackupParameters))]
[JsonSerializable(typeof(CleanupParameters))]
[JsonSerializable(typeof(EmptyTrashParameters))]
[JsonSerializable(typeof(CardProfile))]
internal sealed partial class ArchiveJobJson : JsonSerializerContext
{
@@ -0,0 +1,37 @@
using System.Globalization;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Housekeeping;
using Chronos.Data.Jobs;
namespace Chronos.Data.Archiving.Jobs;
/// <summary>
/// <see cref="JobKind.EmptyTrash"/> (owner review 2, R6): erases exactly the entries of a confirmed plan
/// (<see cref="EmptyTrashParameters"/>) and fails, erasing nothing, when the trash no longer matches the plan's
/// fingerprint (<see cref="StaleTrashPlanException"/>). Checkpoint: <c>done:&lt;n&gt;</c>, the entries done; a resumed job
/// checks each remaining entry against its own fingerprint. Entries kept (a replacement that no longer matches, an entry
/// changed since) are logged and fail the job at the end, after the others are erased.
/// </summary>
internal sealed class EmptyTrashJobHandler(ChronosDatabase db, SequenceTrash trash) : IJobHandler
{
private const string Prefix = "done:";
public JobKind Kind => JobKind.EmptyTrash;
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.EmptyTrashParameters, new EmptyTrashParameters([], string.Empty));
var start = context.Checkpoint is { } checkpoint && checkpoint.StartsWith(Prefix, StringComparison.Ordinal)
&& int.TryParse(checkpoint.AsSpan(Prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out var done)
? Math.Min(done, parameters.Entries.Count)
: 0;
await context.ReportAsync(start, parameters.Entries.Count).ConfigureAwait(false);
var result = await trash.EmptyAsync(archive, parameters, start,
(n, total) => context.CheckpointAsync(Prefix + n.ToString(CultureInfo.InvariantCulture), n, total), context.Cancellation).ConfigureAwait(false);
context.Log(Loc.L("Archive.Log.TrashEmptied", result.Erased, CleanupSteps.Megabytes(result.Bytes)));
foreach (var title in result.Refused) context.Log(Loc.L("Archive.Log.TrashKept", title));
if (result.Refused.Count > 0) throw new InvalidOperationException(Loc.Plural("Archive.Error.TrashKept", result.Refused.Count));
}
}
+34 -4
View File
@@ -12,15 +12,19 @@ namespace Chronos.Data.Archiving;
/// 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
/// order (what editors, renders and the API read), so the old order comes from the index rows. An insertion moves them
/// by position; when an indexed frame is no longer in the sidecar (photos deleted, owner review 2, R6) they are translated
/// by photo, those on the photos that went waiting as pending frames. 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>Index frames read at once when positions are translated by photo.</summary>
private const int PageSize = 1000;
/// <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
@@ -45,9 +49,35 @@ internal static class ProjectPositions
}
if (index != row.Index) moves[row.Index] = index;
}
return Placed(project, moves is null ? null : ProjectSettings.MoveFramePositions(project, moves), manifest);
if (moves is null) return await RemovedAsync(db, indexed.Id, project, manifest, cancellationToken).ConfigureAwait(false);
return Placed(project, ProjectSettings.MoveFramePositions(project, moves), manifest);
}
/// <summary>
/// Indexed frames are no longer in the sidecar (photos deleted into the trash, here or by another process sharing the
/// archive, owner review 2, R6): the positions are translated by photo from the index's frames to the sidecar's
/// (<see cref="ProjectSettings.TranslateFramePositions"/>), so those on the photos that went wait as pending frames
/// and take their place again when the photos come back (a restore), and the others follow their photos.
/// </summary>
private static async Task<PositionMove?> RemovedAsync(ChronosRepositories db, Guid sequenceId, string project, SequenceManifest manifest,
CancellationToken cancellationToken)
{
var before = new List<(int, FramePhoto)>();
for (var after = -1; ;)
{
var page = await db.Frames.ListBySequenceAsync(sequenceId, after, PageSize, cancellationToken).ConfigureAwait(false);
before.AddRange(page.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
if (page.Count < PageSize) break;
after = page[^1].Index;
}
var to = new FramePhotos(manifest.Frames.Select(f => (f.I, new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
var translated = ProjectSettings.TranslateFramePositions(project, new FramePhotos(before), to);
if (translated is null) return null;
var hero = HeroOf(project) is null && HeroOf(translated) is { } index ? manifest.Frames.FirstOrDefault(f => f.I == index)?.Id : null;
return new PositionMove(project, translated, hero);
}
/// <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.
@@ -41,6 +41,22 @@ internal static class SequenceMapping
public static List<Frame> ToFrames(SequenceManifest manifest, SequencePaths sequence) =>
manifest.Frames.Select(f => ToFrame(f, manifest.Id, sequence)).ToList();
/// <summary>
/// The sidecar's tombstones as index rows (owner review 2, R6), without those whose content a frame of the sidecar
/// holds: that photo is in the sequence again (adopted back by a scan, say), and sync offers it like any other.
/// </summary>
public static List<FrameRemoval> ToRemovals(SequenceManifest manifest)
{
if (manifest.Removed is not { Count: > 0 } removed) return [];
var held = manifest.Frames.Where(f => f.Sha256 is not null).Select(f => f.Sha256!).ToHashSet(StringComparer.OrdinalIgnoreCase);
return removed.Where(r => !string.IsNullOrEmpty(r.Sha256) && !held.Contains(r.Sha256))
.Select(r => new FrameRemoval(manifest.Id, r.Sha256.ToLowerInvariant(), r.Replacement?.ToLowerInvariant(), r.Reason, r.At)).ToList();
}
/// <summary>Index rows of tombstones as a sidecar carries them: a sidecar rebuilt from the photos takes them back.</summary>
public static List<RemovedPhoto> ToTombstones(IEnumerable<FrameRemoval> removals) =>
removals.Select(r => new RemovedPhoto { Sha256 = r.Sha256, Replacement = r.ReplacementSha256, Reason = r.Reason, At = r.RemovedAt }).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)
@@ -0,0 +1,227 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving.Jobs;
namespace Chronos.Data.Archiving;
/// <summary>
/// The dry run of emptying an archive's trash (owner review 2, R6; BRIEF §0.2 rule 8): the entries that would be erased,
/// with the files and bytes their folders hold now, and a fingerprint of exactly those entries. Erasing
/// (<see cref="JobKind.EmptyTrash"/>) refuses a plan whose fingerprint no longer matches the trash.
/// </summary>
/// <param name="Unknown">Names asked for that the trash does not hold.</param>
public sealed record TrashEmptyPlan(Guid ArchiveId, IReadOnlyList<TrashEntry> Entries, long Bytes, string Fingerprint, IReadOnlyList<string> Unknown)
{
public int Files => Entries.Sum(e => e.Files);
public int Photos => Entries.Sum(e => e.Frames);
}
/// <summary>What an emptying erased, and the entries it kept (a replacement that no longer matches, an entry changed since the plan).</summary>
public sealed record TrashEmptyResult(int Erased, long Bytes, IReadOnlyList<string> Refused);
/// <summary>The trash changed after the emptying was planned (an entry came, went or changed); nothing was erased.</summary>
public sealed class StaleTrashPlanException() : InvalidOperationException(Loc.L("Archive.Error.TrashChanged"));
public sealed partial class SequenceTrash
{
/// <summary>Folder inside the trash that entries move into before they are erased, so a listing never sees half an entry.</summary>
private const string ErasingFolder = ".erasing";
/// <summary>The lease that keeps a restore and an erasing of one entry apart.</summary>
internal static string EntryLease(string name) => "trash-" + name;
/// <summary>
/// The dry run of emptying the trash: <paramref name="names"/> of the entries to erase (null: every entry), each
/// measured on disk, and the plan's fingerprint (<see cref="Fingerprint"/>). Reads only.
/// </summary>
public async Task<TrashEmptyPlan> PlanEmptyAsync(Archive archive, IReadOnlyList<string>? names = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(archive);
var paths = new ArchivePaths(archive.RootPath);
var listed = await ListAsync(archive, cancellationToken).ConfigureAwait(false);
var wanted = names?.ToHashSet(StringComparer.Ordinal);
var chosen = wanted is null ? listed : [.. listed.Where(e => wanted.Contains(e.Name))];
var measured = await Task.Run(() => chosen.Select(e =>
{
var (folder, _) = Location(paths, e);
var (files, bytes) = Directory.Exists(folder) ? Measure(folder, cancellationToken) : (0, 0L);
return e with { Files = files, Bytes = bytes };
}).ToList(), cancellationToken).ConfigureAwait(false);
var unknown = names?.Where(n => !listed.Any(e => e.Name == n)).Distinct(StringComparer.Ordinal).ToList() ?? [];
return new TrashEmptyPlan(archive.Id, measured, measured.Sum(e => e.Bytes), Fingerprint(measured), unknown);
}
/// <summary>
/// Fingerprint of a set of entries: SHA-256 of each one's <see cref="EntryFingerprint"/> in name order. The same
/// entries with the same files on disk give the same fingerprint whatever order they were listed in.
/// </summary>
public static string Fingerprint(IEnumerable<TrashEntry> entries)
{
ArgumentNullException.ThrowIfNull(entries);
var text = new StringBuilder();
foreach (var entry in entries.OrderBy(e => e.Name, StringComparer.Ordinal)) text.Append(EntryFingerprint(entry)).Append('\n');
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString())));
}
/// <summary>What identifies one entry as planned: its kind, name, files and bytes on disk, and when it was deleted.</summary>
public static string EntryFingerprint(TrashEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);
return string.Create(CultureInfo.InvariantCulture, $"{entry.Kind}|{entry.Name}|{entry.Files}|{entry.Bytes}|{entry.DeletedAt.UtcTicks}");
}
/// <summary>
/// Erases the entries of <paramref name="parameters"/> from <paramref name="start"/> on, one at a time under its lease,
/// each moved aside whole and then deleted (a listing never shows half an entry). From the start, the trash must still
/// hold exactly the planned entries (<see cref="EmptyTrashParameters.Fingerprint"/>), else nothing is erased; a run
/// resumed after a stop checks each remaining entry against its own fingerprint, keeps one that changed and skips one
/// that is gone, and each entry is checked against its fingerprint once more under its lease, just before it goes. A
/// <see cref="TrashKind.Replaced"/> entry is erased only while every replacement still matches its
/// SHA-256 in the sequence (re-hashed now); otherwise it is kept. Leftovers of an interrupted erase are deleted first.
/// </summary>
/// <param name="progress">Entries done so far (the resume point) and their number.</param>
/// <exception cref="StaleTrashPlanException">The trash no longer holds exactly the planned entries; nothing was erased.</exception>
internal async Task<TrashEmptyResult> EmptyAsync(Archive archive, EmptyTrashParameters parameters, int start, Func<int, int, ValueTask> progress,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(archive);
ArgumentNullException.ThrowIfNull(parameters);
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
SweepErasing(paths);
var items = parameters.Entries;
var current = await PlanEmptyAsync(archive, [.. items.Skip(start).Select(i => i.Name)], cancellationToken).ConfigureAwait(false);
if (start == 0 && (current.Fingerprint != parameters.Fingerprint || current.Unknown.Count > 0)) throw new StaleTrashPlanException();
var refused = new List<string>();
int erased = 0;
long bytes = 0;
for (var i = start; i < items.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
var item = items[i];
if (current.Entries.FirstOrDefault(e => e.Name == item.Name) is { } entry)
{
if (EntryFingerprint(entry) != item.Fingerprint)
{
refused.Add(entry.Title);
Log.Warning("archive", $"Trash entry {entry.Name} changed since the emptying was planned; it is kept");
}
else if (await EraseAsync(paths, entry, item.Fingerprint, cancellationToken).ConfigureAwait(false))
{
erased++;
bytes += entry.Bytes;
}
else
{
refused.Add(entry.Title);
}
}
await progress(i + 1, items.Count).ConfigureAwait(false);
}
return new TrashEmptyResult(erased, bytes, refused);
}
/// <summary>
/// Erases one entry under its lease, once its record read and its folder measured again under it still give the
/// planned <paramref name="fingerprint"/> (another host sharing the archive may have restored the entry and deleted the
/// same sequence again since); false (logged) when it changed, or a replaced entry's replacements no longer match.
/// </summary>
private async Task<bool> EraseAsync(ArchivePaths paths, TrashEntry entry, string fingerprint, CancellationToken cancellationToken)
{
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, EntryLease(entry.Name), _writer.Options.Owner, _writer.Options.LeaseWait,
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
{
var (folder, record) = Location(paths, entry);
if (!Directory.Exists(folder) || !File.Exists(record)) return false;
if (Reread(paths, entry, cancellationToken) is not { } now || EntryFingerprint(now) != fingerprint)
{
Log.Warning("archive", $"Trash entry {entry.Name} changed since the emptying was planned; it is kept");
return false;
}
if (entry.Kind == TrashKind.Replaced && !await ReplacementsHoldAsync(paths, entry, cancellationToken).ConfigureAwait(false))
{
Log.Warning("archive", $"Trash entry {entry.Name} is kept: a replacement of its originals no longer matches");
return false;
}
var aside = Path.Combine(TrashDirectory(paths), ErasingFolder, Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(Path.GetDirectoryName(aside)!);
Directory.Move(folder, aside);
File.Delete(record);
Erase(aside);
Log.Info("archive", $"Trash entry {entry.Name} ({entry.Title}, {entry.Files} files, {entry.Bytes} bytes) erased");
return true;
}
}
/// <summary>
/// Whether every photo of a replaced entry still has its replacement in the sequence: a frame holding the replacement's
/// SHA-256 whose file hashes to it now. The originals are erased only then (a later phase's conversion).
/// </summary>
private async Task<bool> ReplacementsHoldAsync(ArchivePaths paths, TrashEntry entry, CancellationToken cancellationToken)
{
if (FrameTrash.ReadEntry(paths, entry.Name) is not { } record) return false;
foreach (var photo in record.Photos)
{
if (photo.Replacement is not { } replacement) return false;
var holders = (await _db.Frames.FindBySha256Async(replacement.ToLowerInvariant(), cancellationToken).ConfigureAwait(false))
.Where(f => f.SequenceId == record.SequenceId).ToList();
var verified = false;
foreach (var frame in holders)
{
var file = paths.FromRelative(frame.RelativePath);
if (!File.Exists(file)) continue;
if (string.Equals(await ContentHash.Sha256Async(file, null, cancellationToken).ConfigureAwait(false), replacement, StringComparison.OrdinalIgnoreCase))
{
verified = true;
break;
}
}
if (!verified) return false;
}
return true;
}
/// <summary>An entry as the trash lists it, from its record and folder as they are now; null when its record cannot be read.</summary>
private static TrashEntry? Reread(ArchivePaths paths, TrashEntry entry, CancellationToken cancellationToken)
{
var (folder, recordPath) = Location(paths, entry);
var now = FrameTrash.IsPhotoEntry(entry.Name)
? FrameTrash.ReadListed(paths, entry.ArchiveId, entry.Name)
: ReadRecord(recordPath) is { } record ? Entry(entry.ArchiveId, Path.GetFileName(entry.Name), record) : null;
if (now is null) return null;
var (files, bytes) = Measure(folder, cancellationToken);
return now with { Files = files, Bytes = bytes };
}
/// <summary>The folder and record of an entry of either kind.</summary>
private static (string Folder, string Record) Location(ArchivePaths paths, TrashEntry entry)
{
if (FrameTrash.IsPhotoEntry(entry.Name)) return FrameTrash.Location(paths, entry.Name);
var folder = Path.Combine(TrashDirectory(paths), Path.GetFileName(entry.Name));
return (folder, folder + RecordExtension);
}
/// <summary>Deletes what an interrupted erase left aside: those entries were confirmed and had left the listing already.</summary>
private static void SweepErasing(ArchivePaths paths)
{
var erasing = Path.Combine(TrashDirectory(paths), ErasingFolder);
if (!Directory.Exists(erasing)) return;
foreach (var leftover in Directory.EnumerateDirectories(erasing)) Erase(leftover);
}
/// <summary>Deletes a folder and everything in it, read-only files included; one that is gone already is fine.</summary>
internal static void Erase(string folder)
{
if (!Directory.Exists(folder)) return;
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", new EnumerationOptions { RecurseSubdirectories = true, AttributesToSkip = 0 }))
{
if ((file.Attributes & FileAttributes.ReadOnly) != 0) file.Attributes &= ~FileAttributes.ReadOnly;
}
Directory.Delete(folder, recursive: true);
}
}
+72 -15
View File
@@ -48,11 +48,27 @@ public sealed record DeletePlan(IReadOnlyList<DeleteStep> Steps, IReadOnlyList<B
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>
/// <summary>What a trash entry holds (owner review 2, R6).</summary>
public enum TrashKind
{
/// <summary>A whole sequence folder (<see cref="SequenceTrash"/>).</summary>
Sequence,
/// <summary>Photos deleted from a sequence (<see cref="FrameTrash"/>).</summary>
Photos,
/// <summary>Originals a conversion replaced (a later phase): erased only while their replacements still match.</summary>
Replaced,
}
/// <summary>An entry of an archive's trash, as <see cref="SequenceTrash.ListAsync"/> lists it: a deleted sequence or deleted photos.</summary>
/// <param name="Name">The entry's name: the folder name inside the trash for a sequence, <c>photos-</c> and the folder name for
/// photos; pass it to <see cref="ArchiveService.RestoreEntryAsync"/>.</param>
/// <param name="Title">The sequence's title (the one the photos came from).</param>
/// <param name="Folder">Archive-relative folder the sequence came from (and returns to when it is free).</param>
/// <param name="Frames">Photos the entry holds.</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);
DateTimeOffset DeletedAt, string? DeletedBy, TrashKind Kind = TrashKind.Sequence);
/// <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"))
@@ -66,6 +82,12 @@ public sealed class SequenceInLibraryException(Guid sequenceId, string title) :
public Guid SequenceId { get; } = sequenceId;
}
/// <summary>
/// No file of a photo entry matches its record any more (each one re-hashed); the entry stays as it is and nothing moved.
/// A restore's <see cref="InvalidDataException"/> is about a sidecar instead (damaged, or another sequence's).
/// </summary>
public sealed class TrashMismatchException() : IOException(Loc.L("Archive.Error.TrashMismatch"));
/// <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
@@ -75,7 +97,7 @@ public sealed class SequenceInLibraryException(Guid sequenceId, string title) :
/// 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
public sealed partial class SequenceTrash
{
/// <summary>Folder of the trash inside the archive's <c>.chronos</c>.</summary>
public const string FolderName = "trash";
@@ -153,6 +175,10 @@ public sealed class SequenceTrash
/// <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>
/// <exception cref="LeaseUnavailableException">A sequence, or the trash entry of a restore into it a crash interrupted, is
/// busy; sequences before it are in the trash.</exception>
/// <exception cref="InvalidDataException">The sidecar of a sequence with an interrupted journal is damaged; 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)
{
@@ -168,7 +194,10 @@ public sealed class SequenceTrash
return entries;
}
/// <summary>The sequences in an archive's trash, newest first; records whose folder is gone are left out.</summary>
/// <summary>
/// The entries of an archive's trash, newest first: deleted sequences (<c>trash/*.json</c>) and deleted photos
/// (<c>trash/photos/*.json</c>); records whose folder is gone are left out.
/// </summary>
public async Task<IReadOnlyList<TrashEntry>> ListAsync(Archive archive, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(archive);
@@ -184,7 +213,8 @@ public sealed class SequenceTrash
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();
entries.AddRange(FrameTrash.List(archive, cancellationToken));
return entries.OrderByDescending(e => e.DeletedAt).ThenBy(e => e.Name, StringComparer.Ordinal).ToList();
}, cancellationToken).ConfigureAwait(false);
}
@@ -215,14 +245,18 @@ public sealed class SequenceTrash
.ToHashSet(StringComparer.OrdinalIgnoreCase);
var folder = FreeFolder(paths, record.Sequence.Folder, locations);
var sequence = paths.Sequence(folder);
// The entry's lease keeps an emptying of the trash out meanwhile.
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, EntryLease(Path.GetFileName(name)), _writer.Options.Owner, _writer.Options.LeaseWait,
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
await using (await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false))
{
if (!Directory.Exists(source)) throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}.");
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);
var manifest = File.Exists(sequence.ManifestPath) ? SequenceWriter.ReadLocked(sequence, id) : Adopt(sequence, record, 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);
}
@@ -242,10 +276,12 @@ public sealed class SequenceTrash
/// <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.
/// sequence keeps its id, and the title, tags, rating, notes and tombstones of the record go into it so sidecar and
/// index agree, and a photo deleted before stays deleted.
/// </summary>
private SequenceManifest Adopt(SequencePaths sequence, Sequence kept, CancellationToken cancellationToken)
private SequenceManifest Adopt(SequencePaths sequence, TrashRecord record, CancellationToken cancellationToken)
{
var kept = record.Sequence;
var built = SequenceAdopter.Build(kept.Id, sequence, _writer.Options.Owner, cancellationToken);
var manifest = built with
{
@@ -254,6 +290,7 @@ public sealed class SequenceTrash
Rating = kept.Rating,
Notes = kept.Notes,
Versions = built.Versions with { Settings = System.Math.Max(built.Versions.Settings, kept.SettingsVersion) },
Removed = record.Removed is { Count: > 0 } removed ? removed : null,
};
Directory.CreateDirectory(sequence.MetaDirectory);
ManifestStore.WriteSequence(sequence.ManifestPath, manifest);
@@ -269,6 +306,7 @@ public sealed class SequenceTrash
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);
await tx.FrameRemovals.SyncSequenceAsync(deleted.Id, SequenceMapping.ToRemovals(manifest), 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)
{
@@ -335,12 +373,25 @@ public sealed class SequenceTrash
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);
// A photo deletion, a restore from the trash or an ingest a crash interrupted is settled first, as any writer does
// (SequenceWriter.ReadLocked): neither its journal nor the files it moved travel into this entry, where emptying it
// would erase them while their own entry still lists them. A restore whose entry is busy keeps the folder here.
var (files, bytes) = (step.Files, step.Bytes);
if (File.Exists(folder.ManifestPath) && (File.Exists(folder.RemovalJournalPath) || File.Exists(folder.RestoreJournalPath)
|| File.Exists(folder.IngestJournalPath)))
{
SequenceWriter.ReadLocked(folder, sequence.Id);
FrameTrash.EnsureSettled(folder);
// Files came back into the folder, or left it: the record counts what moves.
(files, bytes) = Measure(folder.Folder, cancellationToken);
}
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);
var tombstones = await _db.FrameRemovals.ListBySequenceAsync(sequence.Id, cancellationToken).ConfigureAwait(false);
var record = new TrashRecord(row, await _db.Renders.ListBySequenceAsync(sequence.Id, cancellationToken).ConfigureAwait(false), files,
bytes, DateTimeOffset.UtcNow, deletedBy, tombstones.Count > 0 ? SequenceMapping.ToTombstones(tombstones) : null);
cancellationToken.ThrowIfCancellationRequested();
// The record first: a crash before the move leaves a record without a folder, which the listing ignores.
var recordPath = target + RecordExtension;
@@ -366,7 +417,7 @@ public sealed class SequenceTrash
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)");
Log.Info("archive", $"{row.DisplayTitle} moved to the trash: {row.Folder} → {name} ({files} files, {bytes} bytes)");
return Entry(archive.Id, name, record);
}
}
@@ -426,7 +477,7 @@ public sealed class SequenceTrash
/// 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)
internal async Task<IReadOnlySet<Guid>> BusyAsync(CancellationToken cancellationToken)
{
var busy = new HashSet<Guid>();
foreach (var state in new[] { JobState.Running, JobState.Paused })
@@ -545,10 +596,16 @@ public sealed class SequenceTrash
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);
/// <summary>
/// What the trash keeps next to a deleted folder: the index row and renders the sidecar does not carry, and the
/// sequence's tombstones, which a sidecar rebuilt from the photos on restore takes back.
/// </summary>
internal sealed record TrashRecord(Sequence Sequence, IReadOnlyList<Render> Renders, int Files, long Bytes, DateTimeOffset DeletedAt, string? DeletedBy,
IReadOnlyList<RemovedPhoto>? Removed = null);
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
UseStringEnumConverter = true, IgnoreReadOnlyProperties = true)]
[JsonSerializable(typeof(TrashRecord))]
[JsonSerializable(typeof(PhotoTrashRecord))]
[JsonSerializable(typeof(FrameRestoreJournal))]
internal sealed partial class TrashJson : JsonSerializerContext;
+7 -2
View File
@@ -88,14 +88,19 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options)
}
/// <summary>
/// Reads the sidecar of a locked sequence, completing an interrupted ingest batch first.
/// Reads the sidecar of a locked sequence, undoing an interrupted photo deletion (<see cref="FrameRemovalJournal"/>),
/// settling an interrupted restore from the trash (<see cref="FrameRestoreJournal"/>; left for later while its trash
/// entry is busy) and completing an interrupted ingest batch first.
/// </summary>
/// <param name="heldEntryLease">The trash entry lease the caller holds already (a restore of that entry), if any.</param>
/// <exception cref="InvalidDataException">The sidecar in the folder belongs to another sequence.</exception>
public static SequenceManifest ReadLocked(SequencePaths sequence, Guid sequenceId)
public static SequenceManifest ReadLocked(SequencePaths sequence, Guid sequenceId, string? heldEntryLease = null)
{
var manifest = ManifestStore.ReadSequence(sequence.ManifestPath);
if (manifest.Id != sequenceId)
throw new InvalidDataException($"{sequence.ManifestPath} belongs to sequence {manifest.Id}, not {sequenceId}.");
FrameRemovalJournal.Recover(sequence, manifest);
FrameTrash.RecoverRestore(sequence, manifest, heldEntryLease);
if (IngestJournal.Recover(sequence, manifest) is { } recovered)
{
ManifestStore.WriteSequence(sequence.ManifestPath, recovered);
+4
View File
@@ -23,6 +23,7 @@ public abstract class ChronosRepositories
Audit = new AuditRepository(access);
Uploads = new UploadRepository(access);
Schedules = new ScheduleRepository(access);
FrameRemovals = new FrameRemovalRepository(access);
}
public ArchiveRepository Archives { get; }
@@ -41,6 +42,9 @@ public abstract class ChronosRepositories
/// <summary>Scheduled jobs (owner review 2, R10).</summary>
public ScheduleRepository Schedules { get; }
/// <summary>Tombstones of the photos removed from sequences (owner review 2, R6).</summary>
public FrameRemovalRepository FrameRemovals { get; }
}
/// <summary>
@@ -0,0 +1,14 @@
-- Tombstones of photos removed from sequences (owner review 2, R6): a photo deleted into the archive's trash (reason 0)
-- or replaced by a converted file (reason 1, with the replacement's SHA-256). The sidecar's "removed" list is the truth;
-- the index writes these rows from it, so a rebuild keeps them. Sync never offers a tombstoned photo back, and an upload
-- of that content into the sequence is answered as already there. Mirrors sqlite/0008_frame_removals.sql.
CREATE TABLE frame_removals (
sequence_id uuid NOT NULL REFERENCES sequences (id) ON DELETE CASCADE,
sha256 text NOT NULL,
replacement_sha256 text,
reason integer NOT NULL DEFAULT 0,
removed_at timestamptz NOT NULL,
PRIMARY KEY (sequence_id, sha256)
);
CREATE INDEX ix_frame_removals_sha256 ON frame_removals (sha256);
@@ -0,0 +1,14 @@
-- Tombstones of photos removed from sequences (owner review 2, R6): a photo deleted into the archive's trash (reason 0)
-- or replaced by a converted file (reason 1, with the replacement's SHA-256). The sidecar's "removed" list is the truth;
-- the index writes these rows from it, so a rebuild keeps them. Sync never offers a tombstoned photo back, and an upload
-- of that content into the sequence is answered as already there. Mirrors postgres/0008_frame_removals.sql.
CREATE TABLE frame_removals (
sequence_id TEXT NOT NULL REFERENCES sequences (id) ON DELETE CASCADE,
sha256 TEXT NOT NULL,
replacement_sha256 TEXT,
reason INTEGER NOT NULL DEFAULT 0,
removed_at TEXT NOT NULL,
PRIMARY KEY (sequence_id, sha256)
);
CREATE INDEX ix_frame_removals_sha256 ON frame_removals (sha256);
@@ -0,0 +1,71 @@
using System.Globalization;
using System.Text;
using Chronos.Core.Model;
namespace Chronos.Data.Repositories;
/// <summary>
/// Tombstones of the photos removed from sequences (owner review 2, R6; <c>frame_removals</c>), by sequence and SHA-256.
/// The sidecar's <c>removed</c> list is the truth: the index writes a sequence's rows from it whenever it takes the
/// sidecar (<see cref="SyncSequenceAsync"/>), so a rebuild keeps them, and they go with the sequence's row.
/// </summary>
public sealed class FrameRemovalRepository
{
private const string Columns = "sequence_id, sha256, replacement_sha256, reason, removed_at";
/// <summary>Rows one INSERT writes (five parameters each, well inside both engines' limits).</summary>
private const int InsertRows = 200;
private readonly DbAccess _db;
internal FrameRemovalRepository(DbAccess db) => _db = db;
/// <summary>The tombstones of a sequence, oldest first.</summary>
public Task<IReadOnlyList<FrameRemoval>> ListBySequenceAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
_db.ListAsync($"SELECT {Columns} FROM frame_removals WHERE sequence_id = $1 ORDER BY removed_at, sha256", [sequenceId], Map, cancellationToken);
/// <summary>Whether <paramref name="sha256"/> was removed from the sequence (any reason).</summary>
public async Task<bool> IsRemovedAsync(Guid sequenceId, string sha256, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrEmpty(sha256);
return await _db.ScalarAsync<long>("SELECT count(*) FROM frame_removals WHERE sequence_id = $1 AND sha256 = $2",
[sequenceId, sha256.ToLowerInvariant()], cancellationToken).ConfigureAwait(false) > 0;
}
/// <summary>
/// Replaces the tombstones of a sequence with <paramref name="removals"/> (the sidecar's list; one per SHA-256, the
/// last one given wins). Returns how many rows the sequence has now.
/// </summary>
public Task<int> SyncSequenceAsync(Guid sequenceId, IReadOnlyList<FrameRemoval> removals, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(removals);
var rows = removals.Where(r => !string.IsNullOrEmpty(r.Sha256)).GroupBy(r => r.Sha256.ToLowerInvariant(), StringComparer.Ordinal)
.Select(g => g.Last() with { Sha256 = g.Key, SequenceId = sequenceId }).ToList();
return _db.InTransactionAsync(async session =>
{
await session.ExecuteAsync("DELETE FROM frame_removals WHERE sequence_id = $1", [sequenceId], cancellationToken).ConfigureAwait(false);
for (var start = 0; start < rows.Count; start += InsertRows)
{
var count = Math.Min(InsertRows, rows.Count - start);
var sql = new StringBuilder($"INSERT INTO frame_removals ({Columns}) VALUES ");
var args = new DbParam[count * 5];
for (var i = 0; i < count; i++)
{
var row = rows[start + i];
sql.Append(i > 0 ? ", (" : "(").Append(string.Join(", ", Enumerable.Range(i * 5 + 1, 5).Select(n => "$" + n.ToString(CultureInfo.InvariantCulture))))
.Append(')');
args[i * 5] = row.SequenceId;
args[i * 5 + 1] = row.Sha256;
args[i * 5 + 2] = row.ReplacementSha256?.ToLowerInvariant();
args[i * 5 + 3] = (int)row.Reason;
args[i * 5 + 4] = row.RemovedAt;
}
await session.ExecuteAsync(sql.ToString(), args, cancellationToken).ConfigureAwait(false);
}
return rows.Count;
}, cancellationToken);
}
private static FrameRemoval Map(DbRow r) =>
new(r.GetGuid(0), r.GetString(1), r.GetStringOrNull(2), (RemovalReason)r.GetInt32(3), r.GetDateTimeOffset(4));
}
@@ -1,3 +1,4 @@
using System.Globalization;
using Chronos.Core.Imaging;
using Chronos.Core.Model;
@@ -103,6 +104,15 @@ public sealed record CameraBucket(string? Make, string? Model, int Sequences, lo
public sealed record FormatBucket(ImageFileFormat Format, long Photos, long Bytes);
/// <summary>
/// A value a Library filter offers, as <see cref="SequenceQuery"/> takes it (a year, an exact camera model, a tag), and
/// how many sequences have it; <see cref="Make"/> is a camera model's make, for its label.
/// </summary>
public sealed record ArchiveFacet(string Value, int Sequences, string? Make = null);
/// <summary>The years of first capture, camera models and tags of an archive's sequences (owner review 2, R6: the panel's filters).</summary>
public sealed record ArchiveFacets(IReadOnlyList<ArchiveFacet> Years, IReadOnlyList<ArchiveFacet> Cameras, IReadOnlyList<ArchiveFacet> Tags);
/// <summary>Health counters: sequences needing attention and flagged frames.</summary>
public sealed record ArchiveHealth(
int Unverified,
@@ -389,6 +399,32 @@ public sealed class SequenceRepository
}, cancellationToken);
}
/// <summary>
/// What the Library's filters offer for <paramref name="archiveId"/>: years of first capture (newest first), camera
/// models (most sequences first; one entry per model, as the camera filter matches the model alone) and the tags in use
/// (by name). Only sequence rows are read, never frames.
/// </summary>
public Task<ArchiveFacets> GetFacetsAsync(Guid archiveId, CancellationToken cancellationToken = default)
{
DbParam[] args = [archiveId];
var year = _db.Sql.Year("s.first_capture");
return _db.RunAsync(async session =>
{
var years = await session.QueryListAsync(
$"SELECT {year}, count(*) FROM sequences s WHERE s.archive_id = $1 AND s.first_capture IS NOT NULL GROUP BY 1 ORDER BY 1 DESC", args,
r => new ArchiveFacet(r.GetInt32(0).ToString(CultureInfo.InvariantCulture), r.GetInt32(1)), cancellationToken).ConfigureAwait(false);
var cameras = await session.QueryListAsync(
"SELECT s.camera_model, MIN(s.camera_make), count(*) FROM sequences s " +
"WHERE s.archive_id = $1 AND s.camera_model IS NOT NULL AND s.camera_model <> '' GROUP BY s.camera_model ORDER BY 3 DESC, 1", args,
r => new ArchiveFacet(r.GetString(0), r.GetInt32(2), r.GetStringOrNull(1)), cancellationToken).ConfigureAwait(false);
var tags = await session.QueryListAsync(
"SELECT MIN(t.name), count(*) FROM sequence_tags st JOIN tags t ON t.id = st.tag_id JOIN sequences s ON s.id = st.sequence_id " +
"WHERE s.archive_id = $1 GROUP BY t.name_key ORDER BY t.name_key", args,
r => new ArchiveFacet(r.GetString(0), r.GetInt32(1)), cancellationToken).ConfigureAwait(false);
return new ArchiveFacets(years, cameras, tags);
}, cancellationToken);
}
/// <summary>
/// The sequences of <paramref name="archiveId"/> a rolling verification checks next (owner review 2, R10): those never
/// verified first, then the longest unverified, at most <paramref name="limit"/>. With <paramref name="verifiedBefore"/>
+14 -3
View File
@@ -24,6 +24,9 @@ internal sealed class SyncPositions(ChronosDatabase db, ISyncRemote remote, Guid
/// <summary>The manifest's frames by hash, and with their capture times once fetched.</summary>
private FramePhotos? _hashed, _timed;
/// <summary>The photos either copy removed: a replaced photo is translated as its replacement (owner review 2, R6).</summary>
private SyncTombstones? _tombstones;
/// <summary>The server's frames version the translation to the server's frames is made against.</summary>
public int ServerFrames => manifest.FramesVersion;
@@ -73,7 +76,10 @@ internal sealed class SyncPositions(ChronosDatabase db, ISyncRemote remote, Guid
var frames = await SequenceFrames.ListAsync(db, localId, cancellationToken).ConfigureAwait(false);
if (await db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false) is not { } after) return null;
if (after.FramesVersion == before.FramesVersion)
return new LocalState(after, new FramePhotos(frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, f.CapturedAt)))));
{
var tombstones = await TombstonesAsync(cancellationToken).ConfigureAwait(false);
return new LocalState(after, new FramePhotos(frames.Select(f => (f.Index, tombstones.Canonical(new FramePhoto(f.Sha256, f.Size, f.CapturedAt))))));
}
}
return null;
}
@@ -87,20 +93,25 @@ internal sealed class SyncPositions(ChronosDatabase db, ISyncRemote remote, Guid
/// </summary>
private async Task<FramePhotos?> ServerAsync(FramePhotos local, CancellationToken cancellationToken)
{
var tombstones = await TombstonesAsync(cancellationToken).ConfigureAwait(false);
if (_hashed is null)
{
if (!OneList(manifest.Frames)) return null;
_hashed = new FramePhotos(manifest.Frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, null))));
_hashed = new FramePhotos(manifest.Frames.Select(f => (f.Index, tombstones.Canonical(new FramePhoto(f.Sha256, f.Size, null)))));
}
if (_hashed.SameAs(local)) return _hashed;
if (_timed is null)
{
var captured = (await remote.ListFramesAsync(manifest.SequenceId, cancellationToken).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
_timed = new FramePhotos(manifest.Frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, captured.GetValueOrDefault(f.Id)))));
_timed = new FramePhotos(manifest.Frames.Select(f => (f.Index, tombstones.Canonical(new FramePhoto(f.Sha256, f.Size, captured.GetValueOrDefault(f.Id))))));
}
return _timed;
}
/// <summary>This copy's tombstones and the server's, read once.</summary>
private async Task<SyncTombstones> TombstonesAsync(CancellationToken cancellationToken) =>
_tombstones ??= new SyncTombstones(await db.FrameRemovals.ListBySequenceAsync(localId, cancellationToken).ConfigureAwait(false), manifest.Removed);
/// <summary>Each frame once, at the indices 0…n-1 a sequence's frames always take.</summary>
private static bool OneList(IReadOnlyList<ManifestFrame> frames)
{
+22
View File
@@ -164,6 +164,28 @@ public static class SyncRules
];
}
/// <summary>
/// <see cref="CompareOriginals(IReadOnlyCollection{FramePhoto}, IReadOnlyCollection{FramePhoto})"/> honouring the photos
/// either side removed (owner review 2, R6): a photo the server deleted is not missing there, one this PC deleted is not
/// missing here, and a photo replaced by a converted file on either side is compared as its replacement. A tombstone
/// leaves out only a photo its side no longer holds: one left beside a frame of the same content (the other copy of a
/// duplicate, a file put back by hand) would otherwise keep the other side's copy missing for good.
/// </summary>
public static (int MissingRemote, int MissingLocal) CompareOriginals(IReadOnlyCollection<FramePhoto> local, IReadOnlyCollection<FramePhoto> remote,
SyncTombstones tombstones)
{
ArgumentNullException.ThrowIfNull(local);
ArgumentNullException.ThrowIfNull(remote);
ArgumentNullException.ThrowIfNull(tombstones);
if (tombstones.IsEmpty) return CompareOriginals(local, remote);
var mine = local.Select(p => (p.Sha256, Photo: tombstones.Canonical(p))).ToList();
var theirs = remote.Select(p => (p.Sha256, Photo: tombstones.Canonical(p))).ToList();
var minePhotos = new FramePhotos(mine.Select((p, i) => (i, p.Photo)));
var theirPhotos = new FramePhotos(theirs.Select((p, i) => (i, p.Photo)));
return CompareOriginals([.. mine.Where(p => !tombstones.DeletedRemotely(p.Sha256) || theirPhotos.IndexOf(p.Photo) is not null).Select(p => p.Photo)],
[.. theirs.Where(p => !tombstones.DeletedLocally(p.Sha256) || minePhotos.IndexOf(p.Photo) is not null).Select(p => p.Photo)]);
}
/// <summary>
/// Frames whose proxy the server asks for (it cannot decode their originals, BRIEF §2.3) that this PC holds and its
/// <paramref name="decoder"/> reads: an upload makes and sends them. A local original not hashed yet (a folder adopted
+3 -1
View File
@@ -528,8 +528,10 @@ public sealed class SyncService
var captured = manifest.Frames.Any(f => f.Sha256.Length == 0) || present.Any(f => f.Sha256 is null)
? (await remote.ListFramesAsync(link.RemoteId, cancellationToken).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt)
: null;
// Photos either side removed are not offered back; one replaced by a converted file counts as its replacement (owner review 2, R6).
var tombstones = new SyncTombstones(await _db.FrameRemovals.ListBySequenceAsync(local.Id, cancellationToken).ConfigureAwait(false), manifest.Removed);
var (missingRemote, missingLocal) = SyncRules.CompareOriginals([.. present.Select(f => new FramePhoto(f.Sha256, f.Size, f.CapturedAt))],
[.. manifest.Frames.Select(f => new FramePhoto(f.Sha256, f.Size, captured?.GetValueOrDefault(f.Id)))]);
[.. manifest.Frames.Select(f => new FramePhoto(f.Sha256, f.Size, captured?.GetValueOrDefault(f.Id)))], tombstones);
// Proxies the server asks for that this PC can make from its originals travel with an upload too (BRIEF §2.3).
var proxies = policy.CanEdit && manifest.Proxies is not null ? SyncRules.ProxiesToSend(manifest, present, Options.Archive.Decoder, captured) : 0;
// Those change without the server's frame counters moving: while some may be made here, the server's next
+81
View File
@@ -0,0 +1,81 @@
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Protocol;
namespace Chronos.Data.Sync;
/// <summary>
/// The photos each copy of a linked pair removed (owner review 2, R6; BRIEF §14.5): a photo one side deleted is not
/// offered to it again (no upload of what the server deleted, no download of what this PC deleted; local files are never
/// deleted by sync), and a photo one side replaced by a converted file is the same photo as its replacement on either side
/// (an alias: both are compared, matched and translated as the replacement). No I/O.
/// </summary>
public sealed class SyncTombstones
{
/// <summary>Links a replacement chain may have at most (a conversion of a conversion…); longer ones stop there.</summary>
private const int MaxAliasSteps = 8;
private readonly HashSet<string> _deletedLocally;
private readonly HashSet<string> _deletedRemotely;
private readonly Dictionary<string, string> _aliases;
public SyncTombstones(IEnumerable<FrameRemoval> local, IEnumerable<RemovedPhotoDto>? remote)
{
ArgumentNullException.ThrowIfNull(local);
_deletedLocally = new HashSet<string>(StringComparer.Ordinal);
_deletedRemotely = new HashSet<string>(StringComparer.Ordinal);
_aliases = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var removal in local) Add(removal.Sha256, removal.ReplacementSha256, removal.Reason == RemovalReason.Replaced, _deletedLocally);
foreach (var removal in remote ?? [])
Add(removal.Sha256, removal.Replacement, string.Equals(removal.Reason, Wire(RemovalReason.Replaced), StringComparison.OrdinalIgnoreCase), _deletedRemotely);
}
/// <summary>No photo removed on either side.</summary>
public static SyncTombstones None { get; } = new([], null);
/// <summary>Whether either side removed or replaced anything.</summary>
public bool IsEmpty => _deletedLocally.Count == 0 && _deletedRemotely.Count == 0 && _aliases.Count == 0;
/// <summary>The wire name of a removal reason (<c>deleted</c>, <c>replaced</c>).</summary>
public static string Wire(RemovalReason reason) => reason.ToString().ToLowerInvariant();
/// <summary>The tombstones of a sequence as the manifest carries them.</summary>
public static IReadOnlyList<RemovedPhotoDto> ToDto(IEnumerable<FrameRemoval> removals) =>
[.. removals.Select(r => new RemovedPhotoDto(r.Sha256, r.ReplacementSha256, Wire(r.Reason), r.RemovedAt))];
/// <summary>
/// The SHA-256 a photo is compared as: the end of its replacement chain on either side, lower-case; null or empty
/// (not hashed yet) stays as it is.
/// </summary>
public string? Canonical(string? sha256)
{
if (string.IsNullOrEmpty(sha256)) return sha256;
var current = sha256.ToLowerInvariant();
for (var step = 0; step < MaxAliasSteps && _aliases.TryGetValue(current, out var next); step++) current = next;
return current;
}
/// <summary>The photo as it is compared (<see cref="Canonical(string?)"/>).</summary>
public FramePhoto Canonical(FramePhoto photo)
{
ArgumentNullException.ThrowIfNull(photo);
return photo.IsHashed && _aliases.Count > 0 ? photo with { Sha256 = Canonical(photo.Sha256) } : photo;
}
/// <summary>This PC deleted the photo (or what replaced it): the server's copy is not downloaded.</summary>
public bool DeletedLocally(string? sha256) => Deleted(sha256, _deletedLocally);
/// <summary>The server deleted the photo (or what replaced it): this PC's copy is not uploaded.</summary>
public bool DeletedRemotely(string? sha256) => Deleted(sha256, _deletedRemotely);
private bool Deleted(string? sha256, HashSet<string> deleted) =>
!string.IsNullOrEmpty(sha256) && deleted.Count > 0 && (deleted.Contains(sha256.ToLowerInvariant()) || deleted.Contains(Canonical(sha256)!));
private void Add(string sha256, string? replacement, bool replaced, HashSet<string> deleted)
{
if (string.IsNullOrEmpty(sha256)) return;
var sha = sha256.ToLowerInvariant();
if (replaced && !string.IsNullOrEmpty(replacement)) _aliases[sha] = replacement.ToLowerInvariant();
else deleted.Add(sha);
}
}
+41 -14
View File
@@ -48,13 +48,15 @@ internal sealed class SyncTransfers(SyncService sync)
var frames = (await SequenceFrames.ListAsync(db, local.Id, ct).ConfigureAwait(false)).Where(f => (f.Flags & FrameFlags.Missing) == 0).ToList();
var manifest = remoteId is { } known ? await remote.GetManifestAsync(known, ct).ConfigureAwait(false) : null;
var present = manifest?.Frames.Where(f => f.Sha256.Length > 0).Select(f => f.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal) ?? [];
// A photo the server deleted is not sent back; one it replaced by a converted file is there as its replacement (owner review 2, R6).
var tombstones = new SyncTombstones(await db.FrameRemovals.ListBySequenceAsync(local.Id, ct).ConfigureAwait(false), manifest?.Removed);
var present = manifest?.Frames.Where(f => f.Sha256.Length > 0).Select(f => tombstones.Canonical(f.Sha256)!).ToHashSet(StringComparer.Ordinal) ?? [];
// Originals the server holds without a hash (adopted there, not verified) are the ones of their size and capture
// time: the server could not recognise them by content, so they are not sent again.
var adopted = manifest is not null && manifest.Frames.Any(f => f.Sha256.Length == 0)
? await UnhashedAsync(remote, manifest, ct).ConfigureAwait(false)
: new FramePhotos([]);
var pending = new Queue<Frame>(frames.Where(f => (f.Sha256 is null || !present.Contains(f.Sha256.ToLowerInvariant()))
var pending = new Queue<Frame>(frames.Where(f => (f.Sha256 is null || (!present.Contains(tombstones.Canonical(f.Sha256)!) && !tombstones.DeletedRemotely(f.Sha256)))
&& adopted.IndexOf(new FramePhoto(f.Sha256, f.Size, f.CapturedAt)) is null));
var progress = new TransferProgress(context, frames.Count, frames.Count - pending.Count);
await progress.ReportAsync().ConfigureAwait(false);
@@ -68,8 +70,8 @@ internal sealed class SyncTransfers(SyncService sync)
// server has filed one, which creates the sequence (an original it already holds elsewhere creates nothing).
while (remoteId is null && pending.TryDequeue(out var first))
{
var sent = await UploadFrameAsync(context, remote, null, SyncService.SessionKey(local.Id), paths.FromRelative(first.RelativePath), first, hashes, ct)
.ConfigureAwait(false);
var sent = await UploadFrameAsync(context, remote, null, SyncService.SessionKey(local.Id), paths.FromRelative(first.RelativePath), first, tombstones,
hashes, ct).ConfigureAwait(false);
if (sent is null) skipped++;
else if (sent.SequenceId != Guid.Empty)
{
@@ -83,11 +85,15 @@ internal sealed class SyncTransfers(SyncService sync)
await Parallel.ForEachAsync(pending, Workers(sync.Options.Uploads, ct), async (frame, token) =>
{
if (await UploadFrameAsync(context, remote, target, null, paths.FromRelative(frame.RelativePath), frame, hashes, token).ConfigureAwait(false) is null)
Interlocked.Increment(ref skipped);
var sent = await UploadFrameAsync(context, remote, target, null, paths.FromRelative(frame.RelativePath), frame, tombstones, hashes, token)
.ConfigureAwait(false);
if (sent is null) Interlocked.Increment(ref skipped);
await progress.StepAsync().ConfigureAwait(false);
}).ConfigureAwait(false);
await SendProxiesAsync(context, remote, target, local, paths, frames, hashes).ConfigureAwait(false);
// An original the index has no hash for turned out to be a photo the server deleted: the verify gives the index
// the hashes (as before a download), so the comparison leaves it out instead of offering its upload again and again.
if (hashes.Values.Any(tombstones.DeletedRemotely)) await VerifyAsync(archive, local.Id, ct).ConfigureAwait(false);
if (created) await sync.PushAllAsync(remote, target, ct).ConfigureAwait(false);
await sync.RecompareAsync(remote, target, ct).ConfigureAwait(false);
@@ -205,12 +211,16 @@ internal sealed class SyncTransfers(SyncService sync)
var manifest = await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false);
var captured = (await remote.ListFramesAsync(remoteId, ct).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
var (have, restore, photos) = local is null ? ([], [], new FramePhotos([])) : await LocalContentAsync(archive, local, ct).ConfigureAwait(false);
// A photo this PC deleted is not fetched again; one replaced here by a converted file is here as its replacement (owner review 2, R6).
var tombstones = local is null ? SyncTombstones.None
: new SyncTombstones(await db.FrameRemovals.ListBySequenceAsync(local.Id, ct).ConfigureAwait(false), manifest.Removed);
if (!tombstones.IsEmpty) have = [.. have.Select(h => tombstones.Canonical(h)!)];
// An original the server has not hashed yet (adopted there, not verified) is here when an original of its size and
// capture time is; each one is fetched on its own and hashed here.
var wanted = manifest.Frames
.Where(f => f.Sha256.Length == 0
? photos.IndexOf(new FramePhoto(null, f.Size, captured.GetValueOrDefault(f.Id))) is null
: !have.Contains(f.Sha256.ToLowerInvariant()))
: !have.Contains(tombstones.Canonical(f.Sha256)!) && !tombstones.DeletedLocally(f.Sha256))
.DistinctBy(f => f.Sha256.Length == 0 ? f.Id.ToString("N") : f.Sha256.ToLowerInvariant()).ToList();
EnsureSpace(paths.Root, wanted.Sum(f => f.Size));
@@ -234,7 +244,7 @@ internal sealed class SyncTransfers(SyncService sync)
await progress.StepAsync().ConfigureAwait(false);
}
var sequenceId = local?.Id;
var restored = 0;
int restored = 0, refused = 0;
await Parallel.ForEachAsync(rest, Workers(sync.Options.Downloads, ct), async (frame, token) =>
{
var (staged, sha) = await FetchOriginalAsync(remote, frame, staging, token).ConfigureAwait(false);
@@ -243,6 +253,14 @@ internal sealed class SyncTransfers(SyncService sync)
Restore(staged, place);
Interlocked.Increment(ref restored);
}
else if (frame.Sha256.Length == 0 && (tombstones.DeletedLocally(sha) || have.Contains(tombstones.Canonical(sha)!)))
{
// An original the server has not hashed is known by content only now: one this PC deleted (or holds as
// the converted file that replaced it) is not filed again, which would also drop its tombstone.
File.Delete(staged);
Interlocked.Increment(ref refused);
if (tombstones.DeletedLocally(sha)) context.Log($"{frame.FileName}: deleted on this PC, not downloaded");
}
else
{
await CommitAsync(remoteId, archive.Id, sequenceId, frame, staged, sha, captured, token).ConfigureAwait(false);
@@ -255,7 +273,7 @@ internal sealed class SyncTransfers(SyncService sync)
if (created) await sync.TakeAllAsync(remote, remoteId, ct).ConfigureAwait(false);
await sync.RecompareAsync(remote, remoteId, ct).ConfigureAwait(false);
if (sequenceId is { } downloaded && wanted.Count > restored)
if (sequenceId is { } downloaded && wanted.Count > restored + refused)
{
var label = local!.DisplayTitle;
await EnqueueFollowUpAsync(context, ArchiveJobs.Thumbnails([downloaded], label)).ConfigureAwait(false);
@@ -491,10 +509,11 @@ internal sealed class SyncTransfers(SyncService sync)
/// <summary>
/// Hashes the original again and sends it into <paramref name="sequenceId"/> (or the sequence of
/// <paramref name="sessionKey"/>); null (logged) when it is gone or no longer the archived file. The hash of an
/// original the index has none for goes into <paramref name="hashes"/>.
/// original the index has none for goes into <paramref name="hashes"/>; known by content only now, such an original
/// the server deleted (<paramref name="tombstones"/>) is not sent back.
/// </summary>
private static async Task<CompleteUploadResponse?> UploadFrameAsync(JobContext context, ISyncRemote remote, Guid? sequenceId, string? sessionKey, string path,
Frame frame, ConcurrentDictionary<Guid, string> hashes, CancellationToken cancellationToken)
Frame frame, SyncTombstones tombstones, ConcurrentDictionary<Guid, string> hashes, CancellationToken cancellationToken)
{
if (!File.Exists(path))
{
@@ -502,14 +521,22 @@ internal sealed class SyncTransfers(SyncService sync)
return null;
}
var sha = await ChronosClient.HashFileAsync(path, cancellationToken).ConfigureAwait(false);
if (frame.Sha256 is null) hashes[frame.Id] = sha;
var notSent = new CompleteUploadResponse(Guid.Empty, sequenceId ?? Guid.Empty, -1);
if (frame.Sha256 is null)
{
hashes[frame.Id] = sha;
if (tombstones.DeletedRemotely(sha))
{
context.Log($"{frame.FileName}: deleted on the server, not uploaded");
return notSent;
}
}
if (frame.Sha256 is { } archived && !archived.Equals(sha, StringComparison.OrdinalIgnoreCase))
{
context.Log($"{frame.FileName}: changed since it was archived, not uploaded");
return null;
}
return await remote.UploadFileAsync(path, sequenceId, sessionKey, sha, frame.CapturedAt, cancellationToken).ConfigureAwait(false)
?? new CompleteUploadResponse(Guid.Empty, sequenceId ?? Guid.Empty, -1);
return await remote.UploadFileAsync(path, sequenceId, sessionKey, sha, frame.CapturedAt, cancellationToken).ConfigureAwait(false) ?? notSent;
}
/// <summary>Commits one original from staging into the local sequence (created from the server id when null).</summary>