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

- 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:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-27 11:19:26 +01:00
1 parent 1f089888e8
commit af9eeaab9b
349 files changed
+28341 -1304

No files matched your search

@@ -0,0 +1,55 @@
using Chronos.Core.Diagnostics;
namespace Chronos.App.Infrastructure;
/// <summary>
/// Settings › Advanced › Logs applied to this PC's log files (owner review 2, R11): the level, retention, size limits and
/// rotation of the <see cref="FileLogSink"/> App starts with, and the engine's <see cref="Log.MinimumLevel"/> (the files
/// are the only output outside screenshots). Values outside the ranges Settings offers are brought within them, and a
/// total below one file is raised to that file (<see cref="LogFileOptions.TotalBelowFile"/>), which the server refuses.
/// </summary>
public static class AppLogging
{
public const int DefaultDiagnosticsLogMb = (int)(DiagnosticsArchive.DefaultLogTailBytes / LogFileOptions.BytesPerMb);
public const int MaxRetentionDays = 3650;
public const int MaxFileMb = 10 * 1024;
public const int MaxTotalMb = 1024 * 1024;
public const int MaxDiagnosticsLogMb = 1024;
public static LogFileOptions Options(AppSettings settings)
{
var file = int.Clamp(settings.LogMaxFileMb, 0, MaxFileMb);
var total = int.Clamp(settings.LogMaxTotalMb, 0, MaxTotalMb);
return new()
{
Level = Enum.IsDefined(settings.LogLevel) ? settings.LogLevel : LogLevel.Info,
RetentionDays = int.Clamp(settings.LogRetentionDays, 1, MaxRetentionDays),
MaxFileMb = file,
MaxTotalMb = LogFileOptions.TotalBelowFile(file, total) ? file : total,
Rotation = Enum.IsDefined(settings.LogRotation) ? settings.LogRotation : LogRotation.Daily,
};
}
/// <summary>Bytes the diagnostics bundle keeps from the end of each log file.</summary>
public static long DiagnosticsTailBytes(AppSettings settings) => int.Clamp(settings.DiagnosticsLogMb, 1, MaxDiagnosticsLogMb) * LogFileOptions.BytesPerMb;
/// <summary>
/// The log files App starts with, in <paramref name="directory"/>, with <paramref name="settings"/> from the first line:
/// that line opens a file and prunes, so the defaults would delete what the user keeps longer.
/// </summary>
public static FileLogSink Open(string directory, AppSettings settings)
{
var options = Options(settings);
Log.MinimumLevel = options.Level;
return new FileLogSink(directory, "chronos", options);
}
/// <summary>The settings to <paramref name="sink"/> and the engine, from the next line on.</summary>
public static void Apply(FileLogSink sink, AppSettings settings)
{
var options = Options(settings);
sink.Configure(options);
Log.MinimumLevel = options.Level;
}
}
+138 -71
View File
@@ -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));
+25 -1
View File
@@ -3,6 +3,7 @@ using System.Text.Json;
using System.Text.Json.Serialization;
using Chronos.Core.Analysis.Deep;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Import;
using Chronos.Core.IO;
using Chronos.Core.Naming;
@@ -96,7 +97,11 @@ public sealed class AppSettings
/// <summary>Thumbnail long edge of new archives (also written into the open archive), BRIEF §8.5.</summary>
public int ThumbnailLongEdge { get; set; } = 320;
/// <summary>Minutes between the rescans of the open archive (BRIEF §7: polling by mtime and size, no file-system watchers).</summary>
/// <summary>
/// Obsolete (owner review 2, R10): the former Settings › Archive › Rescan every. Nothing edits it any more; it only seeds
/// the interval of the <c>archive-scan</c> schedule (<see cref="Jobs.DesktopScheduleHost"/>) the first time it is created,
/// and is what Reset puts that schedule back to. The schedule's own interval is edited in Jobs › Scheduled.
/// </summary>
public int ScanIntervalMinutes { get; set; } = DefaultScanIntervalMinutes;
// ---- Import (defaults of new cards and folders; a card's own profile wins) ----
@@ -185,6 +190,25 @@ public sealed class AppSettings
/// <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; }
// ---- Advanced › Logs (owner review 2, R11; applied by AppLogging) ----
/// <summary>Least severe level written to the log files.</summary>
public LogLevel LogLevel { get; set; } = LogLevel.Info;
/// <summary>Log files last written longer ago are deleted.</summary>
public int LogRetentionDays { get; set; } = LogFileOptions.DefaultRetentionDays;
/// <summary>A log file this large (MB of 2²⁰ bytes) continues in a numbered one; 0 = no limit.</summary>
public int LogMaxFileMb { get; set; } = LogFileOptions.DefaultMaxFileMb;
/// <summary>While the log files together are larger (MB), the oldest are deleted, never the current one; 0 = no limit.</summary>
public int LogMaxTotalMb { get; set; } = LogFileOptions.DefaultMaxTotalMb;
/// <summary>One log file per UTC day or per hour.</summary>
public LogRotation LogRotation { get; set; } = LogRotation.Daily;
/// <summary>MB kept from the end of each log file in the diagnostics bundle.</summary>
public int DiagnosticsLogMb { get; set; } = AppLogging.DefaultDiagnosticsLogMb;
public sealed class WindowPlacement
{
public double Left { get; set; }
@@ -14,7 +14,8 @@ namespace Chronos.App.Infrastructure;
/// <summary>
/// The diagnostics bundle of Settings › Advanced (BRIEF §12.8, §12.9, §22 Phase 8): an environment report, the codec
/// and encoder inventory, the settings, the latest failed jobs and the log files, zipped into a folder the user chose.
/// and encoder inventory, the settings, the latest failed jobs and the end of each log file (Settings › Advanced ›
/// Diagnostics logs), zipped into a folder the user chose.
/// Everything passes through <see cref="SecretScrubber"/> (the saved server token, passwords and keys never leave the
/// PC) and no photo or archive file is ever included.
/// </summary>
@@ -31,6 +32,7 @@ public static class DiagnosticsBundle
public static Task<string> CreateAsync(AppServices services, string folder, IEnumerable<string>? extraLines = null, CancellationToken ct = default)
{
var settings = services.Settings.ToJson();
var tailBytes = AppLogging.DiagnosticsTailBytes(services.Settings);
var report = Report(services.Environment, extraLines) + DatabaseLine(services.Database);
return Task.Run(async () =>
{
@@ -47,7 +49,7 @@ public static class DiagnosticsBundle
bundle.AddText("codecs.txt", codecs);
bundle.AddJson("settings.json", settings);
bundle.AddJobs("jobs-failed.json", failures);
bundle.AddLogs(services.Environment.LogDirectory, cancellationToken: ct);
bundle.AddLogs(services.Environment.LogDirectory, tailBytes: tailBytes, cancellationToken: ct);
}
File.Move(temp, path);
return path;
@@ -114,8 +116,15 @@ public static class DiagnosticsBundle
}
}
/// <summary>What <see cref="CacheStore.Trim"/> did: the cache's size before, the bytes and files it deleted.</summary>
public sealed record CacheTrimResult(long Before, long Freed, int Deleted)
{
/// <summary>The cache's size afterwards.</summary>
public long After => Before - Freed;
}
/// <summary>
/// The disk cache (spilled frames, thumbnails): its folder, its size and clearing it. Only a folder Chronos created
/// The disk cache (spilled frames, thumbnails): its folder, its size, trimming and clearing it. Only a folder Chronos created
/// (it carries a marker file) is ever emptied, so pointing the cache at a folder with user files cannot delete them.
/// </summary>
public static class CacheStore
@@ -179,6 +188,69 @@ public static class CacheStore
return freed;
}
/// <summary>
/// Brings an owned cache folder down to <paramref name="limitBytes"/> (owner review 2, R10: the housekeeping
/// schedule's cache step): the least recently written files go first, files in use stay (a render spilling, an import
/// staging), and so does everything under the <paramref name="keep"/> folders (relative to the cache: sets that must
/// stay whole), which still counts towards the size. Null when the folder is not a Chronos cache folder: nothing is
/// deleted there.
/// </summary>
public static CacheTrimResult? Trim(string folder, long limitBytes, IReadOnlyCollection<string>? keep = null, CancellationToken ct = default)
{
if (!Directory.Exists(folder)) return new CacheTrimResult(0, 0, 0);
if (!IsOwned(folder)) return null;
var root = new DirectoryInfo(folder);
var kept = (keep ?? []).Select(k => Path.TrimEndingDirectorySeparator(Path.GetFullPath(Path.Combine(root.FullName, k))) + Path.DirectorySeparatorChar).ToList();
var marker = Path.Combine(root.FullName, MarkerFile);
var options = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint };
var candidates = new List<FileInfo>();
long size = 0;
foreach (var file in root.EnumerateFiles("*", options))
{
size += file.Length;
if (file.FullName.Equals(marker, StringComparison.OrdinalIgnoreCase)
|| kept.Any(k => file.FullName.StartsWith(k, StringComparison.OrdinalIgnoreCase))) continue;
candidates.Add(file);
}
var before = size;
long freed = 0;
var deleted = 0;
foreach (var file in candidates.OrderBy(f => f.LastWriteTimeUtc))
{
if (size <= limitBytes) break;
ct.ThrowIfCancellationRequested();
// Read before the delete: a deleted file has no length.
var length = file.Length;
if (!TryDeleteUnused(file)) continue;
size -= length;
freed += length;
deleted++;
}
return new CacheTrimResult(before, freed, deleted);
}
/// <summary>Deletes a file nobody has open; false for one in use or protected.</summary>
private static bool TryDeleteUnused(FileInfo file)
{
try
{
// A file open anywhere else (written, read or mapped) cannot be opened exclusively: it stays.
using (new FileStream(file.FullName, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
}
file.Delete();
return true;
}
catch (IOException)
{
return false;
}
catch (UnauthorizedAccessException)
{
return false;
}
}
private static long TryDelete(FileInfo file)
{
try