fix: keep render filing retryable and writers out of a folder another index moved
Third fix round of owner review 2, phase 4a (Reorganize), cross-cutting items. - Server render filing now runs under the sequence lease, so it can meet a busy sequence or an offline archive. Both completions (client render uploads and render-node results) used to answer 500 and leave the upload stuck in Committing until a restart. They now answer 503 sequence_busy or archive_offline, which clients retry. The upload goes back to receiving with its part file and the node keeps its job (UploadService.ReceiveAgainAsync). - Save both: when this PC's copy cannot be written (another index moved the folder), the server's version is no longer applied, even if this index's scan relocates the row before the apply would run. A copy that has to be dropped is deleted from where the folder is now, as a best effort. - Export rebase on a folder move (scan and Reorganize): the sequence's own export follows the folder unless its file is still at the old path and not at the new one. A file written into a re-created old folder therefore keeps a row that finds it, so the file is never stranded. - A render job refuses to start when its folder is not where the index has it, which also stops it from re-creating the old folder. Renders fetched by sync are now filed under the sequence lease into the current folder, or not at all (new string Errors.Archive.FolderMoved, en and it). - The proxy pass holds the thumbnail lease one batch at a time (a quarter of the lease wait), then lets it go for longer than a waiter's poll and reads the folder and sidecar again. Before, another process's Reorganize, sequence deletion or pack compaction could wait out its lease wait and fail. Updated the stale comments on that lease and ARCHITECTURE.md to match. Tests cover each fix, and each new test fails with its fix reverted. Also covered: proxy store and pass in a moved folder, RenderStore with the folder gone, Take server with the folder moved, and an editor save with the folder moved. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 811509d32a118ed50ad10d47d4b002e534da9d77)
This commit is contained in:
1 parent
0377040a19
commit
c3756d03c9
26 files changed
+666
-134
No files matched your search
@@ -25,6 +25,9 @@ public sealed class LeaseFile : IDisposable
|
||||
{
|
||||
public static readonly TimeSpan DefaultDuration = TimeSpan.FromMinutes(2);
|
||||
|
||||
/// <summary>The longest a writer waiting for a lease (<see cref="AcquireAsync"/>) sleeps between two tries.</summary>
|
||||
public static readonly TimeSpan LongestPoll = TimeSpan.FromMilliseconds(500);
|
||||
|
||||
private const string Extension = ".lease";
|
||||
private const string StaleExtension = ".stale";
|
||||
private const int ReadAttempts = 5;
|
||||
@@ -84,7 +87,7 @@ public sealed class LeaseFile : IDisposable
|
||||
if (TryAcquire(locksDirectory, name, owner, duration) is { } lease) return lease;
|
||||
if (DateTime.UtcNow >= deadline) throw new LeaseUnavailableException(name, Read(PathFor(locksDirectory, name)));
|
||||
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
|
||||
delay = TimeSpan.FromMilliseconds(System.Math.Min(delay.TotalMilliseconds * 2, 500));
|
||||
delay = TimeSpan.FromMilliseconds(System.Math.Min(delay.TotalMilliseconds * 2, LongestPoll.TotalMilliseconds));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Imaging.Decoders;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Metadata;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
@@ -57,6 +58,9 @@ public sealed class ArchiveImages
|
||||
|
||||
private static readonly TimeSpan CommitInterval = TimeSpan.FromSeconds(10);
|
||||
|
||||
/// <summary>How long a proxy pass lets the thumbnail lease go between two batches: longer than a waiting writer sleeps between its tries.</summary>
|
||||
private static readonly TimeSpan BatchGap = LeaseFile.LongestPoll * 1.5;
|
||||
|
||||
/// <summary>
|
||||
/// Age of a proxy file under which its header is not kept: a file system's clock may give a file written again at
|
||||
/// once (with the same length) the same write time, at a granularity of up to two seconds.
|
||||
@@ -214,9 +218,9 @@ public sealed class ArchiveImages
|
||||
int built = 0, reused = 0, undecodable = 0;
|
||||
var complete = true;
|
||||
var tiers = new Dictionary<Guid, FileTier>();
|
||||
// Thumbnail writers exclude each other only; ingest keeps committing meanwhile. A Reorganize moves the folder under
|
||||
// this lease too, so the folder is the one the index has once it is held: the pack never opens in a folder the
|
||||
// sequence left, which opening it would create again.
|
||||
// Image passes exclude each other only (a proxy pass holds this lease a batch at a time); ingest keeps committing
|
||||
// meanwhile. A Reorganize moves the folder under this lease too, so the folder is the one the index has once it is
|
||||
// held: the pack never opens in a folder the sequence left, which opening it would create again.
|
||||
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{sequence.Id:N}", _writer.Options.Owner, _writer.Options.LeaseWait,
|
||||
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
@@ -292,7 +296,10 @@ public sealed class ArchiveImages
|
||||
/// proxies of the frames an earlier run did again (their headers only). The <see cref="FrameFlags.PreviewOnly"/> flag
|
||||
/// of frames this host reads through their proxies follows whether they have one (<see cref="FrameTiers"/>). Several
|
||||
/// originals are decoded at once (<see cref="PassParallelism"/>), and a checkpoint still means that every frame before
|
||||
/// it has its proxy written (<see cref="OrderedWork{T}"/>).
|
||||
/// it has its proxy written (<see cref="OrderedWork{T}"/>). The pass works in batches (<see cref="ProxyBatch"/>), each
|
||||
/// under the thumbnail lease with the sequence's folder and sidecar read again; a folder that is not where the index
|
||||
/// has it (another index moved it, until this index's next scan) stops the pass with an
|
||||
/// <see cref="InvalidOperationException"/>, nothing written there.
|
||||
/// </remarks>
|
||||
public async Task<ImagePassResult> BuildProxiesAsync(Archive archive, Sequence sequence, bool force, int startFrame,
|
||||
Func<int, int, ValueTask> checkpoint, CancellationToken cancellationToken = default)
|
||||
@@ -301,99 +308,119 @@ public sealed class ArchiveImages
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
var policy = ManifestStore.ReadArchive(paths.ManifestPath).ProxyPolicy;
|
||||
if (policy.LongEdge == ProxyPolicy.Disabled) return new ImagePassResult(0, 0, 0);
|
||||
SequenceManifest manifest;
|
||||
SequenceManifest? manifest = null;
|
||||
int built = 0, reused = 0, undecodable = 0, waiting = 0;
|
||||
var complete = true;
|
||||
var tiers = new Dictionary<Guid, FileTier>();
|
||||
var cadence = new Cadence();
|
||||
// Under the thumbnail lease, as the thumbnail pass: image passes exclude each other only, ingest keeps committing
|
||||
// meanwhile, and a Reorganize waits for the pass, so the proxies go to the folder the index has once the lease is
|
||||
// held, never into one the sequence left, which writing them would create again.
|
||||
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{sequence.Id:N}", _writer.Options.Owner, _writer.Options.LeaseWait,
|
||||
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
|
||||
// meanwhile, and a Reorganize waits for the batch, so the proxies go to the folder the index has once the lease is
|
||||
// held, never into one the sequence left, which writing them would create again. Between two batches the lease is let
|
||||
// go for longer than a waiting writer sleeps between its tries, so another process's Reorganize, sequence deletion or
|
||||
// pack compaction waits for one batch, not for the whole pass.
|
||||
for (var next = 0; ;)
|
||||
{
|
||||
var folder = await SequenceWriter.FolderAsync(_db, paths, sequence, cancellationToken).ConfigureAwait(false);
|
||||
manifest = ManifestStore.ReadSequence(folder.ManifestPath);
|
||||
Directory.CreateDirectory(folder.Proxies);
|
||||
var companions = await GprCompanions.FindAsync(_db, archive, manifest.Frames, cancellationToken).ConfigureAwait(false);
|
||||
var cadence = new Cadence();
|
||||
await using (var work = new OrderedWork<Made>(ProxyParallelism(manifest.Frames, policy), made =>
|
||||
{
|
||||
switch (made.Outcome)
|
||||
{
|
||||
case ProxyOutcome.Built:
|
||||
built++;
|
||||
break;
|
||||
case ProxyOutcome.Reused:
|
||||
reused++;
|
||||
break;
|
||||
case ProxyOutcome.Waiting:
|
||||
waiting++;
|
||||
break;
|
||||
case ProxyOutcome.Failed:
|
||||
undecodable++;
|
||||
complete = false;
|
||||
break;
|
||||
default:
|
||||
undecodable++;
|
||||
break;
|
||||
}
|
||||
if (made.Tier is { } tier) tiers[made.FrameId] = tier;
|
||||
return cadence.Due() ? checkpoint(made.Index + 1, manifest.Frames.Count) : ValueTask.CompletedTask;
|
||||
}, cancellationToken))
|
||||
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{sequence.Id:N}", _writer.Options.Owner, _writer.Options.LeaseWait,
|
||||
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
for (var i = 0; i < manifest.Frames.Count; i++)
|
||||
var folder = await SequenceWriter.FolderAsync(_db, paths, sequence, cancellationToken).ConfigureAwait(false);
|
||||
if (!Directory.Exists(folder.Folder)) throw new InvalidOperationException(Loc.L("Errors.Archive.FolderMoved"));
|
||||
var read = ManifestStore.ReadSequence(folder.ManifestPath);
|
||||
// Photos added, removed or renumbered since the last batch: what the earlier batches made may not be theirs.
|
||||
if (manifest is not null && !SameFrames(read.Frames, manifest.Frames, names: false)) complete = false;
|
||||
manifest = read;
|
||||
Directory.CreateDirectory(folder.Proxies);
|
||||
var companions = await GprCompanions.FindAsync(_db, archive, read.Frames, cancellationToken).ConfigureAwait(false);
|
||||
var batch = Stopwatch.StartNew();
|
||||
await using (var work = new OrderedWork<Made>(ProxyParallelism(read.Frames, policy), made =>
|
||||
{
|
||||
switch (made.Outcome)
|
||||
{
|
||||
case ProxyOutcome.Built:
|
||||
built++;
|
||||
break;
|
||||
case ProxyOutcome.Reused:
|
||||
reused++;
|
||||
break;
|
||||
case ProxyOutcome.Waiting:
|
||||
waiting++;
|
||||
break;
|
||||
case ProxyOutcome.Failed:
|
||||
undecodable++;
|
||||
complete = false;
|
||||
break;
|
||||
default:
|
||||
undecodable++;
|
||||
break;
|
||||
}
|
||||
if (made.Tier is { } tier) tiers[made.FrameId] = tier;
|
||||
return cadence.Due() ? checkpoint(made.Index + 1, read.Frames.Count) : ValueTask.CompletedTask;
|
||||
}, cancellationToken))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var frame = manifest.Frames[i];
|
||||
var path = folder.Proxy(frame.I);
|
||||
var done = i < startFrame;
|
||||
if (NeedsProxy(frame.Format))
|
||||
// At least one frame per batch, so the pass always moves on.
|
||||
for (var first = next; next < read.Frames.Count && (next == first || batch.Elapsed < ProxyBatch); next++)
|
||||
{
|
||||
// Only a client or render node that decodes the original makes this proxy: a preview would make one the
|
||||
// size of a thumbnail here. One left from a frame renumbered since goes, so it is asked for again, and so
|
||||
// does one smaller than the policy's (made here from a preview by an earlier version).
|
||||
var check = Check(path, frame.CapturedAt, frame.W, frame.H, policy).Check;
|
||||
var usable = check is ProxyCheck.Current or ProxyCheck.Unverifiable;
|
||||
if (check == ProxyCheck.Stale) Delete(path);
|
||||
complete &= usable;
|
||||
if (done) continue;
|
||||
var outcome = usable ? ProxyOutcome.Reused
|
||||
: (frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0 ? ProxyOutcome.Unreadable
|
||||
: ProxyOutcome.Waiting;
|
||||
await work.AddAsync(new Made(i, frame.Id, outcome, null)).ConfigureAwait(false);
|
||||
continue;
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var frame = read.Frames[next];
|
||||
var path = folder.Proxy(frame.I);
|
||||
var done = next < startFrame;
|
||||
if (NeedsProxy(frame.Format))
|
||||
{
|
||||
// Only a client or render node that decodes the original makes this proxy: a preview would make one the
|
||||
// size of a thumbnail here. One left from a frame renumbered since goes, so it is asked for again, and so
|
||||
// does one smaller than the policy's (made here from a preview by an earlier version).
|
||||
var check = Check(path, frame.CapturedAt, frame.W, frame.H, policy).Check;
|
||||
var usable = check is ProxyCheck.Current or ProxyCheck.Unverifiable;
|
||||
if (check == ProxyCheck.Stale) Delete(path);
|
||||
complete &= usable;
|
||||
if (done) continue;
|
||||
var outcome = usable ? ProxyOutcome.Reused
|
||||
: (frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0 ? ProxyOutcome.Unreadable
|
||||
: ProxyOutcome.Waiting;
|
||||
await work.AddAsync(new Made(next, frame.Id, outcome, null)).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
if (done)
|
||||
{
|
||||
// Made by the earlier run, unless the frame did not decode then.
|
||||
complete &= ReadProxy(path, frame.CapturedAt).Check is ProxyCheck.Current or ProxyCheck.Unverifiable;
|
||||
continue;
|
||||
}
|
||||
if (!force && ReadProxy(path, frame.CapturedAt).Check == ProxyCheck.Current)
|
||||
{
|
||||
reused++;
|
||||
continue;
|
||||
}
|
||||
var index = next;
|
||||
var companion = companions.GetValueOrDefault(frame.Id);
|
||||
await work.AddAsync(ct =>
|
||||
{
|
||||
var (image, tier) = Render(folder, frame, companion, recordTier: true,
|
||||
() => _renderer.Proxy(folder, frame, read.Camera, policy, ct, companion));
|
||||
if (image is null) return new Made(index, frame.Id, ProxyOutcome.Failed, tier);
|
||||
AtomicFile.WriteAllBytes(path, image.Jpeg);
|
||||
Headers.TryRemove(path, out _);
|
||||
return new Made(index, frame.Id, ProxyOutcome.Built, tier);
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
if (done)
|
||||
{
|
||||
// Made by the earlier run, unless the frame did not decode then.
|
||||
complete &= ReadProxy(path, frame.CapturedAt).Check is ProxyCheck.Current or ProxyCheck.Unverifiable;
|
||||
continue;
|
||||
}
|
||||
if (!force && ReadProxy(path, frame.CapturedAt).Check == ProxyCheck.Current)
|
||||
{
|
||||
reused++;
|
||||
continue;
|
||||
}
|
||||
var index = i;
|
||||
var companion = companions.GetValueOrDefault(frame.Id);
|
||||
await work.AddAsync(ct =>
|
||||
{
|
||||
var (image, tier) = Render(folder, frame, companion, recordTier: true,
|
||||
() => _renderer.Proxy(folder, frame, manifest.Camera, policy, ct, companion));
|
||||
if (image is null) return new Made(index, frame.Id, ProxyOutcome.Failed, tier);
|
||||
AtomicFile.WriteAllBytes(path, image.Jpeg);
|
||||
Headers.TryRemove(path, out _);
|
||||
return new Made(index, frame.Id, ProxyOutcome.Built, tier);
|
||||
}).ConfigureAwait(false);
|
||||
await work.CompleteAsync().ConfigureAwait(false);
|
||||
}
|
||||
await work.CompleteAsync().ConfigureAwait(false);
|
||||
if (next >= read.Frames.Count) break;
|
||||
}
|
||||
await Task.Delay(BatchGap, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
await _tiers.RecordAsync(archive, sequence, tiers, proxies: true, cancellationToken).ConfigureAwait(false);
|
||||
await MarkAsync(archive, paths, sequence, manifest, JobKind.Proxies, SequenceStatus.ProxiesBuilt, complete, cancellationToken).ConfigureAwait(false);
|
||||
return new ImagePassResult(built, reused, undecodable, waiting);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// How long a proxy pass holds the thumbnail lease for one batch of frames: a quarter of the lease wait, so a writer of
|
||||
/// another process waiting for the lease meanwhile gets it well before it gives up (the frames the batch started finish
|
||||
/// first).
|
||||
/// </summary>
|
||||
private TimeSpan ProxyBatch => _writer.Options.LeaseWait / 4;
|
||||
|
||||
/// <summary>Photos a thumbnail pass draws at once (<see cref="PassParallelism"/>): previews of the thumbnail's size serve it.</summary>
|
||||
private int ThumbnailParallelism(IReadOnlyList<SidecarFrame> frames, ThumbnailPolicy policy) =>
|
||||
PassParallelism(_writer.Options.Parallelism(), _writer.Options.MemoryBudget(), frames, policy.LongEdge, preferPreview: true, _writer.Options.Decoder);
|
||||
@@ -673,13 +700,15 @@ public sealed class ArchiveImages
|
||||
/// removed, renumbered or replaced since have none of what the pass made. A hash learnt since (a verify hashing a
|
||||
/// photo the scan adopted) changes nothing about the photo, and its thumbnail stays its own (<see cref="ThumbPack.IsFrom"/>).
|
||||
/// </summary>
|
||||
private static bool SameFrames(IReadOnlyList<SidecarFrame> current, IReadOnlyList<SidecarFrame> read)
|
||||
/// <param name="names">Whether a file renamed since counts as a change (a pass's own batches: it does not, a proxy is
|
||||
/// kept by frame index and a Reorganize renames files).</param>
|
||||
private static bool SameFrames(IReadOnlyList<SidecarFrame> current, IReadOnlyList<SidecarFrame> read, bool names = true)
|
||||
{
|
||||
if (current.Count != read.Count) return false;
|
||||
for (var i = 0; i < current.Count; i++)
|
||||
{
|
||||
var (now, then) = (current[i], read[i]);
|
||||
if (now.Id != then.Id || now.I != then.I || now.File != then.File || now.Size != then.Size || now.CapturedAt != then.CapturedAt
|
||||
if (now.Id != then.Id || now.I != then.I || (names && now.File != then.File) || now.Size != then.Size || now.CapturedAt != then.CapturedAt
|
||||
|| (then.Sha256 is not null && !string.Equals(now.Sha256, then.Sha256, StringComparison.OrdinalIgnoreCase))) return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -187,16 +187,23 @@ public sealed class ArchiveIndexer
|
||||
|
||||
/// <summary>
|
||||
/// The render rows of the archive that follow a sequence's folder from <paramref name="from"/> to <paramref name="to"/>,
|
||||
/// in the caller's transaction (<see cref="Repositories.RenderRepository.RebaseFolderAsync"/>): the sequence's own exports
|
||||
/// inside it, and another sequence's whose file moved with it (at its new path and no longer at the old one, which on a
|
||||
/// file system that ignores case is the same file when only the case changed).
|
||||
/// in the caller's transaction (<see cref="Repositories.RenderRepository.RebaseFolderAsync"/>). A file is at its old path
|
||||
/// still when it is there and the new path is not the same file (on a file system that ignores case it is, when only the
|
||||
/// case changed). The sequence's own exports inside the folder follow unless their file is at the old path still and not
|
||||
/// at the new one: written there after the move by a writer that read the old folder, which created it again, so the row
|
||||
/// keeps naming where the file is. Another sequence's export follows only when its file moved with the folder (at its new
|
||||
/// path and no longer at the old one). An export missing from both places follows if it is the sequence's own.
|
||||
/// </summary>
|
||||
internal static Task<int> RebaseRendersAsync(ChronosRepositories tx, Archive archive, Guid sequenceId, string from, string to,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
return tx.Renders.RebaseFolderAsync(archive.Id, sequenceId, from, to, (before, after) => File.Exists(paths.FromRelative(after))
|
||||
&& (string.Equals(before, after, StringComparison.OrdinalIgnoreCase) || !File.Exists(paths.FromRelative(before))), cancellationToken);
|
||||
return tx.Renders.RebaseFolderAsync(archive.Id, sequenceId, from, to, (before, after, own) =>
|
||||
{
|
||||
var moved = File.Exists(paths.FromRelative(after));
|
||||
var behind = !string.Equals(before, after, StringComparison.OrdinalIgnoreCase) && File.Exists(paths.FromRelative(before));
|
||||
return own ? moved || !behind : moved && !behind;
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -584,8 +584,9 @@ public sealed partial class FrameTrash
|
||||
/// Moves the thumbnails of the frames whose index changed to their new index in <c>thumbs.pack</c> (BRIEF §8.5: the pack
|
||||
/// is keyed by frame index) and drops those of the frames removed, as <see cref="ShiftProxies"/> does for proxies, so the
|
||||
/// thumbnail pass queued afterwards reuses them instead of drawing the rest of the sequence again. Only the pack's index
|
||||
/// is rewritten. A thumbnail writer holding the pack meanwhile (its lease) leaves it as it is, and so does a failure
|
||||
/// (logged): each thumbnail carries its original's fingerprint, so one in the wrong place is drawn again.
|
||||
/// is rewritten. An image pass holding the thumbnail lease meanwhile (a thumbnail pass, or a batch of a proxy pass)
|
||||
/// leaves the pack as it is, and so does a failure (logged): each thumbnail carries its original's fingerprint, so one
|
||||
/// in the wrong place is drawn again.
|
||||
/// </summary>
|
||||
private void ShiftThumbnails(ArchivePaths paths, SequencePaths folder, Guid sequenceId, IReadOnlyList<SidecarFrame> before,
|
||||
IReadOnlyList<SidecarFrame> after)
|
||||
@@ -598,7 +599,7 @@ public sealed partial class FrameTrash
|
||||
using var lease = LeaseFile.TryAcquire(paths.LocksDirectory, $"thumbs-{sequenceId:N}", _writer.Options.Owner, _writer.Options.LeaseDuration);
|
||||
if (lease is null)
|
||||
{
|
||||
Log.Info("archive", $"Thumbnails of {folder.RelativeFolder} are being written; the thumbnail pass draws those that moved again");
|
||||
Log.Info("archive", $"An image pass holds the thumbnails of {folder.RelativeFolder}; the thumbnail pass draws those that moved again");
|
||||
return;
|
||||
}
|
||||
using var pack = ThumbPackWriter.Open(folder.ThumbsPackPath);
|
||||
|
||||
@@ -57,7 +57,7 @@ public sealed record ArchiveServiceOptions
|
||||
/// journaled, or once its folder moved and its index row followed when the step then failed: by its job, or by an archive
|
||||
/// open that completed a plan an interruption left (<see cref="ArchiveService.OpenAsync"/>).
|
||||
/// A server tells its connected clients (BRIEF §14.3); the service it opens its archive with at start sets none, as no
|
||||
/// client is connected yet. A failure is logged and never fails the job.
|
||||
/// client is connected yet. The desktop reloads an editor open on the sequence. A failure is logged and never fails the job.
|
||||
/// </summary>
|
||||
public Func<Guid, string, CancellationToken, Task>? SequenceChanged { get; init; }
|
||||
|
||||
|
||||
@@ -21,7 +21,8 @@ namespace Chronos.Data.Processing.Jobs;
|
||||
/// server), named by the template without taking a name another render of this process is writing, and each finished
|
||||
/// output is recorded at once (its row id derives from the job and the entry, so every attempt knows what is recorded).
|
||||
/// Checkpoint: the entries recorded and the output being written, so a crashed attempt's leftovers are removed and only
|
||||
/// unfinished entries render again. A failed entry fails the job after the others ran; retrying renders it alone.
|
||||
/// unfinished entries render again. A failed entry fails the job after the others ran; retrying renders it alone. A
|
||||
/// sequence whose folder is not where the index has it (another index moved it, until this index's next scan) is refused.
|
||||
/// </summary>
|
||||
internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions options, FrameTiers tiers) : IJobHandler
|
||||
{
|
||||
@@ -40,6 +41,9 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
var folder = paths.Sequence(sequence.Folder);
|
||||
// A folder another index moved is found by this index's next scan. Until then nothing renders: its photos would all be
|
||||
// stand-ins, and its outputs would create the old folder again.
|
||||
if (!Directory.Exists(folder.Folder)) throw new InvalidOperationException(Loc.L("Errors.Archive.FolderMoved"));
|
||||
// A server writes only inside its archive (BRIEF §14.2): an export folder chosen on a client means nothing there.
|
||||
if (options.Host == EncoderHost.Server) export = export with { Folder = null };
|
||||
var project = (parameters.SettingsJson is { } embedded ? ProjectStore.Parse(embedded) : ProjectStore.Read(sequence, folder)) with { Export = export };
|
||||
|
||||
@@ -48,17 +48,19 @@ public sealed class RenderRepository
|
||||
/// <summary>
|
||||
/// Rewrites the archive-relative output paths of an archive's renders after the folder of sequence
|
||||
/// <paramref name="sequenceId"/> moved (a Reorganize, or a move another index of the archive or the user made, which a
|
||||
/// scan finds): an export inside the folder moved with it. The sequence's own exports there follow it, and so does an
|
||||
/// export of another sequence saved inside it (through the Export folder picker) when <paramref name="moved"/> says its
|
||||
/// file moved with it: a sequence that took the old folder since (a later Reorganize another index made) keeps its own.
|
||||
/// Outputs elsewhere (absolute paths, other folders) stay as they are.
|
||||
/// scan finds): an export inside the folder moved with it. Each render under the old folder whose file
|
||||
/// <paramref name="follows"/> the folder takes the new path: the caller tells the sequence's own exports there (which
|
||||
/// follow unless their file stayed behind) from an export of another sequence saved inside it through the Export
|
||||
/// folder picker (which follows only when its file moved with the folder: a sequence that took the old folder since, by
|
||||
/// a later Reorganize another index made, keeps its own). Outputs elsewhere (absolute paths, other folders) stay as they are.
|
||||
/// </summary>
|
||||
/// <param name="moved">Whether the file at the first archive-relative path is at the second one now.</param>
|
||||
/// <param name="follows">Whether the render at the first archive-relative path follows to the second one; the third
|
||||
/// argument says whether it is one of the sequence's own.</param>
|
||||
/// <remarks>Only paths still under <paramref name="oldFolder"/> change, so repeating it after a crash is harmless.</remarks>
|
||||
public async Task<int> RebaseFolderAsync(Guid archiveId, Guid sequenceId, string oldFolder, string newFolder, Func<string, string, bool> moved,
|
||||
public async Task<int> RebaseFolderAsync(Guid archiveId, Guid sequenceId, string oldFolder, string newFolder, Func<string, string, bool, bool> follows,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(moved);
|
||||
ArgumentNullException.ThrowIfNull(follows);
|
||||
// The archive root never moves, and its prefix ("/") would match absolute paths outside the archive.
|
||||
if (oldFolder.Length == 0) return 0;
|
||||
// substr counts characters (code points) on both dialects.
|
||||
@@ -71,7 +73,7 @@ public sealed class RenderRepository
|
||||
foreach (var (id, owner, path) in under)
|
||||
{
|
||||
var to = newFolder.Length == 0 ? path[prefix.Length..] : newFolder + path[oldFolder.Length..];
|
||||
if (owner != sequenceId && !moved(path, to)) continue;
|
||||
if (!follows(path, to, owner == sequenceId)) continue;
|
||||
rebased += await _db.ExecuteAsync("UPDATE renders SET output_path = $2 WHERE id = $1", [id, to], cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
return rebased;
|
||||
|
||||
@@ -177,7 +177,9 @@ public sealed class SyncService
|
||||
/// <summary>
|
||||
/// Settles a conflict as the user chose (BRIEF §12.7), against the versions the user was shown: when either side
|
||||
/// changed again since, nothing is written, the sequence is compared again and <see cref="SyncConflictChangedException"/>
|
||||
/// is thrown. Returns the file this PC's settings were saved to for <see cref="SyncResolution.SaveBoth"/>, else null.
|
||||
/// is thrown, as it is when <see cref="SyncResolution.SaveBoth"/> cannot keep this PC's version first (the folder is not
|
||||
/// where the index has it). Returns the file this PC's settings were saved to for <see cref="SyncResolution.SaveBoth"/>,
|
||||
/// else null.
|
||||
/// </summary>
|
||||
public async Task<string?> ResolveAsync(ISyncRemote remote, Guid remoteId, SyncResolution resolution, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -222,9 +224,14 @@ public sealed class SyncService
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
else if (resolution == SyncResolution.SaveBoth && (saved = await SaveCopyAsync(local, cancellationToken).ConfigureAwait(false)) is null)
|
||||
{
|
||||
// This PC's version could not be kept (another index moved the folder): the server's does not replace it,
|
||||
// even where this index's scan finds the folder before the server's version would be written.
|
||||
changed = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (resolution == SyncResolution.SaveBoth) saved = await SaveCopyAsync(local, cancellationToken).ConfigureAwait(false);
|
||||
var theirs = SyncPayload.Of(dto, manifest!.SettingsJson);
|
||||
if (await ApplyLocallyAsync(local, theirs, Positions(remote, local, manifest), cancellationToken).ConfigureAwait(false) is { } applied)
|
||||
{
|
||||
@@ -234,7 +241,7 @@ public sealed class SyncService
|
||||
{
|
||||
// Edited on this PC since it was read: the copy of a version the user did not choose to keep goes.
|
||||
changed = true;
|
||||
if (saved is not null) File.Delete(saved);
|
||||
if (saved is not null) await DeleteCopyAsync(local, saved, cancellationToken).ConfigureAwait(false);
|
||||
saved = null;
|
||||
}
|
||||
}
|
||||
@@ -816,6 +823,30 @@ public sealed class SyncService
|
||||
return path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a "Save both" copy of a version the user did not keep from the sequence's folder as the index has it now: a
|
||||
/// Reorganize may have moved the folder, the copy with it, since the copy was written. Best effort: a copy that cannot
|
||||
/// be reached (the folder gone, the sequence busy, the archive offline) stays, as one more copy of this PC's version.
|
||||
/// </summary>
|
||||
private async Task DeleteCopyAsync(Sequence local, string saved, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var archive = await _db.Archives.GetAsync(local.ArchiveId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new InvalidDataException($"Archive {local.ArchiveId} is not indexed.");
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
await using (await _writer.LockAsync(paths, local.Id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var folder = await SequenceWriter.FolderAsync(_db, paths, local, cancellationToken).ConfigureAwait(false);
|
||||
if (Directory.Exists(folder.MetaDirectory)) File.Delete(Path.Combine(folder.MetaDirectory, Path.GetFileName(saved)));
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
|
||||
{
|
||||
Log.Warning(LogCategory, $"The copy {saved} of {local.DisplayTitle}'s settings could not be deleted", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The file name of a "Save both" copy kept at <paramref name="localTime"/>.</summary>
|
||||
public static string SavedCopyName(DateTime localTime) =>
|
||||
string.Create(CultureInfo.InvariantCulture, $"{SavedCopyPrefix}{localTime.ToString(SavedCopyTimeFormat, CultureInfo.InvariantCulture)}.json");
|
||||
|
||||
@@ -370,31 +370,43 @@ internal sealed class SyncTransfers(SyncService sync)
|
||||
EnsureSpace(paths.Root, wanted.Sum(r => r.Bytes));
|
||||
|
||||
var staging = Path.Combine(paths.StagingDirectory, "exports-" + remoteId.ToString("N"));
|
||||
var exports = paths.Sequence(local.Folder).Exports;
|
||||
Directory.CreateDirectory(staging);
|
||||
Directory.CreateDirectory(exports);
|
||||
var progress = new TransferProgress(context, wanted.Count, 0);
|
||||
await progress.ReportAsync().ConfigureAwait(false);
|
||||
foreach (var render in wanted)
|
||||
{
|
||||
var (part, name) = await FetchRenderAsync(remote, render, staging, ct).ConfigureAwait(false);
|
||||
var target = Unique(exports, name);
|
||||
File.Move(part, target);
|
||||
await db.Renders.InsertAsync(new Render
|
||||
// Filed under the sequence's lease into its folder as the index has it then, as a server files a render: a
|
||||
// Reorganize may have moved it since the sequence was read, and moves the row's path along when it moves it later.
|
||||
// One another index moved is found by this index's next scan; until then nothing is filed (the download stays
|
||||
// staged for the next attempt), so the folder it left is not created again.
|
||||
var filed = await sync.Archives.UnderLeaseAsync(local, async row =>
|
||||
{
|
||||
Id = render.Id,
|
||||
SequenceId = local.Id,
|
||||
PresetName = render.PresetName,
|
||||
OutputPath = paths.ToRelative(target),
|
||||
Codec = render.Codec,
|
||||
Width = render.Width,
|
||||
Height = render.Height,
|
||||
Fps = render.Fps,
|
||||
DurationSeconds = render.DurationSeconds,
|
||||
Bytes = new FileInfo(target).Length,
|
||||
Created = render.Created,
|
||||
ProducedBy = render.ProducedBy,
|
||||
if (row is null) throw new InvalidOperationException(Loc.L("Errors.Sync.LocalMissing"));
|
||||
var folder = paths.Sequence(row.Folder);
|
||||
if (!Directory.Exists(folder.Folder)) return false;
|
||||
Directory.CreateDirectory(folder.Exports);
|
||||
var target = Unique(folder.Exports, name);
|
||||
File.Move(part, target);
|
||||
// Recorded even if the job is being cancelled: a filed export is never left without its row.
|
||||
await db.Renders.InsertAsync(new Render
|
||||
{
|
||||
Id = render.Id,
|
||||
SequenceId = row.Id,
|
||||
PresetName = render.PresetName,
|
||||
OutputPath = paths.ToRelative(target),
|
||||
Codec = render.Codec,
|
||||
Width = render.Width,
|
||||
Height = render.Height,
|
||||
Fps = render.Fps,
|
||||
DurationSeconds = render.DurationSeconds,
|
||||
Bytes = new FileInfo(target).Length,
|
||||
Created = render.Created,
|
||||
ProducedBy = render.ProducedBy,
|
||||
}, CancellationToken.None).ConfigureAwait(false);
|
||||
return true;
|
||||
}, ct).ConfigureAwait(false);
|
||||
if (!filed) throw new InvalidOperationException(Loc.L("Errors.Archive.FolderMoved"));
|
||||
await progress.StepAsync().ConfigureAwait(false);
|
||||
}
|
||||
TryDeleteDirectory(staging);
|
||||
|
||||
@@ -56,7 +56,11 @@ public sealed record JobPriorityRequest(string Priority);
|
||||
/// </summary>
|
||||
public sealed record RenderJobParameters(string PresetName, string PresetJson, string Codec, int Width, int Height, bool UseProxies, string? SettingsJson);
|
||||
|
||||
/// <summary><c>POST /api/v1/nodes/{id}/jobs/{jobId}/result</c>: the finished output a node is about to upload in chunks.</summary>
|
||||
/// <summary>
|
||||
/// <c>POST /api/v1/nodes/{id}/jobs/{jobId}/result</c>: the finished output a node is about to upload in chunks. A
|
||||
/// <c>result/complete</c> that cannot file it for now answers 503 <c>sequence_busy</c> or <c>archive_offline</c>; the
|
||||
/// upload and the job stay the node's, to be completed again.
|
||||
/// </summary>
|
||||
public sealed record RenderResultRequest(
|
||||
string FileName,
|
||||
long Size,
|
||||
|
||||
@@ -43,7 +43,8 @@ public sealed record CardImportReport(Guid ImportId, string Card, string State,
|
||||
/// renders are uploaded on request). The render keeps its id on the server, so both sides recognise it; when the
|
||||
/// server already has that id it answers 200 with <see cref="StartUploadResponse.AlreadyExists"/>. Chunks go to
|
||||
/// <c>/uploads/{uploadId}/chunks/{n}</c>; <c>POST /sequences/{id}/renders/{uploadId}/complete</c> verifies the SHA-256
|
||||
/// and files the render under the sequence's exports.
|
||||
/// and files the render under the sequence's exports. A completion that cannot file it for now answers 503
|
||||
/// <c>sequence_busy</c> or <c>archive_offline</c> and keeps the upload, to be completed again.
|
||||
/// </summary>
|
||||
public sealed record RenderUploadRequest(
|
||||
Guid RenderId,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Jobs;
|
||||
@@ -175,7 +176,16 @@ public sealed class RenderNodeService(
|
||||
if (await uploads.StageVerifiedAsync(upload, cancellationToken) is not { } staged) return Outcome<RenderDto>.Fail(422, "hash_mismatch");
|
||||
var output = JsonSerializer.Deserialize(upload.RenderJson, ProtocolJson.Default.RenderResultRequest)!;
|
||||
var sequence = await db.Sequences.GetAsync(job.TargetIds[0], cancellationToken);
|
||||
var render = sequence is null ? null : await renders.CommitAsync(sequence, staged, output, node.ClientName, cancellationToken);
|
||||
Render? render;
|
||||
try
|
||||
{
|
||||
render = sequence is null ? null : await renders.CommitAsync(sequence, staged, output, node.ClientName, cancellationToken);
|
||||
}
|
||||
catch (Exception ex) when (ex is LeaseUnavailableException or ArchiveOfflineException)
|
||||
{
|
||||
// The node keeps the job and completes again.
|
||||
return await uploads.ReceiveAgainAsync<RenderDto>(upload, staged, ex);
|
||||
}
|
||||
if (render is null)
|
||||
{
|
||||
UploadStore.TryDelete(staged);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Protocol;
|
||||
@@ -87,8 +89,16 @@ public sealed class RenderUploads(
|
||||
var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken);
|
||||
var result = new RenderResultRequest(output.FileName, output.Size, output.Sha256, output.PresetName, output.Codec, output.Width, output.Height, output.Fps,
|
||||
output.DurationSeconds);
|
||||
var render = sequence is null ? null : await renders.CommitAsync(sequence, staged, result, output.ProducedBy ?? caller.ClientName ?? caller.User.Username,
|
||||
output.RenderId, cancellationToken);
|
||||
Render? render;
|
||||
try
|
||||
{
|
||||
render = sequence is null ? null : await renders.CommitAsync(sequence, staged, result, output.ProducedBy ?? caller.ClientName ?? caller.User.Username,
|
||||
output.RenderId, cancellationToken);
|
||||
}
|
||||
catch (Exception ex) when (ex is LeaseUnavailableException or ArchiveOfflineException)
|
||||
{
|
||||
return await uploads.ReceiveAgainAsync<RenderDto>(upload, staged, ex);
|
||||
}
|
||||
if (render is null)
|
||||
{
|
||||
UploadStore.TryDelete(staged);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Repositories;
|
||||
@@ -303,6 +304,21 @@ public sealed class UploadService(
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A verified upload whose filing was refused before anything moved, for a reason that passes: its sequence held by
|
||||
/// another writer past the lease wait (503 <c>sequence_busy</c>), or the archive offline or read-only (503
|
||||
/// <c>archive_offline</c>). The staged copy goes and the upload receives again with its part file, so the client
|
||||
/// completes it again, as it does after any 503.
|
||||
/// </summary>
|
||||
public async Task<Outcome<T>> ReceiveAgainAsync<T>(Upload upload, string staged, Exception refusal)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(upload);
|
||||
logger.LogWarning("Upload {Upload} ({File}) not filed for now: {Reason}", upload.Id, upload.FileName, refusal.Message);
|
||||
UploadStore.TryDelete(staged);
|
||||
await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Receiving, cancellationToken: CancellationToken.None);
|
||||
return Fail<T>(503, refusal is ArchiveOfflineException ? "archive_offline" : "sequence_busy");
|
||||
}
|
||||
|
||||
private async Task FailAsync(Upload upload)
|
||||
{
|
||||
await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Failed, cancellationToken: CancellationToken.None);
|
||||
|
||||
Reference in new issue
Block a user