Files
Chronos/tests/Chronos.App.Tests/Jobs/DesktopScheduleHostTests.cs
T
Alby96 bc786c12c4 feat(app): Jobs › Scheduled and the desktop scheduler
Owner review 2, R10 on the desktop: every timer that queued work out of
sight is now a visible, editable schedule of this PC.

- DesktopScheduleHost implements IScheduleHost: the PC's time zone, the
  archive at Settings › Archive's folder (refreshed from archive.json,
  none while it is offline), and three system schedules: archive-scan
  (every:<ScanIntervalMinutes>m, seeded once from the old setting, no
  catch-up), index-backup (every day with catch-up, replacing
  DatabaseBackups.RunDailyAsync) and housekeeping (daily 04:00 with
  catch-up: job history 90 days and the new cache-trim step).
- AppServices starts the Scheduler after the engine, once the archive was
  reopened; an unplugged archive is looked for every minute and the
  scheduler woken when it is back. The rescan loop and the daily backup
  loop are gone; ApplyJobSettings wakes the scheduler.
- CacheStore.Trim brings the cache to Settings › Storage › Cache limit,
  oldest files first, skipping files in use and the proxies, render-node
  and server-import folders; CacheTrimStep runs it as a clean-up step.
- Jobs gets a Queue | Scheduled segmented control. Scheduled lists the
  schedules (switch, name, action, when, next run, last result) with Run
  now, Edit, Reset (system) or Delete (user's, confirmed), the selected
  schedule's last runs with Show in queue, and an in-window editor that
  checks every field with the scheduler's limits. Jobs a schedule queued
  carry a "Scheduled" pill; the history line follows the housekeeping's
  job-history days.
- JobNotices: a scheduled background run raises a toast only when it
  fails (upkeep stays silent).
- Settings › Archive › Rescan every is removed; ScanIntervalMinutes stays
  only as the seed. Strings in en and it; the others are retranslated.
- The capture shows jobs-scheduled and jobs-schedule-editor on a stopped
  scheduler clock with sample schedules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit e25d812feb3f417cb9251c748c29e8035fd9b03c)
2026-10-27 02:26:07 +01:00

