feat(archive): convert sequences to JPEG, TIFF-16 or linear DNG after import
Owner review 2, R7 asks for mass conversion after import on the web panel and the desktop, with a choice at every run between Replace and New sequence. This is the engine and the server API both UIs build on. - Core/Conversion: ConvertOptions (JPEG 4:4:4 at quality 1-100, default 95; TIFF-16 sRGB Deflate with the predictor; linear DNG, the archival choice; converted names keep the stem and take the target's extension in the old one's case). FrameConverter decodes at the native tier only, encodes with the in-house writers, writes Exif from the sidecar (capture time to the tick, offset, exposure) and the original (camera, serial, lens, modes, GPS), hashes the bytes as made, writes atomically and verifies: read back, the metadata again, a decode by the server's decoders. ExifWriter now writes the exposure program, metering mode, flash and white balance. ConvertPlanner: convertible frames, skips with reasons, size estimates per pixel, the plan's space and fingerprint. - FrameTrash.ReplaceAsync swaps the files of frames in place: same ids and indices, the old files and their XMP companions into one Replaced trash entry (records, replacement hashes, a copy of analysis.json), tombstones aliasing old content to new, proxies of the swapped frames dropped, under .chronos/replace.pending.json, which the next writer undoes or completes. Restoring a Replaced entry swaps back while every converted frame is unchanged (the converted files become a Replaced entry in turn), else the originals come back as a new sequence. - MassConverter and JobKind.Convert (19): the dry run (busy, offline, unreadable, space against ArchiveServiceOptions.FreeSpace), stage A converting into staging/convert-<job>/ in parallel with each source re-hashed and each staged file appended to journal/convert-<job>.staged, stage B per sequence all or nothing under the lease at the planned frames version: Replace, or a new sequence through the ingest with the source's tags, rating, notes and project. Resumes keep verified staged files; a sequence changed, busy or with a failed photo is left as it was and fails the job at the end, the journal kept for a retry. - POST /api/v1/archive/convert: dry run with the plan, its space line and fingerprint, or a 202 convert job; formats the server cannot read at full resolution are skipped as convert_on_pc; validated, audited (archive_converted), sequenceChanged converted/created. The server measures the space volume for the check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 809210d924cfc3f597ecdea26106fb3ff62d3762) (cherry picked from commit e13d4c0bb1bd9441933b6f3e5b6220e865a7228c)
This commit is contained in:
1 parent
d518e87733
commit
0e52929274
34 files changed
+3519
-32
No files matched your search
@@ -1,5 +1,6 @@
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Conversion;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Localization;
|
||||
@@ -14,8 +15,8 @@ namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// What the desktop client and the server call to work with archives (BRIEF §7, §12.4, §12.5, §14.4): open, create
|
||||
/// or adopt an archive, read and change its settings, plan and apply mass renames, plan imports and card erases, delete
|
||||
/// sequences into the trash and restore them, query duplicates and orphans, and
|
||||
/// or adopt an archive, read and change its settings, plan and apply mass renames, plan mass conversions, plan imports and
|
||||
/// card erases, delete sequences into the trash and restore them, query duplicates and orphans, and
|
||||
/// the job handlers for the long operations (enqueue them with <see cref="ArchiveJobs"/>).
|
||||
/// </summary>
|
||||
public sealed class ArchiveService : IJobHandlerProvider
|
||||
@@ -42,6 +43,7 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
Imports = new ImportService(db, Ingest);
|
||||
Trash = new SequenceTrash(db, _writer, Indexer);
|
||||
FrameTrash = new FrameTrash(db, _writer, Indexer, Ingest, Trash);
|
||||
Converter = new MassConverter(db, _writer, Ingest, FrameTrash, Trash, this);
|
||||
var shared = Housekeeping.CleanupSteps.Shared(Trash);
|
||||
CleanupSteps = [.. shared, .. _writer.Options.CleanupSteps.Where(s => !shared.Any(o => o.Name == s.Name))];
|
||||
}
|
||||
@@ -63,6 +65,9 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
/// <summary>Deletes photos of a sequence into the archive's trash and restores them (owner review 2, R6).</summary>
|
||||
public FrameTrash FrameTrash { get; }
|
||||
|
||||
/// <summary>Converts sequences to JPEG, TIFF-16 or linear DNG, replacing their frames or into new sequences (owner review 2, R7).</summary>
|
||||
public MassConverter Converter { 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.
|
||||
@@ -74,8 +79,9 @@ 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), the emptying of the trash (R6) and Reorganize (R7,
|
||||
/// <see cref="JobKind.Move"/>); register them on the <see cref="JobEngine"/>.
|
||||
/// reports, index backups and clean-ups (owner review 2, R10), the emptying of the trash (R6), Reorganize (R7,
|
||||
/// <see cref="JobKind.Move"/>) and mass conversion (R7, <see cref="JobKind.Convert"/>); register them on the
|
||||
/// <see cref="JobEngine"/>.
|
||||
/// </summary>
|
||||
public IReadOnlyList<IJobHandler> CreateJobHandlers() =>
|
||||
[
|
||||
@@ -92,6 +98,7 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
new Housekeeping.CleanupJobHandler(_db, CleanupSteps, TimeProvider.System),
|
||||
new EmptyTrashJobHandler(_db, Trash),
|
||||
new MoveJobHandler(_db, Renamer, _writer.Options.SequenceChanged),
|
||||
new ConvertJobHandler(_db, Converter, _writer.Options.SequenceChanged),
|
||||
];
|
||||
|
||||
/// <summary>Makes <paramref name="root"/> a new, empty archive and indexes it.</summary>
|
||||
@@ -394,6 +401,21 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
return await Renamer.PlanAsync(archive, ids, templates, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The dry run of a mass conversion (owner review 2, R7): <paramref name="sequenceIds"/>, or every sequence of the
|
||||
/// archive (by folder) when null, converted with <paramref name="options"/> in <paramref name="mode"/>. Apply it in a job
|
||||
/// (<see cref="ArchiveJobs.Convert"/>).
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">The archive is unknown, the options are invalid, or a sequence is not in the archive.</exception>
|
||||
public async Task<ConvertPlan> PlanConvertAsync(Guid archiveId, IReadOnlyList<Guid>? sequenceIds, ConvertOptions options, ConvertMode mode,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false);
|
||||
var ids = sequenceIds ?? [.. (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false)).Select(l => l.Id)];
|
||||
return await Converter.PlanAsync(archive, ids, options, mode, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task<RenameResult> ApplyRenameAsync(RenamePlan plan, IProgress<int>? progress = null, CancellationToken cancellationToken = default) =>
|
||||
await Renamer.ApplyAsync(await LoadArchiveAsync(plan.ArchiveId, cancellationToken).ConfigureAwait(false), plan, progress, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
@@ -432,7 +454,7 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
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);
|
||||
return new TrashRestoreResult(photos.Kind, 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>
|
||||
@@ -673,6 +695,24 @@ public static class ArchiveJobs
|
||||
JobPriority.User);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Convert"/>: applies the conversion <paramref name="plan"/> (<see cref="ArchiveService.PlanConvertAsync"/>)
|
||||
/// as confirmed (owner review 2, R7): the sequences it converts, in its order with their frames versions, are the job's
|
||||
/// targets, so jobs that would touch them wait. A sequence that changed before it ran is left as it is and reported.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">The plan converts nothing.</exception>
|
||||
public static ArchiveJobRequest Convert(Archive archive, ConvertPlan plan)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
var sequences = plan.Converted.Select(s => new ConvertSequence(s.SequenceId, s.FramesVersion)).ToList();
|
||||
if (sequences.Count == 0) throw new ArgumentException("The plan converts nothing.", nameof(plan));
|
||||
var label = sequences.Count == 1 ? plan.Converted.First().Title : archive.Name;
|
||||
return new(JobKind.Convert, [.. sequences.Select(s => s.Id)], label,
|
||||
Json(new ConvertJobParameters(archive.Id, plan.Options.Target, plan.Options.Quality, plan.Mode, sequences, plan.Fingerprint()),
|
||||
ArchiveJobJson.Default.ConvertJobParameters), 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,522 @@
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Naming;
|
||||
using SequenceFrames = Chronos.Core.Archiving.SequenceFrames;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// One frame a replacement swaps (owner review 2, R7): the file that comes in, its companions, the name it is filed under
|
||||
/// and the record the frame gets.
|
||||
/// </summary>
|
||||
/// <param name="Incoming">The file that comes in, relative to the archive root: a staged conversion, or an original in a
|
||||
/// trash entry.</param>
|
||||
/// <param name="Companions">Files that come in with it (the XMP companions of an original back from the trash).</param>
|
||||
/// <param name="Name">The name it is filed under, from the frame as the sidecar has it under the lease, relative to the
|
||||
/// sequence folder; made unique with <c>_2</c>, <c>_3</c>… when it, or one of its companions' names, is taken.</param>
|
||||
/// <param name="Record">The frame's record after the swap, from the frame as the sidecar has it under the lease (its
|
||||
/// <see cref="SidecarFrame.Sha256"/> names the incoming file): the replacement keeps the frame's id and index, files it
|
||||
/// under its name, and keeps the flags a user or the capture set (<see cref="FrameTrash.ContentFlags"/> come from the
|
||||
/// record).</param>
|
||||
internal sealed record FrameSwap(Guid FrameId, string Incoming, IReadOnlyList<IncomingCompanion> Companions, Func<SidecarFrame, string> Name,
|
||||
Func<SidecarFrame, SidecarFrame> Record);
|
||||
|
||||
/// <summary>A companion that comes in with its photo: where it is (relative to the archive root), and what its name adds to the photo's stem.</summary>
|
||||
internal sealed record IncomingCompanion(string From, string Tail);
|
||||
|
||||
/// <summary>
|
||||
/// The trash entry a replacement takes its incoming files from (the undo of a conversion): once the sidecar is written,
|
||||
/// the photos of <see cref="Frames"/> leave its record, and its copy of <c>analysis.json</c> (<see cref="Analysis"/>) goes back
|
||||
/// into the sequence.
|
||||
/// </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>
|
||||
/// <param name="Lease">The entry's lease, which the replacement's caller holds.</param>
|
||||
/// <param name="Analysis">The entry's copy of <c>analysis.json</c>, relative to the archive root; null when it has none.</param>
|
||||
internal sealed record ConsumedEntry(string Record, string Folder, string Lease, IReadOnlyList<Guid> Frames, string? Analysis);
|
||||
|
||||
/// <summary>One file a replacement moves: its place in the sequence folder and the other end, relative to the archive root.</summary>
|
||||
/// <param name="Place">Relative to the sequence folder (forward slashes).</param>
|
||||
/// <param name="Other">Relative to the archive root: the trash entry an outgoing file goes to, or where an incoming file comes from.</param>
|
||||
internal sealed record SwapMove(string Place, string Other);
|
||||
|
||||
/// <summary>What a replacement did: the trash entry of the files that went, the sequence as it is now, and its statuses before.</summary>
|
||||
internal sealed record ReplaceResult(TrashEntry Entry, Sequence Sequence, SequenceStatus Had);
|
||||
|
||||
/// <summary>
|
||||
/// Write-ahead record of a frame replacement (<c>.chronos/replace.pending.json</c>, owner review 2, R7): the sidecar's frames
|
||||
/// version before it, the new trash entry (its record pending until the sidecar is written), every file that leaves the
|
||||
/// sequence for the entry and every file that comes in, whether the entry holds a copy of <c>analysis.json</c>, and the
|
||||
/// entry the incoming files come from (an undo). Written under the sequence's lease before the first move and removed once
|
||||
/// the replacement is settled, so the next writer of the sequence (<see cref="SequenceWriter.ReadLocked"/>) undoes one a
|
||||
/// crash interrupted before its sidecar was written, and completes one interrupted after.
|
||||
/// </summary>
|
||||
/// <param name="Record">The new entry's record, relative to the archive root (its name once the replacement is complete).</param>
|
||||
/// <param name="Folder">The new entry's folder, relative to the archive root.</param>
|
||||
/// <param name="Out">Files that leave the sequence for the new entry.</param>
|
||||
/// <param name="In">Files that come into the sequence.</param>
|
||||
internal sealed record FrameReplaceJournal(int FramesVersion, string Record, string Folder, IReadOnlyList<SwapMove> Out, IReadOnlyList<SwapMove> In,
|
||||
bool Analysis, ConsumedEntry? Consumed)
|
||||
{
|
||||
public void Write(SequencePaths sequence)
|
||||
{
|
||||
System.IO.Directory.CreateDirectory(sequence.MetaDirectory);
|
||||
AtomicFile.WriteAllBytes(sequence.ReplaceJournalPath, JsonSerializer.SerializeToUtf8Bytes(this, TrashJson.Default.FrameReplaceJournal));
|
||||
}
|
||||
|
||||
/// <summary>The journal of a sequence; null when it is torn (written by a process that died while writing it: nothing moved yet).</summary>
|
||||
public static FrameReplaceJournal? Read(SequencePaths sequence)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize(AtomicFile.ReadAllBytes(sequence.ReplaceJournalPath), TrashJson.Default.FrameReplaceJournal);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void Delete(SequencePaths sequence)
|
||||
{
|
||||
if (File.Exists(sequence.ReplaceJournalPath)) File.Delete(sequence.ReplaceJournalPath);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed partial class FrameTrash
|
||||
{
|
||||
/// <summary>
|
||||
/// Flags that follow a frame's file, not the frame: a replacement takes them from the incoming record and keeps the
|
||||
/// others (excluded, intervalometer, black, white) as the frame has them.
|
||||
/// </summary>
|
||||
internal const FrameFlags ContentFlags = FrameFlags.Missing | FrameFlags.Corrupt | FrameFlags.Duplicate | FrameFlags.PreviewOnly | FrameFlags.Undecodable;
|
||||
|
||||
/// <summary>The name of the copy of a sequence's <c>analysis.json</c> a replaced entry keeps, inside its folder.</summary>
|
||||
internal const string AnalysisCopy = "analysis.json";
|
||||
|
||||
/// <summary>
|
||||
/// Replaces the files of frames of a sequence, keeping the frames (owner review 2, R7; BRIEF §7): under the sequence's
|
||||
/// lease, with its frames version still <paramref name="framesVersion"/> (null: any) and <paramref name="unchanged"/>
|
||||
/// (when given) still true, every swapped frame's original and its XMP companions move into one trash entry of kind
|
||||
/// <see cref="TrashKind.Replaced"/> (its record holds the old frame records and each one's replacement SHA-256, and a copy
|
||||
/// of <c>analysis.json</c>), and the incoming files move in under their names (made unique). The sidecar takes the
|
||||
/// records with the same ids and indices (frames version + 1, the statuses the frames uncovered cleared) and a tombstone
|
||||
/// per old content naming its replacement, so sync counts the old photo as the new one; content that comes back loses
|
||||
/// its tombstone. Then the index follows, the proxies of the swapped frames are deleted (the proxy pass makes them
|
||||
/// again) and the project's positions stay on their frames. A journal (<see cref="FrameReplaceJournal"/>) makes it all
|
||||
/// or nothing: a failure before the sidecar is written puts every file back, and a crash is undone or completed by the
|
||||
/// next writer of the sequence. Returns null, nothing touched, when the sequence is gone, its frames changed, a swapped
|
||||
/// frame's original is not there whole or was never hashed, or <paramref name="unchanged"/> said no.
|
||||
/// </summary>
|
||||
/// <param name="replacedBy">Who asked (user name or client), kept in the trash record.</param>
|
||||
/// <param name="consumed">The trash entry the incoming files come from (an undo), settled once the sidecar is written.</param>
|
||||
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only; nothing moved.</exception>
|
||||
/// <exception cref="LeaseUnavailableException">The sequence is busy, or holds a restore or a replacement not settled yet.</exception>
|
||||
/// <exception cref="IOException">An incoming file is missing, or a file could not move; nothing changed.</exception>
|
||||
internal async Task<ReplaceResult?> ReplaceAsync(Archive archive, Guid sequenceId, int? framesVersion, IReadOnlyList<FrameSwap> swaps, string? replacedBy,
|
||||
ConsumedEntry? consumed, Func<SequenceManifest, SequencePaths, CancellationToken, Task<bool>>? unchanged, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
ArgumentNullException.ThrowIfNull(swaps);
|
||||
if (swaps.Count == 0) throw new ArgumentException("No frame is swapped.", nameof(swaps));
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
if (await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) is not { } row || row.ArchiveId != archive.Id) return null;
|
||||
var folder = paths.Sequence(row.Folder);
|
||||
var had = row.Status;
|
||||
TrashEntry entry;
|
||||
SequenceManifest updated;
|
||||
bool indexed;
|
||||
await using (await _writer.LockAsync(paths, sequenceId, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var manifest = SequenceWriter.ReadLocked(folder, sequenceId, consumed?.Lease);
|
||||
EnsureSettled(folder);
|
||||
EnsureReplaced(folder);
|
||||
if (framesVersion is { } expected && manifest.Versions.Frames != expected) return null;
|
||||
var byId = manifest.Frames.ToDictionary(f => f.Id);
|
||||
var swapped = new Dictionary<Guid, SidecarFrame>();
|
||||
foreach (var swap in swaps)
|
||||
{
|
||||
if (!byId.TryGetValue(swap.FrameId, out var current) || current.Sha256 is null || swapped.ContainsKey(swap.FrameId)) return null;
|
||||
var file = new FileInfo(folder.File(current.File));
|
||||
if (!file.Exists || file.Length != current.Size) return null;
|
||||
var next = swap.Record(current);
|
||||
if (next.Sha256 is null) throw new ArgumentException($"The record that replaces {current.File} names no content.", nameof(swaps));
|
||||
swapped[swap.FrameId] = next;
|
||||
}
|
||||
if (unchanged is not null && !await unchanged(manifest, folder, cancellationToken).ConfigureAwait(false)) return null;
|
||||
foreach (var swap in swaps.Where(s => !File.Exists(paths.FromRelative(s.Incoming))))
|
||||
throw new FileNotFoundException($"The file that replaces {byId[swap.FrameId].File} is missing.", swap.Incoming);
|
||||
var inStep = await _indexer.InStepAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false);
|
||||
var photosChanged = !inStep && await _indexer.PhotosChangedAsync(archive, folder, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var leaving = manifest.Frames.Where(f => swapped.ContainsKey(f.Id)).ToList();
|
||||
var kept = manifest.Frames.Where(f => !swapped.ContainsKey(f.Id)).ToList();
|
||||
var photos = (await TrashedAsync(folder, leaving, kept, cancellationToken).ConfigureAwait(false))
|
||||
.Select(p => p with { Replacement = swapped[p.Frame.Id].Sha256!.ToLowerInvariant() }).ToList();
|
||||
var (incoming, names) = Incoming(folder, manifest, swaps, byId);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
updated = SequenceFrames.WithFrames(manifest,
|
||||
[.. manifest.Frames.Select(f => swapped.TryGetValue(f.Id, out var record) ? Swapped(f, record, names[f.Id]) : f)]) with
|
||||
{
|
||||
Status = manifest.Status & ~Uncovered,
|
||||
Removed = WithAliases(manifest.Removed, leaving, swapped, kept, now),
|
||||
};
|
||||
|
||||
var trash = Directory(paths);
|
||||
System.IO.Directory.CreateDirectory(trash);
|
||||
var name = EntryName(trash, sequenceId);
|
||||
var entryFolder = Path.Combine(trash, name);
|
||||
var recordPath = entryFolder + RecordExtension;
|
||||
var analysis = new FileInfo(folder.AnalysisPath);
|
||||
List<TrashedFile>? leftovers = analysis.Exists
|
||||
? [new TrashedFile(ArchiveLayout.MetaFolder + "/" + ArchiveLayout.AnalysisFile, AnalysisCopy, analysis.Length, null)]
|
||||
: null;
|
||||
var record = new PhotoTrashRecord(TrashKind.Replaced, sequenceId, row.DisplayTitle, row.Folder, photos,
|
||||
photos.Sum(p => p.Files.Sum(f => f.Size)) + (leftovers?.Sum(f => f.Size) ?? 0), now, replacedBy, leftovers);
|
||||
var outgoing = photos.SelectMany(p => p.Files).Select(f => new SwapMove(f.From, paths.ToRelative(Path.Combine(entryFolder, f.Path)))).ToList();
|
||||
var journal = new FrameReplaceJournal(manifest.Versions.Frames, paths.ToRelative(recordPath), paths.ToRelative(entryFolder), outgoing, incoming,
|
||||
analysis.Exists, consumed);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// The journal first: a crash from here until the sidecar is written puts every file back (ReadLocked).
|
||||
journal.Write(folder);
|
||||
// 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 movedOut = new List<SwapMove>();
|
||||
var movedIn = new List<SwapMove>();
|
||||
try
|
||||
{
|
||||
if (analysis.Exists) File.Copy(analysis.FullName, Path.Combine(entryFolder, AnalysisCopy), overwrite: false);
|
||||
foreach (var move in outgoing)
|
||||
{
|
||||
MoveFile(folder.File(move.Place), paths.FromRelative(move.Other));
|
||||
movedOut.Add(move);
|
||||
}
|
||||
foreach (var move in incoming)
|
||||
{
|
||||
MoveFile(paths.FromRelative(move.Other), folder.File(move.Place));
|
||||
movedIn.Add(move);
|
||||
}
|
||||
ManifestStore.WriteSequence(folder.ManifestPath, updated);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// A file is open elsewhere, or the sidecar cannot be written: what moved goes back, and nothing changed.
|
||||
Log.Warning("archive", $"{row.DisplayTitle}: the frames could not be replaced; the files that moved go back", ex);
|
||||
UndoReplace(folder, movedOut, movedIn, journal);
|
||||
throw;
|
||||
}
|
||||
CompleteReplace(folder, journal, consumed?.Lease);
|
||||
Log.Info("archive", $"{row.DisplayTitle}: {photos.Count} frame(s) replaced; the files they had are in 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, row.DisplayTitle).ConfigureAwait(false);
|
||||
DropProxies(folder, leaving);
|
||||
entry = Entry(archive.Id, name, record);
|
||||
}
|
||||
var sequence = await RowAsync(row, updated, indexed).ConfigureAwait(false);
|
||||
return new ReplaceResult(entry, sequence, had);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settles the replacement a crash interrupted (<see cref="FrameReplaceJournal"/>), if any; the caller holds the
|
||||
/// sequence's lease, and <paramref name="heldLease"/> when it holds a trash entry's lease too. While
|
||||
/// <paramref name="manifest"/> is at the journal's frames version the sidecar was not written: every file that moved
|
||||
/// goes back (one whose place is taken again stays, logged, and keeps the journal) and the new entry goes. Otherwise the
|
||||
/// replacement stands and is completed (<see cref="CompleteReplace"/>).
|
||||
/// </summary>
|
||||
internal static void RecoverReplace(SequencePaths sequence, SequenceManifest manifest, string? heldLease = null)
|
||||
{
|
||||
if (!File.Exists(sequence.ReplaceJournalPath)) return;
|
||||
if (FrameReplaceJournal.Read(sequence) is not { } journal)
|
||||
{
|
||||
FrameReplaceJournal.Delete(sequence);
|
||||
return;
|
||||
}
|
||||
if (manifest.Versions.Frames == journal.FramesVersion)
|
||||
{
|
||||
Log.Warning("archive", $"An interrupted frame replacement in {sequence.RelativeFolder} is undone");
|
||||
UndoReplace(sequence, journal.Out, journal.In, journal, onlyPresent: true);
|
||||
}
|
||||
else
|
||||
{
|
||||
Log.Warning("archive", $"An interrupted frame replacement in {sequence.RelativeFolder} is completed");
|
||||
CompleteReplace(sequence, journal, heldLease);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Refuses to go on while a replacement of <paramref name="sequence"/> is not settled after
|
||||
/// <see cref="SequenceWriter.ReadLocked"/> (the entry its files came from was busy): its journal is not written over.
|
||||
/// </summary>
|
||||
/// <exception cref="LeaseUnavailableException">The replacement is not settled; nothing was changed.</exception>
|
||||
internal static void EnsureReplaced(SequencePaths sequence)
|
||||
{
|
||||
if (!File.Exists(sequence.ReplaceJournalPath)) return;
|
||||
var lease = FrameReplaceJournal.Read(sequence)?.Consumed?.Lease ?? "replace";
|
||||
throw new LeaseUnavailableException(lease, LeaseFile.Holder(sequence.Archive.LocksDirectory, lease));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The incoming moves, each file under its name made free: every name the sequence's folders hold stays taken, those of
|
||||
/// the files that leave included, so no incoming file takes the place of one that leaves (a crash between the two is
|
||||
/// then undone without doubt), and so do the files of every frame and the names already given.
|
||||
/// </summary>
|
||||
private static (List<SwapMove> Moves, Dictionary<Guid, string> Names) Incoming(SequencePaths folder, SequenceManifest manifest, IReadOnlyList<FrameSwap> swaps,
|
||||
Dictionary<Guid, SidecarFrame> frames)
|
||||
{
|
||||
var taken = new HashSet<string>(FileRenames.ListPresent(folder, manifest), StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var frame in manifest.Frames) taken.Add(frame.File);
|
||||
var unique = new UniqueNames(taken);
|
||||
var moves = new List<SwapMove>();
|
||||
var names = new Dictionary<Guid, string>();
|
||||
foreach (var swap in swaps)
|
||||
{
|
||||
var file = unique.Claim(swap.Name(frames[swap.FrameId]), c => swap.Companions.All(t => !taken.Contains(StemOf(c) + t.Tail)));
|
||||
names[swap.FrameId] = file;
|
||||
moves.Add(new SwapMove(file, swap.Incoming));
|
||||
foreach (var companion in swap.Companions)
|
||||
{
|
||||
var to = StemOf(file) + companion.Tail;
|
||||
taken.Add(to);
|
||||
moves.Add(new SwapMove(to, companion.From));
|
||||
}
|
||||
}
|
||||
return (moves, names);
|
||||
}
|
||||
|
||||
/// <summary>A path without its extension (<c>originals/IMG_0001</c>): companions add their tail to it.</summary>
|
||||
private static string StemOf(string file) => file[..^Path.GetExtension(file).Length];
|
||||
|
||||
/// <summary>The frame's record after a swap: <paramref name="record"/> at the frame's id and index, under its new name, with its own user flags.</summary>
|
||||
private static SidecarFrame Swapped(SidecarFrame current, SidecarFrame record, string file) => record with
|
||||
{
|
||||
Id = current.Id,
|
||||
I = current.I,
|
||||
File = file,
|
||||
Sha256 = record.Sha256!.ToLowerInvariant(),
|
||||
Flags = (current.Flags & ~ContentFlags) | (record.Flags & ContentFlags),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The tombstones after a replacement: those of before but the ones of content that comes back, and one per content
|
||||
/// that leaves naming its replacement (<see cref="RemovalReason.Replaced"/>), unless a frame that stays holds it too.
|
||||
/// </summary>
|
||||
private static List<RemovedPhoto>? WithAliases(IReadOnlyList<RemovedPhoto>? before, List<SidecarFrame> leaving, Dictionary<Guid, SidecarFrame> swapped,
|
||||
List<SidecarFrame> kept, DateTimeOffset at)
|
||||
{
|
||||
var incoming = swapped.Values.Select(s => s.Sha256!).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var held = kept.Where(f => f.Sha256 is not null).Select(f => f.Sha256!).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var tombstones = new Dictionary<string, RemovedPhoto>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var tombstone in before ?? [])
|
||||
{
|
||||
if (!incoming.Contains(tombstone.Sha256)) tombstones[tombstone.Sha256] = tombstone;
|
||||
}
|
||||
foreach (var frame in leaving)
|
||||
{
|
||||
var old = frame.Sha256!.ToLowerInvariant();
|
||||
var replacement = swapped[frame.Id].Sha256!.ToLowerInvariant();
|
||||
if (old == replacement || held.Contains(old)) continue;
|
||||
tombstones[old] = new RemovedPhoto { Sha256 = old, Replacement = replacement, Reason = RemovalReason.Replaced, At = at };
|
||||
}
|
||||
return tombstones.Count == 0 ? null : [.. tombstones.Values];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts back what a replacement moved before its sidecar was written (incoming files back where they came from, the
|
||||
/// files that left back into the sequence) and removes its entry and journal. With <paramref name="onlyPresent"/> (a
|
||||
/// recovery) a file not at its new place, or whose old place is taken, is left where it is (logged); the journal and the
|
||||
/// entry then stay, and the entry is listed under its record's own name. A failure (logged) keeps the journal, and the
|
||||
/// next writer of the sequence tries again.
|
||||
/// </summary>
|
||||
private static void UndoReplace(SequencePaths folder, IReadOnlyList<SwapMove> movedOut, IReadOnlyList<SwapMove> movedIn, FrameReplaceJournal journal,
|
||||
bool onlyPresent = false)
|
||||
{
|
||||
var archive = folder.Archive;
|
||||
var recordPath = archive.FromRelative(journal.Record);
|
||||
var entryFolder = archive.FromRelative(journal.Folder);
|
||||
var stuck = 0;
|
||||
try
|
||||
{
|
||||
foreach (var move in movedIn.Reverse())
|
||||
{
|
||||
if (!Back(folder.File(move.Place), archive.FromRelative(move.Other))) stuck++;
|
||||
}
|
||||
foreach (var move in movedOut.Reverse())
|
||||
{
|
||||
if (!Back(archive.FromRelative(move.Other), folder.File(move.Place))) stuck++;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Error("archive", $"A frame replacement in {folder.RelativeFolder} could not be undone; the journal puts it back later", ex);
|
||||
return;
|
||||
}
|
||||
if (stuck > 0)
|
||||
{
|
||||
// What could not go back is in the entry, listed, restorable and erasable like any entry.
|
||||
FrameRemovalJournal.Publish(recordPath);
|
||||
FrameReplaceJournal.Delete(folder);
|
||||
return;
|
||||
}
|
||||
var copy = Path.Combine(entryFolder, AnalysisCopy);
|
||||
if (journal.Analysis && File.Exists(copy)) File.Delete(copy);
|
||||
if (File.Exists(FrameRemovalJournal.PendingRecord(recordPath))) File.Delete(FrameRemovalJournal.PendingRecord(recordPath));
|
||||
FrameRemovalJournal.RemoveEmpty(entryFolder);
|
||||
FrameReplaceJournal.Delete(folder);
|
||||
|
||||
bool Back(string from, string to)
|
||||
{
|
||||
if (!File.Exists(from)) return !onlyPresent || File.Exists(to) || Gone(from, to);
|
||||
if (File.Exists(to))
|
||||
{
|
||||
Log.Warning("archive", $"{to} is there again; {from} stays where it is");
|
||||
return false;
|
||||
}
|
||||
MoveFile(from, to);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Neither here nor there: nothing to put back for this file.
|
||||
static bool Gone(string from, string to)
|
||||
{
|
||||
Log.Warning("archive", $"{from} is not there to go back to {to}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Completes a replacement whose sidecar is written: its entry is listed under its record's own name, the entry its
|
||||
/// incoming files came from (if any) is settled under its lease (the photos swapped leave its record, its copy of
|
||||
/// <c>analysis.json</c> goes back into the sequence, and an entry left without anything goes), and the journal goes. An
|
||||
/// entry busy now (or a failure, logged) keeps the journal for the next writer of the sequence.
|
||||
/// </summary>
|
||||
private static void CompleteReplace(SequencePaths folder, FrameReplaceJournal journal, string? heldLease)
|
||||
{
|
||||
var archive = folder.Archive;
|
||||
try
|
||||
{
|
||||
FrameRemovalJournal.Publish(archive.FromRelative(journal.Record));
|
||||
if (journal.Consumed is { } consumed && !Settle(folder, consumed, heldLease)) return;
|
||||
FrameReplaceJournal.Delete(folder);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"A frame replacement in {folder.RelativeFolder} is not settled yet; the next writer of the sequence settles it", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Settles the entry a replacement took its files from (<see cref="CompleteReplace"/>); false while it is busy.</summary>
|
||||
private static bool Settle(SequencePaths folder, ConsumedEntry consumed, string? heldLease)
|
||||
{
|
||||
var archive = folder.Archive;
|
||||
LeaseFile? taken = null;
|
||||
if (consumed.Lease != heldLease)
|
||||
{
|
||||
taken = LeaseFile.TryAcquire(archive.LocksDirectory, consumed.Lease, SettleOwner);
|
||||
if (taken is null)
|
||||
{
|
||||
Log.Info("archive", $"A frame replacement in {folder.RelativeFolder} waits: the trash entry its files came from is busy");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
using var held = taken;
|
||||
var recordPath = archive.FromRelative(consumed.Record);
|
||||
var entryFolder = archive.FromRelative(consumed.Folder);
|
||||
// The copy of the analysis of the frames that came back takes the place of the analysis of the frames that went
|
||||
// (the new entry keeps a copy of that one).
|
||||
if (consumed.Analysis is { } copy && File.Exists(archive.FromRelative(copy)))
|
||||
{
|
||||
System.IO.Directory.CreateDirectory(folder.MetaDirectory);
|
||||
File.Move(archive.FromRelative(copy), folder.AnalysisPath, overwrite: true);
|
||||
}
|
||||
if (ReadRecord(recordPath) is { } record)
|
||||
{
|
||||
var frames = consumed.Frames.ToHashSet();
|
||||
var leftovers = record.Leftovers?.Where(f => File.Exists(Path.Combine(entryFolder, f.Path))).ToList();
|
||||
Rewrite(recordPath, entryFolder, record with
|
||||
{
|
||||
Photos = [.. record.Photos.Where(p => !frames.Contains(p.Frame.Id))],
|
||||
Leftovers = leftovers is { Count: > 0 } ? leftovers : null,
|
||||
});
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the proxies of frames whose file was replaced: a proxy carries its frame's capture time, which a converted file
|
||||
/// keeps, so the proxy pass would take the old one for current. A failure is logged; the pass then reuses what is left.
|
||||
/// </summary>
|
||||
private static void DropProxies(SequencePaths folder, IReadOnlyList<SidecarFrame> frames)
|
||||
{
|
||||
if (!System.IO.Directory.Exists(folder.Proxies)) return;
|
||||
try
|
||||
{
|
||||
foreach (var frame in frames)
|
||||
{
|
||||
var proxy = folder.Proxy(frame.I);
|
||||
if (File.Exists(proxy)) File.Delete(proxy);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"Proxies of the frames replaced in {folder.RelativeFolder} could not be deleted; the proxy pass may keep them", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether every photo of a replaced entry may swap back into its sequence: each one's frame is there with the content
|
||||
/// that replaced it (its file re-hashed now) and still names the photo as its source.
|
||||
/// </summary>
|
||||
private static async Task<bool> SwappableAsync(PhotoTrashRecord record, SequenceManifest manifest, SequencePaths folder, CancellationToken cancellationToken)
|
||||
{
|
||||
var frames = manifest.Frames.ToDictionary(f => f.Id);
|
||||
foreach (var photo in record.Photos)
|
||||
{
|
||||
if (photo.Replacement is not { } replacement || photo.Frame.Sha256 is not { } original || !frames.TryGetValue(photo.Frame.Id, out var frame)) return false;
|
||||
if (!string.Equals(frame.Sha256, replacement, StringComparison.OrdinalIgnoreCase)
|
||||
|| !string.Equals(frame.Source?.Sha256, original, StringComparison.OrdinalIgnoreCase)) return false;
|
||||
var file = new FileInfo(folder.File(frame.File));
|
||||
if (!file.Exists || file.Length != frame.Size
|
||||
|| !string.Equals(await ContentHash.Sha256Async(file.FullName, null, cancellationToken).ConfigureAwait(false), replacement, StringComparison.OrdinalIgnoreCase))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The undo of a conversion: the originals of a replaced entry take their frames' place again
|
||||
/// (<see cref="ReplaceAsync"/>), and the files that replaced them go to the trash as a replaced entry in turn. Null,
|
||||
/// nothing touched, when a frame changed since (<see cref="SwappableAsync"/>) or the sequence did.
|
||||
/// </summary>
|
||||
/// <param name="lease">The entry's lease, which the caller holds.</param>
|
||||
private async Task<ReplaceResult?> SwapBackAsync(Archive archive, ArchivePaths paths, Sequence sequence, PhotoTrashRecord record, string recordPath,
|
||||
string entryFolder, string lease, CancellationToken cancellationToken)
|
||||
{
|
||||
if (record.Photos.Count == 0 || record.Photos.Any(p => p.Files.Count == 0 || p.Frame.Sha256 is null || p.Replacement is null)) return null;
|
||||
var swaps = record.Photos.Select(p => new FrameSwap(p.Frame.Id, paths.ToRelative(Path.Combine(entryFolder, p.Files[0].Path)),
|
||||
[.. p.Files.Skip(1).Select(c => new IncomingCompanion(paths.ToRelative(Path.Combine(entryFolder, c.Path)), FrameCompanions.Tail(c.From, p.Files[0].From)))],
|
||||
_ => p.Files[0].From, _ => p.Frame)).ToList();
|
||||
var copy = Path.Combine(entryFolder, AnalysisCopy);
|
||||
var analysis = record.Leftovers?.Any(f => f.Path == AnalysisCopy) == true && File.Exists(copy) ? paths.ToRelative(copy) : null;
|
||||
var consumed = new ConsumedEntry(paths.ToRelative(recordPath), paths.ToRelative(entryFolder), lease, [.. record.Photos.Select(p => p.Frame.Id)], analysis);
|
||||
return await ReplaceAsync(archive, sequence.Id, null, swaps, null, consumed, (manifest, folder, ct) => SwappableAsync(record, manifest, folder, ct),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A replaced entry's record without its copy of <c>analysis.json</c> once no photo is left in it (all of them filed into
|
||||
/// a new sequence, which is analysed again): the copy, derived from those photos, goes with the entry.
|
||||
/// </summary>
|
||||
private static PhotoTrashRecord WithoutAnalysisCopy(string entryFolder, PhotoTrashRecord record)
|
||||
{
|
||||
if (record.Kind != TrashKind.Replaced || record.Photos.Count > 0 || record.Leftovers?.Any(f => f.Path == AnalysisCopy) != true) return record;
|
||||
var copy = Path.Combine(entryFolder, AnalysisCopy);
|
||||
if (File.Exists(copy)) File.Delete(copy);
|
||||
var leftovers = record.Leftovers.Where(f => f.Path != AnalysisCopy).ToList();
|
||||
return record with { Leftovers = leftovers.Count > 0 ? leftovers : null };
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,10 @@ public sealed partial class FrameTrash
|
||||
/// (<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.
|
||||
/// each photo filed; a cancel there stops before the next photo. The entry goes once nothing is left in it. An entry of
|
||||
/// <see cref="TrashKind.Replaced"/> (originals a conversion replaced, owner review 2, R7) swaps back instead while every
|
||||
/// converted frame is as the conversion left it (<see cref="SwapBackAsync"/>: the converted files go to the trash as a
|
||||
/// replaced entry in turn); otherwise its originals come back as a new sequence.
|
||||
/// </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>
|
||||
@@ -69,6 +72,19 @@ public sealed partial class FrameTrash
|
||||
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();
|
||||
if (record.Kind == TrashKind.Replaced)
|
||||
{
|
||||
// The undo of a conversion: while every converted frame is as the conversion left it, the originals take their
|
||||
// place again; otherwise they come back as a new sequence, beside the converted one.
|
||||
if (into is not null && kept.Count == 0
|
||||
&& await SwapBackAsync(archive, paths, into, record, recordPath, entryFolder, lease, cancellationToken).ConfigureAwait(false) is { } swapped)
|
||||
{
|
||||
Log.Info("archive", $"{record.SequenceTitle}: {record.Photos.Count} converted frame(s) swapped back to their originals");
|
||||
await QueueAsync(followUps, archive, swapped.Sequence, swapped.Had, CancellationToken.None).ConfigureAwait(false);
|
||||
return new PhotoRestoreResult(swapped.Sequence, record.Photos.Count, [], false) { Kind = TrashKind.Replaced };
|
||||
}
|
||||
into = null;
|
||||
}
|
||||
var had = into?.Status ?? SequenceStatus.None;
|
||||
PhotoRestoreResult result;
|
||||
List<Stay> stays;
|
||||
@@ -83,7 +99,8 @@ public sealed partial class FrameTrash
|
||||
{
|
||||
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) });
|
||||
Rewrite(recordPath, entryFolder, WithoutAnalysisCopy(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);
|
||||
@@ -94,7 +111,11 @@ public sealed partial class FrameTrash
|
||||
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))] };
|
||||
var all = result with
|
||||
{
|
||||
Kept = [.. stays.Select(s => new KeptPhoto(s.Photo.Frame.Original ?? Path.GetFileName(s.Photo.Frame.File), s.Reason))],
|
||||
Kind = record.Kind,
|
||||
};
|
||||
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);
|
||||
|
||||
@@ -89,7 +89,11 @@ public sealed record KeptPhoto(string Name, KeptReason Reason)
|
||||
/// 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);
|
||||
public sealed record PhotoRestoreResult(Sequence Sequence, int Restored, IReadOnlyList<KeptPhoto> Kept, bool NewSequence)
|
||||
{
|
||||
/// <summary>The kind of entry restored: deleted photos, or originals a conversion replaced (<see cref="TrashKind.Replaced"/>).</summary>
|
||||
public TrashKind Kind { get; init; } = TrashKind.Photos;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deleting photos of a sequence without erasing anything (owner review 2, R6; BRIEF §0.2 rule 8): <see cref="PlanDeleteAsync"/>
|
||||
@@ -611,10 +615,13 @@ public sealed partial class FrameTrash
|
||||
}
|
||||
}
|
||||
|
||||
/// <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)
|
||||
/// <summary>
|
||||
/// What the frames of <paramref name="sequence"/> need again after they changed, by the statuses it
|
||||
/// <paramref name="had"/>: the light analysis, a background deep analysis when it had one, and the thumbnails and proxies
|
||||
/// the host keeps (always on a server; on a desktop those it had).
|
||||
/// </summary>
|
||||
internal List<ArchiveJobRequest> FollowUps(Archive archive, Sequence sequence, SequenceStatus had)
|
||||
{
|
||||
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 });
|
||||
@@ -622,6 +629,15 @@ public sealed partial class FrameTrash
|
||||
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));
|
||||
return requests;
|
||||
}
|
||||
|
||||
/// <summary>Queues what the frames need again (<see cref="FollowUps"/>), 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;
|
||||
var requests = FollowUps(archive, sequence, had);
|
||||
try
|
||||
{
|
||||
foreach (var request in requests)
|
||||
@@ -676,7 +692,8 @@ public sealed partial class FrameTrash
|
||||
|
||||
/// <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.
|
||||
/// sequence they came from. <see cref="TrashKind.Replaced"/> entries (a conversion, R7) name each photo's replacement and
|
||||
/// keep a copy of the sequence's <c>analysis.json</c> as a leftover (<see cref="FrameTrash.AnalysisCopy"/>).
|
||||
/// </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>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Chronos.Core.Conversion;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
@@ -51,6 +52,18 @@ public sealed record MoveJobParameters(string? FolderTemplate, string? FileTempl
|
||||
/// <summary>A sequence of a <see cref="MoveJobParameters"/> (a job queued by an earlier build also names a frames version, which is ignored).</summary>
|
||||
public sealed record MoveSequence(Guid Id);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Convert"/> (owner review 2, R7): targets = the sequences converted, so the jobs that would touch them
|
||||
/// wait; the archive, the target format and JPEG quality, the mode chosen for this run, the sequences of the confirmed plan
|
||||
/// in its order with the frames version each was planned at, and the plan's fingerprint
|
||||
/// (<see cref="ConvertPlan.Fingerprint"/>). A sequence whose frames changed since is left as it is and reported.
|
||||
/// </summary>
|
||||
public sealed record ConvertJobParameters(Guid ArchiveId, ConvertTarget Target, int Quality, ConvertMode Mode, IReadOnlyList<ConvertSequence> Sequences,
|
||||
string Fingerprint);
|
||||
|
||||
/// <summary>A sequence of a <see cref="ConvertJobParameters"/> and the frames version it was planned at.</summary>
|
||||
public sealed record ConvertSequence(Guid Id, int FramesVersion);
|
||||
|
||||
/// <summary>A job ready to enqueue.</summary>
|
||||
public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets, string? Label, string? ParametersJson, JobPriority Priority);
|
||||
|
||||
@@ -64,6 +77,9 @@ public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets
|
||||
[JsonSerializable(typeof(CleanupParameters))]
|
||||
[JsonSerializable(typeof(EmptyTrashParameters))]
|
||||
[JsonSerializable(typeof(MoveJobParameters))]
|
||||
[JsonSerializable(typeof(ConvertJobParameters))]
|
||||
[JsonSerializable(typeof(ConvertJournal))]
|
||||
[JsonSerializable(typeof(StagedLine))]
|
||||
[JsonSerializable(typeof(CardProfile))]
|
||||
internal sealed partial class ArchiveJobJson : JsonSerializerContext
|
||||
{
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
|
||||
namespace Chronos.Data.Archiving.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Convert"/>: a mass conversion (owner review 2, R7; BRIEF §12.5) of the sequences of a confirmed plan
|
||||
/// (<see cref="ConvertJobParameters"/>) through <see cref="MassConverter"/>, which plans again, refuses when the archive's
|
||||
/// volume lacks the space, and converts one sequence at a time, each all or nothing; its journal makes every stage
|
||||
/// resumable. Progress counts photos; the checkpoint only marks a resume, the journal says where. Each sequence whose frames
|
||||
/// were replaced is told as <c>converted</c>, each new sequence as <c>created</c> (<see cref="ArchiveServiceOptions.SequenceChanged"/>),
|
||||
/// and the passes they need (light analysis, a deep one when the source had it, thumbnails and proxies) are queued as
|
||||
/// follow-ups. Sequences left as they were (changed after the plan, busy, a photo that failed) are logged and fail the job
|
||||
/// at the end, after the others are converted; a retry tries them again.
|
||||
/// </summary>
|
||||
internal sealed class ConvertJobHandler(ChronosDatabase db, MassConverter converter, Func<Guid, string, CancellationToken, Task>? sequenceChanged) : IJobHandler
|
||||
{
|
||||
/// <summary>The change told about a sequence whose frames a conversion replaced.</summary>
|
||||
public const string Converted = "converted";
|
||||
|
||||
/// <summary>The change told about a sequence a conversion made.</summary>
|
||||
public const string Created = "created";
|
||||
|
||||
private const string Checkpoint = "convert";
|
||||
|
||||
public JobKind Kind => JobKind.Convert;
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
{
|
||||
var parameters = (context.Job.ParametersJson is { Length: > 0 } json ? JsonSerializer.Deserialize(json, ArchiveJobJson.Default.ConvertJobParameters) : null)
|
||||
?? throw new InvalidOperationException($"Convert job {context.Job.Id} has no plan.");
|
||||
if (parameters.Fingerprint.Length == 0) throw new InvalidOperationException($"Convert job {context.Job.Id} has no confirmed plan.");
|
||||
var archive = await db.Archives.GetAsync(parameters.ArchiveId, context.Cancellation).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException($"Convert job {context.Job.Id} does not name a known archive.");
|
||||
var by = context.Job.CreatedBy is { } user ? (await db.Users.GetAsync(user, context.Cancellation).ConfigureAwait(false))?.Username : null;
|
||||
var result = await converter.RunAsync(archive, parameters, context.Job.Id, by, new ConvertCallbacks(
|
||||
(done, total) => context.ReportAsync(done, total),
|
||||
(done, total) => context.CheckpointAsync(Checkpoint, done, total),
|
||||
context.Log), context.Cancellation).ConfigureAwait(false);
|
||||
await QueueAsync(context, result).ConfigureAwait(false);
|
||||
context.Log(Loc.L("Archive.Log.ConvertDone", result.Sequences.Count(s => s.Outcome == ConvertOutcome.Converted),
|
||||
result.Sequences.Count(s => s.Outcome == ConvertOutcome.Created), result.Frames));
|
||||
await TellAsync(result).ConfigureAwait(false);
|
||||
var kept = result.Kept.Count();
|
||||
if (kept > 0) throw new InvalidOperationException(Loc.Plural("Archive.Error.ConvertKept", kept));
|
||||
}
|
||||
|
||||
/// <summary>Queues what the converted sequences need, each kind once per sequence; a failure is logged, never passed on.</summary>
|
||||
private async Task QueueAsync(JobContext context, ConvertResult result)
|
||||
{
|
||||
foreach (var request in result.FollowUps)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (request.Targets.Count > 0 && await db.Jobs.IsQueuedAsync(request.Kind, request.Targets[0], CancellationToken.None).ConfigureAwait(false)) continue;
|
||||
await context.EnqueueFollowUpAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority).ConfigureAwait(false);
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning("archive", $"{request.Label}: the passes its converted frames need were not queued; the next scan queues them", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Tells each sequence changed or made; a failure is logged, never passed on to the job.</summary>
|
||||
private async Task TellAsync(ConvertResult result)
|
||||
{
|
||||
if (sequenceChanged is null) return;
|
||||
foreach (var sequence in result.Sequences)
|
||||
{
|
||||
var (id, change) = sequence.Outcome switch
|
||||
{
|
||||
ConvertOutcome.Converted => (sequence.SequenceId, Converted),
|
||||
ConvertOutcome.Created when sequence.NewSequenceId is { } made => (made, Created),
|
||||
_ => (Guid.Empty, string.Empty),
|
||||
};
|
||||
if (id == Guid.Empty) continue;
|
||||
try
|
||||
{
|
||||
await sequenceChanged(id, change, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning("archive", $"The change of sequence {id} was not told", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,745 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Conversion;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Metadata;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>What a conversion did with one sequence (owner review 2, R7).</summary>
|
||||
public enum ConvertOutcome
|
||||
{
|
||||
/// <summary>Its frames were replaced by the converted files (<see cref="ConvertMode.Replace"/>).</summary>
|
||||
Converted,
|
||||
|
||||
/// <summary>The converted files went into a new sequence (<see cref="ConvertMode.NewSequence"/>).</summary>
|
||||
Created,
|
||||
|
||||
/// <summary>It had nothing to convert.</summary>
|
||||
Nothing,
|
||||
|
||||
/// <summary>Left as it was: its frames changed after the plan, or it is no longer in the archive.</summary>
|
||||
Changed,
|
||||
|
||||
/// <summary>Left as it was: it is busy, or its sidecar cannot be read.</summary>
|
||||
Blocked,
|
||||
|
||||
/// <summary>Left as it was: a photo could not be converted (all or nothing), or the files could not move.</summary>
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>One sequence of a conversion: what happened, how many photos, the new sequence when one was made, and the failure.</summary>
|
||||
public sealed record ConvertSequenceResult(Guid SequenceId, string Title, ConvertOutcome Outcome, int Frames, Guid? NewSequenceId = null, string? Error = null)
|
||||
{
|
||||
/// <summary>Whether the sequence is done with: converted, made, or with nothing to convert.</summary>
|
||||
public bool Final => Outcome is ConvertOutcome.Converted or ConvertOutcome.Created or ConvertOutcome.Nothing;
|
||||
}
|
||||
|
||||
/// <summary>What a conversion did, and the passes the sequences it changed or made need (to queue as follow-ups).</summary>
|
||||
public sealed record ConvertResult(IReadOnlyList<ConvertSequenceResult> Sequences, IReadOnlyList<ArchiveJobRequest> FollowUps)
|
||||
{
|
||||
/// <summary>Photos converted, into their sequence or a new one.</summary>
|
||||
public int Frames => Sequences.Where(s => s.Outcome is ConvertOutcome.Converted or ConvertOutcome.Created).Sum(s => s.Frames);
|
||||
|
||||
/// <summary>The sequences left as they were (changed, blocked, failed).</summary>
|
||||
public IEnumerable<ConvertSequenceResult> Kept => Sequences.Where(s => !s.Final);
|
||||
}
|
||||
|
||||
/// <summary>How a running conversion reports: progress in photos, a checkpoint after each sequence, and job log lines.</summary>
|
||||
internal sealed record ConvertCallbacks(Func<long, long, ValueTask> Progress, Func<long, long, ValueTask> Checkpoint, Action<string> Log);
|
||||
|
||||
/// <summary>
|
||||
/// Mass conversion of existing sequences (owner review 2, R7; BRIEF §12.5): <see cref="PlanAsync(Archive, IReadOnlyList{Guid}, ConvertOptions, ConvertMode, CancellationToken)"/>
|
||||
/// is the dry run (<see cref="ConvertPlanner"/> per sequence, what blocks it, the space needed against the free space of
|
||||
/// the archive's volume, <see cref="ArchiveServiceOptions.FreeSpace"/>), and a <see cref="JobKind.Convert"/> job applies the
|
||||
/// confirmed plan one sequence at a time. Stage A, without a lease: each photo is hashed against its record and converted
|
||||
/// (<see cref="FrameConverter"/>, several at once as the host's parallelism and memory allow) into
|
||||
/// <c>.chronos/staging/convert-<job>/<sequence>/</c>, each staged file appended to the job's journal
|
||||
/// (<see cref="ConvertJournal"/>), so a resumed job keeps the staged files whose hash still verifies. Stage B, all or nothing,
|
||||
/// under the sequence's lease and while its frames are still at the version planned: <see cref="ConvertMode.Replace"/>
|
||||
/// swaps the frames' files (<see cref="FrameTrash.ReplaceAsync"/>: the originals into one trash entry of kind
|
||||
/// <see cref="TrashKind.Replaced"/>, same ids and indices, tombstones naming the replacements); <see cref="ConvertMode.NewSequence"/>
|
||||
/// files the converted copies into a new sequence through the archive ingest (session key <c>convert:<job>:<source></c>,
|
||||
/// so a resume finds it again), titled "title (FORMAT)", with the source's tags, rating, notes and project, the source left
|
||||
/// as it is. A sequence that changed after the plan, is busy, or has a photo that fails is left as it was and reported.
|
||||
/// </summary>
|
||||
public sealed class MassConverter
|
||||
{
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly SequenceWriter _writer;
|
||||
private readonly ArchiveIngest _ingest;
|
||||
private readonly FrameTrash _frames;
|
||||
private readonly SequenceTrash _trash;
|
||||
private readonly ArchiveService _service;
|
||||
|
||||
internal MassConverter(ChronosDatabase db, SequenceWriter writer, ArchiveIngest ingest, FrameTrash frames, SequenceTrash trash, ArchiveService service)
|
||||
{
|
||||
_db = db;
|
||||
_writer = writer;
|
||||
_ingest = ingest;
|
||||
_frames = frames;
|
||||
_trash = trash;
|
||||
_service = service;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The dry run of converting <paramref name="sequenceIds"/> of <paramref name="archive"/>: per sequence the frames
|
||||
/// converted and those skipped with why, the bytes before and after, what blocks it (busy, offline, unreadable); the
|
||||
/// space needed and free; the fingerprint a confirmation sends back. Reads only.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">The options are invalid, or a sequence is not in the archive.</exception>
|
||||
public Task<ConvertPlan> PlanAsync(Archive archive, IReadOnlyList<Guid> sequenceIds, ConvertOptions options, ConvertMode mode,
|
||||
CancellationToken cancellationToken = default) => PlanAsync(archive, sequenceIds, options, mode, null, cancellationToken);
|
||||
|
||||
/// <param name="job">The job asking (a conversion planning again): what it holds does not make its sequences busy.</param>
|
||||
internal async Task<ConvertPlan> PlanAsync(Archive archive, IReadOnlyList<Guid> sequenceIds, ConvertOptions options, ConvertMode mode, Guid? job,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
ArgumentNullException.ThrowIfNull(sequenceIds);
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
if (!options.IsValid) throw new ArgumentException("Unknown target or a quality outside 1–100.", nameof(options));
|
||||
if (!Enum.IsDefined(mode)) throw new ArgumentException($"Unknown mode {mode}.", nameof(mode));
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var online = ArchiveVolume.Probe(paths) == ArchiveAvailability.Online;
|
||||
var busy = await _trash.BusyAsync(job, cancellationToken).ConfigureAwait(false);
|
||||
var plans = new List<ConvertSequencePlan>();
|
||||
foreach (var id in sequenceIds.Distinct())
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var row = await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
if (row is null || row.ArchiveId != archive.Id) throw new ArgumentException($"Sequence {id} is not in archive {archive.Name}.", nameof(sequenceIds));
|
||||
plans.Add(await PlanOneAsync(paths, row, online, busy.Contains(id) || busy.Contains(archive.Id), options, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
var estimated = plans.Where(p => p.Converts).Sum(p => p.BytesAfter);
|
||||
return new ConvertPlan(archive.Id, options, mode, plans, new ConvertSpace(ConvertPlanner.Required(estimated), FreeSpace(paths)));
|
||||
}
|
||||
|
||||
private async Task<ConvertSequencePlan> PlanOneAsync(ArchivePaths paths, Sequence row, bool online, bool busy, ConvertOptions options,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
List<ConvertBlock> blocked = [];
|
||||
if (!online) blocked.Add(ConvertBlock.Offline);
|
||||
if (busy) blocked.Add(ConvertBlock.Busy);
|
||||
var empty = new ConvertSequencePlan(row.Id, row.DisplayTitle, row.Folder, row.FramesVersion, [], [], blocked);
|
||||
// Created without photos (no folder yet), or nothing to read while offline.
|
||||
if (!online || row.FrameCount == 0 && ArchiveIngest.AwaitsFolder(row, paths)) return empty;
|
||||
var folder = paths.Sequence(row.Folder);
|
||||
if (Read(folder, row.Id) is not { } manifest) return empty with { Blocked = [.. blocked, ConvertBlock.Unreadable] };
|
||||
var decoder = _writer.Options.Decoder;
|
||||
var plan = await Task.Run(() => ConvertPlanner.Plan(manifest, folder, FileRenames.ListPresent(folder, manifest), options, decoder, row.DisplayTitle),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return plan with { Blocked = blocked };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies a confirmed conversion (<see cref="ConvertJobParameters"/>) as the job <paramref name="jobId"/>: plans again,
|
||||
/// refuses when the archive's volume lacks the space the photos still to convert need, then converts each sequence that
|
||||
/// still fits the plan (stage A, then stage B), resuming from the job's journal. Sequences left as they were are in the
|
||||
/// result; the journal stays while there are any, so a retry tries them again and knows what was done.
|
||||
/// </summary>
|
||||
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only; the job resumes where it stopped.</exception>
|
||||
/// <exception cref="IOException">The volume lacks the space (<c>Archive.Error.ConvertSpace</c>); nothing was converted since.</exception>
|
||||
internal async Task<ConvertResult> RunAsync(Archive archive, ConvertJobParameters parameters, Guid jobId, string? createdBy, ConvertCallbacks callbacks,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
ArgumentNullException.ThrowIfNull(parameters);
|
||||
ArgumentNullException.ThrowIfNull(callbacks);
|
||||
var options = new ConvertOptions(parameters.Target, parameters.Quality);
|
||||
if (!options.IsValid || !Enum.IsDefined(parameters.Mode)) throw new InvalidOperationException($"Convert job {jobId} has invalid options.");
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
var journal = ConvertJournal.Read(paths, jobId) ?? new ConvertJournal { JobId = jobId };
|
||||
var steps = parameters.Sequences.DistinctBy(s => s.Id).ToList();
|
||||
// What is still to do: every sequence not final in an earlier attempt that is still in the archive.
|
||||
var rows = new Dictionary<Guid, Sequence>();
|
||||
foreach (var step in steps.Where(s => journal.Of(s.Id)?.Final != true))
|
||||
{
|
||||
if (await _db.Sequences.GetAsync(step.Id, cancellationToken).ConfigureAwait(false) is { } row && row.ArchiveId == archive.Id) rows[step.Id] = row;
|
||||
}
|
||||
var plan = await PlanAsync(archive, [.. rows.Keys], options, parameters.Mode, jobId, cancellationToken).ConfigureAwait(false);
|
||||
var plans = plan.Sequences.ToDictionary(p => p.SequenceId);
|
||||
var versions = steps.ToDictionary(s => s.Id, s => s.FramesVersion);
|
||||
var runnable = plan.Sequences.Where(p => p.Converts && p.FramesVersion == versions[p.SequenceId]).ToList();
|
||||
var staged = journal.Staged(paths);
|
||||
var stagedBytes = runnable.Sum(p => staged.Of(p.SequenceId, p.FramesVersion).Sum(s => s.Size));
|
||||
var space = new ConvertSpace(ConvertPlanner.Required(Math.Max(0, runnable.Sum(p => p.BytesAfter) - stagedBytes)), FreeSpace(paths));
|
||||
if (runnable.Count > 0 && !space.Enough)
|
||||
throw new IOException(Loc.L("Archive.Error.ConvertSpace", Gigabytes(space.Required), Gigabytes(space.Free ?? 0)));
|
||||
var progress = new Progress(runnable.Sum(p => p.Frames.Count), runnable.Sum(p => staged.Of(p.SequenceId, p.FramesVersion).Count));
|
||||
await callbacks.Progress(progress.Done, progress.Total).ConfigureAwait(false);
|
||||
|
||||
var results = new List<ConvertSequenceResult>();
|
||||
var followUps = new List<ArchiveJobRequest>();
|
||||
foreach (var step in steps)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var noted = journal.Of(step.Id);
|
||||
ConvertSequenceResult result;
|
||||
if (noted?.Final == true)
|
||||
{
|
||||
result = new ConvertSequenceResult(step.Id, noted.Title ?? step.Id.ToString(), noted.Outcome!.Value, noted.Frames, noted.NewSequenceId);
|
||||
}
|
||||
else if (!rows.TryGetValue(step.Id, out var row) || !plans.TryGetValue(step.Id, out var planned))
|
||||
{
|
||||
result = new ConvertSequenceResult(step.Id, step.Id.ToString(), ConvertOutcome.Changed, 0);
|
||||
}
|
||||
else if (planned.Blocked.Contains(ConvertBlock.Offline))
|
||||
{
|
||||
throw new ArchiveOfflineException(paths.Root, ArchiveVolume.Probe(paths));
|
||||
}
|
||||
else if (planned.FramesVersion != step.FramesVersion)
|
||||
{
|
||||
// Replaced already, by this job before a crash, or changed by someone else since the plan.
|
||||
if (parameters.Mode == ConvertMode.Replace && ReplacedEarlier(paths, row, staged.Of(step.Id, step.FramesVersion)) is { } frames)
|
||||
{
|
||||
result = new ConvertSequenceResult(step.Id, row.DisplayTitle, ConvertOutcome.Converted, frames);
|
||||
followUps.AddRange(_frames.FollowUps(archive, row, row.Status));
|
||||
}
|
||||
else
|
||||
{
|
||||
result = new ConvertSequenceResult(step.Id, row.DisplayTitle, ConvertOutcome.Changed, 0);
|
||||
}
|
||||
}
|
||||
else if (planned.Blocked.Count > 0)
|
||||
{
|
||||
result = new ConvertSequenceResult(step.Id, row.DisplayTitle, ConvertOutcome.Blocked, 0);
|
||||
}
|
||||
else if (planned.Frames.Count == 0)
|
||||
{
|
||||
result = new ConvertSequenceResult(step.Id, row.DisplayTitle, ConvertOutcome.Nothing, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
(result, var queued) = await ConvertOneAsync(archive, paths, row, planned, options, parameters.Mode, jobId, createdBy, journal, staged, progress,
|
||||
callbacks, cancellationToken).ConfigureAwait(false);
|
||||
followUps.AddRange(queued);
|
||||
}
|
||||
results.Add(result);
|
||||
journal.Note(result);
|
||||
journal.Write(paths);
|
||||
if (!result.Final) DeleteStaging(StagingOf(paths, jobId, step.Id));
|
||||
Log(callbacks, result);
|
||||
await callbacks.Checkpoint(progress.Done, progress.Total).ConfigureAwait(false);
|
||||
}
|
||||
DeleteStaging(Path.Combine(paths.StagingDirectory, StagingFolder(jobId)));
|
||||
// Kept while a sequence is left as it was: a retry knows what was done and tries the others again.
|
||||
if (results.All(r => r.Final)) ConvertJournal.Delete(paths, jobId);
|
||||
return new ConvertResult(results, followUps);
|
||||
}
|
||||
|
||||
/// <summary>Stage A and stage B of one sequence.</summary>
|
||||
private async Task<(ConvertSequenceResult, IReadOnlyList<ArchiveJobRequest>)> ConvertOneAsync(Archive archive, ArchivePaths paths, Sequence row,
|
||||
ConvertSequencePlan planned, ConvertOptions options, ConvertMode mode, Guid jobId, string? createdBy, ConvertJournal journal, StagedLog staged,
|
||||
Progress progress, ConvertCallbacks callbacks, CancellationToken cancellationToken)
|
||||
{
|
||||
var folder = paths.Sequence(row.Folder);
|
||||
if (Read(folder, row.Id) is not { } manifest) return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Blocked, 0), []);
|
||||
if (manifest.Versions.Frames != planned.FramesVersion) return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Changed, 0), []);
|
||||
var staging = StagingOf(paths, jobId, row.Id);
|
||||
var key = SessionKey(jobId, row.Id);
|
||||
// A new sequence a resumed job finds again holds the photos it filed before it stopped.
|
||||
var filed = mode == ConvertMode.NewSequence
|
||||
? await FiledAsync(archive, key, cancellationToken).ConfigureAwait(false)
|
||||
: new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var ready = await Task.Run(() => Ready(manifest, planned, staged.Of(row.Id, planned.FramesVersion), staging, filed), cancellationToken).ConfigureAwait(false);
|
||||
progress.Done -= staged.Of(row.Id, planned.FramesVersion).Count - ready.Count;
|
||||
|
||||
var failure = await StageAsync(row, manifest, folder, planned, ready, staging, options, staged, progress, callbacks, cancellationToken).ConfigureAwait(false);
|
||||
if (failure is not null)
|
||||
return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Failed, 0, Error: failure), []);
|
||||
try
|
||||
{
|
||||
return mode == ConvertMode.Replace
|
||||
? await ReplaceAsync(archive, paths, row, planned, manifest, ready, staging, options, createdBy, cancellationToken).ConfigureAwait(false)
|
||||
: await CreateAsync(archive, paths, row, manifest, ready, staging, options, key, createdBy, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (LeaseUnavailableException ex)
|
||||
{
|
||||
return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Blocked, 0, Error: ex.Message), []);
|
||||
}
|
||||
catch (ArchiveOfflineException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or InvalidOperationException)
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("archive", $"{row.DisplayTitle}: the converted photos could not take their place", ex);
|
||||
return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Failed, 0, Error: ex.Message), []);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The staged conversions of a sequence that still hold: of a frame the plan converts, at the content it had then,
|
||||
/// whose staged file is there with its size and SHA-256 (re-hashed now: a pause, a crash or a clean-up may have taken it
|
||||
/// since), or which a new sequence holds already (<paramref name="filed"/>).
|
||||
/// </summary>
|
||||
private static Dictionary<Guid, StagedConversion> Ready(SequenceManifest manifest, ConvertSequencePlan planned, IReadOnlyList<StagedConversion> noted,
|
||||
string staging, IReadOnlySet<string> filed)
|
||||
{
|
||||
var frames = manifest.Frames.ToDictionary(f => f.Id);
|
||||
var converted = planned.Frames.Select(f => f.FrameId).ToHashSet();
|
||||
var ready = new Dictionary<Guid, StagedConversion>();
|
||||
foreach (var conversion in noted)
|
||||
{
|
||||
if (!converted.Contains(conversion.FrameId) || !frames.TryGetValue(conversion.FrameId, out var frame)
|
||||
|| !string.Equals(frame.Sha256, conversion.Source, StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
if (filed.Contains(conversion.Sha256) || Intact(Path.Combine(staging, conversion.File), conversion)) ready[conversion.FrameId] = conversion;
|
||||
}
|
||||
return ready;
|
||||
}
|
||||
|
||||
private static bool Intact(string path, StagedConversion conversion)
|
||||
{
|
||||
var file = new FileInfo(path);
|
||||
if (!file.Exists || file.Length != conversion.Size) return false;
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 20, FileOptions.SequentialScan);
|
||||
return string.Equals(Convert.ToHexStringLower(SHA256.HashData(stream)), conversion.Sha256, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stage A: converts the planned frames not staged yet, several at once, each staged file appended to the journal as it
|
||||
/// is consumed (in frame order). Returns the first failure (the file and why); the frames converted meanwhile stay
|
||||
/// staged for a retry.
|
||||
/// </summary>
|
||||
private async Task<string?> StageAsync(Sequence row, SequenceManifest manifest, SequencePaths folder, ConvertSequencePlan planned,
|
||||
Dictionary<Guid, StagedConversion> ready, string staging, ConvertOptions options, StagedLog staged, Progress progress, ConvertCallbacks callbacks,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var frames = manifest.Frames.ToDictionary(f => f.Id);
|
||||
var todo = planned.Frames.Where(f => !ready.ContainsKey(f.FrameId)).Select(f => frames[f.FrameId]).ToList();
|
||||
if (todo.Count == 0) return null;
|
||||
System.IO.Directory.CreateDirectory(staging);
|
||||
var decoder = _writer.Options.Decoder;
|
||||
var largest = todo.Max(f => (long)Math.Max(f.W, 0) * Math.Max(f.H, 0));
|
||||
// Photos at once as the host's parallelism and memory allow; each encoder then works alone.
|
||||
var atOnce = DecodeBudget.PhotosAtOnce(_writer.Options.Parallelism(), _writer.Options.MemoryBudget(), largest);
|
||||
var threads = atOnce > 1 ? 1 : -1;
|
||||
string? failure = null;
|
||||
await using var work = new OrderedWork<Staged>(atOnce, async result =>
|
||||
{
|
||||
if (result.Conversion is not { } conversion)
|
||||
{
|
||||
failure ??= $"{result.File}: {result.Error?.Message}";
|
||||
return;
|
||||
}
|
||||
staged.Append(row.Id, planned.FramesVersion, conversion);
|
||||
ready[conversion.FrameId] = conversion;
|
||||
await callbacks.Progress(++progress.Done, progress.Total).ConfigureAwait(false);
|
||||
}, cancellationToken);
|
||||
foreach (var frame in todo)
|
||||
{
|
||||
if (failure is not null) break;
|
||||
await work.AddAsync(token => Stage(frame, manifest, folder, staging, options, decoder, threads, token)).ConfigureAwait(false);
|
||||
}
|
||||
await work.CompleteAsync().ConfigureAwait(false);
|
||||
if (failure is not null) Core.Diagnostics.Log.Warning("archive", $"{row.DisplayTitle}: not converted, {failure}");
|
||||
return failure;
|
||||
}
|
||||
|
||||
/// <summary>One photo of stage A: hashed against its record, converted into the staging folder and verified.</summary>
|
||||
private static Staged Stage(SidecarFrame frame, SequenceManifest manifest, SequencePaths folder, string staging, ConvertOptions options, ImageDecoder decoder,
|
||||
int threads, CancellationToken cancellationToken)
|
||||
{
|
||||
var source = folder.File(frame.File);
|
||||
try
|
||||
{
|
||||
// Converted only as archived: a photo whose bytes no longer match its hash waits for a verify.
|
||||
string sha;
|
||||
using (var stream = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, 1 << 20, FileOptions.SequentialScan))
|
||||
sha = Convert.ToHexStringLower(SHA256.HashData(stream));
|
||||
if (!string.Equals(sha, frame.Sha256, StringComparison.OrdinalIgnoreCase))
|
||||
throw new ConversionException($"{frame.File} no longer matches its SHA-256; verify the sequence");
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var target = Path.Combine(staging, frame.Id.ToString("N") + options.Extension);
|
||||
var file = FrameConverter.Convert(new ConvertSource(source, frame, manifest.Camera, manifest.Lens), options, decoder, target, threads, cancellationToken);
|
||||
return new Staged(frame.File, new StagedConversion(frame.Id, sha, Path.GetFileName(target), file.Size, file.Sha256, file.Width, file.Height), null);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or NotSupportedException or FormatException
|
||||
or InvalidOperationException or ArgumentException)
|
||||
{
|
||||
return new Staged(frame.File, null, ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stage B of <see cref="ConvertMode.Replace"/>: the staged files take their frames' place (<see cref="FrameTrash.ReplaceAsync"/>).</summary>
|
||||
private async Task<(ConvertSequenceResult, IReadOnlyList<ArchiveJobRequest>)> ReplaceAsync(Archive archive, ArchivePaths paths, Sequence row,
|
||||
ConvertSequencePlan planned, SequenceManifest manifest, Dictionary<Guid, StagedConversion> ready, string staging, ConvertOptions options,
|
||||
string? createdBy, CancellationToken cancellationToken)
|
||||
{
|
||||
var swaps = manifest.Frames.Where(f => ready.ContainsKey(f.Id)).Select(f =>
|
||||
{
|
||||
var conversion = ready[f.Id];
|
||||
return new FrameSwap(f.Id, paths.ToRelative(Path.Combine(staging, conversion.File)), [], current => options.NameFor(current.File),
|
||||
current => Converted(current, conversion, options));
|
||||
}).ToList();
|
||||
// The frames hold the content that was converted: a frames version that did not move says so, and each hash agrees.
|
||||
var replaced = await _frames.ReplaceAsync(archive, row.Id, planned.FramesVersion, swaps, createdBy, null,
|
||||
(now, _, _) => Task.FromResult(now.Frames.Where(f => ready.ContainsKey(f.Id))
|
||||
.All(f => string.Equals(f.Sha256, ready[f.Id].Source, StringComparison.OrdinalIgnoreCase))), cancellationToken).ConfigureAwait(false);
|
||||
if (replaced is null) return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Changed, 0), []);
|
||||
return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Converted, swaps.Count),
|
||||
_frames.FollowUps(archive, replaced.Sequence, replaced.Had));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A converted frame's record: the frame as it is with the converted file's size, hash, format and upright size, read at
|
||||
/// full-resolution tier, without the embedded preview it no longer has, without the flags of its old file, and with the
|
||||
/// old file as its <see cref="SidecarFrame.Source"/>; capture time, exposure and the other facts stay.
|
||||
/// </summary>
|
||||
internal static SidecarFrame Converted(SidecarFrame current, StagedConversion conversion, ConvertOptions options) => current with
|
||||
{
|
||||
Size = conversion.Size,
|
||||
Sha256 = conversion.Sha256.ToLowerInvariant(),
|
||||
Format = options.Format,
|
||||
W = conversion.Width,
|
||||
H = conversion.Height,
|
||||
Orientation = 1,
|
||||
Tier = DecodeTier.Native,
|
||||
PreviewOffset = null,
|
||||
PreviewLength = null,
|
||||
PreviewW = null,
|
||||
PreviewH = null,
|
||||
Flags = current.Flags & ~FrameTrash.ContentFlags,
|
||||
Source = new FrameSource { Sha256 = current.Sha256, Format = current.Format, File = current.File, Size = current.Size },
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Stage B of <see cref="ConvertMode.NewSequence"/>: the staged files filed into the sequence of <paramref name="key"/>
|
||||
/// (made on first use, titled "title (FORMAT)"), named as their originals with the target's extension, with the source's
|
||||
/// capture facts; then the source's tags, rating, notes and project (its positions translated to the new frames).
|
||||
/// </summary>
|
||||
private async Task<(ConvertSequenceResult, IReadOnlyList<ArchiveJobRequest>)> CreateAsync(Archive archive, ArchivePaths paths, Sequence row,
|
||||
SequenceManifest manifest, Dictionary<Guid, StagedConversion> ready, string staging, ConvertOptions options, string key, string? createdBy,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var frames = manifest.Frames.ToDictionary(f => f.Id);
|
||||
var pending = manifest.Frames.Where(f => ready.ContainsKey(f.Id) && File.Exists(Path.Combine(staging, ready[f.Id].File))).Select(f =>
|
||||
{
|
||||
var conversion = ready[f.Id];
|
||||
var path = Path.Combine(staging, conversion.File);
|
||||
return new StagedFrame(path, f.Original ?? Path.GetFileName(f.File), conversion.Size, conversion.Sha256, Metadata(path, f), null,
|
||||
Path.GetFileName(options.NameFor(f.File)));
|
||||
}).ToList();
|
||||
var title = $"{manifest.Title ?? row.DisplayTitle} ({options.Label})";
|
||||
// Once the first file moves, the commit runs to its end whatever the caller cancels meanwhile.
|
||||
if (pending.Count > 0)
|
||||
await _ingest.CommitSessionAsync(archive, new SequenceTarget(key, title, null, createdBy), pending, CancellationToken.None).ConfigureAwait(false);
|
||||
var id = await _db.Sequences.FindBySessionKeyAsync(archive.Id, key, CancellationToken.None).ConfigureAwait(false)
|
||||
?? throw new IOException($"No converted photo of {row.DisplayTitle} could be filed into a new sequence.");
|
||||
await CopyAsync(paths, row, manifest, ready, id, cancellationToken).ConfigureAwait(false);
|
||||
var made = await _db.Sequences.GetAsync(id, CancellationToken.None).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException($"The new sequence {id} is not indexed.");
|
||||
Core.Diagnostics.Log.Info("archive", $"{row.DisplayTitle}: {ready.Count} photo(s) converted into the new sequence {made.DisplayTitle}");
|
||||
return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Created, ready.Count, id),
|
||||
_frames.FollowUps(archive, made, row.Status & (SequenceStatus.AnalyzedDeep | SequenceStatus.ThumbsBuilt | SequenceStatus.ProxiesBuilt)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The metadata a converted copy is filed with: what its file says, with the source frame's capture time, offset and
|
||||
/// time source (the sidecar wins, to the tick) and its intervalometer flag, which the MakerNote left behind carried.
|
||||
/// </summary>
|
||||
private static FrameMetadata Metadata(string path, SidecarFrame source)
|
||||
{
|
||||
var read = MetadataReader.Read(path, CancellationToken.None);
|
||||
var interval = (source.Flags & FrameFlags.Intervalometer) != 0 ? true : read.IntervalShooting;
|
||||
return source.CapturedAt is { } captured
|
||||
? read with { CapturedAt = captured, UtcOffsetMinutes = source.UtcOffset, TimestampSource = source.TimeSource, IntervalShooting = interval }
|
||||
: read with { IntervalShooting = interval };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gives the new sequence the source's tags, rating and notes, and its project with the frame positions (exclusions,
|
||||
/// hero, keyframes) moved from the source's frames to the copies of them; a project that cannot be read is left out
|
||||
/// (logged).
|
||||
/// </summary>
|
||||
private async Task CopyAsync(ArchivePaths paths, Sequence source, SequenceManifest manifest, Dictionary<Guid, StagedConversion> ready, Guid id,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await _service.EditSequenceInfoAsync(id, info => info with { Tags = source.Tags, Rating = source.Rating, Notes = source.Notes }, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
var folder = paths.Sequence(source.Folder);
|
||||
var json = source.SettingsJson ?? (File.Exists(folder.ProjectPath) ? AtomicFile.ReadAllText(folder.ProjectPath) : null);
|
||||
if (string.IsNullOrWhiteSpace(json)) return;
|
||||
var made = await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException($"The new sequence {id} is not indexed.");
|
||||
var copy = Read(paths.Sequence(made.Folder), id) ?? throw new InvalidDataException($"The sidecar of the new sequence {made.DisplayTitle} cannot be read.");
|
||||
// The source's frames as the copies the conversion made of them; a frame not converted keeps its own photo, which the
|
||||
// new sequence lacks (its positions wait as pending frames).
|
||||
var from = new FramePhotos(manifest.Frames.Select(f => (f.I, ready.TryGetValue(f.Id, out var c)
|
||||
? new FramePhoto(c.Sha256.ToLowerInvariant(), c.Size, f.CapturedAt)
|
||||
: new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
|
||||
var to = new FramePhotos(copy.Frames.Select(f => (f.I, new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
|
||||
try
|
||||
{
|
||||
var translated = ProjectSettings.TranslateFramePositions(json, from, to) ?? json;
|
||||
var project = ProjectStore.Parse(translated);
|
||||
await new ProjectStore(_db, _writer).UpdateAsync(paths, made, _ => project, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (InvalidDataException ex)
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("archive", $"{source.DisplayTitle}: its project cannot be read; the new sequence {made.DisplayTitle} starts without it", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The SHA-256 of the frames the sequence of <paramref name="key"/> holds; empty when there is none yet.</summary>
|
||||
private async Task<IReadOnlySet<string>> FiledAsync(Archive archive, string key, CancellationToken cancellationToken)
|
||||
{
|
||||
var shas = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
if (await _db.Sequences.FindBySessionKeyAsync(archive.Id, key, cancellationToken).ConfigureAwait(false) is not { } id) return shas;
|
||||
for (var after = -1; ;)
|
||||
{
|
||||
var page = await _db.Frames.ListBySequenceAsync(id, after, 1000, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var frame in page.Where(f => f.Sha256 is not null)) shas.Add(frame.Sha256!);
|
||||
if (page.Count < 1000) return shas;
|
||||
after = page[^1].Index;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The photos converted, when this job replaced the sequence's frames already (a crash after its stage B, before the
|
||||
/// journal said so): every staged conversion is a frame of the sidecar now, holding the converted content and naming the
|
||||
/// converted content as its source. Null otherwise.
|
||||
/// </summary>
|
||||
private static int? ReplacedEarlier(ArchivePaths paths, Sequence row, IReadOnlyList<StagedConversion> noted)
|
||||
{
|
||||
if (noted.Count == 0 || Read(paths.Sequence(row.Folder), row.Id) is not { } manifest) return null;
|
||||
var frames = manifest.Frames.ToDictionary(f => f.Id);
|
||||
return noted.All(c => frames.TryGetValue(c.FrameId, out var f) && string.Equals(f.Sha256, c.Sha256, StringComparison.OrdinalIgnoreCase)
|
||||
&& string.Equals(f.Source?.Sha256, c.Source, StringComparison.OrdinalIgnoreCase))
|
||||
? noted.Select(c => c.FrameId).Distinct().Count()
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <summary>The sidecar of a sequence, read without its lease; null when it cannot be read or names another sequence.</summary>
|
||||
private static SequenceManifest? Read(SequencePaths folder, Guid id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
|
||||
return manifest.Id == id ? manifest : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or InvalidOperationException)
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("archive", $"The sidecar of {folder.RelativeFolder} cannot be read", ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Free bytes of the archive's volume as the host counts them (<see cref="ArchiveServiceOptions.FreeSpace"/>); null when unknown.</summary>
|
||||
private long? FreeSpace(ArchivePaths paths)
|
||||
{
|
||||
if (_writer.Options.FreeSpace is { } measure) return measure(paths.Root);
|
||||
try
|
||||
{
|
||||
// Windows wants a drive root; Unix accepts any directory and reports the volume it is mounted on.
|
||||
return new DriveInfo(OperatingSystem.IsWindows() ? Path.GetPathRoot(paths.Root)! : paths.Root).AvailableFreeSpace;
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void Log(ConvertCallbacks callbacks, ConvertSequenceResult result)
|
||||
{
|
||||
var line = result.Outcome switch
|
||||
{
|
||||
ConvertOutcome.Converted => Loc.L("Archive.Log.Converted", result.Title, result.Frames),
|
||||
ConvertOutcome.Created => Loc.L("Archive.Log.ConvertedNew", result.Title, result.Frames),
|
||||
ConvertOutcome.Nothing => Loc.L("Archive.Log.ConvertNothing", result.Title),
|
||||
ConvertOutcome.Changed => Loc.L("Archive.Log.ConvertChanged", result.Title),
|
||||
ConvertOutcome.Blocked => Loc.L("Archive.Log.ConvertBlocked", result.Title),
|
||||
_ => Loc.L("Archive.Log.ConvertFailed", result.Title, result.Error),
|
||||
};
|
||||
callbacks.Log(line);
|
||||
}
|
||||
|
||||
private static string Gigabytes(long bytes) => Loc.L("Common.Size.GB", (bytes / 1e9).ToString("0.#", Loc.Culture));
|
||||
|
||||
/// <summary>The session key of the new sequence a conversion makes from <paramref name="source"/>.</summary>
|
||||
internal static string SessionKey(Guid job, Guid source) => $"convert:{job:N}:{source:N}";
|
||||
|
||||
private static string StagingFolder(Guid job) => $"convert-{job:N}";
|
||||
|
||||
private static string StagingOf(ArchivePaths paths, Guid job, Guid sequence) =>
|
||||
Path.Combine(paths.StagingDirectory, StagingFolder(job), sequence.ToString("N"));
|
||||
|
||||
/// <summary>Deletes what a conversion staged that no step needs any more (converted copies, never originals); a failure is logged.</summary>
|
||||
private static void DeleteStaging(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (System.IO.Directory.Exists(folder)) System.IO.Directory.Delete(folder, recursive: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("archive", $"{folder} could not be deleted; maintenance removes it later", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Photos converted so far and in all.</summary>
|
||||
private sealed class Progress(long total, long done)
|
||||
{
|
||||
public long Total { get; } = total;
|
||||
public long Done { get; set; } = done;
|
||||
}
|
||||
|
||||
/// <summary>A photo of stage A: its file and its staged conversion, or why it failed.</summary>
|
||||
private sealed record Staged(string File, StagedConversion? Conversion, Exception? Error);
|
||||
}
|
||||
|
||||
/// <summary>One photo converted and staged: its frame, the content it was converted from, the staged file's name, size and SHA-256, and its size in pixels.</summary>
|
||||
/// <param name="Source">SHA-256 of the original it was converted from.</param>
|
||||
/// <param name="File">The staged file's name inside the sequence's staging folder.</param>
|
||||
internal sealed record StagedConversion(Guid FrameId, string Source, string File, long Size, string Sha256, int Width, int Height);
|
||||
|
||||
/// <summary>A line of the staged log: a staged conversion of a sequence at a frames version.</summary>
|
||||
internal sealed record StagedLine(Guid Sequence, int FramesVersion, StagedConversion Conversion);
|
||||
|
||||
/// <summary>
|
||||
/// The journal of a conversion job (<c>.chronos/journal/convert-<job>.json</c>, owner review 2, R7): what each sequence
|
||||
/// came to, written after each one; with it, the staged log (<c>convert-<job>.staged</c>), one line per photo staged,
|
||||
/// appended and flushed as it is staged, so a job of thousands of photos journals each once. A resumed or retried job keeps
|
||||
/// the sequences that are final and the staged files whose hash still verifies.
|
||||
/// </summary>
|
||||
internal sealed class ConvertJournal
|
||||
{
|
||||
public Guid JobId { get; set; }
|
||||
|
||||
public List<ConvertJournalSequence> Sequences { get; set; } = [];
|
||||
|
||||
public ConvertJournalSequence? Of(Guid id) => Sequences.FirstOrDefault(s => s.Id == id);
|
||||
|
||||
public void Note(ConvertSequenceResult result)
|
||||
{
|
||||
var noted = Of(result.SequenceId);
|
||||
if (noted is null) Sequences.Add(noted = new ConvertJournalSequence { Id = result.SequenceId });
|
||||
noted.Title = result.Title;
|
||||
noted.Outcome = result.Outcome;
|
||||
noted.Frames = result.Frames;
|
||||
noted.NewSequenceId = result.NewSequenceId;
|
||||
}
|
||||
|
||||
public static string PathFor(ArchivePaths paths, Guid job) => Path.Combine(paths.JournalDirectory, $"convert-{job:N}.json");
|
||||
|
||||
public static string StagedPathFor(ArchivePaths paths, Guid job) => Path.Combine(paths.JournalDirectory, $"convert-{job:N}.staged");
|
||||
|
||||
/// <summary>The journal of <paramref name="job"/>; null when there is none, or it is torn.</summary>
|
||||
public static ConvertJournal? Read(ArchivePaths paths, Guid job)
|
||||
{
|
||||
var path = PathFor(paths, job);
|
||||
if (!File.Exists(path)) return null;
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize(AtomicFile.ReadAllBytes(path), ArchiveJobJson.Default.ConvertJournal);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("archive", $"The conversion journal {path} is torn; the job starts over", ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void Write(ArchivePaths paths)
|
||||
{
|
||||
System.IO.Directory.CreateDirectory(paths.JournalDirectory);
|
||||
AtomicFile.WriteAllBytes(PathFor(paths, JobId), JsonSerializer.SerializeToUtf8Bytes(this, ArchiveJobJson.Default.ConvertJournal));
|
||||
}
|
||||
|
||||
/// <summary>The staged log of this job, read now.</summary>
|
||||
public StagedLog Staged(ArchivePaths paths) => StagedLog.Open(StagedPathFor(paths, JobId));
|
||||
|
||||
public static void Delete(ArchivePaths paths, Guid job)
|
||||
{
|
||||
foreach (var path in new[] { StagedPathFor(paths, job), PathFor(paths, job) })
|
||||
{
|
||||
if (File.Exists(path)) File.Delete(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What the journal knows of one sequence of a conversion.</summary>
|
||||
internal sealed class ConvertJournalSequence
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
|
||||
public string? Title { get; set; }
|
||||
|
||||
public ConvertOutcome? Outcome { get; set; }
|
||||
|
||||
public int Frames { get; set; }
|
||||
|
||||
public Guid? NewSequenceId { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public bool Final => Outcome is ConvertOutcome.Converted or ConvertOutcome.Created or ConvertOutcome.Nothing;
|
||||
}
|
||||
|
||||
/// <summary>The staged log of a conversion job (<see cref="ConvertJournal"/>): read once, appended to line by line.</summary>
|
||||
internal sealed class StagedLog
|
||||
{
|
||||
private readonly string _path;
|
||||
private readonly Dictionary<(Guid, int), Dictionary<Guid, StagedConversion>> _lines = [];
|
||||
|
||||
private StagedLog(string path) => _path = path;
|
||||
|
||||
/// <summary>The log at <paramref name="path"/>; a line torn by a crash, or unreadable, is skipped.</summary>
|
||||
public static StagedLog Open(string path)
|
||||
{
|
||||
var log = new StagedLog(path);
|
||||
if (!File.Exists(path)) return log;
|
||||
foreach (var line in File.ReadLines(path, Encoding.UTF8))
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(line)) continue;
|
||||
try
|
||||
{
|
||||
if (JsonSerializer.Deserialize(line, ArchiveJobJson.Default.StagedLine) is { } staged) log.Add(staged);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Torn while appended: that photo is converted again.
|
||||
}
|
||||
}
|
||||
return log;
|
||||
}
|
||||
|
||||
/// <summary>The staged conversions of a sequence at a frames version, latest per frame.</summary>
|
||||
public IReadOnlyList<StagedConversion> Of(Guid sequence, int framesVersion) =>
|
||||
_lines.TryGetValue((sequence, framesVersion), out var frames) ? [.. frames.Values] : [];
|
||||
|
||||
/// <summary>Appends a staged conversion and flushes it to disk.</summary>
|
||||
public void Append(Guid sequence, int framesVersion, StagedConversion conversion)
|
||||
{
|
||||
var line = new StagedLine(sequence, framesVersion, conversion);
|
||||
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(_path)!);
|
||||
using (var stream = new FileStream(_path, FileMode.Append, FileAccess.Write, FileShare.Read))
|
||||
{
|
||||
stream.Write(JsonSerializer.SerializeToUtf8Bytes(line, ArchiveJobJson.Default.StagedLine));
|
||||
stream.WriteByte((byte)'\n');
|
||||
stream.Flush(flushToDisk: true);
|
||||
}
|
||||
Add(line);
|
||||
}
|
||||
|
||||
private void Add(StagedLine line)
|
||||
{
|
||||
if (!_lines.TryGetValue((line.Sequence, line.FramesVersion), out var frames)) _lines[(line.Sequence, line.FramesVersion)] = frames = [];
|
||||
frames[line.Conversion.FrameId] = line.Conversion;
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,7 @@ public enum TrashKind
|
||||
/// <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>
|
||||
/// <summary>Originals a conversion replaced (owner review 2, R7): erased only while their replacements still match.</summary>
|
||||
Replaced,
|
||||
}
|
||||
|
||||
@@ -477,7 +477,10 @@ public sealed partial 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>
|
||||
internal async Task<IReadOnlySet<Guid>> BusyAsync(CancellationToken cancellationToken)
|
||||
internal Task<IReadOnlySet<Guid>> BusyAsync(CancellationToken cancellationToken) => BusyAsync(null, cancellationToken);
|
||||
|
||||
/// <summary>What running and paused jobs hold, but the job <paramref name="except"/> (the one asking).</summary>
|
||||
internal async Task<IReadOnlySet<Guid>> BusyAsync(Guid? except, CancellationToken cancellationToken)
|
||||
{
|
||||
var busy = new HashSet<Guid>();
|
||||
foreach (var state in new[] { JobState.Running, JobState.Paused })
|
||||
@@ -486,7 +489,7 @@ public sealed partial class SequenceTrash
|
||||
do
|
||||
{
|
||||
var page = await _db.Jobs.ListAsync(state, JobPage, cursor, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var job in page.Items) busy.UnionWith(Holds(job));
|
||||
foreach (var job in page.Items.Where(j => j.Id != except)) busy.UnionWith(Holds(job));
|
||||
cursor = page.NextCursor;
|
||||
}
|
||||
while (cursor is not null);
|
||||
@@ -608,4 +611,5 @@ internal sealed record TrashRecord(Sequence Sequence, IReadOnlyList<Render> Rend
|
||||
[JsonSerializable(typeof(TrashRecord))]
|
||||
[JsonSerializable(typeof(PhotoTrashRecord))]
|
||||
[JsonSerializable(typeof(FrameRestoreJournal))]
|
||||
[JsonSerializable(typeof(FrameReplaceJournal))]
|
||||
internal sealed partial class TrashJson : JsonSerializerContext;
|
||||
@@ -55,12 +55,20 @@ public sealed record ArchiveServiceOptions
|
||||
/// <summary>
|
||||
/// Told after a Reorganize changed a sequence's folder, title or file names (change <c>reorganized</c>), once its step is
|
||||
/// journaled, or once its folder moved and its index row followed when the step then failed: by its job, or by an archive
|
||||
/// open that completed a plan an interruption left (<see cref="ArchiveService.OpenAsync"/>).
|
||||
/// open that completed a plan an interruption left (<see cref="ArchiveService.OpenAsync"/>). Told too after a conversion
|
||||
/// replaced a sequence's frames (<c>converted</c>) or made a new sequence of them (<c>created</c>).
|
||||
/// A server tells its connected clients (BRIEF §14.3); the service it opens its archive with at start sets none, as no
|
||||
/// client is connected yet. The desktop reloads an editor open on the sequence. A failure is logged and never fails the job.
|
||||
/// </summary>
|
||||
public Func<Guid, string, CancellationToken, Task>? SequenceChanged { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The free bytes of the volume an archive root lies on, as the host counts them (a server measures its space volume,
|
||||
/// owner review 2, R2); null: the volume of the root itself. A conversion checks its estimate against it (R7). The
|
||||
/// function returns null when the space cannot be measured.
|
||||
/// </summary>
|
||||
public Func<string, long?>? FreeSpace { get; init; }
|
||||
|
||||
/// <summary>Half the logical cores, at least one: the parallelism when the host sets none.</summary>
|
||||
public static int DefaultParallelism => Math.Max(1, Environment.ProcessorCount / 2);
|
||||
|
||||
@@ -99,7 +107,8 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options)
|
||||
|
||||
/// <summary>
|
||||
/// Reads the sidecar of a locked sequence, completing an interrupted Reorganize of its files (<see cref="FileRenameJournal"/>),
|
||||
/// undoing an interrupted photo deletion (<see cref="FrameRemovalJournal"/>), settling an interrupted restore from the
|
||||
/// undoing an interrupted photo deletion (<see cref="FrameRemovalJournal"/>), undoing or completing an interrupted frame
|
||||
/// replacement (<see cref="FrameReplaceJournal"/>, a conversion or its undo), 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. A sidecar a rename recovery rewrites leaves the index behind it until the rename resumes or the
|
||||
/// next scan reads it.
|
||||
@@ -121,6 +130,7 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options)
|
||||
FileRenameJournal.Delete(sequence);
|
||||
}
|
||||
FrameRemovalJournal.Recover(sequence, manifest);
|
||||
FrameTrash.RecoverReplace(sequence, manifest, heldEntryLease);
|
||||
FrameTrash.RecoverRestore(sequence, manifest, heldEntryLease);
|
||||
if (IngestJournal.Recover(sequence, manifest) is { } recovered)
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user