diff --git a/i18n/en/Archive.resx b/i18n/en/Archive.resx index 0fa0ac79..54f82ed4 100644 --- a/i18n/en/Archive.resx +++ b/i18n/en/Archive.resx @@ -199,6 +199,7 @@ Left as it was, changed after the plan: {0}long: job log line; {0} sequence title Sequences converted: {0}, new sequences: {1}, photos: {2}long: job log line of a conversion Left as it was: {0}. {1}long: job log line; {0} sequence title, {1} what failed and why (sentences) + {0}: photos not converted, left in the source alone: {1}long: job log line after a conversion into a new sequence; {0} sequence title, {1} photos Nothing to convert: {0}long: job log line; {0} sequence title {0}: photos replaced by their conversion: {1}long: job log line; {0} sequence title, {1} photos {0}: photos converted into a new sequence: {1}long: job log line; {0} sequence title, {1} photos diff --git a/i18n/it/Archive.it.resx b/i18n/it/Archive.it.resx index 44c29bf2..8b14d4fd 100644 --- a/i18n/it/Archive.it.resx +++ b/i18n/it/Archive.it.resx @@ -193,6 +193,7 @@ Lasciata com'era, cambiata dopo il piano: {0} Sequenze convertite: {0}, nuove sequenze: {1}, foto: {2} Lasciata com'era: {0}. {1} + {0}: foto non convertite, rimaste solo nella sorgente: {1} Niente da convertire: {0} {0}: foto sostituite dalla loro conversione: {1} {0}: foto convertite in una nuova sequenza: {1} diff --git a/src/Chronos.App/Infrastructure/AppServices.cs b/src/Chronos.App/Infrastructure/AppServices.cs index baf4fc5c..90f39ebc 100644 --- a/src/Chronos.App/Infrastructure/AppServices.cs +++ b/src/Chronos.App/Infrastructure/AppServices.cs @@ -453,6 +453,8 @@ public sealed class AppServices : IAsyncDisposable var archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateClient(_wic), + // Measured by Windows itself, so an archive on a network share (UNC) is measured too: a conversion checks its space. + FreeSpace = Chronos.Core.Windows.Devices.VolumeInfo.FreeBytesAt, Parallelism = () => Parallelism, MemoryBudget = () => ProcessingTuning.MemoryBudget(Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes), // The housekeeping schedule trims the cache to Settings › Storage › Cache limit (owner review 2, R10). diff --git a/src/Chronos.Core.Windows/Devices/VolumeInfo.cs b/src/Chronos.Core.Windows/Devices/VolumeInfo.cs index 10291f3f..cbf68ab0 100644 --- a/src/Chronos.Core.Windows/Devices/VolumeInfo.cs +++ b/src/Chronos.Core.Windows/Devices/VolumeInfo.cs @@ -70,6 +70,26 @@ public sealed record VolumeInfo( } } + /// + /// Free bytes available to the current user on the volume holding the folder , quotas counted: a + /// network share's (UNC) too, which cannot measure. Null when the folder cannot be reached or measured. + /// + public static long? FreeBytesAt(string folder) + { + ArgumentException.ThrowIfNullOrEmpty(folder); + // A share's folder must end with a separator. + var directory = Path.EndsInDirectorySeparator(folder) ? folder : folder + Path.DirectorySeparatorChar; + VolumeNative.SetThreadErrorMode(VolumeNative.SEM_FAILCRITICALERRORS, out var previousMode); + try + { + return VolumeNative.GetDiskFreeSpaceEx(directory, out var free, out _, out _) ? (long)Math.Min(free, long.MaxValue) : null; + } + finally + { + VolumeNative.SetThreadErrorMode(previousMode, out _); + } + } + /// Every ready fixed or removable volume, enumerated through (network and optical drives are skipped). public static IReadOnlyList ListLocal() { diff --git a/src/Chronos.Core/Conversion/ConvertPlanner.cs b/src/Chronos.Core/Conversion/ConvertPlanner.cs index a9dccc50..29e6d432 100644 --- a/src/Chronos.Core/Conversion/ConvertPlanner.cs +++ b/src/Chronos.Core/Conversion/ConvertPlanner.cs @@ -43,7 +43,7 @@ public enum ConvertSkip /// Why a whole sequence is not converted now; nothing of it is touched. public enum ConvertBlock { - /// A running or paused job works on the sequence or its whole archive. + /// A running or paused job works on the sequence or its whole archive, or a conversion of it waits in the queue. Busy, /// The archive is offline or read-only. @@ -52,15 +52,21 @@ public enum ConvertBlock /// The sequence's sidecar cannot be read, or belongs to another sequence. Unreadable, - /// The sequence's frames changed after the plan was made (found by the job, which then leaves it as it is). + /// + /// The photos the sequence converts are no longer those of the plan confirmed (found by the job, which then leaves it as + /// it is). + /// FramesChanged, } /// Frames of a sequence that are not converted, and why. public sealed record ConvertSkipped(ConvertSkip Reason, int Frames); -/// One frame a conversion converts: its id and index, its file and format, its size and the converted file's estimated size. -public sealed record ConvertFramePlan(Guid FrameId, int Index, string File, ImageFileFormat Format, long Size, long EstimatedBytes); +/// +/// One frame a conversion converts: its id and index, its file and format, its size, the converted file's estimated size, +/// and the SHA-256 of the content converted. +/// +public sealed record ConvertFramePlan(Guid FrameId, int Index, string File, ImageFileFormat Format, long Size, long EstimatedBytes, string? Sha256 = null); /// /// One sequence of a conversion plan: the frames converted, those skipped with why, the frames version the plan was made at, @@ -79,6 +85,21 @@ public sealed record ConvertSequencePlan(Guid SequenceId, string Title, string F public long BytesAfter => Frames.Sum(f => f.EstimatedBytes); public int SkippedFrames => Skipped.Sum(s => s.Frames); + + /// + /// A digest of the photos the sequence converts: each frame in order with the SHA-256 of the content converted. A + /// conversion job converts the sequence only while its plan there still has the digest the user confirmed. + /// + public string Digest() => DigestOf(Frames.Select(f => (f.FrameId, f.Sha256))); + + /// The digest of frames, each with the SHA-256 of its content, in order (). + public static string DigestOf(IEnumerable<(Guid FrameId, string? Sha256)> frames) + { + ArgumentNullException.ThrowIfNull(frames); + var text = new StringBuilder(); + foreach (var (id, sha) in frames) text.Append(CultureInfo.InvariantCulture, $"{id:N}|{sha?.ToLowerInvariant()}\n"); + return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString()))); + } } /// @@ -108,15 +129,16 @@ public sealed record ConvertPlan(Guid ArchiveId, ConvertOptions Options, Convert public int Skipped => Sequences.Sum(s => s.SkippedFrames); /// - /// A digest of what the plan converts (options, mode, and each sequence in order with its frames version, the frames - /// converted and skipped, and what blocks it), the same for two plans of the same archive state. + /// A digest of what the plan converts (options, mode, and each sequence in order with its frames version, the photos + /// converted with their content (), those skipped, and what blocks it), the + /// same for two plans of the same archive state. /// public string Fingerprint() { var text = new StringBuilder().Append(Options.Key).Append('|').Append(Mode).Append('\n'); foreach (var s in Sequences) { - text.Append(CultureInfo.InvariantCulture, $"{s.SequenceId:N}|{s.FramesVersion}|{s.Frames.Count}|{s.BytesBefore}|"); + text.Append(CultureInfo.InvariantCulture, $"{s.SequenceId:N}|{s.FramesVersion}|{s.Frames.Count}|{s.BytesBefore}|{s.Digest()}|"); foreach (var skipped in s.Skipped) text.Append(CultureInfo.InvariantCulture, $"{skipped.Reason}:{skipped.Frames};"); foreach (var blocked in s.Blocked) text.Append(blocked).Append(';'); text.Append('\n'); @@ -180,7 +202,7 @@ public static class ConvertPlanner skipped[reason] = skipped.GetValueOrDefault(reason) + 1; continue; } - frames.Add(new ConvertFramePlan(frame.Id, frame.I, frame.File, frame.Format, frame.Size, EstimateBytes(options, frame.W, frame.H))); + frames.Add(new ConvertFramePlan(frame.Id, frame.I, frame.File, frame.Format, frame.Size, EstimateBytes(options, frame.W, frame.H), frame.Sha256)); } return new ConvertSequencePlan(manifest.Id, title, folder.RelativeFolder, manifest.Versions.Frames, frames, [.. skipped.OrderBy(s => s.Key).Select(s => new ConvertSkipped(s.Key, s.Value))], []); diff --git a/src/Chronos.Data/Archiving/ArchiveMaintenance.cs b/src/Chronos.Data/Archiving/ArchiveMaintenance.cs index 8bc41d12..38892bd2 100644 --- a/src/Chronos.Data/Archiving/ArchiveMaintenance.cs +++ b/src/Chronos.Data/Archiving/ArchiveMaintenance.cs @@ -40,6 +40,12 @@ public sealed class ArchiveMaintenance /// Staged copies older than this belong to no running import. private static readonly TimeSpan StagingAge = TimeSpan.FromHours(24); + /// + /// The journal of a conversion job this index does not know (another host's, or one its history forgot) is left alone + /// until it has not been written for this long: the job history keeps finished jobs as long by default. + /// + private static readonly TimeSpan JournalAge = TimeSpan.FromDays(Housekeeping.CleanupSteps.DefaultHistoryDays); + /// Temporary files of atomic writes older than this were left by a crash. private static readonly TimeSpan TempAge = TimeSpan.FromHours(1); @@ -141,7 +147,7 @@ public sealed class ArchiveMaintenance leases = LeaseFile.CleanupStale(paths.LocksDirectory, dryRun); break; case 1: - temps = PurgeTemporaryFiles(paths, locations, dryRun); + temps = await PurgeTemporaryFilesAsync(paths, locations, dryRun, cancellationToken).ConfigureAwait(false); break; case 2: packs = await CompactPacksAsync(paths, locations, dryRun, cancellationToken).ConfigureAwait(false); @@ -172,20 +178,66 @@ public sealed class ArchiveMaintenance return (space.ReclaimableBytes, long.Max(0, before.FileBytes - after.FileBytes)); } - /// Staging copies and atomic-write temporaries left behind by crashes (never originals). - private static List PurgeTemporaryFiles(ArchivePaths paths, IReadOnlyList locations, bool dryRun) + /// + /// Staging copies and atomic-write temporaries left behind by crashes (never originals), and what a conversion job left + /// (): its staged conversions stay while the job is queued, running or paused, however old, go + /// as soon as it is done, and otherwise once none of them was written for a day (a retry then converts again); its journal + /// stays while a retry can use it, and goes once the job is done, or unknown to this index and untouched for as long as + /// the job history keeps jobs. + /// + private async Task> PurgeTemporaryFilesAsync(ArchivePaths paths, IReadOnlyList locations, bool dryRun, + CancellationToken cancellationToken) { var now = DateTime.UtcNow; var found = new List(); + var conversions = new List(); + var states = new Dictionary(); + async Task StateAsync(Guid job) + { + if (!states.TryGetValue(job, out var state)) states[job] = state = (await _db.Jobs.GetAsync(job, cancellationToken).ConfigureAwait(false))?.State; + return state; + } + bool Old(string file, TimeSpan age) => now - File.GetLastWriteTimeUtc(file) > age; void Collect(string directory, string pattern, TimeSpan age, bool recursive) { if (!Directory.Exists(directory)) return; foreach (var file in Directory.EnumerateFiles(directory, pattern, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)) { - if (now - File.GetLastWriteTimeUtc(file) > age) found.Add(file); + if (Old(file, age)) found.Add(file); + } + } + if (Directory.Exists(paths.StagingDirectory)) + { + foreach (var file in Directory.EnumerateFiles(paths.StagingDirectory)) + { + if (Old(file, StagingAge)) found.Add(file); + } + foreach (var directory in Directory.EnumerateDirectories(paths.StagingDirectory)) + { + if (ConvertJournal.JobOf(Path.GetFileName(directory)) is not { } job) + { + Collect(directory, "*", StagingAge, recursive: true); + continue; + } + var state = await StateAsync(job).ConfigureAwait(false); + if (state is JobState.Queued or JobState.Running or JobState.Paused) continue; + var files = Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories).ToList(); + if (state == JobState.Done || files.All(f => Old(f, StagingAge))) + { + found.AddRange(files); + conversions.Add(directory); + } + } + } + if (Directory.Exists(paths.JournalDirectory)) + { + foreach (var file in Directory.EnumerateFiles(paths.JournalDirectory, ConvertJournal.Prefix + "*")) + { + if (ConvertJournal.JobOf(Path.GetFileName(file)) is not { } job) continue; + var state = await StateAsync(job).ConfigureAwait(false); + if (state == JobState.Done || state is null && Old(file, JournalAge)) found.Add(file); } } - Collect(paths.StagingDirectory, "*", StagingAge, recursive: true); Collect(paths.MetaDirectory, ".*.tmp", TempAge, recursive: false); foreach (var location in locations) { @@ -206,6 +258,7 @@ public sealed class ArchiveMaintenance Log.Warning("archive", $"Could not remove {file}", ex); } } + foreach (var directory in conversions) MassConverter.DeleteStaging(directory); } return found.ConvertAll(paths.ToRelative); } diff --git a/src/Chronos.Data/Archiving/ArchiveService.cs b/src/Chronos.Data/Archiving/ArchiveService.cs index 62b2a4cb..08864bb2 100644 --- a/src/Chronos.Data/Archiving/ArchiveService.cs +++ b/src/Chronos.Data/Archiving/ArchiveService.cs @@ -697,15 +697,16 @@ public static class ArchiveJobs /// /// : applies the conversion () - /// 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. + /// as confirmed (owner review 2, R7): the sequences it converts, in its order with their frames versions and the digest of + /// the photos each converts (), are the job's targets, so jobs that would touch + /// them wait. A sequence whose photos to convert are no longer those when the job comes to it is left as it is and reported. /// /// The plan converts nothing. 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(); + var sequences = plan.Converted.Select(s => new ConvertSequence(s.SequenceId, s.FramesVersion, s.Digest())).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, diff --git a/src/Chronos.Data/Archiving/Jobs/ArchiveJobParameters.cs b/src/Chronos.Data/Archiving/Jobs/ArchiveJobParameters.cs index edc94cde..b05474ff 100644 --- a/src/Chronos.Data/Archiving/Jobs/ArchiveJobParameters.cs +++ b/src/Chronos.Data/Archiving/Jobs/ArchiveJobParameters.cs @@ -55,14 +55,18 @@ public sealed record MoveSequence(Guid Id); /// /// (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 -/// (). A sequence whose frames changed since is left as it is and reported. +/// in its order, each with what it converts, and the plan's fingerprint (). A sequence +/// whose photos to convert are no longer those confirmed is left as it is and reported. /// public sealed record ConvertJobParameters(Guid ArchiveId, ConvertTarget Target, int Quality, ConvertMode Mode, IReadOnlyList Sequences, string Fingerprint); -/// A sequence of a and the frames version it was planned at. -public sealed record ConvertSequence(Guid Id, int FramesVersion); +/// +/// A sequence of a : the frames version it was planned at and the digest of the photos it +/// converts, each with its content (), which the job checks under the sequence's +/// lease before it converts anything; null in a job an earlier build queued, which checks the frames version only. +/// +public sealed record ConvertSequence(Guid Id, int FramesVersion, string? Frames = null); /// A job ready to enqueue. public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList Targets, string? Label, string? ParametersJson, JobPriority Priority); @@ -80,6 +84,7 @@ public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList Targets [JsonSerializable(typeof(ConvertJobParameters))] [JsonSerializable(typeof(ConvertJournal))] [JsonSerializable(typeof(StagedLine))] +[JsonSerializable(typeof(PinnedSequence))] [JsonSerializable(typeof(CardProfile))] internal sealed partial class ArchiveJobJson : JsonSerializerContext { diff --git a/src/Chronos.Data/Archiving/Jobs/ConvertJobHandler.cs b/src/Chronos.Data/Archiving/Jobs/ConvertJobHandler.cs index b3ae0416..1e878492 100644 --- a/src/Chronos.Data/Archiving/Jobs/ConvertJobHandler.cs +++ b/src/Chronos.Data/Archiving/Jobs/ConvertJobHandler.cs @@ -8,13 +8,14 @@ namespace Chronos.Data.Archiving.Jobs; /// /// : a mass conversion (owner review 2, R7; BRIEF §12.5) of the sequences of a confirmed plan -/// () through , 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 +/// () through , which settles what a crash left half-way, refuses +/// when the volume lacks the space (measured again before each sequence and each photo), and converts one sequence at a +/// time, each all or nothing and only while the photos it converts are those confirmed; 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 converted, each new sequence as created (), -/// as soon as it is done; 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. +/// and the passes it needs (light analysis, a deep one when the source had it, thumbnails and proxies) are queued as +/// follow-ups, as soon as it is done. 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 with what they staged. /// internal sealed class ConvertJobHandler(ChronosDatabase db, MassConverter converter, Func? sequenceChanged) : IJobHandler { @@ -35,22 +36,24 @@ internal sealed class ConvertJobHandler(ChronosDatabase db, MassConverter conver 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( + var name = 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, new ConvertRequester(name, context.Job.CreatedBy), new ConvertCallbacks( (done, total) => context.ReportAsync(done, total), (done, total) => context.CheckpointAsync(Checkpoint, done, total), - context.Log, TellAsync), context.Cancellation).ConfigureAwait(false); - await QueueAsync(context, result).ConfigureAwait(false); + context.Log, TellAsync, requests => QueueAsync(context, requests)), context.Cancellation).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)); var kept = result.Kept.Count(); if (kept > 0) throw new InvalidOperationException(Loc.Plural("Archive.Error.ConvertKept", kept)); } - /// Queues what the converted sequences need, each kind once per sequence; a failure is logged, never passed on. - private async Task QueueAsync(JobContext context, ConvertResult result) + /// + /// Queues what a sequence converted or made needs as soon as its outcome is journaled, each kind once per sequence; a + /// failure is logged, never passed on. + /// + private async ValueTask QueueAsync(JobContext context, IReadOnlyList requests) { - foreach (var request in result.FollowUps) + foreach (var request in requests) { try { diff --git a/src/Chronos.Data/Archiving/MassConverter.cs b/src/Chronos.Data/Archiving/MassConverter.cs index 0d51f1de..72846637 100644 --- a/src/Chronos.Data/Archiving/MassConverter.cs +++ b/src/Chronos.Data/Archiving/MassConverter.cs @@ -29,7 +29,7 @@ public enum ConvertOutcome /// It had nothing to convert. Nothing, - /// Left as it was: its frames changed after the plan, or it is no longer in the archive. + /// Left as it was: the photos it converts are no longer those of the plan confirmed, or it is no longer in the archive. Changed, /// Left as it was: it is busy, or its sidecar cannot be read. @@ -39,14 +39,18 @@ public enum ConvertOutcome Failed, } -/// One sequence of a conversion: what happened, how many photos, the new sequence when one was made, and the failure. -public sealed record ConvertSequenceResult(Guid SequenceId, string Title, ConvertOutcome Outcome, int Frames, Guid? NewSequenceId = null, string? Error = null) +/// +/// One sequence of a conversion: what happened, how many photos, the new sequence when one was made, the failure, and the +/// photos of the source a new sequence does not hold (those the plan did not convert stay in the source alone). +/// +public sealed record ConvertSequenceResult(Guid SequenceId, string Title, ConvertOutcome Outcome, int Frames, Guid? NewSequenceId = null, string? Error = null, + int LeftOut = 0) { /// Whether the sequence is done with: converted, made, or with nothing to convert. public bool Final => Outcome is ConvertOutcome.Converted or ConvertOutcome.Created or ConvertOutcome.Nothing; } -/// What a conversion did, and the passes the sequences it changed or made need (to queue as follow-ups). +/// What a conversion did, and the passes the sequences it changed or made need (queued as follow-ups as each one ended). public sealed record ConvertResult(IReadOnlyList Sequences, IReadOnlyList FollowUps) { /// Photos converted, into their sequence or a new one. @@ -57,32 +61,43 @@ public sealed record ConvertResult(IReadOnlyList Sequence } /// -/// How a running conversion reports: progress in photos, a checkpoint after each sequence, job log lines, and each sequence -/// it came to an end with in this run, once its outcome is journaled (to tell the sequences it changed or made while the -/// rest of the job runs, as a Reorganize tells each step). +/// How a running conversion reports: progress in photos, a checkpoint after each sequence, job log lines, each sequence it +/// came to an end with in this run once its outcome is journaled (to tell the sequences it changed or made while the rest +/// of the job runs, as a Reorganize tells each step), and the passes a sequence it converted or made needs, to queue then +/// too (the journal says whether they were, so a pause, a yield, a stop or a crash later loses none). /// internal sealed record ConvertCallbacks(Func Progress, Func Checkpoint, Action Log, - Func? Done = null); + Func? Done = null, Func, ValueTask>? Queue = null); + +/// Who asked for a conversion: the user's name, kept in the trash records of a Replace, and id, the owner of a new sequence when its source has none. +internal sealed record ConvertRequester(string? Name, Guid? Id); /// /// Mass conversion of existing sequences (owner review 2, R7; BRIEF §12.5): -/// is the dry run ( per sequence, what blocks it, the space needed against the free space of -/// the archive's volume, ), and a job applies the -/// confirmed plan one sequence at a time. Stage A, once the sequence's sidecar is settled under its lease where the index -/// has it then (), without the lease: each photo is hashed against its record and -/// converted (, several at once as the host's parallelism and memory allow) into -/// .chronos/staging/convert-<job>/<sequence>/, each staged file appended to the job's journal -/// (), 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: -/// swaps the frames' files (: the originals into one trash entry of kind -/// , same ids and indices, tombstones naming the replacements; the converted files named as -/// filing names a photo of the sequence, ); -/// files the converted copies into a new sequence through the archive ingest (session key convert:<job>:<source>, -/// 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. +/// is the dry run ( per sequence, what blocks it, the space needed against the free space where +/// the conversion writes, ), and a job applies the +/// confirmed plan one sequence at a time. Under the sequence's lease, its sidecar settled where the index has it then +/// (), the job plans it again and goes on only while the photos it converts are those +/// confirmed, each with its content (); it pins them then (), so a photo +/// that comes in or is verified later stays as it is, on a retry too. Stage A, without the lease: each photo is hashed +/// against its record and converted (, several at once as the host's parallelism and memory +/// allow) into .chronos/staging/convert-<job>/<sequence>/, the free space checked before each one, each staged +/// file appended to the job's journal (), so a resumed or retried job keeps the staged files +/// whose hash still verifies. Stage B, all or nothing, under the sequence's lease and while every photo pinned still holds +/// the content converted: swaps the frames' files (: +/// the originals into one trash entry of kind , same ids and indices, tombstones naming the +/// replacements; the converted files named as filing names a photo of the sequence, ); +/// files the converted copies into a new sequence through the archive ingest (session +/// key convert:<job>:<source>, so a resume finds it again), titled "title (FORMAT)", owned as the source is, +/// with the source's tags, rating, notes and project, the source left as it is (the photos the plan did not convert stay +/// there alone, as the job log says). A sequence whose photos changed, that is busy, or has a photo that fails is left as it +/// was and reported. /// public sealed class MassConverter { + /// What the frames of a sequence no longer have once their files were replaced (). + private const SequenceStatus Uncovered = SequenceStatus.AnalyzedLight | SequenceStatus.AnalyzedDeep | SequenceStatus.ThumbsBuilt | SequenceStatus.ProxiesBuilt; + private readonly ChronosDatabase _db; private readonly SequenceWriter _writer; private readonly ArchiveIngest _ingest; @@ -102,8 +117,8 @@ public sealed class MassConverter /// /// The dry run of converting of : 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. + /// converted and those skipped with why, the bytes before and after, what blocks it (busy, a conversion of it already + /// queued, offline, unreadable); the space needed and free; the fingerprint a confirmation sends back. Reads only. /// /// The options are invalid, or a sequence is not in the archive. public Task PlanAsync(Archive archive, IReadOnlyList sequenceIds, ConvertOptions options, ConvertMode mode, @@ -120,7 +135,11 @@ public sealed class MassConverter 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 busy = new HashSet(await _trash.BusyAsync(job, cancellationToken).ConfigureAwait(false)); + // A conversion waiting in the queue holds its sequences for a dry run too, so the same conversion is not confirmed twice + // (another tab or user, an answer lost and Apply pressed again). A job planning again counts only running and paused + // jobs: a duplicate queued after it would otherwise hold back the one before it. + if (job is null) busy.UnionWith(await _db.Jobs.ListPendingTargetsAsync(JobKind.Convert, cancellationToken).ConfigureAwait(false)); var plans = new List(); foreach (var id in sequenceIds.Distinct()) { @@ -151,18 +170,21 @@ public sealed class MassConverter } /// - /// Applies a confirmed conversion () as the job : 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. + /// Applies a confirmed conversion () as the job , resuming from its + /// journal: settles the sidecars a crash left half-way, refuses when the volume lacks the space the photos still to convert + /// need, then converts each sequence while what it converts is still what was confirmed (stage A, then stage B), the space + /// measured again before each. The passes a sequence converted or made needs are queued as soon as it is journaled. + /// Sequences left as they were are in the result; the journal and their staged files stay while there are any, so a retry + /// tries them again and knows what was done. /// /// The archive is offline or read-only; the job resumes where it stopped. - /// The volume lacks the space (Archive.Error.ConvertSpace); nothing was converted since. - internal async Task RunAsync(Archive archive, ConvertJobParameters parameters, Guid jobId, string? createdBy, ConvertCallbacks callbacks, + /// The volume lacks the space (Archive.Error.ConvertSpace); what was converted stays, and a retry resumes. + internal async Task RunAsync(Archive archive, ConvertJobParameters parameters, Guid jobId, ConvertRequester by, ConvertCallbacks callbacks, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(archive); ArgumentNullException.ThrowIfNull(parameters); + ArgumentNullException.ThrowIfNull(by); 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."); @@ -170,22 +192,31 @@ public sealed class MassConverter 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 staged = journal.Staged(paths); + var pins = journal.Pins(paths); + // What is still to do: every sequence not final in an earlier attempt that is still in the archive, its sidecar settled + // first when a writer a crash interrupted left a journal in its folder (this job's replacement among them). var rows = new Dictionary(); 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; + if (await _db.Sequences.GetAsync(step.Id, cancellationToken).ConfigureAwait(false) is { } row && row.ArchiveId == archive.Id) + rows[step.Id] = await SettledRowAsync(archive, paths, row, cancellationToken).ConfigureAwait(false); } 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)); + if (plan.Sequences.Any(p => p.Blocked.Contains(ConvertBlock.Offline))) throw new ArchiveOfflineException(paths.Root, ArchiveVolume.Probe(paths)); + // What each of them converts, as far as the job can tell before it comes to it (what it pinned, or the plan still confirmed), + // and the bytes its photos not staged yet are estimated at. + var byId = steps.ToDictionary(s => s.Id); + var progress = new Progress(); + var unstaged = new Dictionary(); + foreach (var p in plan.Sequences.Where(p => p.Blocked.Count == 0)) + { + if (Confirmed(byId[p.SequenceId], p, pins.Of(p.SequenceId)) is not { Frames.Count: > 0 } converts) continue; + progress.Count(converts.SequenceId, converts.Frames.Count, staged.Of(converts.SequenceId, converts.FramesVersion).Count); + unstaged[converts.SequenceId] = Unstaged(paths, jobId, converts, staged); + } + var space = new SpaceWatch(this, paths); + EnsureSpace(unstaged.Values.Sum(), space); await callbacks.Progress(progress.Done, progress.Total).ConfigureAwait(false); var results = new List(); @@ -194,73 +225,115 @@ public sealed class MassConverter { cancellationToken.ThrowIfCancellationRequested(); var noted = journal.Of(step.Id); - ConvertSequenceResult result; - if (noted?.Final == true) + var final = noted?.Final == true; + StepDone done; + if (final) { - result = new ConvertSequenceResult(step.Id, noted.Title ?? step.Id.ToString(), noted.Outcome!.Value, noted.Frames, noted.NewSequenceId); + // Done with in an earlier attempt, and the passes it needs too unless a pause, a yield, a stop or a crash came first. + done = new StepDone(new ConvertSequenceResult(step.Id, noted!.Title ?? step.Id.ToString(), noted.Outcome!.Value, noted.Frames, noted.NewSequenceId), + noted.Had, noted.Queued ? null : await FollowUpsAsync(archive, noted, cancellationToken).ConfigureAwait(false)); } - else if (!rows.TryGetValue(step.Id, out var row) || !plans.TryGetValue(step.Id, out var planned)) + else if (!rows.TryGetValue(step.Id, out var row)) { - 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); + done = new StepDone(new ConvertSequenceResult(step.Id, step.Id.ToString(), ConvertOutcome.Changed, 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); + ArchiveVolume.EnsureWritable(paths); + // The space for what is left, measured again: the volume may have filled since, and the files staged so far tell + // how far off the estimate is. + EnsureSpace(unstaged.Values.Sum(), space); + done = await ConvertOneAsync(archive, paths, step, row, options, parameters.Mode, jobId, by, journal, pins, staged, progress, space, callbacks, + cancellationToken).ConfigureAwait(false); } + unstaged.Remove(step.Id); + var result = done.Result; results.Add(result); - journal.Note(result); - journal.Write(paths); - if (!result.Final) DeleteStaging(StagingOf(paths, jobId, step.Id)); - Log(callbacks, result); - if (noted?.Final != true && callbacks.Done is { } done) await done(result).ConfigureAwait(false); + if (!final) + { + journal.Note(result, done.Had); + journal.Write(paths); + // What a sequence done with left staged, or staged for photos that are no longer the ones confirmed, is of no use + // to anything. A sequence blocked or failed keeps its staged files, which a retry verifies and takes. + if (result.Final || result.Outcome == ConvertOutcome.Changed) DeleteStaging(StagingOf(paths, jobId, step.Id)); + Log(callbacks, result); + if (callbacks.Done is { } told) await told(result).ConfigureAwait(false); + } + if (done.FollowUps is { } passes) + { + if (passes.Count > 0) + { + followUps.AddRange(passes); + if (callbacks.Queue is { } queue) await queue(passes).ConfigureAwait(false); + } + journal.Of(step.Id)!.Queued = true; + journal.Write(paths); + } 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); + // Done with every sequence: what the job staged and its journal go. Otherwise both stay for a retry, until the job is gone + // from the history (ArchiveMaintenance). + if (results.All(r => r.Final)) + { + DeleteStaging(Path.Combine(paths.StagingDirectory, StagingFolder(jobId))); + ConvertJournal.Delete(paths, jobId); + } return new ConvertResult(results, followUps); } - /// Stage A and stage B of one sequence. - private async Task<(ConvertSequenceResult, IReadOnlyList)> 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) + /// + /// One sequence: under its lease, its sidecar settled, planned again and held to what was confirmed (the photos pinned the + /// first time); then stage A without the lease, and stage B. + /// + private async Task ConvertOneAsync(Archive archive, ArchivePaths paths, ConvertSequence step, Sequence row, ConvertOptions options, + ConvertMode mode, Guid jobId, ConvertRequester by, ConvertJournal journal, PinLog pins, StagedLog staged, Progress progress, SpaceWatch space, + ConvertCallbacks callbacks, CancellationToken cancellationToken) { - Sequence now; + // Another job holds it now (a Reorganize paused since the job started, a render): it waits for the retry. + var busy = await _trash.BusyAsync(jobId, cancellationToken).ConfigureAwait(false); + if (busy.Contains(step.Id) || busy.Contains(archive.Id)) return new StepDone(Result(row, ConvertOutcome.Blocked)); SequencePaths folder; SequenceManifest manifest; + ConvertSequencePlan planned; try { - if (await SettledAsync(archive, paths, row.Id, cancellationToken).ConfigureAwait(false) is not { } settled) - return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Changed, 0), []); - (now, folder, manifest) = settled; + await using (await _writer.LockAsync(paths, step.Id, cancellationToken).ConfigureAwait(false)) + { + // Where the index has it now (a Reorganize may have moved its folder since the job planned), its sidecar as every + // writer reads it: a rename of its files, a deletion, a replacement, a restore or an ingest a crash left half-way is + // settled first, so the plan sees each photo where it is. + if (await _db.Sequences.GetAsync(step.Id, cancellationToken).ConfigureAwait(false) is not { } now || now.ArchiveId != archive.Id) + return new StepDone(Result(row, ConvertOutcome.Changed)); + row = now; + folder = paths.Sequence(row.Folder); + manifest = SequenceWriter.ReadLocked(folder, row.Id); + FrameTrash.EnsureReplaced(folder); + var pin = pins.Of(step.Id); + if (mode == ConvertMode.Replace && ReplacedEarlier(manifest, step, pin, staged.Of(step.Id, step.FramesVersion), options) is { } frames) + { + // Replaced by this job already: a crash after its stage B, before the journal said so (the settle may just have + // completed it). + var synced = await SyncedAsync(archive, folder, row, manifest).ConfigureAwait(false); + var had = journal.Of(step.Id)?.Had ?? row.Status; + return new StepDone(Result(synced, ConvertOutcome.Converted, frames), had, _frames.FollowUps(archive, synced, had)); + } + var (sidecar, at, title) = (manifest, folder, row.DisplayTitle); + var fresh = await Task.Run(() => ConvertPlanner.Plan(sidecar, at, FileRenames.ListPresent(at, sidecar), options, _writer.Options.Decoder, title), + cancellationToken).ConfigureAwait(false); + if (Confirmed(step, fresh, pin) is not { } confirmed) + { + Core.Diagnostics.Log.Info("archive", $"{row.DisplayTitle}: the photos it converts are no longer those of the plan confirmed; it is not converted"); + return new StepDone(Result(row, ConvertOutcome.Changed)); + } + planned = confirmed; + if (pin is null) + { + // From here on the job converts these photos of it, whatever comes in or is verified meanwhile, on a retry too. + pins.Append(step.Id, planned); + journal.Begin(step.Id, row.DisplayTitle, row.Status); + journal.Write(paths); + } + } } catch (ArchiveOfflineException) { @@ -269,31 +342,31 @@ public sealed class MassConverter catch (Exception ex) when (ex is LeaseUnavailableException or IOException or UnauthorizedAccessException or InvalidDataException or InvalidOperationException) { Core.Diagnostics.Log.Warning("archive", $"The sidecar of {row.DisplayTitle} cannot be read; it is not converted", ex); - return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Blocked, 0, Error: ex.Message), []); + return new StepDone(Result(row, ConvertOutcome.Blocked, error: ex.Message)); } - row = now; - 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(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 noted = staged.Of(row.Id, planned.FramesVersion); + var ready = await Task.Run(() => Ready(manifest, planned, noted, staging, filed), cancellationToken).ConfigureAwait(false); + progress.Count(row.Id, planned.Frames.Count, ready.Count); + await callbacks.Progress(progress.Done, progress.Total).ConfigureAwait(false); - 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), []); + var failure = await StageAsync(row, manifest, folder, planned, ready, staging, options, staged, progress, space, callbacks, cancellationToken) + .ConfigureAwait(false); + if (failure is not null) return new StepDone(Result(row, ConvertOutcome.Failed, 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); + ? await ReplaceAsync(archive, paths, row, planned, ready, staging, options, by.Name, cancellationToken).ConfigureAwait(false) + : await CreateAsync(archive, paths, row, planned, ready, staging, options, key, by.Id, cancellationToken).ConfigureAwait(false); } catch (LeaseUnavailableException ex) { - return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Blocked, 0, Error: ex.Message), []); + return new StepDone(Result(row, ConvertOutcome.Blocked, error: ex.Message)); } catch (ArchiveOfflineException) { @@ -303,10 +376,46 @@ public sealed class MassConverter { Core.Diagnostics.Log.Warning("archive", $"{row.DisplayTitle}: the converted photos could not take their place", ex); var cause = Loc.L(ex is UnauthorizedAccessException ? "Archive.Failed.Access" : "Archive.Failed.Files"); - return (new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Failed, 0, Error: Loc.L("Archive.Convert.NotPlaced", cause)), []); + return new StepDone(Result(row, ConvertOutcome.Failed, error: Loc.L("Archive.Convert.NotPlaced", cause))); } } + /// + /// What the job converts of a sequence whose plan is now : the photos it pinned when it first came to + /// it, each still planned with the content it had then (photos that came in or were verified since stay as they are); the + /// first time, the whole plan while it is still the one confirmed (the step's digest; a job an earlier build queued: its + /// frames version). Null when it is not: the sequence changed after the plan, and the user plans again. + /// + internal static ConvertSequencePlan? Confirmed(ConvertSequence step, ConvertSequencePlan fresh, PinnedSequence? pin) + { + if (pin is not null) + { + var now = fresh.Frames.ToDictionary(f => f.FrameId); + var frames = new List(pin.Frames.Count); + foreach (var pinned in pin.Frames) + { + if (!now.TryGetValue(pinned.Id, out var frame) || !string.Equals(frame.Sha256, pinned.Sha256, StringComparison.OrdinalIgnoreCase)) return null; + frames.Add(frame); + } + return frames.Count > 0 ? fresh with { FramesVersion = pin.FramesVersion, Frames = frames } : null; + } + if (fresh.Frames.Count == 0) return null; + var confirmed = step.Frames is { } digest + ? string.Equals(fresh.Digest(), digest, StringComparison.Ordinal) + : fresh.FramesVersion == step.FramesVersion; + return confirmed ? fresh : null; + } + + /// Whether every photo of is a frame of still holding the content it was planned with. + private static bool Holds(SequenceManifest manifest, ConvertSequencePlan planned) + { + var frames = manifest.Frames.ToDictionary(f => f.Id); + return planned.Frames.All(p => frames.TryGetValue(p.FrameId, out var f) && string.Equals(f.Sha256, p.Sha256, StringComparison.OrdinalIgnoreCase)); + } + + private static ConvertSequenceResult Result(Sequence row, ConvertOutcome outcome, int frames = 0, string? error = null) => + new(row.Id, row.DisplayTitle, outcome, frames, Error: error); + /// /// 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 @@ -330,32 +439,39 @@ public sealed class MassConverter private static bool Intact(string path, StagedConversion conversion) { - var file = new FileInfo(path); - if (!file.Exists || file.Length != conversion.Size) return false; + if (!Present(path, conversion)) 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); } + /// Whether a staged conversion's file is there at its size (not re-hashed). + private static bool Present(string path, StagedConversion conversion) => new FileInfo(path) is { Exists: true } file && file.Length == conversion.Size; + /// /// 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, localised; the exception goes to the - /// diagnostics log); the frames converted meanwhile stay staged for a retry. + /// is consumed (in frame order). A photo starts only while the volume has the space it and those being converted may + /// take, with the reserve: short of it the job stops (Archive.Error.ConvertSpace) before the volume fills. Returns + /// the first failure (the file and why, localised; the exception goes to the diagnostics log); the frames converted + /// meanwhile stay staged for a retry. /// + /// The volume lacks the space for the next photo; what was staged stays. private async Task StageAsync(Sequence row, SequenceManifest manifest, SequencePaths folder, ConvertSequencePlan planned, - Dictionary ready, string staging, ConvertOptions options, StagedLog staged, Progress progress, ConvertCallbacks callbacks, - CancellationToken cancellationToken) + Dictionary ready, string staging, ConvertOptions options, StagedLog staged, Progress progress, SpaceWatch space, + 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(); + var todo = planned.Frames.Where(f => !ready.ContainsKey(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)); + var largest = todo.Max(f => (long)Math.Max(frames[f.FrameId].W, 0) * Math.Max(frames[f.FrameId].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; + var estimates = todo.ToDictionary(f => f.FrameId, f => f.EstimatedBytes); string? failure = null; Exception? error = null; + string? full = null; await using var work = new OrderedWork(atOnce, async result => { if (result.Conversion is not { } conversion) @@ -369,14 +485,26 @@ public sealed class MassConverter } staged.Append(row.Id, planned.FramesVersion, conversion); ready[conversion.FrameId] = conversion; + space.Staged(conversion.Size, estimates[conversion.FrameId]); await callbacks.Progress(++progress.Done, progress.Total).ConfigureAwait(false); }, cancellationToken); - foreach (var frame in todo) + foreach (var next in todo) { if (failure is not null) break; + if (space.Short(next.EstimatedBytes * atOnce) is { } message) + { + full = message; + break; + } + var frame = frames[next.FrameId]; await work.AddAsync(token => Stage(frame, manifest, folder, staging, options, decoder, threads, token)).ConfigureAwait(false); } await work.CompleteAsync().ConfigureAwait(false); + if (full is not null) + { + Core.Diagnostics.Log.Warning("archive", $"{row.DisplayTitle}: the conversion stops, {full}"); + throw new IOException(full); + } if (failure is not null) Core.Diagnostics.Log.Warning("archive", $"{row.DisplayTitle}: not converted", error); return failure; } @@ -411,28 +539,26 @@ public sealed class MassConverter } /// - /// Stage B of : the staged files take their frames' place (), - /// each named as filing names a photo of the sequence (: the archive's file template, - /// the frame and the sequence as the sidecar has them under the lease), made unique among every file there. + /// Stage B of : the staged files take their frames' place () + /// while every photo pinned still holds the content converted (photos that came in since stay as they are, so the frames + /// version is not held to the plan's), each named as filing names a photo of the sequence (: + /// the archive's file template, the frame and the sequence as the sidecar has them under the lease), made unique among + /// every file there. /// - private async Task<(ConvertSequenceResult, IReadOnlyList)> ReplaceAsync(Archive archive, ArchivePaths paths, Sequence row, - ConvertSequencePlan planned, SequenceManifest manifest, Dictionary ready, string staging, ConvertOptions options, - string? createdBy, CancellationToken cancellationToken) + private async Task ReplaceAsync(Archive archive, ArchivePaths paths, Sequence row, ConvertSequencePlan planned, + Dictionary ready, string staging, ConvertOptions options, string? replacedBy, CancellationToken cancellationToken) { var template = PathTemplate.Parse(archive.FileTemplate); - var swaps = manifest.Frames.Where(f => ready.ContainsKey(f.Id)).Select(f => + var swaps = planned.Frames.Select(f => { - var conversion = ready[f.Id]; - return new FrameSwap(f.Id, paths.ToRelative(Path.Combine(staging, conversion.File)), [], (current, sequence) => options.FileName(template, current, sequence), + var conversion = ready[f.FrameId]; + return new FrameSwap(f.FrameId, paths.ToRelative(Path.Combine(staging, conversion.File)), [], (current, sequence) => options.FileName(template, current, sequence), 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)); + var replaced = await _frames.ReplaceAsync(archive, row.Id, null, swaps, replacedBy, null, (now, _, _) => Task.FromResult(Holds(now, planned)), + cancellationToken).ConfigureAwait(false); + if (replaced is null) return new StepDone(Result(row, ConvertOutcome.Changed)); + return new StepDone(Result(row, ConvertOutcome.Converted, swaps.Count), replaced.Had, _frames.FollowUps(archive, replaced.Sequence, replaced.Had)); } /// @@ -458,37 +584,57 @@ public sealed class MassConverter }; /// - /// Stage B of : the staged files filed into the sequence of - /// (made on first use, titled "title (FORMAT)") and named as the ingest names every photo it files there - /// (: {name} the original's name on the card, {ext} the target's), with - /// the source's capture facts; then the source's tags, rating, notes and project (its positions translated to the new frames). + /// Stage B of : once the source's photos pinned are checked under its lease as a Replace + /// checks them, the staged files filed into the sequence of (made on first use, titled "title (FORMAT)", + /// owned by the source's owner, else by who asked for it) and named as the ingest names every photo it files there + /// (: {name} the original's name on the card, {ext} the target's), with the + /// source's capture facts; then the source's tags, rating, notes and project (its positions translated to the new frames). + /// Every conversion not filed yet must still be staged whole: one gone since (a clean-up, a quarantine) fails the sequence + /// rather than leave its photo out. The photos the plan did not convert are not in the new sequence (). /// - private async Task<(ConvertSequenceResult, IReadOnlyList)> CreateAsync(Archive archive, ArchivePaths paths, Sequence row, - SequenceManifest manifest, Dictionary ready, string staging, ConvertOptions options, string key, string? createdBy, - CancellationToken cancellationToken) + private async Task CreateAsync(Archive archive, ArchivePaths paths, Sequence row, ConvertSequencePlan planned, + Dictionary ready, string staging, ConvertOptions options, string key, Guid? requestedBy, 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 => + SequenceManifest manifest; + await using (await _writer.LockAsync(paths, row.Id, cancellationToken).ConfigureAwait(false)) { - var conversion = ready[f.Id]; + if (await _db.Sequences.GetAsync(row.Id, cancellationToken).ConfigureAwait(false) is not { } now || now.ArchiveId != archive.Id) + return new StepDone(Result(row, ConvertOutcome.Changed)); + row = now; + manifest = SequenceWriter.ReadLocked(paths.Sequence(row.Folder), row.Id); + if (!Holds(manifest, planned)) return new StepDone(Result(row, ConvertOutcome.Changed)); + } + var frames = manifest.Frames.ToDictionary(f => f.Id); + var filed = await FiledAsync(archive, key, cancellationToken).ConfigureAwait(false); + var pending = new List(); + foreach (var converted in planned.Frames) + { + var conversion = ready[converted.FrameId]; + if (filed.Contains(conversion.Sha256)) continue; + var frame = frames[converted.FrameId]; 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, null) + if (!Present(path, conversion)) throw new FileNotFoundException($"The conversion of {frame.File} is no longer staged; a retry converts it again.", path); + pending.Add(new StagedFrame(path, frame.Original ?? Path.GetFileName(frame.File), conversion.Size, conversion.Sha256, Metadata(path, frame), null, null) { - NamedAs = options.WithExtension(Path.GetFileName(f.File)), - }; - }).ToList(); + NamedAs = options.WithExtension(Path.GetFileName(frame.File)), + }); + } var title = $"{manifest.Title ?? row.DisplayTitle} ({options.Label})"; + // A user id, as every filing records it (the owner a row is given), never a user name. + var owner = (row.OwnerUserId ?? requestedBy)?.ToString(); // 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); + await _ingest.CommitSessionAsync(archive, new SequenceTarget(key, title, null, owner), 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))); + var leftOut = manifest.Frames.Count - planned.Frames.Count; + Core.Diagnostics.Log.Info("archive", $"{row.DisplayTitle}: {planned.Frames.Count} photo(s) converted into the new sequence {made.DisplayTitle}, {leftOut} left in the source alone"); + var had = row.Status & (SequenceStatus.AnalyzedDeep | SequenceStatus.ThumbsBuilt | SequenceStatus.ProxiesBuilt); + return new StepDone(new ConvertSequenceResult(row.Id, row.DisplayTitle, ConvertOutcome.Created, planned.Frames.Count, id, LeftOut: leftOut), had, + _frames.FollowUps(archive, made, had)); } /// @@ -553,13 +699,31 @@ public sealed class MassConverter /// /// 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. + /// journal said so): every photo it pinned is a frame holding a file of the target's format converted from the content + /// pinned. Without a pin (its journal lost), the frames holding a conversion to the target are, by their sources, the + /// photos confirmed (the step's digest); a job an earlier build queued: every staged conversion is a frame holding the + /// converted content. Null otherwise. /// - private static int? ReplacedEarlier(ArchivePaths paths, Sequence row, IReadOnlyList noted) + private static int? ReplacedEarlier(SequenceManifest manifest, ConvertSequence step, PinnedSequence? pin, IReadOnlyList noted, + ConvertOptions options) { - if (noted.Count == 0 || Read(paths.Sequence(row.Folder), row.Id) is not { } manifest) return null; var frames = manifest.Frames.ToDictionary(f => f.Id); + if (pin is not null) + { + return pin.Frames.Count > 0 && pin.Frames.All(p => frames.TryGetValue(p.Id, out var f) && f.Format == options.Format + && string.Equals(f.Source?.Sha256, p.Sha256, StringComparison.OrdinalIgnoreCase) + && !string.Equals(f.Sha256, p.Sha256, StringComparison.OrdinalIgnoreCase)) + ? pin.Frames.Count + : null; + } + if (step.Frames is { } digest) + { + var converted = manifest.Frames.Where(f => f.Format == options.Format && f.Source?.Sha256 is not null).ToList(); + return converted.Count > 0 && string.Equals(ConvertSequencePlan.DigestOf(converted.Select(f => (f.Id, f.Source!.Sha256))), digest, StringComparison.Ordinal) + ? converted.Count + : null; + } + if (noted.Count == 0) return null; 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() @@ -567,23 +731,60 @@ public sealed class MassConverter } /// - /// The sequence before its stage A, under its lease: where the index has it now (a Reorganize, another host's or one this - /// job made way for, may have moved its folder since the job planned) and its sidecar as every writer reads it - /// (: a rename of its files, a deletion, a replacement, a restore or an ingest a - /// crash left half-way is settled first), so stage A converts the files the sidecar names. Stage B reads it again under - /// that lease. Null when the sequence left the archive. + /// The row of a sequence this job replaced the frames of, the index brought in line with its sidecar when a crash left it + /// behind (after the sidecar was written, before the index followed); a failure is logged, and the next scan does it. The + /// caller holds the sequence's lease. /// - private async Task<(Sequence Row, SequencePaths Folder, SequenceManifest Manifest)?> SettledAsync(Archive archive, ArchivePaths paths, Guid id, - CancellationToken cancellationToken) + private async Task SyncedAsync(Archive archive, SequencePaths folder, Sequence row, SequenceManifest manifest) { - await using (await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false)) + if (row.FramesVersion == manifest.Versions.Frames) return row; + try { - if (await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } row || row.ArchiveId != archive.Id) return null; - var folder = paths.Sequence(row.Folder); - return (row, folder, SequenceWriter.ReadLocked(folder, id)); + // The photos moved with the replacement: the next incremental scan looks at them again. + await _service.Indexer.SyncAsync(archive, folder, manifest, null, Uncovered, photosChanged: true, CancellationToken.None).ConfigureAwait(false); + return await _db.Sequences.GetAsync(row.Id, CancellationToken.None).ConfigureAwait(false) ?? row; + } + catch (Exception ex) when (ex is DatabaseException or IOException or UnauthorizedAccessException) + { + Core.Diagnostics.Log.Warning("archive", $"{row.DisplayTitle}: the index did not follow its converted frames; the next scan resyncs it", ex); + return row; } } + /// + /// The row of a sequence still to convert, its sidecar settled first under its lease when a writer a crash interrupted left + /// a journal in its folder (): planned as its files lie half-way, photos in the + /// trash would count as missing. The row as it was when there is none, or when the settle cannot run now (the sequence's + /// turn reports it). + /// + private async Task SettledRowAsync(Archive archive, ArchivePaths paths, Sequence row, CancellationToken cancellationToken) + { + if (!HasJournal(paths.Sequence(row.Folder))) return row; + try + { + await using (await _writer.LockAsync(paths, row.Id, cancellationToken).ConfigureAwait(false)) + { + if (await _db.Sequences.GetAsync(row.Id, cancellationToken).ConfigureAwait(false) is not { } now || now.ArchiveId != archive.Id) return row; + SequenceWriter.ReadLocked(paths.Sequence(now.Folder), now.Id); + return now; + } + } + catch (ArchiveOfflineException) + { + throw; + } + catch (Exception ex) when (ex is LeaseUnavailableException or IOException or UnauthorizedAccessException or InvalidDataException or InvalidOperationException) + { + Core.Diagnostics.Log.Warning("archive", $"{row.DisplayTitle}: what a crash left half-way in it could not be settled yet", ex); + return row; + } + } + + /// Whether a writer left a journal in the sequence's folder: a rename of its files, a deletion, a replacement, a restore or an ingest. + private static bool HasJournal(SequencePaths folder) => + File.Exists(folder.FileRenameJournalPath) || File.Exists(folder.RemovalJournalPath) || File.Exists(folder.ReplaceJournalPath) + || File.Exists(folder.RestoreJournalPath) || File.Exists(folder.IngestJournalPath); + /// The sidecar of a sequence, read without its lease; null when it cannot be read or names another sequence. private static SequenceManifest? Read(SequencePaths folder, Guid id) { @@ -599,14 +800,68 @@ public sealed class MassConverter } } - /// Free bytes of the archive's volume as the host counts them (); null when unknown. + /// + /// The passes a sequence this job converted or made in an earlier attempt needs, from its journal (a pause, a yield, a stop + /// or a crash came before they were queued); null for any other outcome. + /// + private async Task?> FollowUpsAsync(Archive archive, ConvertJournalSequence noted, CancellationToken cancellationToken) + { + if (noted.Outcome == ConvertOutcome.Converted) + { + return await _db.Sequences.GetAsync(noted.Id, cancellationToken).ConfigureAwait(false) is { } row && row.ArchiveId == archive.Id + ? _frames.FollowUps(archive, row, noted.Had ?? row.Status) + : []; + } + if (noted is { Outcome: ConvertOutcome.Created, NewSequenceId: { } id }) + { + return await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } made && made.ArchiveId == archive.Id + ? _frames.FollowUps(archive, made, noted.Had ?? 0) + : []; + } + return null; + } + + /// The bytes the photos converts are estimated at, but for those whose staged file is there already. + private static long Unstaged(ArchivePaths paths, Guid jobId, ConvertSequencePlan plan, StagedLog staged) + { + var folder = StagingOf(paths, jobId, plan.SequenceId); + var there = staged.Of(plan.SequenceId, plan.FramesVersion).Where(c => Present(Path.Combine(folder, c.File), c)).Select(c => c.FrameId).ToHashSet(); + return plan.Frames.Where(f => !there.Contains(f.FrameId)).Sum(f => f.EstimatedBytes); + } + + /// + /// Refuses to go on while the volume lacks the space the photos still to convert need: their estimates, + /// bytes, as the files staged so far scale them. + /// + /// The volume lacks it (Archive.Error.ConvertSpace). + private static void EnsureSpace(long estimated, SpaceWatch space) + { + if (estimated > 0 && space.Short(estimated) is { } message) throw new IOException(message); + } + + /// + /// Free bytes where a conversion writes, as the host counts them (): the volume of + /// the archive root and the one of its staging folder, the tighter; null when neither can be measured. + /// private long? FreeSpace(ArchivePaths paths) { - if (_writer.Options.FreeSpace is { } measure) return measure(paths.Root); + long? free = null; + foreach (var folder in (string[])[paths.Root, paths.StagingDirectory]) + { + if (!System.IO.Directory.Exists(folder) || Measure(folder) is not { } bytes) continue; + free = free is { } known ? Math.Min(known, bytes) : bytes; + } + return free; + } + + private long? Measure(string folder) + { + if (_writer.Options.FreeSpace is { } measure) return measure(folder); 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; + // Windows wants a drive root (a network share is measured by the host); Unix accepts any directory and reports the + // volume it is mounted on. + return new DriveInfo(OperatingSystem.IsWindows() ? Path.GetPathRoot(folder)! : folder).AvailableFreeSpace; } catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException) { @@ -626,6 +881,8 @@ public sealed class MassConverter _ => Loc.L("Archive.Log.ConvertFailed", result.Title, result.Error), }; callbacks.Log(line); + // A new sequence holds only the photos converted: those the plan skipped stay in the source alone. + if (result is { Outcome: ConvertOutcome.Created, LeftOut: > 0 }) callbacks.Log(Loc.L("Archive.Log.ConvertLeftOut", result.Title, result.LeftOut)); } private static string Gigabytes(long bytes) => Loc.L("Common.Size.GB", (bytes / 1e9).ToString("0.#", Loc.Culture)); @@ -633,13 +890,14 @@ public sealed class MassConverter /// The session key of the new sequence a conversion makes from . internal static string SessionKey(Guid job, Guid source) => $"convert:{job:N}:{source:N}"; - private static string StagingFolder(Guid job) => $"convert-{job:N}"; + /// The folder under .chronos/staging a conversion job stages into, one subfolder per sequence. + internal static string StagingFolder(Guid job) => ConvertJournal.Prefix + job.ToString("N"); private static string StagingOf(ArchivePaths paths, Guid job, Guid sequence) => Path.Combine(paths.StagingDirectory, StagingFolder(job), sequence.ToString("N")); /// Deletes what a conversion staged that no step needs any more (converted copies, never originals); a failure is logged. - private static void DeleteStaging(string folder) + internal static void DeleteStaging(string folder) { try { @@ -651,13 +909,61 @@ public sealed class MassConverter } } - /// Photos converted so far and in all. - private sealed class Progress(long total, long done) + /// Photos converted so far and in all, counted per sequence. + private sealed class Progress { - public long Total { get; } = total; - public long Done { get; set; } = done; + private readonly Dictionary _counted = []; + + public long Total { get; private set; } + + public long Done { get; set; } + + /// Counts the photos a sequence converts and those staged already, in place of what was counted for it before. + public void Count(Guid sequence, int frames, int staged) + { + if (_counted.TryGetValue(sequence, out var counted)) + { + Total -= counted.Frames; + Done -= counted.Staged; + } + _counted[sequence] = (frames, staged); + Total += frames; + Done += staged; + } } + /// + /// The free space a running conversion watches: measured where it writes, against estimates scaled by how far the files it + /// staged came out above theirs (photos of a 14-bit RAW carry more noise than the estimate's bits per pixel allow for). + /// + private sealed class SpaceWatch(MassConverter converter, ArchivePaths paths) + { + private long _actual; + private long _estimated; + + /// The bytes staged over their estimates, at least 1. + public double Ratio => _estimated > 0 ? Math.Max(1, (double)_actual / _estimated) : 1; + + public void Staged(long actual, long estimated) + { + _actual += actual; + _estimated += Math.Max(1, estimated); + } + + /// + /// Why the volume cannot take bytes more (scaled, with the margin and the reserve), localized; + /// null when it can, or when its free space cannot be measured. + /// + public string? Short(long estimated) + { + var space = new ConvertSpace(ConvertPlanner.Required((long)Math.Ceiling(estimated * Ratio)), converter.FreeSpace(paths)); + return space.Enough ? null : Loc.L("Archive.Error.ConvertSpace", Gigabytes(space.Required), Gigabytes(space.Free ?? 0)); + } + } + + /// What a sequence came to: its result, the statuses its follow-ups follow from, and those follow-ups (null: none to queue). + private sealed record StepDone(ConvertSequenceResult Result, SequenceStatus? Had = null, IReadOnlyList? FollowUps = null); + /// A photo of stage A: its file and its staged conversion, or why it failed. private sealed record Staged(string File, StagedConversion? Conversion, Exception? Error); } @@ -670,21 +976,43 @@ internal sealed record StagedConversion(Guid FrameId, string Source, string File /// A line of the staged log: a staged conversion of a sequence at a frames version. internal sealed record StagedLine(Guid Sequence, int FramesVersion, StagedConversion Conversion); +/// The photos of a sequence a conversion job pinned: the frames version then, and each photo with the content converted. +internal sealed record PinnedSequence(Guid Sequence, int FramesVersion, IReadOnlyList Frames); + +/// A photo pinned: its frame and the SHA-256 of the content converted. +internal sealed record PinnedFrame(Guid Id, string Sha256); + /// /// The journal of a conversion job (.chronos/journal/convert-<job>.json, owner review 2, R7): what each sequence -/// came to, written after each one; with it, the staged log (convert-<job>.staged), 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. +/// came to, and whether the passes it needs were queued, written after each one; with it, the pin log +/// (convert-<job>.pins, ), the photos the job converts of each sequence, and the staged log +/// (convert-<job>.staged), one line per photo staged, both appended and flushed as they grow, so a job of thousands +/// of photos journals each once. A resumed or retried job keeps the sequences that are final, the photos pinned, and the +/// staged files whose hash still verifies. All of it goes when every sequence is final, or once the job is gone +/// (). /// internal sealed class ConvertJournal { + /// How the journal files and the staging folder of a conversion job begin, before the job's id. + public const string Prefix = "convert-"; + public Guid JobId { get; set; } public List Sequences { get; set; } = []; public ConvertJournalSequence? Of(Guid id) => Sequences.FirstOrDefault(s => s.Id == id); - public void Note(ConvertSequenceResult result) + /// Notes a sequence the job comes to and pins, with the statuses it had then. + public void Begin(Guid id, string title, SequenceStatus had) + { + var noted = Of(id); + if (noted is null) Sequences.Add(noted = new ConvertJournalSequence { Id = id }); + noted.Title = title; + noted.Had = had; + } + + /// Notes what a sequence came to and, when it was converted or made, the statuses its follow-ups follow from. + public void Note(ConvertSequenceResult result, SequenceStatus? had = null) { var noted = Of(result.SequenceId); if (noted is null) Sequences.Add(noted = new ConvertJournalSequence { Id = result.SequenceId }); @@ -692,11 +1020,26 @@ internal sealed class ConvertJournal noted.Outcome = result.Outcome; noted.Frames = result.Frames; noted.NewSequenceId = result.NewSequenceId; + if (had is { } status) noted.Had = status; } - public static string PathFor(ArchivePaths paths, Guid job) => Path.Combine(paths.JournalDirectory, $"convert-{job:N}.json"); + public static string PathFor(ArchivePaths paths, Guid job) => Path.Combine(paths.JournalDirectory, $"{Prefix}{job:N}.json"); - public static string StagedPathFor(ArchivePaths paths, Guid job) => Path.Combine(paths.JournalDirectory, $"convert-{job:N}.staged"); + public static string StagedPathFor(ArchivePaths paths, Guid job) => Path.Combine(paths.JournalDirectory, $"{Prefix}{job:N}.staged"); + + public static string PinsPathFor(ArchivePaths paths, Guid job) => Path.Combine(paths.JournalDirectory, $"{Prefix}{job:N}.pins"); + + /// + /// The conversion job a journal file or a staging folder belongs to, from its name (convert-<job> and any + /// extension); null for any other name. + /// + public static Guid? JobOf(string name) + { + if (!name.StartsWith(Prefix, StringComparison.Ordinal)) return null; + var rest = name[Prefix.Length..]; + var dot = rest.IndexOf('.', StringComparison.Ordinal); + return Guid.TryParseExact(dot < 0 ? rest : rest[..dot], "N", out var job) ? job : null; + } /// The journal of ; null when there is none, or it is torn. public static ConvertJournal? Read(ArchivePaths paths, Guid job) @@ -723,9 +1066,15 @@ internal sealed class ConvertJournal /// The staged log of this job, read now. public StagedLog Staged(ArchivePaths paths) => StagedLog.Open(StagedPathFor(paths, JobId)); + /// The pin log of this job, read now. + public PinLog Pins(ArchivePaths paths) => PinLog.Open(PinsPathFor(paths, JobId)); + + /// The journal files of , whichever exist. + public static IEnumerable Files(ArchivePaths paths, Guid job) => [StagedPathFor(paths, job), PinsPathFor(paths, job), PathFor(paths, job)]; + public static void Delete(ArchivePaths paths, Guid job) { - foreach (var path in new[] { StagedPathFor(paths, job), PathFor(paths, job) }) + foreach (var path in Files(paths, job)) { if (File.Exists(path)) File.Delete(path); } @@ -745,6 +1094,15 @@ internal sealed class ConvertJournalSequence public Guid? NewSequenceId { get; set; } + /// + /// The statuses the passes it needs follow from: the sequence's before its frames were replaced, or the source's a new + /// sequence takes on (a deep analysis, thumbnails, proxies). + /// + public SequenceStatus? Had { get; set; } + + /// The passes it needs were queued (a resumed job queues them when they were not). + public bool Queued { get; set; } + [JsonIgnore] public bool Final => Outcome is ConvertOutcome.Converted or ConvertOutcome.Created or ConvertOutcome.Nothing; } @@ -761,10 +1119,8 @@ internal sealed class StagedLog 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)) + foreach (var line in JournalLines.Read(path)) { - if (string.IsNullOrWhiteSpace(line)) continue; try { if (JsonSerializer.Deserialize(line, ArchiveJobJson.Default.StagedLine) is { } staged) log.Add(staged); @@ -785,13 +1141,7 @@ internal sealed class StagedLog 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); - } + JournalLines.Append(_path, JsonSerializer.SerializeToUtf8Bytes(line, ArchiveJobJson.Default.StagedLine)); Add(line); } @@ -801,3 +1151,60 @@ internal sealed class StagedLog frames[line.Conversion.FrameId] = line.Conversion; } } + +/// +/// The pin log of a conversion job (): the photos it converts of each sequence, pinned under the +/// sequence's lease the first time the job comes to it, while its plan is still the one confirmed. A retry converts those, +/// never photos that came in or were verified since. One line per sequence, appended and flushed. +/// +internal sealed class PinLog +{ + private readonly string _path; + private readonly Dictionary _pins = []; + + private PinLog(string path) => _path = path; + + /// The log at ; a line torn by a crash is skipped (that sequence is held to the plan confirmed again). + public static PinLog Open(string path) + { + var log = new PinLog(path); + foreach (var line in JournalLines.Read(path)) + { + try + { + if (JsonSerializer.Deserialize(line, ArchiveJobJson.Default.PinnedSequence) is { } pinned) log._pins[pinned.Sequence] = pinned; + } + catch (JsonException) + { + // Torn while appended. + } + } + return log; + } + + public PinnedSequence? Of(Guid sequence) => _pins.GetValueOrDefault(sequence); + + /// Pins the photos converts, and flushes it to disk. + public void Append(Guid sequence, ConvertSequencePlan planned) + { + var pinned = new PinnedSequence(sequence, planned.FramesVersion, [.. planned.Frames.Select(f => new PinnedFrame(f.FrameId, f.Sha256 ?? string.Empty))]); + JournalLines.Append(_path, JsonSerializer.SerializeToUtf8Bytes(pinned, ArchiveJobJson.Default.PinnedSequence)); + _pins[sequence] = pinned; + } +} + +/// Files of JSON lines a job appends to as it goes: each line written whole and flushed to disk, read back skipping blank ones. +internal static class JournalLines +{ + public static IEnumerable Read(string path) => + File.Exists(path) ? File.ReadLines(path, Encoding.UTF8).Where(l => !string.IsNullOrWhiteSpace(l)) : []; + + public static void Append(string path, byte[] json) + { + System.IO.Directory.CreateDirectory(Path.GetDirectoryName(path)!); + using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read); + stream.Write(json); + stream.WriteByte((byte)'\n'); + stream.Flush(flushToDisk: true); + } +} diff --git a/src/Chronos.Data/Archiving/SequenceWriter.cs b/src/Chronos.Data/Archiving/SequenceWriter.cs index 32a94a44..d518a81c 100644 --- a/src/Chronos.Data/Archiving/SequenceWriter.cs +++ b/src/Chronos.Data/Archiving/SequenceWriter.cs @@ -63,9 +63,11 @@ public sealed record ArchiveServiceOptions public Func? SequenceChanged { get; init; } /// - /// 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. + /// The free bytes a write under a folder of an archive (its root, its staging folder) may count on, as the host counts + /// them: a server takes the tighter of its space volume (owner review 2, R2) and the folder's own volume, the desktop asks + /// Windows, which measures a network share too; null: the folder's drive (). A conversion checks its + /// estimate against it before it starts, before each sequence and before each photo (R7). The function returns null when + /// the space cannot be measured. /// public Func? FreeSpace { get; init; } diff --git a/src/Chronos.Server/Storage/ArchiveModule.cs b/src/Chronos.Server/Storage/ArchiveModule.cs index 768bece1..75b8def1 100644 --- a/src/Chronos.Server/Storage/ArchiveModule.cs +++ b/src/Chronos.Server/Storage/ArchiveModule.cs @@ -42,8 +42,10 @@ public static class ArchiveModule events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion)); }, Decoder = DecoderFactory.CreateServer(), - // What the panel shows as the archive's free space (owner review 2, R2): a conversion's estimate is checked against it. - FreeSpace = volumes is null ? null : root => volumes.Report(root).Space?.FreeBytes, + // Where a conversion writes (owner review 2, R7): the tighter of what the panel shows as the archive's free space + // (R2: the space path's volume) and the volume the archive's folders are on, which takes every byte it stages + // and files (on Unraid the cache, until the mover runs). + FreeSpace = volumes is null ? null : volumes.WritableFree, Owner = Owner, ImagesAfterScan = true, Parallelism = () => options.Parallelism, diff --git a/src/Chronos.Server/Storage/VolumeSpace.cs b/src/Chronos.Server/Storage/VolumeSpace.cs index b705c524..c36c1bc8 100644 --- a/src/Chronos.Server/Storage/VolumeSpace.cs +++ b/src/Chronos.Server/Storage/VolumeSpace.cs @@ -47,6 +47,17 @@ public class VolumeSpace(ServerOptions options, ILogger logger) } } + /// + /// The free bytes a write under the folder of the archive may count on (a conversion checks its + /// estimate against it, owner review 2, R7): the tighter of the space volume and the volume the folder is on, which on + /// Unraid is the cache a share writes to until the mover runs; null when neither can be measured. + /// + public long? WritableFree(string path) + { + var report = Report(path); + return report.Space is { } space && report.Write is { } write ? Math.Min(space.FreeBytes, write.FreeBytes) : report.Space?.FreeBytes; + } + /// /// The storage figures of the archive at : of the space path when one is set and can be /// measured, else of the archive root (a space path that cannot be measured is logged once, until it can again). diff --git a/tests/Chronos.Core.Tests/Conversion/ConvertPlannerTests.cs b/tests/Chronos.Core.Tests/Conversion/ConvertPlannerTests.cs index 2dfa2d11..d400d547 100644 --- a/tests/Chronos.Core.Tests/Conversion/ConvertPlannerTests.cs +++ b/tests/Chronos.Core.Tests/Conversion/ConvertPlannerTests.cs @@ -54,6 +54,7 @@ public sealed class ConvertPlannerTests(TestContext context) Assert.Equal((manifest.Id, "Roof", "2026/roof", 7), (plan.SequenceId, plan.Title, plan.Folder, plan.FramesVersion)); Assert.SequenceEqual([0], plan.Frames.Select(f => f.Index)); + Assert.Equal("s0", plan.Frames.Single().Sha256); Assert.SequenceEqual( [(ConvertSkip.SameFormat, 1), (ConvertSkip.NoNativeDecoder, 2), (ConvertSkip.PreviewOnly, 1), (ConvertSkip.Undecodable, 1), (ConvertSkip.Missing, 2), (ConvertSkip.Unhashed, 1)], @@ -219,6 +220,28 @@ public sealed class ConvertPlannerTests(TestContext context) Plan(new ConvertOptions(ConvertTarget.Jpeg, 80), ConvertMode.Replace, Sequence(3, 2)).Fingerprint()); } + [Test] + public void TheDigestFollowsThePhotosConvertedAndTheirContent() + { + var a = Guid.NewGuid(); + var b = Guid.NewGuid(); + ConvertSequencePlan Sequence(int version, params (Guid Id, string Sha)[] frames) => + new(Guid.Empty, "Roof", "roof", version, [.. frames.Select((f, i) => new ConvertFramePlan(f.Id, i, $"f{i}", ImageFileFormat.Cr2, 10, 20, f.Sha))], [], []); + var reference = Sequence(3, (a, "aa"), (b, "bb")).Digest(); + Assert.Equal(64, reference.Length); + // The frames version and the case of a hash say nothing of what converts. + Assert.Equal(reference, Sequence(4, (a, "AA"), (b, "bb")).Digest()); + Assert.Equal(reference, ConvertSequencePlan.DigestOf([(a, "aa"), (b, "bb")])); + // Another content, a photo fewer or more (verified since the plan), the same photos in another order: another digest. + Assert.NotEqual(reference, Sequence(3, (a, "aa"), (b, "cc")).Digest()); + Assert.NotEqual(reference, Sequence(3, (a, "aa")).Digest()); + Assert.NotEqual(reference, Sequence(3, (a, "aa"), (b, "bb"), (Guid.NewGuid(), "dd")).Digest()); + Assert.NotEqual(reference, Sequence(3, (b, "bb"), (a, "aa")).Digest()); + // The plan's fingerprint pins the content too: as many photos of the same size holding other content is another plan. + ConvertPlan Plan(ConvertSequencePlan sequence) => new(Guid.Empty, new ConvertOptions(ConvertTarget.LinearDng), ConvertMode.Replace, [sequence], new ConvertSpace(0, null)); + Assert.NotEqual(Plan(Sequence(3, (a, "aa"), (b, "bb"))).Fingerprint(), Plan(Sequence(3, (a, "aa"), (b, "cc"))).Fingerprint()); + } + /// A provider that reads CR2 natively by format, and probes the files picks (all /// by default) at a fixed tier, the others native. private sealed class ProbeAs(DecodeTier tier, Func? applies = null) : IImageDecoderProvider diff --git a/tests/Chronos.Core.Windows.Tests/Devices/FreeSpaceTests.cs b/tests/Chronos.Core.Windows.Tests/Devices/FreeSpaceTests.cs new file mode 100644 index 00000000..4e0dee73 --- /dev/null +++ b/tests/Chronos.Core.Windows.Tests/Devices/FreeSpaceTests.cs @@ -0,0 +1,32 @@ +using Chronos.Core.Windows.Devices; +using Chronos.Testing; + +namespace Chronos.Core.Windows.Tests.Devices; + +/// +/// The free space of a folder's volume as a conversion checks it on the desktop (owner review 2, R7): a network share's too, +/// which cannot measure. Apart from , which enumerate every volume. +/// +public sealed class FreeSpaceTests(TestContext context) +{ + [Test] + [WindowsOnly] + public void AFolderIsMeasuredOnItsVolumeAndAMissingOneIsNot() + { + var folder = context.CreateTempDirectory("free"); + Assert.Greater(Assert.NotNull(VolumeInfo.FreeBytesAt(folder)), 0); + Assert.Greater(Assert.NotNull(VolumeInfo.FreeBytesAt(folder + Path.DirectorySeparatorChar)), 0); + Assert.Null(VolumeInfo.FreeBytesAt(Path.Combine(folder, "missing", "deeper"))); + } + + [Test] + [WindowsOnly] + public void AFolderOnAShareIsMeasuredWhereTheDriveCannotBe() + { + var folder = Path.GetFullPath(context.CreateTempDirectory("share")); + var share = $@"\\localhost\{char.ToLowerInvariant(folder[0])}$" + folder[2..]; + if (!Directory.Exists(share)) TestContext.Skip("This PC has no administrative share for the test folder."); + Assert.Throws(() => new DriveInfo(Path.GetPathRoot(share)!)); + Assert.Greater(Assert.NotNull(VolumeInfo.FreeBytesAt(share)), 0); + } +} diff --git a/tests/Chronos.Data.Tests/Archiving/ConvertTests.cs b/tests/Chronos.Data.Tests/Archiving/ConvertTests.cs index 023b829d..f7aa08c0 100644 --- a/tests/Chronos.Data.Tests/Archiving/ConvertTests.cs +++ b/tests/Chronos.Data.Tests/Archiving/ConvertTests.cs @@ -10,6 +10,7 @@ using Chronos.Core.Model; using Chronos.Core.Project; using Chronos.Data.Archiving; using Chronos.Data.Archiving.Jobs; +using Chronos.Data.Housekeeping; using Chronos.Data.Jobs; using Chronos.Data.Repositories; using Chronos.Testing; @@ -32,15 +33,15 @@ public sealed class ConvertTests(TestContext context) return more is null ? options : more(options); }); - /// A sequence of uploaded photos (hashed, under originals/), ten seconds apart. - private static async Task UploadedAsync(ArchiveFixture fx, int count, string session = "upload-1", int seed = 100) + /// A sequence of uploaded photos (hashed, under originals/), ten seconds apart, by . + private static async Task UploadedAsync(ArchiveFixture fx, int count, string session = "upload-1", int seed = 100, Guid? user = null) { Guid? id = null; for (var i = 0; i < count; i++) { var (path, size, sha) = fx.Stage(Start.AddSeconds(10 * i).AddTicks(1_234_567), seed + i); var result = await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, id, null, id is null ? session : null, path, $"IMG_{i + 1:0000}.JPG", - size, sha, null, null), fx.Ct); + size, sha, null, user), fx.Ct); id = result.SequenceId; } return id!.Value; @@ -49,6 +50,37 @@ public sealed class ConvertTests(TestContext context) private static Task PlanAsync(ArchiveFixture fx, ConvertTarget target, ConvertMode mode, params Guid[] ids) => fx.Service.PlanConvertAsync(fx.Archive.Id, ids, new ConvertOptions(target), mode, fx.Ct); + /// The parameters the job of runs with. + private static ConvertJobParameters Parameters(ArchiveFixture fx, ConvertPlan plan) => + JsonSerializer.Deserialize(ArchiveJobs.Convert(fx.Archive, plan).ParametersJson!, ArchiveJobJson.Default.ConvertJobParameters)!; + + /// Callbacks that report nothing, but for and when given. + private static ConvertCallbacks Callbacks(Action? progress = null, Action? done = null, + Action>? queue = null) => new( + (n, total) => + { + progress?.Invoke(n, total); + return ValueTask.CompletedTask; + }, + (_, _) => ValueTask.CompletedTask, + _ => { }, + s => + { + done?.Invoke(s); + return ValueTask.CompletedTask; + }, + requests => + { + queue?.Invoke(requests); + return ValueTask.CompletedTask; + }); + + /// The conversion job of , run here as its handler runs it. + private static Task RunHereAsync(ArchiveFixture fx, ConvertPlan plan, Guid jobId, ConvertCallbacks? callbacks = null) => + fx.Service.Converter.RunAsync(fx.Archive, Parameters(fx, plan), jobId, new ConvertRequester(null, null), callbacks ?? Callbacks(), fx.Ct); + + private static string StagingOf(ArchiveFixture fx, Guid job, Guid sequence) => Path.Combine(Staging(fx), $"convert-{job:N}", $"{sequence:N}"); + private static async Task RunAsync(ArchiveFixture fx, JobEngine engine, ConvertPlan plan, JobState state = JobState.Done) { var job = await engine.EnqueueAsync(ArchiveJobs.Convert(fx.Archive, plan), cancellationToken: fx.Ct); @@ -325,11 +357,28 @@ public sealed class ConvertTests(TestContext context) Assert.SequenceEqual(originals.Select(f => (f.Id, f.Sha256, f.RelativePath)), rows.Select(f => (f.Id, f.Sha256, f.RelativePath))); Assert.True((await FramesAsync(fx, good)).All(f => f.Format == ImageFileFormat.Tiff)); Assert.SequenceEqual([good], (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Select(e => e.SequenceId)); - Assert.False(StagedAnything(fx)); - // The journal stays for a retry, which tries the failed sequence again and leaves the converted one. + // The journal stays for a retry, which tries the failed sequence again and leaves the converted one; so does what the + // failed sequence staged before its photo failed, and only that. var journal = Assert.NotNull(ConvertJournal.Read(fx.Paths, job.Id)); Assert.Equal(ConvertOutcome.Converted, journal.Of(good)!.Outcome); Assert.Equal(ConvertOutcome.Failed, journal.Of(bad)!.Outcome); + Assert.False(Directory.Exists(StagingOf(fx, job.Id, good))); + var noted = StagedLog.Open(ConvertJournal.StagedPathFor(fx.Paths, job.Id)).Of(bad, (await fx.Db.Sequences.GetAsync(bad))!.FramesVersion); + Assert.SequenceEqual(noted.Select(c => c.File).Order(), Directory.EnumerateFiles(StagingOf(fx, job.Id, bad)).Select(f => Path.GetFileName(f)).Order()); + Assert.DoesNotContain(damaged.Id, noted.Select(c => c.FrameId)); + var first = Path.Combine(StagingOf(fx, job.Id, bad), noted.Single(c => c.FrameId == originals[0].Id).File); + File.SetLastWriteTimeUtc(first, new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc)); + + // The photo is put right: the retry takes the staged conversion that still verifies and converts the rest. + bytes[^20] ^= 0x10; + File.WriteAllBytes(path, bytes); + await engine.ResumeAsync(job.Id, fx.Ct); + await fx.WaitForAsync(job.Id, JobState.Done, (int)TestTiming.Budget(60)); + var converted = await FramesAsync(fx, bad); + Assert.True(converted.All(f => f.Format == ImageFileFormat.Tiff)); + Assert.Equal(2020, File.GetLastWriteTimeUtc(fx.Paths.FromRelative(converted[0].RelativePath)).Year); + Assert.False(StagedAnything(fx)); + Assert.FileMissing(ConvertJournal.PathFor(fx.Paths, job.Id)); } [Test] @@ -559,13 +608,35 @@ public sealed class ConvertTests(TestContext context) await using var fx = await FixtureAsync(); var journal = new ConvertJournal { JobId = Guid.NewGuid() }; var first = Guid.NewGuid(); - journal.Note(new ConvertSequenceResult(first, "Roof", ConvertOutcome.Created, 3, Guid.NewGuid())); - journal.Note(new ConvertSequenceResult(Guid.NewGuid(), "Harbour", ConvertOutcome.Failed, 0, Error: "no")); + var harbour = Guid.NewGuid(); + journal.Begin(harbour, "Harbour", SequenceStatus.AnalyzedLight | SequenceStatus.ProxiesBuilt); + journal.Note(new ConvertSequenceResult(first, "Roof", ConvertOutcome.Created, 3, Guid.NewGuid()), SequenceStatus.AnalyzedDeep); + journal.Of(first)!.Queued = true; + journal.Note(new ConvertSequenceResult(harbour, "Harbour", ConvertOutcome.Failed, 0, Error: "no")); journal.Write(fx.Paths); var read = Assert.NotNull(ConvertJournal.Read(fx.Paths, journal.JobId)); - Assert.SequenceEqual(journal.Sequences.Select(s => (s.Id, s.Outcome, s.Frames, s.NewSequenceId, s.Final)), - read.Sequences.Select(s => (s.Id, s.Outcome, s.Frames, s.NewSequenceId, s.Final))); + Assert.SequenceEqual(journal.Sequences.Select(s => (s.Id, s.Outcome, s.Frames, s.NewSequenceId, s.Final, s.Had, s.Queued)), + read.Sequences.Select(s => (s.Id, s.Outcome, s.Frames, s.NewSequenceId, s.Final, s.Had, s.Queued))); Assert.True(read.Of(first)!.Final); + // A failure keeps the statuses the sequence had when the job came to it. + Assert.Equal(SequenceStatus.AnalyzedLight | SequenceStatus.ProxiesBuilt, read.Of(harbour)!.Had); + // The photos pinned: a later line for a sequence replaces an earlier one, a torn one is skipped. + var photo = Guid.NewGuid(); + var pins = read.Pins(fx.Paths); + Assert.Null(pins.Of(first)); + ConvertSequencePlan Pinned(int version, string sha) => + new(first, "Roof", "roof", version, [new ConvertFramePlan(photo, 0, "originals/a.jpg", ImageFileFormat.Jpeg, 1, 2, sha)], [], []); + pins.Append(first, Pinned(4, "aa")); + pins.Append(first, Pinned(5, "bb")); + File.AppendAllText(ConvertJournal.PinsPathFor(fx.Paths, journal.JobId), "{\"sequence\":"); + var pinned = Assert.NotNull(read.Pins(fx.Paths).Of(first)); + Assert.Equal((5, photo, "bb"), (pinned.FramesVersion, pinned.Frames.Single().Id, pinned.Frames.Single().Sha256)); + // Its files and its staging folder are known by their names. + Assert.SequenceEqual([journal.JobId, journal.JobId, journal.JobId], + ConvertJournal.Files(fx.Paths, journal.JobId).Select(p => ConvertJournal.JobOf(Path.GetFileName(p)))); + Assert.Equal(journal.JobId, ConvertJournal.JobOf(MassConverter.StagingFolder(journal.JobId))); + Assert.Null(ConvertJournal.JobOf("convert-test")); + Assert.Null(ConvertJournal.JobOf("rename-" + journal.JobId.ToString("N") + ".json")); // A line torn by a crash is skipped; a later line for a frame replaces an earlier one. var path = ConvertJournal.StagedPathFor(fx.Paths, journal.JobId); var log = StagedLog.Open(path); @@ -578,9 +649,14 @@ public sealed class ConvertTests(TestContext context) Assert.Empty(reread.Of(first, 5)); ConvertJournal.Delete(fx.Paths, journal.JobId); Assert.FileMissing(path); + Assert.FileMissing(ConvertJournal.PinsPathFor(fx.Paths, journal.JobId)); Assert.Null(ConvertJournal.Read(fx.Paths, journal.JobId)); - _ = JsonSerializer.Serialize(new ConvertJobParameters(fx.Archive.Id, ConvertTarget.Jpeg, 80, ConvertMode.NewSequence, [new ConvertSequence(first, 2)], "f"), - ArchiveJobJson.Default.ConvertJobParameters); + // A job an earlier build queued names no digest: it reads with none. + var parameters = JsonSerializer.Serialize(new ConvertJobParameters(fx.Archive.Id, ConvertTarget.Jpeg, 80, ConvertMode.NewSequence, + [new ConvertSequence(first, 2, "d")], "f"), ArchiveJobJson.Default.ConvertJobParameters); + Assert.Equal("d", JsonSerializer.Deserialize(parameters, ArchiveJobJson.Default.ConvertJobParameters)!.Sequences.Single().Frames); + var older = $$"""{"archiveId":"{{fx.Archive.Id}}","target":"Jpeg","quality":80,"mode":"Replace","sequences":[{"id":"{{first}}","framesVersion":2}],"fingerprint":"f"}"""; + Assert.Null(JsonSerializer.Deserialize(older, ArchiveJobJson.Default.ConvertJobParameters)!.Sequences.Single().Frames); } [Test] @@ -674,4 +750,308 @@ public sealed class ConvertTests(TestContext context) Assert.SequenceEqual(originals.Select(f => (f.Id, f.Sha256, f.RelativePath)), (await FramesAsync(fx, id)).Select(f => (f.Id, f.Sha256, f.RelativePath))); Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)); } + + [Test] + public async Task PhotosVerifiedAfterThePlanAreNotReplacedWithoutAConfirmation() + { + await using var fx = await FixtureAsync(); + var id = await UploadedAsync(fx, 3); + var engine = await fx.StartEngineAsync(); + var sequence = (await fx.Db.Sequences.GetAsync(id))!; + var path = fx.Paths.Sequence(sequence.Folder).ManifestPath; + var verified = ManifestStore.ReadSequence(path); + // Never verified when the plan is made (adopted): the dry run says that photo stays as it is. + ManifestStore.WriteSequence(path, verified with { Frames = [verified.Frames[0], verified.Frames[1] with { Sha256 = null }, verified.Frames[2]] }); + var plan = await PlanAsync(fx, ConvertTarget.LinearDng, ConvertMode.Replace, id); + Assert.Equal((2, ConvertSkip.Unhashed), (plan.Frames, plan.Sequences.Single().Skipped.Single().Reason)); + // A verify then hashes it before the job runs, as ArchiveVerifier does: no new frames version. + ManifestStore.WriteSequence(path, verified); + var before = await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id); + + var job = await RunAsync(fx, engine, plan, JobState.Failed); + Assert.Equal(Loc.Plural("Archive.Error.ConvertKept", 1), job.Error); + Assert.Contains(Loc.L("Archive.Log.ConvertChanged", sequence.DisplayTitle), job.LogTail); + Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id)); + Assert.SequenceEqual(verified.Frames.Select(f => (f.Id, f.Sha256, f.File)), ManifestStore.ReadSequence(path).Frames.Select(f => (f.Id, f.Sha256, f.File))); + Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)); + Assert.False(StagedAnything(fx)); + // A retry does not convert it either: the user plans again. + await engine.ResumeAsync(job.Id, fx.Ct); + await fx.WaitForAsync(job.Id, JobState.Failed); + Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)); + } + + [Test] + public async Task PhotosThatComeInOnceTheSequenceIsPinnedStayAsTheyAreAndARetryConvertsTheRest() + { + await using var fx = await FixtureAsync(); + var id = await UploadedAsync(fx, 2); + var engine = await fx.StartEngineAsync(); + var plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, id); + var title = (await fx.Db.Sequences.GetAsync(id))!.DisplayTitle; + // An earlier attempt pinned the sequence's photos and stopped (stage B blocked, a pause); an upload came in since. + var jobId = Guid.CreateVersion7(); + PinLog.Open(ConvertJournal.PinsPathFor(fx.Paths, jobId)).Append(id, plan.Sequences.Single()); + var (path, size, sha) = fx.Stage(Start.AddSeconds(60), 999); + await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, id, null, null, path, "IMG_0099.JPG", size, sha, null, null), fx.Ct); + var added = (await FramesAsync(fx, id)).Single(f => f.Sha256 == sha); + + var job = await fx.EnqueueWithCheckpointAsync(engine, ArchiveJobs.Convert(fx.Archive, plan), "convert", jobId); + var done = await fx.WaitForAsync(job.Id, JobState.Done, (int)TestTiming.Budget(60)); + Assert.Contains(Loc.L("Archive.Log.Converted", title, 2), done.LogTail); + var frames = await FramesAsync(fx, id); + Assert.Equal(2, frames.Count(f => f.Format == ImageFileFormat.Tiff)); + Assert.Equal((sha, ImageFileFormat.Jpeg), frames.Where(f => f.Id == added.Id).Select(f => (f.Sha256, f.Format)).Single()); + Assert.Equal(2, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single().Frames); + } + + [Test] + public async Task AJobResumedAfterACrashInItsReplacementSettlesItAndConvertsTheWholeSequence() + { + await using var fx = await FixtureAsync(); + var id = await UploadedAsync(fx, 2); + var engine = await fx.StartEngineAsync(); + var plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, id); + var sequence = (await fx.Db.Sequences.GetAsync(id))!; + var folder = fx.Paths.Sequence(sequence.Folder); + var manifest = Sidecar(fx, sequence); + // The attempt that crashed: the photos pinned and staged, then its replacement cut short once every original had left + // for the trash, none of the converted files in yet. + var jobId = Guid.CreateVersion7(); + PinLog.Open(ConvertJournal.PinsPathFor(fx.Paths, jobId)).Append(id, plan.Sequences.Single()); + var log = StagedLog.Open(ConvertJournal.StagedPathFor(fx.Paths, jobId)); + var entryFolder = Path.Combine(FrameTrash.Directory(fx.Paths), $"{id:N}-20261027120000"); + var record = entryFolder + ".json"; + List outgoing = []; + List incoming = []; + foreach (var frame in manifest.Frames) + { + var staged = Path.Combine(StagingOf(fx, jobId, id), frame.Id.ToString("N") + ".tif"); + var file = FrameConverter.Convert(new ConvertSource(folder.File(frame.File), frame), new ConvertOptions(ConvertTarget.Tiff16), DecoderFactory.CreateServer(), + staged, cancellationToken: fx.Ct); + log.Append(id, manifest.Versions.Frames, new StagedConversion(frame.Id, frame.Sha256!, Path.GetFileName(staged), file.Size, file.Sha256, file.Width, file.Height)); + outgoing.Add(new SwapMove(frame.File, fx.Paths.ToRelative(Path.Combine(entryFolder, "originals", Path.GetFileName(frame.File))))); + incoming.Add(new SwapMove(Path.ChangeExtension(frame.File, ".tif"), fx.Paths.ToRelative(staged))); + } + new FrameReplaceJournal(manifest.Versions.Frames, fx.Paths.ToRelative(record), fx.Paths.ToRelative(entryFolder), outgoing, incoming, false, null).Write(folder); + Directory.CreateDirectory(FrameTrash.Directory(fx.Paths)); + File.WriteAllText(FrameRemovalJournal.PendingRecord(record), "{}"); + foreach (var move in outgoing) + { + var trashed = fx.Paths.FromRelative(move.Other); + Directory.CreateDirectory(Path.GetDirectoryName(trashed)!); + File.Move(folder.File(move.Place), trashed); + } + + // Not a sequence with nothing to convert, nor half of it converted: the originals come back, then all of it converts. + var job = await fx.EnqueueWithCheckpointAsync(engine, ArchiveJobs.Convert(fx.Archive, plan), "convert", jobId); + var done = await fx.WaitForAsync(job.Id, JobState.Done, (int)TestTiming.Budget(60)); + Assert.Contains(Loc.L("Archive.Log.Converted", sequence.DisplayTitle, 2), done.LogTail); + Assert.True((await FramesAsync(fx, id)).All(f => f.Format == ImageFileFormat.Tiff)); + var entry = (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single(); + Assert.Equal((TrashKind.Replaced, 2), (entry.Kind, entry.Frames)); + Assert.False(Directory.Exists(entryFolder)); + } + + [Test] + public async Task TheFollowUpsOfEachSequenceAreQueuedAsItEndsAndOnResumeWhenAPauseCameFirst() + { + await using var fx = await FixtureAsync(); + var first = await UploadedAsync(fx, 2); + var second = await UploadedAsync(fx, 2, "upload-2", seed: 200); + var plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, first, second); + var events = new List(); + var callbacks = Callbacks(done: s => events.Add($"done {s.SequenceId}"), queue: r => events.AddRange(r.Select(q => $"{q.Kind} {q.Targets.Single()}"))); + await RunHereAsync(fx, plan, Guid.CreateVersion7(), callbacks); + // Queued as each sequence is journaled, before the next starts: a pause, a yield or a crash later loses none of them. + Assert.Less(events.IndexOf($"done {first}"), events.IndexOf($"{JobKind.LightAnalyse} {first}")); + Assert.Less(events.IndexOf($"{JobKind.LightAnalyse} {first}"), events.IndexOf($"done {second}")); + Assert.Contains($"{JobKind.LightAnalyse} {second}", events); + + // As a pause right after the first sequence's outcome was journaled leaves the job: its passes not queued yet. + var jobId = Guid.CreateVersion7(); + var journal = new ConvertJournal { JobId = jobId }; + journal.Note(new ConvertSequenceResult(first, "Roof", ConvertOutcome.Converted, 2), SequenceStatus.AnalyzedDeep | SequenceStatus.ThumbsBuilt); + journal.Note(new ConvertSequenceResult(second, "Lake", ConvertOutcome.Converted, 2), SequenceStatus.AnalyzedLight); + journal.Of(second)!.Queued = true; + journal.Write(fx.Paths); + List queued = []; + var resumed = await RunHereAsync(fx, plan, jobId, Callbacks(queue: queued.AddRange)); + Assert.Equal(4, resumed.Frames); + Assert.SequenceEqual([(JobKind.LightAnalyse, first), (JobKind.DeepAnalyse, first), (JobKind.Thumbs, first)], + queued.Select(r => (r.Kind, r.Targets.Single()))); + Assert.FileMissing(ConvertJournal.PathFor(fx.Paths, jobId)); + } + + [Test] + public async Task AConversionWaitingInTheQueueKeepsItsSequencesFromASecondConfirmation() + { + await using var fx = await FixtureAsync(); + var id = await UploadedAsync(fx, 2); + var plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.NewSequence, id); + var request = ArchiveJobs.Convert(fx.Archive, plan); + var job = new Job + { + Id = Guid.CreateVersion7(), + Kind = request.Kind, + TargetIds = request.Targets, + ParametersJson = request.ParametersJson, + State = JobState.Queued, + Created = DateTimeOffset.UtcNow, + }; + await fx.Db.Jobs.EnqueueAsync(job, fx.Ct); + + // Another tab, or Apply pressed again after an answer was lost: the same copies are not queued twice. + var again = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.NewSequence, id); + Assert.SequenceEqual([ConvertBlock.Busy], again.Sequences.Single().Blocked); + Assert.NotEqual(plan.Fingerprint(), again.Fingerprint()); + Assert.Throws(() => ArchiveJobs.Convert(fx.Archive, again)); + // The job itself plans again with its sequences free, and converts them. + var engine = await fx.StartEngineAsync(); + engine.Wake(); + await fx.WaitForAsync(job.Id, JobState.Done, (int)TestTiming.Budget(60)); + Assert.NotNull(await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Id, MassConverter.SessionKey(job.Id, id))); + Assert.Empty((await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.NewSequence, id)).Sequences.Single().Blocked); + } + + [Test] + public async Task ANewSequenceIsOwnedAsItsSourceIsOrByWhoAskedForIt() + { + await using var fx = await FixtureAsync(); + var owner = Guid.NewGuid(); + var owned = await UploadedAsync(fx, 2, user: owner); + var unowned = await UploadedAsync(fx, 2, "upload-2", seed: 200); + Assert.Equal(owner, (await fx.Db.Sequences.GetAsync(owned))!.OwnerUserId); + var engine = await fx.StartEngineAsync(); + var asker = Guid.NewGuid(); + + var job = await engine.EnqueueAsync(ArchiveJobs.Convert(fx.Archive, await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.NewSequence, owned, unowned)), asker, fx.Ct); + await fx.WaitForAsync(job.Id, JobState.Done, (int)TestTiming.Budget(60)); + foreach (var (source, expected) in new[] { (owned, owner), (unowned, asker) }) + { + var made = (await fx.Db.Sequences.GetAsync((await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Id, MassConverter.SessionKey(job.Id, source)))!.Value))!; + Assert.Equal(expected, made.OwnerUserId); + Assert.Equal(expected.ToString(), Sidecar(fx, made).CreatedBy); + } + } + + [Test] + public async Task AStagedCopyThatVanishesFailsItsNewSequenceInsteadOfLeavingThePhotoOut() + { + await using var fx = await FixtureAsync(); + var id = await UploadedAsync(fx, 2); + var plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.NewSequence, id); + var first = Sidecar(fx, (await fx.Db.Sequences.GetAsync(id))!).Frames[0]; + var jobId = Guid.CreateVersion7(); + // A clean-up takes the first copy once both are staged, before they are filed. + var callbacks = Callbacks(progress: (n, total) => + { + if (n == 2 && total == 2) File.Delete(Path.Combine(StagingOf(fx, jobId, id), first.Id.ToString("N") + ".tif")); + }); + + var failed = (await RunHereAsync(fx, plan, jobId, callbacks)).Sequences.Single(); + Assert.Equal(ConvertOutcome.Failed, failed.Outcome); + Assert.Null(await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Id, MassConverter.SessionKey(jobId, id))); + // The retry converts that photo again and makes the whole copy. + var made = (await RunHereAsync(fx, plan, jobId)).Sequences.Single(); + Assert.Equal((ConvertOutcome.Created, 2, 0), (made.Outcome, made.Frames, made.LeftOut)); + Assert.Count(2, await FramesAsync(fx, made.NewSequenceId!.Value)); + } + + [Test] + public async Task ANewSequenceSaysWhichPhotosItLeftInTheSourceAlone() + { + await using var fx = await FixtureAsync(); + var id = await UploadedAsync(fx, 3); + var engine = await fx.StartEngineAsync(); + // Three TIFFs, then a JPEG uploaded: to JPEG, the TIFFs convert and the JPEG stays in the source alone. + var sequence = (await fx.Db.Sequences.GetAsync(id))!; + await RunAsync(fx, engine, await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, id)); + var (path, size, sha) = fx.Stage(Start.AddSeconds(60), 999); + await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, id, null, null, path, "IMG_0099.JPG", size, sha, null, null), fx.Ct); + + var job = await RunAsync(fx, engine, await PlanAsync(fx, ConvertTarget.Jpeg, ConvertMode.NewSequence, id)); + Assert.Contains(Loc.L("Archive.Log.ConvertedNew", sequence.DisplayTitle, 3), job.LogTail); + Assert.Contains(Loc.L("Archive.Log.ConvertLeftOut", sequence.DisplayTitle, 1), job.LogTail); + var made = Assert.NotNull(await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Id, MassConverter.SessionKey(job.Id, id))); + Assert.Count(3, await FramesAsync(fx, made)); + } + + [Test] + public async Task AVolumeThatFillsDuringTheJobStopsItBeforeTheNextSequenceAndTheNextPhoto() + { + long free = 1L << 50; + await using var fx = await FixtureAsync(o => o with { FreeSpace = _ => free, Parallelism = () => 1 }); + var first = await UploadedAsync(fx, 2); + var second = await UploadedAsync(fx, 2, "upload-2", seed: 200); + var plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, first, second); + var jobId = Guid.CreateVersion7(); + var originals = await FramesAsync(fx, second); + + // Another writer fills the volume while the first sequence converts: the second does not start. + var full = await Assert.ThrowsAsync(() => RunHereAsync(fx, plan, jobId, Callbacks(done: _ => free = 1_000))); + Assert.True(full.Message.StartsWith("The conversion needs", StringComparison.Ordinal), full.Message); + Assert.True((await FramesAsync(fx, first)).All(f => f.Format == ImageFileFormat.Tiff)); + Assert.SequenceEqual(originals.Select(f => (f.Id, f.Sha256)), (await FramesAsync(fx, second)).Select(f => (f.Id, f.Sha256))); + Assert.False(Directory.Exists(StagingOf(fx, jobId, second))); + + // Space again, until the first photo of the second sequence is staged: the next one does not start, what was staged stays. + free = 1L << 50; + await Assert.ThrowsAsync(() => RunHereAsync(fx, plan, jobId, Callbacks(progress: (n, _) => + { + if (n == 1) free = 1_000; + }))); + Assert.Count(1, Directory.EnumerateFiles(StagingOf(fx, jobId, second))); + Assert.SequenceEqual(originals.Select(f => (f.Id, f.Sha256)), (await FramesAsync(fx, second)).Select(f => (f.Id, f.Sha256))); + + free = 1L << 50; + var done = await RunHereAsync(fx, plan, jobId); + Assert.True(done.Sequences.All(s => s.Outcome == ConvertOutcome.Converted)); + Assert.True((await FramesAsync(fx, second)).All(f => f.Format == ImageFileFormat.Tiff)); + Assert.FileMissing(ConvertJournal.PathFor(fx.Paths, jobId)); + } + + [Test] + public async Task MaintenanceKeepsWhatAWaitingConversionStagedAndClearsWhatAFinishedOneLeft() + { + await using var fx = await FixtureAsync(); + var paused = Guid.CreateVersion7(); + var finished = Guid.CreateVersion7(); + var forgotten = Guid.CreateVersion7(); + foreach (var (id, state) in new[] { (paused, JobState.Paused), (finished, JobState.Done) }) + await fx.Db.Jobs.EnqueueAsync(new Job { Id = id, Kind = JobKind.Convert, State = state, Created = DateTimeOffset.UtcNow }, fx.Ct); + string Staged(Guid job) + { + var file = Path.Combine(StagingOf(fx, job, Guid.NewGuid()), "frame.tif"); + Directory.CreateDirectory(Path.GetDirectoryName(file)!); + File.WriteAllText(file, "x"); + File.SetLastWriteTimeUtc(file, DateTime.UtcNow.AddDays(-3)); + return file; + } + string Journal(Guid job) + { + new ConvertJournal { JobId = job }.Write(fx.Paths); + return ConvertJournal.PathFor(fx.Paths, job); + } + var (pausedFile, pausedJournal) = (Staged(paused), Journal(paused)); + var (finishedFile, finishedJournal) = (Staged(finished), Journal(finished)); + var (forgottenFile, forgottenJournal) = (Staged(forgotten), Journal(forgotten)); + + var dry = await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: true, 0, _ => ValueTask.CompletedTask, fx.Ct); + Assert.SequenceEqual(new[] { finishedFile, finishedJournal, forgottenFile }.Select(fx.Paths.ToRelative).Order(), dry.TemporaryFiles.Order()); + await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: false, 0, _ => ValueTask.CompletedTask, fx.Ct); + // A paused job's staged conversions stay however old; a finished job's go with its journal; a job this index does not + // know (another host's, or forgotten by the history) loses staged files idle for a day, and keeps its journal a while. + Assert.FileExists(pausedFile); + Assert.FileExists(pausedJournal); + Assert.False(Directory.Exists(Path.Combine(Staging(fx), MassConverter.StagingFolder(finished)))); + Assert.FileMissing(finishedJournal); + Assert.False(Directory.Exists(Path.Combine(Staging(fx), MassConverter.StagingFolder(forgotten)))); + Assert.FileMissing(forgottenFile); + Assert.FileExists(forgottenJournal); + File.SetLastWriteTimeUtc(forgottenJournal, DateTime.UtcNow.AddDays(-CleanupSteps.DefaultHistoryDays - 1)); + await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: false, 0, _ => ValueTask.CompletedTask, fx.Ct); + Assert.FileMissing(forgottenJournal); + Assert.FileExists(pausedJournal); + } } diff --git a/tests/Chronos.Server.Tests/Storage/VolumeSpaceTests.cs b/tests/Chronos.Server.Tests/Storage/VolumeSpaceTests.cs index b2c30813..40bddc39 100644 --- a/tests/Chronos.Server.Tests/Storage/VolumeSpaceTests.cs +++ b/tests/Chronos.Server.Tests/Storage/VolumeSpaceTests.cs @@ -107,6 +107,27 @@ public sealed class VolumeSpaceTests(TestContext context) Assert.Equal(0, logger.Warnings); } + [Test] + public void AConversionCountsOnTheTighterOfTheSpaceAndTheWriteVolume() + { + var root = context.CreateTempDirectory("writable"); + var archive = Directory.CreateDirectory(Path.Combine(root, "archive")).FullName; + var space = Directory.CreateDirectory(Path.Combine(root, "space")).FullName; + var options = new ServerOptions { ArchivePath = archive }; + var volumes = new FakeVolumeSpace(options, new CountingLogger()); + volumes.Set(archive, new VolumeFigures(120 * GB, 500 * GB)); + Assert.Equal(120 * GB, volumes.WritableFree(archive)); + + // Unraid: the array has room, the cache the share writes to until the mover runs has less, and it is what fills. + options.SpacePath = space; + volumes.Set(space, new VolumeFigures(9_000 * GB, 16_000 * GB)); + Assert.Equal(120 * GB, volumes.WritableFree(archive)); + // An array fuller than the cache is the limit then. + volumes.Set(space, new VolumeFigures(40 * GB, 16_000 * GB)); + Assert.Equal(40 * GB, volumes.WritableFree(archive)); + Assert.Null(new FakeVolumeSpace(new ServerOptions { ArchivePath = archive }, new CountingLogger()).WritableFree(Path.Combine(root, "missing"))); + } + [Test] public void ASpacePathThatCannotBeMeasuredFallsBackWithOneWarning() {