feat: jobs run one at a time, parallelism per photo and a priority queue
Owner review 1, phase 2 (docs/requests/2026-10-15-owner-review-1.md, R2). Jobs now run one at a time on the desktop and on the server. Parallelism (Settings > Rendering, TITANO_PARALLELISM) is how many photos the running job processes at once: thumbnail and proxy passes draw that many photos together and still write the pack and checkpoints in frame order, decode tiers are probed that many at a time, the deep analysis measures that many frames and a render decodes that many ahead. Wherever originals are developed whole (TIFF, PNG, RAW without a usable preview), fewer run at once within the memory budget, which the running job now has whole; the server's frame window is sized to the host instead of 1 GiB. A new job waits its turn and pausing the running job starts the next one. An optional priority queue gives each job kind a level (renders, imports and downloads high, verifies and proxies low by default): a queued job of a higher level pauses the running one without asking, and that job goes back to the queue with its checkpoint and resumes by itself afterwards. Jobs of the same level, and a job's own follow-ups, never interrupt it. The Jobs screen and the admin panel show the parallelism and the queue; Settings > Rendering and the admin panel's Settings set them, at once. TITANO_WORKERS and the Workers key of server.json still set the parallelism (1 to 64, with a warning at start for the variable). Titano.Tools gains i18n prune, which removed the renamed keys from the 36 machine-translated languages; the new strings are translated in all 38. Found while testing: uploads and imports failed when a pass read the sidecar while they wrote it (atomic writes now retry the rename while a reader holds the file, and never for a read-only one), and taking a lease just released while another process read it failed on Windows (the create now waits for the reader). Five adversarial review rounds checked the phase before this commit. Also updates BRIEF (12.8, 14.6, 14.8, 14.9, 24), DECISIONS, CHANGELOG, ARCHITECTURE, STATUS, the request file and the compose/Unraid templates. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
34d03051f5
commit
43b6871cdc
228 files changed
+3535
-793
No files matched your search
@@ -188,6 +188,10 @@ public sealed class ArchiveImages
|
||||
/// <param name="startFrame">Resume point inside the sequence (frames before it were done by an earlier run: the
|
||||
/// sequence's built status counts them as they are now).</param>
|
||||
/// <param name="checkpoint">Called with the next frame index whenever the pack has been committed.</param>
|
||||
/// <remarks>
|
||||
/// Several frames are drawn at once (<see cref="ThumbnailParallelism"/>); the pack takes them in frame order
|
||||
/// (<see cref="OrderedWork{T}"/>), so a checkpoint still means that every frame before it is in the pack.
|
||||
/// </remarks>
|
||||
public async Task<ImagePassResult> BuildThumbnailsAsync(Archive archive, Sequence sequence, bool force, int startFrame,
|
||||
Func<int, int, ValueTask> checkpoint, CancellationToken cancellationToken = default)
|
||||
{
|
||||
@@ -212,44 +216,52 @@ public sealed class ArchiveImages
|
||||
complete &= pack.Entries.GetValueOrDefault(frame.I) is { } entry && ThumbPack.IsFrom(entry.SourceHash, frame.Sha256, frame.File, frame.Size);
|
||||
}
|
||||
var cadence = new Cadence();
|
||||
for (var i = startFrame; i < manifest.Frames.Count; i++)
|
||||
await using (var work = new OrderedWork<Drawn>(ThumbnailParallelism(manifest.Frames, policy), drawn =>
|
||||
{
|
||||
if (drawn.Image is { } image)
|
||||
{
|
||||
pack.Append(drawn.Frame.I, image.Width, image.Height, drawn.Fingerprint, image.Jpeg);
|
||||
built++;
|
||||
}
|
||||
else
|
||||
{
|
||||
undecodable++;
|
||||
}
|
||||
if (drawn.Tier is { } tier) tiers[drawn.Frame.Id] = tier;
|
||||
if (!cadence.Due()) return ValueTask.CompletedTask;
|
||||
pack.Commit();
|
||||
return checkpoint(drawn.Index + 1, manifest.Frames.Count);
|
||||
}, cancellationToken))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var frame = manifest.Frames[i];
|
||||
var fingerprint = ThumbPack.Fingerprint(frame.Sha256, frame.File, frame.Size);
|
||||
var entry = pack.Entries.GetValueOrDefault(frame.I);
|
||||
var edge = entry is null ? 0 : System.Math.Max(entry.Width, entry.Height);
|
||||
var current = !force && entry is not null && ThumbPack.IsFrom(entry.SourceHash, frame.Sha256, frame.File, frame.Size);
|
||||
// A frame this host cannot decode shows its proxy once one arrived; until then its original's embedded
|
||||
// preview, whose smaller thumbnail the proxy's replaces.
|
||||
var fromProxy = false;
|
||||
if (NeedsProxy(frame.Format) && !(current && edge >= policy.LongEdge)
|
||||
&& Check(folder.Proxy(frame.I), frame.CapturedAt, frame.W, frame.H, archiveManifest.ProxyPolicy) is { Check: ProxyCheck.Current or ProxyCheck.Unverifiable } proxy)
|
||||
fromProxy = !current || edge < System.Math.Min(policy.LongEdge, proxy.LongEdge);
|
||||
if (current && !fromProxy)
|
||||
for (var i = startFrame; i < manifest.Frames.Count; i++)
|
||||
{
|
||||
reused++;
|
||||
continue;
|
||||
}
|
||||
var companion = companions.GetValueOrDefault(frame.Id);
|
||||
// A thumbnail drawn from the proxy says nothing about how this host decodes the original.
|
||||
var image = fromProxy
|
||||
? Render(folder, frame, null, null, () => _renderer.Thumbnail(folder, ProxySource(frame), policy, cancellationToken))
|
||||
: Render(folder, frame, companion, tiers, () => _renderer.Thumbnail(folder, frame, policy, cancellationToken, companion));
|
||||
if (image is not null)
|
||||
{
|
||||
pack.Append(frame.I, image.Width, image.Height, fingerprint, image.Jpeg);
|
||||
built++;
|
||||
}
|
||||
else
|
||||
{
|
||||
undecodable++;
|
||||
}
|
||||
if (cadence.Due())
|
||||
{
|
||||
pack.Commit();
|
||||
await checkpoint(i + 1, manifest.Frames.Count).ConfigureAwait(false);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var frame = manifest.Frames[i];
|
||||
var fingerprint = ThumbPack.Fingerprint(frame.Sha256, frame.File, frame.Size);
|
||||
var entry = pack.Entries.GetValueOrDefault(frame.I);
|
||||
var edge = entry is null ? 0 : System.Math.Max(entry.Width, entry.Height);
|
||||
var current = !force && entry is not null && ThumbPack.IsFrom(entry.SourceHash, frame.Sha256, frame.File, frame.Size);
|
||||
// A frame this host cannot decode shows its proxy once one arrived; until then its original's embedded
|
||||
// preview, whose smaller thumbnail the proxy's replaces.
|
||||
var fromProxy = false;
|
||||
if (NeedsProxy(frame.Format) && !(current && edge >= policy.LongEdge)
|
||||
&& Check(folder.Proxy(frame.I), frame.CapturedAt, frame.W, frame.H, archiveManifest.ProxyPolicy) is { Check: ProxyCheck.Current or ProxyCheck.Unverifiable } proxy)
|
||||
fromProxy = !current || edge < System.Math.Min(policy.LongEdge, proxy.LongEdge);
|
||||
if (current && !fromProxy)
|
||||
{
|
||||
reused++;
|
||||
continue;
|
||||
}
|
||||
var companion = companions.GetValueOrDefault(frame.Id);
|
||||
var index = i;
|
||||
// A thumbnail drawn from the proxy says nothing about how this host decodes the original.
|
||||
await work.AddAsync(fromProxy
|
||||
? ct => Drawn.Of(index, frame, fingerprint, Render(folder, frame, null, recordTier: false,
|
||||
() => _renderer.Thumbnail(folder, ProxySource(frame), policy, ct)))
|
||||
: ct => Drawn.Of(index, frame, fingerprint, Render(folder, frame, companion, recordTier: true,
|
||||
() => _renderer.Thumbnail(folder, frame, policy, ct, companion)))).ConfigureAwait(false);
|
||||
}
|
||||
await work.CompleteAsync().ConfigureAwait(false);
|
||||
}
|
||||
pack.Commit();
|
||||
}
|
||||
@@ -264,7 +276,9 @@ public sealed class ArchiveImages
|
||||
/// <see cref="SequenceStatus.ProxiesBuilt"/> is set only when every frame has its proxy: a server asks clients and
|
||||
/// render nodes for none while it is set (BRIEF §2.3), so a pass resumed at <paramref name="startFrame"/> checks the
|
||||
/// 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"/>).
|
||||
/// 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}"/>).
|
||||
/// </remarks>
|
||||
public async Task<ImagePassResult> BuildProxiesAsync(Archive archive, Sequence sequence, bool force, int startFrame,
|
||||
Func<int, int, ValueTask> checkpoint, CancellationToken cancellationToken = default)
|
||||
@@ -281,56 +295,139 @@ public sealed class ArchiveImages
|
||||
var tiers = new Dictionary<Guid, FileTier>();
|
||||
var companions = await GprCompanions.FindAsync(_db, archive, manifest.Frames, cancellationToken).ConfigureAwait(false);
|
||||
var cadence = new Cadence();
|
||||
for (var i = 0; i < manifest.Frames.Count; i++)
|
||||
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))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var frame = manifest.Frames[i];
|
||||
var path = folder.Proxy(frame.I);
|
||||
var done = i < startFrame;
|
||||
if (NeedsProxy(frame.Format))
|
||||
for (var i = 0; i < manifest.Frames.Count; i++)
|
||||
{
|
||||
// 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;
|
||||
if (usable) reused++;
|
||||
else if ((frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0) undecodable++;
|
||||
else waiting++;
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var frame = manifest.Frames[i];
|
||||
var path = folder.Proxy(frame.I);
|
||||
var done = i < 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(i, 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 = 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);
|
||||
}
|
||||
else 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;
|
||||
}
|
||||
else if (!force && ReadProxy(path, frame.CapturedAt).Check == ProxyCheck.Current)
|
||||
{
|
||||
reused++;
|
||||
continue;
|
||||
}
|
||||
else if (Render(folder, frame, companions.GetValueOrDefault(frame.Id), tiers,
|
||||
() => _renderer.Proxy(folder, frame, manifest.Camera, policy, cancellationToken, companions.GetValueOrDefault(frame.Id))) is { } image)
|
||||
{
|
||||
AtomicFile.WriteAllBytes(path, image.Jpeg);
|
||||
Headers.TryRemove(path, out _);
|
||||
built++;
|
||||
}
|
||||
else
|
||||
{
|
||||
undecodable++;
|
||||
complete = false;
|
||||
}
|
||||
if (cadence.Due()) await checkpoint(i + 1, manifest.Frames.Count).ConfigureAwait(false);
|
||||
await work.CompleteAsync().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>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);
|
||||
|
||||
/// <summary>Originals a proxy pass decodes at once (<see cref="PassParallelism"/>): it develops RAWs, and decodes whole for a full-size policy.</summary>
|
||||
private int ProxyParallelism(IReadOnlyList<SidecarFrame> frames, ProxyPolicy policy) =>
|
||||
PassParallelism(_writer.Options.Parallelism(), _writer.Options.MemoryBudget(), frames, System.Math.Max(policy.LongEdge, 0), preferPreview: false,
|
||||
_writer.Options.Decoder);
|
||||
|
||||
/// <summary>
|
||||
/// Photos a pass decoding at <paramref name="edge"/> (0: full size) works on at once: the whole parallelism while no
|
||||
/// frame is developed whole (a JPEG at least twice the edge decodes scaled down; a frame this host reads through its
|
||||
/// proxy or preview develops nothing here, nor one whose embedded preview reaches the edge when previews serve), else
|
||||
/// <see cref="DecodeBudget.PhotosAtOnce"/> for the largest original developed (a TIFF, a PNG, a RAW).
|
||||
/// </summary>
|
||||
internal static int PassParallelism(int parallelism, long memoryBudget, IReadOnlyList<SidecarFrame> frames, int edge, bool preferPreview, ImageDecoder decoder)
|
||||
{
|
||||
parallelism = Math.Max(1, parallelism);
|
||||
long largest = 0;
|
||||
foreach (var frame in frames)
|
||||
{
|
||||
if (NeedsProxy(decoder, frame.Format)) continue;
|
||||
largest = System.Math.Max(largest, DecodeBudget.Developed(frame.Format, frame.W, frame.H, System.Math.Max(frame.PreviewW ?? 0, frame.PreviewH ?? 0),
|
||||
edge, preferPreview));
|
||||
}
|
||||
return largest == 0 ? parallelism : DecodeBudget.PhotosAtOnce(parallelism, memoryBudget, largest);
|
||||
}
|
||||
|
||||
/// <summary>A thumbnail drawn for the frame at <see cref="Index"/> of the pass (null: nothing decoded it) and what decoding found.</summary>
|
||||
private sealed record Drawn(int Index, SidecarFrame Frame, byte[] Fingerprint, EncodedImage? Image, FileTier? Tier)
|
||||
{
|
||||
public static Drawn Of(int index, SidecarFrame frame, byte[] fingerprint, (EncodedImage? Image, FileTier? Tier) rendered) =>
|
||||
new(index, frame, fingerprint, rendered.Image, rendered.Tier);
|
||||
}
|
||||
|
||||
/// <summary>What became of the proxy of a frame of a proxy pass.</summary>
|
||||
private enum ProxyOutcome
|
||||
{
|
||||
Built,
|
||||
|
||||
/// <summary>The frame this host cannot decode has its proxy from a client or render node.</summary>
|
||||
Reused,
|
||||
|
||||
/// <summary>The frame this host cannot decode waits for its proxy from a client or render node.</summary>
|
||||
Waiting,
|
||||
|
||||
/// <summary>The frame this host cannot decode is missing or damaged.</summary>
|
||||
Unreadable,
|
||||
|
||||
/// <summary>No decoder read the original.</summary>
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>The proxy outcome of the frame at <see cref="Index"/> of the pass, and what decoding found.</summary>
|
||||
private sealed record Made(int Index, Guid FrameId, ProxyOutcome Outcome, FileTier? Tier);
|
||||
|
||||
/// <summary>Where a frame's proxy stands; only a capture time tells whether it is the frame's.</summary>
|
||||
private enum ProxyCheck
|
||||
{
|
||||
@@ -457,11 +554,12 @@ public sealed class ArchiveImages
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A frame no decoder can read is skipped and counted; it never stops the pass. What decoding found goes into
|
||||
/// <paramref name="tiers"/> (when given): unavailable when nothing decoded a file that is there (a read error proves
|
||||
/// nothing), and the probed tier when a frame flagged undecodable decoded after all.
|
||||
/// A frame no decoder can read is skipped and counted; it never stops the pass. With <paramref name="recordTier"/>,
|
||||
/// what decoding found comes back with the image: unavailable when nothing decoded a file that is there (a read error
|
||||
/// proves nothing), and the probed tier when a frame flagged undecodable decoded after all. Runs on the pass's
|
||||
/// workers, so it shares nothing with the others.
|
||||
/// </summary>
|
||||
private EncodedImage? Render(SequencePaths folder, SidecarFrame frame, string? companion, Dictionary<Guid, FileTier>? tiers, Func<EncodedImage?> render)
|
||||
private (EncodedImage? Image, FileTier? Tier) Render(SequencePaths folder, SidecarFrame frame, string? companion, bool recordTier, Func<EncodedImage?> render)
|
||||
{
|
||||
var path = folder.File(frame.File);
|
||||
EncodedImage? image;
|
||||
@@ -472,23 +570,17 @@ public sealed class ArchiveImages
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("archive", "Frame image could not be rendered", ex);
|
||||
return null;
|
||||
return (null, null);
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidDataException or NotSupportedException)
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("archive", "Frame image could not be rendered", ex);
|
||||
image = null;
|
||||
}
|
||||
if (tiers is null) return image;
|
||||
if (!recordTier) return (image, null);
|
||||
if (image is null)
|
||||
{
|
||||
if (File.Exists(path)) tiers[frame.Id] = new FileTier(frame.Format, DecodeTier.Unavailable, null, "no decoder produced pixels", 0, 0);
|
||||
}
|
||||
else if ((frame.Flags & FrameFlags.Undecodable) != 0)
|
||||
{
|
||||
tiers[frame.Id] = Reprobe(path, frame, companion, image.Tier);
|
||||
}
|
||||
return image;
|
||||
return (null, File.Exists(path) ? new FileTier(frame.Format, DecodeTier.Unavailable, null, "no decoder produced pixels", 0, 0) : null);
|
||||
return (image, (frame.Flags & FrameFlags.Undecodable) != 0 ? Reprobe(path, frame, companion, image.Tier) : null);
|
||||
}
|
||||
|
||||
/// <summary>The tier of a frame that decoded after it was flagged undecodable (the image's own tier when probing finds none).</summary>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.IO;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Repositories;
|
||||
|
||||
@@ -83,7 +84,7 @@ public sealed class ArchiveIndexer
|
||||
// reading): a sidecar rewritten meanwhile is never filed under its new stamp with its old content.
|
||||
var sidecar = paths.Sequence(folder.RelativeFolder).ManifestPath;
|
||||
var read = bytes is not null ? folder.Sidecar!.Value : FileStamp.Of(sidecar)!.Value;
|
||||
snapshotWriter.Add(folder.RelativeFolder, read, bytes ?? await File.ReadAllBytesAsync(sidecar, cancellationToken).ConfigureAwait(false));
|
||||
snapshotWriter.Add(folder.RelativeFolder, read, bytes ?? await AtomicFile.ReadAllBytesAsync(sidecar, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
indexed.Add(id);
|
||||
if (folder.Sidecar is null) adopted++;
|
||||
@@ -305,7 +306,7 @@ public sealed class ArchiveIndexer
|
||||
}
|
||||
else
|
||||
{
|
||||
bytes = snapshot?.TryGet(folder.RelativeFolder, stamp) ?? await File.ReadAllBytesAsync(sequence.ManifestPath, cancellationToken).ConfigureAwait(false);
|
||||
bytes = snapshot?.TryGet(folder.RelativeFolder, stamp) ?? await AtomicFile.ReadAllBytesAsync(sequence.ManifestPath, cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
manifest = ManifestStore.ParseSequence(bytes, sequence.ManifestPath);
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
using Titano.Core.Imaging;
|
||||
|
||||
namespace Titano.Data.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// How many photos a job decodes from their originals at once (owner review 1, R2): the host's parallelism, fewer when
|
||||
/// the memory budget cannot hold that many decodes of the largest original. A decode takes some
|
||||
/// <see cref="BytesPerPixel"/> per pixel of the original while it runs: a 16-bit mosaic, float RGB and a copy. Only decodes
|
||||
/// that develop an original whole count (<see cref="Developed"/>); thumbnail and proxy passes, deep analyses and every
|
||||
/// window of a render ask it.
|
||||
/// </summary>
|
||||
internal static class DecodeBudget
|
||||
{
|
||||
/// <summary>Memory one decode of an original may take per pixel: a 16-bit mosaic, float RGB and a copy.</summary>
|
||||
public const long BytesPerPixel = 32;
|
||||
|
||||
/// <summary>Pixels assumed for an original of unknown size (a 24 MP sensor).</summary>
|
||||
public const long UnknownPixels = 24_000_000;
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="parallelism"/> decodes, fewer when <paramref name="memoryBudget"/> cannot hold that many of an
|
||||
/// original of <paramref name="largestPixels"/> (unknown when 0 or less); at least one.
|
||||
/// </summary>
|
||||
public static int PhotosAtOnce(int parallelism, long memoryBudget, long largestPixels)
|
||||
{
|
||||
if (parallelism <= 1) return 1;
|
||||
// A size a damaged file claims never overflows the product.
|
||||
var pixels = largestPixels > 0 ? Math.Min(largestPixels, long.MaxValue / BytesPerPixel) : UnknownPixels;
|
||||
return (int)Math.Clamp(memoryBudget / (pixels * BytesPerPixel), 1, parallelism);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The pixels of an original that a decode at <paramref name="edge"/> (0: full size) develops whole, 0 when it takes a
|
||||
/// cheap path: a JPEG whose long edge is at least twice the edge decodes scaled down, and a RAW's embedded preview that
|
||||
/// reaches the edge serves a decode that prefers previews (<paramref name="preferPreview"/>: thumbnails, analyses, a
|
||||
/// render's preparation; never a render). Another format's stored preview is no shortcut: a JPEG-compressed TIFF strip
|
||||
/// may need the file's own tables and fall back to a full decode. Anything else (a TIFF, a PNG, a RAW developed) counts
|
||||
/// whole, an unknown size as <see cref="UnknownPixels"/>.
|
||||
/// </summary>
|
||||
public static long Developed(ImageFileFormat format, int width, int height, int previewLongEdge, int edge, bool preferPreview)
|
||||
{
|
||||
if (edge > 0 && format == ImageFileFormat.Jpeg && Math.Max(width, height) >= 2L * edge) return 0;
|
||||
if (edge > 0 && preferPreview && previewLongEdge >= edge && ImageFormatInfo.Of(format).IsRaw) return 0;
|
||||
var pixels = (long)Math.Max(width, 0) * Math.Max(height, 0);
|
||||
return pixels > 0 ? pixels : UnknownPixels;
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Model;
|
||||
@@ -23,21 +24,21 @@ internal sealed class FrameTiers(TitanoDatabase db, SequenceWriter writer, Archi
|
||||
/// preview whose size is not known (the output cap needs it), or that is a GPR whose JPEG in another sequence
|
||||
/// (<see cref="GprCompanions"/>; an upload may index it after the GPR was probed) is larger than its stored preview,
|
||||
/// or that is stored as GPR without the .gpr extension (indexed before GoPro DNGs converted by Adobe software counted as
|
||||
/// DNG; R4, owner review 1), probed with the host's decoders without decoding pixels; missing and unreadable files are
|
||||
/// left for later.
|
||||
/// DNG; R4, owner review 1), probed with the host's decoders without decoding pixels, several at once
|
||||
/// (<see cref="ArchiveServiceOptions.Parallelism"/>); missing and unreadable files are left for later.
|
||||
/// </summary>
|
||||
public async Task<Dictionary<Guid, FileTier>> ProbeUnknownAsync(Archive archive, SequencePaths folder, SequenceManifest manifest,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var tiers = new Dictionary<Guid, FileTier>();
|
||||
var present = manifest.Frames.Where(f => (f.Flags & FrameFlags.Missing) == 0).ToList();
|
||||
var companions = await GprCompanions.FindWithSizesAsync(db, archive, present, cancellationToken).ConfigureAwait(false);
|
||||
var unknown = present.Where(f => f.Tier == 0 || (f.Tier == DecodeTier.EmbeddedPreview && f.PreviewW is null) || IsStaleGpr(f)
|
||||
|| (companions.TryGetValue(f.Id, out var jpeg)
|
||||
&& int.Max(f.PreviewW ?? 0, f.PreviewH ?? 0) < int.Max(jpeg.Width, jpeg.Height)));
|
||||
foreach (var frame in unknown)
|
||||
&& int.Max(f.PreviewW ?? 0, f.PreviewH ?? 0) < int.Max(jpeg.Width, jpeg.Height))).ToList();
|
||||
var tiers = new ConcurrentDictionary<Guid, FileTier>();
|
||||
var options = new ParallelOptions { MaxDegreeOfParallelism = Math.Max(1, writer.Options.Parallelism()), CancellationToken = cancellationToken };
|
||||
await Parallel.ForEachAsync(unknown, options, (frame, _) =>
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var path = folder.File(frame.File);
|
||||
try
|
||||
{
|
||||
@@ -49,8 +50,9 @@ internal sealed class FrameTiers(TitanoDatabase db, SequenceWriter writer, Archi
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("archive", $"{path} could not be probed", ex);
|
||||
}
|
||||
}
|
||||
return tiers;
|
||||
return ValueTask.CompletedTask;
|
||||
}).ConfigureAwait(false);
|
||||
return new Dictionary<Guid, FileTier>(tiers);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
namespace Titano.Data.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// The frames of a pass worked on several at once (owner review 1, R2: the parallelism decides how many photos the running
|
||||
/// job processes at once). Each item's work runs on the thread pool, at most <c>parallelism</c> at a time, and its result
|
||||
/// is handed to the consumer in the order the items were added, on the caller's flow: whatever the consumer writes (one
|
||||
/// thumbnail pack writer, counters, a checkpoint at a frame index, which then says that every frame before it is done)
|
||||
/// stays sequential and ordered, as in a pass that works on one frame at a time. With a parallelism of one the work runs
|
||||
/// inline. At most twice the parallelism of results wait to be consumed.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Dispose it in every case (<c>await using</c>): after a failure or a cancellation it stops the work still running and
|
||||
/// waits for it, so nothing a pass started outlives it.
|
||||
/// </remarks>
|
||||
internal sealed class OrderedWork<T> : IAsyncDisposable
|
||||
{
|
||||
private readonly Queue<Task<T>> _window = new();
|
||||
private readonly int _parallelism;
|
||||
private readonly Func<T, ValueTask> _consume;
|
||||
private readonly CancellationTokenSource _stop;
|
||||
private readonly SemaphoreSlim _slots;
|
||||
|
||||
public OrderedWork(int parallelism, Func<T, ValueTask> consume, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(parallelism, 1);
|
||||
_parallelism = parallelism;
|
||||
_consume = consume;
|
||||
_stop = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
_slots = new SemaphoreSlim(parallelism, parallelism);
|
||||
}
|
||||
|
||||
/// <summary>Starts <paramref name="work"/>, first consuming earlier results while too many wait.</summary>
|
||||
public async ValueTask AddAsync(Func<CancellationToken, T> work)
|
||||
{
|
||||
var token = _stop.Token;
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (_parallelism == 1)
|
||||
{
|
||||
await _consume(work(token)).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
while (_window.Count >= 2 * _parallelism) await ConsumeNextAsync().ConfigureAwait(false);
|
||||
_window.Enqueue(RunAsync(work, token));
|
||||
await ConsumeFinishedAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>A result known without work, consumed in its turn.</summary>
|
||||
public async ValueTask AddAsync(T ready)
|
||||
{
|
||||
_stop.Token.ThrowIfCancellationRequested();
|
||||
if (_window.Count == 0)
|
||||
{
|
||||
await _consume(ready).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
_window.Enqueue(Task.FromResult(ready));
|
||||
await ConsumeFinishedAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Waits for the work still running and consumes every result in order.</summary>
|
||||
public async ValueTask CompleteAsync()
|
||||
{
|
||||
while (_window.Count > 0) await ConsumeNextAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_window.Count > 0)
|
||||
{
|
||||
await _stop.CancelAsync().ConfigureAwait(false);
|
||||
foreach (var task in _window)
|
||||
{
|
||||
try
|
||||
{
|
||||
await task.ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// The pass already fails or stops with its own exception; the abandoned work's says nothing more.
|
||||
}
|
||||
}
|
||||
_window.Clear();
|
||||
}
|
||||
_stop.Dispose();
|
||||
_slots.Dispose();
|
||||
}
|
||||
|
||||
private async Task<T> RunAsync(Func<CancellationToken, T> work, CancellationToken token)
|
||||
{
|
||||
await _slots.WaitAsync(token).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
return await Task.Run(() => work(token), token).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_slots.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async ValueTask ConsumeNextAsync()
|
||||
{
|
||||
var result = await _window.Peek().ConfigureAwait(false);
|
||||
_ = _window.Dequeue();
|
||||
await _consume(result).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async ValueTask ConsumeFinishedAsync()
|
||||
{
|
||||
while (_window.TryPeek(out var next) && next.IsCompleted) await ConsumeNextAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -91,7 +91,7 @@ internal static class ProjectPositions
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(sequence.ProjectPath) && !SameJson(File.ReadAllText(sequence.ProjectPath), before)) return;
|
||||
if (File.Exists(sequence.ProjectPath) && !SameJson(AtomicFile.ReadAllText(sequence.ProjectPath), before)) return;
|
||||
Directory.CreateDirectory(sequence.MetaDirectory);
|
||||
AtomicFile.WriteAllText(sequence.ProjectPath, moved);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Text.Json;
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.IO;
|
||||
using Titano.Core.Model;
|
||||
|
||||
namespace Titano.Data.Archiving;
|
||||
@@ -96,7 +97,7 @@ internal static class SequenceMapping
|
||||
private static string? ReadProject(SequencePaths sequence)
|
||||
{
|
||||
if (!File.Exists(sequence.ProjectPath)) return null;
|
||||
var text = File.ReadAllText(sequence.ProjectPath);
|
||||
var text = AtomicFile.ReadAllText(sequence.ProjectPath);
|
||||
try
|
||||
{
|
||||
using (JsonDocument.Parse(text)) return text;
|
||||
|
||||
@@ -24,6 +24,25 @@ public sealed record ArchiveServiceOptions
|
||||
/// asked.
|
||||
/// </summary>
|
||||
public bool ImagesAfterScan { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Photos a pass works on at once, asked at the start of each sequence (owner review 1, R2: one job runs at a time and
|
||||
/// the host's parallelism decides how many photos it processes at once; Settings › Rendering › Parallelism on the
|
||||
/// desktop, <c>TITANO_PARALLELISM</c> on the server). Default: half the logical cores.
|
||||
/// </summary>
|
||||
public Func<int> Parallelism { get; init; } = () => DefaultParallelism;
|
||||
|
||||
/// <summary>
|
||||
/// Memory the photos a proxy pass decodes at once may take, in bytes, asked with <see cref="Parallelism"/>: fewer at once
|
||||
/// for large originals. Default: a quarter of the memory available, at least 1 GiB.
|
||||
/// </summary>
|
||||
public Func<long> MemoryBudget { get; init; } = () => DefaultMemoryBudget;
|
||||
|
||||
/// <summary>Half the logical cores, at least one: the parallelism when the host sets none.</summary>
|
||||
public static int DefaultParallelism => Math.Max(1, Environment.ProcessorCount / 2);
|
||||
|
||||
/// <summary>A quarter of the memory available to this process, at least 1 GiB.</summary>
|
||||
public static long DefaultMemoryBudget => Math.Max(1L << 30, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / 4);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+243
-142
@@ -1,14 +1,18 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Threading.Channels;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
|
||||
namespace Titano.Data.Jobs;
|
||||
|
||||
public sealed record JobEngineOptions
|
||||
{
|
||||
/// <summary>Concurrent workers (BRIEF §14.6: default cores / 2).</summary>
|
||||
public int Workers { get; init; } = Math.Max(1, Environment.ProcessorCount / 2);
|
||||
/// <summary>
|
||||
/// Jobs run at once: one (owner review 1, R2). Jobs run one at a time and the host's parallelism decides how many
|
||||
/// photos the running job processes at once; tests run more workers to exercise concurrent claims.
|
||||
/// </summary>
|
||||
public int Workers { get; init; } = 1;
|
||||
|
||||
/// <summary>Identity stamped on claimed jobs (node id); also used for crash recovery.</summary>
|
||||
public string WorkerId { get; init; } = Environment.MachineName;
|
||||
@@ -18,7 +22,7 @@ public sealed record JobEngineOptions
|
||||
|
||||
public TimeSpan CheckpointInterval { get; init; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>Fallback poll for jobs enqueued by other processes.</summary>
|
||||
/// <summary>Fallback poll for jobs enqueued by other processes; also how often the priority queue is reviewed.</summary>
|
||||
public TimeSpan PollInterval { get; init; } = TimeSpan.FromSeconds(3);
|
||||
|
||||
/// <summary>Finished jobs older than this are purged (BRIEF §14.6: 90 days).</summary>
|
||||
@@ -26,20 +30,28 @@ public sealed record JobEngineOptions
|
||||
|
||||
/// <summary>Clock of the throughput windows and the checkpoint interval (tests pass their own).</summary>
|
||||
public TimeProvider Time { get; init; } = TimeProvider.System;
|
||||
|
||||
/// <summary>The priority queue as the settings have it now, asked at every claim and review; null: off (<see cref="JobPriorityQueue"/>).</summary>
|
||||
public Func<JobPriorityQueue>? PriorityQueue { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persistent job queue runner (BRIEF §14.6): N workers claim queued jobs from the database by priority, run the
|
||||
/// registered handler, checkpoint progress, and survive crashes (running jobs are requeued at start with their
|
||||
/// checkpoints). Used by the desktop client (local mode) and the server. Jobs an <see cref="ISelectiveJobHandler"/>
|
||||
/// declines stay queued for other claimers. The number of workers can change while the engine runs
|
||||
/// (<see cref="SetWorkers"/>, Settings › Rendering › Parallelism on the desktop).
|
||||
/// Persistent job queue runner (BRIEF §14.6, amended by owner review 1): one worker claims queued jobs from the database
|
||||
/// in claim order, runs the registered handler, checkpoints progress, and survives crashes (running jobs are requeued at
|
||||
/// start with their checkpoints). Used by the desktop client (local mode) and the server. Jobs an
|
||||
/// <see cref="ISelectiveJobHandler"/> declines stay queued for other claimers. With the priority queue on
|
||||
/// (<see cref="JobEngineOptions.PriorityQueue"/>) a queued job of a higher level makes the running job of a lower level
|
||||
/// yield: it goes back to the queue with its checkpoint and resumes by itself afterwards, never interrupted by the
|
||||
/// follow-ups it queued itself.
|
||||
/// </summary>
|
||||
public sealed class JobEngine : IAsyncDisposable
|
||||
{
|
||||
/// <summary>Queued jobs of selective kinds examined per claim; jobs declined beyond it wait until those ahead leave the queue.</summary>
|
||||
private const int SelectiveWindow = 100;
|
||||
|
||||
/// <summary>Queued jobs a review looks through for one that is not a follow-up of the running job.</summary>
|
||||
private const int ReviewWindow = 50;
|
||||
|
||||
/// <summary>Claims lost to other workers before a worker waits for the next poll.</summary>
|
||||
private const int MaxClaimRaces = 16;
|
||||
|
||||
@@ -48,34 +60,22 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
private IReadOnlyCollection<JobKind> _kinds = [];
|
||||
private Dictionary<JobKind, ISelectiveJobHandler> _selective = [];
|
||||
private IReadOnlyCollection<JobKind> _others = [];
|
||||
private readonly ConcurrentDictionary<Guid, CancellationTokenSource> _running = new();
|
||||
private readonly ConcurrentDictionary<Guid, RunningJob> _running = new();
|
||||
private readonly Channel<bool> _wake = Channel.CreateBounded<bool>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
|
||||
private readonly Channel<bool> _review = Channel.CreateBounded<bool>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
|
||||
private readonly CancellationTokenSource _shutdown = new();
|
||||
private readonly List<Task> _workers = [];
|
||||
private readonly Lock _workerGate = new();
|
||||
private readonly HashSet<int> _activeWorkers = [];
|
||||
private int _workerTarget;
|
||||
private bool _workersStarted;
|
||||
private readonly List<Task> _loops = [];
|
||||
private readonly Lock _gate = new();
|
||||
|
||||
public JobEngine(TitanoDatabase db, IEnumerable<IJobHandler> handlers, JobEngineOptions? options = null)
|
||||
{
|
||||
_db = db;
|
||||
Options = options ?? new JobEngineOptions();
|
||||
_handlers = handlers.ToDictionary(h => h.Kind);
|
||||
_workerTarget = Options.Workers;
|
||||
}
|
||||
|
||||
public JobEngineOptions Options { get; }
|
||||
|
||||
/// <summary>Workers that claim jobs: <see cref="JobEngineOptions.Workers"/> until <see cref="SetWorkers"/> changes it.</summary>
|
||||
public int Workers
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_workerGate) return _workerTarget;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A job changed state (queued, running, done, failed, cancelled, paused).</summary>
|
||||
public event Action<Job>? JobChanged;
|
||||
|
||||
@@ -84,7 +84,10 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
|
||||
public IReadOnlyCollection<Guid> RunningJobIds => [.. _running.Keys];
|
||||
|
||||
/// <summary>Requeues this worker's interrupted jobs, purges old history and starts the workers.</summary>
|
||||
/// <summary>The priority queue as it is now (<see cref="JobEngineOptions.PriorityQueue"/>).</summary>
|
||||
public JobPriorityQueue PriorityQueue => Options.PriorityQueue?.Invoke() ?? JobPriorityQueue.Off;
|
||||
|
||||
/// <summary>Requeues this worker's interrupted jobs, purges old history and starts the worker and the queue's review.</summary>
|
||||
public async Task StartAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var requeued = await _db.Jobs.RequeueRunningAsync(Options.WorkerId, cancellationToken).ConfigureAwait(false);
|
||||
@@ -99,59 +102,28 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
Log.Info("jobs", "No job handlers; this engine claims nothing");
|
||||
return;
|
||||
}
|
||||
lock (_workerGate)
|
||||
var shutdown = _shutdown.Token;
|
||||
lock (_gate)
|
||||
{
|
||||
_workersStarted = true;
|
||||
for (var i = 0; i < _workerTarget; i++) StartWorker(i);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Changes the number of workers. More start claiming at once; the surplus ones finish the job they are running
|
||||
/// (never interrupted) and then stop. Before <see cref="StartAsync"/> it only sets how many start.
|
||||
/// </summary>
|
||||
public void SetWorkers(int count)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(count, 1);
|
||||
lock (_workerGate)
|
||||
{
|
||||
if (_workerTarget == count) return;
|
||||
_workerTarget = count;
|
||||
if (_workersStarted)
|
||||
for (var i = 0; i < Options.Workers; i++)
|
||||
{
|
||||
for (var i = 0; i < count; i++) StartWorker(i);
|
||||
// A single worker keeps the plain id; numbered ones get "#n" (crash recovery requeues both).
|
||||
var id = Options.Workers == 1 ? Options.WorkerId : $"{Options.WorkerId}#{i}";
|
||||
_loops.Add(Task.Run(() => WorkerLoopAsync(id, shutdown), CancellationToken.None));
|
||||
}
|
||||
_loops.Add(Task.Run(() => SuperviseAsync(shutdown), CancellationToken.None));
|
||||
}
|
||||
Log.Info("jobs", $"Job engine set to {count} worker(s)");
|
||||
Wake();
|
||||
}
|
||||
|
||||
/// <summary>Queues a job and wakes a worker.</summary>
|
||||
public async Task<Job> EnqueueAsync(JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel = null, string? parametersJson = null,
|
||||
JobPriority priority = JobPriority.Normal, Guid? createdBy = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var job = new Job
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = kind,
|
||||
TargetIds = targets,
|
||||
TargetLabel = targetLabel,
|
||||
ParametersJson = parametersJson,
|
||||
Priority = priority,
|
||||
State = JobState.Queued,
|
||||
CreatedBy = createdBy,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
};
|
||||
await _db.Jobs.EnqueueAsync(job, cancellationToken).ConfigureAwait(false);
|
||||
JobChanged?.Invoke(job);
|
||||
Wake();
|
||||
return job;
|
||||
}
|
||||
public Task<Job> EnqueueAsync(JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel = null, string? parametersJson = null,
|
||||
JobPriority priority = JobPriority.Normal, Guid? createdBy = null, CancellationToken cancellationToken = default) =>
|
||||
EnqueueAsync(Guid.CreateVersion7(), kind, targets, targetLabel, parametersJson, priority, createdBy, cancellationToken);
|
||||
|
||||
/// <summary>Cancels a queued or running job; a running handler observes its token.</summary>
|
||||
public Task CancelAsync(Guid id, CancellationToken cancellationToken = default) => TransitionAsync(id, JobState.Cancelled, cancellationToken);
|
||||
|
||||
/// <summary>Pauses a job: a running one stops at its next check and keeps its checkpoint.</summary>
|
||||
/// <summary>Pauses a job: a running one stops at its next check and keeps its checkpoint, and the next queued job starts.</summary>
|
||||
public Task PauseAsync(Guid id, CancellationToken cancellationToken = default) => TransitionAsync(id, JobState.Paused, cancellationToken);
|
||||
|
||||
/// <summary>Resumes a paused job or retries a failed/cancelled one from its last checkpoint.</summary>
|
||||
@@ -162,22 +134,24 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
Wake();
|
||||
}
|
||||
|
||||
/// <summary>Signals workers that new work may be available (also call on PostgreSQL NOTIFY).</summary>
|
||||
public void Wake() => _wake.Writer.TryWrite(true);
|
||||
/// <summary>
|
||||
/// Signals that the queue may have changed (also call on PostgreSQL NOTIFY, and after the priority queue's settings
|
||||
/// changed): an idle worker looks for work, and the priority queue is reviewed at once.
|
||||
/// </summary>
|
||||
public void Wake()
|
||||
{
|
||||
_wake.Writer.TryWrite(true);
|
||||
_review.Writer.TryWrite(true);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
Task[] workers;
|
||||
lock (_workerGate)
|
||||
{
|
||||
// No worker starts any more: the shutdown token is about to be disposed.
|
||||
_workersStarted = false;
|
||||
workers = [.. _workers];
|
||||
}
|
||||
Task[] loops;
|
||||
lock (_gate) loops = [.. _loops];
|
||||
await _shutdown.CancelAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(workers).ConfigureAwait(false);
|
||||
await Task.WhenAll(loops).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
@@ -226,9 +200,66 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
/// <summary>True when this engine claims jobs of <paramref name="kind"/> (it has a handler and the kind is not filtered out).</summary>
|
||||
internal bool Runs(JobKind kind) => _kinds.Contains(kind);
|
||||
|
||||
/// <summary>
|
||||
/// Queues follow-up work of the running job <paramref name="parent"/> (<see cref="JobContext.EnqueueFollowUpAsync"/>):
|
||||
/// it works on what the parent produces, so it never interrupts it, whatever its level. Null when this engine has no
|
||||
/// handler for <paramref name="kind"/>.
|
||||
/// </summary>
|
||||
internal async Task<Job?> EnqueueFollowUpAsync(Guid parent, JobKind kind, IReadOnlyList<Guid> targets, string? label, string? parametersJson,
|
||||
JobPriority priority, Guid? createdBy, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!Runs(kind)) return null;
|
||||
var id = Guid.CreateVersion7();
|
||||
// Known before the job is queued, so the review its queueing starts already leaves the parent running.
|
||||
if (_running.TryGetValue(parent, out var run)) run.FollowUps.TryAdd(id, 0);
|
||||
return await EnqueueAsync(id, kind, targets, label, parametersJson, priority, createdBy, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal void StopJob(Guid id)
|
||||
{
|
||||
if (_running.TryGetValue(id, out var cts)) cts.Cancel();
|
||||
if (_running.TryGetValue(id, out var run)) run.Stop();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes the running job yield when the priority queue is on and a queued job of a higher level waits that this engine
|
||||
/// would claim (not a follow-up of that running job): the running job of the lowest level stops, goes back to the
|
||||
/// queue with its checkpoint and resumes after the higher ones. A free worker would claim the waiting job anyway, so
|
||||
/// only a full engine interrupts one. True when a job was asked to yield.
|
||||
/// </summary>
|
||||
internal async Task<bool> ReviewAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var queue = PriorityQueue;
|
||||
if (!queue.Enabled) return false;
|
||||
var running = _running.Values.Where(r => !r.Yielding).ToList();
|
||||
if (running.Count == 0 || running.Count < Options.Workers) return false;
|
||||
var lowest = running.MinBy(r => queue.LevelOf(r.Job.Kind))!;
|
||||
if (queue.LevelOf(lowest.Job.Kind) == JobKindPriority.High) return false;
|
||||
var next = await PeekAsync(queue, lowest, cancellationToken).ConfigureAwait(false);
|
||||
if (next is null || !queue.Interrupts(next.Kind, lowest.Job.Kind)) return false;
|
||||
if (!lowest.Yield(next)) return false;
|
||||
Log.Info("jobs", $"{lowest.Job.Kind} job {lowest.Job.Id} yields to {next.Kind} job {next.Id} (priority queue)");
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task<Job> EnqueueAsync(Guid id, JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel, string? parametersJson,
|
||||
JobPriority priority, Guid? createdBy, CancellationToken cancellationToken)
|
||||
{
|
||||
var job = new Job
|
||||
{
|
||||
Id = id,
|
||||
Kind = kind,
|
||||
TargetIds = targets,
|
||||
TargetLabel = targetLabel,
|
||||
ParametersJson = parametersJson,
|
||||
Priority = priority,
|
||||
State = JobState.Queued,
|
||||
CreatedBy = createdBy,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
};
|
||||
await _db.Jobs.EnqueueAsync(job, cancellationToken).ConfigureAwait(false);
|
||||
JobChanged?.Invoke(job);
|
||||
Wake();
|
||||
return job;
|
||||
}
|
||||
|
||||
private async Task TransitionAsync(Guid id, JobState state, CancellationToken cancellationToken)
|
||||
@@ -243,34 +274,11 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
if (await _db.Jobs.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } job) JobChanged?.Invoke(job);
|
||||
}
|
||||
|
||||
/// <summary>Starts worker <paramref name="index"/> unless it runs already; call under <see cref="_workerGate"/>.</summary>
|
||||
private void StartWorker(int index)
|
||||
{
|
||||
if (!_activeWorkers.Add(index)) return;
|
||||
// A single worker keeps the plain id (as before workers could be added); numbered ones get "#n".
|
||||
var id = index == 0 && Options.Workers == 1 ? Options.WorkerId : $"{Options.WorkerId}#{index}";
|
||||
var shutdown = _shutdown.Token;
|
||||
_workers.Add(Task.Run(() => WorkerLoopAsync(index, id, shutdown), CancellationToken.None));
|
||||
}
|
||||
|
||||
/// <summary>True when worker <paramref name="index"/> is beyond the wanted count; it is then no longer active.</summary>
|
||||
private bool Retires(int index)
|
||||
{
|
||||
lock (_workerGate)
|
||||
{
|
||||
if (index < _workerTarget) return false;
|
||||
_activeWorkers.Remove(index);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Claims and runs jobs until shutdown, or until <see cref="SetWorkers"/> no longer wants this worker.
|
||||
/// Nothing a job or a handler throws ends the worker.</summary>
|
||||
private async Task WorkerLoopAsync(int index, string workerId, CancellationToken shutdown)
|
||||
/// <summary>Claims and runs jobs until shutdown. Nothing a job or a handler throws ends the worker.</summary>
|
||||
private async Task WorkerLoopAsync(string workerId, CancellationToken shutdown)
|
||||
{
|
||||
while (!shutdown.IsCancellationRequested)
|
||||
{
|
||||
if (Retires(index)) return;
|
||||
Job? job;
|
||||
try
|
||||
{
|
||||
@@ -288,22 +296,13 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
|
||||
if (job is null)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(shutdown);
|
||||
timeout.CancelAfter(Options.PollInterval);
|
||||
try
|
||||
{
|
||||
await _wake.Reader.ReadAsync(timeout.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Poll interval elapsed or shutdown.
|
||||
}
|
||||
await WaitAsync(_wake, shutdown).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await RunAsync(job, shutdown).ConfigureAwait(false);
|
||||
await RunAsync(job, workerId, shutdown).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -315,28 +314,64 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The next job in claim order (priority, then age). Without selective handlers the database picks it atomically.
|
||||
/// With them, the first job a selective handler accepts among the first <see cref="SelectiveWindow"/> of its kinds
|
||||
/// competes with the head of the other kinds: the other kinds are still claimed atomically, the selective job by id.
|
||||
/// A lost race means another worker took a job, so looking again at once makes progress.
|
||||
/// Reviews the priority queue (<see cref="ReviewAsync"/>) whenever the queue may have changed (<see cref="Wake"/>) and
|
||||
/// at every poll, which also covers jobs queued by other processes. Nothing a review throws ends it.
|
||||
/// </summary>
|
||||
private async Task SuperviseAsync(CancellationToken shutdown)
|
||||
{
|
||||
while (!shutdown.IsCancellationRequested)
|
||||
{
|
||||
await WaitAsync(_review, shutdown).ConfigureAwait(false);
|
||||
if (shutdown.IsCancellationRequested) return;
|
||||
try
|
||||
{
|
||||
await ReviewAsync(shutdown).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (shutdown.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning("jobs", "The priority queue could not be reviewed", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Waits for a signal on <paramref name="channel"/>, the poll interval or shutdown, whichever comes first.</summary>
|
||||
private async Task WaitAsync(Channel<bool> channel, CancellationToken shutdown)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(shutdown);
|
||||
timeout.CancelAfter(Options.PollInterval);
|
||||
try
|
||||
{
|
||||
await channel.Reader.ReadAsync(timeout.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Poll interval elapsed or shutdown.
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The next job in claim order (<see cref="JobPriorityQueue.ClaimsBefore"/>). Without selective handlers the database
|
||||
/// picks it atomically. With them, the first job a selective handler accepts among the first
|
||||
/// <see cref="SelectiveWindow"/> of its kinds competes with the head of the other kinds: the other kinds are still
|
||||
/// claimed atomically, the selective job by id. A lost race means another worker took a job, so looking again at once
|
||||
/// makes progress.
|
||||
/// </summary>
|
||||
private async Task<Job?> ClaimAsync(string workerId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_selective.Count == 0) return await _db.Jobs.ClaimNextAsync(workerId, _kinds, cancellationToken).ConfigureAwait(false);
|
||||
var queue = PriorityQueue;
|
||||
if (_selective.Count == 0) return await _db.Jobs.ClaimNextAsync(workerId, _kinds, queue, cancellationToken).ConfigureAwait(false);
|
||||
for (var attempt = 0; attempt < MaxClaimRaces; attempt++)
|
||||
{
|
||||
Job? candidate = null;
|
||||
foreach (var queued in await _db.Jobs.ListQueuedAsync(_selective.Keys, SelectiveWindow, cancellationToken).ConfigureAwait(false))
|
||||
var candidate = await AcceptedAsync(queue, null, cancellationToken).ConfigureAwait(false);
|
||||
if (candidate is null) return _others.Count > 0 ? await _db.Jobs.ClaimNextAsync(workerId, _others, queue, cancellationToken).ConfigureAwait(false) : null;
|
||||
if (_others.Count > 0 && (await _db.Jobs.ListQueuedAsync(_others, 1, queue, cancellationToken).ConfigureAwait(false)).FirstOrDefault() is { } head
|
||||
&& queue.ClaimsBefore(head, candidate))
|
||||
{
|
||||
if (!await AcceptsAsync(queued, cancellationToken).ConfigureAwait(false)) continue;
|
||||
candidate = queued;
|
||||
break;
|
||||
}
|
||||
if (candidate is null) return _others.Count > 0 ? await _db.Jobs.ClaimNextAsync(workerId, _others, cancellationToken).ConfigureAwait(false) : null;
|
||||
if (_others.Count > 0 && (await _db.Jobs.ListQueuedAsync(_others, 1, cancellationToken).ConfigureAwait(false)).FirstOrDefault() is { } head
|
||||
&& ClaimsBefore(head, candidate))
|
||||
{
|
||||
if (await _db.Jobs.ClaimNextAsync(workerId, _others, cancellationToken).ConfigureAwait(false) is { } next) return next;
|
||||
if (await _db.Jobs.ClaimNextAsync(workerId, _others, queue, cancellationToken).ConfigureAwait(false) is { } next) return next;
|
||||
}
|
||||
else if (await _db.Jobs.TryClaimAsync(candidate.Id, workerId, cancellationToken).ConfigureAwait(false) is { } claimed)
|
||||
{
|
||||
@@ -346,6 +381,34 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The job a free worker would claim now (<see cref="ClaimAsync"/>) leaving out the follow-ups of <paramref name="running"/>, without claiming it.</summary>
|
||||
private async Task<Job?> PeekAsync(JobPriorityQueue queue, RunningJob running, CancellationToken cancellationToken)
|
||||
{
|
||||
var candidate = _selective.Count > 0 ? await AcceptedAsync(queue, running, cancellationToken).ConfigureAwait(false) : null;
|
||||
Job? head = null;
|
||||
if (_others.Count > 0)
|
||||
{
|
||||
foreach (var queued in await _db.Jobs.ListQueuedAsync(_others, ReviewWindow, queue, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (running.FollowUps.ContainsKey(queued.Id)) continue;
|
||||
head = queued;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return head is null ? candidate : candidate is null || queue.ClaimsBefore(head, candidate) ? head : candidate;
|
||||
}
|
||||
|
||||
/// <summary>The first queued job of the selective kinds whose handler takes it now, leaving out the follow-ups of <paramref name="running"/>.</summary>
|
||||
private async Task<Job?> AcceptedAsync(JobPriorityQueue queue, RunningJob? running, CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var queued in await _db.Jobs.ListQueuedAsync(_selective.Keys, SelectiveWindow, queue, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (running?.FollowUps.ContainsKey(queued.Id) == true || !await AcceptsAsync(queued, cancellationToken).ConfigureAwait(false)) continue;
|
||||
return queued;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>A job its handler cannot judge is taken, so it fails here with its reason instead of blocking the queue.</summary>
|
||||
private async ValueTask<bool> AcceptsAsync(Job job, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -360,14 +423,14 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
private static bool ClaimsBefore(Job a, Job b) =>
|
||||
a.Priority != b.Priority ? a.Priority > b.Priority : a.Created != b.Created ? a.Created < b.Created : a.Id.CompareTo(b.Id) < 0;
|
||||
|
||||
private async Task RunAsync(Job job, CancellationToken shutdown)
|
||||
private async Task RunAsync(Job job, string workerId, CancellationToken shutdown)
|
||||
{
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(shutdown);
|
||||
_running[job.Id] = cts;
|
||||
var run = new RunningJob(job, cts);
|
||||
_running[job.Id] = run;
|
||||
JobChanged?.Invoke(job);
|
||||
// A job queued while this one was being claimed may outrank it.
|
||||
_review.Writer.TryWrite(true);
|
||||
var context = new JobContext(this, job, cts.Token);
|
||||
JobState final;
|
||||
string? error = null;
|
||||
@@ -381,15 +444,17 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
}
|
||||
catch (OperationCanceledException) when (cts.IsCancellationRequested)
|
||||
{
|
||||
// Read once: the job a yield names is set together with the yield itself.
|
||||
var yieldsTo = shutdown.IsCancellationRequested ? null : run.YieldsTo;
|
||||
var yielded = yieldsTo is not null;
|
||||
if (yieldsTo is not null) context.Log(Loc.L("Jobs.Line.Yielded", Loc.L("Jobs.Kind." + yieldsTo.Kind)));
|
||||
await PersistAsync(context).ConfigureAwait(false);
|
||||
if (shutdown.IsCancellationRequested)
|
||||
{
|
||||
// Engine stopping: leave the job running so the next start requeues it from its checkpoint.
|
||||
_running.TryRemove(job.Id, out _);
|
||||
return;
|
||||
}
|
||||
// Cancel or pause already wrote the state; keep it.
|
||||
_running.TryRemove(job.Id, out _);
|
||||
// Engine stopping: leave the job running so the next start requeues it from its checkpoint.
|
||||
if (shutdown.IsCancellationRequested) return;
|
||||
// Yielded to a higher job: back to the queue with its checkpoint, unless the user paused or cancelled it
|
||||
// meanwhile (their state stays). Otherwise cancel or pause already wrote the state; keep it.
|
||||
if (yielded) await _db.Jobs.RequeueAsync(job.Id, workerId, CancellationToken.None).ConfigureAwait(false);
|
||||
await NotifyAsync(job.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
@@ -408,4 +473,40 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
await _db.Jobs.SetStateAsync(job.Id, final, error, CancellationToken.None).ConfigureAwait(false);
|
||||
await NotifyAsync(job.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>A job a worker runs: how it is stopped, whether it was stopped to yield, and the follow-ups it queued.</summary>
|
||||
private sealed class RunningJob(Job job, CancellationTokenSource cancellation)
|
||||
{
|
||||
private Job? _yieldsTo;
|
||||
|
||||
public Job Job { get; } = job;
|
||||
|
||||
/// <summary>Jobs this one queued as follow-ups (<see cref="EnqueueFollowUpAsync"/>): they never make it yield.</summary>
|
||||
public ConcurrentDictionary<Guid, byte> FollowUps { get; } = new();
|
||||
|
||||
public bool Yielding => YieldsTo is not null;
|
||||
|
||||
/// <summary>The job of a higher level this one yields to; set, atomically, before it is stopped.</summary>
|
||||
public Job? YieldsTo => Volatile.Read(ref _yieldsTo);
|
||||
|
||||
/// <summary>Signals the job's token; a job that ended meanwhile (its source disposed) needs nothing.</summary>
|
||||
public void Stop()
|
||||
{
|
||||
try
|
||||
{
|
||||
cancellation.Cancel();
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stops the job to yield to <paramref name="to"/>; false when it is yielding already.</summary>
|
||||
public bool Yield(Job to)
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _yieldsTo, to, null) is not null) return false;
|
||||
Stop();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,12 +90,11 @@ public sealed class JobContext
|
||||
|
||||
/// <summary>
|
||||
/// Queues follow-up work on this job's engine for the same user (light analysis after an import); null when the
|
||||
/// engine has no handler for <paramref name="kind"/>, since nothing here would run it.
|
||||
/// engine has no handler for <paramref name="kind"/>, since nothing here would run it. A follow-up never makes this job
|
||||
/// yield in the priority queue: it works on what this job produces.
|
||||
/// </summary>
|
||||
public async Task<Job?> EnqueueFollowUpAsync(JobKind kind, IReadOnlyList<Guid> targets, string? label, string? parametersJson, JobPriority priority) =>
|
||||
_engine.Runs(kind)
|
||||
? await _engine.EnqueueAsync(kind, targets, label, parametersJson, priority, Job.CreatedBy, Cancellation).ConfigureAwait(false)
|
||||
: null;
|
||||
public Task<Job?> EnqueueFollowUpAsync(JobKind kind, IReadOnlyList<Guid> targets, string? label, string? parametersJson, JobPriority priority) =>
|
||||
_engine.EnqueueFollowUpAsync(Job.Id, kind, targets, label, parametersJson, priority, Job.CreatedBy, Cancellation);
|
||||
|
||||
/// <summary>Appends a line to the job log (the last lines are kept with the job).</summary>
|
||||
public void Log(string line)
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Titano.Core.Model;
|
||||
|
||||
namespace Titano.Data.Jobs;
|
||||
|
||||
/// <summary>How much a kind of job counts in the priority queue (<see cref="JobPriorityQueue"/>).</summary>
|
||||
public enum JobKindPriority
|
||||
{
|
||||
Low,
|
||||
Normal,
|
||||
High,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The priority queue of Settings (owner review 1, R2). Jobs always run one at a time. Off, they run in claim order
|
||||
/// (priority, then age) and a running job is never interrupted: the user pauses it to let the next one start. On, a kind
|
||||
/// of a higher <see cref="JobKindPriority"/> runs first, and a queued job of a higher level that the engine can run makes
|
||||
/// the running job of a lower level yield without asking: it goes back to the queue with its checkpoint and resumes by
|
||||
/// itself once nothing above it waits. Kinds of the same level never interrupt each other.
|
||||
/// </summary>
|
||||
public sealed record JobPriorityQueue
|
||||
{
|
||||
/// <summary>The levels a kind has unless the user changed it: renders, imports and downloads first; the long passes that resume anywhere last.</summary>
|
||||
public static IReadOnlyDictionary<JobKind, JobKindPriority> DefaultLevels { get; } = new Dictionary<JobKind, JobKindPriority>
|
||||
{
|
||||
[JobKind.Render] = JobKindPriority.High,
|
||||
[JobKind.Import] = JobKindPriority.High,
|
||||
[JobKind.Download] = JobKindPriority.High,
|
||||
[JobKind.Verify] = JobKindPriority.Low,
|
||||
[JobKind.Proxies] = JobKindPriority.Low,
|
||||
};
|
||||
|
||||
/// <summary>The strict queue: no levels, no interruptions.</summary>
|
||||
public static JobPriorityQueue Off { get; } = new();
|
||||
|
||||
/// <summary>Whether levels order the queue and interrupt lower jobs.</summary>
|
||||
public bool Enabled { get; init; }
|
||||
|
||||
/// <summary>Levels the user set; a kind not listed has its <see cref="DefaultLevels"/> level, else normal.</summary>
|
||||
public IReadOnlyDictionary<JobKind, JobKindPriority> Levels { get; init; } = new Dictionary<JobKind, JobKindPriority>();
|
||||
|
||||
/// <summary>The level of <paramref name="kind"/>.</summary>
|
||||
public JobKindPriority LevelOf(JobKind kind) =>
|
||||
Levels.TryGetValue(kind, out var level) || DefaultLevels.TryGetValue(kind, out level) ? level : JobKindPriority.Normal;
|
||||
|
||||
/// <summary>Whether a queued job of <paramref name="challenger"/> interrupts a running job of <paramref name="running"/>.</summary>
|
||||
public bool Interrupts(JobKind challenger, JobKind running) => Enabled && LevelOf(challenger) > LevelOf(running);
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="a"/> is claimed before <paramref name="b"/>: the higher level first while the queue is on,
|
||||
/// then the higher priority, the older job and the lower id (<see cref="Repositories.JobRepository.ClaimNextAsync"/>).
|
||||
/// </summary>
|
||||
public bool ClaimsBefore(Job a, Job b)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(a);
|
||||
ArgumentNullException.ThrowIfNull(b);
|
||||
if (Enabled && LevelOf(a.Kind) != LevelOf(b.Kind)) return LevelOf(a.Kind) > LevelOf(b.Kind);
|
||||
return a.Priority != b.Priority ? a.Priority > b.Priority : a.Created != b.Created ? a.Created < b.Created : a.Id.CompareTo(b.Id) < 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The SQL ordering of the queue (before priority, age and id): the levels of <paramref name="kinds"/>, highest first, as
|
||||
/// a <c>CASE</c> over the kind column; empty while the queue is off or every kind has the same level.
|
||||
/// </summary>
|
||||
internal string OrderSql(IEnumerable<JobKind> kinds)
|
||||
{
|
||||
if (!Enabled) return string.Empty;
|
||||
var levels = kinds.Distinct().GroupBy(LevelOf).Where(g => g.Key != JobKindPriority.Normal).ToList();
|
||||
if (levels.Count == 0) return string.Empty;
|
||||
var sql = new StringBuilder("CASE");
|
||||
foreach (var level in levels)
|
||||
{
|
||||
sql.Append(" WHEN kind IN (").AppendJoin(", ", level.Select(k => ((int)k).ToString(CultureInfo.InvariantCulture))).Append(") THEN ")
|
||||
.Append(((int)level.Key).ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
return sql.Append(" ELSE ").Append(((int)JobKindPriority.Normal).ToString(CultureInfo.InvariantCulture)).Append(" END DESC, ").ToString();
|
||||
}
|
||||
|
||||
/// <summary>Wire name of a level in API v1 and settings files: <c>high</c>, <c>normal</c>, <c>low</c>.</summary>
|
||||
public static string Wire(JobKindPriority level) => level.ToString().ToLowerInvariant();
|
||||
|
||||
/// <summary>The level named <paramref name="text"/> (<see cref="Wire"/>, any case); false for anything else.</summary>
|
||||
public static bool TryParse(string? text, out JobKindPriority level)
|
||||
{
|
||||
foreach (var candidate in Enum.GetValues<JobKindPriority>())
|
||||
{
|
||||
if (!string.Equals(text, Wire(candidate), StringComparison.OrdinalIgnoreCase)) continue;
|
||||
level = candidate;
|
||||
return true;
|
||||
}
|
||||
level = JobKindPriority.Normal;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The queue from settings: <paramref name="levels"/> maps kind names (<see cref="JobWire.Kind"/> or the enum name) to
|
||||
/// level names; unknown kinds and levels are skipped, so a settings file written by a newer build still loads.
|
||||
/// </summary>
|
||||
public static JobPriorityQueue From(bool enabled, IReadOnlyDictionary<string, string>? levels)
|
||||
{
|
||||
var parsed = new Dictionary<JobKind, JobKindPriority>();
|
||||
foreach (var (name, value) in levels ?? new Dictionary<string, string>())
|
||||
{
|
||||
if ((JobWire.TryParseKind(name, out var kind) || Enum.TryParse(name, ignoreCase: true, out kind)) && Enum.IsDefined(kind) && TryParse(value, out var level))
|
||||
parsed[kind] = level;
|
||||
}
|
||||
return new JobPriorityQueue { Enabled = enabled, Levels = parsed };
|
||||
}
|
||||
|
||||
/// <summary>The levels that differ from <see cref="DefaultLevels"/>, by wire kind name: what settings store.</summary>
|
||||
public static Dictionary<string, string> Changed(IReadOnlyDictionary<JobKind, JobKindPriority> levels)
|
||||
{
|
||||
var defaults = new JobPriorityQueue();
|
||||
return levels.Where(l => defaults.LevelOf(l.Key) != l.Value).OrderBy(l => l.Key)
|
||||
.ToDictionary(l => JobWire.Kind(l.Key), l => Wire(l.Value), StringComparer.Ordinal);
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,21 @@ public sealed record ProcessingOptions
|
||||
/// <summary>These options with the host's current tuning (<see cref="Tune"/>).</summary>
|
||||
internal ProcessingOptions Current => Tune?.Invoke(this) ?? this;
|
||||
|
||||
/// <summary>
|
||||
/// These options with <paramref name="parallelism"/> photos processed at once (owner review 1, R2: one job runs at a
|
||||
/// time and the host's parallelism decides how many photos it processes at once): the deep analysis measures that many
|
||||
/// frames together and the render's decode window loads that many ahead, within its memory budget.
|
||||
/// </summary>
|
||||
public ProcessingOptions WithParallelism(int parallelism)
|
||||
{
|
||||
var n = Math.Max(1, parallelism);
|
||||
return this with
|
||||
{
|
||||
DeepAnalysis = DeepAnalysis with { MaxDegreeOfParallelism = n },
|
||||
FrameWindow = FrameWindow with { MaxConcurrentLoads = n, Ahead = Math.Max(FrameWindow.Ahead, n) },
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Tells <see cref="SequenceChanged"/>; a failure is logged, never passed on to the job.</summary>
|
||||
internal async Task NotifyAsync(Guid sequenceId, string change, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -20,7 +20,7 @@ internal sealed class ProjectStore(TitanoDatabase db, SequenceWriter writer)
|
||||
/// <summary>The settings in force: the index copy, else <c>project.json</c>, else defaults.</summary>
|
||||
/// <exception cref="InvalidDataException">The settings are not valid JSON or come from a newer Titano.</exception>
|
||||
public static ProjectSettings Read(Sequence sequence, SequencePaths folder) =>
|
||||
Parse(sequence.SettingsJson ?? (File.Exists(folder.ProjectPath) ? File.ReadAllText(folder.ProjectPath) : null));
|
||||
Parse(sequence.SettingsJson ?? (File.Exists(folder.ProjectPath) ? AtomicFile.ReadAllText(folder.ProjectPath) : null));
|
||||
|
||||
/// <exception cref="InvalidDataException">The settings are not valid JSON or come from a newer Titano.</exception>
|
||||
public static ProjectSettings Parse(string? json)
|
||||
|
||||
@@ -286,6 +286,7 @@ internal sealed class SequenceAnalyser(TitanoDatabase db, ProcessingOptions opti
|
||||
// The host's analysis parameters as they are now (Settings › Analysis on the desktop). Those that change per-frame
|
||||
// results are part of the checkpoint's fingerprint, so a partial run made with other values starts again.
|
||||
var analysis = options.Current.DeepAnalysis;
|
||||
analysis = analysis with { MaxDegreeOfParallelism = AnalysisParallelism(analysis, frames, options.Archive.MemoryBudget()) };
|
||||
var companions = await GprCompanions.FindAsync(db, archive, frames.Frames, cancellationToken).ConfigureAwait(false);
|
||||
DeepAnalysisReport report;
|
||||
Dictionary<Guid, FileTier> decoded;
|
||||
@@ -308,6 +309,22 @@ internal sealed class SequenceAnalyser(TitanoDatabase db, ProcessingOptions opti
|
||||
return (report, decoded);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Frames a deep analysis measures at once (owner review 1): its parallelism, fewer when some frame is developed whole
|
||||
/// at its analysis size and <paramref name="memoryBudget"/> cannot hold that many (<see cref="SequenceFrames.DevelopedPixels"/>).
|
||||
/// A sequence of JPEGs, proxies or RAWs with large enough embedded previews keeps the whole parallelism.
|
||||
/// </summary>
|
||||
internal static int AnalysisParallelism(DeepAnalysisOptions analysis, SequenceFrames frames, long memoryBudget)
|
||||
{
|
||||
long largest = 0;
|
||||
for (var i = 0; i < frames.Count; i++)
|
||||
{
|
||||
var frame = frames.Frames[i];
|
||||
largest = Math.Max(largest, frames.DevelopedPixels(i, analysis.AnalysisLongEdge(Math.Max(frame.Width, frame.Height)), preferPreview: true));
|
||||
}
|
||||
return largest == 0 ? analysis.MaxDegreeOfParallelism : DecodeBudget.PhotosAtOnce(analysis.MaxDegreeOfParallelism, memoryBudget, largest);
|
||||
}
|
||||
|
||||
/// <summary>Identity of the analysed content: frames replaced or renumbered since a checkpoint was written (with the
|
||||
/// same count), or now read from their proxies where they were read from their originals (or the other way round),
|
||||
/// make it stale, like changed options do. Only frames read from proxies are marked, so the key of a sequence read
|
||||
|
||||
@@ -105,7 +105,12 @@ internal sealed class SequenceFrameSource : IFrameSource, IRenderFrameSource, IA
|
||||
{
|
||||
if (_window is not null) await _window.DisposeAsync().ConfigureAwait(false);
|
||||
_windowKey = (maxLongEdge, purpose);
|
||||
_window = new FrameWindow(Count, (i, ct) => ValueTask.FromResult(Load(i, maxLongEdge, purpose, ct)), _windowOptions);
|
||||
// The window caps only its read-ahead; a demand load runs beside it, so a window that develops originals takes
|
||||
// one gate for every decode, read-ahead and demand alike (owner review 1).
|
||||
var limit = DevelopingLimit(maxLongEdge, purpose);
|
||||
var decodes = limit is { } n ? new SemaphoreSlim(n, n) : null;
|
||||
_window = new FrameWindow(Count, (i, ct) => LoadAsync(i, maxLongEdge, purpose, decodes, ct),
|
||||
limit is { } loads ? _windowOptions with { MaxConcurrentLoads = loads } : _windowOptions);
|
||||
}
|
||||
_window.MoveTo(index);
|
||||
return await ReadAsync(_window, index, cancellationToken).ConfigureAwait(false)
|
||||
@@ -131,6 +136,21 @@ internal sealed class SequenceFrameSource : IFrameSource, IRenderFrameSource, IA
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary><see cref="Load"/> within <paramref name="decodes"/>, the gate of a window that develops originals (null: none).</summary>
|
||||
private async ValueTask<ImageBuffer> LoadAsync(int index, int maxLongEdge, DecodePurpose purpose, SemaphoreSlim? decodes, CancellationToken cancellationToken)
|
||||
{
|
||||
if (decodes is null) return Load(index, maxLongEdge, purpose, cancellationToken);
|
||||
await decodes.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
return Load(index, maxLongEdge, purpose, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
decodes.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The window's loader, for the pipeline's reads and the read-ahead alike: the decoded frame, else
|
||||
/// <see cref="NotDecodedException"/>, remembered so the read-ahead does not decode the file again.
|
||||
@@ -142,6 +162,23 @@ internal sealed class SequenceFrameSource : IFrameSource, IRenderFrameSource, IA
|
||||
throw new NotDecodedException();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decodes a window at <paramref name="edge"/> for <paramref name="purpose"/> may run at once when some of them develop
|
||||
/// an original whole (<see cref="SequenceFrames.DevelopedPixels"/>: a render's TIFFs, PNGs and RAWs, or a preparation's
|
||||
/// frames without a large enough RAW preview), which takes room beyond the decoded frame the window counts (owner
|
||||
/// review 1); null when none does (scaled JPEGs, proxies, embedded previews), and the window runs as it is set.
|
||||
/// </summary>
|
||||
internal int? DevelopingLimit(int edge, DecodePurpose purpose)
|
||||
{
|
||||
long largest = 0;
|
||||
for (var i = 0; i < _frames.Count; i++) largest = Math.Max(largest, _frames.DevelopedPixels(i, edge, preferPreview: purpose != DecodePurpose.Render));
|
||||
return largest == 0 ? null : Archiving.DecodeBudget.PhotosAtOnce(_windowOptions.MaxConcurrentLoads, _windowOptions.MemoryBudget, largest);
|
||||
}
|
||||
|
||||
/// <summary>The options of a window at <paramref name="edge"/> for <paramref name="purpose"/>: its read-ahead within <see cref="DevelopingLimit"/>.</summary>
|
||||
internal FrameWindowOptions WindowOptions(int edge, DecodePurpose purpose) =>
|
||||
DevelopingLimit(edge, purpose) is { } limit ? _windowOptions with { MaxConcurrentLoads = limit } : _windowOptions;
|
||||
|
||||
/// <summary>A copy of the window's frame, or null when it does not decode.</summary>
|
||||
private static async ValueTask<ImageBuffer?> ReadAsync(FrameWindow window, int index, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -14,6 +14,21 @@ namespace Titano.Data.Processing;
|
||||
/// </summary>
|
||||
internal sealed record SequenceFrames(Sequence Sequence, IReadOnlyList<Frame> Frames, IReadOnlyList<string?> Files)
|
||||
{
|
||||
/// <summary>
|
||||
/// The pixels of frame <paramref name="index"/>'s original that a decode at <paramref name="edge"/> develops whole
|
||||
/// (<see cref="DecodeBudget.Developed"/>), 0 when it takes a cheap path or the frame has no file. A frame read through
|
||||
/// its proxy, or from a JPEG file (an archive proxy, a proxy cache's copy), decodes as a JPEG (owner review 1).
|
||||
/// </summary>
|
||||
internal long DevelopedPixels(int index, int edge, bool preferPreview)
|
||||
{
|
||||
if (Files[index] is not { } file) return 0;
|
||||
var frame = Frames[index];
|
||||
var jpeg = Proxied?[index] == true || Path.GetExtension(file) is var extension
|
||||
&& (extension.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || extension.Equals(".jpeg", StringComparison.OrdinalIgnoreCase));
|
||||
return DecodeBudget.Developed(jpeg ? ImageFileFormat.Jpeg : frame.Format, frame.Width, frame.Height, Math.Max(frame.PreviewWidth, frame.PreviewHeight),
|
||||
edge, preferPreview);
|
||||
}
|
||||
|
||||
/// <summary>Flags of frames that never reach a render.</summary>
|
||||
public const FrameFlags NotRendered = FrameFlags.Missing | FrameFlags.Corrupt | FrameFlags.Excluded | FrameFlags.Undecodable;
|
||||
|
||||
|
||||
@@ -38,10 +38,19 @@ public sealed class JobRepository
|
||||
/// <paramref name="workerId"/> and returns it, or null when none waits. Concurrent claimers never get the same
|
||||
/// job: PostgreSQL skips rows locked by other claimers, SQLite holds its write lock across select and update.
|
||||
/// </summary>
|
||||
public Task<Job?> ClaimNextAsync(string workerId, IReadOnlyCollection<JobKind>? kinds = null, CancellationToken cancellationToken = default)
|
||||
public Task<Job?> ClaimNextAsync(string workerId, IReadOnlyCollection<JobKind>? kinds = null, CancellationToken cancellationToken = default) =>
|
||||
ClaimNextAsync(workerId, kinds, JobPriorityQueue.Off, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="ClaimNextAsync(string, IReadOnlyCollection{JobKind}?, CancellationToken)"/> in the order of
|
||||
/// <paramref name="queue"/>: while it is on, the kinds of the highest level first (<see cref="JobPriorityQueue.ClaimsBefore"/>).
|
||||
/// </summary>
|
||||
public Task<Job?> ClaimNextAsync(string workerId, IReadOnlyCollection<JobKind>? kinds, JobPriorityQueue queue, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(queue);
|
||||
var kindFilter = kinds is { Count: > 0 } ? $" AND kind IN ({KindList(kinds)})" : string.Empty;
|
||||
var pick = $"SELECT id FROM jobs WHERE state = {(int)JobState.Queued}{kindFilter} ORDER BY priority DESC, created, id LIMIT 1";
|
||||
var pick = $"SELECT id FROM jobs WHERE state = {(int)JobState.Queued}{kindFilter} ORDER BY {queue.OrderSql(kinds is { Count: > 0 } ? kinds : Enum.GetValues<JobKind>())}" +
|
||||
"priority DESC, created, id LIMIT 1";
|
||||
var claim = $"UPDATE jobs SET state = {(int)JobState.Running}, node_id = $1, started = $2, finished = NULL, error = NULL, attempts = attempts + 1";
|
||||
DbParam[] args = [workerId, DateTimeOffset.UtcNow];
|
||||
if (_db.Sql.IsPostgres)
|
||||
@@ -124,6 +133,15 @@ public sealed class JobRepository
|
||||
(nodeId is null ? string.Empty : " AND (node_id = $1 OR substr(node_id, 1, length($2)) = $2)"),
|
||||
nodeId is null ? [] : [nodeId, nodeId + "#"], cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Puts the job <paramref name="nodeId"/> runs back in the queue, keeping its checkpoint (a job that yielded to a higher
|
||||
/// one in the priority queue); false when it no longer runs there: paused or cancelled meanwhile, that state stays.
|
||||
/// </summary>
|
||||
public async Task<bool> RequeueAsync(Guid id, string nodeId, CancellationToken cancellationToken = default) =>
|
||||
await _db.ExecuteAsync(
|
||||
$"UPDATE jobs SET state = {(int)JobState.Queued}, node_id = NULL, started = NULL WHERE id = $1 AND node_id = $2 AND state = {(int)JobState.Running}",
|
||||
[id, nodeId], cancellationToken).ConfigureAwait(false) > 0;
|
||||
|
||||
public async Task<bool> SetPriorityAsync(Guid id, JobPriority priority, CancellationToken cancellationToken = default) =>
|
||||
await _db.ExecuteAsync("UPDATE jobs SET priority = $2 WHERE id = $1", [id, (int)priority], cancellationToken).ConfigureAwait(false) > 0;
|
||||
|
||||
@@ -133,9 +151,16 @@ public sealed class JobRepository
|
||||
|
||||
/// <summary>Queued jobs of the given kinds in claim order (highest priority, then oldest).</summary>
|
||||
public Task<IReadOnlyList<Job>> ListQueuedAsync(IReadOnlyCollection<JobKind> kinds, int limit = 50, CancellationToken cancellationToken = default) =>
|
||||
kinds.Count == 0 ? Task.FromResult<IReadOnlyList<Job>>([]) : _db.ListAsync(
|
||||
$"SELECT {Columns} FROM jobs WHERE state = {(int)JobState.Queued} AND kind IN ({KindList(kinds)}) ORDER BY priority DESC, created, id LIMIT $1",
|
||||
ListQueuedAsync(kinds, limit, JobPriorityQueue.Off, cancellationToken);
|
||||
|
||||
/// <summary>Queued jobs of the given kinds in the claim order of <paramref name="queue"/>.</summary>
|
||||
public Task<IReadOnlyList<Job>> ListQueuedAsync(IReadOnlyCollection<JobKind> kinds, int limit, JobPriorityQueue queue, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(queue);
|
||||
return kinds.Count == 0 ? Task.FromResult<IReadOnlyList<Job>>([]) : _db.ListAsync(
|
||||
$"SELECT {Columns} FROM jobs WHERE state = {(int)JobState.Queued} AND kind IN ({KindList(kinds)}) ORDER BY {queue.OrderSql(kinds)}priority DESC, created, id LIMIT $1",
|
||||
[Cursor.ClampLimit(limit)], Map, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Running jobs claimed by <paramref name="nodeId"/>.</summary>
|
||||
public Task<IReadOnlyList<Job>> ListRunningByNodeAsync(string nodeId, CancellationToken cancellationToken = default) =>
|
||||
|
||||
Reference in new issue
Block a user