CI / Build and test (pull_request) Successful in 8m52s
CI / PostgreSQL 16 integration (pull_request) Successful in 9m21s
CI / Docker image (pull_request) Successful in 1m48s
CI / YAML check (pull_request) Successful in 7s
CI / Windows tests and installer (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Successful in 8m59s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
209 lines
12 KiB
C#
209 lines
12 KiB
C#
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(4, (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; the workspace clean-up, with catch-up too, runs once as well).
|
||
fx.Clock.Advance(TimeSpan.FromDays(2.5));
|
||
Assert.Equal(3, 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);
|
||
}
|
||
|
||
/// <summary>Phase 5c: the workspace's clean-up is a system schedule of its own, seeded once, daily at 04:30 with catch-up.</summary>
|
||
[Test]
|
||
public async Task TheWorkspaceCleanUpIsSeededOnceAsASystemSchedule()
|
||
{
|
||
await using var fx = await ScheduleFixture.CreateAsync(context);
|
||
await fx.StartAsync();
|
||
var cleanup = Assert.NotNull(await fx.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.WorkspaceCleanup));
|
||
Assert.Equal(("daily:04:30", true, ScheduleActions.Cleanup, true), (cleanup.Recurrence, cleanup.CatchUp, cleanup.Action, cleanup.Enabled));
|
||
var parameters = ScheduleMapping.Parameters(cleanup);
|
||
Assert.SequenceEqual([WorkspaceCleanStep.StepName, WorkspaceTrashStep.StepName], parameters.Steps!);
|
||
Assert.Equal(0, parameters.OlderThanDays);
|
||
Assert.Equal(("Workspace media", "Workspace trash"), (ScheduleText.Step(WorkspaceCleanStep.StepName), ScheduleText.Step(WorkspaceTrashStep.StepName)));
|
||
|
||
await fx.StartAsync();
|
||
Assert.Count(1, (await fx.Db.Schedules.ListAsync()).Where(s => s.SystemKey == DesktopScheduleHost.WorkspaceCleanup));
|
||
}
|
||
|
||
[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);
|
||
}
|
||
}
|