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

@@ -1,9 +1,11 @@
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.App.Tests.Uploader;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Scheduling;
using Chronos.Testing;
namespace Chronos.App.Tests.Infrastructure;
@@ -21,7 +23,7 @@ public sealed class AppServicesTests
[Test]
[WindowsOnly]
public void ExitStopsPollingAndTheEngineWhileTheUiThreadWaits()
public void ExitStopsTheSchedulesAndTheEngineWhileTheUiThreadWaits()
{
var environment = AppEnvironment.ForCapture();
try
@@ -33,11 +35,14 @@ public sealed class AppServicesTests
await new ArchiveService(setup).CreateAsync(root, "Exit");
var services = new AppServices(environment, new AppSettings { Language = "en", LastArchivePath = root }, () => { }, new NoDialogs());
await services.OpenAsync(environment.DatabasePath);
// The archive was reopened and its first rescan queued: polling now waits for the next one.
// The archive was reopened, then the schedules started (owner review 2, R10) and its scan schedule ran at once,
// as the rescans did at start: a scan of it is queued without waiting for the interval.
Assert.True(await services.SchedulerReady, "the schedules started");
var scan = Assert.NotNull(await services.Database!.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan));
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while ((await services.Database!.Jobs.ListAsync(null, JobKind.Scan)).Items.Count == 0)
while (!(await services.Database!.Jobs.ListAsync(null, JobKind.Scan)).Items.Any(j => j.ScheduleId == scan.Id))
{
Assert.True(DateTime.UtcNow < until, "no rescan queued");
Assert.True(DateTime.UtcNow < until, "no scan at start");
await Task.Delay(50);
}
@@ -51,10 +56,13 @@ public sealed class AppServicesTests
}
}
/// <summary>BRIEF §7: polling follows the archive folder, also one chosen after the start (first run, Settings, relink).</summary>
/// <summary>
/// BRIEF §7, owner review 2 R10: the scheduled scans follow the archive folder, also one chosen after the start (first
/// run, Settings, relink).
/// </summary>
[Test]
[WindowsOnly]
public void RescansFollowTheArchiveFolderChosenAfterTheStart()
public void ScheduledScansFollowTheArchiveFolderChosenAfterTheStart()
{
var environment = AppEnvironment.ForCapture();
try
@@ -67,20 +75,21 @@ public sealed class AppServicesTests
try
{
await services.OpenAsync(environment.DatabasePath);
Assert.Null(await services.RescanAsync());
// The rescans run all the same: Settings › Archive › Rescan every reaches them.
settings.ScanIntervalMinutes = 30;
services.SaveSettings();
Assert.Equal<TimeSpan?>(TimeSpan.FromMinutes(30), services.PollingPeriod);
Assert.True(await services.SchedulerReady, "the schedules started");
Assert.Null(await services.ScheduleHost.GetArchiveAsync(default));
// The scans run all the same, on the schedule seeded from the former Settings › Archive › Rescan every.
var scan = Assert.NotNull(await services.Database!.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan));
Assert.Equal("every:10m", scan.Recurrence);
Assert.Equal(ScheduleOutcome.SkippedOffline, (await services.Scheduler!.RunNowAsync(scan.Id, null))?.Outcome);
// The first-run dialog creates an archive: the next rescan is of it.
// The first-run dialog creates an archive: the schedules work on it.
var firstRoot = Path.Combine(environment.DataDirectory, "first");
await services.ArchiveSetup.CreateAsync(firstRoot);
var first = Assert.NotNull(await services.RescanAsync());
var first = Assert.NotNull(await services.ScheduleHost.GetArchiveAsync(default));
Assert.Equal("first", first.Name);
// Settings › Archive moves to another archive, which the index lists after the first one: the next rescan
// is of the archive at the folder, no longer of the first one.
// Settings › Archive moves to another archive, which the index lists after the first one: the next scheduled
// scan is of the archive at the folder, no longer of the first one.
var other = Path.Combine(environment.DataDirectory, "zeta");
await new ArchiveService(services.Database!).CreateAsync(other, "zeta");
Assert.Equal("first", (await services.Database!.Archives.ListAsync())[0].Name);
@@ -89,15 +98,57 @@ public sealed class AppServicesTests
var scansOfFirst = await ScansOfAsync(first.Id);
settings.LastArchivePath = other;
services.SaveSettings();
var rescanned = Assert.NotNull(await services.RescanAsync());
var rescanned = Assert.NotNull(await services.ScheduleHost.GetArchiveAsync(default));
Assert.Equal("zeta", rescanned.Name);
Assert.Equal(ScheduleOutcome.Queued, (await services.Scheduler.RunNowAsync(scan.Id, null))?.Outcome);
Assert.True(await ScansOfAsync(rescanned.Id) > 0, "the archive at the folder is rescanned");
Assert.Equal(scansOfFirst, await ScansOfAsync(first.Id));
// And back: the folder decides, whatever the order of the index.
settings.LastArchivePath = firstRoot;
services.SaveSettings();
Assert.Equal(first.Id, (await services.RescanAsync())?.Id);
Assert.Equal(first.Id, (await services.ScheduleHost.GetArchiveAsync(default))?.Id);
}
finally
{
Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10)), "services stopped");
}
});
}
finally
{
environment.DeleteCaptureData();
}
}
/// <summary>
/// Owner review 2, R10: when the index does not open, the schedules are known not to run at once, so Jobs › Scheduled
/// says so instead of waiting for them with an empty tab.
/// </summary>
[Test]
[WindowsOnly]
public void AnIndexThatDoesNotOpenTellsTheScheduledTabTheSchedulesDoNotRun()
{
var environment = AppEnvironment.ForCapture();
try
{
SingleThreadedContext.Run(async () =>
{
// "File is not a database", and no staged restore to recover it.
Directory.CreateDirectory(Path.GetDirectoryName(environment.DatabasePath)!);
await File.WriteAllBytesAsync(environment.DatabasePath, [.. Enumerable.Repeat((byte)0x5A, 8192)]);
var services = new AppServices(environment, new AppSettings { Language = "en" }, () => { }, new NoDialogs());
try
{
await services.OpenAsync(environment.DatabasePath);
Assert.NotNull(services.OpenError);
var ready = services.SchedulerReady;
Assert.Same(ready, await Task.WhenAny(ready, Task.Delay(TimeSpan.FromSeconds(TestTiming.Budget(10)))));
Assert.False(await ready, "no schedules without an index");
using var schedules = new SchedulesViewModel(() => services.Scheduler, () => services.Database, _ => false, (_, _, _) => { }, _ => Task.CompletedTask);
await schedules.AttachAsync(services.SchedulerReady);
Assert.True(schedules.IsLoaded && schedules.IsUnavailable && !schedules.IsRunning, "the tab shows that the schedules do not run");
}
finally
{
@@ -0,0 +1,77 @@
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.Testing;
namespace Chronos.App.Tests.Infrastructure;
/// <summary>Owner review 2, R10: the housekeeping trims the cache to its limit, oldest files first, never what is in use or kept whole.</summary>
public sealed class CacheStoreTests(TestContext context)
{
private static readonly DateTime Start = new(2026, 9, 1, 8, 0, 0, DateTimeKind.Utc);
/// <summary>A cache file of <paramref name="bytes"/> last written <paramref name="day"/> days after <see cref="Start"/>.</summary>
private static string Write(string folder, string name, int bytes, int day)
{
var path = Path.Combine(folder, name);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllBytes(path, new byte[bytes]);
File.SetLastWriteTimeUtc(path, Start.AddDays(day));
return path;
}
[Test]
public void TheOldestFilesGoFirstUntilTheCacheFits()
{
var cache = context.CreateTempDirectory("cache");
CacheStore.Prepare(cache);
var oldest = Write(cache, "spill-1.bin", 400, 1);
var older = Write(cache, Path.Combine("render", "spill-2.bin"), 400, 2);
var recent = Write(cache, "spill-3.bin", 400, 3);
var size = CacheStore.Size(cache);
var result = Assert.NotNull(CacheStore.Trim(cache, size - 500));
// 400 bytes were not enough: the two oldest went, the newest and the marker stay.
Assert.Equal((size, 800L, 2), (result.Before, result.Freed, result.Deleted));
Assert.Equal(size - 800, result.After);
Assert.False(File.Exists(oldest));
Assert.False(File.Exists(older));
Assert.True(File.Exists(recent));
Assert.True(CacheStore.IsOwned(cache), "the marker stays");
// Within the limit: nothing to do.
Assert.Equal(0, CacheStore.Trim(cache, 1L << 30)!.Deleted);
}
[Test]
public void FilesInUseAndKeptFoldersStay()
{
var cache = context.CreateTempDirectory("cache");
CacheStore.Prepare(cache);
var proxies = Write(cache, Path.Combine("proxies", "server", "sequence", "frame.jpg"), 1000, 0);
var busy = Write(cache, "spill-busy.bin", 1000, 1);
var free = Write(cache, "spill-free.bin", 1000, 2);
using (new FileStream(busy, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var result = Assert.NotNull(CacheStore.Trim(cache, 0, CacheTrimStep.Kept));
Assert.Equal((1000L, 1), (result.Freed, result.Deleted));
}
Assert.True(File.Exists(proxies), "a kept folder is never trimmed");
Assert.True(File.Exists(busy), "a file in use is skipped");
Assert.False(File.Exists(free));
}
[Test]
public void AFolderChronosDidNotMakeIsLeftAlone()
{
var folder = context.CreateTempDirectory("photos");
var photo = Write(folder, "IMG_0001.JPG", 1000, 0);
Assert.Null(CacheStore.Trim(folder, 0));
Assert.True(File.Exists(photo));
Assert.Equal((0L, 0L, 0), CacheStore.Trim(Path.Combine(folder, "missing"), 0) is { } none ? (none.Before, none.Freed, none.Deleted) : (-1L, -1L, -1));
}
}
@@ -0,0 +1,191 @@
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Housekeeping;
using Chronos.Data.Scheduling;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.App.Tests.Jobs;
/// <summary>
/// Owner review 2, R10: the desktop's timers became visible system schedules: the archive scan (seeded once from the
/// former Rescan every setting), the index backup that replaced the daily backup loop, and the housekeeping with the cache
/// trim; the schedules work on the archive at Settings › Archive's folder while it is online.
/// </summary>
public sealed class DesktopScheduleHostTests(TestContext context)
{
[Test]
public async Task TheScanScheduleIsSeededOnceFromTheFormerRescanInterval()
{
var settings = new AppSettings { Language = "en", ScanIntervalMinutes = 30, DeepAnalysisAfterScan = true };
await using var fx = await ScheduleFixture.CreateAsync(context, settings);
var scheduler = await fx.StartAsync();
var scan = Assert.NotNull(await fx.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan));
Assert.Equal(("every:30m", false, JobPriority.Background, true, ScheduleActions.Scan), (scan.Recurrence, scan.CatchUp, scan.Priority, scan.Enabled, scan.Action));
// The deep analysis is not frozen into the schedule: each run reads Settings › Analysis › After a scan.
Assert.Null(ScheduleMapping.Parameters(scan).Deep);
Assert.Equal(fx.Clock.Now.AddMinutes(30), scan.NextRun);
// The user edits the schedule in Jobs › Scheduled; the old setting changes (or never changes again): the next
// start keeps the schedule as it is.
Assert.Null((await scheduler.UpdateAsync(scan.Id, new UpdateScheduleRequest(Recurrence: new("every", Every: 2, Unit: "hours")))).Problem);
settings.ScanIntervalMinutes = 5;
await fx.StartAsync();
var kept = Assert.NotNull(await fx.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan));
Assert.Equal((scan.Id, "every:2h"), (kept.Id, kept.Recurrence));
Assert.Count(3, (await fx.Db.Schedules.ListAsync()).Where(s => s.IsSystem));
// Reset goes back to what the host seeds with.
Assert.Null((await fx.Scheduler!.ResetAsync(scan.Id)).Problem);
Assert.Equal("every:5m", (await fx.Db.Schedules.GetAsync(scan.Id))!.Recurrence);
}
/// <summary>
/// Owner review 2, R10: the scheduled scans follow Settings › Analysis › After a scan as it is at each run, like the
/// scans started by hand, so that checkbox's tooltip stays true; and the archive is scanned right after it was opened
/// (once per start, and again when an unplugged archive is back), as the rescans did.
/// </summary>
[Test]
public async Task TheScanRunsAtOnceAndFollowsTheDeepAnalysisSettingAtEachRun()
{
var settings = new AppSettings { Language = "en", DeepAnalysisAfterScan = false };
await using var fx = await ScheduleFixture.CreateAsync(context, settings);
var archive = await fx.Archives.CreateAsync(Path.Combine(fx.Folder, "archive"), "archive");
settings.LastArchivePath = archive.RootPath;
var started = fx.Clock.Now;
var scheduler = await fx.StartAsync();
// Right after the start, not one interval later.
var first = Assert.NotNull(await scheduler.RunSystemNowAsync(DesktopScheduleHost.ArchiveScan, started));
Assert.Equal(ScheduleOutcome.Queued, first.Outcome);
Assert.False(await DeepAsync(fx, first.JobId!.Value));
Assert.Null(await scheduler.RunSystemNowAsync(DesktopScheduleHost.ArchiveScan, started));
// The setting changes after the schedule was seeded: the next run follows it.
settings.DeepAnalysisAfterScan = true;
await fx.Db.Jobs.SetStateAsync(first.JobId!.Value, JobState.Done);
var second = Assert.NotNull(await scheduler.RunSystemNowAsync(DesktopScheduleHost.ArchiveScan));
Assert.Equal(ScheduleOutcome.Queued, second.Outcome);
Assert.True(await DeepAsync(fx, second.JobId!.Value));
Assert.True(fx.Host.DeepAnalysisAfterScan);
// The editor offers no deep switch for a scan (only for an analysis), so a scan schedule never freezes it.
using var vm = await fx.ViewModelAsync();
vm.NewCommand.Execute(null);
var editor = Assert.NotNull(vm.Editor);
editor.SelectedAction = editor.ActionOptions.Single(a => a.Name == ScheduleActions.Scan);
Assert.True(editor.ShowsForce && !editor.ShowsDeep, "a scan's switches: a full scan only");
}
/// <summary>Whether the scan job <paramref name="id"/> gives what it finds a deep analysis.</summary>
private static async Task<bool> DeepAsync(ScheduleFixture fx, Guid id)
{
var job = Assert.NotNull(await fx.Db.Jobs.GetAsync(id));
Assert.Equal(JobKind.Scan, job.Kind);
using var parameters = System.Text.Json.JsonDocument.Parse(job.ParametersJson!);
return parameters.RootElement.GetProperty("deepAnalysis").GetBoolean();
}
[Test]
public void TheFormerIntervalIsClampedToWhatAnIntervalAccepts()
{
Assert.Equal(ScheduleRecurrence.MinMinutes, DesktopScheduleHost.ScanMinutes(new AppSettings { ScanIntervalMinutes = 1 }));
Assert.Equal(AppSettings.DefaultScanIntervalMinutes, DesktopScheduleHost.ScanMinutes(new AppSettings()));
Assert.Equal(ScheduleRecurrence.MaxMinutes, DesktopScheduleHost.ScanMinutes(new AppSettings { ScanIntervalMinutes = 100_000 }));
}
[Test]
public async Task TheBackupScheduleReplacesTheDailyBackupLoop()
{
await using var fx = await ScheduleFixture.CreateAsync(context);
var scheduler = await fx.StartAsync();
var backup = Assert.NotNull(await fx.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.IndexBackup));
Assert.Equal(("every:1d", true, JobPriority.Background, ScheduleActions.Backup), (backup.Recurrence, backup.CatchUp, backup.Priority, backup.Action));
Assert.Equal(DatabaseBackups.Keep, ScheduleMapping.Parameters(backup).Keep);
Assert.Equal(fx.Clock.Now.AddDays(1), backup.NextRun);
// Chronos was closed for two days: the missed copy is made once at start (catch-up, as the housekeeping's run; the
// scan has none and just moves on).
fx.Clock.Advance(TimeSpan.FromDays(2.5));
Assert.Equal(2, await scheduler.RunDueAsync());
var job = (await fx.Db.Jobs.ListByScheduleAsync(backup.Id)).Single();
Assert.Equal((JobKind.Backup, JobPriority.Background, JobState.Queued), (job.Kind, job.Priority, job.State));
Assert.Equal(0, await scheduler.RunDueAsync());
// The engine makes the copy in the backups folder next to the index, as the loop did.
await fx.Engine.StartAsync();
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while ((await fx.Db.Jobs.GetAsync(job.Id))!.State is JobState.Queued or JobState.Running)
{
Assert.True(DateTime.UtcNow < until, "the backup job did not finish");
await Task.Delay(50);
}
Assert.Equal(JobState.Done, (await fx.Db.Jobs.GetAsync(job.Id))!.State);
Assert.Count(1, DatabaseBackups.List(fx.Backups, fx.DatabasePath));
}
/// <summary>
/// The first start after the upgrade: the daily loop made a copy at start once the newest was a day old, so the index
/// backup is seeded due when it is (copied in the first pass); a fresher copy waits for its first day as a new install does.
/// </summary>
[Test]
public async Task TheFirstStartAfterTheUpgradeCopiesWhenTheNewestCopyIsADayOld()
{
await using (var stale = await ScheduleFixture.CreateAsync(context))
{
Directory.CreateDirectory(stale.Backups);
File.WriteAllText(Path.Combine(stale.Backups, $"chronos-{ScheduleFixture.T0.AddDays(-7):yyyyMMdd-HHmmss}-000.db"), "copy");
await stale.StartAsync();
var backup = Assert.NotNull(await stale.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.IndexBackup));
Assert.Equal((ScheduleOutcome.Queued, ScheduleFixture.T0.AddDays(1)), (backup.LastOutcome!, backup.NextRun!.Value));
Assert.Equal(JobKind.Backup, Assert.NotNull(await stale.Db.Jobs.GetAsync(backup.LastJobId!.Value)).Kind);
}
await using var fresh = await ScheduleFixture.CreateAsync(context);
Directory.CreateDirectory(fresh.Backups);
File.WriteAllText(Path.Combine(fresh.Backups, $"chronos-{ScheduleFixture.T0.AddHours(-2):yyyyMMdd-HHmmss}-000.db"), "copy");
await fresh.StartAsync();
var waiting = Assert.NotNull(await fresh.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.IndexBackup));
Assert.Equal(((string?)null, ScheduleFixture.T0.AddDays(1)), (waiting.LastOutcome, waiting.NextRun!.Value));
}
[Test]
public async Task TheHousekeepingRemovesOldHistoryAndTrimsTheCache()
{
await using var fx = await ScheduleFixture.CreateAsync(context);
await fx.StartAsync();
var housekeeping = Assert.NotNull(await fx.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.Housekeeping));
Assert.Equal(("daily:04:00", true, ScheduleActions.Cleanup), (housekeeping.Recurrence, housekeeping.CatchUp, housekeeping.Action));
var parameters = ScheduleMapping.Parameters(housekeeping);
Assert.SequenceEqual([CleanupSteps.JobHistory, CacheTrimStep.StepName], parameters.Steps!);
Assert.Equal(CleanupSteps.DefaultHistoryDays, parameters.OlderThanDays);
// The host's step is one the clean-up jobs run, after the shared ones.
Assert.SequenceEqual([CleanupSteps.JobHistory, CleanupSteps.Audit, CleanupSteps.TrashReport, CacheTrimStep.StepName], fx.Host.CleanupSteps);
Assert.Equal(ScheduleRecurrence.DailyAt(new TimeOnly(4, 0)).Next(fx.Clock.Now, TimeZoneInfo.Utc), housekeeping.NextRun);
}
[Test]
public async Task SchedulesWorkOnTheArchiveAtTheFolderWhileItIsOnline()
{
await using var fx = await ScheduleFixture.CreateAsync(context);
Assert.Null(await fx.Host.GetArchiveAsync(context.Cancellation));
var first = await fx.Archives.CreateAsync(Path.Combine(fx.Folder, "first"), "first");
var other = await fx.Archives.CreateAsync(Path.Combine(fx.Folder, "other"), "other");
// No folder chosen: the first archive of the index; then the one at the folder.
Assert.Equal(first.Id, (await fx.Host.GetArchiveAsync(context.Cancellation))?.Id);
fx.Settings.LastArchivePath = other.RootPath;
Assert.Equal(other.Id, (await fx.Host.GetArchiveAsync(context.Cancellation))?.Id);
// Unplugged: none, so the runs that need it are skipped (and the scheduler logs it) until it is back.
var moved = other.RootPath + "-away";
Directory.Move(other.RootPath, moved);
Assert.Null(await fx.Host.GetArchiveAsync(context.Cancellation));
Directory.Move(moved, other.RootPath);
Assert.Equal(other.Id, (await fx.Host.GetArchiveAsync(context.Cancellation))?.Id);
}
}
@@ -30,6 +30,7 @@ public sealed class JobNoticesTests
[Case(JobKind.LightAnalyse)]
[Case(JobKind.Thumbs)]
[Case(JobKind.Proxies)]
[Case(JobKind.Cleanup)]
public void UpkeepAndScansEndSilently(JobKind kind)
{
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Running, Job(kind, JobState.Done)));
@@ -41,6 +42,7 @@ public sealed class JobNoticesTests
[Case(JobKind.Download)]
[Case(JobKind.Duplicates)]
[Case(JobKind.Orphans)]
[Case(JobKind.Backup)]
public void EveryOtherFailureIsSaid(JobKind kind)
{
// An import announces its result on the Import screen, a download on its Library card and Server row.
@@ -140,6 +142,44 @@ public sealed class JobNoticesTests
Assert.Empty(endings.Take(model.IsBusy));
}
/// <summary>Owner review 2, R10: a schedule's background run is said only when it fails, unless the next run repeats it anyway.</summary>
[Theory]
[Case(JobKind.Backup)]
[Case(JobKind.Verify)]
[Case(JobKind.Maintenance)]
[Case(JobKind.Duplicates)]
[Case(JobKind.DeepAnalyse)]
public void AScheduledBackgroundRunIsSaidOnlyWhenItFails(JobKind kind)
{
var schedule = Guid.CreateVersion7();
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Running, Job(kind, JobState.Done, JobPriority.Background) with { ScheduleId = schedule }));
Assert.Equal(JobNotice.Failed, JobNotices.For(JobState.Running, Job(kind, JobState.Failed, JobPriority.Background) with { ScheduleId = schedule }));
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Failed, Job(kind, JobState.Failed, JobPriority.Background) with { ScheduleId = schedule }));
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Running, Job(kind, JobState.Cancelled, JobPriority.Background) with { ScheduleId = schedule }));
// The same work queued in the background by something else stays silent.
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Running, Job(kind, JobState.Failed, JobPriority.Background)));
}
[Theory]
[Case(JobKind.Scan)]
[Case(JobKind.Thumbs)]
[Case(JobKind.Proxies)]
[Case(JobKind.LightAnalyse)]
[Case(JobKind.Cleanup)]
public void AScheduledUpkeepRunEndsSilently(JobKind kind)
{
var schedule = Guid.CreateVersion7();
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Running, Job(kind, JobState.Done, JobPriority.Background) with { ScheduleId = schedule }));
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Running, Job(kind, JobState.Failed, JobPriority.Background) with { ScheduleId = schedule }));
}
[Test]
public void AScheduledRunAtAHigherPriorityIsSaidAsAnyOther()
{
var verify = Job(JobKind.Verify, JobState.Done, JobPriority.Normal) with { ScheduleId = Guid.CreateVersion7() };
Assert.Equal(JobNotice.Done, JobNotices.For(JobState.Running, verify));
}
private static Job Job(JobKind kind, JobState state, JobPriority priority = JobPriority.User) => new()
{
Id = Guid.CreateVersion7(),
@@ -0,0 +1,97 @@
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Scheduling;
using Chronos.Testing;
namespace Chronos.App.Tests.Jobs;
/// <summary>A clock the test moves by hand; its timers are the system's.</summary>
internal sealed class ManualClock(DateTimeOffset start) : TimeProvider
{
private long _ticks = start.UtcTicks;
public DateTimeOffset Now => GetUtcNow();
public override DateTimeOffset GetUtcNow() => new(Interlocked.Read(ref _ticks), TimeSpan.Zero);
public void Advance(TimeSpan by) => Interlocked.Add(ref _ticks, by.Ticks);
}
/// <summary>
/// The desktop's schedules as <see cref="AppServices"/> composes them, without the shell: an SQLite index file, the archive
/// engine with the cache-trim step and a backups folder, a job engine that is not started (queued jobs stay queued), and a
/// <see cref="Scheduler"/> on <see cref="DesktopScheduleHost"/> with a clock the test moves.
/// </summary>
internal sealed class ScheduleFixture : IAsyncDisposable
{
public static readonly DateTimeOffset T0 = new(2026, 10, 2, 9, 0, 0, TimeSpan.Zero);
private ScheduleFixture(TestContext context, AppSettings settings, ChronosDatabase db, string folder)
{
Context = context;
Settings = settings;
Db = db;
Folder = folder;
Cache = Path.Combine(folder, "cache");
Backups = Path.Combine(folder, DatabaseBackups.DirectoryName);
Archives = new ArchiveService(db, new ArchiveServiceOptions
{
Owner = "test",
CleanupSteps = [new CacheTrimStep(() => Cache, () => CacheLimitBytes)],
BackupDirectory = Backups,
});
Engine = new JobEngine(db, Archives.CreateJobHandlers(), new JobEngineOptions { WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(100) });
Host = new DesktopScheduleHost(settings, () => Db, () => Archives) { TimeZone = TimeZoneInfo.Utc };
}
public TestContext Context { get; }
public AppSettings Settings { get; }
public ChronosDatabase Db { get; }
public string Folder { get; }
public string Cache { get; }
public string Backups { get; }
public long CacheLimitBytes { get; set; } = 1L << 30;
public ArchiveService Archives { get; }
public JobEngine Engine { get; }
public DesktopScheduleHost Host { get; }
public ManualClock Clock { get; } = new(T0);
public Scheduler? Scheduler { get; private set; }
public string DatabasePath => Path.Combine(Folder, "chronos.db");
public static async Task<ScheduleFixture> CreateAsync(TestContext context, AppSettings? settings = null)
{
var folder = context.CreateTempDirectory("schedules");
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(folder, "chronos.db")), context.Cancellation);
return new ScheduleFixture(context, settings ?? new AppSettings { Language = "en" }, db, folder);
}
/// <summary>Starts a scheduler on the host (a previous one is stopped first, as at the next start of the app).</summary>
public async Task<Scheduler> StartAsync()
{
if (Scheduler is not null) await Scheduler.DisposeAsync();
Scheduler = new Scheduler(Db, Engine, new SchedulerOptions { Time = Clock, Tick = TimeSpan.FromHours(1) });
await Scheduler.StartAsync(Host, Context.Cancellation);
return Scheduler;
}
/// <summary>The view model of Jobs › Scheduled on this scheduler; deletes and resets are confirmed with <paramref name="confirm"/>.</summary>
public async Task<SchedulesViewModel> ViewModelAsync(Func<ConfirmRequest, bool>? confirm = null, List<string>? toasts = null)
{
var scheduler = Scheduler ?? await StartAsync();
var vm = new SchedulesViewModel(() => scheduler, () => Db, confirm ?? (_ => true), (title, _, _) => toasts?.Add(title), _ => Task.CompletedTask);
await vm.AttachAsync(Task.FromResult(true));
return vm;
}
public async ValueTask DisposeAsync()
{
if (Scheduler is not null) await Scheduler.DisposeAsync();
await Engine.DisposeAsync();
await Db.DisposeAsync();
}
}
@@ -0,0 +1,79 @@
using System.Globalization;
using Chronos.App.Jobs;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Scheduling;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.App.Tests.Jobs;
/// <summary>
/// Jobs › Scheduled in another language (owner review 2, R10). These switch the process-wide UI language, so the class is
/// serial: in parallel it would race with the English assertions of the classes running beside it.
/// </summary>
[Serial]
public sealed class ScheduleLanguageTests(TestContext context)
{
/// <summary>The days of a weekly schedule read in the order of the editor's toggles: from the UI language's first day.</summary>
[Test]
public void WeeklyDaysFollowTheWeekOfTheUiLanguage()
{
var weekend = ScheduleRecurrence.WeeklyAt([DayOfWeek.Saturday, DayOfWeek.Sunday], new TimeOnly(3, 0));
try
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
Assert.Equal(DayOfWeek.Sunday, Loc.Culture.DateTimeFormat.FirstDayOfWeek);
Assert.Equal(Loc.L("Jobs.Schedule.DayList", ScheduleText.DayShort(DayOfWeek.Sunday), ScheduleText.DayShort(DayOfWeek.Saturday)),
ScheduleText.Days(weekend.Days));
Assert.Equal(Loc.L("Jobs.Schedule.When.Weekly", ScheduleText.Days(weekend.Days), ScheduleText.Time(new TimeOnly(3, 0))), ScheduleText.When(weekend));
Loc.SetCulture(CultureInfo.GetCultureInfo("it"));
Assert.Equal(DayOfWeek.Monday, Loc.Culture.DateTimeFormat.FirstDayOfWeek);
Assert.Equal(Loc.L("Jobs.Schedule.DayList", ScheduleText.DayShort(DayOfWeek.Saturday), ScheduleText.DayShort(DayOfWeek.Sunday)),
ScheduleText.Days(weekend.Days));
Assert.Equal(Loc.L("Jobs.Schedule.DayList", ScheduleText.DayShort(DayOfWeek.Monday), ScheduleText.DayShort(DayOfWeek.Thursday)),
ScheduleText.Days([DayOfWeek.Thursday, DayOfWeek.Monday]));
}
finally
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
}
/// <summary>The editor's dropdowns say their choices in the new language, and keep what was chosen.</summary>
[Test]
public async Task TheOpenEditorSaysItsChoicesInTheNewLanguage()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
await using var fx = await ScheduleFixture.CreateAsync(context);
using var vm = await fx.ViewModelAsync();
vm.NewCommand.Execute(null);
var editor = Assert.NotNull(vm.Editor);
editor.SelectedAction = editor.ActionOptions.Single(a => a.Name == ScheduleActions.Verify);
editor.SelectedUnit = editor.Units.Single(u => u.Value == RecurrenceUnit.Minutes);
editor.SelectedPriority = editor.Priorities.Single(p => p.Value == JobPriority.Normal);
Assert.Equal(("minutes", "Normal"), (editor.SelectedUnit.Label, editor.SelectedPriority.Label));
var actions = editor.ActionOptions;
try
{
Loc.SetCulture(CultureInfo.GetCultureInfo("it"));
Assert.SequenceEqual(Enum.GetValues<RecurrenceUnit>().Select(u => Loc.L("Jobs.Editor.Unit." + u)), editor.Units.Select(u => u.Label));
Assert.SequenceEqual(["In background", "Normale", "Alta"], editor.Priorities.Select(p => p.Label));
Assert.Equal((RecurrenceUnit.Minutes, "minuti"), (editor.SelectedUnit.Value, editor.SelectedUnit.Label));
Assert.Equal((JobPriority.Normal, "Normale"), (editor.SelectedPriority.Value, editor.SelectedPriority.Label));
Assert.True(editor.Units.Any(u => ReferenceEquals(u, editor.SelectedUnit)) && editor.Priorities.Any(p => ReferenceEquals(p, editor.SelectedPriority)),
"the choices are among the new options");
// The actions are new options too, so their dropdown reads their names again.
Assert.False(ReferenceEquals(actions, editor.ActionOptions), "the action list was built again");
Assert.Equal(("Scansione archivio", ScheduleActions.Verify), (editor.ActionOptions[0].Label, editor.SelectedAction.Name));
Assert.True(editor.ActionOptions.Any(o => ReferenceEquals(o, editor.SelectedAction)), "the action is among the new options");
}
finally
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
}
}
@@ -0,0 +1,117 @@
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using Chronos.App.Jobs;
using Chronos.App.Sections;
using Chronos.App.Shell;
using Chronos.App.Tests.Windows;
using Chronos.Core.Localization;
using Chronos.Testing;
namespace Chronos.App.Tests.Jobs;
/// <summary>
/// Jobs › Scheduled on the capture sample (owner review 2, R10): the tab draws in both themes, every row and control is
/// named and has a tooltip, system rows reset and the user's delete, a schedule's run opens in the Queue tab with its
/// "Scheduled" pill, and the editor opens over the screen.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class ScheduledTabTests
{
[Test]
public Task TheScheduledTabListsTheSchedulesAndLeadsToTheirJobs() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var shell = app.Shell;
await app.Sample.FillAsync();
await shell.Jobs.ReloadAsync();
var schedules = shell.Jobs.Schedules;
await schedules.Attached;
await schedules.ReloadAsync();
shell.Navigate(SectionKey.Jobs);
shell.Jobs.TabIndex = 1;
await app.ExpectAsync<SchedulesView>("jobs-scheduled");
Assert.SequenceEqual(["Archive scan", "Index backup", "Housekeeping", "Weekly integrity check", "Monthly orphans report"], schedules.Rows.Select(r => r.Name));
var items = app.FindAll<ListBoxItem>().Where(i => i.DataContext is ScheduleRowViewModel && i.IsVisible).ToList();
Assert.Count(5, items);
foreach (var item in items)
{
var row = (ScheduleRowViewModel)item.DataContext;
Assert.Equal(row.AccessibleName, AutomationProperties.GetName(item));
var controls = Descendants<ButtonBase>(item).Where(b => b.IsVisible).ToList();
// The switch, Run now, Edit, and Reset or Delete.
Assert.Count(4, controls);
Assert.True(controls.All(c => c.ToolTip is not null && AutomationProperties.GetName(c).Contains(row.Name, StringComparison.Ordinal)),
$"every control of {row.Name} has a tooltip and names its row");
var last = Descendants<Button>(item).Last(b => b.IsVisible);
Assert.Equal(Loc.L(row.IsSystem ? "Jobs.Schedule.Reset" : "Jobs.Schedule.Delete"), last.Content);
}
// The queue's toolbar gives way to New schedule.
Assert.True(app.FindAll<Button>().Any(b => b.IsVisible && Equals(b.Content, Loc.L("Jobs.Schedule.New"))), "New schedule is on the toolbar");
Assert.False(app.FindAll<TextBox>().Any(t => t.IsVisible && AutomationProperties.GetName(t) == Loc.L("Jobs.Search")), "the queue's search is hidden");
// The weekly check's run waits in the queue: Show in queue opens it there, expanded.
var weekly = schedules.Rows.Single(r => r.Name == "Weekly integrity check");
schedules.Selected = weekly;
await schedules.RunsLoading;
var run = Assert.NotNull(schedules.Runs.SingleOrDefault());
Assert.Equal(weekly.Schedule.LastJobId, run.Id);
await shell.Jobs.ShowJobAsync(run.Id);
Assert.True(shell.Jobs.IsQueue, "the Queue tab is shown");
var shown = shell.Jobs.Rows.Single(r => r.Id == run.Id);
Assert.True(shown.IsExpanded && shown.IsScheduled, "the job is expanded and marked as scheduled");
await app.ExpectAsync<JobsView>("jobs-from-schedule");
var pills = app.FindAll<Border>().Where(b => b.IsVisible && Equals(b.ToolTip, Loc.L("Tooltips.Jobs.Scheduled"))).ToList();
Assert.True(pills.Count >= 1, "a scheduled job carries the pill");
});
[Test]
public Task TheEditorOpensOverTheScreenAndCloses() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var shell = app.Shell;
await app.Sample.FillAsync();
var schedules = shell.Jobs.Schedules;
await schedules.Attached;
await schedules.ReloadAsync();
shell.Navigate(SectionKey.Jobs);
shell.Jobs.TabIndex = 1;
var weekly = schedules.Rows.Single(r => r.Name == "Weekly integrity check");
weekly.EditCommand.Execute(null);
var editor = Assert.NotNull(schedules.Editor);
Assert.False(shell.Jobs.IsContentEnabled);
await app.ExpectAsync<SchedulesView>("jobs-schedule-editor");
// Weekly, on Sunday at 02:00, verifying 25 % of the sequences unverified for 30 days.
Assert.Equal(2, editor.KindIndex);
Assert.SequenceEqual([DayOfWeek.Sunday], editor.Days.Where(d => d.IsChecked).Select(d => d.Value));
Assert.Equal(("02:00", "30", "25"), (editor.Time.Text, editor.OlderThan.Text, editor.Percent.Text));
var fields = app.FindAll<TextBox>().Where(t => t.IsVisible && t.DataContext is ScheduleEditorViewModel).ToList();
Assert.True(fields.Count >= 4, "name, time, age and share are on screen");
Assert.True(fields.All(t => t.ToolTip is not null && !string.IsNullOrWhiteSpace(AutomationProperties.GetName(t))), "every field is named and has a tooltip");
var toggles = app.FindAll<ToggleButton>().Where(t => t.IsVisible && t.DataContext is ScheduleChoice<DayOfWeek>).ToList();
Assert.Count(7, toggles);
// Unavailable actions are listed disabled: the scheduler answers for this PC.
Assert.True(editor.ActionOptions.Any(a => a.IsAvailable), "actions are available");
editor.CloseCommand.Execute(null);
Assert.Null(schedules.Editor);
Assert.True(shell.Jobs.IsContentEnabled);
});
private static IEnumerable<T> Descendants<T>(DependencyObject node)
where T : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++)
{
var child = VisualTreeHelper.GetChild(node, i);
if (child is T match) yield return match;
foreach (var nested in Descendants<T>(child)) yield return nested;
}
}
}
@@ -0,0 +1,340 @@
using System.Globalization;
using System.IO;
using Chronos.App.Jobs;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Housekeeping;
using Chronos.Data.Scheduling;
using Chronos.Protocol;
using Chronos.Testing;
using Chronos.Ui.Controls;
namespace Chronos.App.Tests.Jobs;
/// <summary>Jobs › Scheduled (owner review 2, R10): the list, the switch, the row commands and the editor, on a real scheduler.</summary>
public sealed class SchedulesViewModelTests
{
private readonly TestContext _context;
public SchedulesViewModelTests(TestContext context)
{
_context = context;
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
[Test]
public async Task SystemSchedulesComeFirstInTheUsersLanguage()
{
await using var fx = await ScheduleFixture.CreateAsync(_context);
using var vm = await fx.ViewModelAsync();
Assert.True(vm.IsRunning && vm.IsLoaded && vm.HasRows, "the schedules are listed");
Assert.SequenceEqual(["Archive scan", "Index backup", "Housekeeping"], vm.Rows.Select(r => r.Name));
Assert.SequenceEqual(["Every 10 minutes", "Every day", "Daily at " + ScheduleText.Time(new TimeOnly(4, 0))], vm.Rows.Select(r => r.WhenText));
Assert.SequenceEqual(["Archive scan", "Index backup", "Clean-up"], vm.Rows.Select(r => r.ActionText));
Assert.True(vm.Rows.All(r => r.IsSystem && r.IsEnabled && r.LastText == "never run" && r.LastKind == StatusKind.Offline), "nothing ran yet");
// The scan's next run is ten minutes away, today.
Assert.Equal(ScheduleText.Moment(fx.Clock.Now.AddMinutes(10)), vm.Rows[0].NextText);
Assert.Equal(CleanupSteps.DefaultHistoryDays, vm.HistoryDays);
// A schedule the user creates joins the list after the system ones.
var created = await fx.Scheduler!.CreateAsync(new CreateScheduleRequest("Weekly check", ScheduleActions.Verify, new RecurrenceDto("weekly", Time: "02:30", Days: ["mon", "thu"])), null);
Assert.Null(created.Problem);
Assert.Equal("Weekly check", vm.Rows[3].Name);
Assert.Equal(ScheduleText.DayShort(DayOfWeek.Monday) + ", " + ScheduleText.DayShort(DayOfWeek.Thursday) + " at " + ScheduleText.Time(new TimeOnly(2, 30)),
vm.Rows[3].WhenText);
}
[Test]
public void RecurrencesReadAsTheTableShowsThem()
{
var at3 = ScheduleText.Time(new TimeOnly(3, 0));
Assert.Equal("Every 5 minutes", ScheduleText.When(ScheduleRecurrence.Interval(5, RecurrenceUnit.Minutes)));
Assert.Equal("Every hour", ScheduleText.When(ScheduleRecurrence.Interval(1, RecurrenceUnit.Hours)));
Assert.Equal("Every 6 hours", ScheduleText.When(ScheduleRecurrence.Interval(6, RecurrenceUnit.Hours)));
Assert.Equal("Every 2 days", ScheduleText.When(ScheduleRecurrence.Interval(2, RecurrenceUnit.Days)));
Assert.Equal("Daily at " + at3, ScheduleText.When(ScheduleRecurrence.DailyAt(new TimeOnly(3, 0))));
Assert.Equal("Daily at " + at3, ScheduleText.When(ScheduleRecurrence.WeeklyAt(Enum.GetValues<DayOfWeek>(), new TimeOnly(3, 0))));
Assert.Equal("Sun at " + at3, ScheduleText.When(ScheduleRecurrence.WeeklyAt([DayOfWeek.Sunday], new TimeOnly(3, 0))));
Assert.Equal("Monthly, day 1 at " + at3, ScheduleText.When(ScheduleRecurrence.MonthlyAt(1, new TimeOnly(3, 0))));
Assert.Equal("Invalid recurrence", ScheduleText.When(new RecurrenceDto("hourly")));
// Outcomes: the job's state while it is known, else the run's own word.
Assert.Equal("skipped: busy", ScheduleText.Outcome(ScheduleOutcome.SkippedPending, null));
Assert.Equal("failed", ScheduleText.Outcome(ScheduleOutcome.Failed("disk full"), null));
Assert.Equal("queued", ScheduleText.Outcome(ScheduleOutcome.Queued, null));
var job = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Backup, State = JobState.Done };
Assert.Equal("done", ScheduleText.Outcome(ScheduleOutcome.Queued, job));
Assert.Equal(StatusKind.Done, ScheduleText.OutcomeKind(ScheduleOutcome.Queued, job));
Assert.Equal(StatusKind.Failed, ScheduleText.OutcomeKind(ScheduleOutcome.Failed("x"), null));
Assert.Contains("disk full", ScheduleText.OutcomeToolTip(ScheduleOutcome.Failed("disk full"), DateTimeOffset.UtcNow, null));
Assert.Equal("Off", ScheduleText.Next(DateTimeOffset.UtcNow, enabled: false));
Assert.Equal("Cache trim", ScheduleText.Step(CacheTrimStep.StepName));
Assert.Equal("someone-else", ScheduleText.Step("someone-else"));
}
[Test]
public async Task TheSwitchTurnsAScheduleOffAndOn()
{
await using var fx = await ScheduleFixture.CreateAsync(_context);
using var vm = await fx.ViewModelAsync();
var backup = vm.Rows.Single(r => r.Schedule.SystemKey == DesktopScheduleHost.IndexBackup);
await vm.SetEnabledAsync(backup, false);
Assert.False(backup.IsEnabled);
Assert.Equal("Off", backup.NextText);
var stored = (await fx.Db.Schedules.GetAsync(backup.Id))!;
Assert.Equal((false, (DateTimeOffset?)null), (stored.Enabled, stored.NextRun));
await vm.SetEnabledAsync(backup, true);
Assert.True(backup.IsEnabled);
Assert.Equal(fx.Clock.Now.AddDays(1), (await fx.Db.Schedules.GetAsync(backup.Id))!.NextRun);
// The housekeeping turned off keeps every job: the history line says so.
var housekeeping = vm.Rows.Single(r => r.Schedule.SystemKey == DesktopScheduleHost.Housekeeping);
await vm.SetEnabledAsync(housekeeping, false);
Assert.Null(vm.HistoryDays);
}
[Test]
public async Task RunNowShowsTheJobsStateAsTheLastResult()
{
await using var fx = await ScheduleFixture.CreateAsync(_context);
var toasts = new List<string>();
using var vm = await fx.ViewModelAsync(toasts: toasts);
var backup = vm.Rows.Single(r => r.Schedule.SystemKey == DesktopScheduleHost.IndexBackup);
var next = backup.Schedule.NextRun;
await vm.RunNowAsync(backup);
Assert.Equal(ScheduleOutcome.Queued, backup.Schedule.LastOutcome);
Assert.Equal(next, backup.Schedule.NextRun);
Assert.Empty(toasts);
var job = (await fx.Db.Jobs.ListByScheduleAsync(backup.Id)).Single();
Assert.Equal(job.Id, backup.Schedule.LastJobId);
// The Jobs screen forwards the job's changes: the last result follows it, and so do the selected schedule's runs.
vm.Selected = backup;
await vm.RunsLoading;
Assert.SequenceEqual([job.Id], vm.Runs.Select(r => r.Id));
vm.OnJob(job with { State = JobState.Done });
Assert.Equal(("done", StatusKind.Done), (backup.LastText, backup.LastKind));
Assert.Equal("done", vm.Runs[0].StateText);
// Run again while that job is still pending (the engine runs nothing here): nothing new is queued, and a toast says why.
await vm.RunNowAsync(backup);
Assert.Equal(ScheduleOutcome.SkippedPending, backup.Schedule.LastOutcome);
Assert.Count(1, toasts);
Assert.Count(1, await fx.Db.Jobs.ListByScheduleAsync(backup.Id));
}
[Test]
public async Task UsersSchedulesAreDeletedSystemOnesReset()
{
await using var fx = await ScheduleFixture.CreateAsync(_context);
var answer = false;
using var vm = await fx.ViewModelAsync(confirm: _ => answer);
await fx.Scheduler!.CreateAsync(new CreateScheduleRequest("Orphans", ScheduleActions.Orphans, new RecurrenceDto("monthly", Time: "05:00", DayOfMonth: 1)), null);
var mine = vm.Rows.Single(r => !r.IsSystem);
var scan = vm.Rows.Single(r => r.Schedule.SystemKey == DesktopScheduleHost.ArchiveScan);
Assert.False(scan.DeleteCommand.CanExecute(null));
Assert.False(mine.ResetCommand.CanExecute(null));
await vm.DeleteAsync(mine);
Assert.Count(4, vm.Rows);
answer = true;
vm.Selected = mine;
await vm.DeleteAsync(mine);
Assert.Count(3, vm.Rows);
Assert.Null(vm.Selected);
Assert.Null(await fx.Db.Schedules.GetAsync(mine.Id));
await fx.Scheduler.UpdateAsync(scan.Id, new UpdateScheduleRequest(Recurrence: new RecurrenceDto("every", Every: 1, Unit: "hours"), CatchUp: true));
Assert.Equal("Every hour", scan.WhenText);
await vm.ResetAsync(scan);
Assert.Equal(("Every 10 minutes", false), (scan.WhenText, scan.Schedule.CatchUp));
}
/// <summary>A delete the index refuses (busy, locked) keeps the row: the schedule still runs, so it stays in sight.</summary>
[Test]
public async Task ADeleteThatFailsKeepsTheRow()
{
await using var fx = await ScheduleFixture.CreateAsync(_context);
var toasts = new List<string>();
using var vm = await fx.ViewModelAsync(toasts: toasts);
await fx.Scheduler!.CreateAsync(new CreateScheduleRequest("Orphans", ScheduleActions.Orphans, new RecurrenceDto("monthly", Time: "05:00", DayOfMonth: 1)), null);
var mine = vm.Rows.Single(r => !r.IsSystem);
await using (var session = await fx.Db.Database.OpenAsync(_context.Cancellation))
{
await session.ExecuteScriptAsync("CREATE TRIGGER refuse_delete BEFORE DELETE ON schedules BEGIN SELECT RAISE(ABORT, 'the index is busy'); END;",
_context.Cancellation);
}
await vm.DeleteAsync(mine);
Assert.SequenceEqual([Loc.L("Jobs.Schedule.Failed")], toasts);
Assert.Count(4, vm.Rows);
Assert.Contains(mine, vm.Rows);
Assert.NotNull(await fx.Db.Schedules.GetAsync(mine.Id));
}
/// <summary>
/// Whether this PC runs an action is read again when Jobs › Scheduled is shown: proxies turned on in Settings › Archive
/// make the Proxies schedule runnable and the action selectable, without a restart.
/// </summary>
[Test]
public async Task ShowingTheTabReadsTheActionsAgain()
{
await using var fx = await ScheduleFixture.CreateAsync(_context);
var archive = await fx.Archives.CreateAsync(Path.Combine(fx.Folder, "archive"), "archive", proxies: new ProxyPolicy { LongEdge = ProxyPolicy.Disabled });
fx.Settings.LastArchivePath = archive.RootPath;
using var vm = await fx.ViewModelAsync();
Assert.Null((await fx.Scheduler!.CreateAsync(new CreateScheduleRequest("Proxies", ScheduleActions.Proxies, new RecurrenceDto("daily", Time: "01:00")), null)).Problem);
var proxies = vm.Rows.Single(r => !r.IsSystem);
Assert.False(vm.IsAvailable(ScheduleActions.Proxies));
Assert.False(proxies.RunNowCommand.CanExecute(null));
Assert.Equal(Loc.L("Tooltips.Jobs.Schedule.Unavailable.ProxiesDisabled"), proxies.RunNowToolTip);
vm.NewCommand.Execute(null);
var editor = Assert.NotNull(vm.Editor);
Assert.False(editor.ActionOptions.Single(a => a.Name == ScheduleActions.Proxies).IsAvailable);
await fx.Archives.UpdateSettingsAsync(archive.Id, a => a with { Proxies = a.Proxies with { LongEdge = 1920 } }, _context.Cancellation);
await vm.RefreshActionsAsync();
Assert.True(vm.IsAvailable(ScheduleActions.Proxies));
Assert.True(proxies.RunNowCommand.CanExecute(null));
Assert.Equal(Loc.L("Tooltips.Jobs.Schedule.RunNow"), proxies.RunNowToolTip);
Assert.Equal(ScheduleText.ActionToolTip(ScheduleActions.Proxies), proxies.ActionToolTip);
// The open editor follows too; what it had chosen stays chosen.
var chosen = editor.SelectedAction.Name;
Assert.True(editor.ActionOptions.Single(a => a.Name == ScheduleActions.Proxies).IsAvailable);
Assert.Equal(chosen, editor.SelectedAction.Name);
Assert.True(editor.ActionOptions.Any(o => ReferenceEquals(o, editor.SelectedAction)), "the choice is one of the new options");
editor.SelectedAction = editor.ActionOptions.Single(a => a.Name == ScheduleActions.Proxies);
Assert.Equal(ScheduleActions.Proxies, editor.SelectedAction.Name);
}
/// <summary>
/// The last result follows the newest news of the last job: a read of it that started before a live change (or before
/// a later read) does not put back an older state.
/// </summary>
[Test]
public async Task AReadOfTheLastJobNeverUndoesANewerChange()
{
await using var fx = await ScheduleFixture.CreateAsync(_context);
using var vm = await fx.ViewModelAsync();
var job = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Backup, State = JobState.Running };
// A row of its own: the view model reads nothing into it meanwhile.
var row = new ScheduleRowViewModel(vm.Rows[1].Schedule with { LastOutcome = ScheduleOutcome.Queued, LastJobId = job.Id }, vm);
// The job ends while it is read: the engine's Done comes first, the read's Running after it.
var read = row.BeginLastJobRead();
row.SetLastJob(job with { State = JobState.Done });
row.SetLoadedLastJob(job, read);
Assert.Equal(("done", StatusKind.Done), (row.LastText, row.LastKind));
// Two reads: the later one wins, whichever ends first.
var first = row.BeginLastJobRead();
var second = row.BeginLastJobRead();
row.SetLoadedLastJob(job with { State = JobState.Failed }, second);
row.SetLoadedLastJob(job, first);
Assert.Equal(StatusKind.Failed, row.LastKind);
// A read of the job of the previous run does not apply once the schedule has run again.
var stale = row.BeginLastJobRead();
row.Update(row.Schedule with { LastJobId = Guid.CreateVersion7() });
row.SetLoadedLastJob(job with { State = JobState.Done }, stale);
Assert.Null(row.LastJob);
Assert.Equal(("queued", StatusKind.Queued), (row.LastText, row.LastKind));
}
[Test]
public async Task TheEditorChecksEachFieldAndBuildsTheRecurrence()
{
await using var fx = await ScheduleFixture.CreateAsync(_context);
using var vm = await fx.ViewModelAsync();
vm.NewCommand.Execute(null);
var editor = Assert.NotNull(vm.Editor);
Assert.True(editor.IsNew && !editor.IsSystem && editor.CanChangeAction, "a new schedule of the user");
Assert.Equal(Loc.L("Tooltips.Jobs.Editor.NameMissing"), editor.Problem());
Assert.False(editor.SaveCommand.CanExecute(null));
editor.Name.Text = "Nightly thumbnails";
Assert.Null(editor.Problem());
Assert.Equal(new RecurrenceDto("daily", Time: "03:00"), editor.Recurrence());
// Every: the unit decides the range.
editor.KindIndex = 0;
editor.SelectedUnit = editor.Units.Single(u => u.Value == RecurrenceUnit.Minutes);
editor.Every.Text = "3";
Assert.Equal(Loc.L("Tooltips.Jobs.Editor.Number", "5", "1440"), editor.Problem());
Assert.Equal("—", editor.WhenText);
editor.SelectedUnit = editor.Units.Single(u => u.Value == RecurrenceUnit.Hours);
Assert.Null(editor.Problem());
Assert.Equal("Every 3 hours", editor.WhenText);
// Weekly: a time and at least one day.
editor.KindIndex = 2;
foreach (var day in editor.Days) day.IsChecked = false;
Assert.Equal(Loc.L("Tooltips.Jobs.Editor.NoDays"), editor.Problem());
editor.Days.Single(d => d.Value == DayOfWeek.Thursday).IsChecked = true;
editor.Days.Single(d => d.Value == DayOfWeek.Monday).IsChecked = true;
editor.Time.Text = "25:00";
Assert.Equal(Loc.L("Tooltips.Jobs.Editor.TimeInvalid"), editor.Problem());
editor.Time.Text = "2:30";
Assert.Equal("weekly:mon,thu@02:30", ScheduleMapping.FromDto(editor.Recurrence())!.Format());
// Monthly: days 1 to 28.
editor.KindIndex = 3;
editor.DayOfMonth.Text = "31";
Assert.NotNull(editor.Problem());
editor.DayOfMonth.Text = "28";
Assert.Equal("monthly:28@02:30", ScheduleMapping.FromDto(editor.Recurrence())!.Format());
// The action's own parameters, from its defaults.
editor.SelectedAction = editor.ActionOptions.Single(a => a.Name == ScheduleActions.Verify);
Assert.True(editor.ShowsOlderThan && editor.ShowsPercent && !editor.ShowsSteps, "verify's parameters");
Assert.Equal(("30", "100"), (editor.OlderThan.Text, editor.Percent.Text));
editor.Percent.Text = "0";
Assert.Equal(Loc.L("Tooltips.Jobs.Editor.Number", "1", "100"), editor.Problem());
editor.Percent.Text = "25";
Assert.Equal(new ScheduleParametersDto(OlderThanDays: 30, Percent: 25), editor.Parameters());
editor.SelectedPriority = editor.Priorities.Single(p => p.Value == JobPriority.Normal);
editor.CatchUp = false;
Assert.True(editor.SaveCommand.CanExecute(null), "the schedule can be saved");
await editor.SaveAsync();
Assert.Null(vm.Editor);
var saved = vm.Rows.Single(r => !r.IsSystem);
Assert.Equal((ScheduleActions.Verify, "monthly:28@02:30", "normal", false), (saved.Schedule.Action, ScheduleMapping.FromDto(saved.Schedule.Recurrence)!.Format(),
saved.Schedule.Priority, saved.Schedule.CatchUp));
Assert.Equal(new ScheduleParametersDto(OlderThanDays: 30, Percent: 25), saved.Schedule.Parameters);
Assert.Same(saved, vm.Selected);
}
[Test]
public async Task ASystemScheduleKeepsItsNameAndActionInTheEditor()
{
await using var fx = await ScheduleFixture.CreateAsync(_context);
using var vm = await fx.ViewModelAsync();
var housekeeping = vm.Rows.Single(r => r.Schedule.SystemKey == DesktopScheduleHost.Housekeeping);
housekeeping.EditCommand.Execute(null);
var editor = Assert.NotNull(vm.Editor);
Assert.True(editor.IsSystem && !editor.CanChangeAction, "a system schedule");
Assert.Equal("Housekeeping", editor.SystemName);
// The steps this PC runs, the schedule's own checked.
Assert.SequenceEqual([CleanupSteps.JobHistory, CleanupSteps.Audit, CleanupSteps.TrashReport, CacheTrimStep.StepName], editor.Steps.Select(s => s.Value));
Assert.SequenceEqual([CleanupSteps.JobHistory, CacheTrimStep.StepName], editor.Steps.Where(s => s.IsChecked).Select(s => s.Value));
foreach (var step in editor.Steps) step.IsChecked = false;
Assert.Equal(Loc.L("Tooltips.Jobs.Editor.NoSteps"), editor.Problem());
editor.Steps[0].IsChecked = true;
editor.OlderThan.Text = "30";
var update = editor.BuildUpdate();
Assert.Equal(((string?)null, (string?)null), (update.Name, update.Action));
await editor.SaveAsync();
Assert.Null(vm.Editor);
Assert.Equal(30, vm.HistoryDays);
Assert.SequenceEqual([CleanupSteps.JobHistory], housekeeping.Schedule.Parameters.Steps!);
Assert.Equal("Housekeeping", housekeeping.Name);
}
}
@@ -0,0 +1,221 @@
using System.Globalization;
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Settings;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Testing;
namespace Chronos.App.Tests.Settings;
/// <summary>Settings › Advanced › Logs (owner review 2, R11): the stored values, the file options they become and the rows.</summary>
public sealed class LogSettingsTests
{
private readonly TestContext _context;
public LogSettingsTests(TestContext context)
{
_context = context;
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
[Test]
public void LogSettingsSurviveTheSettingsFileAndOlderFilesGetTheDefaults()
{
var settings = new AppSettings
{
LogLevel = LogLevel.Debug,
LogRetentionDays = 30,
LogMaxFileMb = 0,
LogMaxTotalMb = 2048,
LogRotation = LogRotation.Hourly,
DiagnosticsLogMb = 16,
};
var json = settings.ToJson();
Assert.Contains("\"LogLevel\": \"Debug\"", json);
Assert.Contains("\"LogRotation\": \"Hourly\"", json);
foreach (var copy in new[] { AppSettings.Parse(json)!, settings.Clone() })
{
Assert.Equal((LogLevel.Debug, 30, 0, 2048, LogRotation.Hourly, 16),
(copy.LogLevel, copy.LogRetentionDays, copy.LogMaxFileMb, copy.LogMaxTotalMb, copy.LogRotation, copy.DiagnosticsLogMb));
}
// A settings file written before these rows existed (or exported by such a copy) keeps the former behaviour's defaults.
var older = AppSettings.Parse("""{ "Theme": "Light" }""")!;
Assert.Equal((LogLevel.Info, 14, 50, 1024, LogRotation.Daily, 4),
(older.LogLevel, older.LogRetentionDays, older.LogMaxFileMb, older.LogMaxTotalMb, older.LogRotation, older.DiagnosticsLogMb));
}
[Test]
public void TheSettingsBecomeTheLogFileOptions()
{
Assert.Equal(new LogFileOptions(), AppLogging.Options(new AppSettings()));
Assert.Equal(4L << 20, AppLogging.DiagnosticsTailBytes(new AppSettings()));
var tuned = new AppSettings { LogLevel = LogLevel.Warning, LogRetentionDays = 3, LogMaxFileMb = 10, LogMaxTotalMb = 0, LogRotation = LogRotation.Hourly };
Assert.Equal(new LogFileOptions { Level = LogLevel.Warning, RetentionDays = 3, MaxFileMb = 10, MaxTotalMb = 0, Rotation = LogRotation.Hourly },
AppLogging.Options(tuned));
// A hand-edited file never makes the sink keep nothing or delete everything.
var odd = new AppSettings { LogLevel = (LogLevel)42, LogRetentionDays = 0, LogMaxFileMb = -3, LogMaxTotalMb = -1, LogRotation = (LogRotation)7, DiagnosticsLogMb = 0 };
Assert.Equal(new LogFileOptions { RetentionDays = 1, MaxFileMb = 0, MaxTotalMb = 0 }, AppLogging.Options(odd));
Assert.Equal(1L << 20, AppLogging.DiagnosticsTailBytes(odd));
var huge = new AppSettings { LogRetentionDays = 99_999, LogMaxFileMb = 99_999, LogMaxTotalMb = int.MaxValue, DiagnosticsLogMb = 5000 };
Assert.Equal(new LogFileOptions { RetentionDays = 3650, MaxFileMb = 10_240, MaxTotalMb = 1_048_576 }, AppLogging.Options(huge));
Assert.Equal(1024L << 20, AppLogging.DiagnosticsTailBytes(huge));
// A total below one file would delete each finished file as the next one opens: it is raised to the file (the
// server refuses it). Without a file limit any total holds.
Assert.True(LogFileOptions.TotalBelowFile(500, 256));
Assert.False(LogFileOptions.TotalBelowFile(256, 256) || LogFileOptions.TotalBelowFile(500, 0) || LogFileOptions.TotalBelowFile(0, 256));
var below = AppLogging.Options(new AppSettings { LogMaxFileMb = 500, LogMaxTotalMb = 256 });
Assert.Equal((500, 500), (below.MaxFileMb, below.MaxTotalMb));
var free = AppLogging.Options(new AppSettings { LogMaxFileMb = 0, LogMaxTotalMb = 256 });
Assert.Equal((0, 256), (free.MaxFileMb, free.MaxTotalMb));
var level = Log.MinimumLevel;
using var sink = new FileLogSink(_context.CreateTempDirectory(), "chronos");
try
{
AppLogging.Apply(sink, tuned);
Assert.Equal(AppLogging.Options(tuned), sink.Options);
Assert.Equal(LogLevel.Warning, Log.MinimumLevel);
}
finally
{
Log.MinimumLevel = level;
}
}
[Test]
public void TheLogFilesStartWithTheSettings()
{
// App opens its files with the settings: the first line opens a file and prunes, at every start and at every launch
// that only hands over to the running Chronos, so the defaults would delete what the user keeps longer.
var level = Log.MinimumLevel;
try
{
foreach (var (settings, kept) in new[] { (new AppSettings { LogLevel = LogLevel.Debug, LogRetentionDays = 365, LogMaxTotalMb = 0 }, true), (new AppSettings(), false) })
{
var dir = _context.CreateTempDirectory();
var old = Path.Combine(dir, $"chronos-{DateTime.UtcNow.AddDays(-30):yyyyMMdd}.log");
File.WriteAllText(old, "a month ago");
File.SetLastWriteTimeUtc(old, DateTime.UtcNow.AddDays(-30));
using var sink = AppLogging.Open(dir, settings);
Assert.Equal((AppLogging.Options(settings), settings.LogLevel), (sink.Options, Log.MinimumLevel));
sink.Write(LogLevel.Info, "app", "Chronos starting", null);
Assert.Equal(kept, File.Exists(old), $"retention {settings.LogRetentionDays} days");
Assert.FileExists(sink.CurrentPath);
}
}
finally
{
Log.MinimumLevel = level;
}
}
[Test]
public void EachRowStoresAndSavesItsChoice()
{
var settings = new AppSettings();
var saves = 0;
var rows = new LogSettingsRows(settings, () => saves++);
var changed = new List<string?>();
rows.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
Assert.SequenceEqual(["Trace", "Debug", "Information", "Warning", "Error"], rows.Levels.Select(l => l.Label));
Assert.Equal(("Information", "14 days", "50 MB", "1,024 MB", "Daily", "4 MB"), (rows.SelectedLevel.Label, rows.SelectedRetention.Label,
rows.SelectedFileSize.Label, rows.SelectedTotalSize.Label, rows.SelectedRotation.Label, rows.SelectedDiagnostics.Label));
Assert.Equal("1 day", rows.RetentionChoices[0].Label);
// "No limit" closes both size lists.
Assert.Equal((0, "No limit"), (rows.FileSizeChoices[^1].Value, rows.FileSizeChoices[^1].Label));
Assert.Equal(0, rows.TotalSizeChoices[^1].Value);
Assert.SequenceEqual(["Daily", "Hourly"], rows.Rotations.Select(r => r.Label));
rows.SelectedLevel = rows.Levels.Single(l => l.Value == LogLevel.Debug);
rows.SelectedRetention = rows.RetentionChoices.Single(c => c.Value == 90);
rows.SelectedFileSize = rows.FileSizeChoices[^1];
rows.SelectedTotalSize = rows.TotalSizeChoices.Single(c => c.Value == 5120);
rows.SelectedRotation = rows.Rotations.Single(r => r.Value == LogRotation.Hourly);
rows.SelectedDiagnostics = rows.DiagnosticsChoices.Single(c => c.Value == 16);
Assert.Equal((LogLevel.Debug, 90, 0, 5120, LogRotation.Hourly, 16),
(settings.LogLevel, settings.LogRetentionDays, settings.LogMaxFileMb, settings.LogMaxTotalMb, settings.LogRotation, settings.DiagnosticsLogMb));
Assert.Equal(6, saves);
// A size changes the choices of the other.
Assert.SequenceEqual(["SelectedLevel", "SelectedRetention", "SelectedFileSize", "TotalSizeChoices", "SelectedTotalSize", "SelectedTotalSize",
"FileSizeChoices", "SelectedFileSize", "SelectedRotation", "SelectedDiagnostics"], changed);
// The same choice again, or none (a list being rebuilt), changes nothing.
rows.SelectedLevel = rows.Levels.Single(l => l.Value == LogLevel.Debug);
rows.SelectedRotation = null!;
Assert.Equal(6, saves);
// Values set elsewhere are listed in order with the presets.
settings.LogRetentionDays = 45;
settings.LogMaxTotalMb = 3000;
Assert.SequenceEqual([1, 3, 7, 14, 30, 45, 90, 365], rows.RetentionChoices.Select(c => c.Value));
Assert.Equal("45 days", rows.SelectedRetention.Label);
Assert.SequenceEqual([256, 512, 1024, 2048, 3000, 5120, 10240, 0], rows.TotalSizeChoices.Select(c => c.Value));
// Reset section on Advanced: the defaults, shown at once; the caller saves.
changed.Clear();
rows.Reset();
Assert.Equal((LogLevel.Info, 14, 50, 1024, LogRotation.Daily, 4),
(settings.LogLevel, settings.LogRetentionDays, settings.LogMaxFileMb, settings.LogMaxTotalMb, settings.LogRotation, settings.DiagnosticsLogMb));
Assert.Equal(string.Empty, changed.Single());
Assert.Equal(6, saves);
}
[Test]
public void TheSizeRowsNeverOfferATotalBelowOneFile()
{
var settings = new AppSettings { LogMaxFileMb = 500 };
var saves = 0;
var rows = new LogSettingsRows(settings, () => saves++);
Assert.SequenceEqual([512, 1024, 2048, 5120, 10240, 0], rows.TotalSizeChoices.Select(c => c.Value));
Assert.SequenceEqual([10, 20, 50, 100, 200, 500, 0], rows.FileSizeChoices.Select(c => c.Value));
rows.SelectedTotalSize = rows.TotalSizeChoices.Single(c => c.Value == 512);
rows.SelectedFileSize = rows.FileSizeChoices.Single(c => c.Value == 100);
rows.SelectedTotalSize = rows.TotalSizeChoices.Single(c => c.Value == 256);
Assert.Equal((100, 256, 3), (settings.LogMaxFileMb, settings.LogMaxTotalMb, saves));
Assert.SequenceEqual([10, 20, 50, 100, 200, 0], rows.FileSizeChoices.Select(c => c.Value));
// Without a file limit every total is offered, and without a total every file size.
rows.SelectedFileSize = rows.FileSizeChoices[^1];
Assert.SequenceEqual([256, 512, 1024, 2048, 5120, 10240, 0], rows.TotalSizeChoices.Select(c => c.Value));
rows.SelectedTotalSize = rows.TotalSizeChoices[^1];
Assert.SequenceEqual([10, 20, 50, 100, 200, 500, 0], rows.FileSizeChoices.Select(c => c.Value));
// An imported file with a total below its file size shows the total the files get.
settings.LogMaxFileMb = 500;
settings.LogMaxTotalMb = 256;
Assert.Equal(("500 MB", "500 MB"), (rows.SelectedFileSize.Label, rows.SelectedTotalSize.Label));
Assert.SequenceEqual([500, 512, 1024, 2048, 5120, 10240, 0], rows.TotalSizeChoices.Select(c => c.Value));
}
[Test]
public void OutOfRangeValuesShowWhatTheFilesGet()
{
// A hand-edited or imported settings file: every row shows the value applied, and none fails to find its choice.
var settings = new AppSettings { LogLevel = (LogLevel)42, LogRetentionDays = 0, LogMaxFileMb = -3, LogMaxTotalMb = -1, LogRotation = (LogRotation)7, DiagnosticsLogMb = 0 };
var saves = 0;
var rows = new LogSettingsRows(settings, () => saves++);
Assert.Equal(("Information", "1 day", "No limit", "No limit", "Daily", "1 MB"), (rows.SelectedLevel.Label, rows.SelectedRetention.Label,
rows.SelectedFileSize.Label, rows.SelectedTotalSize.Label, rows.SelectedRotation.Label, rows.SelectedDiagnostics.Label));
Assert.SequenceEqual(LogSettingsRows.RetentionPresets, rows.RetentionChoices.Select(c => c.Value));
Assert.SequenceEqual([.. LogSettingsRows.FileSizePresets, 0], rows.FileSizeChoices.Select(c => c.Value));
Assert.SequenceEqual(LogSettingsRows.DiagnosticsPresets, rows.DiagnosticsChoices.Select(c => c.Value));
// Choosing the value shown saves it as applied.
var (shownFile, shownRetention) = (rows.SelectedFileSize, rows.SelectedRetention);
rows.SelectedFileSize = shownFile;
rows.SelectedRetention = shownRetention;
Assert.Equal((0, 1, 2), (settings.LogMaxFileMb, settings.LogRetentionDays, saves));
settings.LogRetentionDays = 99_999;
settings.LogMaxFileMb = 99_999;
settings.LogMaxTotalMb = int.MaxValue;
settings.DiagnosticsLogMb = 5000;
Assert.Equal(("3650 days", "10,240 MB", "1,048,576 MB", "1,024 MB"),
(rows.SelectedRetention.Label, rows.SelectedFileSize.Label, rows.SelectedTotalSize.Label, rows.SelectedDiagnostics.Label));
}
}
@@ -80,10 +80,13 @@ public sealed class SettingsScreenSmokeTests
var data = Field(app, Loc.L("Settings.Advanced.DataFolder"));
Assert.Equal(FlowDirection.LeftToRight, data.FlowDirection);
Assert.Equal(settings.DataFolder, data.ToolTip);
// Advanced has nothing to reset: no Reset section there.
Assert.False(settings.CanResetSection);
Assert.False(settings.ResetSectionCommand.CanExecute(null));
Assert.False(app.FindAll<Button>().Any(b => b.Content as string == Loc.L("Settings.ResetSection") && b.IsVisible), "no Reset section on Advanced");
// Advanced's Reset section puts its log rows back to their defaults (owner review 2, R11).
Assert.True(settings.CanResetSection);
Assert.True(app.FindAll<Button>().Any(b => b.Content as string == Loc.L("Settings.ResetSection") && b.IsVisible), "a Reset section on Advanced");
settings.Logs.SelectedRotation = settings.Logs.Rotations.Single(r => r.Value == Chronos.Core.Diagnostics.LogRotation.Hourly);
Assert.Equal(Chronos.Core.Diagnostics.LogRotation.Hourly, shell.Services.Settings.LogRotation);
settings.ResetSectionCommand.Execute(null);
Assert.Equal(Chronos.Core.Diagnostics.LogRotation.Daily, shell.Services.Settings.LogRotation);
// Forgetting a trusted certificate asks first, as on the Server screen; a "no" keeps it and the session.
settings.Page = SettingsPage.Server;
@@ -0,0 +1,195 @@
using Chronos.Core.Diagnostics;
using Chronos.Testing;
namespace Chronos.Core.Tests.Diagnostics;
public sealed class FileLogSinkTests(TestContext context)
{
private static readonly string Block = new('x', 64 * 1024);
/// <summary>Names are fixed by this clock; far from today, so nothing is old enough to be pruned by age.</summary>
private sealed class ManualTime(DateTimeOffset now) : TimeProvider
{
public DateTimeOffset Now { get; set; } = now;
public override DateTimeOffset GetUtcNow() => Now;
}
[Test]
public void AFullFileContinuesInNumberedParts()
{
var dir = context.CreateTempDirectory();
var time = new ManualTime(new DateTimeOffset(2026, 10, 26, 9, 30, 0, TimeSpan.Zero));
using (var sink = new FileLogSink(dir, "p", new LogFileOptions { MaxFileMb = 1, MaxTotalMb = 0, RetentionDays = 0 }, time))
{
// 40 blocks of 64 KiB: two full files of 1 MiB and the rest in a third.
for (var i = 0; i < 40; i++) sink.Write(LogLevel.Info, "test", Block, null);
Assert.Equal(Path.Combine(dir, "p-20261026.2.log"), sink.CurrentPath);
}
Assert.SequenceEqual(["p-20261026.1.log", "p-20261026.2.log", "p-20261026.log"], Names(dir));
var first = new FileInfo(Path.Combine(dir, "p-20261026.log")).Length;
Assert.InRange(first, 1L << 20, (1L << 20) + Block.Length + 200);
Assert.Greater(new FileInfo(Path.Combine(dir, "p-20261026.2.log")).Length, 0);
}
[Test]
public void ARestartContinuesTheNewestPartUnlessItIsFull()
{
var dir = context.CreateTempDirectory();
File.WriteAllText(Path.Combine(dir, "p-20261026.log"), new string('a', 2 << 20));
File.WriteAllText(Path.Combine(dir, "p-20261026.1.log"), "earlier\n");
var time = new ManualTime(new DateTimeOffset(2026, 10, 26, 9, 30, 0, TimeSpan.Zero));
var options = new LogFileOptions { MaxFileMb = 1, MaxTotalMb = 0, RetentionDays = 0 };
using (var sink = new FileLogSink(dir, "p", options, time)) sink.Write(LogLevel.Info, "test", "after restart", null);
var text = File.ReadAllText(Path.Combine(dir, "p-20261026.1.log"));
Assert.True(text.StartsWith("earlier\n", StringComparison.Ordinal) && text.Contains("after restart", StringComparison.Ordinal), text);
File.WriteAllText(Path.Combine(dir, "p-20261026.1.log"), new string('b', 1 << 20));
using (var sink = new FileLogSink(dir, "p", options, time)) sink.Write(LogLevel.Info, "test", "next part", null);
Assert.Contains("next part", File.ReadAllText(Path.Combine(dir, "p-20261026.2.log")));
}
[Test]
public void HourlyFilesAreNamedByTheHourAndTheRotationChangesLive()
{
var dir = context.CreateTempDirectory();
var time = new ManualTime(new DateTimeOffset(2026, 10, 26, 13, 59, 59, TimeSpan.Zero));
using var sink = new FileLogSink(dir, "server", new LogFileOptions { Rotation = LogRotation.Hourly, RetentionDays = 0 }, time);
sink.Write(LogLevel.Info, "test", "one", null);
time.Now = time.Now.AddSeconds(2);
sink.Write(LogLevel.Info, "test", "two", null);
Assert.SequenceEqual(["server-20261026-13.log", "server-20261026-14.log"], Names(dir));
Assert.Contains("two", Read(Path.Combine(dir, "server-20261026-14.log")));
sink.Configure(sink.Options with { Rotation = LogRotation.Daily });
sink.Write(LogLevel.Info, "test", "three", null);
Assert.Equal(Path.Combine(dir, "server-20261026.log"), sink.CurrentPath);
Assert.Contains("three", Read(sink.CurrentPath));
}
[Test]
public void TheTotalSizeDropsTheOldestFilesButNeverTheCurrentOne()
{
var dir = context.CreateTempDirectory();
var now = DateTime.UtcNow;
foreach (var (name, daysAgo) in new[] { ("p-20261020.log", 6), ("p-20261021.1.log", 5), ("p-20261022-08.log", 4) })
{
var path = Path.Combine(dir, name);
File.WriteAllText(path, new string('o', 600 * 1024));
File.SetLastWriteTimeUtc(path, now.AddDays(-daysAgo));
}
// Other programs' files and names this sink never writes are left alone, whatever their size.
File.WriteAllText(Path.Combine(dir, "other-20261019.log"), new string('o', 2 << 20));
File.WriteAllText(Path.Combine(dir, "p-notes.log"), new string('o', 2 << 20));
File.SetLastWriteTimeUtc(Path.Combine(dir, "p-notes.log"), now.AddDays(-30));
using var sink = new FileLogSink(dir, "p", new LogFileOptions { MaxTotalMb = 1, MaxFileMb = 0 });
sink.Write(LogLevel.Info, "test", "today", null);
Assert.SequenceEqual(Sorted("other-20261019.log", "p-20261022-08.log", Path.GetFileName(sink.CurrentPath), "p-notes.log"), Names(dir));
// The file being written stays even when it alone is over the limit.
for (var i = 0; i < 24; i++) sink.Write(LogLevel.Info, "test", Block, null);
sink.PruneNow();
Assert.SequenceEqual(Sorted("other-20261019.log", Path.GetFileName(sink.CurrentPath), "p-notes.log"), Names(dir));
}
[Test]
public void FilesOlderThanTheRetentionAreDeleted()
{
var dir = context.CreateTempDirectory();
var now = DateTime.UtcNow;
foreach (var (name, daysAgo) in new[] { ("p-20200101.log", 30), ("p-20200102.3.log", 20), ("p-20200103.log", 2), ("q-20200101.log", 30) })
{
var path = Path.Combine(dir, name);
File.WriteAllText(path, "old\n");
File.SetLastWriteTimeUtc(path, now.AddDays(-daysAgo));
}
using var sink = new FileLogSink(dir, "p", new LogFileOptions { RetentionDays = 14 });
sink.Write(LogLevel.Info, "test", "today", null);
Assert.SequenceEqual(Sorted("p-20200103.log", Path.GetFileName(sink.CurrentPath), "q-20200101.log"), Names(dir));
}
[Test]
public void ConfigureAppliesTheLevelAndTheRetentionAtOnce()
{
var dir = context.CreateTempDirectory();
using var sink = new FileLogSink(dir, "p", new LogFileOptions());
sink.Write(LogLevel.Debug, "test", "hidden", null);
sink.Write(LogLevel.Info, "test", "shown", null);
sink.Configure(sink.Options with { Level = LogLevel.Debug });
sink.Write(LogLevel.Debug, "test", "detail", null);
sink.Configure(sink.Options with { Level = LogLevel.Error });
sink.Write(LogLevel.Warning, "test", "quiet", null);
var text = Read(sink.CurrentPath);
Assert.True(text.Contains("shown", StringComparison.Ordinal) && text.Contains("detail", StringComparison.Ordinal), text);
Assert.False(text.Contains("hidden", StringComparison.Ordinal) || text.Contains("quiet", StringComparison.Ordinal), text);
// A shorter retention prunes without waiting for the next file.
var old = Path.Combine(dir, "p-20200101.log");
File.WriteAllText(old, "old\n");
File.SetLastWriteTimeUtc(old, DateTime.UtcNow.AddDays(-3));
sink.Configure(sink.Options with { RetentionDays = 7 });
Assert.FileExists(old);
sink.Configure(sink.Options with { RetentionDays = 1 });
Assert.FileMissing(old);
Assert.FileExists(sink.CurrentPath);
}
[Test]
public void TheFormerConstructorWritesDailyFilesWithTheDefaultLimits()
{
var dir = context.CreateTempDirectory();
var sink = new FileLogSink(dir, "setup", 7);
Assert.Equal(new LogFileOptions { RetentionDays = 7 }, sink.Options);
Assert.Equal((LogLevel.Info, 50, 1024, LogRotation.Daily), (sink.Options.Level, sink.Options.MaxFileMb, sink.Options.MaxTotalMb, sink.Options.Rotation));
var before = DateTime.UtcNow;
sink.Write(LogLevel.Warning, "setup", "written", null);
var after = DateTime.UtcNow;
// The system clock: a write across midnight UTC names either day.
var expected = sink.CurrentPath;
Assert.Contains(expected, new[] { before, after }.Select(day => Path.Combine(dir, $"setup-{day:yyyyMMdd}.log")));
sink.Dispose();
// Engine code may log after the host closed its sink: the line is dropped.
sink.Write(LogLevel.Error, "setup", "after", null);
var text = File.ReadAllText(expected);
Assert.Contains("Warning setup: written", text);
Assert.False(text.Contains("after", StringComparison.Ordinal), text);
}
/// <summary>
/// A folder removed under a sink (a server's data folder deleted, /data/logs gone) drops lines instead of throwing into
/// the code that logs; once the folder is back, the next line opens the file again.
/// </summary>
[Test]
public void ARemovedFolderDropsLinesUntilItIsBack()
{
var dir = Path.Combine(context.CreateTempDirectory(), "logs");
var time = new ManualTime(new DateTimeOffset(2026, 10, 27, 9, 0, 0, TimeSpan.Zero));
using var sink = new FileLogSink(dir, "server", new LogFileOptions { RetentionDays = 0 }, time);
Directory.Delete(dir);
// Before the first line, as a server whose temporary folder a test already deleted.
sink.Write(LogLevel.Error, "jobs", "lost", new InvalidOperationException("cause"));
Assert.False(Directory.Exists(dir), "the sink does not create the folder again by itself");
Directory.CreateDirectory(dir);
sink.Write(LogLevel.Error, "jobs", "kept", null);
sink.Write(LogLevel.Info, "jobs", "next", null);
var path = Path.Combine(dir, "server-20261027.log");
Assert.Equal(path, sink.CurrentPath);
var text = Read(path);
Assert.True(text.Contains("kept", StringComparison.Ordinal) && text.Contains("next", StringComparison.Ordinal) && !text.Contains("lost", StringComparison.Ordinal), text);
}
/// <summary>Reads a file the sink may still be writing (it shares it for reading and writing, as the log tail does).</summary>
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();
}
private static string[] Sorted(params string[] names) => [.. names.Order(StringComparer.Ordinal)];
private static string[] Names(string dir) => [.. Directory.EnumerateFiles(dir).Select(Path.GetFileName).OfType<string>().Order(StringComparer.Ordinal)];
}
@@ -0,0 +1,70 @@
using Chronos.Core.Diagnostics;
using Chronos.Testing;
namespace Chronos.Core.Tests.Diagnostics;
/// <summary>
/// Logging never throws into the code that logs: the job engine and the scheduler log from their error handling, and a line
/// that escaped there once left a failed job running and could stop a worker. Serial: these tests replace the process-wide sink.
/// </summary>
[Serial]
public sealed class LogTests
{
/// <summary>Throws what Microsoft.Extensions.Logging throws when a file provider's folder is gone.</summary>
private sealed class BrokenSink : ILogSink
{
public int Calls;
public void Write(LogLevel level, string category, string message, Exception? exception)
{
Interlocked.Increment(ref Calls);
throw new AggregateException("An error occurred while writing to logger(s).", new DirectoryNotFoundException("Could not find a part of the path"));
}
}
private sealed class ListSink : ILogSink
{
public List<string> Lines { get; } = [];
public void Write(LogLevel level, string category, string message, Exception? exception)
{
lock (Lines) Lines.Add($"{level} {category}: {message}");
}
}
[Test]
public void ALineASinkCannotWriteIsDroppedWithoutThrowing()
{
var sink = new BrokenSink();
var previous = Log.Sink;
var level = Log.MinimumLevel;
Log.SetSink(sink);
Log.MinimumLevel = LogLevel.Debug;
try
{
Log.Debug("test", "debug");
Log.Info("test", "info");
Log.Warning("test", "warning", new InvalidOperationException("cause"));
Log.Error("test", "error", new InvalidOperationException("cause"));
Log.Write(LogLevel.Error, "test", "write", null);
}
finally
{
Log.SetSink(previous);
Log.MinimumLevel = level;
}
Assert.Equal(5, sink.Calls);
}
[Test]
public void OneSinkOfATeeThatCannotWriteDoesNotKeepTheLineFromTheOthers()
{
var broken = new BrokenSink();
var kept = new ListSink();
var tee = new TeeLogSink(broken, kept);
tee.Write(LogLevel.Warning, "test", "first", null);
tee.Write(LogLevel.Error, "test", "second", new IOException("disk"));
Assert.Equal(2, broken.Calls);
Assert.SequenceEqual(["Warning test: first", "Error test: second"], kept.Lines);
}
}
@@ -446,4 +446,30 @@ public sealed class JobEngineTests(TestContext context)
Assert.Equal("encoder lost", failed.Error);
Assert.Contains("encoder lost", failed.LogTail);
}
[Test]
public async Task StartingKeepsTheHistoryAndKnowsItsKindsBefore()
{
// The housekeeping schedule's job-history step purges finished jobs now (owner review 2, R10), not the engine's start.
await using var db = await OpenAsync();
var old = new Job
{
Id = Guid.CreateVersion7(),
Kind = JobKind.Scan,
State = JobState.Done,
Created = DateTimeOffset.UtcNow.AddDays(-400),
Finished = DateTimeOffset.UtcNow.AddDays(-400),
};
await db.Jobs.EnqueueAsync(old);
await using var engine = new JobEngine(db, [new CountingHandler(JobKind.Scan, 1), new CountingHandler(JobKind.Verify, 1)],
new JobEngineOptions { WorkerId = "t", Kinds = [JobKind.Scan] });
Assert.True(engine.CanRun(JobKind.Scan));
Assert.False(engine.CanRun(JobKind.Verify), "filtered out");
Assert.False(engine.CanRun(JobKind.Render), "no handler");
await engine.StartAsync();
Assert.NotNull(await db.Jobs.GetAsync(old.Id));
var scheduled = await engine.EnqueueAsync(JobKind.Scan, [], null, null, JobPriority.Background, null, Guid.CreateVersion7());
Assert.Equal(scheduled.ScheduleId, (await db.Jobs.GetAsync(scheduled.Id))!.ScheduleId);
}
}
@@ -0,0 +1,133 @@
using System.Threading.Channels;
using Chronos.Core.Diagnostics;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Scheduling;
using Chronos.Data.Tests.Scheduling;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Jobs;
/// <summary>
/// The job engine and the scheduler log from their error handling: a log line that cannot be written must change nothing
/// they do. It once left a failed job running (its log line threw before the state was stored, the cause of the
/// intermittent JobApiTests failures: the process-wide sink was a stopped test server's, whose log folder was gone) and
/// killed the worker. Serial: these tests replace the process-wide sink.
/// </summary>
[Serial]
[Category("jobs")]
public sealed class LoggingFailureTests(TestContext context)
{
private static readonly DateTimeOffset T0 = new(2026, 10, 2, 9, 0, 0, TimeSpan.Zero);
private static TimeSpan Budget => TimeSpan.FromSeconds(TestTiming.Budget(10));
/// <summary>Every line fails as Microsoft.Extensions.Logging fails when a file provider's folder is gone.</summary>
private sealed class BrokenLogging : IDisposable, ILogSink
{
private readonly ILogSink _previous = Log.Sink;
private readonly LogLevel _level = Log.MinimumLevel;
private int _lines;
public BrokenLogging()
{
Log.SetSink(this);
Log.MinimumLevel = LogLevel.Trace;
}
public int Lines => Volatile.Read(ref _lines);
public void Write(LogLevel level, string category, string message, Exception? exception)
{
Interlocked.Increment(ref _lines);
throw new AggregateException("An error occurred while writing to logger(s).", new DirectoryNotFoundException("Could not find a part of the path"));
}
public void Dispose()
{
Log.SetSink(_previous);
Log.MinimumLevel = _level;
}
}
private sealed class CallbackHandler(JobKind kind, Func<JobContext, Task> run) : IJobHandler
{
public JobKind Kind => kind;
public Task RunAsync(JobContext context) => run(context);
}
private async Task<ChronosDatabase> OpenAsync() =>
await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(), "jobs.db")), context.Cancellation);
private static async Task<Job> WaitForStateAsync(ChronosDatabase db, Guid id, JobState state)
{
var until = DateTime.UtcNow + Budget;
while (DateTime.UtcNow < until)
{
if (await db.Jobs.GetAsync(id) is { } job && job.State == state) return job;
await Task.Delay(20);
}
Assert.Fail($"Job {id} is {(await db.Jobs.GetAsync(id))?.State}, expected {state}");
return null!;
}
[Test]
public async Task AFailedJobIsMarkedFailedAndTheWorkerGoesOnWhenLoggingFails()
{
await using var db = await OpenAsync();
var handler = new CallbackHandler(JobKind.Verify, c => c.Job.TargetLabel == "broken" ? throw new InvalidDataException("unreadable") : Task.CompletedTask);
await using var engine = new JobEngine(db, [handler], new JobEngineOptions { Workers = 1, WorkerId = "t", PollInterval = TimeSpan.FromMilliseconds(100) });
await engine.StartAsync();
using var logging = new BrokenLogging();
// The engine logs the failure before it stores it: that line failing once left the job running.
var broken = await engine.EnqueueAsync(JobKind.Verify, [], "broken");
var failed = await WaitForStateAsync(db, broken.Id, JobState.Failed);
Assert.Equal("unreadable", failed.Error);
Assert.Greater(logging.Lines, 0);
// The one worker is still claiming jobs.
var next = await engine.EnqueueAsync(JobKind.Verify, [], "fine");
await WaitForStateAsync(db, next.Id, JobState.Done);
}
[Test]
public async Task TheSchedulerFiresAndRecordsRunsWhenLoggingFails()
{
await using var db = await OpenAsync();
// Never started: the queued backups stay queued.
await using var engine = new JobEngine(db, new ArchiveService(db).CreateJobHandlers(), new JobEngineOptions { WorkerId = "t" });
var clock = new ScheduleClock(T0);
// Disposed at the end: a loop that faulted would throw there.
await using var scheduler = new Scheduler(db, engine, new SchedulerOptions { Time = clock, Tick = TimeSpan.FromHours(1) });
await scheduler.StartAsync(new TestScheduleHost(null), context.Cancellation);
var runs = Channel.CreateUnbounded<ScheduleDto>();
scheduler.ScheduleChanged += dto => runs.Writer.TryWrite(dto);
var schedule = Assert.NotNull((await scheduler.CreateAsync(new CreateScheduleRequest("Backup", ScheduleActions.Backup,
new RecurrenceDto("every", Every: 10, Unit: "minutes")), null, context.Cancellation)).Schedule);
// From here every line the loop logs (the claim, the outcome, a failed pass) fails.
using var logging = new BrokenLogging();
async Task<ScheduleDto> RunAsync(Guid? previousJob)
{
clock.Advance(TimeSpan.FromMinutes(10));
scheduler.Wake();
while (true)
{
var dto = await runs.Reader.ReadAsync(context.Cancellation).AsTask().WaitAsync(Budget);
if (dto.Id == schedule.Id && dto.LastOutcome == ScheduleOutcome.Queued && dto.LastJobId != previousJob) return dto;
}
}
var first = await RunAsync(null);
Assert.Equal(clock.Now, first.LastRun);
await db.Jobs.SetStateAsync(first.LastJobId!.Value, JobState.Done, cancellationToken: context.Cancellation);
// The loop survived the lines it could not write: the next run fires too.
var second = await RunAsync(first.LastJobId);
Assert.Equal(clock.Now, second.LastRun);
Assert.Greater(logging.Lines, 0);
}
}
@@ -9,7 +9,7 @@ public abstract class MigrationTests(TestContext context) : RepositoryTest(conte
private static readonly string[] Tables =
[
"archives", "sequences", "frames", "renders", "jobs", "media_cards", "import_history", "users", "tokens",
"render_nodes", "settings", "tags", "sequence_tags", "audit_log", "uploads",
"render_nodes", "settings", "tags", "sequence_tags", "audit_log", "uploads", "schedules",
];
[Test]
@@ -29,11 +29,78 @@ public abstract class JobRepositoryTests(TestContext context) : RepositoryTest(c
State = JobState.Failed,
Started = TestData.Now.AddMinutes(1),
Finished = TestData.Now.AddMinutes(2),
ScheduleId = Guid.CreateVersion7(),
};
await db.Jobs.EnqueueAsync(job, Ct);
var read = Assert.NotNull(await db.Jobs.GetAsync(job.Id, Ct));
Assert.SequenceEqual(job.TargetIds, read.TargetIds);
Assert.Equal(job with { TargetIds = read.TargetIds }, read);
Assert.Null((await db.Jobs.GetAsync((await EnqueueAsync(db, TestData.Job())).Id, Ct))!.ScheduleId);
}
[Test]
public async Task JobsOfAScheduleAreListedNewestFirst()
{
var db = await OpenChronosAsync();
var schedule = Guid.CreateVersion7();
var older = await EnqueueAsync(db, TestData.Job(created: TestData.Now.AddMinutes(-5)) with { ScheduleId = schedule });
var newer = await EnqueueAsync(db, TestData.Job() with { ScheduleId = schedule });
await EnqueueAsync(db, TestData.Job());
Assert.SequenceEqual([newer.Id, older.Id], (await db.Jobs.ListByScheduleAsync(schedule, cancellationToken: Ct)).Select(j => j.Id));
Assert.Empty(await db.Jobs.ListByScheduleAsync(Guid.CreateVersion7(), cancellationToken: Ct));
}
[Test]
public async Task JobsOfAScheduleArePagedNewestFirst()
{
// The runs a schedule's row lists in the admin panel (owner review 2, R10).
var db = await OpenChronosAsync();
var schedule = Guid.CreateVersion7();
var jobs = new List<Job>();
for (var i = 0; i < 3; i++) jobs.Add(await EnqueueAsync(db, TestData.Job(created: TestData.Now.AddMinutes(i)) with { ScheduleId = schedule }));
await EnqueueAsync(db, TestData.Job(created: TestData.Now.AddMinutes(5)));
var first = await db.Jobs.PageByScheduleAsync(schedule, 2, null, Ct);
Assert.SequenceEqual([jobs[2].Id, jobs[1].Id], first.Items.Select(j => j.Id));
var second = await db.Jobs.PageByScheduleAsync(schedule, 2, Assert.NotNull(first.NextCursor), Ct);
Assert.SequenceEqual([jobs[0].Id], second.Items.Select(j => j.Id));
Assert.Null(second.NextCursor);
Assert.Empty((await db.Jobs.PageByScheduleAsync(Guid.CreateVersion7(), cancellationToken: Ct)).Items);
// A cursor of another listing is refused.
var other = await db.Jobs.ListAsync(null, 1, null, Ct);
await Assert.ThrowsAsync<FormatException>(() => db.Jobs.PageByScheduleAsync(schedule, 2, Assert.NotNull(other.NextCursor), Ct));
}
[Test]
public async Task PendingJobsAreFoundByKindAndTarget()
{
// A schedule queues nothing while a job doing the same work waits, runs or is paused (owner review 2, R10).
var db = await OpenChronosAsync();
Guid archive = Guid.CreateVersion7(), a = Guid.CreateVersion7(), b = Guid.CreateVersion7(), c = Guid.CreateVersion7();
await EnqueueAsync(db, TestData.Job(JobKind.Scan) with { TargetIds = [archive] });
await EnqueueAsync(db, TestData.Job(JobKind.Thumbs) with { TargetIds = [a, b], State = JobState.Paused });
await EnqueueAsync(db, TestData.Job(JobKind.Thumbs) with { TargetIds = [c], State = JobState.Done, Finished = TestData.Now });
await EnqueueAsync(db, TestData.Job(JobKind.Verify) with { TargetIds = [archive], State = JobState.Failed, Finished = TestData.Now });
Assert.True(await db.Jobs.HasPendingAsync([JobKind.Scan, JobKind.Rebuild], [archive], Ct));
Assert.False(await db.Jobs.HasPendingAsync([JobKind.Rebuild], [archive], Ct));
Assert.False(await db.Jobs.HasPendingAsync([JobKind.Verify], [archive], Ct), "a failed job is not pending");
Assert.True(await db.Jobs.HasPendingAsync([JobKind.Thumbs], [b], Ct), "the second of a job's targets");
Assert.True(await db.Jobs.HasPendingAsync([JobKind.Thumbs], null, Ct));
Assert.False(await db.Jobs.HasPendingAsync([JobKind.Thumbs], [c], Ct), "a done job is not pending");
Assert.False(await db.Jobs.HasPendingAsync([JobKind.Scan], [], Ct));
var claimed = await db.Jobs.ClaimNextAsync("node", [JobKind.Scan], Ct);
Assert.Equal(JobState.Running, claimed!.State);
Assert.True(await db.Jobs.HasPendingAsync([JobKind.Scan], [archive], Ct), "a running job is pending");
Assert.SequenceEqual(new[] { a, b }.Order(), (await db.Jobs.ListPendingTargetsAsync(JobKind.Thumbs, Ct)).Order());
Assert.Empty(await db.Jobs.ListPendingTargetsAsync(JobKind.Verify, Ct));
}
private async Task<Job> EnqueueAsync(ChronosDatabase db, Job job)
{
await db.Jobs.EnqueueAsync(job, Ct);
return job;
}
[Test]
@@ -0,0 +1,192 @@
using Chronos.Core.Model;
using Chronos.Data.Repositories;
using Chronos.Data.Scheduling;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Repositories;
/// <summary>Schedules on both dialects (owner review 2, R10): round trip, system rows, the compare-and-set claim, due rows.</summary>
public abstract class ScheduleRepositoryTests(TestContext context) : RepositoryTest(context)
{
private static Schedule NewSchedule(string name = "Nightly scan", string? systemKey = null) => new()
{
Id = Guid.CreateVersion7(),
SystemKey = systemKey,
Name = name,
Action = ScheduleActions.Scan,
Recurrence = "daily:03:00",
Created = TestData.Now,
Updated = TestData.Now,
};
private static SystemSchedule System(string key, string recurrence = "every:10m", bool enabled = true) =>
new(key, "System " + key, ScheduleActions.Verify, ScheduleRecurrence.Parse(recurrence), new ScheduleParametersDto(Percent: 25), enabled, CatchUp: false);
[Test]
public async Task SchedulesRoundTripEveryField()
{
var db = await OpenChronosAsync();
var schedule = NewSchedule() with
{
SystemKey = "archive-scan",
Target = "current",
ParametersJson = """{"force": true}""",
CatchUp = false,
Priority = JobPriority.User,
Enabled = false,
NextRun = TestData.Now.AddHours(1),
LastRun = TestData.Now.AddHours(-1),
LastJobId = Guid.CreateVersion7(),
LastOutcome = ScheduleOutcome.SkippedPending,
CreatedBy = Guid.CreateVersion7(),
Updated = TestData.Now.AddMinutes(5),
};
await db.Schedules.InsertAsync(schedule, Ct);
Assert.Equal(schedule, await db.Schedules.GetAsync(schedule.Id, Ct));
Assert.Equal(schedule, await db.Schedules.GetBySystemKeyAsync("archive-scan", Ct));
Assert.Null(await db.Schedules.GetAsync(Guid.CreateVersion7(), Ct));
var plain = NewSchedule("Weekly verify");
await db.Schedules.InsertAsync(plain, Ct);
Assert.Equal(plain, await db.Schedules.GetAsync(plain.Id, Ct));
Assert.SequenceEqual([schedule.Id, plain.Id], (await db.Schedules.ListAsync(Ct)).Select(s => s.Id));
}
[Test]
public async Task UpdatesKeepTheRunHistoryAndSystemRowsAreNeverDeleted()
{
var db = await OpenChronosAsync();
var user = NewSchedule();
var system = NewSchedule("Backup", "index-backup");
await db.Schedules.InsertAsync(user, Ct);
await db.Schedules.InsertAsync(system, Ct);
await db.Schedules.RecordOutcomeAsync(user.Id, Guid.CreateVersion7(), ScheduleOutcome.Queued, TestData.Now, Ct);
var recorded = (await db.Schedules.GetAsync(user.Id, Ct))!;
var edited = recorded with { Name = "Renamed", Recurrence = "every:6h", Enabled = false, NextRun = null, Updated = TestData.Now.AddDays(1), LastOutcome = "ignored" };
Assert.True(await db.Schedules.UpdateAsync(edited, cancellationToken: Ct));
Assert.Equal(edited with { LastOutcome = recorded.LastOutcome }, await db.Schedules.GetAsync(user.Id, Ct));
// Without the next run: a run claimed meanwhile stays claimed.
Assert.True(await db.Schedules.TryAdvanceAsync(system.Id, null, TestData.Now.AddHours(2), Ct));
Assert.True(await db.Schedules.UpdateAsync(system with { Name = "Backup 2", NextRun = null }, setNextRun: false, Ct));
Assert.Equal(TestData.Now.AddHours(2), (await db.Schedules.GetAsync(system.Id, Ct))!.NextRun);
Assert.False(await db.Schedules.UpdateAsync(NewSchedule(), cancellationToken: Ct));
Assert.False(await db.Schedules.DeleteAsync(system.Id, Ct));
Assert.NotNull(await db.Schedules.GetAsync(system.Id, Ct));
Assert.True(await db.Schedules.DeleteAsync(user.Id, Ct));
Assert.False(await db.Schedules.DeleteAsync(user.Id, Ct));
}
[Test]
public async Task SeedingSystemSchedulesKeepsTheUsersEdits()
{
var db = await OpenChronosAsync();
Assert.Equal(2, await db.Schedules.EnsureSystemAsync([System("archive-scan"), System("index-backup", enabled: false)], TestData.Now, Ct));
var seeded = (await db.Schedules.GetBySystemKeyAsync("archive-scan", Ct))!;
Assert.Equal(("System archive-scan", "verify", "every:10m", false, true, JobPriority.Background), (seeded.Name, seeded.Action, seeded.Recurrence, seeded.CatchUp, seeded.Enabled, seeded.Priority));
// Stored normalised: the verify defaults fill what the host left out.
Assert.Equal(new ScheduleParametersDto(OlderThanDays: 30, Percent: 25), ScheduleMapping.Parameters(seeded));
Assert.Null(seeded.NextRun);
Assert.False((await db.Schedules.GetBySystemKeyAsync("index-backup", Ct))!.Enabled);
await db.Schedules.UpdateAsync(seeded with { Recurrence = "every:30m", Enabled = false }, cancellationToken: Ct);
// A later start brings other defaults and a new system schedule: the edited row stays as the user left it.
Assert.Equal(1, await db.Schedules.EnsureSystemAsync([System("archive-scan", "every:5m"), System("index-backup"), System("housekeeping")], TestData.Now, Ct));
var kept = (await db.Schedules.GetBySystemKeyAsync("archive-scan", Ct))!;
Assert.Equal((seeded.Id, "every:30m", false), (kept.Id, kept.Recurrence, kept.Enabled));
Assert.Count(3, await db.Schedules.ListAsync(Ct));
Assert.Equal(0, await db.Schedules.EnsureSystemAsync([], TestData.Now, Ct));
await db.Schedules.TryAdvanceAsync(kept.Id, null, TestData.Now.AddHours(1), Ct);
Assert.True(await db.Schedules.ResetSystemAsync("archive-scan", System("archive-scan", "every:15m"), TestData.Now.AddDays(1), Ct));
var reset = (await db.Schedules.GetBySystemKeyAsync("archive-scan", Ct))!;
Assert.Equal((seeded.Id, "every:15m", true, (DateTimeOffset?)null, TestData.Now.AddDays(1)), (reset.Id, reset.Recurrence, reset.Enabled, reset.NextRun, reset.Updated));
Assert.False(await db.Schedules.ResetSystemAsync("unknown", System("unknown"), TestData.Now, Ct));
}
[Test]
public async Task OnlyOneClaimOfARunWins()
{
var db = await OpenChronosAsync(multiConnection: true);
var schedule = NewSchedule() with { NextRun = TestData.Now };
await db.Schedules.InsertAsync(schedule, Ct);
for (var round = 0; round < 5; round++)
{
var due = (await db.Schedules.GetAsync(schedule.Id, Ct))!.NextRun;
var next = due!.Value.AddDays(1);
var claims = await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => Task.Run(() => db.Schedules.TryAdvanceAsync(schedule.Id, due, next, Ct))));
Assert.Equal(1, claims.Count(c => c));
Assert.Equal(next, (await db.Schedules.GetAsync(schedule.Id, Ct))!.NextRun);
}
Assert.False(await db.Schedules.TryAdvanceAsync(schedule.Id, TestData.Now, TestData.Now.AddDays(2), Ct), "a stale expectation loses");
var unset = NewSchedule("Unset");
await db.Schedules.InsertAsync(unset, Ct);
Assert.True(await db.Schedules.TryAdvanceAsync(unset.Id, null, TestData.Now, Ct));
Assert.False(await db.Schedules.TryAdvanceAsync(unset.Id, null, TestData.Now.AddHours(1), Ct));
var disabled = NewSchedule("Disabled") with { Enabled = false, NextRun = TestData.Now };
await db.Schedules.InsertAsync(disabled, Ct);
Assert.False(await db.Schedules.TryAdvanceAsync(disabled.Id, TestData.Now, TestData.Now.AddHours(1), Ct), "a disabled schedule is never claimed");
}
[Test]
public async Task DueSchedulesAreEnabledOnesAtOrBeforeNow()
{
var db = await OpenChronosAsync();
var late = NewSchedule("Late") with { NextRun = TestData.Now.AddHours(-2) };
var onTime = NewSchedule("On time") with { NextRun = TestData.Now };
var future = NewSchedule("Future") with { NextRun = TestData.Now.AddSeconds(1) };
var disabled = NewSchedule("Disabled") with { NextRun = TestData.Now.AddHours(-3), Enabled = false };
var unset = NewSchedule("Unset");
foreach (var s in new[] { onTime, future, disabled, unset, late }) await db.Schedules.InsertAsync(s, Ct);
Assert.SequenceEqual([late.Id, onTime.Id], (await db.Schedules.ListDueAsync(TestData.Now, Ct)).Select(s => s.Id));
}
[Test]
public async Task ARunWithoutAJobKeepsThePreviousJob()
{
var db = await OpenChronosAsync();
var schedule = NewSchedule();
await db.Schedules.InsertAsync(schedule, Ct);
var job = Guid.CreateVersion7();
Assert.True(await db.Schedules.RecordOutcomeAsync(schedule.Id, job, ScheduleOutcome.Queued, TestData.Now, Ct));
Assert.True(await db.Schedules.RecordOutcomeAsync(schedule.Id, null, ScheduleOutcome.SkippedPending, TestData.Now.AddMinutes(10), Ct));
var read = (await db.Schedules.GetAsync(schedule.Id, Ct))!;
Assert.Equal((job, ScheduleOutcome.SkippedPending, TestData.Now.AddMinutes(10)), (read.LastJobId!.Value, read.LastOutcome!, read.LastRun!.Value));
Assert.False(await db.Schedules.RecordOutcomeAsync(Guid.CreateVersion7(), null, ScheduleOutcome.Queued, TestData.Now, Ct));
}
[Test]
public async Task VerifyCandidatesAreTheLeastRecentlyVerifiedFirst()
{
var db = await OpenChronosAsync();
var archive = TestData.Archive();
await db.Archives.UpsertAsync(archive, Ct);
var never = TestData.Sequence(archive.Id) with { FrameCount = 3 };
var old = TestData.Sequence(archive.Id) with { FrameCount = 3, VerifiedAt = TestData.Now.AddDays(-60) };
var recent = TestData.Sequence(archive.Id) with { FrameCount = 3, VerifiedAt = TestData.Now.AddDays(-2) };
var empty = TestData.Sequence(archive.Id);
foreach (var s in new[] { recent, empty, old, never }) await db.Sequences.UpsertAsync(s, Ct);
var other = TestData.Archive("Other");
await db.Archives.UpsertAsync(other, Ct);
await db.Sequences.UpsertAsync(TestData.Sequence(other.Id) with { FrameCount = 1 }, Ct);
Assert.SequenceEqual([never.Id, old.Id, recent.Id], await db.Sequences.ListVerifyCandidatesAsync(archive.Id, null, 10, Ct));
Assert.SequenceEqual([never.Id, old.Id], await db.Sequences.ListVerifyCandidatesAsync(archive.Id, TestData.Now.AddDays(-30), 10, Ct));
Assert.SequenceEqual([never.Id], await db.Sequences.ListVerifyCandidatesAsync(archive.Id, null, 1, Ct));
}
}
public sealed class SqliteScheduleRepositoryTests(TestContext context) : ScheduleRepositoryTests(context)
{
protected override Backend Backend => Backend.SqliteMemory;
}
[RequiresEnvironment(PgTestServer.Variable)]
public sealed class PostgresScheduleRepositoryTests(TestContext context) : ScheduleRepositoryTests(context)
{
protected override Backend Backend => Backend.Postgres;
}
@@ -158,6 +158,17 @@ public abstract class ServerRepositoryTests(TestContext context) : RepositoryTes
Assert.Equal(3, (await db.Audit.ListAsync(user, cancellationToken: Ct)).Items.Count);
}
[Test]
public async Task TheAuditRetentionRemovesOnlyOlderEntries()
{
var db = await OpenChronosAsync();
foreach (var days in new[] { 400, 366, 10 })
await db.Audit.AppendAsync(new AuditEntry { Id = Guid.CreateVersion7(), At = TestData.Now.AddDays(-days), Action = "user.login" }, Ct);
Assert.Equal(2, await db.Audit.PurgeAsync(TestData.Now.AddDays(-365), Ct));
Assert.Equal(TestData.Now.AddDays(-10), Assert.NotNull((await db.Audit.ListAsync(cancellationToken: Ct)).Items.SingleOrDefault()).At);
Assert.Equal(0, await db.Audit.PurgeAsync(TestData.Now.AddDays(-365), Ct));
}
[Test]
public async Task UploadsTrackChunksAndStates()
{
@@ -0,0 +1,200 @@
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Housekeeping;
using Chronos.Data.Jobs;
using Chronos.Data.Sqlite;
using Chronos.Data.Tests.Archiving;
using Chronos.Testing;
namespace Chronos.Data.Tests.Scheduling;
/// <summary>The jobs schedules add (owner review 2, R10): index backups, clean-up steps, and the read-only duplicates and orphans reports.</summary>
[Category("schedules")]
public sealed class HousekeepingJobTests(TestContext context)
{
/// <summary>A host step that counts its runs, or fails.</summary>
private sealed class TestStep(string name, bool fails = false) : ICleanupStep
{
public int Runs;
public string Name => name;
public Task<string> RunAsync(CleanupContext context, CleanupParameters parameters)
{
Interlocked.Increment(ref Runs);
return fails ? throw new IOException("disk gone") : Task.FromResult($"{name} ran for {parameters.OlderThanDays} days");
}
}
private static async Task<Guid> IngestAsync(ArchiveFixture fx, string key, int count, int seed)
{
Guid sequence = default;
for (var i = 0; i < count; i++)
{
var staged = fx.Stage(ArchiveFixture.Start.AddSeconds(10 * i), seed + i);
sequence = (await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, null, null, key, staged.Path, $"IMG_{i:0000}.JPG",
staged.Size, staged.Sha256, null, null), fx.Ct)).SequenceId;
}
return sequence;
}
private static async Task<Job> RunAsync(ArchiveFixture fx, JobEngine engine, ArchiveJobRequest request, JobState state = JobState.Done)
{
var job = await engine.EnqueueAsync(request, cancellationToken: fx.Ct);
return await fx.WaitForAsync(job.Id, state);
}
[Test]
public async Task BackupsGoNextToTheIndexAndKeepTheNewest()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
var engine = await fx.StartEngineAsync();
var path = ((SqliteDatabase)fx.Db.Database).Path!;
Job done = null!;
for (var i = 0; i < 3; i++) done = await RunAsync(fx, engine, ArchiveJobs.Backup(keep: 2));
var backups = DatabaseBackups.List(DatabaseBackups.DefaultDirectory(path), path);
Assert.Equal(2, backups.Count);
Assert.Equal(Path.Combine(Path.GetDirectoryName(path)!, "backups"), DatabaseBackups.DefaultDirectory(path));
Assert.Contains(backups[0].Path, done.LogTail);
Assert.Equal((1L, 1L), (done.ProgressDone, done.ProgressTotal));
Assert.Null(DatabaseBackups.Unavailable(fx.Db));
// One folder, one retention: a backup that keeps fewer never deletes the copies the index backup schedule keeps.
await fx.Db.Schedules.EnsureSystemAsync([new Data.Scheduling.SystemSchedule(DatabaseBackups.ScheduleKey, "Index backup", Data.Scheduling.ScheduleActions.Backup,
Data.Scheduling.ScheduleRecurrence.Parse("daily:03:00"), new Protocol.ScheduleParametersDto(Keep: 4))], DateTimeOffset.UtcNow, fx.Ct);
for (var i = 0; i < 3; i++) await RunAsync(fx, engine, ArchiveJobs.Backup(keep: 1));
Assert.Count(4, DatabaseBackups.List(DatabaseBackups.DefaultDirectory(path), path));
}
[Test]
public async Task ABackupOfAnIndexWithoutAFileFails()
{
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.SqliteInMemory(), context.Cancellation);
Assert.Equal(Data.Scheduling.ScheduleUnavailable.NoIndexFile, DatabaseBackups.Unavailable(db));
await using var engine = new JobEngine(db, new ArchiveService(db).CreateJobHandlers(),
new JobEngineOptions { WorkerId = "memory", PollInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync(context.Cancellation);
var job = await engine.EnqueueAsync(ArchiveJobs.Backup(), cancellationToken: context.Cancellation);
for (var i = 0; i < 500 && (await db.Jobs.GetAsync(job.Id))!.State is JobState.Queued or JobState.Running; i++) await Task.Delay(20);
var failed = (await db.Jobs.GetAsync(job.Id))!;
Assert.Equal(JobState.Failed, failed.State);
Assert.Contains("without a file", failed.Error);
}
[Test]
public async Task TheJobHistoryStepRemovesOnlyOldFinishedJobs()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
var now = DateTimeOffset.UtcNow;
Job Old(JobState state, int days, JobKind kind = JobKind.Scan) => new()
{
Id = Guid.CreateVersion7(),
Kind = kind,
State = state,
Created = now.AddDays(-days),
Finished = state is JobState.Done or JobState.Failed or JobState.Cancelled ? now.AddDays(-days) : null,
};
// A render waits: the archive engine has no render handler, so it stays queued however old.
var old = Old(JobState.Done, 100);
var oldFailed = Old(JobState.Failed, 91);
var recent = Old(JobState.Done, 10);
var waiting = Old(JobState.Queued, 200, JobKind.Render);
foreach (var job in new[] { old, oldFailed, recent, waiting }) await fx.Db.Jobs.EnqueueAsync(job, fx.Ct);
var engine = await fx.StartEngineAsync();
var kept = await RunAsync(fx, engine, ArchiveJobs.Cleanup(fx.Archive, [CleanupSteps.JobHistory], 0));
Assert.Contains(Loc.L("Archive.Log.HistoryKept"), kept.LogTail);
Assert.NotNull(await fx.Db.Jobs.GetAsync(old.Id, fx.Ct));
var purged = await RunAsync(fx, engine, ArchiveJobs.Cleanup(fx.Archive, [CleanupSteps.JobHistory], 90));
Assert.Contains(Loc.L("Archive.Log.HistoryPurged", 2), purged.LogTail);
Assert.Null(await fx.Db.Jobs.GetAsync(old.Id, fx.Ct));
Assert.Null(await fx.Db.Jobs.GetAsync(oldFailed.Id, fx.Ct));
Assert.NotNull(await fx.Db.Jobs.GetAsync(recent.Id, fx.Ct));
Assert.NotNull(await fx.Db.Jobs.GetAsync(waiting.Id, fx.Ct));
}
[Test]
public async Task TheAuditStepKeepsEverythingAtZeroDays()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
var now = DateTimeOffset.UtcNow;
foreach (var days in new[] { 400, 1 })
await fx.Db.Audit.AppendAsync(new AuditEntry { Id = Guid.CreateVersion7(), At = now.AddDays(-days), Action = "user.login" }, fx.Ct);
var engine = await fx.StartEngineAsync();
var kept = await RunAsync(fx, engine, ArchiveJobs.Cleanup(null, [CleanupSteps.Audit], 0));
Assert.Contains(Loc.L("Archive.Log.AuditKept"), kept.LogTail);
Assert.Count(2, (await fx.Db.Audit.ListAsync(cancellationToken: fx.Ct)).Items);
var purged = await RunAsync(fx, engine, ArchiveJobs.Cleanup(null, [CleanupSteps.Audit], 365));
Assert.Contains(Loc.L("Archive.Log.AuditPurged", 1), purged.LogTail);
Assert.Count(1, (await fx.Db.Audit.ListAsync(cancellationToken: fx.Ct)).Items);
}
[Test]
public async Task TheTrashReportListsOldEntriesAndNeverDeletes()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
var id = await IngestAsync(fx, "a", 2, 1);
var entry = (await fx.Service.DeleteAsync(await fx.Service.PlanDeleteAsync([id], cancellationToken: fx.Ct), "test", cancellationToken: fx.Ct)).Single();
var folder = Path.Combine(SequenceTrash.TrashDirectory(fx.Paths), entry.Name);
var files = Directory.GetFiles(folder, "*", SearchOption.AllDirectories).Length;
var engine = await fx.StartEngineAsync();
var all = await RunAsync(fx, engine, ArchiveJobs.Cleanup(fx.Archive, [CleanupSteps.TrashReport, "shred"], 0));
Assert.Contains(Loc.L("Archive.Log.TrashReport", 1, CleanupSteps.Megabytes(entry.Bytes)), all.LogTail);
Assert.Contains(entry.Title, all.LogTail);
Assert.Contains(Loc.L("Archive.Log.StepUnknown", "shred"), all.LogTail);
var none = await RunAsync(fx, engine, ArchiveJobs.Cleanup(fx.Archive, [CleanupSteps.TrashReport], 30));
Assert.Contains(Loc.L("Archive.Log.TrashReport", 0, CleanupSteps.Megabytes(0)), none.LogTail);
// Reported, never deleted: emptying the trash stays the user's action.
Assert.Equal(files, Directory.GetFiles(folder, "*", SearchOption.AllDirectories).Length);
Assert.Equal(entry.Name, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single().Name);
var offline = await RunAsync(fx, engine, ArchiveJobs.Cleanup(null, [CleanupSteps.TrashReport], 0));
Assert.Contains(Loc.L("Archive.Log.TrashOffline"), offline.LogTail);
}
[Test]
public async Task AFailingStepFailsTheJobAfterTheOthersRan()
{
var count = new TestStep("count");
var explode = new TestStep("explode", fails: true);
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(), "chronos.db")), context.Cancellation);
var service = new ArchiveService(db, new ArchiveServiceOptions { CleanupSteps = [explode, count, new TestStep(CleanupSteps.Audit)] });
Assert.SequenceEqual([CleanupSteps.JobHistory, CleanupSteps.Audit, CleanupSteps.TrashReport, "explode", "count"], service.CleanupSteps.Select(s => s.Name));
await using var engine = new JobEngine(db, service.CreateJobHandlers(), new JobEngineOptions { WorkerId = "steps", PollInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync(context.Cancellation);
var job = await engine.EnqueueAsync(ArchiveJobs.Cleanup(null, ["explode", "count"], 7), cancellationToken: context.Cancellation);
for (var i = 0; i < 500 && (await db.Jobs.GetAsync(job.Id))!.State is JobState.Queued or JobState.Running; i++) await Task.Delay(20);
var failed = (await db.Jobs.GetAsync(job.Id))!;
Assert.Equal(JobState.Failed, failed.State);
Assert.Contains("explode", failed.Error);
Assert.Contains(Loc.L("Archive.Log.StepFailed", "explode", "disk gone"), failed.LogTail);
Assert.Contains("count ran for 7 days", failed.LogTail);
Assert.Equal((1, 1), (explode.Runs, count.Runs));
}
[Test]
public async Task DuplicatesAndOrphansReportWithoutChangingAnything()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await IngestAsync(fx, "a", 3, 1);
await IngestAsync(fx, "b", 2, 1);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "New folder"), ArchiveFixture.Start, 1, firstSeed: 60);
var before = await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id);
var engine = await fx.StartEngineAsync();
var duplicates = await RunAsync(fx, engine, ArchiveJobs.Duplicates(fx.Archive));
Assert.Contains(Loc.L("Archive.Log.DuplicatesDone", 2, 2), duplicates.LogTail);
Assert.Contains(Loc.L("Archive.Log.ReportOnly"), duplicates.LogTail);
var orphans = await RunAsync(fx, engine, ArchiveJobs.Orphans(fx.Archive));
Assert.Contains(Loc.L("Archive.Log.FolderUnindexed", "New folder"), orphans.LogTail);
Assert.Contains(Loc.L("Archive.Log.OrphanFolders", 0, 1), orphans.LogTail);
Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id));
Assert.Equal(0L, (await fx.Db.Sequences.GetStatsAsync(fx.Archive.Id, fx.Ct)).Health.DuplicateFrames);
}
}
@@ -0,0 +1,174 @@
using Chronos.Data.Scheduling;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Scheduling;
/// <summary>The in-house recurrence of schedules (owner review 2, R10): text form, intervals on their anchor, wall-clock times across clock changes.</summary>
[Category("schedules")]
public sealed class ScheduleRecurrenceTests
{
/// <summary>Central European time, built here so the test does not depend on the machine's zone data: +1, +2 from the last Sunday of March 02:00 to the last Sunday of October 03:00.</summary>
internal static readonly TimeZoneInfo Cet = TimeZoneInfo.CreateCustomTimeZone("Test/CET", TimeSpan.FromHours(1), "Test CET", "Test CET", "Test CEST",
[
TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(DateTime.MinValue.Date, DateTime.MaxValue.Date, TimeSpan.FromHours(1),
TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 3, 5, DayOfWeek.Sunday),
TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 3, 0, 0), 10, 5, DayOfWeek.Sunday)),
]);
private static DateTimeOffset Utc(int month, int day, int hour, int minute = 0, int second = 0) => new(2026, month, day, hour, minute, second, TimeSpan.Zero);
[Theory]
[Case("every:5m", "every:5m")]
[Case("every:1440m", "every:1440m")]
[Case(" Every : 6H ", "every:6h")]
[Case("every:7d", "every:7d")]
[Case("daily:3:05", "daily:03:05")]
[Case("daily:23:59", "daily:23:59")]
[Case("weekly:thu,mon,thu@2:30", "weekly:mon,thu@02:30")]
[Case("WEEKLY:sun@00:00", "weekly:sun@00:00")]
[Case("monthly:28@04:00", "monthly:28@04:00")]
[Case("monthly: 1 @ 04:00", "monthly:1@04:00")]
public void TheTextFormRoundTrips(string text, string canonical)
{
var recurrence = ScheduleRecurrence.Parse(text);
Assert.Equal(canonical, recurrence.Format());
Assert.Equal(recurrence, ScheduleRecurrence.Parse(recurrence.Format()));
Assert.Equal(recurrence, ScheduleMapping.FromDto(ScheduleMapping.ToDto(recurrence)));
}
[Theory]
[Case("")]
[Case("every")]
[Case("every:")]
[Case("every:4m")]
[Case("every:1441m")]
[Case("every:0h")]
[Case("every:169h")]
[Case("every:367d")]
[Case("every:10x")]
[Case("every:-5m")]
[Case("every:1.5h")]
[Case("hourly:1")]
[Case("daily:24:00")]
[Case("daily:12:60")]
[Case("daily:3:5")]
[Case("daily:")]
[Case("weekly:@03:00")]
[Case("weekly:mon")]
[Case("weekly:mon,xyz@03:00")]
[Case("monthly:0@03:00")]
[Case("monthly:29@03:00")]
[Case("monthly:@03:00")]
public void InvalidTextIsRefused(string text)
{
Assert.False(ScheduleRecurrence.TryParse(text, out _), text);
Assert.Throws<FormatException>(() => ScheduleRecurrence.Parse(text));
}
[Test]
public void TheFactoriesCheckTheirRanges()
{
Assert.False(ScheduleRecurrence.TryParse(null, out _));
Assert.Throws<ArgumentOutOfRangeException>(() => ScheduleRecurrence.Interval(4, RecurrenceUnit.Minutes));
Assert.Throws<ArgumentOutOfRangeException>(() => ScheduleRecurrence.MonthlyAt(29, new TimeOnly(3, 0)));
Assert.Throws<ArgumentException>(() => ScheduleRecurrence.WeeklyAt([], new TimeOnly(3, 0)));
// Seconds are dropped: schedules work to the minute.
Assert.Equal(ScheduleRecurrence.DailyAt(new TimeOnly(3, 0)), ScheduleRecurrence.DailyAt(new TimeOnly(3, 0, 42)));
Assert.Equal(ScheduleRecurrence.Parse("weekly:thu,mon@02:30"), ScheduleRecurrence.WeeklyAt([DayOfWeek.Monday, DayOfWeek.Thursday], new TimeOnly(2, 30)));
Assert.NotEqual(ScheduleRecurrence.Parse("weekly:mon@02:30"), ScheduleRecurrence.Parse("weekly:tue@02:30"));
Assert.SequenceEqual([DayOfWeek.Monday, DayOfWeek.Sunday], ScheduleRecurrence.Parse("weekly:sun,mon@02:30").Days);
}
[Test]
public void PeriodsBoundTheGapBetweenRuns()
{
Assert.Equal(TimeSpan.FromMinutes(10), ScheduleRecurrence.Parse("every:10m").Period);
Assert.Equal(TimeSpan.FromHours(6), ScheduleRecurrence.Parse("every:6h").Period);
Assert.Equal(TimeSpan.FromDays(2), ScheduleRecurrence.Parse("every:2d").Period);
Assert.Equal(TimeSpan.FromDays(1), ScheduleRecurrence.Parse("daily:03:00").Period);
Assert.Equal(TimeSpan.FromDays(7), ScheduleRecurrence.Parse("weekly:mon@03:00").Period);
Assert.Equal(TimeSpan.FromDays(31), ScheduleRecurrence.Parse("monthly:1@03:00").Period);
}
[Test]
public void IntervalsStayOnTheGridOfTheirAnchor()
{
var every10 = ScheduleRecurrence.Parse("every:10m");
var anchor = Utc(10, 2, 12, 0);
Assert.Equal(Utc(10, 2, 12, 10), every10.Next(anchor, TimeZoneInfo.Utc, anchor));
// Late by 35 minutes: the missed runs collapse into the next one on the grid, no drift.
Assert.Equal(Utc(10, 2, 12, 40), every10.Next(Utc(10, 2, 12, 35, 10), TimeZoneInfo.Utc, anchor));
Assert.Equal(Utc(10, 2, 12, 40), every10.Next(Utc(10, 2, 12, 30), TimeZoneInfo.Utc, anchor));
// An anchor ahead of the time asked about is itself on the grid.
Assert.Equal(Utc(10, 2, 11, 50), every10.Next(Utc(10, 2, 11, 45), TimeZoneInfo.Utc, anchor));
Assert.Equal(Utc(10, 2, 12, 0), every10.Next(Utc(10, 2, 11, 59, 59), TimeZoneInfo.Utc, anchor));
// Without an anchor: one interval after the minute.
Assert.Equal(Utc(10, 2, 12, 13), every10.Next(Utc(10, 2, 12, 3, 27), TimeZoneInfo.Utc));
// Days of an interval are 24 hours whatever the clocks do.
Assert.Equal(Utc(3, 29, 1, 30), ScheduleRecurrence.Parse("every:1d").Next(Utc(3, 28, 1, 30), Cet, Utc(3, 28, 1, 30)));
}
[Test]
public void DailyWeeklyAndMonthlyTimesAreWallClockTimes()
{
var daily = ScheduleRecurrence.Parse("daily:03:00");
Assert.Equal(Utc(10, 2, 3, 0), daily.Next(Utc(10, 2, 2, 59), TimeZoneInfo.Utc));
Assert.Equal(Utc(10, 3, 3, 0), daily.Next(Utc(10, 2, 3, 0), TimeZoneInfo.Utc));
// 03:00 in Rome on 2 October (summer time) is 01:00 UTC; in January (winter time) 02:00 UTC.
Assert.Equal(Utc(10, 2, 1, 0), daily.Next(Utc(10, 1, 23, 0), Cet));
Assert.Equal(new DateTimeOffset(2027, 1, 15, 2, 0, 0, TimeSpan.Zero), daily.Next(new DateTimeOffset(2027, 1, 15, 1, 0, 0, TimeSpan.Zero), Cet));
// 2 October 2026 is a Friday.
var weekly = ScheduleRecurrence.Parse("weekly:mon,thu@08:00");
Assert.Equal(Utc(10, 5, 6, 0), weekly.Next(Utc(10, 2, 12, 0), Cet));
Assert.Equal(Utc(10, 8, 6, 0), weekly.Next(Utc(10, 5, 6, 0), Cet));
Assert.Equal(Utc(10, 12, 6, 0), weekly.Next(Utc(10, 8, 7, 0), Cet));
var monthly = ScheduleRecurrence.Parse("monthly:28@04:00");
Assert.Equal(Utc(3, 28, 4, 0), monthly.Next(Utc(2, 28, 5, 0), TimeZoneInfo.Utc));
Assert.Equal(Utc(2, 28, 4, 0), monthly.Next(Utc(1, 28, 4, 0), TimeZoneInfo.Utc));
}
[Test]
public void ATimeTheClocksSkipMovesForwardByTheGap()
{
// 29 March 2026: 02:00 CET becomes 03:00 CEST, so 02:30 does not exist that night and runs at 03:30 CEST.
var daily = ScheduleRecurrence.Parse("daily:02:30");
var next = daily.Next(Utc(3, 28, 23, 0), Cet);
Assert.Equal(Utc(3, 29, 1, 30), next);
Assert.Equal(new DateTime(2026, 3, 29, 3, 30, 0), TimeZoneInfo.ConvertTime(next, Cet).DateTime);
// The next night is a normal one again.
Assert.Equal(Utc(3, 30, 0, 30), daily.Next(next, Cet));
Assert.Equal(Utc(3, 29, 1, 30), ScheduleRecurrence.ToUtc(new DateTime(2026, 3, 29, 2, 30, 0), Cet));
}
[Test]
public void ATimeTheClocksGoBackOverRunsOnceAtItsFirstOccurrence()
{
// 25 October 2026: 03:00 CEST becomes 02:00 CET, so 02:30 happens twice; it runs at the first (00:30 UTC).
var daily = ScheduleRecurrence.Parse("daily:02:30");
var first = daily.Next(Utc(10, 24, 23, 0), Cet);
Assert.Equal(Utc(10, 25, 0, 30), first);
// Not again an hour later at the second 02:30: the next run is the next day's.
Assert.Equal(Utc(10, 26, 1, 30), daily.Next(first, Cet));
Assert.Equal(Utc(10, 26, 1, 30), daily.Next(Utc(10, 25, 1, 0), Cet));
Assert.Equal(Utc(10, 25, 0, 30), ScheduleRecurrence.ToUtc(new DateTime(2026, 10, 25, 2, 30, 0), Cet));
}
[Test]
public void TheStructuredFormIsCheckedLikeTheText()
{
Assert.Equal("every:15m", ScheduleMapping.FromDto(new RecurrenceDto("every", Every: 15, Unit: "minutes"))?.Format());
Assert.Equal("weekly:mon,fri@06:00", ScheduleMapping.FromDto(new RecurrenceDto("Weekly", Time: "06:00", Days: ["fri", "mon"]))?.Format());
Assert.Equal("monthly:3@01:15", ScheduleMapping.FromDto(new RecurrenceDto("monthly", Time: "01:15", DayOfMonth: 3))?.Format());
Assert.Equal(new RecurrenceDto("weekly", Time: "06:00", Days: null), ScheduleMapping.ToDto(ScheduleRecurrence.Parse("weekly:mon@06:00")) with { Days = null });
Assert.Null(ScheduleMapping.FromDto(null));
Assert.Null(ScheduleMapping.FromDto(new RecurrenceDto("every", Every: 2, Unit: "minutes")));
Assert.Null(ScheduleMapping.FromDto(new RecurrenceDto("every", Every: 2, Unit: "weeks")));
Assert.Null(ScheduleMapping.FromDto(new RecurrenceDto("daily")));
Assert.Null(ScheduleMapping.FromDto(new RecurrenceDto("weekly", Time: "06:00", Days: [])));
Assert.Null(ScheduleMapping.FromDto(new RecurrenceDto("monthly", Time: "06:00", DayOfMonth: 31)));
Assert.Null(ScheduleMapping.FromDto(new RecurrenceDto("yearly", Time: "06:00")));
}
}
@@ -0,0 +1,722 @@
using System.Threading.Channels;
using Chronos.Core.Archiving;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Scheduling;
using Chronos.Data.Sqlite;
using Chronos.Data.Tests.Archiving;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Scheduling;
/// <summary>
/// A clock the test sets by hand; its timers are real ones, so the scheduler's loop waits in real time (most tests drive
/// passes themselves; the loop's own tests give it a short tick or wake it).
/// </summary>
internal sealed class ScheduleClock(DateTimeOffset start) : TimeProvider
{
private long _ticks = start.UtcTicks;
public DateTimeOffset Now => GetUtcNow();
public override DateTimeOffset GetUtcNow() => new(Interlocked.Read(ref _ticks), TimeSpan.Zero);
public void Advance(TimeSpan by) => Interlocked.Add(ref _ticks, by.Ticks);
public void Set(DateTimeOffset at) => Interlocked.Exchange(ref _ticks, at.UtcTicks);
}
/// <summary>A host whose archive, system schedules and refusals the test sets.</summary>
internal sealed class TestScheduleHost(Archive? archive) : IScheduleHost
{
public Archive? Archive { get; set; } = archive;
public TimeZoneInfo TimeZone { get; set; } = TimeZoneInfo.Utc;
public List<SystemSchedule> Systems { get; } = [];
public Dictionary<string, string> Refused { get; } = [];
public IReadOnlyList<SystemSchedule> SystemSchedules => Systems;
public IReadOnlyList<string> CleanupSteps { get; set; } = ["job-history", "audit", "trash-report"];
public bool DeepAnalysisAfterScan { get; set; }
/// <summary>Awaited before the archive is handed out (a slow drive, a pass the test holds).</summary>
public Func<CancellationToken, Task>? BeforeArchive { get; set; }
public async ValueTask<Archive?> GetArchiveAsync(CancellationToken cancellationToken)
{
if (BeforeArchive is { } wait) await wait(cancellationToken);
return Archive;
}
public string? Unavailable(string action) => Refused.GetValueOrDefault(action);
}
/// <summary>The scheduler (owner review 2, R10): due runs fire once, pending work is not queued twice, catch-up, clock changes, edits.</summary>
[Category("schedules")]
public sealed class SchedulerTests(TestContext context)
{
private static readonly DateTimeOffset T0 = new(2026, 10, 2, 9, 0, 0, TimeSpan.Zero);
private static readonly RecurrenceDto Every10 = new("every", Every: 10, Unit: "minutes");
private CancellationToken Ct => context.Cancellation;
/// <summary>An engine with the archive and analysis handlers that is never started, so queued jobs stay queued.</summary>
private static JobEngine Engine(ArchiveFixture fx) =>
new(fx.Db, [.. fx.Service.CreateJobHandlers(), .. new ProcessingService(fx.Db).CreateJobHandlers()], new JobEngineOptions { WorkerId = "test" });
private async Task<Scheduler> StartAsync(ChronosDatabase db, JobEngine engine, IScheduleHost host, ScheduleClock clock)
{
var scheduler = new Scheduler(db, engine, new SchedulerOptions { Time = clock, Tick = TimeSpan.FromHours(1) });
await scheduler.StartAsync(host, Ct);
return scheduler;
}
private async Task<ScheduleDto> CreateAsync(Scheduler scheduler, string action, RecurrenceDto? recurrence = null, ScheduleParametersDto? parameters = null,
bool enabled = true, bool catchUp = true)
{
var result = await scheduler.CreateAsync(new CreateScheduleRequest("Test " + action, action, recurrence ?? Every10, parameters, catchUp, Enabled: enabled), null, Ct);
Assert.Null(result.Problem);
return result.Schedule!;
}
[Test]
public async Task ADueScheduleFiresOnceAtItsPriorityWithItsId()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
var clock = new ScheduleClock(T0);
await using var scheduler = await StartAsync(fx.Db, engine, new TestScheduleHost(fx.Archive), clock);
var schedule = await CreateAsync(scheduler, ScheduleActions.Scan);
Assert.Equal(T0.AddMinutes(10), schedule.NextRun);
Assert.Equal(0, await scheduler.RunDueAsync(Ct));
clock.Advance(TimeSpan.FromMinutes(10));
Assert.Equal(1, await scheduler.RunDueAsync(Ct));
Assert.Equal(0, await scheduler.RunDueAsync(Ct));
var job = (await fx.Db.Jobs.ListByScheduleAsync(schedule.Id, cancellationToken: Ct)).Single();
Assert.Equal((JobKind.Scan, JobPriority.Background, JobState.Queued), (job.Kind, job.Priority, job.State));
Assert.SequenceEqual([fx.Archive.Id], job.TargetIds);
var after = (await scheduler.GetAsync(schedule.Id, Ct))!;
Assert.Equal((ScheduleOutcome.Queued, job.Id, T0.AddMinutes(20), clock.Now), (after.LastOutcome!, after.LastJobId!.Value, after.NextRun!.Value, after.LastRun!.Value));
}
[Test]
public async Task ARunWhosePreviousJobIsPendingIsSkipped()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
var clock = new ScheduleClock(T0);
await using var scheduler = await StartAsync(fx.Db, engine, new TestScheduleHost(fx.Archive), clock);
var schedule = await CreateAsync(scheduler, ScheduleActions.Duplicates);
clock.Advance(TimeSpan.FromMinutes(10));
await scheduler.RunDueAsync(Ct);
var first = (await scheduler.GetAsync(schedule.Id, Ct))!.LastJobId;
clock.Advance(TimeSpan.FromMinutes(10));
Assert.Equal(1, await scheduler.RunDueAsync(Ct));
var skipped = (await scheduler.GetAsync(schedule.Id, Ct))!;
Assert.Equal((ScheduleOutcome.SkippedPending, first), (skipped.LastOutcome!, skipped.LastJobId));
Assert.Count(1, await fx.Db.Jobs.ListByScheduleAsync(schedule.Id, cancellationToken: Ct));
// Once it ends, the next run queues again; a scan another user queued counts as the same work.
await fx.Db.Jobs.SetStateAsync(first!.Value, JobState.Done, cancellationToken: Ct);
clock.Advance(TimeSpan.FromMinutes(10));
await scheduler.RunDueAsync(Ct);
Assert.Equal(ScheduleOutcome.Queued, (await scheduler.GetAsync(schedule.Id, Ct))!.LastOutcome);
await engine.EnqueueAsync(ArchiveJobs.Scan(fx.Archive), cancellationToken: Ct);
var scan = await CreateAsync(scheduler, ScheduleActions.Scan);
Assert.Equal(ScheduleOutcome.SkippedPending, (await scheduler.RunNowAsync(scan.Id, null, Ct))!.Outcome);
}
[Test]
public async Task MissedRunsFireOnceWithCatchUpAndAreSkippedWithout()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
var clock = new ScheduleClock(T0);
var host = new TestScheduleHost(fx.Archive);
ScheduleDto catchUp, skip;
await using (var before = await StartAsync(fx.Db, engine, host, clock))
{
catchUp = await CreateAsync(before, ScheduleActions.Scan, new RecurrenceDto("every", Every: 1, Unit: "hours"), catchUp: true);
skip = await CreateAsync(before, ScheduleActions.Orphans, new RecurrenceDto("every", Every: 1, Unit: "hours"), catchUp: false);
}
// The host was off for 5 h 30: five runs of each were missed.
clock.Advance(TimeSpan.FromMinutes(330));
await using var after = await StartAsync(fx.Db, engine, host, clock);
Assert.Count(1, await fx.Db.Jobs.ListByScheduleAsync(catchUp.Id, cancellationToken: Ct));
Assert.Empty(await fx.Db.Jobs.ListByScheduleAsync(skip.Id, cancellationToken: Ct));
var caught = (await after.GetAsync(catchUp.Id, Ct))!;
var skipped = (await after.GetAsync(skip.Id, Ct))!;
Assert.Equal(ScheduleOutcome.Queued, caught.LastOutcome);
Assert.Null(skipped.LastOutcome);
// Both move to the next occurrence on their grid, in the future.
Assert.Equal(T0.AddHours(6), caught.NextRun);
Assert.Equal(T0.AddHours(6), skipped.NextRun);
Assert.Equal(0, await after.RunDueAsync(Ct));
}
/// <summary>The server fixes an age limit from its environment there: a run caught up at start must already use it.</summary>
[Test]
public async Task AnEditBeforeTheFirstPassAppliesToTheRunCaughtUpAtStart()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
var clock = new ScheduleClock(T0);
var host = new TestScheduleHost(fx.Archive);
host.Systems.Add(new SystemSchedule("audit-cleanup", "Audit log clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.Parse("daily:04:30"),
new ScheduleParametersDto(OlderThanDays: 90, Steps: ["audit"])));
await using (await StartAsync(fx.Db, engine, host, clock))
{
}
// The host was off over the run of 04:30.
clock.Advance(TimeSpan.FromDays(1));
await using var scheduler = new Scheduler(fx.Db, engine, new SchedulerOptions { Time = clock, Tick = TimeSpan.FromHours(1) });
var id = Guid.Empty;
await scheduler.StartAsync(host, async ct =>
{
var row = (await fx.Db.Schedules.GetBySystemKeyAsync("audit-cleanup", ct))!;
id = row.Id;
Assert.Empty(await fx.Db.Jobs.ListByScheduleAsync(id, cancellationToken: ct));
var edit = await scheduler.UpdateAsync(id, new UpdateScheduleRequest(Parameters: new ScheduleParametersDto(OlderThanDays: 365, Steps: ["audit"])), ct);
Assert.Null(edit.Problem);
}, Ct);
var jobs = await fx.Db.Jobs.ListByScheduleAsync(id, cancellationToken: Ct);
Assert.Count(1, jobs);
using var parameters = System.Text.Json.JsonDocument.Parse(jobs[0].ParametersJson!);
Assert.Equal(365, parameters.RootElement.GetProperty("olderThanDays").GetInt32());
}
[Test]
public async Task DisabledSchedulesNeverRunAndGetANewNextRunWhenEnabled()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
var clock = new ScheduleClock(T0);
await using var scheduler = await StartAsync(fx.Db, engine, new TestScheduleHost(fx.Archive), clock);
var disabled = await CreateAsync(scheduler, ScheduleActions.Scan, enabled: false);
Assert.Null(disabled.NextRun);
var enabled = await CreateAsync(scheduler, ScheduleActions.Orphans);
Assert.Null((await scheduler.UpdateAsync(enabled.Id, new UpdateScheduleRequest(Enabled: false), Ct)).Schedule!.NextRun);
clock.Advance(TimeSpan.FromDays(1));
Assert.Equal(0, await scheduler.RunDueAsync(Ct));
Assert.Empty((await fx.Db.Jobs.ListAsync(cancellationToken: Ct)).Items);
var back = (await scheduler.UpdateAsync(enabled.Id, new UpdateScheduleRequest(Enabled: true), Ct)).Schedule!;
Assert.Equal(clock.Now.AddMinutes(10), back.NextRun);
Assert.Equal(0, await scheduler.RunDueAsync(Ct));
// An edit that keeps the recurrence keeps the next run; a new recurrence moves it.
Assert.Equal(back.NextRun, (await scheduler.UpdateAsync(enabled.Id, new UpdateScheduleRequest(Name: "Renamed"), Ct)).Schedule!.NextRun);
var hourly = (await scheduler.UpdateAsync(enabled.Id, new UpdateScheduleRequest(Recurrence: new RecurrenceDto("daily", Time: "03:00")), Ct)).Schedule!;
Assert.Equal(new DateTimeOffset(2026, 10, 4, 3, 0, 0, TimeSpan.Zero), hourly.NextRun);
}
[Test]
public async Task RunNowQueuesForTheUserWithoutMovingTheNextRun()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
var clock = new ScheduleClock(T0);
await using var scheduler = await StartAsync(fx.Db, engine, new TestScheduleHost(fx.Archive), clock);
var user = Guid.CreateVersion7();
var disabled = await CreateAsync(scheduler, ScheduleActions.Duplicates, enabled: false);
var run = (await scheduler.RunNowAsync(disabled.Id, user, Ct))!;
Assert.Equal(ScheduleOutcome.Queued, run.Outcome);
var job = (await fx.Db.Jobs.GetAsync(run.JobId!.Value, Ct))!;
Assert.Equal((JobKind.Duplicates, user, disabled.Id), (job.Kind, job.CreatedBy!.Value, job.ScheduleId!.Value));
Assert.Null(run.Schedule.NextRun);
Assert.Equal(run.JobId, run.Schedule.LastJobId);
var enabled = await CreateAsync(scheduler, ScheduleActions.Orphans);
Assert.Equal(ScheduleOutcome.Queued, (await scheduler.RunNowAsync(enabled.Id, null, Ct))!.Outcome);
Assert.Equal(enabled.NextRun, (await scheduler.GetAsync(enabled.Id, Ct))!.NextRun);
Assert.Equal(ScheduleOutcome.SkippedPending, (await scheduler.RunNowAsync(enabled.Id, null, Ct))!.Outcome);
Assert.Null(await scheduler.RunNowAsync(Guid.CreateVersion7(), null, Ct));
}
[Test]
public async Task TwoSchedulersOnOneDatabaseFireEachRunOnce()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
var path = ((SqliteDatabase)fx.Db.Database).Path!;
await using var otherDb = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(path), Ct);
await using var engine = Engine(fx);
await using var otherEngine = new JobEngine(otherDb, fx.Service.CreateJobHandlers(), new JobEngineOptions { WorkerId = "other" });
var clock = new ScheduleClock(T0);
await using var a = await StartAsync(fx.Db, engine, new TestScheduleHost(fx.Archive), clock);
await using var b = await StartAsync(otherDb, otherEngine, new TestScheduleHost(fx.Archive), clock);
var schedule = await CreateAsync(a, ScheduleActions.Backup);
for (var round = 1; round <= 4; round++)
{
clock.Advance(TimeSpan.FromMinutes(10));
var fired = await Task.WhenAll(Task.Run(() => a.RunDueAsync(Ct)), Task.Run(() => b.RunDueAsync(Ct)));
Assert.Equal(1, fired.Sum(), $"round {round}");
// The backup jobs never run here: each round queues once, then the next is skipped while it waits.
Assert.Count(1, await fx.Db.Jobs.ListByScheduleAsync(schedule.Id, cancellationToken: Ct));
}
}
[Test]
public async Task ANextRunFarAheadAfterTheClockWentBackIsComputedAgain()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
var clock = new ScheduleClock(T0);
await using var scheduler = await StartAsync(fx.Db, engine, new TestScheduleHost(fx.Archive), clock);
var schedule = await CreateAsync(scheduler, ScheduleActions.Scan);
clock.Set(T0.AddHours(-5).AddSeconds(20));
Assert.Equal(0, await scheduler.RunDueAsync(Ct));
Assert.Equal(T0.AddHours(-5).AddMinutes(10), (await scheduler.GetAsync(schedule.Id, Ct))!.NextRun);
// Within two periods it is left alone.
clock.Advance(TimeSpan.FromMinutes(-5));
await scheduler.RunDueAsync(Ct);
Assert.Equal(T0.AddHours(-5).AddMinutes(10), (await scheduler.GetAsync(schedule.Id, Ct))!.NextRun);
}
[Test]
public async Task SystemSchedulesAreSeededOnceEditableAndResetNeverDeleted()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
var clock = new ScheduleClock(T0);
var host = new TestScheduleHost(fx.Archive);
host.Systems.Add(new SystemSchedule("archive-scan", "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Parse("every:10m")));
host.Systems.Add(new SystemSchedule("index-backup", "Index backup", ScheduleActions.Backup, ScheduleRecurrence.Parse("daily:03:00"), Enabled: false));
Guid id;
await using (var first = await StartAsync(fx.Db, engine, host, clock))
{
var list = await first.ListAsync(Ct);
Assert.SequenceEqual(["archive-scan", "index-backup"], list.Items.Select(s => s.SystemKey!));
var scan = list.Items[0];
id = scan.Id;
Assert.Equal(T0.AddMinutes(10), scan.NextRun);
Assert.Null(list.Items[1].NextRun);
Assert.Equal("UTC", list.TimeZone);
Assert.SequenceEqual(host.CleanupSteps, list.Steps!);
Assert.Equal("name", (await first.UpdateAsync(id, new UpdateScheduleRequest(Name: "Mine"), Ct)).Problem);
Assert.Equal("action", (await first.UpdateAsync(id, new UpdateScheduleRequest(Action: ScheduleActions.Verify), Ct)).Problem);
Assert.Null((await first.UpdateAsync(id, new UpdateScheduleRequest(Name: "Archive scan", Recurrence: new RecurrenceDto("every", Every: 30, Unit: "minutes")), Ct)).Problem);
Assert.Equal(ScheduleDeleteOutcome.System, await first.DeleteAsync(id, Ct));
}
host.Systems[0] = host.Systems[0] with { Recurrence = ScheduleRecurrence.Parse("every:5m") };
await using var second = await StartAsync(fx.Db, engine, host, clock);
Assert.Equal(new RecurrenceDto("every", Every: 30, Unit: "minutes"), (await second.GetAsync(id, Ct))!.Recurrence);
var reset = (await second.ResetAsync(id, Ct)).Schedule!;
Assert.Equal((new RecurrenceDto("every", Every: 5, Unit: "minutes"), T0.AddMinutes(5)), (reset.Recurrence, reset.NextRun!.Value));
var mine = await CreateAsync(second, ScheduleActions.Orphans);
Assert.Equal("systemKey", (await second.ResetAsync(mine.Id, Ct)).Problem);
Assert.Equal(ScheduleDeleteOutcome.Deleted, await second.DeleteAsync(mine.Id, Ct));
Assert.Equal(ScheduleDeleteOutcome.NotFound, await second.DeleteAsync(mine.Id, Ct));
Assert.True((await second.UpdateAsync(mine.Id, new UpdateScheduleRequest(Enabled: false), Ct)).NotFound);
}
[Test]
public async Task InvalidSchedulesNameTheirField()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
await using var scheduler = await StartAsync(fx.Db, engine, new TestScheduleHost(fx.Archive), new ScheduleClock(T0));
async Task<string?> Problem(CreateScheduleRequest request) => (await scheduler.CreateAsync(request, null, Ct)).Problem;
Assert.Equal("name", await Problem(new CreateScheduleRequest(" ", ScheduleActions.Scan, Every10)));
Assert.Equal("name", await Problem(new CreateScheduleRequest(new string('n', Scheduler.MaxNameLength + 1), ScheduleActions.Scan, Every10)));
Assert.Equal("action", await Problem(new CreateScheduleRequest("Rebuild", "rebuild", Every10)));
Assert.Equal("recurrence", await Problem(new CreateScheduleRequest("Fast", ScheduleActions.Scan, new RecurrenceDto("every", Every: 2, Unit: "minutes"))));
Assert.Equal("parameters.percent", await Problem(new CreateScheduleRequest("Verify", ScheduleActions.Verify, Every10, new ScheduleParametersDto(Percent: 0))));
Assert.Equal("parameters.olderThanDays", await Problem(new CreateScheduleRequest("Verify", ScheduleActions.Verify, Every10, new ScheduleParametersDto(OlderThanDays: -1))));
Assert.Equal("parameters.keep", await Problem(new CreateScheduleRequest("Backup", ScheduleActions.Backup, Every10, new ScheduleParametersDto(Keep: 0))));
Assert.Equal("parameters.steps", await Problem(new CreateScheduleRequest("Clean", ScheduleActions.Cleanup, Every10, new ScheduleParametersDto(Steps: ["shred"]))));
Assert.Equal("parameters.steps", await Problem(new CreateScheduleRequest("Clean", ScheduleActions.Cleanup, Every10, new ScheduleParametersDto(Steps: []))));
Assert.Equal("priority", await Problem(new CreateScheduleRequest("Scan", ScheduleActions.Scan, Every10, Priority: "urgent")));
Assert.Equal("target", await Problem(new CreateScheduleRequest("Scan", ScheduleActions.Scan, Every10, Target: "elsewhere")));
// Parameters are stored normalised: the action's own fields, its defaults for those left out.
var verify = (await scheduler.CreateAsync(new CreateScheduleRequest("Verify", ScheduleActions.Verify, Every10,
new ScheduleParametersDto(Percent: 25, DryRun: true, Steps: ["audit"]), Priority: "user"), null, Ct)).Schedule!;
Assert.Equal((new ScheduleParametersDto(OlderThanDays: 30, Percent: 25), "user"), (verify.Parameters, verify.Priority));
// Another action starts from its own defaults.
var changed = (await scheduler.UpdateAsync(verify.Id, new UpdateScheduleRequest(Action: ScheduleActions.Backup), Ct)).Schedule!;
Assert.Equal(new ScheduleParametersDto(Keep: 3), changed.Parameters);
}
[Test]
public async Task UnavailableActionsAndAMissingArchiveQueueNothing()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
var host = new TestScheduleHost(fx.Archive);
host.Refused[ScheduleActions.Thumbnails] = "not-here";
await using var scheduler = await StartAsync(fx.Db, engine, host, new ScheduleClock(T0));
var actions = (await scheduler.ListAsync(Ct)).Actions.ToDictionary(a => a.Name);
Assert.SequenceEqual(ScheduleActions.All, actions.Keys);
Assert.Equal(new ScheduleActionDto(ScheduleActions.Thumbnails, false, "not-here"), actions[ScheduleActions.Thumbnails]);
Assert.True(actions[ScheduleActions.Backup].Available, "an SQLite index file is backed up");
Assert.True(actions[ScheduleActions.Proxies].Available);
var thumbnails = await CreateAsync(scheduler, ScheduleActions.Thumbnails);
Assert.Equal(ScheduleOutcome.Unavailable, (await scheduler.RunNowAsync(thumbnails.Id, null, Ct))!.Outcome);
var proxies = await CreateAsync(scheduler, ScheduleActions.Proxies);
host.Archive = await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Proxies = s.Proxies with { LongEdge = ProxyPolicy.Disabled } }, Ct);
Assert.Equal(new ScheduleActionDto(ScheduleActions.Proxies, false, ScheduleUnavailable.ProxiesDisabled),
(await scheduler.ListAsync(Ct)).Actions.Single(a => a.Name == ScheduleActions.Proxies));
Assert.Equal(ScheduleOutcome.Unavailable, (await scheduler.RunNowAsync(proxies.Id, null, Ct))!.Outcome);
// No engine handler for the kind: a desktop without the archive engine, a server without the processing module.
await using var bare = new JobEngine(fx.Db, [], new JobEngineOptions { WorkerId = "bare" });
await using var other = new Scheduler(fx.Db, bare, new SchedulerOptions { Time = new ScheduleClock(T0), Tick = TimeSpan.FromHours(1) });
await other.StartAsync(new TestScheduleHost(fx.Archive), Ct);
Assert.True((await other.ListAsync(Ct)).Actions.All(a => a is { Available: false, Reason: ScheduleUnavailable.NoHandler }));
host.Archive = null;
var scan = await CreateAsync(scheduler, ScheduleActions.Scan);
Assert.Equal(ScheduleOutcome.SkippedOffline, (await scheduler.RunNowAsync(scan.Id, null, Ct))!.Outcome);
// The backup and the clean-up need no archive.
var backup = await CreateAsync(scheduler, ScheduleActions.Backup);
Assert.Equal(ScheduleOutcome.Queued, (await scheduler.RunNowAsync(backup.Id, null, Ct))!.Outcome);
var cleanup = await CreateAsync(scheduler, ScheduleActions.Cleanup);
var cleanupRun = (await scheduler.RunNowAsync(cleanup.Id, null, Ct))!;
Assert.Equal(ScheduleOutcome.Queued, cleanupRun.Outcome);
Assert.Empty((await fx.Db.Jobs.GetAsync(cleanupRun.JobId!.Value, Ct))!.TargetIds);
}
[Test]
public async Task BackupsAreUnavailableWithoutAnIndexFile()
{
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.SqliteInMemory(), Ct);
await using var engine = new JobEngine(db, new ArchiveService(db).CreateJobHandlers(), new JobEngineOptions { WorkerId = "memory" });
await using var scheduler = new Scheduler(db, engine, new SchedulerOptions { Time = new ScheduleClock(T0) });
await scheduler.StartAsync(new TestScheduleHost(null), Ct);
Assert.Equal(new ScheduleActionDto(ScheduleActions.Backup, false, ScheduleUnavailable.NoIndexFile),
(await scheduler.ListAsync(Ct)).Actions.Single(a => a.Name == ScheduleActions.Backup));
Assert.Equal(ScheduleOutcome.Unavailable,
(await scheduler.RunNowAsync((await CreateAsync(scheduler, ScheduleActions.Backup)).Id, null, Ct))!.Outcome);
Assert.Equal(ScheduleOutcome.SkippedOffline,
(await scheduler.RunNowAsync((await CreateAsync(scheduler, ScheduleActions.Duplicates)).Id, null, Ct))!.Outcome);
}
[Test]
public async Task VerifyTakesTheLeastRecentlyVerifiedShareOfTheArchive()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
var clock = new ScheduleClock(DateTimeOffset.UtcNow);
await using var scheduler = await StartAsync(fx.Db, engine, new TestScheduleHost(fx.Archive), clock);
var ids = new List<Guid>();
for (var i = 0; i < 4; i++) ids.Add(await IngestAsync(fx, "s" + i, 10 * i + 1));
await fx.Db.Sequences.RecordVerifiedAsync(ids[0], SequenceStatus.Verified, SequenceStatus.None, clock.Now.AddDays(-60), Ct);
await fx.Db.Sequences.RecordVerifiedAsync(ids[1], SequenceStatus.Verified, SequenceStatus.None, clock.Now.AddDays(-2), Ct);
var half = await CreateAsync(scheduler, ScheduleActions.Verify, parameters: new ScheduleParametersDto(OlderThanDays: 30, Percent: 50));
var job = (await fx.Db.Jobs.GetAsync((await scheduler.RunNowAsync(half.Id, null, Ct))!.JobId!.Value, Ct))!;
var never = ids.Skip(2).Order().ToList();
Assert.SequenceEqual(never, ArchiveJobJson.Read(job, ArchiveJobJson.Default.VerifyParameters, new VerifyParameters(null)).SequenceIds!.Order());
await fx.Db.Jobs.SetStateAsync(job.Id, JobState.Done, cancellationToken: Ct);
var all = await CreateAsync(scheduler, ScheduleActions.Verify, parameters: new ScheduleParametersDto(OlderThanDays: 0, Percent: 100));
var whole = (await fx.Db.Jobs.GetAsync((await scheduler.RunNowAsync(all.Id, null, Ct))!.JobId!.Value, Ct))!;
Assert.Null(ArchiveJobJson.Read(whole, ArchiveJobJson.Default.VerifyParameters, new VerifyParameters([])).SequenceIds);
await fx.Db.Jobs.SetStateAsync(whole.Id, JobState.Done, cancellationToken: Ct);
foreach (var id in ids) await fx.Db.Sequences.RecordVerifiedAsync(id, SequenceStatus.Verified, SequenceStatus.None, clock.Now.AddDays(-1), Ct);
Assert.Equal(ScheduleOutcome.SkippedNothing, (await scheduler.RunNowAsync(half.Id, null, Ct))!.Outcome);
}
[Test]
public async Task ImagePassesCoverTheSequencesWithoutThemOnce()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
await using var scheduler = await StartAsync(fx.Db, engine, new TestScheduleHost(fx.Archive), new ScheduleClock(T0));
var a = await IngestAsync(fx, "a", 1);
var b = await IngestAsync(fx, "b", 11);
await fx.Db.Sequences.UpdateStatusAsync(b, SequenceStatus.ThumbsBuilt, SequenceStatus.None, Ct);
var thumbnails = await CreateAsync(scheduler, ScheduleActions.Thumbnails);
var run = (await scheduler.RunNowAsync(thumbnails.Id, null, Ct))!;
var job = (await fx.Db.Jobs.GetAsync(run.JobId!.Value, Ct))!;
Assert.Equal((JobKind.Thumbs, ScheduleOutcome.Queued), (job.Kind, run.Outcome));
Assert.SequenceEqual([a], job.TargetIds);
// Another schedule finds that work pending.
var again = await CreateAsync(scheduler, ScheduleActions.Thumbnails);
Assert.Equal(ScheduleOutcome.SkippedPending, (await scheduler.RunNowAsync(again.Id, null, Ct))!.Outcome);
var forced = await CreateAsync(scheduler, ScheduleActions.Thumbnails, parameters: new ScheduleParametersDto(Force: true));
var forcedRun = (await scheduler.RunNowAsync(forced.Id, null, Ct))!;
Assert.Equal(ScheduleOutcome.Queued, forcedRun.Outcome);
var forcedJob = (await fx.Db.Jobs.GetAsync(forcedRun.JobId!.Value, Ct))!;
Assert.SequenceEqual([b], forcedJob.TargetIds);
var analysis = await CreateAsync(scheduler, ScheduleActions.Analysis);
var light = (await fx.Db.Jobs.GetAsync((await scheduler.RunNowAsync(analysis.Id, null, Ct))!.JobId!.Value, Ct))!;
Assert.Equal(JobKind.LightAnalyse, light.Kind);
Assert.SequenceEqual(new[] { a, b }.Order(), light.TargetIds.Order());
var deep = await CreateAsync(scheduler, ScheduleActions.Analysis, parameters: new ScheduleParametersDto(Deep: true));
var deepJob = (await fx.Db.Jobs.GetAsync((await scheduler.RunNowAsync(deep.Id, null, Ct))!.JobId!.Value, Ct))!;
Assert.Equal((JobKind.DeepAnalyse, JobPriority.Background), (deepJob.Kind, deepJob.Priority));
// Without the analysis engine (a host that registers only the archive's handlers) analysis is not available.
await using var archiveOnly = new JobEngine(fx.Db, fx.Service.CreateJobHandlers(), new JobEngineOptions { WorkerId = "archive" });
await using var other = new Scheduler(fx.Db, archiveOnly, new SchedulerOptions { Time = new ScheduleClock(T0), Tick = TimeSpan.FromHours(1) });
await other.StartAsync(new TestScheduleHost(fx.Archive), Ct);
Assert.Equal(ScheduleOutcome.Unavailable, (await other.RunNowAsync((await CreateAsync(other, ScheduleActions.Analysis)).Id, null, Ct))!.Outcome);
}
/// <summary>
/// Owner review 2, R10: both hosts scan right after they start (the desktop also when its archive is back), as their
/// polling did, through the archive scan system schedule: once, only while it is enabled, never twice for one start.
/// </summary>
[Test]
public async Task ASystemScheduleRunsNowOnceWhenEnabledAndNotRunSince()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
var clock = new ScheduleClock(T0);
var host = new TestScheduleHost(fx.Archive);
host.Systems.Add(new SystemSchedule("archive-scan", "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(10, RecurrenceUnit.Minutes), CatchUp: false));
await using var scheduler = await StartAsync(fx.Db, engine, host, clock);
Assert.Null(await scheduler.RunSystemNowAsync("no-such-key", null, Ct));
// Right after the start: the scan is queued, without waiting for its first interval.
var started = clock.Now;
var run = Assert.NotNull(await scheduler.RunSystemNowAsync("archive-scan", started, Ct));
Assert.Equal(ScheduleOutcome.Queued, run.Outcome);
var job = (await fx.Db.Jobs.GetAsync(run.JobId!.Value, Ct))!;
Assert.Equal((JobKind.Scan, JobPriority.Background, (Guid?)run.Schedule.Id), (job.Kind, job.Priority, job.ScheduleId));
Assert.Equal(T0.AddMinutes(10), run.Schedule.NextRun);
// It ran since that start: not again. Asked again later (the archive is back), its pending scan is not queued twice.
Assert.Null(await scheduler.RunSystemNowAsync("archive-scan", started, Ct));
Assert.Equal(ScheduleOutcome.SkippedPending, (await scheduler.RunSystemNowAsync("archive-scan", null, Ct))!.Outcome);
Assert.Count(1, await fx.Db.Jobs.ListByScheduleAsync(run.Schedule.Id, cancellationToken: Ct));
// Turned off, it does not run at start.
Assert.Null((await scheduler.UpdateAsync(run.Schedule.Id, new UpdateScheduleRequest(Enabled: false), Ct)).Problem);
await fx.Db.Jobs.SetStateAsync(job.Id, JobState.Done, cancellationToken: Ct);
Assert.Null(await scheduler.RunSystemNowAsync("archive-scan", null, Ct));
}
/// <summary>
/// Owner review 2, R10: a scan whose schedule leaves deep unset follows the host at every run (the desktop's Settings ›
/// Analysis › After a scan as it is then), one that sets it keeps its own choice.
/// </summary>
[Test]
public async Task AScanWithoutItsOwnDeepFollowsTheHostAtEveryRun()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
var host = new TestScheduleHost(fx.Archive);
await using var scheduler = await StartAsync(fx.Db, engine, host, new ScheduleClock(T0));
var follows = await CreateAsync(scheduler, ScheduleActions.Scan);
Assert.Null(follows.Parameters.Deep);
var own = await CreateAsync(scheduler, ScheduleActions.Scan, parameters: new ScheduleParametersDto(Deep: false));
Assert.Equal(false, own.Parameters.Deep);
async Task<bool> DeepAsync(ScheduleDto schedule)
{
var resolution = await ScheduleActions.ResolveAsync(new ScheduleActionContext(fx.Db, host, _ => true, T0), schedule.Action, schedule.Parameters, Ct);
var request = resolution.Requests.Single();
return System.Text.Json.JsonSerializer.Deserialize(request.ParametersJson!, ArchiveJobJson.Default.ScanParameters)!.DeepAnalysis;
}
Assert.False(await DeepAsync(follows));
host.DeepAnalysisAfterScan = true;
Assert.True(await DeepAsync(follows));
Assert.False(await DeepAsync(own));
// The queued job carries it too.
var job = (await fx.Db.Jobs.GetAsync((await scheduler.RunNowAsync(follows.Id, null, Ct))!.JobId!.Value, Ct))!;
Assert.True(ArchiveJobJson.Read(job, ArchiveJobJson.Default.ScanParameters, new ScanParameters(false)).DeepAnalysis);
}
/// <summary>
/// Owner review 2, R10: a system schedule that replaced a timer is seeded due when the timer's work was last done a period
/// or more before (the newest index copy a week old: the first start after the upgrade copies at once, as the daily loop
/// did); done more recently, or never, it waits for the recurrence's first occurrence. Rows that exist keep their runs.
/// </summary>
[Test]
public async Task ASystemScheduleIsSeededDueWhenItsWorkIsAPeriodOld()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
var clock = new ScheduleClock(T0);
var host = new TestScheduleHost(fx.Archive);
var daily = ScheduleRecurrence.Interval(1, RecurrenceUnit.Days);
host.Systems.Add(new SystemSchedule("index-backup", "Index backup", ScheduleActions.Backup, daily, LastDone: T0.AddDays(-7)));
host.Systems.Add(new SystemSchedule("nightly-backup", "Nightly", ScheduleActions.Backup, ScheduleRecurrence.DailyAt(new TimeOnly(3, 0)), LastDone: T0.AddHours(-23)));
host.Systems.Add(new SystemSchedule("new-backup", "New", ScheduleActions.Backup, daily));
host.Systems.Add(new SystemSchedule("off-backup", "Off", ScheduleActions.Backup, daily, Enabled: false, LastDone: T0.AddDays(-7)));
await using (var first = await StartAsync(fx.Db, engine, host, clock))
{
var due = (await fx.Db.Schedules.GetBySystemKeyAsync("index-backup", Ct))!;
Assert.Equal((ScheduleOutcome.Queued, T0, T0.AddDays(1)), (due.LastOutcome!, due.LastRun!.Value, due.NextRun!.Value));
var nightly = (await fx.Db.Schedules.GetBySystemKeyAsync("nightly-backup", Ct))!;
Assert.Equal(((string?)null, new DateTimeOffset(2026, 10, 3, 3, 0, 0, TimeSpan.Zero)), (nightly.LastOutcome, nightly.NextRun!.Value));
var fresh = (await fx.Db.Schedules.GetBySystemKeyAsync("new-backup", Ct))!;
Assert.Equal(((string?)null, T0.AddDays(1)), (fresh.LastOutcome, fresh.NextRun!.Value));
var off = (await fx.Db.Schedules.GetBySystemKeyAsync("off-backup", Ct))!;
Assert.Equal(((string?)null, (DateTimeOffset?)null), (off.LastOutcome, off.NextRun));
}
// The next start finds the rows: nothing is due again.
clock.Advance(TimeSpan.FromHours(1));
await using var second = await StartAsync(fx.Db, engine, host, clock);
Assert.Count(1, (await fx.Db.Jobs.ListAsync(cancellationToken: Ct)).Items);
}
/// <summary>The loop itself (no pass by hand): its tick fires a due schedule.</summary>
[Test]
public async Task TheLoopFiresADueScheduleAtItsTick()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
var clock = new ScheduleClock(T0);
await using var scheduler = new Scheduler(fx.Db, engine, new SchedulerOptions { Time = clock, Tick = TimeSpan.FromMilliseconds(100) });
await scheduler.StartAsync(new TestScheduleHost(fx.Archive), Ct);
var changes = Changes(scheduler);
var schedule = await CreateAsync(scheduler, ScheduleActions.Scan);
clock.Advance(TimeSpan.FromMinutes(10));
var ran = await RanAsync(changes, schedule.Id, null);
Assert.Equal((ScheduleOutcome.Queued, T0.AddMinutes(20)), (ran.LastOutcome!, ran.NextRun!.Value));
Assert.Count(1, await fx.Db.Jobs.ListByScheduleAsync(schedule.Id, cancellationToken: Ct));
}
/// <summary><see cref="Scheduler.Wake"/> makes the loop look now, long before its tick.</summary>
[Test]
public async Task WakeFiresADueScheduleBeforeTheTick()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
var clock = new ScheduleClock(T0);
await using var scheduler = await StartAsync(fx.Db, engine, new TestScheduleHost(fx.Archive), clock);
var changes = Changes(scheduler);
var schedule = await CreateAsync(scheduler, ScheduleActions.Scan);
clock.Advance(TimeSpan.FromMinutes(10));
await Task.Delay(200, Ct);
Assert.Null((await scheduler.GetAsync(schedule.Id, Ct))!.LastOutcome, "the tick is an hour away");
scheduler.Wake();
Assert.Equal(ScheduleOutcome.Queued, (await RanAsync(changes, schedule.Id, null)).LastOutcome);
}
/// <summary>Nothing a pass throws (here a subscriber of <see cref="Scheduler.ScheduleChanged"/>) ends the loop: the next run still fires.</summary>
[Test]
public async Task TheLoopSurvivesAPassThatThrew()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
var clock = new ScheduleClock(T0);
await using var scheduler = await StartAsync(fx.Db, engine, new TestScheduleHost(fx.Archive), clock);
var changes = Changes(scheduler);
var thrown = 0;
scheduler.ScheduleChanged += dto =>
{
if (dto.LastOutcome is not null && Interlocked.Exchange(ref thrown, 1) == 0) throw new InvalidOperationException("A subscriber failed");
};
var schedule = await CreateAsync(scheduler, ScheduleActions.Duplicates);
clock.Advance(TimeSpan.FromMinutes(10));
scheduler.Wake();
var first = await RanAsync(changes, schedule.Id, null);
Assert.Equal(1, Volatile.Read(ref thrown));
await fx.Db.Jobs.SetStateAsync(first.LastJobId!.Value, JobState.Done, cancellationToken: Ct);
clock.Advance(TimeSpan.FromMinutes(10));
scheduler.Wake();
var second = await RanAsync(changes, schedule.Id, first.LastJobId);
Assert.Equal((ScheduleOutcome.Queued, T0.AddMinutes(20)), (second.LastOutcome!, second.LastRun!.Value));
Assert.Count(2, await fx.Db.Jobs.ListByScheduleAsync(schedule.Id, cancellationToken: Ct));
}
/// <summary>
/// Disposing stops the loop during a pass: it waits for a host call that does not watch its token, so the database is
/// never used after it returns, and cancels one that does.
/// </summary>
[Test]
public async Task DisposeDuringAPassWaitsForItAndStopsIt()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
var clock = new ScheduleClock(T0);
var host = new TestScheduleHost(fx.Archive);
var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var scheduler = await StartAsync(fx.Db, engine, host, clock);
var disposed = false;
try
{
await CreateAsync(scheduler, ScheduleActions.Scan);
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
host.BeforeArchive = async _ =>
{
entered.TrySetResult();
await gate.Task;
};
clock.Advance(TimeSpan.FromMinutes(10));
scheduler.Wake();
await entered.Task.WaitAsync(Budget, Ct);
var disposing = scheduler.DisposeAsync().AsTask();
disposed = true;
await Task.Delay(200, Ct);
Assert.False(disposing.IsCompleted, "disposed while a pass was still running");
gate.SetResult();
await disposing.WaitAsync(Budget, Ct);
}
finally
{
gate.TrySetResult();
if (!disposed) await scheduler.DisposeAsync();
}
// A host call that watches the token ends with it.
var again = await StartAsync(fx.Db, engine, host, clock);
var waiting = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
host.BeforeArchive = async ct =>
{
waiting.TrySetResult();
await Task.Delay(Timeout.Infinite, ct);
};
clock.Advance(TimeSpan.FromMinutes(10));
again.Wake();
await waiting.Task.WaitAsync(Budget, Ct);
await again.DisposeAsync().AsTask().WaitAsync(Budget, Ct);
}
private static TimeSpan Budget => TimeSpan.FromSeconds(TestTiming.Budget(10));
/// <summary>Every <see cref="Scheduler.ScheduleChanged"/> from now on.</summary>
private static Channel<ScheduleDto> Changes(Scheduler scheduler)
{
var changes = Channel.CreateUnbounded<ScheduleDto>();
scheduler.ScheduleChanged += dto => changes.Writer.TryWrite(dto);
return changes;
}
/// <summary>The first change of <paramref name="id"/> that records a run whose job is not <paramref name="previousJob"/>.</summary>
private async Task<ScheduleDto> RanAsync(Channel<ScheduleDto> changes, Guid id, Guid? previousJob)
{
while (true)
{
var dto = await changes.Reader.ReadAsync(Ct).AsTask().WaitAsync(Budget, Ct);
if (dto.Id == id && dto.LastOutcome is not null && dto.LastJobId != previousJob) return dto;
}
}
private static async Task<Guid> IngestAsync(ArchiveFixture fx, string key, int seed)
{
var staged = fx.Stage(ArchiveFixture.Start.AddMinutes(seed), seed);
return (await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, null, null, key, staged.Path, "IMG_0001.JPG",
staged.Size, staged.Sha256, null, null), fx.Ct)).SequenceId;
}
}
@@ -1,25 +1,20 @@
using Chronos.Core.Model;
using Chronos.Data.Repositories;
using Chronos.Data.Scheduling;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Sqlite;
/// <summary>
/// BRIEF §6.2: a VACUUM INTO copy of the SQLite index once a day, the newest three kept, and a restore from Settings ›
/// Advanced that waits for the next start, runs before the index opens (so it recovers one that no longer opens), checks
/// the copy first (quick_check included) and never replaces a working index with a broken one.
/// BRIEF §6.2: VACUUM INTO copies of the SQLite index (the index backup schedule's, Back up now's, the one kept before a
/// restore), as many kept as the backup schedules keep, and a restore from Settings › Advanced that waits for the next
/// start, runs before the index opens (so it recovers one that no longer opens), checks the copy first (quick_check
/// included) and never replaces a working index with a broken one.
/// </summary>
[Category("sqlite")]
public sealed class DatabaseBackupsTests(TestContext context)
{
/// <summary>A clock the test moves; timers created on it never fire by themselves.</summary>
private sealed class ManualClock(DateTimeOffset now) : TimeProvider
{
public DateTimeOffset Now { get; set; } = now;
public override DateTimeOffset GetUtcNow() => Now;
}
private async Task<(ChronosDatabase Db, string Path)> OpenAsync(string name = "chronos.db")
{
var path = System.IO.Path.Combine(context.CreateTempDirectory("db"), name);
@@ -49,42 +44,55 @@ public sealed class DatabaseBackupsTests(TestContext context)
}
[Test]
public void ACopyIsDueWhenTheNewestIsADayOld()
public async Task TheNewestCopyIsWhatTheIndexBackupIsSeededWith()
{
var now = new DateTimeOffset(2026, 10, 12, 9, 0, 0, TimeSpan.Zero);
Assert.True(DatabaseBackups.IsDue([], now));
Assert.False(DatabaseBackups.IsDue([new DatabaseBackup("b", now.AddHours(-23), 1)], now));
Assert.True(DatabaseBackups.IsDue([new DatabaseBackup("b", now.AddHours(-24), 1)], now));
}
[Test]
public async Task TheDailyCopyIsMadeAtStartOnlyWhenDue()
{
var (db, _) = await OpenAsync();
var (db, path) = await OpenAsync();
await using var _ = db;
var directory = context.CreateTempDirectory("backups");
var clock = new ManualClock(DateTimeOffset.UtcNow);
Assert.Null(DatabaseBackups.Newest(db, directory));
File.WriteAllText(Path.Combine(directory, "chronos-20261010-030000-000.db"), "a");
File.WriteAllText(Path.Combine(directory, "chronos-20261012-030000-000.db"), "b");
File.WriteAllText(Path.Combine(directory, "other-20261013-030000-000.db"), "x");
Assert.Equal(new DateTimeOffset(2026, 10, 12, 3, 0, 0, TimeSpan.Zero), DatabaseBackups.Newest(db, directory));
// Without a folder of its own, the one next to the index.
Assert.Null(DatabaseBackups.Newest(db, null));
await db.BackupAsync(DatabaseBackups.DefaultDirectory(path), DatabaseBackups.Keep, context.Cancellation);
Assert.NotNull(DatabaseBackups.Newest(db, null));
await using var memory = await ChronosDatabase.OpenAsync(DatabaseOptions.SqliteInMemory(), context.Cancellation);
Assert.Null(DatabaseBackups.Newest(memory, directory));
}
// No copy yet: one is made at once, then the loop waits for its hourly check until stopped.
using (var stop = new CancellationTokenSource())
{
var loop = DatabaseBackups.RunDailyAsync(db, directory, clock, stop.Token);
var until = DateTime.UtcNow.AddSeconds(20);
while (Directory.GetFiles(directory, "*.db").Length == 0 && DateTime.UtcNow < until) await Task.Delay(20);
await stop.CancelAsync();
await loop.WaitAsync(TimeSpan.FromSeconds(20));
}
Assert.Count(1, Directory.GetFiles(directory, "*.db"));
/// <summary>
/// One folder, one retention (owner review 2, R10): Back up now and the copy kept before a restore keep as many copies
/// as the backup schedules keep (the largest Copies kept, enabled or not), not a fixed three.
/// </summary>
[Test]
public async Task EveryCopyKeepsAsManyAsTheBackupSchedulesKeep()
{
var (db, path) = await OpenAsync();
var directory = context.CreateTempDirectory("backups");
Assert.Equal(DatabaseBackups.Keep, await DatabaseBackups.KeptAsync(db, context.Cancellation));
await db.Schedules.EnsureSystemAsync(
[
new SystemSchedule(DatabaseBackups.ScheduleKey, "Index backup", ScheduleActions.Backup, ScheduleRecurrence.Parse("every:1d"), new ScheduleParametersDto(Keep: 5)),
new SystemSchedule("other-backup", "Other backup", ScheduleActions.Backup, ScheduleRecurrence.Parse("every:1d"), new ScheduleParametersDto(Keep: 1), Enabled: false),
new SystemSchedule("cleanup", "Clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.Parse("daily:04:00"), new ScheduleParametersDto(Steps: ["audit"], OlderThanDays: 30)),
], DateTimeOffset.UtcNow, context.Cancellation);
Assert.Equal(5, await DatabaseBackups.KeptAsync(db, context.Cancellation));
// A fresh copy exists: starting again makes none.
using (var stop = new CancellationTokenSource())
{
var loop = DatabaseBackups.RunDailyAsync(db, directory, clock, stop.Token);
await Task.Delay(300);
await stop.CancelAsync();
await loop.WaitAsync(TimeSpan.FromSeconds(20));
}
Assert.Count(1, Directory.GetFiles(directory, "*.db"));
// Five copies of the schedule, then Back up now: the four newest stay with the new one.
for (var i = 0; i < 5; i++) await db.BackupAsync(directory, 5, context.Cancellation);
var scheduled = DatabaseBackups.List(directory, path).Select(b => b.Path).ToList();
var manual = await db.BackupAsync(directory, await DatabaseBackups.KeptAsync(db, context.Cancellation), context.Cancellation);
Assert.SequenceEqual([manual, .. scheduled.Take(4)], DatabaseBackups.List(directory, path).Select(b => b.Path));
// The copy of the index a restore replaces prunes the same way.
await DatabaseBackups.StageRestoreAsync(scheduled[0], path, context.Cancellation);
await db.DisposeAsync();
Assert.True(await DatabaseBackups.RestoreStagedAsync(path, directory, context.Cancellation));
var after = DatabaseBackups.List(directory, path).Select(b => b.Path).ToList();
Assert.Count(5, after);
Assert.SequenceEqual([manual, .. scheduled.Take(3)], after.Skip(1));
}
[Test]
@@ -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);