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
@@ -4,6 +4,7 @@ using Titano.App.About;
|
||||
using Titano.App.Editor;
|
||||
using Titano.App.Import;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Jobs;
|
||||
using Titano.App.Library;
|
||||
using Titano.App.Server;
|
||||
using Titano.App.Settings;
|
||||
@@ -15,6 +16,7 @@ using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Diagnostics.Synthetic;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Imaging.Decoders;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Metadata;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
@@ -119,6 +121,8 @@ public sealed class SampleData
|
||||
settings.TrustedCertificates = [new TrustedCertificate { Fingerprint = ServerFingerprint, Server = "https://nas.local:8443", TrustedAt = new DateTimeOffset(2026, 9, 1, 9, 30, 0, TimeSpan.Zero) }];
|
||||
settings.RecentServers = ["https://nas.local:8443"];
|
||||
settings.RenderNodeOptIn = true;
|
||||
// The jobs sample shows a deep analysis that yielded to the render (owner review 1).
|
||||
settings.PriorityQueue = true;
|
||||
settings.FirstRunCompleted = true;
|
||||
}
|
||||
|
||||
@@ -133,7 +137,8 @@ public sealed class SampleData
|
||||
|
||||
/// <summary>
|
||||
/// Transfers for the sync table: an upload at 46 % (Comet over the ridge), an upload waiting (Fog lifting, Asti), a
|
||||
/// download of originals running (Sunrise over Superga) and one paused (Lake Como storm).
|
||||
/// download of originals waiting its turn halfway (Sunrise over Superga: jobs run one at a time) and one paused (Lake
|
||||
/// Como storm).
|
||||
/// </summary>
|
||||
public async Task FillSyncAsync()
|
||||
{
|
||||
@@ -158,13 +163,17 @@ public sealed class SampleData
|
||||
Created = now.AddMinutes(-5),
|
||||
Started = state == JobState.Queued ? null : now.AddMinutes(-5),
|
||||
};
|
||||
// One job at a time (owner review 1): the upload runs, so a job of this PC that ran waits for its turn, in the plain
|
||||
// queue (the Jobs and Settings scenes, captured before, show the priority queue).
|
||||
await RequeueLocalJobsAsync(db);
|
||||
_services.Settings.PriorityQueue = false;
|
||||
var upload = $$"""{"server":"{{ServerAddress}}"}""";
|
||||
var originals = $$"""{"server":"{{ServerAddress}}","mode":"Originals"}""";
|
||||
var comet = await LocalAsync("Comet");
|
||||
var fog = await LocalAsync("Fog lifting");
|
||||
await db.Jobs.EnqueueAsync(Transfer(JobKind.UploadCommit, comet.Id, comet.DisplayTitle, upload, JobState.Running, 462, 1_005));
|
||||
await db.Jobs.EnqueueAsync(Transfer(JobKind.UploadCommit, fog.Id, fog.DisplayTitle, upload, JobState.Queued, 0, 0));
|
||||
await db.Jobs.EnqueueAsync(Transfer(JobKind.Download, _sunrise, "Sunrise over Superga", originals, JobState.Running, 1_210, 2_880));
|
||||
await db.Jobs.EnqueueAsync(Transfer(JobKind.Download, _sunrise, "Sunrise over Superga", originals, JobState.Queued, 1_210, 2_880));
|
||||
await db.Jobs.EnqueueAsync(Transfer(JobKind.Download, _lakeComo, "Lake Como storm", originals, JobState.Paused, 300, 1_450));
|
||||
}
|
||||
|
||||
@@ -360,6 +369,8 @@ public sealed class SampleData
|
||||
public async Task MarkAnalysingAsync(Guid sequenceId)
|
||||
{
|
||||
var db = _db ?? throw new InvalidOperationException("OpenEmptyAsync first.");
|
||||
// The analysis is the one job this PC runs (owner review 1).
|
||||
await RequeueLocalJobsAsync(db);
|
||||
var now = Now;
|
||||
await db.Jobs.EnqueueAsync(new Job
|
||||
{
|
||||
@@ -379,6 +390,13 @@ public sealed class SampleData
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Puts the jobs this PC runs back in the queue, so the job a scene starts is the one running (owner review 1).</summary>
|
||||
private async Task RequeueLocalJobsAsync(TitanoDatabase db)
|
||||
{
|
||||
foreach (var running in (await db.Jobs.ListAsync(JobState.Running, 50)).Items.Where(j => j.NodeId is { } node && JobText.IsLocal(node, _services.WorkerId)))
|
||||
await db.Jobs.RequeueAsync(running.Id, running.NodeId!);
|
||||
}
|
||||
|
||||
/// <summary>A two-minute sunset at 2 s intervals: darkening scene, flicker, two shutter steps the pixels received, warming light.</summary>
|
||||
private static readonly SyntheticSequenceOptions EditorSunset = new()
|
||||
{
|
||||
@@ -640,14 +658,19 @@ public sealed class SampleData
|
||||
Finished = state is JobState.Done or JobState.Failed && startedAgo is { } a2 ? now - a2 + (runFor ?? TimeSpan.FromMinutes(1)) : null,
|
||||
};
|
||||
|
||||
// The user's render runs before the older render the batch queued (higher priority).
|
||||
yield return Make(JobKind.Render, s[0], "Harbour sunset → 4K 10-bit HEVC · 24 fps", JobState.Running, 2_232, 3_600, 11.3, TimeSpan.FromMinutes(2),
|
||||
startedAgo: TimeSpan.FromMinutes(3.4), log:
|
||||
startedAgo: TimeSpan.FromMinutes(3.4), priority: JobPriority.User, log:
|
||||
"10:14:02 window 41 · deflicker −67 % · 3 exposure steps redistributed over 18 frames\n" +
|
||||
"10:14:03 stabilisation on · mean shake 0.42 px · crop 1.8 %\n" +
|
||||
"10:14:03 encoder NVENC HEVC Main10 · 3840×2160 · 120 Mb/s · 24 fps · GOP 48\n" +
|
||||
"10:15:41 frame 2232 / 3600 · 11.3 fps · spill 0 · memory 6.1 GB of 8 GB budget");
|
||||
yield return Make(JobKind.DeepAnalyse, s[4], s[4].DisplayTitle, JobState.Running, 2_498, 8_920, 41, TimeSpan.FromMinutes(6), startedAgo: TimeSpan.FromMinutes(1.1));
|
||||
yield return Make(JobKind.Proxies, s[1], s[1].DisplayTitle, JobState.Running, 915, 1_005, 118, TimeSpan.FromSeconds(8), startedAgo: TimeSpan.FromSeconds(8));
|
||||
// Jobs run one at a time (owner review 1): the deep analysis yielded to the render and resumes after it; the user
|
||||
// paused the proxies, so the render started at once.
|
||||
yield return Make(JobKind.DeepAnalyse, s[4], s[4].DisplayTitle, JobState.Queued, 2_498, 8_920, createdAgo: TimeSpan.FromMinutes(9),
|
||||
log: "10:12:40 " + Loc.L("Jobs.Line.Yielded", Loc.L("Jobs.Kind.Render")));
|
||||
yield return Make(JobKind.Proxies, s[1], s[1].DisplayTitle, JobState.Paused, 915, 1_005, startedAgo: TimeSpan.FromMinutes(14),
|
||||
priority: JobPriority.Background);
|
||||
yield return Make(JobKind.Render, s[3], "Aurora, Tromsø → 1080p share H.264", JobState.Queued, 0, 0, createdAgo: TimeSpan.FromMinutes(12));
|
||||
yield return Make(JobKind.Verify, null, "Archive · 2024", JobState.Queued, 0, 0, priority: JobPriority.Background, createdAgo: TimeSpan.FromMinutes(30));
|
||||
yield return Make(JobKind.Verify, s[7], s[7].DisplayTitle, JobState.Failed, 640, 640, 900, startedAgo: TimeSpan.FromMinutes(25), runFor: TimeSpan.FromSeconds(43),
|
||||
|
||||
@@ -182,16 +182,22 @@ public sealed class AppServices : IAsyncDisposable
|
||||
ApplyJobSettings();
|
||||
}
|
||||
|
||||
/// <summary>The parallelism of Settings › Rendering as the engine's workers, and the archive's rescan interval, now.</summary>
|
||||
/// <summary>
|
||||
/// The archive's rescan interval, now, and a review of the priority queue (Settings › Rendering): turned on, it may make
|
||||
/// the running job yield at once. The parallelism applies from the next sequence or job.
|
||||
/// </summary>
|
||||
public void ApplyJobSettings()
|
||||
{
|
||||
Engine?.SetWorkers(Parallelism);
|
||||
Engine?.Wake();
|
||||
if (_pollTimer is { } timer && timer.Period != ScanInterval) timer.Period = ScanInterval;
|
||||
}
|
||||
|
||||
/// <summary>Workers of this PC's job engine (Settings › Rendering › Parallelism, Auto: half the logical cores).</summary>
|
||||
/// <summary>Photos the running job of this PC processes at once (Settings › Rendering › Parallelism, Auto: half the logical cores).</summary>
|
||||
public int Parallelism => ProcessingTuning.Parallelism(Settings, System.Environment.ProcessorCount);
|
||||
|
||||
/// <summary>The priority queue of Settings › Rendering, as the job engine reads it.</summary>
|
||||
public JobPriorityQueue PriorityQueue => JobPriorityQueue.From(Settings.PriorityQueue, Settings.JobPriorities);
|
||||
|
||||
/// <summary>Starts, restarts or stops the render node to match the opt-in, the server session and the trusted certificates (BRIEF §14.7).</summary>
|
||||
public void UpdateRenderNode() =>
|
||||
_renderNode.Update(RenderNodeSession.For(Settings.RenderNodeOptIn && Processing is not null && !Environment.IsCapture, _server.IsConnected,
|
||||
@@ -371,20 +377,26 @@ public sealed class AppServices : IAsyncDisposable
|
||||
private async Task StartJobsAsync(TitanoDatabase database, bool startEngine, CancellationToken ct)
|
||||
{
|
||||
_wic = new WicDecoderProvider();
|
||||
var archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateClient(_wic) };
|
||||
var archive = new ArchiveServiceOptions
|
||||
{
|
||||
Decoder = DecoderFactory.CreateClient(_wic),
|
||||
Parallelism = () => Parallelism,
|
||||
MemoryBudget = () => ProcessingTuning.MemoryBudget(Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes),
|
||||
};
|
||||
Archives = new ArchiveService(database, archive);
|
||||
Processing = new ProcessingService(database, ProcessingOptions(archive));
|
||||
Sync.Open(database, Archives, archive);
|
||||
var handlers = CreateJobHandlers(this);
|
||||
var kinds = handlers.Select(h => h.Kind).Distinct().ToArray();
|
||||
Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds, Workers = Parallelism });
|
||||
// One job at a time (owner review 1): the parallelism works inside it, the priority queue decides which runs.
|
||||
Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds, PriorityQueue = () => PriorityQueue });
|
||||
// Sync follows the engine's jobs before it runs any: a render resumed at start that finishes at once is still sent (Export "Sync").
|
||||
Sync.Update();
|
||||
// With no handler the engine must not run: an empty kind list would let workers claim (and fail) every job.
|
||||
var started = startEngine && handlers.Count > 0;
|
||||
if (started) await Engine.StartAsync(ct);
|
||||
Jobs = new EngineJobQueue(database, Engine, started);
|
||||
Log.Info("jobs", started ? $"Job engine started with {Engine.Workers} worker(s) for {string.Join(", ", kinds)}" : "No job handlers registered; jobs stay queued");
|
||||
Log.Info("jobs", started ? $"Job engine started for {string.Join(", ", kinds)}" : "No job handlers registered; jobs stay queued");
|
||||
UpdateRenderNode();
|
||||
}
|
||||
|
||||
|
||||
@@ -131,7 +131,7 @@ public sealed class AppSettings
|
||||
/// <summary>Frame memory budget in GB; null = Auto (a quarter of installed memory).</summary>
|
||||
public int? MemoryBudgetGb { get; set; }
|
||||
|
||||
/// <summary>Jobs run at once, also capping their decode and analysis threads; null = Auto (half the logical cores, at least one, with the jobs' own thread counts).</summary>
|
||||
/// <summary>Photos the running job processes at once (owner review 1: jobs run one at a time); null = Auto (half the logical cores, at least one).</summary>
|
||||
public int? Parallelism { get; set; }
|
||||
|
||||
public bool BackgroundPriority { get; set; } = true;
|
||||
@@ -170,6 +170,15 @@ public sealed class AppSettings
|
||||
public bool PauseUploadsOnMetered { get; set; }
|
||||
|
||||
// ---- Jobs ----
|
||||
/// <summary>
|
||||
/// The priority queue (owner review 1): a job of a higher level makes the running one of a lower level yield, and that
|
||||
/// one resumes by itself afterwards. Off: jobs wait their turn.
|
||||
/// </summary>
|
||||
public bool PriorityQueue { get; set; }
|
||||
|
||||
/// <summary>Levels of the priority queue that differ from the defaults, by job kind (<c>render</c> → <c>high</c>).</summary>
|
||||
public Dictionary<string, string> JobPriorities { get; set; } = [];
|
||||
|
||||
/// <summary>"Clear done": finished jobs older than this are hidden from the Jobs list (they stay in the history).</summary>
|
||||
public DateTimeOffset? JobsClearedAt { get; set; }
|
||||
|
||||
|
||||
@@ -59,6 +59,9 @@ public sealed class JobListModel
|
||||
/// </summary>
|
||||
public long Stamp => _stamp;
|
||||
|
||||
/// <summary>The priority queue the engine claims jobs by, which orders the queue here too (<see cref="JobPriorityQueue.ClaimsBefore"/>).</summary>
|
||||
public JobPriorityQueue PriorityQueue { get; set; } = JobPriorityQueue.Off;
|
||||
|
||||
/// <summary>Inserts or replaces a snapshot that is known to be current (an engine event). True when something changed.</summary>
|
||||
public bool Apply(Job job) => Store(job, ++_stamp);
|
||||
|
||||
@@ -96,8 +99,9 @@ public sealed class JobListModel
|
||||
public bool Remove(Guid id) => _entries.Remove(id);
|
||||
|
||||
/// <summary>
|
||||
/// Display order: running (oldest start first), paused, queued in the order workers claim them (priority, then
|
||||
/// age), then the history, newest finish first. Finished jobs before <paramref name="clearedBefore"/> are hidden.
|
||||
/// Display order: running (oldest start first), paused, queued in the order the engine claims them (the level of the
|
||||
/// priority queue while it is on, priority, then age), then the history, newest finish first. Finished jobs before
|
||||
/// <paramref name="clearedBefore"/> are hidden.
|
||||
/// </summary>
|
||||
public IReadOnlyList<JobEntry> Ordered(JobFilter filter = JobFilter.All, string? search = null, DateTimeOffset? clearedBefore = null)
|
||||
{
|
||||
@@ -105,6 +109,7 @@ public sealed class JobListModel
|
||||
return _entries.Values
|
||||
.Where(e => Matches(e, filter) && Visible(e, clearedBefore) && (text is null || MatchesText(e, text)))
|
||||
.OrderBy(Group)
|
||||
.ThenBy(e => e.State == JobState.Queued && PriorityQueue.Enabled ? -(int)PriorityQueue.LevelOf(e.Job.Kind) : 0)
|
||||
.ThenBy(e => e.State == JobState.Queued ? -(int)e.Job.Priority : 0)
|
||||
.ThenBy(e => e.IsFinished ? -(e.Job.Finished ?? e.Job.Created).UtcTicks : (e.Job.Started ?? e.Job.Created).UtcTicks)
|
||||
.ThenBy(e => e.Job.Created)
|
||||
@@ -120,7 +125,7 @@ public sealed class JobListModel
|
||||
public int QueuePosition(Guid id)
|
||||
{
|
||||
if (!_entries.TryGetValue(id, out var entry) || entry.State != JobState.Queued) return 0;
|
||||
return _entries.Values.Count(e => e.State == JobState.Queued && ClaimsBefore(e.Job, entry.Job)) + 1;
|
||||
return _entries.Values.Count(e => e.State == JobState.Queued && PriorityQueue.ClaimsBefore(e.Job, entry.Job)) + 1;
|
||||
}
|
||||
|
||||
/// <summary>The job the job bar mirrors: the running job with the most recent progress, else the first running one.</summary>
|
||||
@@ -144,9 +149,8 @@ public sealed class JobListModel
|
||||
public bool IsBusy(JobKind kind) =>
|
||||
_entries.Values.Any(e => e.Job.Kind == kind && e.Job.Priority != JobPriority.Background && e.State is JobState.Queued or JobState.Running);
|
||||
|
||||
/// <summary>Same order as <c>JobRepository.ClaimNextAsync</c>: priority descending, then creation time and id.</summary>
|
||||
public 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;
|
||||
/// <summary>Same order as <c>JobRepository.ClaimNextAsync</c> with the priority queue off: priority descending, then creation time and id.</summary>
|
||||
public static bool ClaimsBefore(Job a, Job b) => JobPriorityQueue.Off.ClaimsBefore(a, b);
|
||||
|
||||
private static int Group(JobEntry e) => e.State switch
|
||||
{
|
||||
|
||||
@@ -17,8 +17,8 @@ public interface IJobQueue
|
||||
/// <summary>Node id stamped on jobs run by this PC.</summary>
|
||||
string WorkerId { get; }
|
||||
|
||||
/// <summary>Concurrent workers of the local engine; 0 when it runs no handler yet.</summary>
|
||||
int Workers { get; }
|
||||
/// <summary>The local engine runs jobs (it runs none before it starts, or without handlers).</summary>
|
||||
bool IsRunning { get; }
|
||||
|
||||
/// <summary>Kinds this PC can run.</summary>
|
||||
IReadOnlyCollection<JobKind> Kinds { get; }
|
||||
@@ -63,7 +63,7 @@ public sealed class EngineJobQueue : IJobQueue, IDisposable
|
||||
|
||||
public string WorkerId => _engine.Options.WorkerId;
|
||||
|
||||
public int Workers => _started ? _engine.Options.Workers : 0;
|
||||
public bool IsRunning => _started;
|
||||
|
||||
public IReadOnlyCollection<JobKind> Kinds => _engine.Options.Kinds ?? [];
|
||||
|
||||
|
||||
@@ -93,8 +93,14 @@
|
||||
ui:Field.Placeholder="{l:Loc Jobs.Search}" ToolTip="{l:Loc Tooltips.Jobs.Search}" AutomationProperties.Name="{l:Loc Jobs.Search}" />
|
||||
</StackPanel>
|
||||
</WrapPanel>
|
||||
<TextBlock Grid.Column="1" Text="{Binding WorkersText}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" Margin="12,0,0,0"
|
||||
Typography.NumeralAlignment="Tabular" ToolTip="{l:Loc Tooltips.Jobs.Workers}" Visibility="{Binding HasWorkers, Converter={StaticResource BoolToVisibility}}" />
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center" Margin="12,0,0,0" Visibility="{Binding HasEngine, Converter={StaticResource BoolToVisibility}}">
|
||||
<Border Style="{StaticResource Pill.Auto}" Margin="0,0,10,0" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.Jobs.PriorityQueue}"
|
||||
Visibility="{Binding IsPriorityQueueOn, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{l:Loc Jobs.PriorityQueue}" FontSize="{StaticResource Size.Chip}" Foreground="{DynamicResource Brush.Accent}" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<TextBlock Text="{Binding ParallelismText}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center"
|
||||
Typography.NumeralAlignment="Tabular" ToolTip="{l:Loc Tooltips.Jobs.Parallelism}" />
|
||||
</StackPanel>
|
||||
<Button Grid.Column="2" Content="{l:Loc Jobs.PauseAll}" Command="{Binding PauseAllCommand}" ToolTip="{l:Loc Tooltips.Jobs.PauseAll}" Margin="12,0,0,0" VerticalAlignment="Center" />
|
||||
<Button Grid.Column="3" Content="{l:Loc Jobs.ClearDone}" Command="{Binding ClearDoneCommand}" ToolTip="{l:Loc Tooltips.Jobs.ClearDone}" Margin="8,0,0,0" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
|
||||
@@ -132,11 +132,14 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"Workers 1 / 4": jobs this PC's workers run out of its workers.</summary>
|
||||
public string WorkersText => Loc.L("Jobs.Workers", _queue is { } queue ? _model.RunningOn(queue.WorkerId) : 0, _queue?.Workers ?? 0);
|
||||
/// <summary>"8 photos at once": what the running job of this PC processes together (Settings › Rendering › Parallelism).</summary>
|
||||
public string ParallelismText => Loc.Plural("Jobs.Parallelism", Shell.Services.Parallelism);
|
||||
|
||||
/// <summary>The engine of this PC runs workers (it has none before it starts).</summary>
|
||||
public bool HasWorkers => _queue is { Workers: > 0 };
|
||||
/// <summary>The engine of this PC runs jobs (it runs none before it starts).</summary>
|
||||
public bool HasEngine => _queue is { IsRunning: true };
|
||||
|
||||
/// <summary>The priority queue of Settings › Rendering is on: higher jobs pause the running one.</summary>
|
||||
public bool IsPriorityQueueOn => HasEngine && Shell.Services.Settings.PriorityQueue;
|
||||
|
||||
/// <summary>"History keeps 90 days".</summary>
|
||||
public string HistoryText => Loc.Plural("Jobs.History", (long)new JobEngineOptions().HistoryRetention.TotalDays);
|
||||
@@ -344,6 +347,7 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
/// <summary>Brings <see cref="Rows"/> to the model's order with moves (rows keep their expanded log).</summary>
|
||||
private void SyncRows()
|
||||
{
|
||||
_model.PriorityQueue = Shell.Services.PriorityQueue;
|
||||
var ordered = _model.Ordered(_filter, _searchText, ClearedAt);
|
||||
var wanted = new HashSet<Guid>(ordered.Select(e => e.Id));
|
||||
for (var i = Rows.Count - 1; i >= 0; i--)
|
||||
@@ -384,8 +388,9 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
Shell.SetJobCount(active, _model.QueuedCount);
|
||||
Shell.SetUnseenFailures(_unseenFailures.Count);
|
||||
Badge = active + _unseenFailures.Count;
|
||||
OnPropertyChanged(nameof(WorkersText));
|
||||
OnPropertyChanged(nameof(HasWorkers));
|
||||
OnPropertyChanged(nameof(ParallelismText));
|
||||
OnPropertyChanged(nameof(HasEngine));
|
||||
OnPropertyChanged(nameof(IsPriorityQueueOn));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
|
||||
|
||||
@@ -292,17 +292,45 @@
|
||||
<TextBox Style="{StaticResource TextBox.SettingNumber}" Text="{Binding Parallelism.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
shell:EditBehavior.Field="{Binding Parallelism}" ToolTip="{Binding Parallelism.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Rendering.Parallelism}" />
|
||||
<TextBlock Style="{StaticResource Text.Hint}" Text="{Binding CoresText}" Margin="12,0,0,0" />
|
||||
<Border Style="{StaticResource Pill.Auto}" Margin="12,0,0,0" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.Settings.WorkersAuto}"
|
||||
<Border Style="{StaticResource Pill.Auto}" Margin="12,0,0,0" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.Settings.ParallelismAuto}"
|
||||
Visibility="{Binding IsParallelismAuto, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Style="{StaticResource Text.AutoPill}" Text="{Binding ParallelismAutoText}" />
|
||||
</Border>
|
||||
<Button Style="{StaticResource Button.Reset}" Margin="12,0,0,0" Command="{Binding ResetParallelismCommand}" ToolTip="{l:Loc Tooltips.Settings.WorkersReset}"
|
||||
<Button Style="{StaticResource Button.Reset}" Margin="12,0,0,0" Command="{Binding ResetParallelismCommand}" ToolTip="{l:Loc Tooltips.Settings.ParallelismReset}"
|
||||
AutomationProperties.Name="{l:Loc Settings.BackToAuto}"
|
||||
Visibility="{Binding IsParallelismAuto, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
<CheckBox Content="{l:Loc Settings.Rendering.Background}" IsChecked="{Binding BackgroundPriority}" ToolTip="{l:Loc Tooltips.Settings.InterfacePriority}"
|
||||
Margin="24,0,0,0" VerticalAlignment="Center" />
|
||||
</WrapPanel>
|
||||
</HeaderedContentControl>
|
||||
<!-- Owner review 1: jobs run one at a time; the priority queue lets a higher kind pause the running job. -->
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Rendering.PriorityQueue}">
|
||||
<StackPanel Margin="0,4,0,0">
|
||||
<CheckBox Content="{l:Loc Settings.Rendering.PriorityQueueOn}" IsChecked="{Binding PriorityQueue}" ToolTip="{l:Loc Tooltips.Settings.PriorityQueue}"
|
||||
HorizontalAlignment="Left" />
|
||||
<ItemsControl ItemsSource="{Binding JobPriorities}" Margin="0,8,0,0" Focusable="False"
|
||||
Visibility="{Binding PriorityQueue, Converter={StaticResource BoolToVisibility}}">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<WrapPanel />
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Grid Width="272" Margin="0,0,16,6">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="112" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{Binding Label}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" Margin="0,0,8,0" />
|
||||
<ComboBox Grid.Column="1" ItemsSource="{Binding Levels}" SelectedItem="{Binding Selected}" DisplayMemberPath="Label"
|
||||
ToolTip="{Binding ToolTip}" AutomationProperties.Name="{Binding Label}" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Rendering.Hardware}">
|
||||
<WrapPanel Margin="0,4,0,0">
|
||||
<RadioButton Content="{l:Loc Settings.Rendering.PreferHardware}" IsChecked="{Binding IsPreferHardware}" ToolTip="{l:Loc Tooltips.Settings.PreferHardware}" Margin="0,0,18,0" />
|
||||
|
||||
@@ -17,6 +17,7 @@ using Titano.Core.Model;
|
||||
using Titano.Core.Naming;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Archiving;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Ui.Mvvm;
|
||||
using Titano.Ui.Theming;
|
||||
|
||||
@@ -75,7 +76,8 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
new(SettingsPage.Import, ["Import.Scan.Sessions", "Import.Label.Scan", "Import.Scan.Subfolders", "Import.Scan.Verify", "Import.Label.Duplicates",
|
||||
"Import.Label.After", "Import.After.Eject"]),
|
||||
new(SettingsPage.Analysis, ["Settings.Analysis.Width", "Settings.Analysis.Night", "Settings.Analysis.Stars", "Settings.Analysis.Deep"]),
|
||||
new(SettingsPage.Rendering, ["Settings.Rendering.Quality", "Settings.Rendering.Memory", "Settings.Rendering.Parallelism", "Settings.Rendering.Hardware", "Settings.Rendering.Encoders"]),
|
||||
new(SettingsPage.Rendering, ["Settings.Rendering.Quality", "Settings.Rendering.Memory", "Settings.Rendering.Parallelism", "Settings.Rendering.PriorityQueue",
|
||||
"Settings.Rendering.Hardware", "Settings.Rendering.Encoders"]),
|
||||
new(SettingsPage.Formats, ["Settings.Formats.Title", "Settings.Formats.Column.Tier", "Settings.Formats.Install"]),
|
||||
new(SettingsPage.Storage, ["Settings.Storage.Folder", "Settings.Storage.Thumbnails", "Settings.Storage.Limit"]),
|
||||
new(SettingsPage.Server, ["Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates"]),
|
||||
@@ -147,7 +149,8 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
// Saving applies it: the job engine takes the new number of workers at once.
|
||||
Save();
|
||||
OnPropertyChanged(nameof(IsParallelismAuto));
|
||||
}, () => Loc.L("Tooltips.Settings.Workers"));
|
||||
}, () => Loc.L("Tooltips.Settings.Parallelism"));
|
||||
JobPriorities = [.. PriorityKinds.Select(k => new JobPriorityRow(k, kind => Shell.Services.PriorityQueue.LevelOf(kind), SetJobPriority))];
|
||||
|
||||
// ---- Storage ----
|
||||
CacheFolder = new EditableField(CacheStore.Folder(shell.Services.Environment, _s), v => ArchiveLocations.Validate(v), v =>
|
||||
@@ -603,7 +606,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
|
||||
public int LogicalCores => Environment.ProcessorCount;
|
||||
|
||||
/// <summary>Auto: half the logical cores, the job engine's default (BRIEF §14.6).</summary>
|
||||
/// <summary>Auto: half the logical cores (photos the running job processes at once, owner review 1).</summary>
|
||||
public int ParallelismAuto => ProcessingTuning.ParallelismAuto(LogicalCores);
|
||||
|
||||
private int EffectiveParallelism => _s.Parallelism ?? ParallelismAuto;
|
||||
@@ -616,6 +619,19 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
|
||||
public ICommand ResetParallelismCommand { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The priority queue (owner review 1): on, a job of a higher level pauses the running one without asking, and that one
|
||||
/// resumes by itself afterwards; off, jobs wait their turn.
|
||||
/// </summary>
|
||||
public bool PriorityQueue
|
||||
{
|
||||
get => _s.PriorityQueue;
|
||||
set => SetSetting(_s.PriorityQueue, value, v => _s.PriorityQueue = v);
|
||||
}
|
||||
|
||||
/// <summary>The kinds of job this PC runs with their levels in the priority queue, the ones the user waits for first.</summary>
|
||||
public IReadOnlyList<JobPriorityRow> JobPriorities { get; }
|
||||
|
||||
public bool BackgroundPriority
|
||||
{
|
||||
get => _s.BackgroundPriority;
|
||||
@@ -1102,6 +1118,23 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
|
||||
private string? ValidateParallelism(string text) => ValidateInt(text, 1, Math.Max(1, LogicalCores * 2));
|
||||
|
||||
/// <summary>The kinds the priority queue lists, in the order of the Jobs screen's kinds the user starts most.</summary>
|
||||
private static readonly JobKind[] PriorityKinds =
|
||||
[
|
||||
JobKind.Render, JobKind.Import, JobKind.Download, JobKind.UploadCommit, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse,
|
||||
JobKind.DeepAnalyse, JobKind.Thumbs, JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move,
|
||||
];
|
||||
|
||||
/// <summary>Stores <paramref name="level"/> for <paramref name="kind"/>, keeping only the levels that differ from the defaults.</summary>
|
||||
private void SetJobPriority(JobKind kind, JobKindPriority level)
|
||||
{
|
||||
var queue = Shell.Services.PriorityQueue;
|
||||
var levels = Enum.GetValues<JobKind>().ToDictionary(k => k, queue.LevelOf);
|
||||
levels[kind] = level;
|
||||
_s.JobPriorities = JobPriorityQueue.Changed(levels);
|
||||
Save();
|
||||
}
|
||||
|
||||
private static string? ValidateInt(string text, int min, int max) =>
|
||||
int.TryParse(text.Trim(), NumberStyles.Integer, CultureInfo.CurrentCulture, out var n) && n >= min && n <= max
|
||||
? null
|
||||
@@ -1425,6 +1458,9 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
_s.Parallelism = null;
|
||||
_s.BackgroundPriority = defaults.BackgroundPriority;
|
||||
_s.HardwareEncoding = defaults.HardwareEncoding;
|
||||
_s.PriorityQueue = defaults.PriorityQueue;
|
||||
_s.JobPriorities = [];
|
||||
foreach (var row in JobPriorities) row.Refresh();
|
||||
Parallelism.Load(ParallelismAuto.ToString(CultureInfo.CurrentCulture));
|
||||
_interfacePriority?.Update();
|
||||
break;
|
||||
@@ -1545,6 +1581,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
if (Shell.Services.Thumbnails is { } thumbs) thumbs.Capacity = _s.ThumbnailMemoryItems;
|
||||
DefaultServer.Load(ServerAddress.Display(_s.ServerUrl));
|
||||
_interfacePriority?.Update();
|
||||
foreach (var row in JobPriorities) row.Refresh();
|
||||
UpdatePreview();
|
||||
LoadCertificates();
|
||||
OnAllPropertiesChanged();
|
||||
@@ -1613,6 +1650,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
{
|
||||
foreach (var page in AllPages) page.Refresh();
|
||||
foreach (var row in Encoders) row.Refresh();
|
||||
foreach (var row in JobPriorities) row.Refresh();
|
||||
foreach (var row in Formats) row.Refresh();
|
||||
foreach (var row in MissingExtensions) row.Refresh();
|
||||
ArchiveRoot.Refresh();
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Data.Processing;
|
||||
|
||||
@@ -8,7 +7,7 @@ namespace Titano.App.Settings;
|
||||
/// <summary>
|
||||
/// Settings › Rendering and Analysis applied to this PC's jobs (asked at the start of each analysis and render, so a
|
||||
/// change applies to the next job): the memory budget and cache folder of the frame window, the quality profile, the
|
||||
/// parallelism and the analysis width and thresholds.
|
||||
/// parallelism (photos the running job processes at once) and the analysis width and thresholds.
|
||||
/// </summary>
|
||||
public static class ProcessingTuning
|
||||
{
|
||||
@@ -31,10 +30,10 @@ public static class ProcessingTuning
|
||||
/// <summary>Frames decoded ahead of the render position, per quality profile (Best keeps more in flight, within the budget).</summary>
|
||||
public static int ReadAhead(QualityProfile quality) => quality == QualityProfile.Best ? 8 : 4;
|
||||
|
||||
/// <summary>Auto parallelism: the job engine's default, half the logical cores (BRIEF §14.6), at least one.</summary>
|
||||
/// <summary>Auto parallelism: half the logical cores, at least one (the archive engine's default too).</summary>
|
||||
public static int ParallelismAuto(int logicalCores) => int.Max(1, logicalCores / 2);
|
||||
|
||||
/// <summary>Workers of this PC's job engine: the user's value, or Auto.</summary>
|
||||
/// <summary>Photos the running job processes at once (owner review 1, R2): the user's value, or Auto.</summary>
|
||||
public static int Parallelism(AppSettings settings, int logicalCores) => settings.Parallelism is { } n and > 0 ? n : ParallelismAuto(logicalCores);
|
||||
|
||||
/// <summary>The frame memory budget of this PC in bytes: the user's GB, or Auto (a quarter of <paramref name="installedBytes"/>).</summary>
|
||||
@@ -42,32 +41,24 @@ public static class ProcessingTuning
|
||||
settings.MemoryBudgetGb is { } gb ? gb * (1L << 30) : long.Max(1L << 30, installedBytes / 4);
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="basis"/> with the user's current Rendering and Analysis settings. The memory budget is shared by the
|
||||
/// jobs that can run at once: each job's frame window gets its share (budget ÷ workers). Auto keeps the engine's own
|
||||
/// thread counts per job; a value the user set also caps the background decodes and the deep analysis's threads.
|
||||
/// <paramref name="basis"/> with the user's current Rendering and Analysis settings. Jobs run one at a time (owner
|
||||
/// review 1, R2), so the job that runs has the whole memory budget for its frame window, and the parallelism sets how
|
||||
/// many frames its render decodes ahead and its deep analysis measures at once (<see cref="ProcessingOptions.WithParallelism"/>).
|
||||
/// </summary>
|
||||
public static ProcessingOptions Apply(ProcessingOptions basis, AppSettings settings, long installedBytes, int logicalCores, string spillDirectory)
|
||||
{
|
||||
var workers = Parallelism(settings, logicalCores);
|
||||
int? cap = settings.Parallelism is { } n and > 0 ? n : null;
|
||||
var analysis = settings.DeepAnalysis(basis.DeepAnalysis);
|
||||
return basis with
|
||||
public static ProcessingOptions Apply(ProcessingOptions basis, AppSettings settings, long installedBytes, int logicalCores, string spillDirectory) =>
|
||||
(basis with
|
||||
{
|
||||
FrameWindow = basis.FrameWindow with
|
||||
{
|
||||
MemoryBudget = long.Max(1, MemoryBudget(settings, installedBytes) / workers),
|
||||
MemoryBudget = MemoryBudget(settings, installedBytes),
|
||||
SpillDirectory = spillDirectory,
|
||||
Ahead = ReadAhead(settings.Quality),
|
||||
MaxConcurrentLoads = cap is { } loads ? int.Clamp(loads, 1, basis.FrameWindow.MaxConcurrentLoads) : basis.FrameWindow.MaxConcurrentLoads,
|
||||
},
|
||||
Render = basis.Render with
|
||||
{
|
||||
AnalysisLongEdge = PreparationLongEdge(settings.Quality),
|
||||
DefaultFlowQuality = FlowQuality(settings.Quality),
|
||||
},
|
||||
DeepAnalysis = cap is { } threads
|
||||
? analysis with { MaxDegreeOfParallelism = int.Clamp(threads, 1, DeepAnalysisOptions.Default.MaxDegreeOfParallelism) }
|
||||
: analysis,
|
||||
};
|
||||
}
|
||||
DeepAnalysis = settings.DeepAnalysis(basis.DeepAnalysis),
|
||||
}).WithParallelism(Parallelism(settings, logicalCores));
|
||||
}
|
||||
@@ -2,8 +2,10 @@ using System.Windows.Input;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Windows.Codecs;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Ui.Controls;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
@@ -48,6 +50,36 @@ public sealed record SettingsOption<T>(T Value, string Label)
|
||||
public override string ToString() => Label;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A kind of job and its level in the priority queue (Settings › Rendering, owner review 1): <paramref name="level"/> reads
|
||||
/// the level the settings give it, <paramref name="set"/> stores another.
|
||||
/// </summary>
|
||||
public sealed class JobPriorityRow(JobKind kind, Func<JobKind, JobKindPriority> level, Action<JobKind, JobKindPriority> set) : ObservableObject
|
||||
{
|
||||
public JobKind Kind { get; } = kind;
|
||||
|
||||
public string Label => Loc.L("Jobs.Kind." + Kind);
|
||||
|
||||
public string ToolTip => Loc.L("Tooltips.Settings.JobPriority", Label);
|
||||
|
||||
/// <summary>The levels, highest first.</summary>
|
||||
public IReadOnlyList<SettingsOption<JobKindPriority>> Levels =>
|
||||
[.. Enum.GetValues<JobKindPriority>().Reverse().Select(l => new SettingsOption<JobKindPriority>(l, Loc.L("Settings.Rendering.Priority." + l)))];
|
||||
|
||||
public SettingsOption<JobKindPriority> Selected
|
||||
{
|
||||
get => Levels.First(l => l.Value == level(Kind));
|
||||
set
|
||||
{
|
||||
if (value is null || value.Value == level(Kind)) return;
|
||||
set(Kind, value.Value);
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
internal void Refresh() => OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
/// <summary>One row of the encoder table with its self-test state.</summary>
|
||||
public sealed class EncoderRowViewModel(EncoderRow row) : ObservableObject
|
||||
{
|
||||
|
||||
@@ -138,6 +138,8 @@ public static class ScreenCapture
|
||||
await sample.CacheProxiesAsync();
|
||||
await sample.FillSyncAsync();
|
||||
await shell.Server.Sync.ReloadAsync();
|
||||
// The job bar follows the upload the sync sample runs.
|
||||
await shell.Jobs.ReloadAsync();
|
||||
foreach (var theme in Themes)
|
||||
{
|
||||
ThemeManager.Apply(theme);
|
||||
@@ -281,6 +283,8 @@ public static class ScreenCapture
|
||||
// Last, as it stays: an analysis of the sequence running (settings disabled, viewing tools live).
|
||||
await sample.MarkAnalysingAsync(id);
|
||||
await editor.AttachJobsAsync();
|
||||
// The job bar shows the analysis, the one job running.
|
||||
await shell.Jobs.ReloadAsync();
|
||||
foreach (var theme in Themes)
|
||||
{
|
||||
ThemeManager.Apply(theme);
|
||||
|
||||
@@ -31,7 +31,7 @@ public sealed class IndexSnapshot
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path)) return null;
|
||||
data = File.ReadAllBytes(path);
|
||||
data = AtomicFile.ReadAllBytes(path);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
|
||||
@@ -32,7 +32,7 @@ public sealed record IngestJournal(IReadOnlyList<SidecarFrame> Frames)
|
||||
IngestJournal? journal;
|
||||
try
|
||||
{
|
||||
journal = JsonSerializer.Deserialize(File.ReadAllBytes(sequence.IngestJournalPath), ArchiveJson.Default.IngestJournal);
|
||||
journal = JsonSerializer.Deserialize(AtomicFile.ReadAllBytes(sequence.IngestJournalPath), ArchiveJson.Default.IngestJournal);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
|
||||
@@ -28,6 +28,9 @@ public sealed class LeaseFile : IDisposable
|
||||
private const string Extension = ".lease";
|
||||
private const string StaleExtension = ".stale";
|
||||
private const int ReadAttempts = 5;
|
||||
|
||||
/// <summary>Creates tried, some 130 ms in all, while a released lease's name is still taken by a reader (<see cref="TryCreate"/>).</summary>
|
||||
private const int CreateAttempts = 8;
|
||||
private static readonly TimeSpan ReadRetryDelay = TimeSpan.FromMilliseconds(20);
|
||||
private readonly Lock _gate = new();
|
||||
private readonly Timer _renewal;
|
||||
@@ -202,10 +205,16 @@ public sealed class LeaseFile : IDisposable
|
||||
{
|
||||
return false;
|
||||
}
|
||||
catch (IOException) when (attempt < 3)
|
||||
catch (IOException) when (attempt < CreateAttempts)
|
||||
{
|
||||
// The holder released the lease between the failed create and the check: the name is free again.
|
||||
}
|
||||
catch (UnauthorizedAccessException) when (attempt < CreateAttempts)
|
||||
{
|
||||
// On Windows a lease released while a reader still holds it open (readers share deletion) stays pending
|
||||
// deletion, and creating its name answers "access denied" until the reader lets go, a moment later.
|
||||
Thread.Sleep(1 << (attempt - 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ public sealed class NewerFormatException(string path, int version)
|
||||
public static class ManifestStore
|
||||
{
|
||||
/// <exception cref="InvalidDataException">The file is not valid JSON or lacks required fields.</exception>
|
||||
public static ArchiveManifest ReadArchive(string path) => Parse(File.ReadAllBytes(path), path, ArchiveJson.Default.ArchiveManifest);
|
||||
public static ArchiveManifest ReadArchive(string path) => Parse(AtomicFile.ReadAllBytes(path), path, ArchiveJson.Default.ArchiveManifest);
|
||||
|
||||
public static void WriteArchive(string path, ArchiveManifest manifest)
|
||||
{
|
||||
@@ -28,7 +28,7 @@ public static class ManifestStore
|
||||
}
|
||||
|
||||
/// <exception cref="InvalidDataException">The file is not valid JSON or lacks required fields.</exception>
|
||||
public static SequenceManifest ReadSequence(string path) => ParseSequence(File.ReadAllBytes(path), path);
|
||||
public static SequenceManifest ReadSequence(string path) => ParseSequence(AtomicFile.ReadAllBytes(path), path);
|
||||
|
||||
/// <summary>Parses sidecar bytes (from disk or from the index snapshot).</summary>
|
||||
public static SequenceManifest ParseSequence(ReadOnlySpan<byte> utf8, string source) => Parse(utf8, source, ArchiveJson.Default.SequenceManifest);
|
||||
|
||||
@@ -4,10 +4,45 @@ namespace Titano.Core.IO;
|
||||
|
||||
/// <summary>
|
||||
/// Crash-safe writes: content goes to a temporary sibling, is flushed to disk, then renamed over the
|
||||
/// target (BRIEF §7 "temp → fsync → rename").
|
||||
/// target (BRIEF §7 "temp → fsync → rename"). The readers of sidecars and projects take no lease (a thumbnail pass reads
|
||||
/// a sidecar while an upload commits to it), and Windows refuses to rename over a file someone has open: a write tries the
|
||||
/// rename again for a moment (<see cref="Replace"/>), and <see cref="ReadAllBytes"/> and its siblings read such files whole
|
||||
/// and at once, sharing deletion where the file system allows a rename over an open file.
|
||||
/// </summary>
|
||||
public static class AtomicFile
|
||||
{
|
||||
/// <summary>Renames tried, some 1 s in all, before a replace held by a reader or another program (an indexer, an antivirus) fails.</summary>
|
||||
private const int ReplaceAttempts = 15;
|
||||
|
||||
private const int SharingViolation = unchecked((int)0x80070020);
|
||||
private const int LockViolation = unchecked((int)0x80070021);
|
||||
|
||||
/// <summary>The whole file as it was when opened, read so that a writer may replace it meanwhile.</summary>
|
||||
/// <exception cref="IOException">The file is larger than an array holds (2 GB), as <see cref="File.ReadAllBytes"/> says.</exception>
|
||||
public static byte[] ReadAllBytes(string path)
|
||||
{
|
||||
using var stream = OpenShared(path, FileOptions.SequentialScan);
|
||||
var bytes = new byte[CheckedLength(stream, path)];
|
||||
stream.ReadExactly(bytes);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="ReadAllBytes"/>
|
||||
public static async Task<byte[]> ReadAllBytesAsync(string path, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var stream = OpenShared(path, FileOptions.SequentialScan | FileOptions.Asynchronous);
|
||||
var bytes = new byte[CheckedLength(stream, path)];
|
||||
await stream.ReadExactlyAsync(bytes, cancellationToken).ConfigureAwait(false);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/// <summary>The file's text (UTF-8 unless it starts with another byte order mark), read as <see cref="ReadAllBytes"/>.</summary>
|
||||
public static string ReadAllText(string path)
|
||||
{
|
||||
using var reader = new StreamReader(OpenShared(path, FileOptions.SequentialScan), Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
|
||||
public static void WriteAllBytes(string path, ReadOnlySpan<byte> content)
|
||||
{
|
||||
var temp = TempPathFor(path);
|
||||
@@ -18,7 +53,7 @@ public static class AtomicFile
|
||||
fs.Write(content);
|
||||
fs.Flush(flushToDisk: true);
|
||||
}
|
||||
File.Move(temp, path, overwrite: true);
|
||||
Replace(temp, path);
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -41,7 +76,7 @@ public static class AtomicFile
|
||||
await fs.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
fs.Flush(flushToDisk: true);
|
||||
}
|
||||
File.Move(temp, path, overwrite: true);
|
||||
await ReplaceAsync(temp, path, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -55,7 +90,7 @@ public static class AtomicFile
|
||||
{
|
||||
using (var fs = new FileStream(tempPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
|
||||
fs.Flush(flushToDisk: true);
|
||||
File.Move(tempPath, path, overwrite: true);
|
||||
Replace(tempPath, path);
|
||||
}
|
||||
|
||||
public static string TempPathFor(string path)
|
||||
@@ -65,6 +100,70 @@ public static class AtomicFile
|
||||
return Path.Combine(dir, "." + Path.GetFileName(path) + "." + Guid.NewGuid().ToString("N")[..8] + ".tmp");
|
||||
}
|
||||
|
||||
/// <summary>Opened for reading whole: other readers and a rename over it may come, a writer in place may not.</summary>
|
||||
private static FileStream OpenShared(string path, FileOptions options) =>
|
||||
new(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, 1 << 16, options);
|
||||
|
||||
private static int CheckedLength(FileStream stream, string path) =>
|
||||
stream.Length <= Array.MaxLength ? (int)stream.Length : throw new IOException($"{path} is larger than 2 GB.");
|
||||
|
||||
/// <summary>
|
||||
/// Renames <paramref name="temp"/> over <paramref name="path"/>, trying again for a moment while another handle holds
|
||||
/// the target (<see cref="Holds"/>); anything else fails at once.
|
||||
/// </summary>
|
||||
private static void Replace(string temp, string path)
|
||||
{
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Move(temp, path, overwrite: true);
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (attempt < ReplaceAttempts && Holds(ex, temp, path))
|
||||
{
|
||||
Thread.Sleep(10 * attempt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Replace"/>
|
||||
private static async Task ReplaceAsync(string temp, string path, CancellationToken cancellationToken)
|
||||
{
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Move(temp, path, overwrite: true);
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (attempt < ReplaceAttempts && Holds(ex, temp, path))
|
||||
{
|
||||
await Task.Delay(10 * attempt, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the rename failed because another handle holds the target, which clears once it closes: a sharing or lock
|
||||
/// violation, or the "access denied" Windows answers for an open file that is neither read-only nor a folder (those
|
||||
/// never clear, so they fail at once, as a missing file or folder does).
|
||||
/// </summary>
|
||||
private static bool Holds(Exception ex, string temp, string path)
|
||||
{
|
||||
if (!File.Exists(temp)) return false;
|
||||
if (ex is IOException { HResult: SharingViolation or LockViolation }) return true;
|
||||
if (ex is not UnauthorizedAccessException) return false;
|
||||
try
|
||||
{
|
||||
return (File.GetAttributes(path) & (FileAttributes.ReadOnly | FileAttributes.Directory)) == 0;
|
||||
}
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryDelete(string path)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -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) =>
|
||||
|
||||
@@ -3,8 +3,10 @@ namespace Titano.Protocol;
|
||||
/// <summary>
|
||||
/// <c>GET/PUT /api/v1/server/settings</c> (admin): the editable part of the server configuration. Settings named in
|
||||
/// <see cref="Locked"/> come from environment variables and cannot be changed here; <see cref="RestartRequired"/> says
|
||||
/// that saved values (ports, TLS, workers, chunk size) wait for a restart. <see cref="ProxyWarning"/> is set in
|
||||
/// that saved values (ports, TLS, chunk size, job history) wait for a restart. <see cref="ProxyWarning"/> is set in
|
||||
/// responses when TLS mode is proxy and the request did not come through a trusted proxy over HTTPS (ignored when saving).
|
||||
/// <see cref="Parallelism"/> is how many photos the running job processes at once (jobs run one at a time), and
|
||||
/// <see cref="PriorityQueue"/> with <see cref="JobPriorities"/> the priority queue (owner review 1); both apply at once.
|
||||
/// </summary>
|
||||
public sealed record ServerSettingsDto(
|
||||
string ServerName,
|
||||
@@ -14,7 +16,9 @@ public sealed record ServerSettingsDto(
|
||||
string? TlsCert,
|
||||
string? TlsKey,
|
||||
string Language,
|
||||
int Workers,
|
||||
int Parallelism,
|
||||
bool PriorityQueue,
|
||||
IReadOnlyList<JobPriorityDto> JobPriorities,
|
||||
bool Discovery,
|
||||
long MaxUploadBytes,
|
||||
int ChunkSizeBytes,
|
||||
@@ -25,6 +29,9 @@ public sealed record ServerSettingsDto(
|
||||
bool RestartRequired,
|
||||
bool ProxyWarning);
|
||||
|
||||
/// <summary>A kind of job (<c>render</c>) and its level in the server's priority queue: <c>high</c>, <c>normal</c> or <c>low</c>.</summary>
|
||||
public sealed record JobPriorityDto(string Kind, string Level);
|
||||
|
||||
/// <summary>A server log file (<c>GET /api/v1/logs/files</c>).</summary>
|
||||
public sealed record LogFileDto(string Name, long Size, DateTimeOffset Modified);
|
||||
|
||||
@@ -51,7 +58,8 @@ public sealed record DashboardDto(
|
||||
int Users,
|
||||
ArchiveStatsDto Archive,
|
||||
JobCountsDto Jobs,
|
||||
int Workers,
|
||||
int Parallelism,
|
||||
bool PriorityQueue,
|
||||
IReadOnlyList<RenderNodeDto> Nodes,
|
||||
IReadOnlyList<UploadDayDto> Uploads,
|
||||
IReadOnlyList<AuditEntryDto> Activity,
|
||||
|
||||
@@ -234,6 +234,9 @@ pre.log.tall { max-height: 60vh; border-top: 0; }
|
||||
.settings { display: grid; gap: 20px; }
|
||||
.field { display: grid; grid-template-columns: 180px minmax(0, 420px); align-items: center; gap: 12px; color: var(--text-muted); }
|
||||
.settings-form .field { grid-template-columns: 140px minmax(0, 1fr); }
|
||||
/* Levels of the priority queue (owner review 1): several per row on a wide screen. */
|
||||
.priorities { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(280px, 100%), 1fr)); gap: 8px 24px; }
|
||||
.priorities .field { grid-template-columns: minmax(0, 1fr) 120px; }
|
||||
.fingerprint { font: 12px var(--mono); color: var(--text); }
|
||||
|
||||
/* Dialogs and toasts */
|
||||
|
||||
@@ -56,7 +56,7 @@ export async function render(root, { api, setMeta, actions, onEvent }) {
|
||||
<span class="value num">${formatNumber(d.jobs.running)}<small data-i18n="Admin.Dashboard.Running"></small></span>
|
||||
<span class="sub">${escapeHtml([plural("Admin.Dashboard.QueuedCount", d.jobs.queued), plural("Admin.Dashboard.DoneToday", d.jobs.doneToday),
|
||||
plural("Admin.Dashboard.FailedToday", d.jobs.failedToday)].join(" · "))}</span>
|
||||
<span class="sub">${escapeHtml(plural("Admin.Dashboard.WorkerCount", d.workers))}</span>
|
||||
<span class="sub">${escapeHtml([plural("Admin.Dashboard.Parallelism", d.parallelism), ...(d.priorityQueue ? [t("Admin.Dashboard.PriorityQueue")] : [])].join(" · "))}</span>
|
||||
</section>
|
||||
<section class="panel tile" aria-labelledby="tile-nodes">
|
||||
<h2 class="label" id="tile-nodes" data-i18n="Admin.Dashboard.Nodes"></h2>
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
// Settings (BRIEF §14.8): server name, ports, TLS, discovery, limits, language, retention. Values fixed by environment
|
||||
// variables are read-only here; ports, TLS, workers, chunk size and job history apply at the next restart.
|
||||
// Settings (BRIEF §14.8): server name, ports, TLS, discovery, jobs, limits, language, retention. Values fixed by environment
|
||||
// variables are read-only here; ports, TLS, chunk size and job history apply at the next restart. Jobs run one at a time
|
||||
// (owner review 1): the parallelism (photos at once) and the priority queue apply at once.
|
||||
import { t, applyStrings, languages } from "../i18n.js";
|
||||
import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, markInvalid, clearInvalid, invalidText, escapeReverts, PROXY_WARNING } from "../ui.js";
|
||||
import { kindLabel } from "../jobs.js";
|
||||
|
||||
/** Setting → environment variable that can fix it (BRIEF §14.9). */
|
||||
const VARIABLES = {
|
||||
serverName: "TITANO_SERVER_NAME", httpPort: "TITANO_HTTP_PORT", httpsPort: "TITANO_HTTPS_PORT", tlsMode: "TITANO_TLS_MODE",
|
||||
tlsCert: "TITANO_TLS_CERT", tlsKey: "TITANO_TLS_KEY", language: "TITANO_LANG", workers: "TITANO_WORKERS", discovery: "TITANO_DISCOVERY",
|
||||
tlsCert: "TITANO_TLS_CERT", tlsKey: "TITANO_TLS_KEY", language: "TITANO_LANG", parallelism: "TITANO_PARALLELISM", discovery: "TITANO_DISCOVERY",
|
||||
priorityQueue: "TITANO_PRIORITY_QUEUE",
|
||||
};
|
||||
/** Levels of the priority queue, highest first. */
|
||||
const LEVELS = ["high", "normal", "low"];
|
||||
/** Settings the server names in error details whose field here has another name. */
|
||||
const FIELDS = { maxuploadbytes: "maxUploadMb", chunksizebytes: "chunkSizeMib" };
|
||||
const PEM_FILES = ["tlsCert", "tlsKey"];
|
||||
@@ -42,9 +47,18 @@ export async function render(root, { api, info, setMeta, actions }) {
|
||||
${text("serverName", settings.serverName)}
|
||||
${field("language", `<select class="input" name="language" ${lock("language")}>${languages().concat(languages().includes(settings.language) ? [] : [settings.language])
|
||||
.map((code) => `<option value="${attr(code)}" ${code === settings.language ? "selected" : ""}>${escapeHtml(nativeName(code))}</option>`).join("")}</select>`)}
|
||||
${number("workers", settings.workers, 'min="1" max="64"')}
|
||||
${field("discovery", `<span class="inline"><input type="checkbox" name="discovery" ${settings.discovery ? "checked" : ""} ${lock("discovery")}></span>`)}
|
||||
</section>
|
||||
<section class="panel" aria-labelledby="jobs-title">
|
||||
<h2 id="jobs-title" data-i18n="Admin.Settings.Jobs"></h2>
|
||||
${number("parallelism", settings.parallelism, 'min="1" max="64"')}
|
||||
${field("priorityQueue", `<span class="inline"><input type="checkbox" name="priorityQueue" ${settings.priorityQueue ? "checked" : ""} ${lock("priorityQueue")}></span>`)}
|
||||
<div class="priorities" ${settings.priorityQueue ? "" : "hidden"}>
|
||||
${settings.jobPriorities.map((p) => `<label class="field"><span>${escapeHtml(kindLabel(p.kind))}</span>
|
||||
<select class="input narrow" name="priority:${attr(p.kind)}" title="${attr(t("Admin.Settings.JobPriority.Tip", kindLabel(p.kind)))}">${LEVELS.map((l) =>
|
||||
`<option value="${l}" ${l === p.level ? "selected" : ""}>${escapeHtml(t(`Admin.Settings.Priority.${cap(l)}`))}</option>`).join("")}</select></label>`).join("")}
|
||||
</div>
|
||||
</section>
|
||||
<section class="panel" aria-labelledby="network-title">
|
||||
<div class="panel-head"><h2 id="network-title" data-i18n="Admin.Settings.Network"></h2>
|
||||
${settings.proxyWarning ? PROXY_WARNING : ""}</div>
|
||||
@@ -71,6 +85,8 @@ export async function render(root, { api, info, setMeta, actions }) {
|
||||
form.addEventListener("submit", save);
|
||||
form.elements.tlsMode.addEventListener("change", () => pemFiles(form));
|
||||
pemFiles(form);
|
||||
// The levels matter only while the priority queue is on.
|
||||
form.elements.priorityQueue.addEventListener("change", () => { root.querySelector(".priorities").hidden = !form.elements.priorityQueue.checked; });
|
||||
}
|
||||
|
||||
/** The certificate and key files are used only in Own certificate mode; elsewhere they are off and say so. */
|
||||
@@ -94,7 +110,9 @@ export async function render(root, { api, info, setMeta, actions }) {
|
||||
...settings,
|
||||
serverName: String(value("serverName", settings.serverName)).trim(),
|
||||
language: String(value("language", settings.language)),
|
||||
workers: Number(value("workers", settings.workers)),
|
||||
parallelism: Number(value("parallelism", settings.parallelism)),
|
||||
priorityQueue: form.elements.priorityQueue.disabled ? settings.priorityQueue : form.elements.priorityQueue.checked,
|
||||
jobPriorities: settings.jobPriorities.map((p) => ({ kind: p.kind, level: String(data.get(`priority:${p.kind}`) ?? p.level) })),
|
||||
discovery: form.elements.discovery.disabled ? settings.discovery : form.elements.discovery.checked,
|
||||
httpPort: Number(value("httpPort", settings.httpPort)),
|
||||
httpsPort: Number(value("httpsPort", settings.httpsPort)),
|
||||
|
||||
@@ -196,6 +196,8 @@ export function escapeReverts(form) {
|
||||
form.addEventListener("keydown", (e) => {
|
||||
const field = e.target;
|
||||
if (e.key !== "Escape" || !(field instanceof HTMLInputElement || field instanceof HTMLSelectElement) || field.type === "search") return;
|
||||
const checkable = field.type === "checkbox" || field.type === "radio";
|
||||
const before = checkable ? field.checked : field.value;
|
||||
if (field instanceof HTMLSelectElement) {
|
||||
[...field.options].forEach((o) => {
|
||||
o.selected = o.defaultSelected;
|
||||
@@ -206,6 +208,8 @@ export function escapeReverts(form) {
|
||||
field.value = field.defaultValue;
|
||||
}
|
||||
clearInvalid(field);
|
||||
// What follows the value (the certificate files of a TLS mode, the levels of the priority queue) follows it back.
|
||||
if ((checkable ? field.checked : field.value) !== before) field.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ public static class AdminEndpoints
|
||||
}
|
||||
|
||||
private static async Task<IResult> DashboardAsync(HttpContext context, TitanoDatabase db, ServerArchive archive, ServerOptions options, ServerState state,
|
||||
JobEngineHost jobs, TimeProvider time)
|
||||
TimeProvider time)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
var now = time.GetUtcNow();
|
||||
@@ -63,7 +63,8 @@ public static class AdminEndpoints
|
||||
users.Count,
|
||||
await ArchiveEndpoints.StatsAsync(db, archive, ct),
|
||||
new JobCountsDto(counts.Queued, counts.Running, counts.Paused, counts.DoneSince, counts.FailedSince),
|
||||
jobs.Workers,
|
||||
options.Parallelism,
|
||||
options.PriorityQueue,
|
||||
[.. nodes.Select(n => Dto.Node(n, names.GetValueOrDefault(n.UserId, string.Empty)))],
|
||||
[.. uploads.Select(u => new UploadDayDto(u.Day, u.Count, u.Bytes))],
|
||||
[.. activity.Items.Select(Dto.Audit)],
|
||||
@@ -73,7 +74,7 @@ public static class AdminEndpoints
|
||||
}
|
||||
|
||||
private static async Task<IResult> SaveSettingsAsync(HttpContext context, Caller caller, ServerSettingsDto request, ServerSettingsStore store, ServerOptions options,
|
||||
AuditLog audit)
|
||||
AuditLog audit, JobEngineHost jobs)
|
||||
{
|
||||
switch (store.Save(request))
|
||||
{
|
||||
@@ -82,6 +83,8 @@ public static class AdminEndpoints
|
||||
case (var code, var setting):
|
||||
return ApiErrors.BadRequest(context, code, setting, setting);
|
||||
}
|
||||
// A priority queue turned on, or a level raised, may make the running job yield at once.
|
||||
jobs.Engine.Wake();
|
||||
await audit.WriteAsync(caller, context, "server_settings", "server", null, request.ServerName);
|
||||
return Results.Json(store.Current() with { ProxyWarning = AdminPanel.BypassesProxy(context, options) }, ProtocolJson.Default.ServerSettingsDto);
|
||||
}
|
||||
|
||||
@@ -25,11 +25,11 @@ public static class DiagnosticsEndpoints
|
||||
api.MapGet("/server/diagnostics", DownloadAsync).Requires(Permissions.ManageArchive);
|
||||
|
||||
private static async Task<IResult> DownloadAsync(HttpContext context, Caller caller, TitanoDatabase db, ServerOptions options, ServerState state,
|
||||
JobEngineHost jobs, AuditLog audit, TimeProvider time, IServiceProvider services)
|
||||
AuditLog audit, TimeProvider time, IServiceProvider services)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
var failures = (await db.Jobs.ListAsync(JobState.Failed, FailedJobs, null, ct)).Items;
|
||||
var report = Report(options, state, jobs, time);
|
||||
var report = Report(options, state, time);
|
||||
var settings = JsonSerializer.Serialize(options, ServerOptionsJson.Default.ServerOptions);
|
||||
var encoders = Encoders(services.GetService<ProcessingService>());
|
||||
|
||||
@@ -64,7 +64,7 @@ public static class DiagnosticsEndpoints
|
||||
return Results.File(file, "application/zip", name);
|
||||
}
|
||||
|
||||
private static string Report(ServerOptions options, ServerState state, JobEngineHost jobs, TimeProvider time)
|
||||
private static string Report(ServerOptions options, ServerState state, TimeProvider time)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
sb.AppendLine(CultureInfo.InvariantCulture, $"Titano Server {SystemEndpoints.Version} ({options.ServerName})");
|
||||
@@ -75,7 +75,7 @@ public static class DiagnosticsEndpoints
|
||||
if (options.Database == DatabaseKind.Sqlite)
|
||||
sb.AppendLine("SQLite compile options: " + string.Join(' ', Titano.Data.Sqlite.SqliteDatabase.CompileOptions));
|
||||
sb.AppendLine(CultureInfo.InvariantCulture, $"TLS {options.TlsMode} {state.TlsFingerprint}");
|
||||
sb.AppendLine(CultureInfo.InvariantCulture, $"Workers {jobs.Workers}");
|
||||
sb.AppendLine(CultureInfo.InvariantCulture, $"Jobs one at a time, parallelism {options.Parallelism}, priority queue {(options.PriorityQueue ? "on" : "off")}");
|
||||
sb.AppendLine(CultureInfo.InvariantCulture, $"Archive {options.ArchivePath} ({Space(options.ArchivePath)})");
|
||||
sb.AppendLine(CultureInfo.InvariantCulture, $"Data {options.DataPath} ({Space(options.DataPath)})");
|
||||
sb.AppendLine(CultureInfo.InvariantCulture, $"Container {File.Exists("/.dockerenv")}");
|
||||
|
||||
@@ -54,7 +54,15 @@ public sealed class ServerOptions
|
||||
("TITANO_TLS_KEY", nameof(TlsKey), (o, v) => o.TlsKey = v),
|
||||
("TITANO_TRUSTED_PROXIES", nameof(TrustedProxies), (o, v) => o.TrustedProxies = v),
|
||||
("TITANO_LANG", nameof(Language), (o, v) => o.Language = v),
|
||||
("TITANO_WORKERS", nameof(Workers), (o, v) => o.Workers = Math.Max(1, Int("TITANO_WORKERS", v))),
|
||||
// The former name of TITANO_PARALLELISM (jobs run at once before owner review 1) still sets it, with a warning at start;
|
||||
// listed first, so TITANO_PARALLELISM wins when both are set.
|
||||
("TITANO_WORKERS", nameof(Parallelism), (o, v) =>
|
||||
{
|
||||
o.Parallelism = Int("TITANO_WORKERS", v);
|
||||
o.FormerWorkersVariable = true;
|
||||
}),
|
||||
("TITANO_PARALLELISM", nameof(Parallelism), (o, v) => o.Parallelism = Int("TITANO_PARALLELISM", v)),
|
||||
("TITANO_PRIORITY_QUEUE", nameof(PriorityQueue), (o, v) => o.PriorityQueue = bool.Parse(v)),
|
||||
("TITANO_DISCOVERY", nameof(Discovery), (o, v) => o.Discovery = bool.Parse(v)),
|
||||
("TITANO_LOG_LEVEL", nameof(LogLevel), (o, v) => o.LogLevel = Enum.Parse<LogLevel>(v, ignoreCase: true)),
|
||||
];
|
||||
@@ -109,7 +117,43 @@ public sealed class ServerOptions
|
||||
/// </summary>
|
||||
public string TrustedProxies { get; set; } = DefaultTrustedProxies;
|
||||
public string Language { get; set; } = "en";
|
||||
public int Workers { get; set; } = Math.Max(1, Environment.ProcessorCount / 2);
|
||||
|
||||
/// <summary>Highest <see cref="Parallelism"/>; a larger value from the environment or <c>server.json</c> is brought down to it.</summary>
|
||||
public const int MaxParallelism = 64;
|
||||
|
||||
/// <summary>
|
||||
/// Photos the running job processes at once (owner review 1: jobs run one at a time), 1 to <see cref="MaxParallelism"/>.
|
||||
/// Default: half the logical cores.
|
||||
/// </summary>
|
||||
public int Parallelism { get; set; } = Math.Clamp(Environment.ProcessorCount / 2, 1, MaxParallelism);
|
||||
|
||||
/// <summary>
|
||||
/// The priority queue (owner review 1): a job of a higher level makes the running one of a lower level yield, and that
|
||||
/// one resumes by itself afterwards. Off: jobs wait their turn (<see cref="Titano.Data.Jobs.JobPriorityQueue"/>).
|
||||
/// </summary>
|
||||
public bool PriorityQueue { get; set; }
|
||||
|
||||
/// <summary>Levels of the priority queue that differ from the defaults, by job kind (<c>render</c> → <c>high</c>).</summary>
|
||||
public Dictionary<string, string> JobPriorities { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// The former name of <see cref="Parallelism"/> in <c>server.json</c> (jobs run at once before owner review 1): a file
|
||||
/// that still has it sets the parallelism. Never written; saving settings drops it.
|
||||
/// </summary>
|
||||
[JsonPropertyName("Workers")]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public int? FormerWorkers
|
||||
{
|
||||
get => null;
|
||||
set
|
||||
{
|
||||
if (value is { } workers) Parallelism = workers;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>TITANO_WORKERS, the former name of TITANO_PARALLELISM, set the parallelism: the start says to rename it.</summary>
|
||||
[JsonIgnore]
|
||||
public bool FormerWorkersVariable { get; private set; }
|
||||
public bool Discovery { get; set; } = true;
|
||||
|
||||
/// <summary>Least severe level written to the console and the log files.</summary>
|
||||
@@ -197,7 +241,9 @@ public sealed class ServerOptions
|
||||
}
|
||||
locked.Add(setting);
|
||||
}
|
||||
options.Locked = locked;
|
||||
options.Locked = [.. locked.Distinct(StringComparer.Ordinal)];
|
||||
// The admin panel saves only values it accepts: one it cannot change (an environment variable) must be one of them.
|
||||
options.Parallelism = Math.Clamp(options.Parallelism, 1, MaxParallelism);
|
||||
options.Validate();
|
||||
return options;
|
||||
}
|
||||
|
||||
@@ -2,17 +2,26 @@ using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Titano.Core.IO;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Protocol;
|
||||
|
||||
namespace Titano.Server.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// The admin panel's view of the configuration (BRIEF §14.8 Settings). Saving writes <c>/data/server.json</c> (only the
|
||||
/// edited keys; secrets and environment values are never written) and applies what can change while running; ports,
|
||||
/// TLS, workers, chunk size and job history wait for a restart.
|
||||
/// edited keys; secrets and environment values are never written) and applies what can change while running, the
|
||||
/// parallelism and the priority queue included (owner review 1); ports, TLS, chunk size and job history wait for a restart.
|
||||
/// </summary>
|
||||
public sealed class ServerSettingsStore(ServerOptions options)
|
||||
{
|
||||
/// <summary>The kinds of job the server runs, in the order the admin panel lists their levels (downloads and uploads are a client's).</summary>
|
||||
public static IReadOnlyList<JobKind> Kinds { get; } =
|
||||
[
|
||||
JobKind.Render, JobKind.Import, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse, JobKind.DeepAnalyse, JobKind.Thumbs,
|
||||
JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move,
|
||||
];
|
||||
|
||||
private readonly Lock _gate = new();
|
||||
private ServerSettingsDto? _saved;
|
||||
|
||||
@@ -21,6 +30,9 @@ public sealed class ServerSettingsStore(ServerOptions options)
|
||||
lock (_gate) return _saved ?? Snapshot(options, restartRequired: false);
|
||||
}
|
||||
|
||||
/// <summary>The priority queue as the settings have it now (<see cref="ServerOptions.PriorityQueue"/>, <see cref="ServerOptions.JobPriorities"/>).</summary>
|
||||
public static JobPriorityQueue PriorityQueue(ServerOptions options) => JobPriorityQueue.From(options.PriorityQueue, options.JobPriorities);
|
||||
|
||||
/// <summary>Validates and saves; returns the error code and the offending setting, or null on success.</summary>
|
||||
public (string Code, string Setting)? Save(ServerSettingsDto request)
|
||||
{
|
||||
@@ -34,6 +46,8 @@ public sealed class ServerSettingsStore(ServerOptions options)
|
||||
|
||||
var file = File.Exists(options.SettingsFile) ? JsonNode.Parse(File.ReadAllText(options.SettingsFile)) as JsonObject ?? [] : [];
|
||||
foreach (var (name, value) in changes) file[name] = value;
|
||||
// The former name of the parallelism (jobs run at once before owner review 1) would set it again at the next start.
|
||||
if (changes.Any(c => c.Name == nameof(ServerOptions.Parallelism))) file.Remove("Workers");
|
||||
Directory.CreateDirectory(options.DataPath);
|
||||
AtomicFile.WriteAllText(options.SettingsFile, file.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
|
||||
|
||||
@@ -43,18 +57,44 @@ public sealed class ServerSettingsStore(ServerOptions options)
|
||||
options.MaxUploadBytes = request.MaxUploadBytes;
|
||||
options.TokenLifetimeDays = request.TokenLifetimeDays;
|
||||
options.UploadRetentionHours = request.UploadRetentionHours;
|
||||
options.Parallelism = request.Parallelism;
|
||||
options.PriorityQueue = request.PriorityQueue;
|
||||
options.JobPriorities = JobPriorityQueue.Changed(Levels(request.JobPriorities));
|
||||
var restart = request.HttpPort != options.HttpPort || request.HttpsPort != options.HttpsPort
|
||||
|| !string.Equals(request.TlsMode, options.TlsMode.ToString(), StringComparison.OrdinalIgnoreCase)
|
||||
|| request.TlsCert != options.TlsCert || request.TlsKey != options.TlsKey || request.Workers != options.Workers
|
||||
|| request.TlsCert != options.TlsCert || request.TlsKey != options.TlsKey
|
||||
|| request.ChunkSizeBytes != options.ChunkSizeBytes || request.JobHistoryDays != options.JobHistoryDays;
|
||||
_saved = request with { ServerName = request.ServerName.Trim(), Locked = [.. options.Locked], RestartRequired = restart, ProxyWarning = false };
|
||||
_saved = request with
|
||||
{
|
||||
ServerName = request.ServerName.Trim(),
|
||||
JobPriorities = Priorities(PriorityQueue(options)),
|
||||
Locked = [.. options.Locked],
|
||||
RestartRequired = restart,
|
||||
ProxyWarning = false,
|
||||
};
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static ServerSettingsDto Snapshot(ServerOptions o, bool restartRequired) => new(
|
||||
o.ServerName, o.HttpPort, o.HttpsPort, o.TlsMode.ToString().ToLowerInvariant(), o.TlsCert, o.TlsKey, o.Language, o.Workers, o.Discovery,
|
||||
o.MaxUploadBytes, o.ChunkSizeBytes, o.JobHistoryDays, o.TokenLifetimeDays, o.UploadRetentionHours, [.. o.Locked], restartRequired, ProxyWarning: false);
|
||||
o.ServerName, o.HttpPort, o.HttpsPort, o.TlsMode.ToString().ToLowerInvariant(), o.TlsCert, o.TlsKey, o.Language, o.Parallelism, o.PriorityQueue,
|
||||
Priorities(PriorityQueue(o)), o.Discovery, o.MaxUploadBytes, o.ChunkSizeBytes, o.JobHistoryDays, o.TokenLifetimeDays, o.UploadRetentionHours,
|
||||
[.. o.Locked], restartRequired, ProxyWarning: false);
|
||||
|
||||
/// <summary>The level of every kind the server runs in <paramref name="queue"/>.</summary>
|
||||
private static List<JobPriorityDto> Priorities(JobPriorityQueue queue) =>
|
||||
[.. Kinds.Select(k => new JobPriorityDto(JobWire.Kind(k), JobPriorityQueue.Wire(queue.LevelOf(k))))];
|
||||
|
||||
/// <summary>The levels a request sets; <see cref="Validate"/> has checked their names.</summary>
|
||||
private static Dictionary<JobKind, JobKindPriority> Levels(IReadOnlyList<JobPriorityDto>? priorities)
|
||||
{
|
||||
var levels = new Dictionary<JobKind, JobKindPriority>();
|
||||
foreach (var p in priorities ?? [])
|
||||
{
|
||||
if (JobWire.TryParseKind(p.Kind, out var kind) && JobPriorityQueue.TryParse(p.Level, out var level)) levels[kind] = level;
|
||||
}
|
||||
return levels;
|
||||
}
|
||||
|
||||
private static string? Validate(ServerSettingsDto r)
|
||||
{
|
||||
@@ -65,7 +105,9 @@ public sealed class ServerSettingsStore(ServerOptions options)
|
||||
if (tls == TlsMode.Pem && (string.IsNullOrWhiteSpace(r.TlsCert) || !File.Exists(r.TlsCert))) return nameof(ServerOptions.TlsCert);
|
||||
if (tls == TlsMode.Pem && (string.IsNullOrWhiteSpace(r.TlsKey) || !File.Exists(r.TlsKey))) return nameof(ServerOptions.TlsKey);
|
||||
if (!Languages.Shipped.Contains(r.Language, StringComparer.OrdinalIgnoreCase)) return nameof(ServerOptions.Language);
|
||||
if (r.Workers is < 1 or > 64) return nameof(ServerOptions.Workers);
|
||||
if (r.Parallelism is < 1 or > ServerOptions.MaxParallelism) return nameof(ServerOptions.Parallelism);
|
||||
if ((r.JobPriorities ?? []).Any(p => !JobWire.TryParseKind(p.Kind, out var kind) || !Kinds.Contains(kind) || !JobPriorityQueue.TryParse(p.Level, out _)))
|
||||
return nameof(ServerOptions.JobPriorities);
|
||||
if (r.MaxUploadBytes < 1024 * 1024) return nameof(ServerOptions.MaxUploadBytes);
|
||||
if (r.ChunkSizeBytes is < 64 * 1024 or > 64 * 1024 * 1024) return nameof(ServerOptions.ChunkSizeBytes);
|
||||
if (r.JobHistoryDays is < 1 or > 3650) return nameof(ServerOptions.JobHistoryDays);
|
||||
@@ -89,7 +131,13 @@ public sealed class ServerSettingsStore(ServerOptions options)
|
||||
Add(nameof(ServerOptions.TlsCert), a.TlsCert, b.TlsCert, v => v is null ? null : JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.TlsKey), a.TlsKey, b.TlsKey, v => v is null ? null : JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.Language), a.Language, b.Language, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.Workers), a.Workers, b.Workers, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.Parallelism), a.Parallelism, b.Parallelism, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.PriorityQueue), a.PriorityQueue, b.PriorityQueue, v => JsonValue.Create(v));
|
||||
// Only levels that differ from the defaults are stored, as the desktop does.
|
||||
var before = JobPriorityQueue.Changed(Levels(a.JobPriorities));
|
||||
var after = JobPriorityQueue.Changed(Levels(b.JobPriorities));
|
||||
if (!before.OrderBy(l => l.Key).SequenceEqual(after.OrderBy(l => l.Key)))
|
||||
changes.Add((nameof(ServerOptions.JobPriorities), new JsonObject(after.Select(l => KeyValuePair.Create(l.Key, (JsonNode?)JsonValue.Create(l.Value))))));
|
||||
Add(nameof(ServerOptions.Discovery), a.Discovery, b.Discovery, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.MaxUploadBytes), a.MaxUploadBytes, b.MaxUploadBytes, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.ChunkSizeBytes), a.ChunkSizeBytes, b.ChunkSizeBytes, v => JsonValue.Create(v));
|
||||
|
||||
@@ -36,7 +36,10 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
|
||||
TITANO_ARCHIVE_PATH TITANO_DATA_PATH TITANO_SERVER_NAME TITANO_ADMIN_USER TITANO_ADMIN_PASSWORD
|
||||
TITANO_DB (postgres | sqlite | connection string) TITANO_DB_HOST TITANO_DB_PORT TITANO_DB_NAME TITANO_DB_USER
|
||||
TITANO_DB_PASSWORD TITANO_DB_SSLMODE TITANO_HTTP_PORT TITANO_HTTPS_PORT TITANO_TLS_MODE (auto | pem | proxy)
|
||||
TITANO_TLS_CERT TITANO_TLS_KEY TITANO_LANG TITANO_WORKERS
|
||||
TITANO_TLS_CERT TITANO_TLS_KEY TITANO_LANG
|
||||
TITANO_PARALLELISM photos the running job processes at once (jobs run one at a time; default: half the
|
||||
cores); TITANO_WORKERS, its former name, still sets it
|
||||
TITANO_PRIORITY_QUEUE a job of a higher level pauses the running one, which resumes afterwards (true | false)
|
||||
TITANO_LOG_LEVEL (Trace | Debug | Information | Warning | Error)
|
||||
TITANO_DISCOVERY LAN beacon (true | false); in a container it needs host networking
|
||||
TITANO_PUBLIC_HTTP_PORT, TITANO_PUBLIC_HTTPS_PORT
|
||||
|
||||
@@ -88,6 +88,11 @@ public static class ServerHost
|
||||
+ "they could put a link in place of a folder and redirect the files the server moves. Let only those accounts change it (others may read it).",
|
||||
options.ArchivePath);
|
||||
}
|
||||
if (options.FormerWorkersVariable)
|
||||
{
|
||||
app.Logger.LogWarning("TITANO_WORKERS is the former name of TITANO_PARALLELISM: jobs now run one at a time, and the value is how many "
|
||||
+ "photos the running job processes at once. Rename the variable.");
|
||||
}
|
||||
app.Lifetime.ApplicationStopping.Register(() => app.Logger.LogInformation("Titano Server stopping"));
|
||||
app.Lifetime.ApplicationStopped.Register(() => database.DisposeAsync().AsTask().GetAwaiter().GetResult());
|
||||
return app;
|
||||
|
||||
@@ -12,7 +12,8 @@ namespace Titano.Server.Jobs;
|
||||
/// <summary>
|
||||
/// Hosts the server's <see cref="JobEngine"/> (BRIEF §14.6) with the <see cref="IJobHandler"/>s registered in DI (directly or
|
||||
/// through <see cref="IJobHandlerProvider"/>s) and
|
||||
/// relays its state changes and progress as WebSocket events. Render jobs run here only when the registered render
|
||||
/// relays its state changes and progress as WebSocket events. Jobs run one at a time, the parallelism working inside the
|
||||
/// running one, in the order of the priority queue of the settings (owner review 1). Render jobs run here only when the registered render
|
||||
/// handler accepts them (<see cref="ISelectiveJobHandler"/>: managed formats, and MP4 jobs no render node can take);
|
||||
/// render nodes claim the others (BRIEF §14.5, §14.7). On shutdown running jobs stay marked running and are requeued from their checkpoints at the next start.
|
||||
/// </summary>
|
||||
@@ -34,26 +35,23 @@ public sealed class JobEngineHost : IHostedService
|
||||
// A render handler must be selective: a plain one would take the jobs that need a render node's encoder.
|
||||
var local = handlers.Concat(providers.SelectMany(p => p.CreateJobHandlers())).Where(h => h.Kind != JobKind.Render || h is ISelectiveJobHandler).ToList();
|
||||
_kinds = [.. local.Select(h => h.Kind)];
|
||||
// Without handlers no worker starts: an engine with an empty kind list would claim every kind.
|
||||
Workers = _kinds.Count == 0 ? 0 : options.Workers;
|
||||
// Without handlers no worker starts (StartAsync): an engine with an empty kind list would claim every kind.
|
||||
Engine = new JobEngine(db, local, new JobEngineOptions
|
||||
{
|
||||
Workers = Workers,
|
||||
WorkerId = WorkerId,
|
||||
Kinds = _kinds,
|
||||
HistoryRetention = TimeSpan.FromDays(options.JobHistoryDays),
|
||||
PriorityQueue = () => ServerSettingsStore.PriorityQueue(options),
|
||||
});
|
||||
Engine.JobChanged += OnJobChanged;
|
||||
Engine.Progress += OnProgress;
|
||||
}
|
||||
|
||||
/// <summary>Node id stamped on jobs this server runs (its workers use <c>WorkerId#n</c>).</summary>
|
||||
/// <summary>Node id stamped on jobs this server runs.</summary>
|
||||
public static string WorkerId { get; } = "server:" + Environment.MachineName;
|
||||
|
||||
public JobEngine Engine { get; }
|
||||
|
||||
public int Workers { get; }
|
||||
|
||||
/// <summary>True when a job of <paramref name="kind"/> has somewhere to run: a local handler, or render nodes for renders.</summary>
|
||||
public bool CanRun(JobKind kind) => kind == JobKind.Render || _kinds.Contains(kind);
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ using Titano.Core.Imaging.Decoders;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Archiving;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Server.Configuration;
|
||||
|
||||
namespace Titano.Server.Storage;
|
||||
|
||||
@@ -19,8 +20,13 @@ public static class ArchiveModule
|
||||
|
||||
public static void Register(IServiceCollection services)
|
||||
{
|
||||
services.AddSingleton(sp => new ArchiveService(sp.GetRequiredService<TitanoDatabase>(),
|
||||
new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = Owner, ImagesAfterScan = true }));
|
||||
services.AddSingleton(sp =>
|
||||
{
|
||||
var options = sp.GetRequiredService<ServerOptions>();
|
||||
// Photos the running job processes at once: the settings' value as it is when each sequence starts (owner review 1).
|
||||
return new ArchiveService(sp.GetRequiredService<TitanoDatabase>(),
|
||||
new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = Owner, ImagesAfterScan = true, Parallelism = () => options.Parallelism });
|
||||
});
|
||||
services.AddSingleton<IArchiveIngest>(sp => sp.GetRequiredService<ArchiveService>().Ingest);
|
||||
services.AddSingleton<IJobHandlerProvider>(sp => sp.GetRequiredService<ArchiveService>());
|
||||
services.AddSingleton<IFrameAssetLocator, ArchiveAssetLocator>();
|
||||
|
||||
@@ -29,13 +29,21 @@ public static class ProcessingModule
|
||||
{
|
||||
var db = sp.GetRequiredService<TitanoDatabase>();
|
||||
var events = sp.GetRequiredService<EventHub>();
|
||||
var options = sp.GetRequiredService<ServerOptions>();
|
||||
return new ProcessingService(db, new ProcessingOptions
|
||||
{
|
||||
Archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner },
|
||||
Archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner, Parallelism = () => options.Parallelism },
|
||||
// Analyses and renders take the parallelism as it is when they start, and the one job that runs has the host's
|
||||
// memory budget for its frame window, as on the desktop (owner review 1).
|
||||
Tune = basis =>
|
||||
{
|
||||
var tuned = basis.WithParallelism(options.Parallelism);
|
||||
return tuned with { FrameWindow = tuned.FrameWindow with { MemoryBudget = basis.Archive.MemoryBudget() } };
|
||||
},
|
||||
Encoders = [new ManagedEncoderProvider()],
|
||||
Host = EncoderHost.Server,
|
||||
AwaitsRenderNode = sp.GetRequiredService<RenderNodeAvailability>().AwaitsNodeAsync,
|
||||
ProducedBy = sp.GetRequiredService<ServerOptions>().ServerName,
|
||||
ProducedBy = options.ServerName,
|
||||
SequenceChanged = async (id, change, ct) =>
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, ct) is { } sequence)
|
||||
|
||||
@@ -12,6 +12,8 @@ namespace Titano.Tools.Commands;
|
||||
/// <c>i18n export --out dir</c>: one JSON per culture for the web admin.
|
||||
/// <c>i18n missing --culture xx [--all]</c>: untranslated (or all) keys as TSV for a translator or reviewer.
|
||||
/// <c>i18n import --culture xx file.tsv</c>: merges translated <c>key<TAB>text</c> rows into the culture's resx files.
|
||||
/// <c>i18n prune</c>: removes from every translation the keys English no longer has (renamed or removed keys), which
|
||||
/// <c>check</c> reports as orphans.
|
||||
/// </summary>
|
||||
internal sealed partial class I18nCommand : ICommand
|
||||
{
|
||||
@@ -19,7 +21,7 @@ internal sealed partial class I18nCommand : ICommand
|
||||
private static readonly HashSet<string> SentenceAreas = new(StringComparer.Ordinal) { "Tooltips", "Errors", "Advisor" };
|
||||
|
||||
public string Name => "i18n";
|
||||
public string Summary => "check | export --out <dir> | missing --culture <c> [--all] | import --culture <c> <tsv>";
|
||||
public string Summary => "check | export --out <dir> | missing --culture <c> [--all] | import --culture <c> <tsv> | prune";
|
||||
|
||||
public Task<int> RunAsync(string[] args)
|
||||
{
|
||||
@@ -34,6 +36,7 @@ internal sealed partial class I18nCommand : ICommand
|
||||
"missing" => Missing(catalog, a.Get("culture") ?? throw new ToolException("--culture <code> required"), a.Has("all")),
|
||||
"import" => Import(root, catalog, a.Get("culture") ?? throw new ToolException("--culture <code> required"),
|
||||
a.Positional.ElementAtOrDefault(1) ?? throw new ToolException("TSV file required")),
|
||||
"prune" => Prune(Path.Combine(root, "i18n"), catalog),
|
||||
_ => throw new ToolException($"Unknown i18n subcommand '{sub}'"),
|
||||
});
|
||||
}
|
||||
@@ -233,6 +236,44 @@ internal sealed partial class I18nCommand : ICommand
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the orphan keys of every translation under <paramref name="dir"/> (those <see cref="Check"/> reports: not in
|
||||
/// English and not a plural form of an English plural key), rewriting only the files that had some, as
|
||||
/// <see cref="Import"/> writes them. English is the source and is never touched. Returns the number of keys removed.
|
||||
/// </summary>
|
||||
internal static int PruneOrphans(string dir, Catalog catalog)
|
||||
{
|
||||
var en = catalog.Cultures["en"];
|
||||
var removed = 0;
|
||||
foreach (var cultureDir in Directory.EnumerateDirectories(dir).Order(StringComparer.Ordinal))
|
||||
{
|
||||
var culture = Path.GetFileName(cultureDir);
|
||||
if (culture.Equals("en", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
foreach (var path in Directory.EnumerateFiles(cultureDir, "*.resx").Order(StringComparer.Ordinal))
|
||||
{
|
||||
var values = new SortedDictionary<string, string>(StringComparer.Ordinal);
|
||||
var orphans = 0;
|
||||
foreach (var data in XDocument.Load(path).Root!.Elements("data"))
|
||||
{
|
||||
var key = (string)data.Attribute("name")!;
|
||||
if (en.ContainsKey(key) || PluralStem(key, en) is not null) values[key] = (string?)data.Element("value") ?? string.Empty;
|
||||
else orphans++;
|
||||
}
|
||||
if (orphans == 0) continue;
|
||||
WriteResx(path, values);
|
||||
removed += orphans;
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
private static int Prune(string dir, Catalog catalog)
|
||||
{
|
||||
var removed = PruneOrphans(dir, catalog);
|
||||
Console.WriteLine($"i18n: {removed} orphan key(s) removed");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static void WriteResx(string path, IEnumerable<KeyValuePair<string, string>> values)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
|
||||
Reference in new issue
Block a user