fix(archive): convert job applies exactly the confirmed plan, resumes safely and watches its space
The convert job planned every sequence again when it ran and checked only the frames version, so a verify, a repaired upload or a tier change between the dry run and the job let it replace photos the confirmed plan had listed as staying unchanged. - Each sequence of a convert job now carries the digest of the photos it converts, each with its SHA-256 (ConvertSequencePlan.Digest, also in the plan's fingerprint). Under the sequence's lease, its sidecar settled, the job plans it again and goes on only while the digest matches; it then pins those photos (convert-<job>.pins), so photos that come in or are verified later stay as they are, a retry included. Stage B checks under the lease that every pinned photo still holds the content converted instead of holding the frames version, so a sequence still receiving uploads converts what was confirmed. - A resumed job settles the journals a crash left in a sequence (a half-done replacement among them) before it plans, and reports a sequence its replacement completed as Converted, never Nothing or a partial swap. - The passes a converted or new sequence needs are queued as soon as its outcome is journaled; the journal records the statuses they follow from and whether they were queued, so a pause, yield, stop or crash no longer loses them. - Staged conversions of a blocked or failed sequence are kept for the retry, which re-verifies and takes them; maintenance keeps a convert job's staging while the job is queued, running or paused, and removes its journal and staging once the job is done or gone from the history. - A dry run counts the sequences of a queued conversion as busy, so the same conversion cannot be confirmed twice. - New sequence copies are owned by the source's owner, else by the requesting user's id (never the user name); a staged copy that vanished fails the sequence instead of leaving its photo out; the job log states how many photos stayed in the source alone. - Free space is measured where the conversion writes: the server takes the tighter of the space path's volume and the archive's own (Unraid cache), the desktop asks Windows (GetDiskFreeSpaceEx), which also measures UNC archives; the job checks again before each sequence and each photo, scaling estimates by the files staged so far, and stops before the volume fills with what it staged kept. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 2d7d461c33b9f257bf57793cc7cf331d0425c14e)
This commit is contained in:
1 parent
f86a151a5d
commit
67a6d51cbe
17 files changed
+1222
-236
No files matched your search
@@ -199,6 +199,7 @@
|
||||
<data name="Archive.Log.ConvertChanged" xml:space="preserve"><value>Left as it was, changed after the plan: {0}</value><comment>long: job log line; {0} sequence title</comment></data>
|
||||
<data name="Archive.Log.ConvertDone" xml:space="preserve"><value>Sequences converted: {0}, new sequences: {1}, photos: {2}</value><comment>long: job log line of a conversion</comment></data>
|
||||
<data name="Archive.Log.ConvertFailed" xml:space="preserve"><value>Left as it was: {0}. {1}</value><comment>long: job log line; {0} sequence title, {1} what failed and why (sentences)</comment></data>
|
||||
<data name="Archive.Log.ConvertLeftOut" xml:space="preserve"><value>{0}: photos not converted, left in the source alone: {1}</value><comment>long: job log line after a conversion into a new sequence; {0} sequence title, {1} photos</comment></data>
|
||||
<data name="Archive.Log.ConvertNothing" xml:space="preserve"><value>Nothing to convert: {0}</value><comment>long: job log line; {0} sequence title</comment></data>
|
||||
<data name="Archive.Log.Converted" xml:space="preserve"><value>{0}: photos replaced by their conversion: {1}</value><comment>long: job log line; {0} sequence title, {1} photos</comment></data>
|
||||
<data name="Archive.Log.ConvertedNew" xml:space="preserve"><value>{0}: photos converted into a new sequence: {1}</value><comment>long: job log line; {0} sequence title, {1} photos</comment></data>
|
||||
|
||||
@@ -193,6 +193,7 @@
|
||||
<data name="Archive.Log.ConvertChanged" xml:space="preserve"><value>Lasciata com'era, cambiata dopo il piano: {0}</value></data>
|
||||
<data name="Archive.Log.ConvertDone" xml:space="preserve"><value>Sequenze convertite: {0}, nuove sequenze: {1}, foto: {2}</value></data>
|
||||
<data name="Archive.Log.ConvertFailed" xml:space="preserve"><value>Lasciata com'era: {0}. {1}</value></data>
|
||||
<data name="Archive.Log.ConvertLeftOut" xml:space="preserve"><value>{0}: foto non convertite, rimaste solo nella sorgente: {1}</value></data>
|
||||
<data name="Archive.Log.ConvertNothing" xml:space="preserve"><value>Niente da convertire: {0}</value></data>
|
||||
<data name="Archive.Log.Converted" xml:space="preserve"><value>{0}: foto sostituite dalla loro conversione: {1}</value></data>
|
||||
<data name="Archive.Log.ConvertedNew" xml:space="preserve"><value>{0}: foto convertite in una nuova sequenza: {1}</value></data>
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -70,6 +70,26 @@ public sealed record VolumeInfo(
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Free bytes available to the current user on the volume holding the folder <paramref name="folder"/>, quotas counted: a
|
||||
/// network share's (UNC) too, which <see cref="DriveInfo"/> cannot measure. Null when the folder cannot be reached or measured.
|
||||
/// </summary>
|
||||
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 _);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Every ready fixed or removable volume, enumerated through <see cref="DriveInfo"/> (network and optical drives are skipped).</summary>
|
||||
public static IReadOnlyList<VolumeInfo> ListLocal()
|
||||
{
|
||||
|
||||
@@ -43,7 +43,7 @@ public enum ConvertSkip
|
||||
/// <summary>Why a whole sequence is not converted now; nothing of it is touched.</summary>
|
||||
public enum ConvertBlock
|
||||
{
|
||||
/// <summary>A running or paused job works on the sequence or its whole archive.</summary>
|
||||
/// <summary>A running or paused job works on the sequence or its whole archive, or a conversion of it waits in the queue.</summary>
|
||||
Busy,
|
||||
|
||||
/// <summary>The archive is offline or read-only.</summary>
|
||||
@@ -52,15 +52,21 @@ public enum ConvertBlock
|
||||
/// <summary>The sequence's sidecar cannot be read, or belongs to another sequence.</summary>
|
||||
Unreadable,
|
||||
|
||||
/// <summary>The sequence's frames changed after the plan was made (found by the job, which then leaves it as it is).</summary>
|
||||
/// <summary>
|
||||
/// The photos the sequence converts are no longer those of the plan confirmed (found by the job, which then leaves it as
|
||||
/// it is).
|
||||
/// </summary>
|
||||
FramesChanged,
|
||||
}
|
||||
|
||||
/// <summary>Frames of a sequence that are not converted, and why.</summary>
|
||||
public sealed record ConvertSkipped(ConvertSkip Reason, int Frames);
|
||||
|
||||
/// <summary>One frame a conversion converts: its id and index, its file and format, its size and the converted file's estimated size.</summary>
|
||||
public sealed record ConvertFramePlan(Guid FrameId, int Index, string File, ImageFileFormat Format, long Size, long EstimatedBytes);
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed record ConvertFramePlan(Guid FrameId, int Index, string File, ImageFileFormat Format, long Size, long EstimatedBytes, string? Sha256 = null);
|
||||
|
||||
/// <summary>
|
||||
/// 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);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public string Digest() => DigestOf(Frames.Select(f => (f.FrameId, f.Sha256)));
|
||||
|
||||
/// <summary>The digest of frames, each with the SHA-256 of its content, in order (<see cref="Digest"/>).</summary>
|
||||
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())));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -108,15 +129,16 @@ public sealed record ConvertPlan(Guid ArchiveId, ConvertOptions Options, Convert
|
||||
public int Skipped => Sequences.Sum(s => s.SkippedFrames);
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<see cref="ConvertSequencePlan.Digest"/>), those skipped, and what blocks it), the
|
||||
/// same for two plans of the same archive state.
|
||||
/// </summary>
|
||||
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))], []);
|
||||
|
||||
@@ -40,6 +40,12 @@ public sealed class ArchiveMaintenance
|
||||
/// <summary>Staged copies older than this belong to no running import.</summary>
|
||||
private static readonly TimeSpan StagingAge = TimeSpan.FromHours(24);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static readonly TimeSpan JournalAge = TimeSpan.FromDays(Housekeeping.CleanupSteps.DefaultHistoryDays);
|
||||
|
||||
/// <summary>Temporary files of atomic writes older than this were left by a crash.</summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>Staging copies and atomic-write temporaries left behind by crashes (never originals).</summary>
|
||||
private static List<string> PurgeTemporaryFiles(ArchivePaths paths, IReadOnlyList<SequenceLocation> locations, bool dryRun)
|
||||
/// <summary>
|
||||
/// Staging copies and atomic-write temporaries left behind by crashes (never originals), and what a conversion job left
|
||||
/// (<see cref="ConvertJournal"/>): 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.
|
||||
/// </summary>
|
||||
private async Task<List<string>> PurgeTemporaryFilesAsync(ArchivePaths paths, IReadOnlyList<SequenceLocation> locations, bool dryRun,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
var found = new List<string>();
|
||||
var conversions = new List<string>();
|
||||
var states = new Dictionary<Guid, JobState?>();
|
||||
async Task<JobState?> 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);
|
||||
}
|
||||
|
||||
@@ -697,15 +697,16 @@ public static class ArchiveJobs
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Convert"/>: applies the conversion <paramref name="plan"/> (<see cref="ArchiveService.PlanConvertAsync"/>)
|
||||
/// as confirmed (owner review 2, R7): the sequences it converts, in its order with their frames versions, are the job's
|
||||
/// targets, so jobs that would touch them wait. A sequence that changed before it ran is left as it is and reported.
|
||||
/// 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 (<see cref="ConvertSequencePlan.Digest"/>), 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.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">The plan converts nothing.</exception>
|
||||
public static ArchiveJobRequest Convert(Archive archive, ConvertPlan plan)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
var sequences = plan.Converted.Select(s => new ConvertSequence(s.SequenceId, s.FramesVersion)).ToList();
|
||||
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,
|
||||
|
||||
@@ -55,14 +55,18 @@ public sealed record MoveSequence(Guid Id);
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Convert"/> (owner review 2, R7): targets = the sequences converted, so the jobs that would touch them
|
||||
/// wait; the archive, the target format and JPEG quality, the mode chosen for this run, the sequences of the confirmed plan
|
||||
/// in its order with the frames version each was planned at, and the plan's fingerprint
|
||||
/// (<see cref="ConvertPlan.Fingerprint"/>). A sequence whose frames changed since is left as it is and reported.
|
||||
/// in its order, each with what it converts, and the plan's fingerprint (<see cref="ConvertPlan.Fingerprint"/>). A sequence
|
||||
/// whose photos to convert are no longer those confirmed is left as it is and reported.
|
||||
/// </summary>
|
||||
public sealed record ConvertJobParameters(Guid ArchiveId, ConvertTarget Target, int Quality, ConvertMode Mode, IReadOnlyList<ConvertSequence> Sequences,
|
||||
string Fingerprint);
|
||||
|
||||
/// <summary>A sequence of a <see cref="ConvertJobParameters"/> and the frames version it was planned at.</summary>
|
||||
public sealed record ConvertSequence(Guid Id, int FramesVersion);
|
||||
/// <summary>
|
||||
/// A sequence of a <see cref="ConvertJobParameters"/>: the frames version it was planned at and the digest of the photos it
|
||||
/// converts, each with its content (<see cref="ConvertSequencePlan.Digest"/>), 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.
|
||||
/// </summary>
|
||||
public sealed record ConvertSequence(Guid Id, int FramesVersion, string? Frames = null);
|
||||
|
||||
/// <summary>A job ready to enqueue.</summary>
|
||||
public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets, string? Label, string? ParametersJson, JobPriority Priority);
|
||||
@@ -80,6 +84,7 @@ public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets
|
||||
[JsonSerializable(typeof(ConvertJobParameters))]
|
||||
[JsonSerializable(typeof(ConvertJournal))]
|
||||
[JsonSerializable(typeof(StagedLine))]
|
||||
[JsonSerializable(typeof(PinnedSequence))]
|
||||
[JsonSerializable(typeof(CardProfile))]
|
||||
internal sealed partial class ArchiveJobJson : JsonSerializerContext
|
||||
{
|
||||
|
||||
@@ -8,13 +8,14 @@ namespace Chronos.Data.Archiving.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Convert"/>: a mass conversion (owner review 2, R7; BRIEF §12.5) of the sequences of a confirmed plan
|
||||
/// (<see cref="ConvertJobParameters"/>) through <see cref="MassConverter"/>, which plans again, refuses when the archive's
|
||||
/// volume lacks the space, and converts one sequence at a time, each all or nothing; its journal makes every stage
|
||||
/// (<see cref="ConvertJobParameters"/>) through <see cref="MassConverter"/>, 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 <c>converted</c>, each new sequence as <c>created</c> (<see cref="ArchiveServiceOptions.SequenceChanged"/>),
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal sealed class ConvertJobHandler(ChronosDatabase db, MassConverter converter, Func<Guid, string, CancellationToken, Task>? 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));
|
||||
}
|
||||
|
||||
/// <summary>Queues what the converted sequences need, each kind once per sequence; a failure is logged, never passed on.</summary>
|
||||
private async Task QueueAsync(JobContext context, ConvertResult result)
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private async ValueTask QueueAsync(JobContext context, IReadOnlyList<ArchiveJobRequest> requests)
|
||||
{
|
||||
foreach (var request in result.FollowUps)
|
||||
foreach (var request in requests)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -63,9 +63,11 @@ public sealed record ArchiveServiceOptions
|
||||
public Func<Guid, string, CancellationToken, Task>? SequenceChanged { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The free bytes of the volume an archive root lies on, as the host counts them (a server measures its space volume,
|
||||
/// owner review 2, R2); null: the volume of the root itself. A conversion checks its estimate against it (R7). The
|
||||
/// function returns null when the space cannot be measured.
|
||||
/// 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 (<see cref="DriveInfo"/>). 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.
|
||||
/// </summary>
|
||||
public Func<string, long?>? FreeSpace { get; init; }
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -47,6 +47,17 @@ public class VolumeSpace(ServerOptions options, ILogger<VolumeSpace> logger)
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The free bytes a write under the folder <paramref name="path"/> 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The storage figures of the archive at <paramref name="archiveRoot"/>: 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).
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
/// <summary>A provider that reads CR2 natively by format, and probes the files <paramref name="applies"/> picks (all
|
||||
/// by default) at a fixed tier, the others native.</summary>
|
||||
private sealed class ProbeAs(DecodeTier tier, Func<string, bool>? applies = null) : IImageDecoderProvider
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
using Chronos.Core.Windows.Devices;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Core.Windows.Tests.Devices;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="DriveInfo"/> cannot measure. Apart from <see cref="VolumeTests"/>, which enumerate every volume.
|
||||
/// </summary>
|
||||
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<ArgumentException>(() => new DriveInfo(Path.GetPathRoot(share)!));
|
||||
Assert.Greater(Assert.NotNull(VolumeInfo.FreeBytesAt(share)), 0);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
/// <summary>A sequence of <paramref name="count"/> uploaded photos (hashed, under <c>originals/</c>), ten seconds apart.</summary>
|
||||
private static async Task<Guid> UploadedAsync(ArchiveFixture fx, int count, string session = "upload-1", int seed = 100)
|
||||
/// <summary>A sequence of <paramref name="count"/> uploaded photos (hashed, under <c>originals/</c>), ten seconds apart, by <paramref name="user"/>.</summary>
|
||||
private static async Task<Guid> 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<ConvertPlan> PlanAsync(ArchiveFixture fx, ConvertTarget target, ConvertMode mode, params Guid[] ids) =>
|
||||
fx.Service.PlanConvertAsync(fx.Archive.Id, ids, new ConvertOptions(target), mode, fx.Ct);
|
||||
|
||||
/// <summary>The parameters the job of <paramref name="plan"/> runs with.</summary>
|
||||
private static ConvertJobParameters Parameters(ArchiveFixture fx, ConvertPlan plan) =>
|
||||
JsonSerializer.Deserialize(ArchiveJobs.Convert(fx.Archive, plan).ParametersJson!, ArchiveJobJson.Default.ConvertJobParameters)!;
|
||||
|
||||
/// <summary>Callbacks that report nothing, but for <paramref name="progress"/> and <paramref name="done"/> when given.</summary>
|
||||
private static ConvertCallbacks Callbacks(Action<long, long>? progress = null, Action<ConvertSequenceResult>? done = null,
|
||||
Action<IReadOnlyList<ArchiveJobRequest>>? 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;
|
||||
});
|
||||
|
||||
/// <summary>The conversion job <paramref name="jobId"/> of <paramref name="plan"/>, run here as its handler runs it.</summary>
|
||||
private static Task<ConvertResult> 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<Job> 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<SwapMove> outgoing = [];
|
||||
List<SwapMove> 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<string>();
|
||||
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<ArchiveJobRequest> 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<ArgumentException>(() => 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<IOException>(() => 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<IOException>(() => 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);
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user