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

+278
View File
@@ -0,0 +1,278 @@
using System.Globalization;
using System.Text.RegularExpressions;
namespace Chronos.Core.Diagnostics;
/// <summary>How often a <see cref="FileLogSink"/> starts a new file (UTC).</summary>
public enum LogRotation
{
/// <summary>One file per day: <c>prefix-yyyyMMdd.log</c>.</summary>
Daily,
/// <summary>One file per hour: <c>prefix-yyyyMMdd-HH.log</c>.</summary>
Hourly,
}
/// <summary>
/// What a <see cref="FileLogSink"/> writes and keeps (owner review 2, R11): the least severe level written, the days files
/// are kept, the size at which a file continues in a numbered one, the size the sink's files may take together (0: no
/// limit for either size) and the rotation period. Sizes are in MB of 2²⁰ bytes, like the diagnostics tail.
/// </summary>
public sealed record LogFileOptions
{
public const int DefaultRetentionDays = 14;
public const int DefaultMaxFileMb = 50;
public const int DefaultMaxTotalMb = 1024;
/// <summary>Bytes in one MB of the limits.</summary>
public const long BytesPerMb = 1L << 20;
public LogLevel Level { get; init; } = LogLevel.Info;
/// <summary>Files last written longer ago are deleted; 0 or less keeps them whatever their age.</summary>
public int RetentionDays { get; init; } = DefaultRetentionDays;
/// <summary>A file this large continues in the next numbered file (<c>.1.log</c>, <c>.2.log</c>…); 0 = no limit.</summary>
public int MaxFileMb { get; init; } = DefaultMaxFileMb;
/// <summary>While the sink's files together are larger, the oldest are deleted (never the one being written); 0 = no limit.</summary>
public int MaxTotalMb { get; init; } = DefaultMaxTotalMb;
public LogRotation Rotation { get; init; } = LogRotation.Daily;
/// <summary>
/// Whether a total of <paramref name="maxTotalMb"/> is below one file of <paramref name="maxFileMb"/>: each finished file
/// would be deleted as soon as the next one opens. The server refuses such settings; the desktop raises the total.
/// </summary>
public static bool TotalBelowFile(int maxFileMb, int maxTotalMb) => maxTotalMb > 0 && maxFileMb > maxTotalMb;
}
/// <summary>
/// Appends log lines to rotating files: <c>prefix-yyyyMMdd.log</c> (daily) or <c>prefix-yyyyMMdd-HH.log</c> (hourly, UTC);
/// a file that reaches <see cref="LogFileOptions.MaxFileMb"/> continues in <c>prefix-yyyyMMdd[-HH].1.log</c>, <c>.2</c>…
/// At every new file (and when the options change) files older than the retention are deleted, then the oldest while
/// the sink's files exceed <see cref="LogFileOptions.MaxTotalMb"/>; only names this sink writes are touched, never the
/// file being written. Lines are flushed one by one; one that cannot be written (the folder removed, a full disk) is dropped
/// and the next opens the file again. <see cref="Configure"/> applies new options from the next line.
/// </summary>
public sealed class FileLogSink : ILogSink, IDisposable
{
private readonly string _directory;
private readonly string _prefix;
private readonly TimeProvider _time;
private readonly Regex _ownName;
private readonly Lock _gate = new();
private LogFileOptions _options;
private FileStream? _stream;
private StreamWriter? _writer;
private string? _stem;
private int _part;
private string? _path;
private bool _disposed;
/// <summary>Daily files kept for <paramref name="retainDays"/>, with the default size limits.</summary>
public FileLogSink(string directory, string prefix, int retainDays = LogFileOptions.DefaultRetentionDays)
: this(directory, prefix, new LogFileOptions { RetentionDays = retainDays })
{
}
public FileLogSink(string directory, string prefix, LogFileOptions options, TimeProvider? time = null)
{
ArgumentNullException.ThrowIfNull(options);
_directory = Path.GetFullPath(directory);
_prefix = prefix;
_options = options;
_time = time ?? TimeProvider.System;
_ownName = new Regex("^" + Regex.Escape(prefix) + @"-\d{8}(-\d{2})?(\.\d+)?\.log$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
Directory.CreateDirectory(_directory);
}
public LogFileOptions Options
{
get
{
lock (_gate) return _options;
}
}
/// <summary>The file being written; before the first line, the one it will go to.</summary>
public string CurrentPath
{
get
{
lock (_gate) return _path ?? PathOf(Stem(Now), 0);
}
}
private DateTime Now => _time.GetUtcNow().UtcDateTime;
public void Write(LogLevel level, string category, string message, Exception? exception)
{
lock (_gate)
{
if (_disposed || level < _options.Level) return;
var now = Now;
try
{
EnsureFile(now);
_writer!.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{now:O} {level,-7} {category}: {message}"));
if (exception is not null) _writer.WriteLine(exception.ToString());
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// The folder is gone, the disk is full or the file is locked: the line is dropped and the next one opens
// the file again.
Close();
}
}
}
/// <summary>New options from the next line on; a change of retention or limits prunes at once.</summary>
public void Configure(LogFileOptions options)
{
ArgumentNullException.ThrowIfNull(options);
lock (_gate)
{
var prune = options.RetentionDays != _options.RetentionDays || options.MaxTotalMb != _options.MaxTotalMb;
_options = options;
if (prune) Prune(Now);
}
}
/// <summary>Deletes the files older than the retention, then the oldest while the total exceeds the limit.</summary>
public void PruneNow()
{
lock (_gate) Prune(Now);
}
public void Dispose()
{
lock (_gate)
{
_disposed = true;
Close();
}
}
/// <summary>Opens the file of this period, or the next part when the current one is full, and prunes when it changes.</summary>
private void EnsureFile(DateTime now)
{
var stem = Stem(now);
var newPeriod = _writer is null || stem != _stem;
if (!newPeriod && !IsFull) return;
Close();
if (newPeriod)
{
// A restart continues the newest file of the period.
_stem = stem;
_part = LastPart(stem);
}
else
{
_part++;
}
Open();
if (IsFull)
{
Close();
_part++;
Open();
}
Prune(now);
}
private bool IsFull => _options.MaxFileMb > 0 && _stream is { } stream && stream.Position >= _options.MaxFileMb * LogFileOptions.BytesPerMb;
private void Open()
{
_path = PathOf(_stem!, _part);
_stream = new FileStream(_path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
_writer = new StreamWriter(_stream) { AutoFlush = true };
}
private void Close()
{
var writer = _writer;
_writer = null;
_stream = null;
try
{
writer?.Dispose();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// What it still held could not be flushed (a full disk); its file is closed all the same.
}
}
private string Stem(DateTime now) => _options.Rotation == LogRotation.Hourly
? string.Create(CultureInfo.InvariantCulture, $"{_prefix}-{now:yyyyMMdd-HH}")
: string.Create(CultureInfo.InvariantCulture, $"{_prefix}-{now:yyyyMMdd}");
private string PathOf(string stem, int part) =>
Path.Combine(_directory, part == 0 ? stem + ".log" : string.Create(CultureInfo.InvariantCulture, $"{stem}.{part}.log"));
/// <summary>The highest part of <paramref name="stem"/> on disk (0 when there is none).</summary>
private int LastPart(string stem)
{
var last = 0;
try
{
foreach (var file in Directory.EnumerateFiles(_directory, stem + ".*.log"))
{
var name = Path.GetFileName(file);
if (name.Length <= stem.Length + 5 || !name.StartsWith(stem + ".", StringComparison.OrdinalIgnoreCase)) continue;
if (int.TryParse(name[(stem.Length + 1)..^4], NumberStyles.None, CultureInfo.InvariantCulture, out var part)) last = int.Max(last, part);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
}
return last;
}
private void Prune(DateTime now)
{
List<FileInfo> files;
try
{
files = [.. new DirectoryInfo(_directory).EnumerateFiles(_prefix + "-*.log").Where(f => _ownName.IsMatch(f.Name))];
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return;
}
var kept = new List<FileInfo>();
var cutoff = _options.RetentionDays > 0 ? now.AddDays(-_options.RetentionDays) : DateTime.MinValue;
foreach (var file in files)
{
if (!IsCurrent(file) && file.LastWriteTimeUtc < cutoff && TryDelete(file)) continue;
kept.Add(file);
}
if (_options.MaxTotalMb <= 0) return;
var limit = _options.MaxTotalMb * LogFileOptions.BytesPerMb;
// The directory may report a stale size for the file still open: its stream knows.
var total = kept.Sum(f => IsCurrent(f) && _stream is { } stream ? stream.Length : f.Length);
foreach (var file in kept.Where(f => !IsCurrent(f)).OrderBy(f => f.LastWriteTimeUtc).ThenBy(f => f.Name, StringComparer.Ordinal))
{
if (total <= limit) break;
var length = file.Length;
if (TryDelete(file)) total -= length;
}
}
private bool IsCurrent(FileInfo file) => _path is not null && string.Equals(file.FullName, _path, StringComparison.OrdinalIgnoreCase);
private static bool TryDelete(FileInfo file)
{
try
{
file.Delete();
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return false;
}
}
}
+26 -65
View File
@@ -17,13 +17,22 @@ public interface ILogSink
void Write(LogLevel level, string category, string message, Exception? exception);
}
/// <summary>Tiny engine-wide logger. Core code logs through it; hosts plug in a sink.</summary>
/// <summary>
/// Tiny engine-wide logger. Core code logs through it; hosts plug in a sink. <see cref="MinimumLevel"/> drops lines no sink
/// wants before they are formatted: hosts set it to the lowest level of their sinks, which each keep their own (a
/// <see cref="FileLogSink"/> its <see cref="LogFileOptions.Level"/>, the server's console and files their filters).
/// Logging never throws: a line a sink cannot write is dropped, so code that logs from its error handling (the job engine
/// marking a job failed, the scheduler's loop) always goes on to its next step.
/// </summary>
public static class Log
{
private static ILogSink _sink = new ConsoleSink();
public static LogLevel MinimumLevel { get; set; } = LogLevel.Info;
/// <summary>Where lines go now (a test that replaces it puts this one back).</summary>
public static ILogSink Sink => _sink;
public static void SetSink(ILogSink sink) => _sink = sink ?? throw new ArgumentNullException(nameof(sink));
public static void Debug(string category, string message) => Write(LogLevel.Debug, category, message, null);
@@ -38,9 +47,11 @@ public static class Log
{
_sink.Write(level, category, message, exception);
}
catch (IOException)
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// Logging must never take the process down.
// Logging must never take the process down, nor skip what its caller does next: a log folder removed, a full
// disk or the logger of a host already gone (Microsoft.Extensions.Logging wraps what its providers throw in an
// AggregateException) only lose the line.
}
}
@@ -55,72 +66,22 @@ public static class Log
}
}
/// <summary>Appends log lines to rotating files (one per day, kept for <c>retainDays</c>).</summary>
public sealed class FileLogSink : ILogSink, IDisposable
{
private readonly string _directory;
private readonly string _prefix;
private readonly int _retainDays;
private readonly Lock _gate = new();
private StreamWriter? _writer;
private DateOnly _day;
public FileLogSink(string directory, string prefix, int retainDays = 14)
{
_directory = directory;
_prefix = prefix;
_retainDays = retainDays;
Directory.CreateDirectory(directory);
}
public string CurrentPath => Path.Combine(_directory, $"{_prefix}-{_day:yyyyMMdd}.log");
public void Write(LogLevel level, string category, string message, Exception? exception)
{
lock (_gate)
{
var today = DateOnly.FromDateTime(DateTime.UtcNow);
if (_writer is null || today != _day)
{
_writer?.Dispose();
_day = today;
_writer = new StreamWriter(new FileStream(CurrentPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) { AutoFlush = true };
Prune();
}
_writer.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{DateTime.UtcNow:O} {level,-7} {category}: {message}"));
if (exception is not null) _writer.WriteLine(exception.ToString());
}
}
private void Prune()
{
foreach (var file in Directory.EnumerateFiles(_directory, _prefix + "-*.log"))
{
if (File.GetLastWriteTimeUtc(file) < DateTime.UtcNow.AddDays(-_retainDays))
{
try
{
File.Delete(file);
}
catch (IOException)
{
}
}
}
}
public void Dispose()
{
lock (_gate) _writer?.Dispose();
}
}
/// <summary>Writes every event to several sinks.</summary>
/// <summary>Writes every event to several sinks; one that cannot write it does not keep it from the others.</summary>
public sealed class TeeLogSink(params ILogSink[] sinks) : ILogSink
{
public void Write(LogLevel level, string category, string message, Exception? exception)
{
foreach (var sink in sinks) sink.Write(level, category, message, exception);
foreach (var sink in sinks)
{
try
{
sink.Write(level, category, message, exception);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// That sink loses the line (see Log.Write).
}
}
}
}
+57
View File
@@ -182,6 +182,63 @@ public sealed record Job
public DateTimeOffset Created { get; init; }
public DateTimeOffset? Started { get; init; }
public DateTimeOffset? Finished { get; init; }
/// <summary>The schedule that queued this job; null for jobs queued by a user or by other jobs (owner review 2, R10).</summary>
public Guid? ScheduleId { get; init; }
}
/// <summary>
/// A recurring job (owner review 2, R10): an action (scan, verify, backup, …) with its parameters, run on a recurrence
/// in the host's time zone. System schedules (<see cref="SystemKey"/> set) stand for the timers a host used to run out of
/// sight; they are seeded once, can be edited and reset, never deleted.
/// </summary>
public sealed record Schedule
{
public required Guid Id { get; init; }
/// <summary>Stable key of a host's system schedule (<c>archive-scan</c>); null for schedules a user created.</summary>
public string? SystemKey { get; init; }
public required string Name { get; init; }
/// <summary>Wire name of the action (<c>scan</c>, <c>verify</c>, <c>backup</c>…).</summary>
public required string Action { get; init; }
/// <summary>What the action works on: <c>current</c>, the host's archive.</summary>
public string Target { get; init; } = "current";
/// <summary>The action's parameters as JSON (camelCase, only the fields the action reads).</summary>
public string? ParametersJson { get; init; }
/// <summary>The recurrence in its text form (<c>every:10m</c>, <c>daily:03:00</c>, <c>weekly:mon,thu@02:30</c>, <c>monthly:1@04:00</c>).</summary>
public required string Recurrence { get; init; }
/// <summary>A run missed while the host was off happens once when it comes back; otherwise it is skipped.</summary>
public bool CatchUp { get; init; } = true;
/// <summary>Priority of the jobs it queues.</summary>
public JobPriority Priority { get; init; } = JobPriority.Background;
public bool Enabled { get; init; } = true;
/// <summary>When it fires next (UTC); null while disabled or not computed yet.</summary>
public DateTimeOffset? NextRun { get; init; }
public DateTimeOffset? LastRun { get; init; }
/// <summary>The first job the last run queued.</summary>
public Guid? LastJobId { get; init; }
/// <summary>What the last run did: <c>queued</c>, <c>skipped-pending</c>, <c>skipped-offline</c>, <c>skipped-nothing</c>,
/// <c>unavailable</c> or <c>failed:&lt;reason&gt;</c>.</summary>
public string? LastOutcome { get; init; }
public Guid? CreatedBy { get; init; }
public DateTimeOffset Created { get; init; }
public DateTimeOffset Updated { get; init; }
/// <summary>True for a host's system schedule.</summary>
public bool IsSystem => SystemKey is not null;
}
/// <summary>A memory card known to this client (BRIEF §13).</summary>
+6
View File
@@ -81,6 +81,12 @@ public enum JobKind
/// <summary>Client: originals or proxies of a server sequence fetched into this PC (BRIEF §14.5).</summary>
Download,
/// <summary>A <c>VACUUM INTO</c> copy of an SQLite index into the backups folder (owner review 2, R10); stored as 16.</summary>
Backup = 16,
/// <summary>Housekeeping steps: job history, audit log, trash report and the host's own (owner review 2, R10); stored as 17.</summary>
Cleanup = 17,
}
public enum JobState