Files
Alby96andClaude Opus 5.5 af9eeaab9b
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
feat: owner review 2 phase 2: scheduled jobs and log settings (#10)
- 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>
2026-10-27 11:19:26 +01:00

208 lines
10 KiB
C#
Raw Permalink 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.App.Tests.Uploader;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Scheduling;
using Chronos.Testing;
namespace Chronos.App.Tests.Infrastructure;
public sealed class AppServicesTests
{
/// <summary>Dialogs that answer like a user who cancels everything.</summary>
private sealed class NoDialogs : IAppDialogs
{
public string? PickFolder(string title, string? initialFolder = null) => null;
public string? PickJsonFile(string title) => null;
public bool Confirm(ConfirmRequest request) => false;
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
}
[Test]
[WindowsOnly]
public void ExitStopsTheSchedulesAndTheEngineWhileTheUiThreadWaits()
{
var environment = AppEnvironment.ForCapture();
try
{
SingleThreadedContext.Run(async () =>
{
var root = Path.Combine(environment.DataDirectory, "archive");
await using (var setup = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(environment.DataDirectory, "setup.db"))))
await new ArchiveService(setup).CreateAsync(root, "Exit");
var services = new AppServices(environment, new AppSettings { Language = "en", LastArchivePath = root }, () => { }, new NoDialogs());
await services.OpenAsync(environment.DatabasePath);
// The archive was reopened, then the schedules started (owner review 2, R10) and its scan schedule ran at once,
// as the rescans did at start: a scan of it is queued without waiting for the interval.
Assert.True(await services.SchedulerReady, "the schedules started");
var scan = Assert.NotNull(await services.Database!.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan));
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while (!(await services.Database!.Jobs.ListAsync(null, JobKind.Scan)).Items.Any(j => j.ScheduleId == scan.Id))
{
Assert.True(DateTime.UtcNow < until, "no scan at start");
await Task.Delay(50);
}
// App.OnExit blocks the UI thread until the services stop: nothing they await may continue on it.
Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10)), "services stopped");
});
}
finally
{
environment.DeleteCaptureData();
}
}
/// <summary>
/// BRIEF §7, owner review 2 R10: the scheduled scans follow the archive folder, also one chosen after the start (first
/// run, Settings, relink).
/// </summary>
[Test]
[WindowsOnly]
public void ScheduledScansFollowTheArchiveFolderChosenAfterTheStart()
{
var environment = AppEnvironment.ForCapture();
try
{
SingleThreadedContext.Run(async () =>
{
// The first run: the index opens before any archive folder is set.
var settings = new AppSettings { Language = "en" };
var services = new AppServices(environment, settings, () => { }, new NoDialogs());
try
{
await services.OpenAsync(environment.DatabasePath);
Assert.True(await services.SchedulerReady, "the schedules started");
Assert.Null(await services.ScheduleHost.GetArchiveAsync(default));
// The scans run all the same, on the schedule seeded from the former Settings › Archive › Rescan every.
var scan = Assert.NotNull(await services.Database!.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan));
Assert.Equal("every:10m", scan.Recurrence);
Assert.Equal(ScheduleOutcome.SkippedOffline, (await services.Scheduler!.RunNowAsync(scan.Id, null))?.Outcome);
// The first-run dialog creates an archive: the schedules work on it.
var firstRoot = Path.Combine(environment.DataDirectory, "first");
await services.ArchiveSetup.CreateAsync(firstRoot);
var first = Assert.NotNull(await services.ScheduleHost.GetArchiveAsync(default));
Assert.Equal("first", first.Name);
// Settings › Archive moves to another archive, which the index lists after the first one: the next scheduled
// scan is of the archive at the folder, no longer of the first one.
var other = Path.Combine(environment.DataDirectory, "zeta");
await new ArchiveService(services.Database!).CreateAsync(other, "zeta");
Assert.Equal("first", (await services.Database!.Archives.ListAsync())[0].Name);
async Task<int> ScansOfAsync(Guid archiveId) =>
(await services.Database!.Jobs.ListAsync(null, JobKind.Scan)).Items.Count(j => j.TargetIds.Contains(archiveId));
var scansOfFirst = await ScansOfAsync(first.Id);
settings.LastArchivePath = other;
services.SaveSettings();
var rescanned = Assert.NotNull(await services.ScheduleHost.GetArchiveAsync(default));
Assert.Equal("zeta", rescanned.Name);
Assert.Equal(ScheduleOutcome.Queued, (await services.Scheduler.RunNowAsync(scan.Id, null))?.Outcome);
Assert.True(await ScansOfAsync(rescanned.Id) > 0, "the archive at the folder is rescanned");
Assert.Equal(scansOfFirst, await ScansOfAsync(first.Id));
// And back: the folder decides, whatever the order of the index.
settings.LastArchivePath = firstRoot;
services.SaveSettings();
Assert.Equal(first.Id, (await services.ScheduleHost.GetArchiveAsync(default))?.Id);
}
finally
{
Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10)), "services stopped");
}
});
}
finally
{
environment.DeleteCaptureData();
}
}
/// <summary>
/// Owner review 2, R10: when the index does not open, the schedules are known not to run at once, so Jobs › Scheduled
/// says so instead of waiting for them with an empty tab.
/// </summary>
[Test]
[WindowsOnly]
public void AnIndexThatDoesNotOpenTellsTheScheduledTabTheSchedulesDoNotRun()
{
var environment = AppEnvironment.ForCapture();
try
{
SingleThreadedContext.Run(async () =>
{
// "File is not a database", and no staged restore to recover it.
Directory.CreateDirectory(Path.GetDirectoryName(environment.DatabasePath)!);
await File.WriteAllBytesAsync(environment.DatabasePath, [.. Enumerable.Repeat((byte)0x5A, 8192)]);
var services = new AppServices(environment, new AppSettings { Language = "en" }, () => { }, new NoDialogs());
try
{
await services.OpenAsync(environment.DatabasePath);
Assert.NotNull(services.OpenError);
var ready = services.SchedulerReady;
Assert.Same(ready, await Task.WhenAny(ready, Task.Delay(TimeSpan.FromSeconds(TestTiming.Budget(10)))));
Assert.False(await ready, "no schedules without an index");
using var schedules = new SchedulesViewModel(() => services.Scheduler, () => services.Database, _ => false, (_, _, _) => { }, _ => Task.CompletedTask);
await schedules.AttachAsync(services.SchedulerReady);
Assert.True(schedules.IsLoaded && schedules.IsUnavailable && !schedules.IsRunning, "the tab shows that the schedules do not run");
}
finally
{
Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10)), "services stopped");
}
});
}
finally
{
environment.DeleteCaptureData();
}
}
/// <summary>BRIEF §6.2: a restore staged in Settings › Advanced recovers an index that no longer opens.</summary>
[Test]
[WindowsOnly]
public void AStagedRestoreRecoversAnIndexThatNoLongerOpens()
{
var environment = AppEnvironment.ForCapture();
try
{
SingleThreadedContext.Run(async () =>
{
await using (var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(environment.DatabasePath)))
{
await db.Archives.UpsertAsync(new Archive { Id = Guid.CreateVersion7(), Name = "Kept", RootPath = @"C:\Kept", Created = DateTimeOffset.UtcNow });
var backup = await db.BackupAsync(environment.BackupDirectory, DatabaseBackups.Keep);
await DatabaseBackups.StageRestoreAsync(backup, environment.DatabasePath);
}
// The index is damaged beyond opening ("file is not a database").
File.Delete(environment.DatabasePath + "-wal");
File.Delete(environment.DatabasePath + "-shm");
await File.WriteAllBytesAsync(environment.DatabasePath, [.. Enumerable.Repeat((byte)0x5A, 8192)]);
var services = new AppServices(environment, new AppSettings { Language = "en" }, () => { }, new NoDialogs());
try
{
await services.OpenAsync(environment.DatabasePath);
Assert.Null(services.OpenError);
Assert.Equal(StagedRestoreResult.Restored, services.StagedRestore);
Assert.SequenceEqual(["Kept"], (await services.Database!.Archives.ListAsync()).Select(a => a.Name));
Assert.False(DatabaseBackups.HasStagedRestore(environment.DatabasePath));
}
finally
{
Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10)), "services stopped");
}
});
}
finally
{
environment.DeleteCaptureData();
}
}
}