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

+16 -9
View File
@@ -1,6 +1,7 @@
using Chronos.Core.Imaging.Decoders;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Housekeeping;
using Chronos.Data.Jobs;
using Chronos.Server.Configuration;
@@ -8,10 +9,11 @@ namespace Chronos.Server.Storage;
/// <summary>
/// The archive engine behind the server (BRIEF §7, §14.4): ingest of verified uploads, lookup of proxies and
/// thumbnails, its job handlers (scan, rebuild, verify, import, thumbnails, proxies, maintenance) and the periodic
/// incremental scan (<see cref="ArchivePolling"/>); a scan queues thumbnails and proxies of what it indexes, as an upload
/// does. Decoding is managed only (BRIEF §4.2). The daily backup of an SQLite index runs with it
/// (<see cref="DatabaseBackupService"/>).
/// thumbnails, and its job handlers (scan, rebuild, verify, import, thumbnails, proxies, maintenance, the duplicates and
/// orphans reports, index backups and clean-ups with the server's own steps, the <see cref="ICleanupStep"/>s in DI); a scan
/// queues thumbnails and proxies of what it indexes, as an upload does. Decoding is managed only (BRIEF §4.2). Recurring
/// work (the periodic scan, the nightly backup of an SQLite index, clean-ups) is queued by the server's system schedules
/// (<see cref="Jobs.ServerScheduleHost"/>, owner review 2, R10).
/// </summary>
public static class ArchiveModule
{
@@ -24,14 +26,19 @@ public static class ArchiveModule
{
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<ChronosDatabase>(),
new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = Owner, ImagesAfterScan = true, Parallelism = () => options.Parallelism });
return new ArchiveService(sp.GetRequiredService<ChronosDatabase>(), new ArchiveServiceOptions
{
Decoder = DecoderFactory.CreateServer(),
Owner = Owner,
ImagesAfterScan = true,
Parallelism = () => options.Parallelism,
CleanupSteps = [.. sp.GetServices<ICleanupStep>()],
// Next to the index in the data folder, where the daily backups always went.
BackupDirectory = Path.Combine(options.DataPath, DatabaseBackups.DirectoryName),
});
});
services.AddSingleton<IArchiveIngest>(sp => sp.GetRequiredService<ArchiveService>().Ingest);
services.AddSingleton<IJobHandlerProvider>(sp => sp.GetRequiredService<ArchiveService>());
services.AddSingleton<IFrameAssetLocator, ArchiveAssetLocator>();
services.AddHostedService<DatabaseBackupService>();
services.AddSingleton<ArchivePolling>();
services.AddHostedService(sp => sp.GetRequiredService<ArchivePolling>());
}
}
@@ -1,71 +0,0 @@
using Chronos.Core.Archiving;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Server.Jobs;
namespace Chronos.Server.Storage;
/// <summary>
/// Polls the archive (BRIEF §7: by modification time and size, no file-system watchers): an incremental scan at start
/// and every <see cref="Interval"/> while the archive is online, so photos already in an adopted folder and sequences
/// another writer adds (a desktop sharing the archive, files copied in by hand) are indexed without an administrator's
/// rescan. Settings such a writer changed in archive.json reach the index first, so uploads and the admin panel follow
/// them. A scan or rebuild of the archive that is waiting, running or paused is not queued again.
/// </summary>
public sealed class ArchivePolling(ChronosDatabase db, ServerArchive archive, ArchiveService archives, JobEngineHost jobs, TimeProvider time,
ILogger<ArchivePolling> logger)
: BackgroundService
{
/// <summary>The desktop's rhythm (it polls its archive the same way).</summary>
public static readonly TimeSpan Interval = TimeSpan.FromMinutes(10);
private static readonly JobState[] Pending = [JobState.Queued, JobState.Running, JobState.Paused];
/// <summary>Queues an incremental scan of an online archive unless one is pending; returns it, or null when none was queued.</summary>
public async Task<Job?> PollAsync(CancellationToken cancellationToken)
{
if (!jobs.CanRun(JobKind.Scan)) return null;
var current = archive.Current;
if (ArchiveService.GetAvailability(current) != ArchiveAvailability.Online) return null;
current = await archive.RefreshAsync(archives, db, cancellationToken);
foreach (var kind in new[] { JobKind.Scan, JobKind.Rebuild })
{
foreach (var state in Pending)
{
if ((await db.Jobs.ListAsync(state, kind, 50, null, cancellationToken)).Items.Any(j => j.TargetIds.Contains(current.Id))) return null;
}
}
var scan = ArchiveJobs.Scan(current);
// Behind what users asked for (BRIEF §14.6).
return await jobs.Engine.EnqueueAsync(scan.Kind, scan.Targets, scan.Label, scan.ParametersJson, JobPriority.Background,
cancellationToken: cancellationToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (true)
{
try
{
await PollAsync(stoppingToken);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
logger.LogWarning(ex, "The archive could not be polled");
}
try
{
await Task.Delay(Interval, time, stoppingToken);
}
catch (OperationCanceledException)
{
return;
}
}
}
}
@@ -1,21 +0,0 @@
using Chronos.Data;
using Chronos.Server.Configuration;
namespace Chronos.Server.Storage;
/// <summary>
/// The daily <c>VACUUM INTO</c> copy of the index of a Windows server on SQLite (BRIEF §6.2: nightly, kept ×3) into
/// <c>{DataPath}/backups</c>. A server on PostgreSQL is backed up with PostgreSQL's own tools; this service then does nothing.
/// </summary>
public sealed class DatabaseBackupService(ChronosDatabase db, ServerOptions options, TimeProvider time, ILogger<DatabaseBackupService> logger) : BackgroundService
{
/// <summary>Folder of the copies.</summary>
public string Directory => Path.Combine(options.DataPath, "backups");
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
if (db.Dialect != Dialect.Sqlite) return Task.CompletedTask;
logger.LogInformation("Daily index backups go to {Directory}", Directory);
return DatabaseBackups.RunDailyAsync(db, Directory, time, stoppingToken);
}
}
+1 -1
View File
@@ -27,7 +27,7 @@ public sealed class ServerArchive(Archive archive)
/// <summary>
/// <see cref="Current"/> once it and the index row hold the settings another writer sharing the archive (a desktop)
/// put into its archive.json (<see cref="ArchiveService.RefreshSettingsAsync"/>): uploads, the polling and the admin
/// put into its archive.json (<see cref="ArchiveService.RefreshSettingsAsync"/>): uploads, the schedules and the admin
/// panel, whose form saves every field, never work from older ones. Unchanged while the file cannot be read.
/// </summary>
public async Task<Archive> RefreshAsync(ArchiveService archives, ChronosDatabase db, CancellationToken cancellationToken)
+50 -27
View File
@@ -1,20 +1,28 @@
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Housekeeping;
using Chronos.Data.Repositories;
using Chronos.Server.Configuration;
namespace Chronos.Server.Storage;
/// <summary>What one sweep of <see cref="UploadMaintenance.SweepAsync"/> removed.</summary>
public sealed record UploadSweep(int Expired, int Files, int Records, int Tokens);
/// <summary>
/// Upload housekeeping (BRIEF §14.4): at start, uploads a crash left half-committed are settled; then every half hour
/// abandoned uploads expire, orphaned partial and staging files are removed, old upload records and dead tokens purged.
/// Upload housekeeping (BRIEF §14.4): at start, uploads a crash left half-committed are settled; the sweep (abandoned
/// uploads expire, orphaned partial and staging files are removed, old upload records and dead tokens purged) is the
/// <see cref="UploadCleanupStep"/> of the <c>upload-cleanup</c> system schedule (owner review 2, R10), no longer a timer.
/// </summary>
public sealed class UploadMaintenance(ChronosDatabase db, ServerOptions options, ServerArchive archive, UploadStore store, TimeProvider time,
ILogger<UploadMaintenance> logger)
: BackgroundService
{
private static readonly TimeSpan Interval = TimeSpan.FromMinutes(30);
private static readonly TimeSpan FinishedRetention = TimeSpan.FromDays(90);
/// <summary>Days a finished upload's record is kept unless the schedule says otherwise.</summary>
public const int FinishedRetentionDays = 90;
private static readonly TimeSpan StagingRetention = TimeSpan.FromDays(1);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
@@ -27,22 +35,6 @@ public sealed class UploadMaintenance(ChronosDatabase db, ServerOptions options,
{
logger.LogError(ex, "Upload recovery failed");
}
while (!stoppingToken.IsCancellationRequested)
{
try
{
await SweepAsync(stoppingToken);
await Task.Delay(Interval, time, stoppingToken);
}
catch (OperationCanceledException)
{
return;
}
catch (Exception ex)
{
logger.LogWarning(ex, "Upload cleanup failed");
}
}
}
/// <summary>
@@ -77,7 +69,12 @@ public sealed class UploadMaintenance(ChronosDatabase db, ServerOptions options,
return UploadRules.StandIn(archive.Root, copies, target);
}
public async Task SweepAsync(CancellationToken cancellationToken)
/// <summary>
/// Expires uploads untouched for <see cref="ServerOptions.UploadRetentionHours"/>, deletes partial files no upload
/// receives into and this server's staging files older than a day, purges the records of uploads finished more than
/// <paramref name="finishedDays"/> days ago (0 keeps them) and expired tokens. Safe to run at any time.
/// </summary>
public async Task<UploadSweep> SweepAsync(int finishedDays = FinishedRetentionDays, CancellationToken cancellationToken = default)
{
var now = time.GetUtcNow();
var abandonedBefore = now - TimeSpan.FromHours(options.UploadRetentionHours);
@@ -92,23 +89,49 @@ public sealed class UploadMaintenance(ChronosDatabase db, ServerOptions options,
var active = new HashSet<Guid>();
foreach (var state in new[] { UploadState.Receiving, UploadState.Committing })
active.UnionWith((await db.Uploads.ListByStateAsync(state, cancellationToken)).Select(u => u.Id));
var files = 0;
foreach (var (id, _) in store.List().ToList())
{
if (!active.Contains(id)) store.Delete(id);
if (active.Contains(id)) continue;
store.Delete(id);
if (!store.Exists(id)) files++;
}
if (Directory.Exists(options.StagingPath))
{
// Only this server's staging files (named by upload id) are touched; clients may share the archive.
foreach (var file in new DirectoryInfo(options.StagingPath).EnumerateFiles())
{
if (Guid.TryParseExact(Path.GetFileNameWithoutExtension(file.Name), "N", out var id) && !active.Contains(id)
&& file.LastWriteTimeUtc < now.UtcDateTime - StagingRetention)
UploadStore.TryDelete(file.FullName);
if (!Guid.TryParseExact(Path.GetFileNameWithoutExtension(file.Name), "N", out var id) || active.Contains(id)
|| file.LastWriteTimeUtc >= now.UtcDateTime - StagingRetention)
continue;
UploadStore.TryDelete(file.FullName);
if (!File.Exists(file.FullName)) files++;
}
}
await db.Uploads.PurgeFinishedAsync(now - FinishedRetention, cancellationToken);
await db.Tokens.PurgeAsync(now, cancellationToken);
var records = finishedDays > 0 ? await db.Uploads.PurgeFinishedAsync(now - TimeSpan.FromDays(finishedDays), cancellationToken) : 0;
var tokens = await db.Tokens.PurgeAsync(now, cancellationToken);
if (expired > 0) logger.LogInformation("Expired {Count} abandoned upload(s)", expired);
return new UploadSweep(expired, files, records, tokens);
}
}
/// <summary>
/// The server's own clean-up step <c>uploads</c> (owner review 2, R10): <see cref="UploadMaintenance.SweepAsync"/>, with the
/// clean-up's age limit as the days finished upload records are kept. It deletes only what uploads left behind, never a
/// photo of the archive.
/// </summary>
public sealed class UploadCleanupStep(UploadMaintenance maintenance) : ICleanupStep
{
public const string StepName = "uploads";
public string Name => StepName;
public async Task<string> RunAsync(CleanupContext context, CleanupParameters parameters)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(parameters);
var sweep = await maintenance.SweepAsync(parameters.OlderThanDays, context.Cancellation).ConfigureAwait(false);
return Loc.L("Server.Log.UploadsSwept", sweep.Expired, sweep.Files, sweep.Records, sweep.Tokens);
}
}