120 lines
6.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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));
Assert.Equal(true, ScheduleMapping.Parameters(scan).Deep);
Assert.Equal(fx.Clock.Now.AddMinutes(30), scan.NextRun);
// The user edits the schedule in Jobs › Scheduled; the old setting changes (or never changes again): the next
// start keeps the schedule as it is.
Assert.Null((await scheduler.UpdateAsync(scan.Id, new UpdateScheduleRequest(Recurrence: new("every", Every: 2, Unit: "hours")))).Problem);
settings.ScanIntervalMinutes = 5;
await fx.StartAsync();
var kept = Assert.NotNull(await fx.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan));
Assert.Equal((scan.Id, "every:2h"), (kept.Id, kept.Recurrence));
Assert.Count(3, (await fx.Db.Schedules.ListAsync()).Where(s => s.IsSystem));
// Reset goes back to what the host seeds with.
Assert.Null((await fx.Scheduler!.ResetAsync(scan.Id)).Problem);
Assert.Equal("every:5m", (await fx.Db.Schedules.GetAsync(scan.Id))!.Recurrence);
}
[Test]
public void TheFormerIntervalIsClampedToWhatAnIntervalAccepts()
{
Assert.Equal(ScheduleRecurrence.MinMinutes, DesktopScheduleHost.ScanMinutes(new AppSettings { ScanIntervalMinutes = 1 }));
Assert.Equal(AppSettings.DefaultScanIntervalMinutes, DesktopScheduleHost.ScanMinutes(new AppSettings()));
Assert.Equal(ScheduleRecurrence.MaxMinutes, DesktopScheduleHost.ScanMinutes(new AppSettings { ScanIntervalMinutes = 100_000 }));
}
[Test]
public async Task TheBackupScheduleReplacesTheDailyBackupLoop()
{
await using var fx = await ScheduleFixture.CreateAsync(context);
var scheduler = await fx.StartAsync();
var backup = Assert.NotNull(await fx.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.IndexBackup));
Assert.Equal(("every:1d", true, JobPriority.Background, ScheduleActions.Backup), (backup.Recurrence, backup.CatchUp, backup.Priority, backup.Action));
Assert.Equal(DatabaseBackups.Keep, ScheduleMapping.Parameters(backup).Keep);
Assert.Equal(fx.Clock.Now.AddDays(1), backup.NextRun);
// Chronos was closed for two days: the missed copy is made once at start (catch-up, as the housekeeping's run; the
// scan has none and just moves on).
fx.Clock.Advance(TimeSpan.FromDays(2.5));
Assert.Equal(2, await scheduler.RunDueAsync());
var job = (await fx.Db.Jobs.ListByScheduleAsync(backup.Id)).Single();
Assert.Equal((JobKind.Backup, JobPriority.Background, JobState.Queued), (job.Kind, job.Priority, job.State));
Assert.Equal(0, await scheduler.RunDueAsync());
// The engine makes the copy in the backups folder next to the index, as the loop did.
await fx.Engine.StartAsync();
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while ((await fx.Db.Jobs.GetAsync(job.Id))!.State is JobState.Queued or JobState.Running)
{
Assert.True(DateTime.UtcNow < until, "the backup job did not finish");
await Task.Delay(50);
}
Assert.Equal(JobState.Done, (await fx.Db.Jobs.GetAsync(job.Id))!.State);
Assert.Count(1, DatabaseBackups.List(fx.Backups, fx.DatabasePath));
}
[Test]
public async Task TheHousekeepingRemovesOldHistoryAndTrimsTheCache()
{
await using var fx = await ScheduleFixture.CreateAsync(context);
await fx.StartAsync();
var housekeeping = Assert.NotNull(await fx.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.Housekeeping));
Assert.Equal(("daily:04:00", true, ScheduleActions.Cleanup), (housekeeping.Recurrence, housekeeping.CatchUp, housekeeping.Action));
var parameters = ScheduleMapping.Parameters(housekeeping);
Assert.SequenceEqual([CleanupSteps.JobHistory, CacheTrimStep.StepName], parameters.Steps!);
Assert.Equal(CleanupSteps.DefaultHistoryDays, parameters.OlderThanDays);
// The host's step is one the clean-up jobs run, after the shared ones.
Assert.SequenceEqual([CleanupSteps.JobHistory, CleanupSteps.Audit, CleanupSteps.TrashReport, CacheTrimStep.StepName], fx.Host.CleanupSteps);
Assert.Equal(ScheduleRecurrence.DailyAt(new TimeOnly(4, 0)).Next(fx.Clock.Now, TimeZoneInfo.Utc), housekeeping.NextRun);
}
[Test]
public async Task SchedulesWorkOnTheArchiveAtTheFolderWhileItIsOnline()
{
await using var fx = await ScheduleFixture.CreateAsync(context);
Assert.Null(await fx.Host.GetArchiveAsync(context.Cancellation));
var first = await fx.Archives.CreateAsync(Path.Combine(fx.Folder, "first"), "first");
var other = await fx.Archives.CreateAsync(Path.Combine(fx.Folder, "other"), "other");
// No folder chosen: the first archive of the index; then the one at the folder.
Assert.Equal(first.Id, (await fx.Host.GetArchiveAsync(context.Cancellation))?.Id);
fx.Settings.LastArchivePath = other.RootPath;
Assert.Equal(other.Id, (await fx.Host.GetArchiveAsync(context.Cancellation))?.Id);
// Unplugged: none, so the runs that need it are skipped (and the scheduler logs it) until it is back.
var moved = other.RootPath + "-away";
Directory.Move(other.RootPath, moved);
Assert.Null(await fx.Host.GetArchiveAsync(context.Cancellation));
Directory.Move(moved, other.RootPath);
Assert.Equal(other.Id, (await fx.Host.GetArchiveAsync(context.Cancellation))?.Id);
}
}