fix(server): archive.json on its own timer, a live Scheduled tab in one time zone, schedule audit in words
- SchedulerHost reads archive.json every 10 minutes on its own timer. The archive-scan runs that used to do it are skipped while a long scan is pending, and the schedule may be off or daily, so uploads kept a desktop's old folder template or proxy size. - Every schedule change and run, a skipped run included, is published as a scheduleChanged event. The Scheduled tab reloads on it, so skipped runs, next-run moves and other administrators' edits show without waiting for a job. - The Scheduled tab still draws when the schedule a job links to, or an expanded one, no longer exists: its runs are dropped instead of failing the whole load. - Every time on the Scheduled tab (next run, last result, runs) is in the server's time zone, as its "Times in" line says. - Audit details name a system schedule after its key (system:<key> · name · ...). The dashboard and the Logs page show it by its localized name and the recurrence code in words, as the Scheduled tab does. Older entries keep their recorded name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit c20f573d0bdf1cdcf3a86e9702ac76a4bf9508d9)
This commit is contained in:
1 parent
e384564784
commit
3f0e6357b1
10 files changed
+339
-43
No files matched your search
@@ -128,6 +128,89 @@ public sealed class ManualTimeProvider : TimeProvider
|
||||
public void Advance(TimeSpan by) => Interlocked.Add(ref _ticks, by.Ticks);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A clock tests move by hand whose timers (<see cref="PeriodicTimer"/>, <c>Task.Delay</c>, timed cancellation) fire only
|
||||
/// when <see cref="Advance"/> reaches them, never in real time: the loops paced by it run exactly when a test says.
|
||||
/// </summary>
|
||||
public sealed class SteppedTimeProvider : TimeProvider
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<SteppedTimer> _timers = [];
|
||||
private DateTimeOffset _now = DateTimeOffset.UtcNow;
|
||||
|
||||
public override DateTimeOffset GetUtcNow()
|
||||
{
|
||||
lock (_gate) return _now;
|
||||
}
|
||||
|
||||
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
|
||||
{
|
||||
var timer = new SteppedTimer(this, callback, state);
|
||||
timer.Change(dueTime, period);
|
||||
return timer;
|
||||
}
|
||||
|
||||
/// <summary>Moves the clock on, then fires each timer due by then once (a periodic one moves to its next period after now).</summary>
|
||||
public void Advance(TimeSpan by)
|
||||
{
|
||||
List<SteppedTimer> due;
|
||||
lock (_gate)
|
||||
{
|
||||
_now += by;
|
||||
due = [.. _timers.Where(t => t.Due <= _now)];
|
||||
foreach (var timer in due)
|
||||
{
|
||||
if (timer.Period <= TimeSpan.Zero) _timers.Remove(timer);
|
||||
else
|
||||
{
|
||||
while (timer.Due <= _now) timer.Due += timer.Period;
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (var timer in due) timer.Fire();
|
||||
}
|
||||
|
||||
private void Schedule(SteppedTimer timer, TimeSpan dueTime, TimeSpan period)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_timers.Remove(timer);
|
||||
if (dueTime == Timeout.InfiniteTimeSpan) return;
|
||||
timer.Due = _now + dueTime;
|
||||
timer.Period = period == Timeout.InfiniteTimeSpan ? TimeSpan.Zero : period;
|
||||
_timers.Add(timer);
|
||||
}
|
||||
}
|
||||
|
||||
private void Remove(SteppedTimer timer)
|
||||
{
|
||||
lock (_gate) _timers.Remove(timer);
|
||||
}
|
||||
|
||||
private sealed class SteppedTimer(SteppedTimeProvider clock, TimerCallback callback, object? state) : ITimer
|
||||
{
|
||||
public DateTimeOffset Due { get; set; }
|
||||
|
||||
public TimeSpan Period { get; set; }
|
||||
|
||||
public bool Change(TimeSpan dueTime, TimeSpan period)
|
||||
{
|
||||
clock.Schedule(this, dueTime, period);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Fire() => callback(state);
|
||||
|
||||
public void Dispose() => clock.Remove(this);
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
Dispose();
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A job handler that reports progress and then waits until <see cref="Release"/> (or cancellation), so tests can
|
||||
/// observe running, paused and cancelled states.
|
||||
|
||||
@@ -4,12 +4,14 @@ using System.Text.Json;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Events;
|
||||
using Chronos.Server.Jobs;
|
||||
using Chronos.Server.Storage;
|
||||
using Chronos.Testing;
|
||||
@@ -191,9 +193,83 @@ public sealed class ScheduleEndpointTests(TestContext context)
|
||||
using (var notSystem = await admin.PostAsync($"/api/v1/schedules/{custom.Id}/reset", null))
|
||||
await notSystem.ExpectErrorAsync(HttpStatusCode.Conflict, "schedule_no_defaults");
|
||||
using (var unknown = await admin.PostAsync($"/api/v1/schedules/{Guid.CreateVersion7()}/reset", null)) await unknown.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
|
||||
Assert.Equal("queued", (await RunAsync(admin, housekeeping.Id)).Outcome);
|
||||
|
||||
using var audit = await admin.GetAsync("/api/v1/audit?action=schedule_reset");
|
||||
Assert.Equal(housekeeping.Id.ToString(), (await audit.ReadAsync(ProtocolJson.Default.PageAuditEntryDto)).Items.Single().TargetId);
|
||||
// A system schedule is audited after its key, so the admin panel names it in its language, as its Scheduled tab does.
|
||||
using var audit = await admin.GetAsync("/api/v1/audit?action=schedule_updated,schedule_reset,schedule_run");
|
||||
var entries = (await audit.ReadAsync(ProtocolJson.Default.PageAuditEntryDto)).Items;
|
||||
Assert.SequenceEqual(["schedule_run", "schedule_reset", "schedule_updated"], entries.Select(e => e.Action));
|
||||
Assert.True(entries.All(e => e.TargetId == housekeeping.Id.ToString()), "the target is the schedule");
|
||||
Assert.SequenceEqual(["system:housekeeping · Housekeeping · queued", "system:housekeeping · Housekeeping · cleanup · daily:04:00",
|
||||
"system:housekeeping · Housekeeping · cleanup · weekly:sun@05:15 · off"], entries.Select(e => e.Details));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every change and run of a schedule goes out on the event socket, also a run that queues no job, so the admin panel's
|
||||
/// Scheduled tab follows what the scheduler does.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public async Task ScheduleChangesAndRunsAreEvents()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var admin = await server.AdminAsync();
|
||||
using var events = server.Services.GetRequiredService<EventHub>().Subscribe();
|
||||
|
||||
// Off, so the scheduler's own passes leave it alone; without a duplicates handler its run queues nothing.
|
||||
var created = await CreateAsync(admin, new CreateScheduleRequest("Duplicates", "duplicates", new RecurrenceDto("daily", Time: "01:00"), Enabled: false));
|
||||
var run = await RunAsync(admin, created.Id);
|
||||
Assert.Equal(("unavailable", (Guid?)null), (run.Outcome, run.JobId));
|
||||
using (var delete = await admin.DeleteAsync($"/api/v1/schedules/{created.Id}")) await delete.ExpectAsync(HttpStatusCode.NoContent);
|
||||
|
||||
var changes = new List<bool>();
|
||||
while (events.Reader.TryRead(out var e))
|
||||
{
|
||||
if (e is ScheduleChangedEvent changed && changed.ScheduleId == created.Id) changes.Add(changed.Deleted);
|
||||
}
|
||||
Assert.SequenceEqual([false, false, true], changes);
|
||||
Assert.Equal($$"""{"type":"scheduleChanged","scheduleId":"{{created.Id}}","deleted":true}""",
|
||||
JsonSerializer.Serialize<ServerEvent>(new ScheduleChangedEvent(created.Id, true), ProtocolJson.Default.ServerEvent));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settings a desktop put into archive.json reach the index every 10 minutes whatever the archive scan does, as with the
|
||||
/// former polling: the scan's runs read them too, but they are skipped while a long scan is pending, and the schedule may
|
||||
/// be rare or off.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public async Task ArchiveJsonIsReadEveryTenMinutesWhateverTheScanScheduleDoes()
|
||||
{
|
||||
var clock = new SteppedTimeProvider();
|
||||
await using var server = await TestServer.StartAsync(context, services: s =>
|
||||
{
|
||||
ArchiveModule.Register(s);
|
||||
s.AddSingleton<TimeProvider>(clock);
|
||||
});
|
||||
var host = server.Services.GetRequiredService<SchedulerHost>();
|
||||
var archive = server.Services.GetRequiredService<ServerArchive>();
|
||||
// The scan at start is over, then the scan schedule is turned off.
|
||||
await ScansAsync(server, 1);
|
||||
var scanId = Assert.NotNull(await server.Database.Schedules.GetBySystemKeyAsync(ServerScheduleHost.ArchiveScan, Ct)).Id;
|
||||
Assert.Null((await host.Scheduler.UpdateAsync(scanId, new UpdateScheduleRequest(Enabled: false), Ct)).Problem);
|
||||
|
||||
// A desktop sharing the archive changes its folder template; nothing has read it yet.
|
||||
const string template = "{camera}/{date}";
|
||||
var path = new ArchivePaths(archive.Root).ManifestPath;
|
||||
var manifest = ManifestStore.ReadArchive(path);
|
||||
Assert.NotEqual(template, manifest.LayoutTemplates.Folder);
|
||||
ManifestStore.WriteArchive(path, manifest with { LayoutTemplates = manifest.LayoutTemplates with { Folder = template } });
|
||||
Assert.Equal(manifest.LayoutTemplates.Folder, Assert.NotNull(await server.Database.Archives.GetAsync(archive.Id, Ct)).FolderTemplate);
|
||||
|
||||
// Ten minutes on, uploads (the index row) and the admin panel (the served archive) follow it, with no scan.
|
||||
clock.Advance(TimeSpan.FromMinutes(ServerScheduleHost.ScanMinutes));
|
||||
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(30));
|
||||
while (Assert.NotNull(await server.Database.Archives.GetAsync(archive.Id, Ct)).FolderTemplate != template)
|
||||
{
|
||||
Assert.True(DateTime.UtcNow < until, "archive.json was not read again");
|
||||
await Task.Delay(20);
|
||||
}
|
||||
Assert.Equal(template, archive.Current.FolderTemplate);
|
||||
Assert.Count(1, (await server.Database.Jobs.ListAsync(null, JobKind.Scan, 50, null, Ct)).Items);
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
||||
Reference in new issue
Block a user