feat: owner review 2 phase 2: scheduled jobs and log settings (#10)
CI / Build and test (push) Successful in 7m0s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 13m28s
CI / PostgreSQL 16 integration (push) Successful in 5m52s
CI / PostgreSQL 17 integration (push) Successful in 4m50s
CI / Docker image (push) Successful in 1m4s
Release / Server image (push) Successful in 1m35s
CI / Build and test (push) Successful in 7m0s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 13m28s
CI / PostgreSQL 16 integration (push) Successful in 5m52s
CI / PostgreSQL 17 integration (push) Successful in 4m50s
CI / Docker image (push) Successful in 1m4s
Release / Server image (push) Successful in 1m35s
- Jobs > Scheduled on the desktop and the admin panel. Every timer that queued work is now a visible system schedule: archive scan, upload clean-up, index backup, job-history and audit clean-ups, desktop housekeeping. New actions: verify, thumbnails, proxies, analysis, maintenance, backup, clean-ups, reports. - The scheduler: migration 0007, in-house recurrence, compare-and-set claim, catch-up, scan at start. - Log settings: levels, retention, size parts, total limit, daily or hourly rotation, audit retention, diagnostics share; the server writes Debug/Trace to its files again; logging never fails a job. Upgrade: CHRONOS_LOG_LEVEL set in an existing container locks both levels; migration 0007 is one-way. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #10.
This commit is contained in:
1 parent
1f089888e8
commit
af9eeaab9b
349 files changed
+28341
-1304
No files matched your search
@@ -22,19 +22,22 @@ using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Protocol.Client;
|
||||
|
||||
namespace Chronos.App.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// Composition root of local mode (BRIEF §4.4): the SQLite index under the data folder (migrated on open, a restore
|
||||
/// staged in Settings › Advanced carried out first, then copied once a day into the backups folder), the archive engine
|
||||
/// (WIC first, then managed decoders), the analysis and render engine (the same decoders; Media Foundation, then
|
||||
/// managed encoders), the one <see cref="JobEngine"/> of this PC with the handlers of <see cref="CreateJobHandlers"/>,
|
||||
/// thumbnails, the server session, the render node, the encoder and format inventories, the update check and the sync
|
||||
/// with the signed-in server (<see cref="SyncHost"/>). Started after the window shows, stopped when the app exits. The
|
||||
/// archive at Settings › Archive's folder is reopened at start and rescanned every <see cref="ScanInterval"/>, as is one
|
||||
/// chosen later (BRIEF §7: polling, no file-system watchers). Jobs follow Settings › Rendering and Analysis from the
|
||||
/// staged in Settings › Advanced carried out first), the archive engine (WIC first, then managed decoders), the analysis
|
||||
/// and render engine (the same decoders; Media Foundation, then managed encoders), the one <see cref="JobEngine"/> of
|
||||
/// this PC with the handlers of <see cref="CreateJobHandlers"/>, the <see cref="Data.Scheduling.Scheduler"/> that queues the
|
||||
/// recurring work (owner review 2, R10: the archive scan, the daily index backup and the housekeeping are its system
|
||||
/// schedules, <see cref="DesktopScheduleHost"/>), thumbnails, the server session, the render node, the encoder and format
|
||||
/// inventories, the update check and the sync with the signed-in server (<see cref="SyncHost"/>). Started after the
|
||||
/// window shows, stopped when the app exits. The archive at Settings › Archive's folder is reopened at start before the
|
||||
/// scheduler starts, and while it is unplugged every <see cref="ReopenInterval"/> until it is back; the schedules follow
|
||||
/// the folder, also one chosen later (BRIEF §7: polling, no file-system watchers). Jobs follow Settings › Rendering and Analysis from the
|
||||
/// next one on (memory budget, quality profile, analysis parameters through <see cref="ProcessingTuning"/>; parallelism
|
||||
/// as the engine's workers). The render node runs while the user offers this PC (<see cref="AppSettings.RenderNodeOptIn"/>)
|
||||
/// and a server session is open (never in capture mode). Renders and the render node use hardware encoders as
|
||||
@@ -52,9 +55,8 @@ public sealed class AppServices : IAsyncDisposable
|
||||
private static readonly Lazy<HttpClient> DownloadHttp = new(() => new HttpClient { Timeout = Timeout.InfiniteTimeSpan });
|
||||
private readonly CancellationTokenSource _stopping = new();
|
||||
private readonly Dictionary<Guid, Guid> _scans = [];
|
||||
private Task _polling = Task.CompletedTask;
|
||||
private Task _backups = Task.CompletedTask;
|
||||
private PeriodicTimer? _pollTimer;
|
||||
private readonly TaskCompletionSource<bool> _schedulerReady = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private Task _schedules = Task.CompletedTask;
|
||||
private WicDecoderProvider? _wic;
|
||||
private readonly RenderNodeHost _renderNode;
|
||||
private ServerSession _server = null!;
|
||||
@@ -68,6 +70,7 @@ public sealed class AppServices : IAsyncDisposable
|
||||
_renderNode = new RenderNodeHost(StartRenderNode);
|
||||
ArchiveSetup = new EngineArchiveSetup(this);
|
||||
Sync = new SyncHost(this);
|
||||
ScheduleHost = new DesktopScheduleHost(settings, () => Database, () => Archives);
|
||||
Server = new ServerSession(settings, saveSettings, new ChronosServerApiFactory(), new DpapiTokenProtector());
|
||||
Encoders = new MediaFoundationInventory();
|
||||
Formats = new WicFormatInventory(() => _wic);
|
||||
@@ -113,8 +116,20 @@ public sealed class AppServices : IAsyncDisposable
|
||||
/// <summary>Decode tier per format on this PC and the missing codec extensions (Settings › Formats).</summary>
|
||||
public IFormatInventory Formats { get; set; }
|
||||
|
||||
/// <summary>Time between the rescans of the open archive (Settings › Archive).</summary>
|
||||
public TimeSpan ScanInterval => TimeSpan.FromMinutes(int.Clamp(Settings.ScanIntervalMinutes, 1, 24 * 60));
|
||||
/// <summary>How often an archive that was unplugged at start is looked for again, until it is back.</summary>
|
||||
public static TimeSpan ReopenInterval { get; } = TimeSpan.FromMinutes(1);
|
||||
|
||||
/// <summary>What the scheduler works with on this PC: its zone, the current archive, the system schedules.</summary>
|
||||
public DesktopScheduleHost ScheduleHost { get; }
|
||||
|
||||
/// <summary>The schedules of this PC (Jobs › Scheduled); null until they run (<see cref="SchedulerReady"/>).</summary>
|
||||
public Scheduler? Scheduler { get; private set; }
|
||||
|
||||
/// <summary>True once <see cref="Scheduler"/> runs; false when it never will (no index, no engine, it failed, the app stops).</summary>
|
||||
public Task<bool> SchedulerReady => _schedulerReady.Task;
|
||||
|
||||
/// <summary>The clock of the schedules; the capture stops it at its sample moment.</summary>
|
||||
public TimeProvider SchedulerTime { get; set; } = TimeProvider.System;
|
||||
|
||||
/// <summary>How the restore staged in Settings › Advanced went when the index opened; null when none was staged.</summary>
|
||||
public StagedRestoreResult? StagedRestore { get; private set; }
|
||||
@@ -186,13 +201,13 @@ public sealed class AppServices : IAsyncDisposable
|
||||
public void SavePreferences() => SaveSettingsAction();
|
||||
|
||||
/// <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.
|
||||
/// A review of the priority queue (Settings › Rendering): turned on, it may make the running job yield at once; and a
|
||||
/// pass of the schedules, whose runs read the settings. The parallelism applies from the next sequence or job.
|
||||
/// </summary>
|
||||
public void ApplyJobSettings()
|
||||
{
|
||||
Engine?.Wake();
|
||||
if (_pollTimer is { } timer && timer.Period != ScanInterval) timer.Period = ScanInterval;
|
||||
Scheduler?.Wake();
|
||||
}
|
||||
|
||||
/// <summary>Photos the running job of this PC processes at once (Settings › Rendering › Parallelism, Auto: half the logical cores).</summary>
|
||||
@@ -216,8 +231,9 @@ public sealed class AppServices : IAsyncDisposable
|
||||
|
||||
/// <summary>
|
||||
/// Opens (or creates) the index at <paramref name="databasePath"/>, migrates it (after a restore staged in Settings ›
|
||||
/// Advanced replaced it, which needs no open index: it also recovers one that no longer opens), starts the job engine
|
||||
/// and the daily backups.
|
||||
/// Advanced replaced it, which needs no open index: it also recovers one that no longer opens), starts the job engine,
|
||||
/// then in the background reopens the archive and starts the schedules (<see cref="SchedulerReady"/>, false at once
|
||||
/// when the index or the engine does not open).
|
||||
/// </summary>
|
||||
public async Task OpenAsync(string databasePath, CancellationToken ct = default)
|
||||
{
|
||||
@@ -231,31 +247,44 @@ public sealed class AppServices : IAsyncDisposable
|
||||
{
|
||||
OpenError = ex;
|
||||
Log.Error("app", "The index could not be opened", ex);
|
||||
// No index, no schedules: Jobs › Scheduled says so instead of waiting for them.
|
||||
_schedulerReady.TrySetResult(false);
|
||||
return;
|
||||
}
|
||||
await StartJobsAsync(Database, startEngine: true, ct);
|
||||
Thumbnails = new ThumbnailService(Database, Settings.ThumbnailMemoryItems);
|
||||
Devices.Start();
|
||||
var database = Database;
|
||||
_backups = Task.Run(() => DatabaseBackups.RunDailyAsync(database, Environment.BackupDirectory, null, _stopping.Token));
|
||||
_polling = PollAsync(_stopping.Token);
|
||||
try
|
||||
{
|
||||
await StartJobsAsync(Database, startEngine: true, ct);
|
||||
Thumbnails = new ThumbnailService(Database, Settings.ThumbnailMemoryItems);
|
||||
Devices.Start();
|
||||
}
|
||||
catch
|
||||
{
|
||||
_schedulerReady.TrySetResult(false);
|
||||
throw;
|
||||
}
|
||||
_schedules = RunSchedulesAsync(_stopping.Token);
|
||||
}
|
||||
|
||||
/// <summary>Uses an already open index (capture, tests) instead of opening one; sample data keeps the engine stopped.</summary>
|
||||
/// <summary>
|
||||
/// Uses an already open index (capture, tests) instead of opening one, and starts the schedules (no archive to reopen);
|
||||
/// sample data keeps the engine stopped.
|
||||
/// </summary>
|
||||
public async Task AttachAsync(ChronosDatabase database, bool startEngine = true, CancellationToken ct = default)
|
||||
{
|
||||
Database = database;
|
||||
await StartJobsAsync(database, startEngine, ct);
|
||||
Thumbnails = new ThumbnailService(database, Settings.ThumbnailMemoryItems);
|
||||
await StartSchedulerAsync(ct);
|
||||
}
|
||||
|
||||
/// <summary>Stops polling, the render node and the engine, then closes the index. The app's exit waits for this on the UI
|
||||
/// thread, so nothing here continues on it.</summary>
|
||||
/// <summary>Stops the schedules, the render node and the engine, then closes the index. The app's exit waits for this on
|
||||
/// the UI thread, so nothing here continues on it.</summary>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _stopping.CancelAsync().ConfigureAwait(false);
|
||||
await _polling.ConfigureAwait(false);
|
||||
await _backups.ConfigureAwait(false);
|
||||
await _schedules.ConfigureAwait(false);
|
||||
_schedulerReady.TrySetResult(false);
|
||||
if (Scheduler is not null) await Scheduler.DisposeAsync().ConfigureAwait(false);
|
||||
_stopping.Dispose();
|
||||
_server.PropertyChanged -= OnServerChanged;
|
||||
await _renderNode.DisposeAsync().ConfigureAwait(false);
|
||||
@@ -268,66 +297,101 @@ public sealed class AppServices : IAsyncDisposable
|
||||
if (Database is not null) await Database.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The period of the rescans while they run (Settings › Archive › Rescan every); null before the index opens.</summary>
|
||||
internal TimeSpan? PollingPeriod => _pollTimer?.Period;
|
||||
|
||||
/// <summary>
|
||||
/// One rescan of the polling, off the UI thread: the archive the Import and Archive screens work on
|
||||
/// (<see cref="CurrentArchive"/>, the one at Settings › Archive's folder) first takes the settings another process
|
||||
/// sharing it wrote into its archive.json (also on a read-only share), then gets an incremental scan while it is
|
||||
/// online. Returns that archive; null when the index holds none.
|
||||
/// At start, off the UI thread: reopens the archive at Settings › Archive's folder (a moved one relinked, interrupted
|
||||
/// renames finished), then starts the schedules, whose first pass settles the runs missed while Chronos was closed, and
|
||||
/// runs the archive scan once, as the rescans did at start (<see cref="ScanNowAsync"/>). An archive whose archive.json is
|
||||
/// not there (an unplugged drive) is looked for every <see cref="ReopenInterval"/> until it is back, then scanned and the
|
||||
/// schedules look at once for a due run; unless the folder changed meanwhile: whatever changed it opened the new
|
||||
/// archive. The app's exit waits for this on the UI thread.
|
||||
/// </summary>
|
||||
internal Task<Archive?> RescanAsync(CancellationToken ct = default) => Task.Run(async () =>
|
||||
{
|
||||
if (Database is not { } db || Archives is not { } archives) return null;
|
||||
var archive = CurrentArchive.Pick(await db.Archives.ListAsync(ct).ConfigureAwait(false), Settings.LastArchivePath);
|
||||
if (archive is null) return null;
|
||||
var availability = ArchiveService.GetAvailability(archive);
|
||||
if (availability != ArchiveAvailability.Offline) await archives.RefreshSettingsAsync(archive.Id, ct).ConfigureAwait(false);
|
||||
if (availability == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct).ConfigureAwait(false);
|
||||
return archive;
|
||||
}, ct);
|
||||
|
||||
/// <summary>
|
||||
/// Rescans the archive now and every <see cref="ScanInterval"/> (<see cref="RescanAsync"/>) until the app exits, which
|
||||
/// waits for it on the UI thread. Each rescan follows the archive folder: one chosen on the first run, in Settings or
|
||||
/// by a relink is rescanned from the next tick on, the one before no longer. The archive at the folder of the start is
|
||||
/// first reopened (a moved one relinked, interrupted renames finished), at each tick until its archive.json is there
|
||||
/// (an unplugged drive), unless the folder changed meanwhile: whatever changed it opened the new archive.
|
||||
/// </summary>
|
||||
private async Task PollAsync(CancellationToken ct)
|
||||
private async Task RunSchedulesAsync(CancellationToken ct)
|
||||
{
|
||||
var reopen = Settings.LastArchivePath is { Length: > 0 } start ? start : null;
|
||||
// Settings › Archive changes the period of this timer (ApplyJobSettings).
|
||||
using var timer = _pollTimer = new PeriodicTimer(ScanInterval);
|
||||
try
|
||||
{
|
||||
do
|
||||
if (reopen is not null && await ReopenAsync(reopen, ct).ConfigureAwait(false)) reopen = null;
|
||||
var started = SchedulerTime.GetUtcNow();
|
||||
await StartSchedulerAsync(ct).ConfigureAwait(false);
|
||||
if (reopen is null)
|
||||
{
|
||||
if (reopen is not null
|
||||
&& (!string.Equals(reopen, Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase) || await ReopenAsync(reopen, ct).ConfigureAwait(false)))
|
||||
reopen = null;
|
||||
try
|
||||
{
|
||||
await RescanAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or ArgumentException)
|
||||
{
|
||||
// The next tick tries again (a share that dropped, an archive removed from the index meanwhile).
|
||||
Log.Warning("archive", "The archive could not be rescanned", ex);
|
||||
}
|
||||
await ScanNowAsync(started, ct).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
using var timer = new PeriodicTimer(ReopenInterval);
|
||||
while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
if (!string.Equals(reopen, Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase)) return;
|
||||
if (!await ReopenAsync(reopen, ct).ConfigureAwait(false)) continue;
|
||||
await ScanNowAsync(null, ct).ConfigureAwait(false);
|
||||
Scheduler?.Wake();
|
||||
return;
|
||||
}
|
||||
while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false));
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
// The exit waits for this task: nothing it throws may stop the app from closing.
|
||||
Log.Error("schedules", "The archive could not be reopened or the schedules started", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_pollTimer = null;
|
||||
_schedulerReady.TrySetResult(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the archive scan schedule once now when it is enabled (owner review 2, R10: the archive was opened or is back),
|
||||
/// unless it ran since <paramref name="since"/> (the first pass fired it) or its scan is still pending.
|
||||
/// </summary>
|
||||
private async Task ScanNowAsync(DateTimeOffset? since, CancellationToken ct)
|
||||
{
|
||||
if (Scheduler is not { } scheduler) return;
|
||||
try
|
||||
{
|
||||
await scheduler.RunSystemNowAsync(DesktopScheduleHost.ArchiveScan, since, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException)
|
||||
{
|
||||
Log.Warning("schedules", "The archive scan could not be run now; its schedule runs the next one", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts <see cref="Scheduler"/> on this PC's engine: it seeds the system schedules and runs its first pass before
|
||||
/// <see cref="SchedulerReady"/> turns true. Without an engine, or when the schedules cannot be read, there is none.
|
||||
/// </summary>
|
||||
private async Task StartSchedulerAsync(CancellationToken ct)
|
||||
{
|
||||
if (Database is not { } db || Engine is not { } engine || Scheduler is not null)
|
||||
{
|
||||
_schedulerReady.TrySetResult(Scheduler is not null);
|
||||
return;
|
||||
}
|
||||
var scheduler = new Scheduler(db, engine, new SchedulerOptions { Time = SchedulerTime });
|
||||
try
|
||||
{
|
||||
await Task.Run(() => scheduler.StartAsync(ScheduleHost, ct), ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException or ArgumentException)
|
||||
{
|
||||
Log.Error("schedules", "The schedules could not be started; nothing recurring runs until the next start", ex);
|
||||
await scheduler.DisposeAsync().ConfigureAwait(false);
|
||||
_schedulerReady.TrySetResult(false);
|
||||
return;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
await scheduler.DisposeAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
Scheduler = scheduler;
|
||||
Log.Info("schedules", "Schedules started");
|
||||
_schedulerReady.TrySetResult(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the archive at <paramref name="root"/> again as at open; false while its archive.json is not there. A
|
||||
/// damaged or newer one is not tried again: the archive the index holds at the folder is still rescanned.
|
||||
@@ -385,6 +449,9 @@ public sealed class AppServices : IAsyncDisposable
|
||||
Decoder = DecoderFactory.CreateClient(_wic),
|
||||
Parallelism = () => Parallelism,
|
||||
MemoryBudget = () => ProcessingTuning.MemoryBudget(Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes),
|
||||
// The housekeeping schedule trims the cache to Settings › Storage › Cache limit (owner review 2, R10).
|
||||
CleanupSteps = [new CacheTrimStep(() => CacheStore.Folder(Environment, Settings), () => Settings.CacheLimitGb * (1L << 30))],
|
||||
BackupDirectory = Environment.BackupDirectory,
|
||||
};
|
||||
Archives = new ArchiveService(database, archive);
|
||||
Processing = new ProcessingService(database, ProcessingOptions(archive));
|
||||
|
||||
Reference in new issue
Block a user