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

@@ -62,6 +62,27 @@ public sealed class DiagnosticsTests(TestContext context)
Assert.NotEmpty((await server.Database.Audit.ListAsync(null, "server_diagnostics", 10, null)).Items);
}
[Test]
public async Task TheBundleKeepsTheEndOfEachLogTheSettingsAskFor()
{
// Owner review 2, R11: Settings › Logs › Diagnostics logs, 1 MB here.
await using var server = await TestServer.StartAsync(context, o => o.DiagnosticsLogMb = 1);
var admin = await server.AdminAsync();
var log = new System.Text.StringBuilder();
for (var i = 0; i < 30_000; i++) log.Append("line ").Append(i).Append(' ').Append('x', 90).Append('\n');
await File.WriteAllTextAsync(Path.Combine(server.Options.LogPath, "server-20200101.log"), log.ToString());
using var response = await admin.GetAsync("/api/v1/server/diagnostics");
await response.ExpectAsync(HttpStatusCode.OK);
await using var body = await response.Content.ReadAsStreamAsync();
using var zip = new ZipArchive(body, ZipArchiveMode.Read);
var tail = Read(zip.GetEntry("logs/server-20200101.log")!);
Assert.True(tail.StartsWith("[first ", StringComparison.Ordinal), "a cut log says so");
Assert.Contains("line 29999 ", tail);
// 1 MiB of the file, less the cut first line, with the note and the system's line ends (CRLF on Windows).
Assert.InRange(tail.Length, (1 << 20) - 200, (1 << 20) * 1.02);
}
private static string Read(ZipArchiveEntry entry)
{
using var reader = new StreamReader(entry.Open());
+83
View File
@@ -128,6 +128,89 @@ public sealed class ManualTimeProvider : TimeProvider
public void Advance(TimeSpan by) => Interlocked.Add(ref _ticks, by.Ticks);
}
/// <summary>
/// A clock tests move by hand whose timers (<see cref="PeriodicTimer"/>, <c>Task.Delay</c>, timed cancellation) fire only
/// when <see cref="Advance"/> reaches them, never in real time: the loops paced by it run exactly when a test says.
/// </summary>
public sealed class SteppedTimeProvider : TimeProvider
{
private readonly Lock _gate = new();
private readonly List<SteppedTimer> _timers = [];
private DateTimeOffset _now = DateTimeOffset.UtcNow;
public override DateTimeOffset GetUtcNow()
{
lock (_gate) return _now;
}
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
{
var timer = new SteppedTimer(this, callback, state);
timer.Change(dueTime, period);
return timer;
}
/// <summary>Moves the clock on, then fires each timer due by then once (a periodic one moves to its next period after now).</summary>
public void Advance(TimeSpan by)
{
List<SteppedTimer> due;
lock (_gate)
{
_now += by;
due = [.. _timers.Where(t => t.Due <= _now)];
foreach (var timer in due)
{
if (timer.Period <= TimeSpan.Zero) _timers.Remove(timer);
else
{
while (timer.Due <= _now) timer.Due += timer.Period;
}
}
}
foreach (var timer in due) timer.Fire();
}
private void Schedule(SteppedTimer timer, TimeSpan dueTime, TimeSpan period)
{
lock (_gate)
{
_timers.Remove(timer);
if (dueTime == Timeout.InfiniteTimeSpan) return;
timer.Due = _now + dueTime;
timer.Period = period == Timeout.InfiniteTimeSpan ? TimeSpan.Zero : period;
_timers.Add(timer);
}
}
private void Remove(SteppedTimer timer)
{
lock (_gate) _timers.Remove(timer);
}
private sealed class SteppedTimer(SteppedTimeProvider clock, TimerCallback callback, object? state) : ITimer
{
public DateTimeOffset Due { get; set; }
public TimeSpan Period { get; set; }
public bool Change(TimeSpan dueTime, TimeSpan period)
{
clock.Schedule(this, dueTime, period);
return true;
}
public void Fire() => callback(state);
public void Dispose() => clock.Remove(this);
public ValueTask DisposeAsync()
{
Dispose();
return ValueTask.CompletedTask;
}
}
}
/// <summary>
/// A job handler that reports progress and then waits until <see cref="Release"/> (or cancellation), so tests can
/// observe running, paused and cancelled states.
@@ -0,0 +1,195 @@
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Chronos.Core.Diagnostics;
using Chronos.Protocol;
using Chronos.Server.Configuration;
using Chronos.Server.Hosting;
using Chronos.Server.Storage;
using Chronos.Testing;
using CoreLog = Chronos.Core.Diagnostics.Log;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
namespace Chronos.Server.Tests.Hosting;
/// <summary>
/// The server's log settings (owner review 2, R11). Serial: the engine's <see cref="CoreLog"/> is one per process, its
/// sink the last server's started and its level the lower of that server's two.
/// </summary>
[Category("server")]
[Serial]
public sealed partial class LoggingTests(TestContext context)
{
[Test]
public async Task DebugLinesReachTheFilesWhenTheLevelAsksForThem()
{
// The files' logger stopped at Information whatever CHRONOS_LOG_LEVEL said.
var root = context.CreateTempDirectory("debug-variable");
var variable = ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_LOG_LEVEL"] = "Debug" });
Assert.Equal((LogLevel.Debug, LogLevel.Debug), (variable.LogLevel, variable.ConsoleLogLevel));
// The console stays at Warning, so the test log stays readable: the files have their own level.
await using var server = await TestServer.StartAsync(context, o => o.LogLevel = variable.LogLevel);
var marker = Guid.NewGuid().ToString("N");
var logger = server.Services.GetRequiredService<ILoggerFactory>().CreateLogger("Chronos.Server.Tests");
logger.LogDebug("debug {Marker}", marker);
logger.LogTrace("trace {Marker}", marker);
CoreLog.Debug("tests", "engine debug " + marker);
// ASP.NET Core's own lines stay at Warning and above.
server.Services.GetRequiredService<ILoggerFactory>().CreateLogger("Microsoft.AspNetCore.Routing").LogDebug("routing {Marker}", marker);
var text = Logs(server);
Assert.Contains("Debug Chronos.Server.Tests: debug " + marker, text);
Assert.Contains("Debug Chronos.tests: engine debug " + marker, text);
Assert.False(text.Contains("trace " + marker, StringComparison.Ordinal), "Trace is below Debug");
Assert.False(text.Contains("routing " + marker, StringComparison.Ordinal), "request lines stay out");
var logging = server.Services.GetRequiredService<ServerLogging>();
Assert.Equal((LogLevel.Debug, LogLevel.Warning, Chronos.Core.Diagnostics.LogLevel.Debug), (logging.FileLevel, logging.ConsoleLevel, CoreLog.MinimumLevel));
}
[Test]
public async Task TheFileLevelChangesWhileTheServerRuns()
{
await using var server = await TestServer.StartAsync(context, o => o.LogLevel = LogLevel.Debug);
var admin = await server.AdminAsync();
var logger = server.Services.GetRequiredService<ILoggerFactory>().CreateLogger("Chronos.Server.Tests");
var marker = Guid.NewGuid().ToString("N");
logger.LogDebug("before {Marker}", marker);
var settings = await SettingsAsync(admin);
Assert.Equal(("debug", "warning"), (settings.Logs.FileLevel, settings.Logs.ConsoleLevel));
// The test server listens on ports the system chose (0), which no request may set.
var edited = settings with { HttpPort = 18080, HttpsPort = 18443, Logs = settings.Logs with { FileLevel = "information" } };
using (var saved = await admin.PutAsJsonAsync("/api/v1/server/settings", edited, ProtocolJson.Default.ServerSettingsDto))
Assert.Equal("information", (await saved.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).Logs.FileLevel);
logger.LogDebug("after {Marker}", marker);
CoreLog.Debug("tests", "engine after " + marker);
logger.LogInformation("information {Marker}", marker);
var text = Logs(server);
Assert.Contains("before " + marker, text);
Assert.Contains("information " + marker, text);
Assert.False(text.Contains("after " + marker, StringComparison.Ordinal), "Debug stopped at once");
Assert.Equal((LogLevel.Information, Chronos.Core.Diagnostics.LogLevel.Info), (server.Options.LogLevel, CoreLog.MinimumLevel));
var file = JsonNode.Parse(await File.ReadAllTextAsync(server.Options.SettingsFile))!.AsObject();
Assert.Equal("Information", file["LogLevel"]!.GetValue<string>());
Assert.False(file.ContainsKey("ConsoleLogLevel"), "only what changed is written");
}
[Test]
public async Task LogSettingsAreSavedAppliedAndValidated()
{
// With the archive module: its audit step is what the audit retention, the audit clean-up's age limit, deletes with.
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var admin = await server.AdminAsync();
var settings = await SettingsAsync(admin);
Assert.Equal(new LogSettingsDto("warning", "warning", 14, 50, 1024, "daily", 0, 4), settings.Logs);
var edited = settings with { HttpPort = 18080, HttpsPort = 18443, Logs = new LogSettingsDto("Debug", "error", 30, 10, 200, "Hourly", 365, 8) };
using (var saved = await admin.PutAsJsonAsync("/api/v1/server/settings", edited, ProtocolJson.Default.ServerSettingsDto))
Assert.Equal(new LogSettingsDto("debug", "error", 30, 10, 200, "hourly", 365, 8), (await saved.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).Logs);
var o = server.Options;
Assert.Equal((LogLevel.Debug, LogLevel.Error, 30, 10, 200), (o.LogLevel, o.ConsoleLogLevel, o.LogRetentionDays, o.LogMaxFileMb, o.LogMaxTotalMb));
Assert.Equal((LogRotation.Hourly, 365, 8), (o.LogRotation, o.AuditRetentionDays, o.DiagnosticsLogMb));
var logging = server.Services.GetRequiredService<ServerLogging>();
Assert.Equal(new LogFileOptions { Level = Chronos.Core.Diagnostics.LogLevel.Debug, RetentionDays = 30, MaxFileMb = 10, MaxTotalMb = 200, Rotation = LogRotation.Hourly },
logging.Sink.Options);
Assert.Equal((LogLevel.Debug, LogLevel.Error), (logging.FileLevel, logging.ConsoleLevel));
// Without a restart, the next line goes to an hourly file.
var marker = Guid.NewGuid().ToString("N");
server.Services.GetRequiredService<ILoggerFactory>().CreateLogger("Chronos.Server.Tests").LogWarning("hourly {Marker}", marker);
Assert.True(Directory.EnumerateFiles(o.LogPath).Any(f => HourlyName().IsMatch(Path.GetFileName(f)) && Read(f).Contains(marker, StringComparison.Ordinal)),
"an hourly file holds the line");
// server.json takes the names it reads back at the next start.
var file = JsonNode.Parse(await File.ReadAllTextAsync(o.SettingsFile))!.AsObject();
Assert.Equal(("Debug", "Error", "Hourly", 30, 365), (file["LogLevel"]!.GetValue<string>(), file["ConsoleLogLevel"]!.GetValue<string>(),
file["LogRotation"]!.GetValue<string>(), file["LogRetentionDays"]!.GetValue<int>(), file["AuditRetentionDays"]!.GetValue<int>()));
var restarted = ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = o.DataPath, ["CHRONOS_DB"] = "postgres" });
Assert.Equal((LogLevel.Debug, LogLevel.Error, LogRotation.Hourly, 10, 200, 8), (restarted.LogLevel, restarted.ConsoleLogLevel, restarted.LogRotation,
restarted.LogMaxFileMb, restarted.LogMaxTotalMb, restarted.DiagnosticsLogMb));
// A panel that knows no log group keeps them as they are.
var older = JsonSerializer.SerializeToNode(edited with { ServerName = "Older panel" }, ProtocolJson.Default.ServerSettingsDto)!.AsObject();
Assert.True(older.Remove("logs"));
using (var content = new StringContent(older.ToJsonString(), Encoding.UTF8, "application/json"))
using (var saved = await admin.PutAsync("/api/v1/server/settings", content))
Assert.Equal(new LogSettingsDto("debug", "error", 30, 10, 200, "hourly", 365, 8), (await saved.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).Logs);
var logs = edited.Logs;
foreach (var (invalid, setting) in new (LogSettingsDto, string)[]
{
(logs with { FileLevel = "verbose" }, "LogLevel"),
(logs with { ConsoleLevel = "3" }, "ConsoleLogLevel"),
(logs with { Rotation = "weekly" }, "LogRotation"),
(logs with { RetentionDays = 0 }, "LogRetentionDays"),
(logs with { MaxFileMb = -1 }, "LogMaxFileMb"),
(logs with { MaxFileMb = 300 }, "LogMaxTotalMb"),
(logs with { MaxTotalMb = -5 }, "LogMaxTotalMb"),
(logs with { AuditRetentionDays = -1 }, "AuditRetentionDays"),
(logs with { DiagnosticsLogMb = 0 }, "DiagnosticsLogMb"),
})
{
using var refused = await admin.PutAsJsonAsync("/api/v1/server/settings", edited with { Logs = invalid }, ProtocolJson.Default.ServerSettingsDto);
Assert.Equal(setting, (await refused.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_setting")).Details);
}
// No limits at all are a choice too.
using (var unlimited = await admin.PutAsJsonAsync("/api/v1/server/settings", edited with { Logs = logs with { MaxFileMb = 0, MaxTotalMb = 0 } },
ProtocolJson.Default.ServerSettingsDto))
await unlimited.ExpectAsync(HttpStatusCode.OK);
Assert.Equal((0, 0), (logging.Sink.Options.MaxFileMb, logging.Sink.Options.MaxTotalMb));
}
[Test]
public async Task LevelsSetByTheEnvironmentAreLocked()
{
// An install upgraded with the earlier compose file or Unraid template: CHRONOS_LOG_LEVEL fixes both levels.
await using var server = await TestServer.StartAsync(context, o =>
{
o.Locked = [nameof(ServerOptions.LogLevel), nameof(ServerOptions.ConsoleLogLevel), nameof(ServerOptions.LogRotation)];
o.LockedBy = new Dictionary<string, string> { [nameof(ServerOptions.LogLevel)] = "CHRONOS_LOG_LEVEL", [nameof(ServerOptions.ConsoleLogLevel)] = "CHRONOS_LOG_LEVEL" };
});
var admin = await server.AdminAsync();
var settings = await SettingsAsync(admin);
Assert.Contains("ConsoleLogLevel", settings.Locked);
// The panel's tooltip names the variable that fixes each; one locked without it is named by the variable that would.
string[] lockedBy = ["ConsoleLogLevel=CHRONOS_LOG_LEVEL", "LogLevel=CHRONOS_LOG_LEVEL", "LogRotation=CHRONOS_LOG_ROTATION"];
Assert.SequenceEqual(lockedBy, settings.LockedBy.Select(l => $"{l.Key}={l.Value}").Order(StringComparer.Ordinal));
var edited = settings with { HttpPort = 18080, HttpsPort = 18443 };
using (var refused = await admin.PutAsJsonAsync("/api/v1/server/settings", edited with { Logs = edited.Logs with { ConsoleLevel = "debug" } },
ProtocolJson.Default.ServerSettingsDto))
Assert.Equal("ConsoleLogLevel", (await refused.ExpectErrorAsync(HttpStatusCode.Conflict, "setting_locked")).Details);
Assert.Equal(LogLevel.Warning, server.Options.ConsoleLogLevel);
// The settings no variable fixes still save.
// What a request says about the locks is ignored.
using (var saved = await admin.PutAsJsonAsync("/api/v1/server/settings",
edited with { Logs = edited.Logs with { RetentionDays = 7 }, LockedBy = new Dictionary<string, string>() }, ProtocolJson.Default.ServerSettingsDto))
Assert.SequenceEqual(lockedBy, (await saved.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).LockedBy.Select(l => $"{l.Key}={l.Value}").Order(StringComparer.Ordinal));
Assert.Equal(7, server.Options.LogRetentionDays);
}
private static async Task<ServerSettingsDto> SettingsAsync(HttpClient admin)
{
using var read = await admin.GetAsync("/api/v1/server/settings");
return await read.ReadAsync(ProtocolJson.Default.ServerSettingsDto);
}
/// <summary>Every server log file, read beside the sink that may still be writing it.</summary>
private static string Logs(TestServer server) => string.Concat(Directory.EnumerateFiles(server.Options.LogPath, "server-*.log").Order(StringComparer.Ordinal).Select(Read));
private static string Read(string path)
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
[GeneratedRegex(@"^server-\d{8}-\d{2}(\.\d+)?\.log$")]
private static partial Regex HourlyName();
}
@@ -72,6 +72,8 @@ public sealed class StartupTests(TestContext context)
["CHRONOS_DISCOVERY"] = "false",
});
Assert.SequenceEqual(["Database", "HttpPort", "Discovery"], options.Locked);
// The admin panel names the variable that fixes each of them.
Assert.Equal(("CHRONOS_DB", "CHRONOS_HTTP_PORT", "CHRONOS_DISCOVERY"), (options.LockedBy["Database"], options.LockedBy["HttpPort"], options.LockedBy["Discovery"]));
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_WORKERS"] = "many" }));
}
@@ -86,6 +88,7 @@ public sealed class StartupTests(TestContext context)
var former = ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_WORKERS"] = "5" });
Assert.Equal((5, true), (former.Parallelism, former.FormerWorkersVariable));
Assert.SequenceEqual(["Database", "Parallelism"], former.Locked);
Assert.Equal("CHRONOS_WORKERS", former.LockedBy["Parallelism"]);
var both = ServerOptions.Load(new Dictionary<string, string?>
{
["CHRONOS_DATA_PATH"] = root,
@@ -96,6 +99,7 @@ public sealed class StartupTests(TestContext context)
});
Assert.Equal((7, true), (both.Parallelism, both.PriorityQueue));
Assert.SequenceEqual(["Database", "Parallelism", "PriorityQueue"], both.Locked);
Assert.Equal("CHRONOS_PARALLELISM", both.LockedBy["Parallelism"]);
Assert.False(ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_PARALLELISM"] = "2" })
.FormerWorkersVariable);
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_PRIORITY_QUEUE"] = "often" }));
@@ -154,6 +158,48 @@ public sealed class StartupTests(TestContext context)
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_PUBLIC_HTTPS_PORT"] = invalid }));
}
[Test]
public void TheLogVariablesSetTheirSettingsAndLockThem()
{
// Owner review 2, R11: CHRONOS_LOG_LEVEL sets the files and the console, CHRONOS_LOG_CONSOLE_LEVEL the console alone.
var root = context.CreateTempDirectory("log-variables");
Dictionary<string, string?> Env(params (string Name, string Value)[] variables)
{
var env = new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres" };
foreach (var (name, value) in variables) env[name] = value;
return env;
}
var defaults = ServerOptions.Load(Env());
Assert.Equal((Microsoft.Extensions.Logging.LogLevel.Information, Microsoft.Extensions.Logging.LogLevel.Information, 14, 50, 1024),
(defaults.LogLevel, defaults.ConsoleLogLevel, defaults.LogRetentionDays, defaults.LogMaxFileMb, defaults.LogMaxTotalMb));
Assert.Equal((Chronos.Core.Diagnostics.LogRotation.Daily, 0, 4), (defaults.LogRotation, defaults.AuditRetentionDays, defaults.DiagnosticsLogMb));
var both = ServerOptions.Load(Env(("CHRONOS_LOG_LEVEL", "debug")));
Assert.Equal((Microsoft.Extensions.Logging.LogLevel.Debug, Microsoft.Extensions.Logging.LogLevel.Debug), (both.LogLevel, both.ConsoleLogLevel));
Assert.SequenceEqual(["Database", "LogLevel", "ConsoleLogLevel"], both.Locked);
// The earlier compose file and Unraid template set CHRONOS_LOG_LEVEL: the panel names it on both levels.
Assert.Equal(("CHRONOS_LOG_LEVEL", "CHRONOS_LOG_LEVEL"), (both.LockedBy["LogLevel"], both.LockedBy["ConsoleLogLevel"]));
var all = ServerOptions.Load(Env(("CHRONOS_LOG_LEVEL", "Trace"), ("CHRONOS_LOG_CONSOLE_LEVEL", "warn"), ("CHRONOS_LOG_RETENTION_DAYS", "30"),
("CHRONOS_LOG_MAX_FILE_MB", "0"), ("CHRONOS_LOG_MAX_TOTAL_MB", "2048"), ("CHRONOS_LOG_ROTATION", "Hourly"), ("CHRONOS_AUDIT_RETENTION_DAYS", "365"),
("CHRONOS_DIAGNOSTICS_LOG_MB", "16")));
Assert.Equal((Microsoft.Extensions.Logging.LogLevel.Trace, Microsoft.Extensions.Logging.LogLevel.Warning, 30, 0, 2048),
(all.LogLevel, all.ConsoleLogLevel, all.LogRetentionDays, all.LogMaxFileMb, all.LogMaxTotalMb));
Assert.Equal((Chronos.Core.Diagnostics.LogRotation.Hourly, 365, 16), (all.LogRotation, all.AuditRetentionDays, all.DiagnosticsLogMb));
Assert.SequenceEqual(["Database", "LogLevel", "ConsoleLogLevel", "LogRetentionDays", "LogMaxFileMb", "LogMaxTotalMb", "LogRotation", "AuditRetentionDays",
"DiagnosticsLogMb"], all.Locked);
Assert.Equal(("CHRONOS_LOG_LEVEL", "CHRONOS_LOG_CONSOLE_LEVEL"), (all.LockedBy["LogLevel"], all.LockedBy["ConsoleLogLevel"]));
foreach (var invalid in new[]
{
("CHRONOS_LOG_LEVEL", "verbose"), ("CHRONOS_LOG_LEVEL", "2"), ("CHRONOS_LOG_CONSOLE_LEVEL", "loud"), ("CHRONOS_LOG_ROTATION", "weekly"),
("CHRONOS_LOG_RETENTION_DAYS", "0"), ("CHRONOS_LOG_MAX_FILE_MB", "-1"), ("CHRONOS_LOG_MAX_TOTAL_MB", "10"), ("CHRONOS_AUDIT_RETENTION_DAYS", "-1"),
("CHRONOS_DIAGNOSTICS_LOG_MB", "0"),
})
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(Env(invalid)), invalid.Item1 + "=" + invalid.Item2);
}
[Test]
public void HelpListsEveryVariable()
{
@@ -0,0 +1,716 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging.Abstractions;
using Chronos.Core.Archiving;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Jobs;
using Chronos.Data.Scheduling;
using Chronos.Protocol;
using Chronos.Server.Configuration;
using Chronos.Server.Events;
using Chronos.Server.Jobs;
using Chronos.Server.Storage;
using Chronos.Testing;
namespace Chronos.Server.Tests.Jobs;
/// <summary>
/// <c>/api/v1/schedules</c> and the server's system schedules (owner review 2, R10): every timer the server ran is a visible
/// schedule, seeded once, edited, reset and run like the others; the old timers are gone.
/// </summary>
[Category("server")]
public sealed class ScheduleEndpointTests(TestContext context)
{
private static readonly string[] SystemKeys =
[ServerScheduleHost.ArchiveScan, ServerScheduleHost.UploadCleanup, ServerScheduleHost.IndexBackup, ServerScheduleHost.Housekeeping, ServerScheduleHost.AuditCleanup];
private CancellationToken Ct => context.Cancellation;
[Test]
public async Task TheSystemSchedulesTheActionsAndTheTimeZoneAreListed()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var list = await ListAsync(await server.AdminAsync());
// The timers the server ran before, with their timings: nothing runs that this list does not show.
Assert.SequenceEqual(SystemKeys, list.Items.Select(s => s.SystemKey));
var scan = SystemRow(list, ServerScheduleHost.ArchiveScan);
Assert.Equal(("scan", new RecurrenceDto("every", 10, "minutes"), false, "background", true), (scan.Action, scan.Recurrence, scan.CatchUp, scan.Priority, scan.Enabled));
Assert.NotNull(scan.NextRun);
var uploads = SystemRow(list, ServerScheduleHost.UploadCleanup);
// Every 6 hours, not more often: four clean-up jobs a day keep the job history readable.
Assert.Equal(("cleanup", new RecurrenceDto("every", 6, "hours"), true, (int?)90), (uploads.Action, uploads.Recurrence, uploads.CatchUp, uploads.Parameters.OlderThanDays));
Assert.SequenceEqual([UploadCleanupStep.StepName], uploads.Parameters.Steps!);
var backup = SystemRow(list, ServerScheduleHost.IndexBackup);
Assert.Equal(("backup", new RecurrenceDto("daily", Time: "03:00"), true, (int?)3), (backup.Action, backup.Recurrence, backup.CatchUp, backup.Parameters.Keep));
var history = SystemRow(list, ServerScheduleHost.Housekeeping);
Assert.Equal((new RecurrenceDto("daily", Time: "04:00"), (int?)90), (history.Recurrence, history.Parameters.OlderThanDays));
Assert.SequenceEqual(["job-history"], history.Parameters.Steps!);
var audit = SystemRow(list, ServerScheduleHost.AuditCleanup);
// The audit log is kept forever by default: no deletion after an upgrade.
Assert.Equal((new RecurrenceDto("daily", Time: "04:30"), (int?)0, false), (audit.Recurrence, audit.Parameters.OlderThanDays, audit.Enabled));
Assert.SequenceEqual(["audit"], audit.Parameters.Steps!);
// Every action, with whether this server runs it: without the processing module there is no analysis.
Assert.SequenceEqual(ScheduleActions.All, list.Actions.Select(a => a.Name));
Assert.Equal((false, "no-handler"), (list.Actions.Single(a => a.Name == "analysis").Available, list.Actions.Single(a => a.Name == "analysis").Reason));
Assert.True(list.Actions.Where(a => a.Name != "analysis").All(a => a.Available), string.Join(", ", list.Actions.Select(a => $"{a.Name}:{a.Reason}")));
Assert.SequenceEqual(["job-history", "audit", "trash-report", UploadCleanupStep.StepName], list.Steps!);
Assert.Equal(server.Services.GetRequiredService<ServerScheduleHost>().TimeZone.Id, list.TimeZone);
}
[Test]
public async Task SchedulesAreCreatedChangedAndDeleted()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var admin = await server.AdminAsync();
var created = await CreateAsync(admin, new CreateScheduleRequest("Weekly check", "verify", new RecurrenceDto("weekly", Time: "02:30", Days: ["thu", "mon"]),
new ScheduleParametersDto(OlderThanDays: 60, Percent: 25)));
Assert.Equal(("Weekly check", "verify", "current", "background", true, (string?)null), (created.Name, created.Action, created.Target, created.Priority, created.Enabled, created.SystemKey));
Assert.SequenceEqual(["mon", "thu"], created.Recurrence.Days!);
Assert.Equal(((int?)60, (int?)25), (created.Parameters.OlderThanDays, created.Parameters.Percent));
Assert.NotNull(created.NextRun);
// After the system schedules.
Assert.Equal(created.Id, (await ListAsync(admin)).Items[^1].Id);
// PUT replaces the fields it gives; disabled, a schedule has no next run.
using (var put = await admin.PutAsJsonAsync($"/api/v1/schedules/{created.Id}",
new UpdateScheduleRequest(Recurrence: new RecurrenceDto("every", 2, "hours"), Priority: "normal", Enabled: false), ProtocolJson.Default.UpdateScheduleRequest))
{
var updated = await put.ReadAsync(ProtocolJson.Default.ScheduleDto);
Assert.Equal((new RecurrenceDto("every", 2, "hours"), "normal", false, (DateTimeOffset?)null, (int?)25),
(updated.Recurrence, updated.Priority, updated.Enabled, updated.NextRun, updated.Parameters.Percent));
}
// PATCH does the same: enabled again, it gets a next run.
using (var patch = await admin.PatchAsJsonAsync($"/api/v1/schedules/{created.Id}", new UpdateScheduleRequest(Enabled: true, Name: "Check"),
ProtocolJson.Default.UpdateScheduleRequest))
{
var enabled = await patch.ReadAsync(ProtocolJson.Default.ScheduleDto);
Assert.Equal(("Check", true), (enabled.Name, enabled.Enabled));
Assert.NotNull(enabled.NextRun);
}
using (var one = await admin.GetAsync($"/api/v1/schedules/{created.Id}")) Assert.Equal("Check", (await one.ReadAsync(ProtocolJson.Default.ScheduleDto)).Name);
using (var delete = await admin.DeleteAsync($"/api/v1/schedules/{created.Id}")) await delete.ExpectAsync(HttpStatusCode.NoContent);
using (var gone = await admin.GetAsync($"/api/v1/schedules/{created.Id}")) await gone.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
using (var again = await admin.DeleteAsync($"/api/v1/schedules/{created.Id}")) await again.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
Assert.SequenceEqual(SystemKeys, (await ListAsync(admin)).Items.Select(s => s.SystemKey));
// Every change is in the audit log.
using var audit = await admin.GetAsync("/api/v1/audit?action=schedule_created,schedule_updated,schedule_deleted");
var entries = (await audit.ReadAsync(ProtocolJson.Default.PageAuditEntryDto)).Items;
Assert.SequenceEqual(["schedule_deleted", "schedule_updated", "schedule_updated", "schedule_created"], entries.Select(e => e.Action));
Assert.True(entries.All(e => e.TargetId == created.Id.ToString() && e.Username == "admin"), "target and user");
Assert.Equal("Weekly check · verify · weekly:mon,thu@02:30", entries[^1].Details);
Assert.Equal(("Weekly check · verify · every:2h · off", "Check · verify · every:2h"), (entries[2].Details, entries[1].Details));
}
[Test]
public async Task OnlyArchiveAdministratorsSeeAndChangeSchedules()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
using (var list = await editor.GetAsync("/api/v1/schedules")) await list.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var create = await editor.PostAsJsonAsync("/api/v1/schedules", new CreateScheduleRequest("Mine", "scan", new RecurrenceDto("daily", Time: "01:00")),
ProtocolJson.Default.CreateScheduleRequest))
await create.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
var scan = Assert.NotNull(await server.Database.Schedules.GetBySystemKeyAsync(ServerScheduleHost.ArchiveScan, Ct));
using (var run = await editor.PostAsync($"/api/v1/schedules/{scan.Id}/run", null)) await run.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var anonymous = await server.Client.GetAsync("/api/v1/schedules")) Assert.Equal(HttpStatusCode.Unauthorized, anonymous.StatusCode);
}
[Test]
public async Task InvalidFieldsAreNamed()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var admin = await server.AdminAsync();
var daily = new RecurrenceDto("daily", Time: "03:00");
var cases = new (CreateScheduleRequest Request, string Field)[]
{
(new(" ", "scan", daily), "name"),
(new(new string('x', Scheduler.MaxNameLength + 1), "scan", daily), "name"),
(new("Render", "render", daily), "action"),
(new("Often", "scan", new RecurrenceDto("every", 1, "minutes")), "recurrence"),
(new("No days", "scan", new RecurrenceDto("weekly", Time: "03:00", Days: [])), "recurrence"),
(new("Late", "scan", new RecurrenceDto("daily", Time: "25:00")), "recurrence"),
(new("Day 31", "scan", new RecurrenceDto("monthly", Time: "03:00", DayOfMonth: 31)), "recurrence"),
(new("None", "verify", daily, new ScheduleParametersDto(Percent: 0)), "parameters.percent"),
(new("Old", "verify", daily, new ScheduleParametersDto(OlderThanDays: -1)), "parameters.olderThanDays"),
(new("Copies", "backup", daily, new ScheduleParametersDto(Keep: 0)), "parameters.keep"),
(new("Unknown step", "cleanup", daily, new ScheduleParametersDto(Steps: ["photos"])), "parameters.steps"),
(new("No step", "cleanup", daily, new ScheduleParametersDto(Steps: [])), "parameters.steps"),
(new("Urgent", "scan", daily, Priority: "urgent"), "priority"),
(new("Elsewhere", "scan", daily, Target: "another-archive"), "target"),
};
foreach (var (request, field) in cases)
{
using var response = await admin.PostAsJsonAsync("/api/v1/schedules", request, ProtocolJson.Default.CreateScheduleRequest);
var error = await response.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_schedule");
Assert.Equal(field, error.Details, request.Name);
Assert.Contains(field, error.Message);
}
Assert.Count(SystemKeys.Length, (await ListAsync(admin)).Items);
}
[Test]
public async Task SystemSchedulesAreEditedAndResetButNeverDeleted()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var admin = await server.AdminAsync();
var housekeeping = SystemRow(await ListAsync(admin), ServerScheduleHost.Housekeeping);
using (var delete = await admin.DeleteAsync($"/api/v1/schedules/{housekeeping.Id}")) await delete.ExpectErrorAsync(HttpStatusCode.Conflict, "schedule_system");
foreach (var (request, field) in new[] { (new UpdateScheduleRequest(Name: "Mine"), "name"), (new UpdateScheduleRequest(Action: "verify"), "action") })
{
using var refused = await admin.PutAsJsonAsync($"/api/v1/schedules/{housekeeping.Id}", request, ProtocolJson.Default.UpdateScheduleRequest);
Assert.Equal(field, (await refused.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_schedule")).Details);
}
// Its timing, its parameters and its switch change like any schedule's; the same name and action may be sent back.
using (var edit = await admin.PutAsJsonAsync($"/api/v1/schedules/{housekeeping.Id}", new UpdateScheduleRequest(housekeeping.Name, "cleanup",
new RecurrenceDto("weekly", Time: "05:15", Days: ["sun"]), new ScheduleParametersDto(Steps: ["job-history", "trash-report"], OlderThanDays: 30),
CatchUp: false, Enabled: false), ProtocolJson.Default.UpdateScheduleRequest))
{
var edited = await edit.ReadAsync(ProtocolJson.Default.ScheduleDto);
Assert.Equal(("weekly", (int?)30, false, false), (edited.Recurrence.Kind, edited.Parameters.OlderThanDays, edited.CatchUp, edited.Enabled));
}
// Reset puts the server's defaults back, with a new next run.
using (var reset = await admin.PostAsync($"/api/v1/schedules/{housekeeping.Id}/reset", null))
{
var back = await reset.ReadAsync(ProtocolJson.Default.ScheduleDto);
Assert.Equal((new RecurrenceDto("daily", Time: "04:00"), (int?)90, true, true), (back.Recurrence, back.Parameters.OlderThanDays, back.CatchUp, back.Enabled));
Assert.SequenceEqual(["job-history"], back.Parameters.Steps!);
Assert.NotNull(back.NextRun);
}
var custom = await CreateAsync(admin, new CreateScheduleRequest("Mine", "duplicates", new RecurrenceDto("monthly", Time: "01:00", DayOfMonth: 1)));
using (var notSystem = await admin.PostAsync($"/api/v1/schedules/{custom.Id}/reset", null))
await notSystem.ExpectErrorAsync(HttpStatusCode.Conflict, "schedule_no_defaults");
using (var unknown = await admin.PostAsync($"/api/v1/schedules/{Guid.CreateVersion7()}/reset", null)) await unknown.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
Assert.Equal("queued", (await RunAsync(admin, housekeeping.Id)).Outcome);
// A system schedule is audited after its key, so the admin panel names it in its language, as its Scheduled tab does.
using var audit = await admin.GetAsync("/api/v1/audit?action=schedule_updated,schedule_reset,schedule_run");
var entries = (await audit.ReadAsync(ProtocolJson.Default.PageAuditEntryDto)).Items;
Assert.SequenceEqual(["schedule_run", "schedule_reset", "schedule_updated"], entries.Select(e => e.Action));
Assert.True(entries.All(e => e.TargetId == housekeeping.Id.ToString()), "the target is the schedule");
Assert.SequenceEqual(["system:housekeeping · Housekeeping · queued", "system:housekeeping · Housekeeping · cleanup · daily:04:00",
"system:housekeeping · Housekeeping · cleanup · weekly:sun@05:15 · off"], entries.Select(e => e.Details));
}
/// <summary>
/// Every change and run of a schedule goes out on the event socket, also a run that queues no job, so the admin panel's
/// Scheduled tab follows what the scheduler does.
/// </summary>
[Test]
public async Task ScheduleChangesAndRunsAreEvents()
{
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
using var events = server.Services.GetRequiredService<EventHub>().Subscribe();
// Off, so the scheduler's own passes leave it alone; without a duplicates handler its run queues nothing.
var created = await CreateAsync(admin, new CreateScheduleRequest("Duplicates", "duplicates", new RecurrenceDto("daily", Time: "01:00"), Enabled: false));
var run = await RunAsync(admin, created.Id);
Assert.Equal(("unavailable", (Guid?)null), (run.Outcome, run.JobId));
using (var delete = await admin.DeleteAsync($"/api/v1/schedules/{created.Id}")) await delete.ExpectAsync(HttpStatusCode.NoContent);
var changes = new List<bool>();
while (events.Reader.TryRead(out var e))
{
if (e is ScheduleChangedEvent changed && changed.ScheduleId == created.Id) changes.Add(changed.Deleted);
}
Assert.SequenceEqual([false, false, true], changes);
Assert.Equal($$"""{"type":"scheduleChanged","scheduleId":"{{created.Id}}","deleted":true}""",
JsonSerializer.Serialize<ServerEvent>(new ScheduleChangedEvent(created.Id, true), ProtocolJson.Default.ServerEvent));
}
/// <summary>
/// Settings a desktop put into archive.json reach the index every 10 minutes whatever the archive scan does, as with the
/// former polling: the scan's runs read them too, but they are skipped while a long scan is pending, and the schedule may
/// be rare or off.
/// </summary>
[Test]
public async Task ArchiveJsonIsReadEveryTenMinutesWhateverTheScanScheduleDoes()
{
var clock = new SteppedTimeProvider();
await using var server = await TestServer.StartAsync(context, services: s =>
{
ArchiveModule.Register(s);
s.AddSingleton<TimeProvider>(clock);
});
var host = server.Services.GetRequiredService<SchedulerHost>();
var archive = server.Services.GetRequiredService<ServerArchive>();
// The scan at start is over, then the scan schedule is turned off.
await ScansAsync(server, 1);
var scanId = Assert.NotNull(await server.Database.Schedules.GetBySystemKeyAsync(ServerScheduleHost.ArchiveScan, Ct)).Id;
Assert.Null((await host.Scheduler.UpdateAsync(scanId, new UpdateScheduleRequest(Enabled: false), Ct)).Problem);
// A desktop sharing the archive changes its folder template; nothing has read it yet.
const string template = "{camera}/{date}";
var path = new ArchivePaths(archive.Root).ManifestPath;
var manifest = ManifestStore.ReadArchive(path);
Assert.NotEqual(template, manifest.LayoutTemplates.Folder);
ManifestStore.WriteArchive(path, manifest with { LayoutTemplates = manifest.LayoutTemplates with { Folder = template } });
Assert.Equal(manifest.LayoutTemplates.Folder, Assert.NotNull(await server.Database.Archives.GetAsync(archive.Id, Ct)).FolderTemplate);
// Ten minutes on, uploads (the index row) and the admin panel (the served archive) follow it, with no scan.
clock.Advance(TimeSpan.FromMinutes(ServerScheduleHost.ScanMinutes));
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(30));
while (Assert.NotNull(await server.Database.Archives.GetAsync(archive.Id, Ct)).FolderTemplate != template)
{
Assert.True(DateTime.UtcNow < until, "archive.json was not read again");
await Task.Delay(20);
}
Assert.Equal(template, archive.Current.FolderTemplate);
Assert.Count(1, (await server.Database.Jobs.ListAsync(null, JobKind.Scan, 50, null, Ct)).Items);
}
[Test]
public async Task TheJobHistoryOfTheSettingsIsWhatTheHousekeepingScheduleIsResetTo()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var admin = await server.AdminAsync();
using (var read = await admin.GetAsync("/api/v1/server/settings"))
{
var settings = await read.ReadAsync(ProtocolJson.Default.ServerSettingsDto);
// The test server listens on ports the OS chose, which the settings refuse: real ones are sent with the edit.
using var saved = await admin.PutAsJsonAsync("/api/v1/server/settings", settings with { JobHistoryDays = 30, HttpPort = 18080, HttpsPort = 18443 },
ProtocolJson.Default.ServerSettingsDto);
await saved.ExpectAsync(HttpStatusCode.OK);
}
// The schedule keeps its own value; a reset takes the new one, without a restart.
Assert.Equal(30, server.Options.JobHistoryDays);
var housekeeping = SystemRow(await ListAsync(admin), ServerScheduleHost.Housekeeping);
Assert.Equal((int?)90, housekeeping.Parameters.OlderThanDays);
using var reset = await admin.PostAsync($"/api/v1/schedules/{housekeeping.Id}/reset", null);
Assert.Equal((int?)30, (await reset.ReadAsync(ProtocolJson.Default.ScheduleDto)).Parameters.OlderThanDays);
}
/// <summary>
/// Owner review 2, R10 and R11: the audit retention has one source of truth, the audit clean-up schedule's age limit.
/// Settings › Logs shows it wherever it was set (0 while the schedule is off or without its audit step) and sets it
/// (turning the schedule on with its audit step, or off at 0); Reset goes back to the value last saved there, and at 0
/// the audit step deletes nothing.
/// </summary>
[Test]
public async Task TheAuditRetentionOfTheSettingsIsTheAgeLimitOfTheAuditCleanUp()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var admin = await server.AdminAsync();
var audit = SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup);
Assert.Equal(((int?)0, false), (audit.Parameters.OlderThanDays, audit.Enabled));
// At 0 a run (also of the disabled schedule, on request) keeps the whole audit log.
var entries = (await server.Database.Audit.ListByActionsAsync(null, [], 1000, null, Ct)).Items.Select(e => e.Id).ToList();
Assert.True(entries.Count > 0, "the sign-in left audit entries");
var run = await RunAsync(admin, audit.Id);
var job = await JobApiTests.WaitForAsync(admin, run.JobId!.Value, "done");
Assert.Contains("Audit log kept in full", job.LogTail);
var kept = (await server.Database.Audit.ListByActionsAsync(null, [], 1000, null, Ct)).Items.Select(e => e.Id).ToHashSet();
Assert.True(entries.All(kept.Contains), "no audit entry was deleted");
// Saved in Settings › Logs, a retention becomes the schedule's age limit and turns it on, without a restart.
await SaveAuditRetentionAsync(admin, 30);
Assert.Equal(30, server.Options.AuditRetentionDays);
audit = SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup);
Assert.Equal(((int?)30, true), (audit.Parameters.OlderThanDays, audit.Enabled));
// Without an environment variable the schedule stays editable, and Settings shows its limit.
await EditAsync(admin, audit.Id, new UpdateScheduleRequest(Parameters: new ScheduleParametersDto(Steps: ["audit"], OlderThanDays: 60)));
Assert.Equal(60, (await SettingsAsync(admin)).Logs.AuditRetentionDays);
// Saved back as shown, it changes neither the schedule nor the value Reset goes back to.
await SaveAuditRetentionAsync(admin, 60);
Assert.Equal(30, server.Options.AuditRetentionDays);
Assert.Equal((int?)60, SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup).Parameters.OlderThanDays);
using (var reset = await admin.PostAsync($"/api/v1/schedules/{audit.Id}/reset", null))
Assert.Equal((int?)30, (await reset.ReadAsync(ProtocolJson.Default.ScheduleDto)).Parameters.OlderThanDays);
Assert.Equal(30, (await SettingsAsync(admin)).Logs.AuditRetentionDays);
// Turned off on the schedule, nothing is deleted: Settings shows 0, and saving 30 there turns it on again.
await EditAsync(admin, audit.Id, new UpdateScheduleRequest(Enabled: false));
Assert.Equal(0, (await SettingsAsync(admin)).Logs.AuditRetentionDays);
await SaveAuditRetentionAsync(admin, 30);
audit = SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup);
Assert.Equal(((int?)30, true), (audit.Parameters.OlderThanDays, audit.Enabled));
// Without its audit step it deletes nothing either: Settings shows 0, and saving 30 there ticks the step again.
await EditAsync(admin, audit.Id, new UpdateScheduleRequest(Parameters: new ScheduleParametersDto(Steps: ["job-history"], OlderThanDays: 30)));
Assert.Equal(0, (await SettingsAsync(admin)).Logs.AuditRetentionDays);
await SaveAuditRetentionAsync(admin, 30);
audit = SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup);
Assert.Equal(((int?)30, true), (audit.Parameters.OlderThanDays, audit.Enabled));
Assert.SequenceEqual(["job-history", "audit"], audit.Parameters.Steps!);
// Back to 0: kept forever, the schedule off.
await SaveAuditRetentionAsync(admin, 0);
audit = SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup);
Assert.Equal(((int?)0, false), (audit.Parameters.OlderThanDays, audit.Enabled));
// A limit set on the schedule while the setting is 0 is shown, and saving 0 turns the schedule off.
await EditAsync(admin, audit.Id, new UpdateScheduleRequest(Parameters: new ScheduleParametersDto(Steps: ["audit"], OlderThanDays: 45), Enabled: true));
Assert.Equal(45, (await SettingsAsync(admin)).Logs.AuditRetentionDays);
await SaveAuditRetentionAsync(admin, 0);
audit = SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup);
Assert.Equal(((int?)0, false), (audit.Parameters.OlderThanDays, audit.Enabled));
}
private static async Task<ServerSettingsDto> SettingsAsync(HttpClient admin)
{
using var read = await admin.GetAsync("/api/v1/server/settings");
return await read.ReadAsync(ProtocolJson.Default.ServerSettingsDto);
}
/// <summary>Saves Settings › Logs › Keep audit (days) as the admin panel does; the answer shows the value saved.</summary>
private static async Task SaveAuditRetentionAsync(HttpClient admin, int days)
{
var settings = await SettingsAsync(admin);
// The test server listens on ports the OS chose, which the settings refuse: real ones are sent with the edit.
using var saved = await admin.PutAsJsonAsync("/api/v1/server/settings",
settings with { HttpPort = 18080, HttpsPort = 18443, Logs = settings.Logs with { AuditRetentionDays = days } }, ProtocolJson.Default.ServerSettingsDto);
await saved.ExpectAsync(HttpStatusCode.OK);
Assert.Equal(days, (await saved.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).Logs.AuditRetentionDays);
}
private static async Task EditAsync(HttpClient admin, Guid id, UpdateScheduleRequest request)
{
using var edit = await admin.PutAsJsonAsync($"/api/v1/schedules/{id}", request, ProtocolJson.Default.UpdateScheduleRequest);
await edit.ExpectAsync(HttpStatusCode.OK);
}
[Test]
public async Task RunNowQueuesTheJobsOnceAndListsThemAsRuns()
{
var handler = new BlockingJobHandler(JobKind.Duplicates);
await using var server = await TestServer.StartAsync(context, services: s => s.AddSingleton<IJobHandler>(handler));
var admin = await server.AdminAsync();
// Also a disabled schedule runs now.
var schedule = await CreateAsync(admin, new CreateScheduleRequest("Duplicates", "duplicates", new RecurrenceDto("daily", Time: "01:00"), Enabled: false));
var first = await RunAsync(admin, schedule.Id);
Assert.Equal("queued", first.Outcome);
var job = await JobApiTests.WaitForAsync(admin, first.JobId!.Value, "running");
Assert.Equal(("duplicates", (Guid?)schedule.Id, "background"), (job.Kind, job.ScheduleId, job.Priority));
Assert.Equal((first.JobId, "queued", (DateTimeOffset?)null), (first.Schedule.LastJobId, first.Schedule.LastOutcome, first.Schedule.NextRun));
// While its last job has not ended, it is not run again.
using (var busy = await admin.PostAsync($"/api/v1/schedules/{schedule.Id}/run", null))
Assert.Equal(first.JobId.ToString(), (await busy.ExpectErrorAsync(HttpStatusCode.Conflict, "schedule_pending")).Details);
handler.Release();
await JobApiTests.WaitForAsync(admin, first.JobId!.Value, "done");
var second = await RunAsync(admin, schedule.Id);
Assert.Equal("queued", second.Outcome);
await JobApiTests.WaitForAsync(admin, second.JobId!.Value, "running");
handler.Release();
await JobApiTests.WaitForAsync(admin, second.JobId!.Value, "done");
// Its runs, newest first, a page at a time.
using (var page1 = await admin.GetAsync($"/api/v1/schedules/{schedule.Id}/runs?limit=1"))
{
var runs = await page1.ReadAsync(ProtocolJson.Default.PageJobDto);
Assert.Equal(second.JobId, runs.Items.Single().Id);
using var page2 = await admin.GetAsync($"/api/v1/schedules/{schedule.Id}/runs?limit=1&cursor={Uri.EscapeDataString(Assert.NotNull(runs.NextCursor))}");
var rest = await page2.ReadAsync(ProtocolJson.Default.PageJobDto);
Assert.Equal((first.JobId, (string?)null), (rest.Items.Single().Id, rest.NextCursor));
}
using (var bad = await admin.GetAsync($"/api/v1/schedules/{schedule.Id}/runs?cursor=nonsense")) await bad.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_cursor");
using (var unknown = await admin.GetAsync($"/api/v1/schedules/{Guid.CreateVersion7()}/runs")) await unknown.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
using (var other = await admin.PostAsync($"/api/v1/schedules/{Guid.CreateVersion7()}/run", null)) await other.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
// The queue shows which jobs a schedule queued.
using (var queue = await admin.GetAsync("/api/v1/jobs?kind=duplicates"))
Assert.True((await queue.ReadAsync(ProtocolJson.Default.PageJobDto)).Items.All(j => j.ScheduleId == schedule.Id), "scheduleId on the job rows");
using var audit = await admin.GetAsync("/api/v1/audit?action=schedule_run");
Assert.SequenceEqual(["Duplicates · queued", "Duplicates · queued"], (await audit.ReadAsync(ProtocolJson.Default.PageAuditEntryDto)).Items.Select(e => e.Details));
}
[Test]
public async Task SystemSchedulesAreSeededOnceAndKeepTheirEditsAcrossRestarts()
{
var root = context.CreateTempDirectory("restart");
void Paths(ServerOptions o)
{
o.DataPath = Path.Combine(root, "data");
o.ArchivePath = Path.Combine(root, "archive");
Directory.CreateDirectory(o.ArchivePath);
}
Guid scanId;
DateTimeOffset? lastRun;
await using (var first = await TestServer.StartAsync(context, Paths))
{
var admin = await first.AdminAsync();
scanId = SystemRow(await ListAsync(admin), ServerScheduleHost.ArchiveScan).Id;
// Its run at start (no scan handler here: "unavailable") is recorded before the edit.
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while ((lastRun = (await first.Database.Schedules.GetAsync(scanId, Ct))!.LastRun) is null)
{
Assert.True(DateTime.UtcNow < until, "no run at start");
await Task.Delay(20);
}
using var put = await admin.PutAsJsonAsync($"/api/v1/schedules/{scanId}", new UpdateScheduleRequest(Recurrence: new RecurrenceDto("every", 20, "minutes"), Enabled: false),
ProtocolJson.Default.UpdateScheduleRequest);
await put.ExpectAsync(HttpStatusCode.OK);
}
await using var second = await TestServer.StartAsync(context, Paths);
var rows = await second.Database.Schedules.ListAsync(Ct);
Assert.SequenceEqual(SystemKeys, rows.Select(s => s.SystemKey));
var scan = rows.Single(s => s.SystemKey == ServerScheduleHost.ArchiveScan);
Assert.Equal((scanId, "every:20m", false, (DateTimeOffset?)null), (scan.Id, scan.Recurrence, scan.Enabled, scan.NextRun));
// Disabled, the scan does not run at start either.
Assert.Equal(lastRun, scan.LastRun);
}
[Test]
public async Task TheScanScheduleQueuesAScanWhenDueAndNoTimerScansBesideIt()
{
var clock = new ManualTimeProvider();
await using var server = await TestServer.StartAsync(context, services: s =>
{
ArchiveModule.Register(s);
s.AddSingleton<TimeProvider>(clock);
});
var hosted = server.Services.GetServices<IHostedService>().Select(h => h.GetType().Name).ToList();
Assert.Contains(nameof(SchedulerHost), hosted);
Assert.True(hosted.IndexOf(nameof(JobEngineHost)) < hosted.IndexOf(nameof(SchedulerHost)), "the scheduler starts after the engine");
Assert.True(!hosted.Contains("ArchivePolling") && !hosted.Contains("DatabaseBackupService"), string.Join(", ", hosted));
var scheduleId = Assert.NotNull(await server.Database.Schedules.GetBySystemKeyAsync(ServerScheduleHost.ArchiveScan, Ct)).Id;
// At start the scan schedule runs once, as the polling did; no other scan is queued.
var scans = await ScansAsync(server, 1);
Assert.Equal(scheduleId, scans.Single().ScheduleId);
// Ten minutes later it is due: the next pass queues the second scan.
clock.Advance(TimeSpan.FromMinutes(11));
await server.Services.GetRequiredService<SchedulerHost>().Scheduler.RunDueAsync(Ct);
scans = await ScansAsync(server, 2);
Assert.True(scans.All(j => j.ScheduleId == scheduleId && j.Priority == JobPriority.Background), "scans of the schedule, in the background");
var row = Assert.NotNull(await server.Database.Schedules.GetAsync(scheduleId, Ct));
Assert.Equal(("queued", (Guid?)scans[^1].Id), (row.LastOutcome, row.LastJobId));
Assert.True(row.NextRun > clock.GetUtcNow(), "the next run moved on");
}
[Test]
public async Task TheUploadCleanupScheduleSweepsAbandonedUploadsLikeTheFormerTimer()
{
var clock = new ManualTimeProvider();
await using var server = await TestServer.StartAsync(context, o => o.UploadRetentionHours = 48, s =>
{
ArchiveModule.Register(s);
s.AddSingleton<TimeProvider>(clock);
});
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
var id = (await Uploads.StartAsync(uploader, Uploads.Photo(1000, 10))).UploadId!.Value;
var store = server.Services.GetRequiredService<UploadStore>();
Assert.True(store.Exists(id));
var scheduleId = Assert.NotNull(await server.Database.Schedules.GetBySystemKeyAsync(ServerScheduleHost.UploadCleanup, Ct)).Id;
// Two days later its run (every 6 hours, with catch-up) expires the upload and deletes its partial file.
clock.Advance(TimeSpan.FromHours(49));
await server.Services.GetRequiredService<SchedulerHost>().Scheduler.RunDueAsync(Ct);
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
Job? sweep = null;
while (sweep is not { State: JobState.Done })
{
Assert.True(DateTime.UtcNow < until, $"the clean-up did not finish: {sweep?.State} {sweep?.Error}");
await Task.Delay(50);
sweep = (await server.Database.Jobs.ListByScheduleAsync(scheduleId, cancellationToken: Ct)).FirstOrDefault();
}
Assert.Equal(JobKind.Cleanup, sweep.Kind);
Assert.Contains("Uploads expired: 1", sweep.LogTail);
Assert.False(store.Exists(id));
using var state = await uploader.GetAsync($"/api/v1/uploads/{id}");
Assert.Equal("cancelled", (await state.ReadAsync(ProtocolJson.Default.UploadState)).State);
}
[Test]
public async Task AnAuditRetentionFromTheEnvironmentIsAppliedAtStartAndCannotBeChanged()
{
var root = context.CreateTempDirectory("locked");
void Paths(ServerOptions o)
{
o.DataPath = Path.Combine(root, "data");
o.ArchivePath = Path.Combine(root, "archive");
Directory.CreateDirectory(o.ArchivePath);
}
await using (var first = await TestServer.StartAsync(context, Paths, ArchiveModule.Register))
{
var seeded = Assert.NotNull(await first.Database.Schedules.GetBySystemKeyAsync(ServerScheduleHost.AuditCleanup, Ct));
Assert.Equal(((int?)0, false), (ScheduleMapping.Parameters(seeded).OlderThanDays, seeded.Enabled));
// Its audit step unticked before the variable is set.
var unticked = await first.Services.GetRequiredService<SchedulerHost>().Scheduler.UpdateAsync(seeded.Id,
new UpdateScheduleRequest(Parameters: new ScheduleParametersDto(Steps: ["job-history"], OlderThanDays: 0)), Ct);
Assert.Null(unticked.Problem);
}
// CHRONOS_AUDIT_RETENTION_DAYS=30 at the next start: the limit, the switch and the audit step it deletes with.
await using var second = await TestServer.StartAsync(context, o =>
{
Paths(o);
o.AuditRetentionDays = 30;
o.Locked = [nameof(ServerOptions.AuditRetentionDays)];
}, ArchiveModule.Register);
var admin = await second.AdminAsync();
var audit = SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup);
Assert.Equal(((int?)30, true), (audit.Parameters.OlderThanDays, audit.Enabled));
Assert.SequenceEqual(["job-history", "audit"], audit.Parameters.Steps!);
using (var changed = await admin.PutAsJsonAsync($"/api/v1/schedules/{audit.Id}", new UpdateScheduleRequest(Parameters: new ScheduleParametersDto(Steps: ["audit"], OlderThanDays: 60)),
ProtocolJson.Default.UpdateScheduleRequest))
Assert.Equal("AuditRetentionDays", (await changed.ExpectErrorAsync(HttpStatusCode.Conflict, "setting_locked")).Details);
// Turned off, or without its audit step, it would keep what the variable says to delete.
using (var off = await admin.PutAsJsonAsync($"/api/v1/schedules/{audit.Id}", new UpdateScheduleRequest(Enabled: false), ProtocolJson.Default.UpdateScheduleRequest))
Assert.Equal("AuditRetentionDays", (await off.ExpectErrorAsync(HttpStatusCode.Conflict, "setting_locked")).Details);
using (var unticked = await admin.PutAsJsonAsync($"/api/v1/schedules/{audit.Id}",
new UpdateScheduleRequest(Parameters: new ScheduleParametersDto(Steps: ["job-history"], OlderThanDays: 30)), ProtocolJson.Default.UpdateScheduleRequest))
Assert.Equal("AuditRetentionDays", (await unticked.ExpectErrorAsync(HttpStatusCode.Conflict, "setting_locked")).Details);
Assert.SequenceEqual(["job-history", "audit"], SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup).Parameters.Steps!);
// Everything else stays editable.
using var timing = await admin.PutAsJsonAsync($"/api/v1/schedules/{audit.Id}", new UpdateScheduleRequest(Recurrence: new RecurrenceDto("daily", Time: "05:00"),
Parameters: new ScheduleParametersDto(Steps: ["audit", "job-history"], OlderThanDays: 30)), ProtocolJson.Default.UpdateScheduleRequest);
await timing.ExpectAsync(HttpStatusCode.OK);
// Settings shows the fixed value, and the other settings still save with it.
Assert.Equal(30, (await SettingsAsync(admin)).Logs.AuditRetentionDays);
await SaveAuditRetentionAsync(admin, 30);
}
/// <summary>
/// A missed audit clean-up caught up at start runs with the retention CHRONOS_AUDIT_RETENTION_DAYS fixes, not with the
/// age limit the schedule held before: the variable is applied before the first pass.
/// </summary>
[Test]
public async Task ALockedAuditRetentionAppliesToTheRunCaughtUpAtStart()
{
foreach (var days in new[] { 365, 0 })
{
var root = context.CreateTempDirectory($"catch-up-{days}");
void Paths(ServerOptions o)
{
o.DataPath = Path.Combine(root, "data");
o.ArchivePath = Path.Combine(root, "archive");
Directory.CreateDirectory(o.ArchivePath);
}
DatabaseOptions database;
await using (var first = await TestServer.StartAsync(context, Paths, ArchiveModule.Register))
database = first.Options.ToDatabaseOptions();
// While the server was off: a 90-day audit clean-up whose run passed an hour ago, and an entry 200 days old.
var old = Guid.CreateVersion7();
await using (var db = await ChronosDatabase.OpenAsync(database, Ct))
{
var row = Assert.NotNull(await db.Schedules.GetBySystemKeyAsync(ServerScheduleHost.AuditCleanup, Ct));
var parameters = ScheduleMapping.Parameters(row) with { OlderThanDays = 90 };
Assert.True(await db.Schedules.UpdateAsync(row with
{
ParametersJson = ScheduleMapping.ParametersJson(row.Action, parameters),
Enabled = true,
NextRun = DateTimeOffset.UtcNow.AddHours(-1),
}, setNextRun: true, Ct));
await db.Audit.AppendAsync(new AuditEntry { Id = old, At = DateTimeOffset.UtcNow.AddDays(-200), Action = "user.login" }, Ct);
}
// CHRONOS_AUDIT_RETENTION_DAYS at the next start.
await using var second = await TestServer.StartAsync(context, o =>
{
Paths(o);
o.AuditRetentionDays = days;
o.Locked = [nameof(ServerOptions.AuditRetentionDays)];
}, ArchiveModule.Register);
var schedule = Assert.NotNull(await second.Database.Schedules.GetBySystemKeyAsync(ServerScheduleHost.AuditCleanup, Ct));
var queued = await second.Database.Jobs.ListByScheduleAsync(schedule.Id, cancellationToken: Ct);
if (days == 0)
{
// Kept forever: the schedule is off before its missed run could fire.
Assert.False(schedule.Enabled);
Assert.Empty(queued);
}
else
{
Assert.Count(1, queued);
var job = queued[0];
using (var json = JsonDocument.Parse(job.ParametersJson!))
Assert.Equal(days, json.RootElement.GetProperty("olderThanDays").GetInt32());
await JobApiTests.WaitForAsync(await second.AdminAsync(), job.Id, "done");
}
var kept = (await second.Database.Audit.ListByActionsAsync(null, [], 1000, null, Ct)).Items.Select(e => e.Id);
Assert.Contains(old, kept);
}
}
[Test]
public void AnUnknownTimeZoneFallsBackToUtc()
{
var local = ServerScheduleHost.ResolveTimeZone(null, NullLogger.Instance);
Assert.Equal(TimeZoneInfo.Local.BaseUtcOffset, local.BaseUtcOffset);
Assert.Equal(TimeZoneInfo.Local.SupportsDaylightSavingTime, local.SupportsDaylightSavingTime);
// The runtime ignores TZ on Windows; elsewhere a zone it cannot find would leave the schedules in an unknown zone.
if (!OperatingSystem.IsWindows())
{
Assert.Equal(TimeZoneInfo.Utc, ServerScheduleHost.ResolveTimeZone("Not/AZone", NullLogger.Instance));
Assert.Equal(TimeZoneInfo.Local.Id, ServerScheduleHost.ResolveTimeZone(":" + TimeZoneInfo.Local.Id, NullLogger.Instance).Id);
}
}
[Test]
public void TheAuditRetentionVariableIsReadAndChecked()
{
var data = context.CreateTempDirectory("env");
var options = ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = data, ["CHRONOS_DB"] = "postgres", [ServerOptions.AuditRetentionVariable] = "0" });
Assert.Equal(0, options.AuditRetentionDays);
Assert.Contains(nameof(ServerOptions.AuditRetentionDays), options.Locked);
Assert.Equal(0, new ServerOptions().AuditRetentionDays);
Assert.Equal(3650, ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = data, ["CHRONOS_DB"] = "postgres", [ServerOptions.AuditRetentionVariable] = "3650" })
.AuditRetentionDays);
foreach (var invalid in new[] { "-1", "3651", "a year" })
{
Assert.Throws<InvalidOperationException>(() =>
ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = data, ["CHRONOS_DB"] = "postgres", [ServerOptions.AuditRetentionVariable] = invalid }));
}
}
/// <summary>Scan jobs, oldest first, once <paramref name="count"/> exist and none is waiting or running.</summary>
private async Task<List<Job>> ScansAsync(TestServer server, int count)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while (true)
{
var scans = (await server.Database.Jobs.ListAsync(null, JobKind.Scan, 50, null, Ct)).Items.OrderBy(j => j.Created).ToList();
if (scans.Count >= count && scans.All(j => j.State is JobState.Done or JobState.Failed or JobState.Cancelled))
{
Assert.Count(count, scans);
return scans;
}
Assert.True(DateTime.UtcNow < until, $"{scans.Count} scan(s): {string.Join(", ", scans.Select(j => j.State))}");
await Task.Delay(50);
}
}
private static ScheduleDto SystemRow(SchedulesDto list, string key) => list.Items.Single(s => s.SystemKey == key);
private static async Task<SchedulesDto> ListAsync(HttpClient admin)
{
using var response = await admin.GetAsync("/api/v1/schedules");
return await response.ReadAsync(ProtocolJson.Default.SchedulesDto);
}
private static async Task<ScheduleDto> CreateAsync(HttpClient admin, CreateScheduleRequest request)
{
using var response = await admin.PostAsJsonAsync("/api/v1/schedules", request, ProtocolJson.Default.CreateScheduleRequest);
await response.ExpectAsync(HttpStatusCode.Created);
return await response.ReadAsync(ProtocolJson.Default.ScheduleDto);
}
private static async Task<ScheduleRunDto> RunAsync(HttpClient admin, Guid id)
{
using var response = await admin.PostAsync($"/api/v1/schedules/{id}/run", null);
return await response.ReadAsync(ProtocolJson.Default.ScheduleRunDto);
}
}
@@ -67,6 +67,32 @@ public sealed class PostgresServerTests(TestContext context)
await Api.SequenceTests.FramesOfOneVersionAsync(server);
}
[Test]
public async Task SchedulesRunOnPostgresWithoutAnIndexBackup()
{
await using var schema = await Schema.CreateAsync(context);
await using var server = await TestServer.StartAsync(context, o =>
{
o.Database = DatabaseKind.Postgres;
o.DbConnectionString = schema.ConnectionString;
}, Chronos.Server.Storage.ArchiveModule.Register);
var admin = await server.AdminAsync();
using var response = await admin.GetAsync("/api/v1/schedules");
var list = await response.ReadAsync(ProtocolJson.Default.SchedulesDto);
// PostgreSQL is backed up with its own tools (owner review 2, R10): no index-backup schedule, and the action says why.
Assert.SequenceEqual(["archive-scan", "upload-cleanup", "housekeeping", "audit-cleanup"], list.Items.Select(s => s.SystemKey));
var backup = list.Actions.Single(a => a.Name == "backup");
Assert.Equal((false, "postgres"), (backup.Available, backup.Reason));
// A run is claimed, queued and recorded on PostgreSQL as on SQLite.
var history = list.Items.Single(s => s.SystemKey == "housekeeping");
using var run = await admin.PostAsync($"/api/v1/schedules/{history.Id}/run", null);
var ran = await run.ReadAsync(ProtocolJson.Default.ScheduleRunDto);
Assert.Equal(("queued", ran.JobId), (ran.Outcome, ran.Schedule.LastJobId));
await JobApiTests.WaitForAsync(admin, ran.JobId!.Value, "done");
}
/// <summary>A throw-away schema on the test server, selected through <c>Search Path</c>.</summary>
private sealed class Schema : IAsyncDisposable
{
@@ -52,12 +52,16 @@ public sealed class ArchiveModuleTests(TestContext context)
}
[Test]
public async Task AServerOnSqliteBacksUpItsIndexOnStart()
public async Task TheIndexBackupScheduleCopiesAnSqliteIndexIntoTheDataFolder()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var backups = Path.Combine(server.Options.DataPath, "backups");
// No copy yet, so the first one is made at once (BRIEF §6.2), named after the index it copies.
// The nightly copy (BRIEF §6.2) is the index-backup system schedule's (owner review 2, R10), here run now.
var schedule = Assert.NotNull(await server.Database.Schedules.GetBySystemKeyAsync(ServerScheduleHost.IndexBackup, context.Cancellation));
Assert.Equal("daily:03:00", schedule.Recurrence);
var run = Assert.NotNull(await server.Services.GetRequiredService<SchedulerHost>().Scheduler.RunNowAsync(schedule.Id, null, context.Cancellation));
Assert.Equal("queued", run.Outcome);
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while (!Directory.Exists(backups) || Directory.GetFiles(backups, "*.db").Length == 0)
{
@@ -70,8 +74,34 @@ public sealed class ArchiveModuleTests(TestContext context)
Assert.Equal(server.Database.SchemaVersion, summary.SchemaVersion);
}
/// <summary>
/// The first start after the upgrade: the daily loop copied at start once the newest copy was a day old, so the index
/// backup schedule is seeded due then (copied in the first pass) instead of waiting for 03:00.
/// </summary>
[Test]
public async Task PhotosAlreadyInTheArchiveAndAddedLaterAreIndexedByPollingWithThumbnailsAndProxies()
public async Task TheFirstStartCopiesTheIndexWhenTheNewestCopyIsADayOld()
{
string? backups = null;
await using var server = await TestServer.StartAsync(context, options =>
{
backups = Path.Combine(options.DataPath, Chronos.Data.DatabaseBackups.DirectoryName);
Directory.CreateDirectory(backups);
File.WriteAllText(Path.Combine(backups, $"chronos-{DateTime.UtcNow.AddDays(-7):yyyyMMdd-HHmmss}-000.db"), "copy");
}, ArchiveModule.Register);
var schedule = Assert.NotNull(await server.Database.Schedules.GetBySystemKeyAsync(ServerScheduleHost.IndexBackup, context.Cancellation));
Assert.Equal("queued", schedule.LastOutcome);
var path = Assert.NotNull(((Chronos.Data.Sqlite.SqliteDatabase)server.Database.Database).Path);
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(30));
while (Chronos.Data.DatabaseBackups.List(backups!, path).Count < 2)
{
Assert.True(DateTime.UtcNow < until, "no copy at the first start");
await Task.Delay(50);
}
}
[Test]
public async Task PhotosAlreadyInTheArchiveAndAddedLaterAreIndexedByTheScanScheduleWithThumbnailsAndProxies()
{
var photo = Photo();
// An adopted folder that already holds photos.
@@ -87,10 +117,9 @@ public sealed class ArchiveModuleTests(TestContext context)
// The scan queues the thumbnails and proxies clients load from the server, as an upload does.
await UntilImagesAsync(server, editor, archive.Id, "roof");
// Another writer adds a folder: the next poll queues a scan, but not while one is pending.
// Another writer adds a folder: the next run of the scan schedule queues a scan, but not while one is pending.
Directory.CreateDirectory(Path.Combine(server.Options.ArchivePath, "garden"));
File.WriteAllBytes(Path.Combine(server.Options.ArchivePath, "garden", "IMG_0002.JPG"), Photo(seed: 3));
var polling = server.Services.GetRequiredService<ArchivePolling>();
var paused = new Job
{
Id = Guid.CreateVersion7(),
@@ -100,11 +129,13 @@ public sealed class ArchiveModuleTests(TestContext context)
Created = DateTimeOffset.UtcNow,
};
await server.Database.Jobs.EnqueueAsync(paused, context.Cancellation);
Assert.Null(await polling.PollAsync(context.Cancellation));
Assert.Equal("skipped-pending", (await RunScanAsync(server)).Outcome);
await server.Services.GetRequiredService<JobEngineHost>().Engine.CancelAsync(paused.Id, context.Cancellation);
var scan = Assert.NotNull(await polling.PollAsync(context.Cancellation));
Assert.Equal(JobPriority.Background, scan.Priority);
var run = await RunScanAsync(server);
Assert.Equal("queued", run.Outcome);
var scan = Assert.NotNull(await server.Database.Jobs.GetAsync(run.JobId!.Value, context.Cancellation));
Assert.Equal((JobKind.Scan, JobPriority.Background, (Guid?)run.Schedule.Id), (scan.Kind, scan.Priority, scan.ScheduleId));
await UntilIndexedAsync(server, archive.Id, "garden");
await UntilImagesAsync(server, editor, archive.Id, "garden");
}
@@ -141,8 +172,8 @@ public sealed class ArchiveModuleTests(TestContext context)
}
Assert.Equal(1, Assert.NotNull(await server.Database.Sequences.GetAsync(roof.Id)).FrameCount);
// The next poll indexes it and queues the images: the new frame and the one it moved get theirs.
Assert.NotNull(await server.Services.GetRequiredService<ArchivePolling>().PollAsync(context.Cancellation));
// The scan schedule's next run indexes it and queues the images: the new frame and the one it moved get theirs.
Assert.Equal("queued", (await RunScanAsync(server)).Outcome);
await UntilScannedAsync(server);
Assert.Equal(2, Assert.NotNull(await server.Database.Sequences.GetAsync(roof.Id)).FrameCount);
await UntilImagesAsync(server, editor, archive.Id, "roof");
@@ -182,11 +213,12 @@ public sealed class ArchiveModuleTests(TestContext context)
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var archive = server.Services.GetRequiredService<ServerArchive>();
var polling = server.Services.GetRequiredService<ArchivePolling>();
// Every run of a schedule reads the archive through its host, which takes archive.json's settings first.
var schedules = server.Services.GetRequiredService<ServerScheduleHost>();
// Nothing changed: the served archive (the one an administrator's edit put there) is not replaced by a row read again.
var served = archive.Current;
await polling.PollAsync(context.Cancellation);
Assert.True(ReferenceEquals(served, archive.Current), "a poll that registered nothing keeps the served archive");
await schedules.GetArchiveAsync(context.Cancellation);
Assert.True(ReferenceEquals(served, archive.Current), "a refresh that registered nothing keeps the served archive");
// A desktop sharing the archive changed its folder template and proxy size in archive.json.
var path = new ArchivePaths(archive.Root).ManifestPath;
@@ -197,14 +229,14 @@ public sealed class ArchiveModuleTests(TestContext context)
ProxyPolicy = manifest.ProxyPolicy with { LongEdge = 2560 },
});
await polling.PollAsync(context.Cancellation);
Assert.Equal("{camera}/{date}", Assert.NotNull(await schedules.GetArchiveAsync(context.Cancellation)).FolderTemplate);
// Uploads (the index row) and the admin panel (the served archive) follow it.
Assert.Equal(("{camera}/{date}", 2560), (archive.Current.FolderTemplate, archive.Current.ProxyLongEdge));
var row = Assert.NotNull(await server.Database.Archives.GetAsync(archive.Id, context.Cancellation));
Assert.Equal(("{camera}/{date}", 2560), (row.FolderTemplate, row.ProxyLongEdge));
// The admin panel opens before the next poll: its form, which saves every field, starts from the desktop's change.
// The admin panel opens before the next run: its form, which saves every field, starts from the desktop's change.
ManifestStore.WriteArchive(path, ManifestStore.ReadArchive(path) with { LayoutTemplates = manifest.LayoutTemplates with { Folder = "{year}/{camera}" } });
var admin = await server.AdminAsync();
using (var read = await admin.GetAsync("/api/v1/archive/settings"))
@@ -275,6 +307,13 @@ public sealed class ArchiveModuleTests(TestContext context)
}
}
/// <summary>Runs the archive-scan system schedule now, as its next run would.</summary>
private static async Task<ScheduleRunDto> RunScanAsync(TestServer server)
{
var schedule = Assert.NotNull(await server.Database.Schedules.GetBySystemKeyAsync(ServerScheduleHost.ArchiveScan));
return Assert.NotNull(await server.Services.GetRequiredService<SchedulerHost>().Scheduler.RunNowAsync(schedule.Id, null));
}
/// <summary>Waits for the scan queued at start to finish: its sequences are indexed before it ends.</summary>
private static async Task UntilScannedAsync(TestServer server)
{
@@ -335,7 +335,7 @@ public sealed class UploadTests(TestContext context)
// Upload rows carry real timestamps; the sweep looks 48 h past the moved clock.
clock.Advance(TimeSpan.FromHours(49));
await server.Services.GetRequiredService<UploadMaintenance>().SweepAsync(context.Cancellation);
await server.Services.GetRequiredService<UploadMaintenance>().SweepAsync(cancellationToken: context.Cancellation);
Assert.False(store.Exists(id));
using var state = await uploader.GetAsync($"/api/v1/uploads/{id}");
Assert.Equal("cancelled", (await state.ReadAsync(ProtocolJson.Default.UploadState)).State);
+1
View File
@@ -68,6 +68,7 @@ public sealed class TestServer : IAsyncDisposable
LoginAttemptsPerMinute = 1000,
// Info lines of the ~55 servers the suite starts would bury failures in the CI log.
LogLevel = Microsoft.Extensions.Logging.LogLevel.Warning,
ConsoleLogLevel = Microsoft.Extensions.Logging.LogLevel.Warning,
};
Directory.CreateDirectory(options.ArchivePath);
configure?.Invoke(options);