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

@@ -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]