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
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:
1 parent
1f089888e8
commit
af9eeaab9b
349 files changed
+28341
-1304
No files matched your search
@@ -41,7 +41,9 @@ public partial class App : Application
|
||||
var capture = captureIndex >= 0;
|
||||
// Capture never reads or writes the user's data folder.
|
||||
Environment = capture ? AppEnvironment.ForCapture() : AppEnvironment.Detect();
|
||||
_log = new FileLogSink(Environment.LogDirectory, "chronos");
|
||||
// Settings › Advanced › Logs from the first line, which prunes the folder: also a launch that only hands over. The
|
||||
// settings are read again once this launch owns the data folder, since a Chronos that was closing saves them on exit.
|
||||
_log = AppLogging.Open(Environment.LogDirectory, capture ? new AppSettings() : AppSettings.Load(Environment.SettingsPath));
|
||||
// Capture runs in CI: mirror the log to stderr so failures are visible in the job output.
|
||||
Log.SetSink(capture ? new TeeLogSink(_log, new StderrLogSink()) : _log);
|
||||
Log.Info("app", $"Chronos {AppServices.VersionText} starting; data at {Environment.DataDirectory}");
|
||||
@@ -77,6 +79,7 @@ public partial class App : Application
|
||||
}
|
||||
|
||||
Settings = capture ? new AppSettings { Language = "en" } : AppSettings.Load(Environment.SettingsPath);
|
||||
ApplyLogSettings();
|
||||
UiLanguage.Apply(Settings.Language);
|
||||
ThemeManager.Initialize(this, capture ? AppTheme.Dark : Settings.Theme);
|
||||
AppResources.Merge(this);
|
||||
@@ -182,7 +185,7 @@ public partial class App : Application
|
||||
|
||||
public void SaveSettings()
|
||||
{
|
||||
// A launch that handed over to the running Chronos exits before loading any settings.
|
||||
// A launch that handed over to the running Chronos reads the settings only for its log and never sets Settings.
|
||||
if (Settings is null) return;
|
||||
try
|
||||
{
|
||||
@@ -192,6 +195,14 @@ public partial class App : Application
|
||||
{
|
||||
Log.Warning("app", "Settings not saved", ex);
|
||||
}
|
||||
// Every settings change passes here, Settings › Advanced › Logs, its Reset and an imported file included.
|
||||
ApplyLogSettings();
|
||||
}
|
||||
|
||||
/// <summary>Settings › Advanced › Logs to the log files, from the next line on (owner review 2, R11).</summary>
|
||||
private void ApplyLogSettings()
|
||||
{
|
||||
if (_log is not null) AppLogging.Apply(_log, Settings);
|
||||
}
|
||||
|
||||
protected override void OnExit(ExitEventArgs e)
|
||||
|
||||
@@ -24,6 +24,7 @@ using Chronos.Core.Video;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
@@ -33,8 +34,8 @@ namespace Chronos.App.DesignTime;
|
||||
/// <summary>
|
||||
/// Synthetic content for <c>--capture</c> screenshots and the screen smoke tests ONLY: a temporary SQLite index
|
||||
/// with an archive of generated JPEGs (one sequence stores its thumbnail as an embedded preview inside a fake RAW
|
||||
/// file), jobs in every state, a fake signed-in server with sequences to compare (one in conflict) and a fake
|
||||
/// encoder inventory. Everything lives in the
|
||||
/// file), jobs in every state, schedules (the system ones with runs, a weekly integrity check, a monthly report turned
|
||||
/// off), a fake signed-in server with sequences to compare (one in conflict) and a fake encoder inventory. Everything lives in the
|
||||
/// capture environment's temporary folder; nothing touches the network or the user's data.
|
||||
/// </summary>
|
||||
public sealed class SampleData
|
||||
@@ -55,6 +56,8 @@ public sealed class SampleData
|
||||
private ChronosDatabase? _db;
|
||||
private Guid _sunrise;
|
||||
private Guid _lakeComo;
|
||||
private Guid _weeklyVerify = Guid.CreateVersion7();
|
||||
private Guid? _scanSchedule;
|
||||
private Permissions _permissions = RolePermissions.Default(UserRole.Editor);
|
||||
|
||||
private SampleData(AppServices services) => _services = services;
|
||||
@@ -77,6 +80,8 @@ public sealed class SampleData
|
||||
services.Devices = new SampleDeviceMonitor();
|
||||
services.Sync.RemoteFactory = (_, _, _) => sample._remote;
|
||||
services.Sync.EditorFactory = (_, _, _) => sample._remote;
|
||||
// The schedules keep the sample's moment: nothing becomes due while the screenshots are taken.
|
||||
services.SchedulerTime = new FixedTime(Now);
|
||||
return sample;
|
||||
}
|
||||
|
||||
@@ -109,7 +114,10 @@ public sealed class SampleData
|
||||
await db.Sequences.SetTagsAsync(sequences[0].Sequence.Id, ["sunset", "harbour"]);
|
||||
await db.Sequences.SetTagsAsync(sequences[9].Sequence.Id, ["holy grail"]);
|
||||
|
||||
foreach (var job in Jobs(sequences.Select(s => s.Sequence).ToList(), archive.Id)) await db.Jobs.EnqueueAsync(job);
|
||||
_scanSchedule = (await db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan))?.Id;
|
||||
var jobs = Jobs(sequences.Select(s => s.Sequence).ToList(), archive.Id).ToList();
|
||||
foreach (var job in jobs) await db.Jobs.EnqueueAsync(job);
|
||||
await FillSchedulesAsync(db, jobs);
|
||||
await FillServerAsync(db, sequences.Select(s => s.Sequence).ToList());
|
||||
await SampleCards.InsertAsync(db, (SampleDeviceMonitor)_services.Devices, _services.Environment.DataDirectory);
|
||||
await FillViewsAsync(db);
|
||||
@@ -126,6 +134,53 @@ public sealed class SampleData
|
||||
settings.FirstRunCompleted = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Jobs › Scheduled (owner review 2, R10): the archive scan ran 4 minutes ago (its scan is in the history), the index
|
||||
/// backup yesterday, the housekeeping never yet; a weekly integrity check the user made, whose run waits in the queue, and
|
||||
/// a monthly orphans report turned off.
|
||||
/// </summary>
|
||||
private async Task FillSchedulesAsync(ChronosDatabase db, IReadOnlyList<Job> jobs)
|
||||
{
|
||||
var verify = jobs.First(j => j.ScheduleId == _weeklyVerify);
|
||||
var weekly = ScheduleRecurrence.WeeklyAt([DayOfWeek.Sunday], new TimeOnly(2, 0));
|
||||
var created = Now.AddDays(-40);
|
||||
await db.Schedules.InsertAsync(new Schedule
|
||||
{
|
||||
Id = _weeklyVerify,
|
||||
Name = "Weekly integrity check",
|
||||
Action = ScheduleActions.Verify,
|
||||
ParametersJson = ScheduleMapping.ParametersJson(ScheduleActions.Verify, new ScheduleParametersDto(OlderThanDays: 30, Percent: 25)),
|
||||
Recurrence = weekly.Format(),
|
||||
NextRun = weekly.Next(Now, TimeZoneInfo.Local),
|
||||
LastRun = verify.Created,
|
||||
LastJobId = verify.Id,
|
||||
LastOutcome = ScheduleOutcome.Queued,
|
||||
Created = created,
|
||||
Updated = created,
|
||||
});
|
||||
var monthly = ScheduleRecurrence.MonthlyAt(1, new TimeOnly(5, 0));
|
||||
await db.Schedules.InsertAsync(new Schedule
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Name = "Monthly orphans report",
|
||||
Action = ScheduleActions.Orphans,
|
||||
Recurrence = monthly.Format(),
|
||||
Enabled = false,
|
||||
Created = created.AddMinutes(5),
|
||||
Updated = created.AddMinutes(5),
|
||||
});
|
||||
if (_scanSchedule is { } scan && jobs.FirstOrDefault(j => j.ScheduleId == scan) is { } scanned)
|
||||
await db.Schedules.RecordOutcomeAsync(scan, scanned.Id, ScheduleOutcome.Queued, scanned.Created);
|
||||
if (await db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.IndexBackup) is { } backup)
|
||||
await db.Schedules.RecordOutcomeAsync(backup.Id, null, ScheduleOutcome.SkippedNothing, Now.AddDays(-1).AddHours(-2));
|
||||
}
|
||||
|
||||
/// <summary>A clock stopped at one moment (the schedules of the capture).</summary>
|
||||
private sealed class FixedTime(DateTimeOffset now) : TimeProvider
|
||||
{
|
||||
public override DateTimeOffset GetUtcNow() => now;
|
||||
}
|
||||
|
||||
/// <summary>Two saved views of the Library ("Not analysed, largest" and one camera), BRIEF §12.2.</summary>
|
||||
private static async Task FillViewsAsync(ChronosDatabase db)
|
||||
{
|
||||
@@ -185,7 +240,7 @@ public sealed class SampleData
|
||||
{
|
||||
var db = _db ?? throw new InvalidOperationException("FillAsync first.");
|
||||
var service = _services.Sync.Service ?? throw new InvalidOperationException("The index is not open.");
|
||||
// The history is kept whatever the date: the sample's finished jobs are dated from Now, not from today.
|
||||
// The engine purges no history (the housekeeping schedule does): the sample's finished jobs, dated from Now, stay.
|
||||
await using var engine = new JobEngine(db, service.CreateJobHandlers(_services.Sync),
|
||||
new JobEngineOptions
|
||||
{
|
||||
@@ -193,7 +248,6 @@ public sealed class SampleData
|
||||
WorkerId = "sample-proxies",
|
||||
Kinds = [JobKind.Download],
|
||||
PollInterval = TimeSpan.FromMilliseconds(50),
|
||||
HistoryRetention = TimeSpan.FromDays(36_500),
|
||||
});
|
||||
await engine.StartAsync();
|
||||
var job = await service.EnqueueDownloadAsync(engine, ServerAddress, _sunrise, "Sunrise over Superga", SyncDownloadMode.Proxies, null);
|
||||
@@ -637,10 +691,11 @@ public sealed class SampleData
|
||||
var here = _services.WorkerId;
|
||||
Job Make(JobKind kind, Sequence? target, string label, JobState state, long done, long total, double? rate = null, TimeSpan? eta = null,
|
||||
TimeSpan? startedAgo = null, TimeSpan? runFor = null, string? node = null, string? error = null, string? log = null,
|
||||
JobPriority priority = JobPriority.Normal, TimeSpan? createdAgo = null) => new()
|
||||
JobPriority priority = JobPriority.Normal, TimeSpan? createdAgo = null, Guid? schedule = null) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = kind,
|
||||
ScheduleId = schedule,
|
||||
TargetIds = target is null ? [archiveId] : [target.Id],
|
||||
TargetLabel = label,
|
||||
State = state,
|
||||
@@ -672,9 +727,14 @@ public sealed class SampleData
|
||||
yield return Make(JobKind.Proxies, s[1], s[1].DisplayTitle, JobState.Paused, 915, 1_005, startedAgo: TimeSpan.FromMinutes(14),
|
||||
priority: JobPriority.Background);
|
||||
yield return Make(JobKind.Render, s[3], "Aurora, Tromsø → 1080p share H.264", JobState.Queued, 0, 0, createdAgo: TimeSpan.FromMinutes(12));
|
||||
yield return Make(JobKind.Verify, null, "Archive · 2024", JobState.Queued, 0, 0, priority: JobPriority.Background, createdAgo: TimeSpan.FromMinutes(30));
|
||||
// The weekly integrity check the user scheduled waits behind the user's jobs.
|
||||
yield return Make(JobKind.Verify, null, "Archive · 2024", JobState.Queued, 0, 0, priority: JobPriority.Background, createdAgo: TimeSpan.FromMinutes(30),
|
||||
schedule: _weeklyVerify);
|
||||
yield return Make(JobKind.Verify, s[7], s[7].DisplayTitle, JobState.Failed, 640, 640, 900, startedAgo: TimeSpan.FromMinutes(25), runFor: TimeSpan.FromSeconds(43),
|
||||
error: "2 files whose hash no longer matches the sidecar", log: "09:58:01 verify 640 files\n09:58:43 2 hash mismatches: 2025-08-02_0213.ARW, 2025-08-02_0214.ARW");
|
||||
// The archive scan schedule's latest run.
|
||||
yield return Make(JobKind.Scan, null, "ChronosArchive", JobState.Done, 412, 412, 640, startedAgo: TimeSpan.FromMinutes(4), runFor: TimeSpan.FromSeconds(1),
|
||||
priority: JobPriority.Background, schedule: _scanSchedule);
|
||||
yield return Make(JobKind.Render, s[5], "Milan skyline dusk → 4K HEVC", JobState.Done, 2_400, 2_400, 14.8, startedAgo: TimeSpan.FromMinutes(70),
|
||||
runFor: new TimeSpan(0, 2, 41), node: "studio-pc");
|
||||
yield return Make(JobKind.Import, s[0], "EOS R5 · card A → Archive · 4,812 photos", JobState.Done, 4_812, 4_812, 7.1, startedAgo: TimeSpan.FromMinutes(110),
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
using Chronos.Core.Diagnostics;
|
||||
|
||||
namespace Chronos.App.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// Settings › Advanced › Logs applied to this PC's log files (owner review 2, R11): the level, retention, size limits and
|
||||
/// rotation of the <see cref="FileLogSink"/> App starts with, and the engine's <see cref="Log.MinimumLevel"/> (the files
|
||||
/// are the only output outside screenshots). Values outside the ranges Settings offers are brought within them, and a
|
||||
/// total below one file is raised to that file (<see cref="LogFileOptions.TotalBelowFile"/>), which the server refuses.
|
||||
/// </summary>
|
||||
public static class AppLogging
|
||||
{
|
||||
public const int DefaultDiagnosticsLogMb = (int)(DiagnosticsArchive.DefaultLogTailBytes / LogFileOptions.BytesPerMb);
|
||||
|
||||
public const int MaxRetentionDays = 3650;
|
||||
public const int MaxFileMb = 10 * 1024;
|
||||
public const int MaxTotalMb = 1024 * 1024;
|
||||
public const int MaxDiagnosticsLogMb = 1024;
|
||||
|
||||
public static LogFileOptions Options(AppSettings settings)
|
||||
{
|
||||
var file = int.Clamp(settings.LogMaxFileMb, 0, MaxFileMb);
|
||||
var total = int.Clamp(settings.LogMaxTotalMb, 0, MaxTotalMb);
|
||||
return new()
|
||||
{
|
||||
Level = Enum.IsDefined(settings.LogLevel) ? settings.LogLevel : LogLevel.Info,
|
||||
RetentionDays = int.Clamp(settings.LogRetentionDays, 1, MaxRetentionDays),
|
||||
MaxFileMb = file,
|
||||
MaxTotalMb = LogFileOptions.TotalBelowFile(file, total) ? file : total,
|
||||
Rotation = Enum.IsDefined(settings.LogRotation) ? settings.LogRotation : LogRotation.Daily,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Bytes the diagnostics bundle keeps from the end of each log file.</summary>
|
||||
public static long DiagnosticsTailBytes(AppSettings settings) => int.Clamp(settings.DiagnosticsLogMb, 1, MaxDiagnosticsLogMb) * LogFileOptions.BytesPerMb;
|
||||
|
||||
/// <summary>
|
||||
/// The log files App starts with, in <paramref name="directory"/>, with <paramref name="settings"/> from the first line:
|
||||
/// that line opens a file and prunes, so the defaults would delete what the user keeps longer.
|
||||
/// </summary>
|
||||
public static FileLogSink Open(string directory, AppSettings settings)
|
||||
{
|
||||
var options = Options(settings);
|
||||
Log.MinimumLevel = options.Level;
|
||||
return new FileLogSink(directory, "chronos", options);
|
||||
}
|
||||
|
||||
/// <summary>The settings to <paramref name="sink"/> and the engine, from the next line on.</summary>
|
||||
public static void Apply(FileLogSink sink, AppSettings settings)
|
||||
{
|
||||
var options = Options(settings);
|
||||
sink.Configure(options);
|
||||
Log.MinimumLevel = options.Level;
|
||||
}
|
||||
}
|
||||
@@ -22,19 +22,22 @@ using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Protocol.Client;
|
||||
|
||||
namespace Chronos.App.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// Composition root of local mode (BRIEF §4.4): the SQLite index under the data folder (migrated on open, a restore
|
||||
/// staged in Settings › Advanced carried out first, then copied once a day into the backups folder), the archive engine
|
||||
/// (WIC first, then managed decoders), the analysis and render engine (the same decoders; Media Foundation, then
|
||||
/// managed encoders), the one <see cref="JobEngine"/> of this PC with the handlers of <see cref="CreateJobHandlers"/>,
|
||||
/// thumbnails, the server session, the render node, the encoder and format inventories, the update check and the sync
|
||||
/// with the signed-in server (<see cref="SyncHost"/>). Started after the window shows, stopped when the app exits. The
|
||||
/// archive at Settings › Archive's folder is reopened at start and rescanned every <see cref="ScanInterval"/>, as is one
|
||||
/// chosen later (BRIEF §7: polling, no file-system watchers). Jobs follow Settings › Rendering and Analysis from the
|
||||
/// staged in Settings › Advanced carried out first), the archive engine (WIC first, then managed decoders), the analysis
|
||||
/// and render engine (the same decoders; Media Foundation, then managed encoders), the one <see cref="JobEngine"/> of
|
||||
/// this PC with the handlers of <see cref="CreateJobHandlers"/>, the <see cref="Data.Scheduling.Scheduler"/> that queues the
|
||||
/// recurring work (owner review 2, R10: the archive scan, the daily index backup and the housekeeping are its system
|
||||
/// schedules, <see cref="DesktopScheduleHost"/>), thumbnails, the server session, the render node, the encoder and format
|
||||
/// inventories, the update check and the sync with the signed-in server (<see cref="SyncHost"/>). Started after the
|
||||
/// window shows, stopped when the app exits. The archive at Settings › Archive's folder is reopened at start before the
|
||||
/// scheduler starts, and while it is unplugged every <see cref="ReopenInterval"/> until it is back; the schedules follow
|
||||
/// the folder, also one chosen later (BRIEF §7: polling, no file-system watchers). Jobs follow Settings › Rendering and Analysis from the
|
||||
/// next one on (memory budget, quality profile, analysis parameters through <see cref="ProcessingTuning"/>; parallelism
|
||||
/// as the engine's workers). The render node runs while the user offers this PC (<see cref="AppSettings.RenderNodeOptIn"/>)
|
||||
/// and a server session is open (never in capture mode). Renders and the render node use hardware encoders as
|
||||
@@ -52,9 +55,8 @@ public sealed class AppServices : IAsyncDisposable
|
||||
private static readonly Lazy<HttpClient> DownloadHttp = new(() => new HttpClient { Timeout = Timeout.InfiniteTimeSpan });
|
||||
private readonly CancellationTokenSource _stopping = new();
|
||||
private readonly Dictionary<Guid, Guid> _scans = [];
|
||||
private Task _polling = Task.CompletedTask;
|
||||
private Task _backups = Task.CompletedTask;
|
||||
private PeriodicTimer? _pollTimer;
|
||||
private readonly TaskCompletionSource<bool> _schedulerReady = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private Task _schedules = Task.CompletedTask;
|
||||
private WicDecoderProvider? _wic;
|
||||
private readonly RenderNodeHost _renderNode;
|
||||
private ServerSession _server = null!;
|
||||
@@ -68,6 +70,7 @@ public sealed class AppServices : IAsyncDisposable
|
||||
_renderNode = new RenderNodeHost(StartRenderNode);
|
||||
ArchiveSetup = new EngineArchiveSetup(this);
|
||||
Sync = new SyncHost(this);
|
||||
ScheduleHost = new DesktopScheduleHost(settings, () => Database, () => Archives);
|
||||
Server = new ServerSession(settings, saveSettings, new ChronosServerApiFactory(), new DpapiTokenProtector());
|
||||
Encoders = new MediaFoundationInventory();
|
||||
Formats = new WicFormatInventory(() => _wic);
|
||||
@@ -113,8 +116,20 @@ public sealed class AppServices : IAsyncDisposable
|
||||
/// <summary>Decode tier per format on this PC and the missing codec extensions (Settings › Formats).</summary>
|
||||
public IFormatInventory Formats { get; set; }
|
||||
|
||||
/// <summary>Time between the rescans of the open archive (Settings › Archive).</summary>
|
||||
public TimeSpan ScanInterval => TimeSpan.FromMinutes(int.Clamp(Settings.ScanIntervalMinutes, 1, 24 * 60));
|
||||
/// <summary>How often an archive that was unplugged at start is looked for again, until it is back.</summary>
|
||||
public static TimeSpan ReopenInterval { get; } = TimeSpan.FromMinutes(1);
|
||||
|
||||
/// <summary>What the scheduler works with on this PC: its zone, the current archive, the system schedules.</summary>
|
||||
public DesktopScheduleHost ScheduleHost { get; }
|
||||
|
||||
/// <summary>The schedules of this PC (Jobs › Scheduled); null until they run (<see cref="SchedulerReady"/>).</summary>
|
||||
public Scheduler? Scheduler { get; private set; }
|
||||
|
||||
/// <summary>True once <see cref="Scheduler"/> runs; false when it never will (no index, no engine, it failed, the app stops).</summary>
|
||||
public Task<bool> SchedulerReady => _schedulerReady.Task;
|
||||
|
||||
/// <summary>The clock of the schedules; the capture stops it at its sample moment.</summary>
|
||||
public TimeProvider SchedulerTime { get; set; } = TimeProvider.System;
|
||||
|
||||
/// <summary>How the restore staged in Settings › Advanced went when the index opened; null when none was staged.</summary>
|
||||
public StagedRestoreResult? StagedRestore { get; private set; }
|
||||
@@ -186,13 +201,13 @@ public sealed class AppServices : IAsyncDisposable
|
||||
public void SavePreferences() => SaveSettingsAction();
|
||||
|
||||
/// <summary>
|
||||
/// The archive's rescan interval, now, and a review of the priority queue (Settings › Rendering): turned on, it may make
|
||||
/// the running job yield at once. The parallelism applies from the next sequence or job.
|
||||
/// A review of the priority queue (Settings › Rendering): turned on, it may make the running job yield at once; and a
|
||||
/// pass of the schedules, whose runs read the settings. The parallelism applies from the next sequence or job.
|
||||
/// </summary>
|
||||
public void ApplyJobSettings()
|
||||
{
|
||||
Engine?.Wake();
|
||||
if (_pollTimer is { } timer && timer.Period != ScanInterval) timer.Period = ScanInterval;
|
||||
Scheduler?.Wake();
|
||||
}
|
||||
|
||||
/// <summary>Photos the running job of this PC processes at once (Settings › Rendering › Parallelism, Auto: half the logical cores).</summary>
|
||||
@@ -216,8 +231,9 @@ public sealed class AppServices : IAsyncDisposable
|
||||
|
||||
/// <summary>
|
||||
/// Opens (or creates) the index at <paramref name="databasePath"/>, migrates it (after a restore staged in Settings ›
|
||||
/// Advanced replaced it, which needs no open index: it also recovers one that no longer opens), starts the job engine
|
||||
/// and the daily backups.
|
||||
/// Advanced replaced it, which needs no open index: it also recovers one that no longer opens), starts the job engine,
|
||||
/// then in the background reopens the archive and starts the schedules (<see cref="SchedulerReady"/>, false at once
|
||||
/// when the index or the engine does not open).
|
||||
/// </summary>
|
||||
public async Task OpenAsync(string databasePath, CancellationToken ct = default)
|
||||
{
|
||||
@@ -231,31 +247,44 @@ public sealed class AppServices : IAsyncDisposable
|
||||
{
|
||||
OpenError = ex;
|
||||
Log.Error("app", "The index could not be opened", ex);
|
||||
// No index, no schedules: Jobs › Scheduled says so instead of waiting for them.
|
||||
_schedulerReady.TrySetResult(false);
|
||||
return;
|
||||
}
|
||||
await StartJobsAsync(Database, startEngine: true, ct);
|
||||
Thumbnails = new ThumbnailService(Database, Settings.ThumbnailMemoryItems);
|
||||
Devices.Start();
|
||||
var database = Database;
|
||||
_backups = Task.Run(() => DatabaseBackups.RunDailyAsync(database, Environment.BackupDirectory, null, _stopping.Token));
|
||||
_polling = PollAsync(_stopping.Token);
|
||||
try
|
||||
{
|
||||
await StartJobsAsync(Database, startEngine: true, ct);
|
||||
Thumbnails = new ThumbnailService(Database, Settings.ThumbnailMemoryItems);
|
||||
Devices.Start();
|
||||
}
|
||||
catch
|
||||
{
|
||||
_schedulerReady.TrySetResult(false);
|
||||
throw;
|
||||
}
|
||||
_schedules = RunSchedulesAsync(_stopping.Token);
|
||||
}
|
||||
|
||||
/// <summary>Uses an already open index (capture, tests) instead of opening one; sample data keeps the engine stopped.</summary>
|
||||
/// <summary>
|
||||
/// Uses an already open index (capture, tests) instead of opening one, and starts the schedules (no archive to reopen);
|
||||
/// sample data keeps the engine stopped.
|
||||
/// </summary>
|
||||
public async Task AttachAsync(ChronosDatabase database, bool startEngine = true, CancellationToken ct = default)
|
||||
{
|
||||
Database = database;
|
||||
await StartJobsAsync(database, startEngine, ct);
|
||||
Thumbnails = new ThumbnailService(database, Settings.ThumbnailMemoryItems);
|
||||
await StartSchedulerAsync(ct);
|
||||
}
|
||||
|
||||
/// <summary>Stops polling, the render node and the engine, then closes the index. The app's exit waits for this on the UI
|
||||
/// thread, so nothing here continues on it.</summary>
|
||||
/// <summary>Stops the schedules, the render node and the engine, then closes the index. The app's exit waits for this on
|
||||
/// the UI thread, so nothing here continues on it.</summary>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _stopping.CancelAsync().ConfigureAwait(false);
|
||||
await _polling.ConfigureAwait(false);
|
||||
await _backups.ConfigureAwait(false);
|
||||
await _schedules.ConfigureAwait(false);
|
||||
_schedulerReady.TrySetResult(false);
|
||||
if (Scheduler is not null) await Scheduler.DisposeAsync().ConfigureAwait(false);
|
||||
_stopping.Dispose();
|
||||
_server.PropertyChanged -= OnServerChanged;
|
||||
await _renderNode.DisposeAsync().ConfigureAwait(false);
|
||||
@@ -268,66 +297,101 @@ public sealed class AppServices : IAsyncDisposable
|
||||
if (Database is not null) await Database.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The period of the rescans while they run (Settings › Archive › Rescan every); null before the index opens.</summary>
|
||||
internal TimeSpan? PollingPeriod => _pollTimer?.Period;
|
||||
|
||||
/// <summary>
|
||||
/// One rescan of the polling, off the UI thread: the archive the Import and Archive screens work on
|
||||
/// (<see cref="CurrentArchive"/>, the one at Settings › Archive's folder) first takes the settings another process
|
||||
/// sharing it wrote into its archive.json (also on a read-only share), then gets an incremental scan while it is
|
||||
/// online. Returns that archive; null when the index holds none.
|
||||
/// At start, off the UI thread: reopens the archive at Settings › Archive's folder (a moved one relinked, interrupted
|
||||
/// renames finished), then starts the schedules, whose first pass settles the runs missed while Chronos was closed, and
|
||||
/// runs the archive scan once, as the rescans did at start (<see cref="ScanNowAsync"/>). An archive whose archive.json is
|
||||
/// not there (an unplugged drive) is looked for every <see cref="ReopenInterval"/> until it is back, then scanned and the
|
||||
/// schedules look at once for a due run; unless the folder changed meanwhile: whatever changed it opened the new
|
||||
/// archive. The app's exit waits for this on the UI thread.
|
||||
/// </summary>
|
||||
internal Task<Archive?> RescanAsync(CancellationToken ct = default) => Task.Run(async () =>
|
||||
{
|
||||
if (Database is not { } db || Archives is not { } archives) return null;
|
||||
var archive = CurrentArchive.Pick(await db.Archives.ListAsync(ct).ConfigureAwait(false), Settings.LastArchivePath);
|
||||
if (archive is null) return null;
|
||||
var availability = ArchiveService.GetAvailability(archive);
|
||||
if (availability != ArchiveAvailability.Offline) await archives.RefreshSettingsAsync(archive.Id, ct).ConfigureAwait(false);
|
||||
if (availability == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct).ConfigureAwait(false);
|
||||
return archive;
|
||||
}, ct);
|
||||
|
||||
/// <summary>
|
||||
/// Rescans the archive now and every <see cref="ScanInterval"/> (<see cref="RescanAsync"/>) until the app exits, which
|
||||
/// waits for it on the UI thread. Each rescan follows the archive folder: one chosen on the first run, in Settings or
|
||||
/// by a relink is rescanned from the next tick on, the one before no longer. The archive at the folder of the start is
|
||||
/// first reopened (a moved one relinked, interrupted renames finished), at each tick until its archive.json is there
|
||||
/// (an unplugged drive), unless the folder changed meanwhile: whatever changed it opened the new archive.
|
||||
/// </summary>
|
||||
private async Task PollAsync(CancellationToken ct)
|
||||
private async Task RunSchedulesAsync(CancellationToken ct)
|
||||
{
|
||||
var reopen = Settings.LastArchivePath is { Length: > 0 } start ? start : null;
|
||||
// Settings › Archive changes the period of this timer (ApplyJobSettings).
|
||||
using var timer = _pollTimer = new PeriodicTimer(ScanInterval);
|
||||
try
|
||||
{
|
||||
do
|
||||
if (reopen is not null && await ReopenAsync(reopen, ct).ConfigureAwait(false)) reopen = null;
|
||||
var started = SchedulerTime.GetUtcNow();
|
||||
await StartSchedulerAsync(ct).ConfigureAwait(false);
|
||||
if (reopen is null)
|
||||
{
|
||||
if (reopen is not null
|
||||
&& (!string.Equals(reopen, Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase) || await ReopenAsync(reopen, ct).ConfigureAwait(false)))
|
||||
reopen = null;
|
||||
try
|
||||
{
|
||||
await RescanAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or ArgumentException)
|
||||
{
|
||||
// The next tick tries again (a share that dropped, an archive removed from the index meanwhile).
|
||||
Log.Warning("archive", "The archive could not be rescanned", ex);
|
||||
}
|
||||
await ScanNowAsync(started, ct).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
using var timer = new PeriodicTimer(ReopenInterval);
|
||||
while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
if (!string.Equals(reopen, Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase)) return;
|
||||
if (!await ReopenAsync(reopen, ct).ConfigureAwait(false)) continue;
|
||||
await ScanNowAsync(null, ct).ConfigureAwait(false);
|
||||
Scheduler?.Wake();
|
||||
return;
|
||||
}
|
||||
while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false));
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
// The exit waits for this task: nothing it throws may stop the app from closing.
|
||||
Log.Error("schedules", "The archive could not be reopened or the schedules started", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_pollTimer = null;
|
||||
_schedulerReady.TrySetResult(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the archive scan schedule once now when it is enabled (owner review 2, R10: the archive was opened or is back),
|
||||
/// unless it ran since <paramref name="since"/> (the first pass fired it) or its scan is still pending.
|
||||
/// </summary>
|
||||
private async Task ScanNowAsync(DateTimeOffset? since, CancellationToken ct)
|
||||
{
|
||||
if (Scheduler is not { } scheduler) return;
|
||||
try
|
||||
{
|
||||
await scheduler.RunSystemNowAsync(DesktopScheduleHost.ArchiveScan, since, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException)
|
||||
{
|
||||
Log.Warning("schedules", "The archive scan could not be run now; its schedule runs the next one", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts <see cref="Scheduler"/> on this PC's engine: it seeds the system schedules and runs its first pass before
|
||||
/// <see cref="SchedulerReady"/> turns true. Without an engine, or when the schedules cannot be read, there is none.
|
||||
/// </summary>
|
||||
private async Task StartSchedulerAsync(CancellationToken ct)
|
||||
{
|
||||
if (Database is not { } db || Engine is not { } engine || Scheduler is not null)
|
||||
{
|
||||
_schedulerReady.TrySetResult(Scheduler is not null);
|
||||
return;
|
||||
}
|
||||
var scheduler = new Scheduler(db, engine, new SchedulerOptions { Time = SchedulerTime });
|
||||
try
|
||||
{
|
||||
await Task.Run(() => scheduler.StartAsync(ScheduleHost, ct), ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException or ArgumentException)
|
||||
{
|
||||
Log.Error("schedules", "The schedules could not be started; nothing recurring runs until the next start", ex);
|
||||
await scheduler.DisposeAsync().ConfigureAwait(false);
|
||||
_schedulerReady.TrySetResult(false);
|
||||
return;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
await scheduler.DisposeAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
Scheduler = scheduler;
|
||||
Log.Info("schedules", "Schedules started");
|
||||
_schedulerReady.TrySetResult(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the archive at <paramref name="root"/> again as at open; false while its archive.json is not there. A
|
||||
/// damaged or newer one is not tried again: the archive the index holds at the folder is still rescanned.
|
||||
@@ -385,6 +449,9 @@ public sealed class AppServices : IAsyncDisposable
|
||||
Decoder = DecoderFactory.CreateClient(_wic),
|
||||
Parallelism = () => Parallelism,
|
||||
MemoryBudget = () => ProcessingTuning.MemoryBudget(Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes),
|
||||
// The housekeeping schedule trims the cache to Settings › Storage › Cache limit (owner review 2, R10).
|
||||
CleanupSteps = [new CacheTrimStep(() => CacheStore.Folder(Environment, Settings), () => Settings.CacheLimitGb * (1L << 30))],
|
||||
BackupDirectory = Environment.BackupDirectory,
|
||||
};
|
||||
Archives = new ArchiveService(database, archive);
|
||||
Processing = new ProcessingService(database, ProcessingOptions(archive));
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Chronos.Core.Analysis.Deep;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Naming;
|
||||
@@ -96,7 +97,11 @@ public sealed class AppSettings
|
||||
/// <summary>Thumbnail long edge of new archives (also written into the open archive), BRIEF §8.5.</summary>
|
||||
public int ThumbnailLongEdge { get; set; } = 320;
|
||||
|
||||
/// <summary>Minutes between the rescans of the open archive (BRIEF §7: polling by mtime and size, no file-system watchers).</summary>
|
||||
/// <summary>
|
||||
/// Obsolete (owner review 2, R10): the former Settings › Archive › Rescan every. Nothing edits it any more; it only seeds
|
||||
/// the interval of the <c>archive-scan</c> schedule (<see cref="Jobs.DesktopScheduleHost"/>) the first time it is created,
|
||||
/// and is what Reset puts that schedule back to. The schedule's own interval is edited in Jobs › Scheduled.
|
||||
/// </summary>
|
||||
public int ScanIntervalMinutes { get; set; } = DefaultScanIntervalMinutes;
|
||||
|
||||
// ---- Import (defaults of new cards and folders; a card's own profile wins) ----
|
||||
@@ -185,6 +190,25 @@ public sealed class AppSettings
|
||||
/// <summary>"Clear done": finished jobs older than this are hidden from the Jobs list (they stay in the history).</summary>
|
||||
public DateTimeOffset? JobsClearedAt { get; set; }
|
||||
|
||||
// ---- Advanced › Logs (owner review 2, R11; applied by AppLogging) ----
|
||||
/// <summary>Least severe level written to the log files.</summary>
|
||||
public LogLevel LogLevel { get; set; } = LogLevel.Info;
|
||||
|
||||
/// <summary>Log files last written longer ago are deleted.</summary>
|
||||
public int LogRetentionDays { get; set; } = LogFileOptions.DefaultRetentionDays;
|
||||
|
||||
/// <summary>A log file this large (MB of 2²⁰ bytes) continues in a numbered one; 0 = no limit.</summary>
|
||||
public int LogMaxFileMb { get; set; } = LogFileOptions.DefaultMaxFileMb;
|
||||
|
||||
/// <summary>While the log files together are larger (MB), the oldest are deleted, never the current one; 0 = no limit.</summary>
|
||||
public int LogMaxTotalMb { get; set; } = LogFileOptions.DefaultMaxTotalMb;
|
||||
|
||||
/// <summary>One log file per UTC day or per hour.</summary>
|
||||
public LogRotation LogRotation { get; set; } = LogRotation.Daily;
|
||||
|
||||
/// <summary>MB kept from the end of each log file in the diagnostics bundle.</summary>
|
||||
public int DiagnosticsLogMb { get; set; } = AppLogging.DefaultDiagnosticsLogMb;
|
||||
|
||||
public sealed class WindowPlacement
|
||||
{
|
||||
public double Left { get; set; }
|
||||
|
||||
@@ -14,7 +14,8 @@ namespace Chronos.App.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// The diagnostics bundle of Settings › Advanced (BRIEF §12.8, §12.9, §22 Phase 8): an environment report, the codec
|
||||
/// and encoder inventory, the settings, the latest failed jobs and the log files, zipped into a folder the user chose.
|
||||
/// and encoder inventory, the settings, the latest failed jobs and the end of each log file (Settings › Advanced ›
|
||||
/// Diagnostics logs), zipped into a folder the user chose.
|
||||
/// Everything passes through <see cref="SecretScrubber"/> (the saved server token, passwords and keys never leave the
|
||||
/// PC) and no photo or archive file is ever included.
|
||||
/// </summary>
|
||||
@@ -31,6 +32,7 @@ public static class DiagnosticsBundle
|
||||
public static Task<string> CreateAsync(AppServices services, string folder, IEnumerable<string>? extraLines = null, CancellationToken ct = default)
|
||||
{
|
||||
var settings = services.Settings.ToJson();
|
||||
var tailBytes = AppLogging.DiagnosticsTailBytes(services.Settings);
|
||||
var report = Report(services.Environment, extraLines) + DatabaseLine(services.Database);
|
||||
return Task.Run(async () =>
|
||||
{
|
||||
@@ -47,7 +49,7 @@ public static class DiagnosticsBundle
|
||||
bundle.AddText("codecs.txt", codecs);
|
||||
bundle.AddJson("settings.json", settings);
|
||||
bundle.AddJobs("jobs-failed.json", failures);
|
||||
bundle.AddLogs(services.Environment.LogDirectory, cancellationToken: ct);
|
||||
bundle.AddLogs(services.Environment.LogDirectory, tailBytes: tailBytes, cancellationToken: ct);
|
||||
}
|
||||
File.Move(temp, path);
|
||||
return path;
|
||||
@@ -114,8 +116,15 @@ public static class DiagnosticsBundle
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What <see cref="CacheStore.Trim"/> did: the cache's size before, the bytes and files it deleted.</summary>
|
||||
public sealed record CacheTrimResult(long Before, long Freed, int Deleted)
|
||||
{
|
||||
/// <summary>The cache's size afterwards.</summary>
|
||||
public long After => Before - Freed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The disk cache (spilled frames, thumbnails): its folder, its size and clearing it. Only a folder Chronos created
|
||||
/// The disk cache (spilled frames, thumbnails): its folder, its size, trimming and clearing it. Only a folder Chronos created
|
||||
/// (it carries a marker file) is ever emptied, so pointing the cache at a folder with user files cannot delete them.
|
||||
/// </summary>
|
||||
public static class CacheStore
|
||||
@@ -179,6 +188,69 @@ public static class CacheStore
|
||||
return freed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Brings an owned cache folder down to <paramref name="limitBytes"/> (owner review 2, R10: the housekeeping
|
||||
/// schedule's cache step): the least recently written files go first, files in use stay (a render spilling, an import
|
||||
/// staging), and so does everything under the <paramref name="keep"/> folders (relative to the cache: sets that must
|
||||
/// stay whole), which still counts towards the size. Null when the folder is not a Chronos cache folder: nothing is
|
||||
/// deleted there.
|
||||
/// </summary>
|
||||
public static CacheTrimResult? Trim(string folder, long limitBytes, IReadOnlyCollection<string>? keep = null, CancellationToken ct = default)
|
||||
{
|
||||
if (!Directory.Exists(folder)) return new CacheTrimResult(0, 0, 0);
|
||||
if (!IsOwned(folder)) return null;
|
||||
var root = new DirectoryInfo(folder);
|
||||
var kept = (keep ?? []).Select(k => Path.TrimEndingDirectorySeparator(Path.GetFullPath(Path.Combine(root.FullName, k))) + Path.DirectorySeparatorChar).ToList();
|
||||
var marker = Path.Combine(root.FullName, MarkerFile);
|
||||
var options = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint };
|
||||
var candidates = new List<FileInfo>();
|
||||
long size = 0;
|
||||
foreach (var file in root.EnumerateFiles("*", options))
|
||||
{
|
||||
size += file.Length;
|
||||
if (file.FullName.Equals(marker, StringComparison.OrdinalIgnoreCase)
|
||||
|| kept.Any(k => file.FullName.StartsWith(k, StringComparison.OrdinalIgnoreCase))) continue;
|
||||
candidates.Add(file);
|
||||
}
|
||||
var before = size;
|
||||
long freed = 0;
|
||||
var deleted = 0;
|
||||
foreach (var file in candidates.OrderBy(f => f.LastWriteTimeUtc))
|
||||
{
|
||||
if (size <= limitBytes) break;
|
||||
ct.ThrowIfCancellationRequested();
|
||||
// Read before the delete: a deleted file has no length.
|
||||
var length = file.Length;
|
||||
if (!TryDeleteUnused(file)) continue;
|
||||
size -= length;
|
||||
freed += length;
|
||||
deleted++;
|
||||
}
|
||||
return new CacheTrimResult(before, freed, deleted);
|
||||
}
|
||||
|
||||
/// <summary>Deletes a file nobody has open; false for one in use or protected.</summary>
|
||||
private static bool TryDeleteUnused(FileInfo file)
|
||||
{
|
||||
try
|
||||
{
|
||||
// A file open anywhere else (written, read or mapped) cannot be opened exclusively: it stays.
|
||||
using (new FileStream(file.FullName, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
|
||||
{
|
||||
}
|
||||
file.Delete();
|
||||
return true;
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static long TryDelete(FileInfo file)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
using System.IO;
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Housekeeping;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.App.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// The desktop's <see cref="IScheduleHost"/> (owner review 2, R10). Times are the PC's; schedules work on the archive at
|
||||
/// Settings › Archive's folder (<see cref="CurrentArchive"/>), which first takes the settings another process sharing it
|
||||
/// wrote into its archive.json, as the rescans before it did, and counts as none while it is offline (an unplugged
|
||||
/// drive). The system schedules stand for the timers the desktop used to run out of sight: the archive scan (its interval
|
||||
/// carried over from the former Settings › Archive › Rescan every, <see cref="AppSettings.ScanIntervalMinutes"/>, once:
|
||||
/// a row that exists keeps the user's edits), the daily index backup, and the housekeeping clean-up at 04:00 (job history,
|
||||
/// cache trim). Scans give what they find a deep analysis as Settings › Analysis › After a scan says at each run
|
||||
/// (<see cref="DeepAnalysisAfterScan"/>), like the scans started by hand. Thread-safe: the scheduler calls it from its loop.
|
||||
/// </summary>
|
||||
public sealed class DesktopScheduleHost(AppSettings settings, Func<ChronosDatabase?> database, Func<ArchiveService?> archives) : IScheduleHost
|
||||
{
|
||||
/// <summary>Incremental scan of the archive, every <see cref="AppSettings.ScanIntervalMinutes"/> (10) minutes, no catch-up.</summary>
|
||||
public const string ArchiveScan = "archive-scan";
|
||||
|
||||
/// <summary>
|
||||
/// Copy of the index into the backups folder, every day, with catch-up (it replaced the daily backup loop). Seeded due
|
||||
/// at once when the newest copy is a day old, as that loop made one at start.
|
||||
/// </summary>
|
||||
public const string IndexBackup = DatabaseBackups.ScheduleKey;
|
||||
|
||||
/// <summary>Clean-up of the job history and the cache, daily at 04:00, with catch-up.</summary>
|
||||
public const string Housekeeping = "housekeeping";
|
||||
|
||||
/// <summary>When the housekeeping runs.</summary>
|
||||
public static readonly TimeOnly HousekeepingTime = new(4, 0);
|
||||
|
||||
/// <summary>The PC's zone; tests set another.</summary>
|
||||
public TimeZoneInfo TimeZone { get; init; } = TimeZoneInfo.Local;
|
||||
|
||||
public IReadOnlyList<SystemSchedule> SystemSchedules =>
|
||||
[
|
||||
new(ArchiveScan, "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(ScanMinutes(settings), RecurrenceUnit.Minutes),
|
||||
new ScheduleParametersDto(Force: false), CatchUp: false),
|
||||
new(IndexBackup, "Index backup", ScheduleActions.Backup, ScheduleRecurrence.Interval(1, RecurrenceUnit.Days),
|
||||
new ScheduleParametersDto(Keep: DatabaseBackups.Keep),
|
||||
LastDone: database() is { } db ? DatabaseBackups.Newest(db, archives()?.BackupDirectory) : null),
|
||||
new(Housekeeping, "Housekeeping", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(HousekeepingTime),
|
||||
new ScheduleParametersDto(Steps: [Chronos.Data.Housekeeping.CleanupSteps.JobHistory, CacheTrimStep.StepName],
|
||||
OlderThanDays: Chronos.Data.Housekeeping.CleanupSteps.DefaultHistoryDays)),
|
||||
];
|
||||
|
||||
public IReadOnlyList<string> CleanupSteps => archives()?.CleanupSteps.Select(s => s.Name).ToList() ?? [];
|
||||
|
||||
/// <summary>
|
||||
/// The interval the scan schedule is seeded with (and reset to): the former rescan setting, within what an interval
|
||||
/// accepts (5 minutes to a day).
|
||||
/// </summary>
|
||||
public static int ScanMinutes(AppSettings settings)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
return int.Clamp(settings.ScanIntervalMinutes, ScheduleRecurrence.MinMinutes, ScheduleRecurrence.MaxMinutes);
|
||||
}
|
||||
|
||||
public async ValueTask<Archive?> GetArchiveAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (database() is not { } db || archives() is not { } service) return null;
|
||||
var archive = CurrentArchive.Pick(await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false), settings.LastArchivePath);
|
||||
if (archive is null || ArchiveService.GetAvailability(archive) == ArchiveAvailability.Offline) return null;
|
||||
try
|
||||
{
|
||||
await service.RefreshSettingsAsync(archive.Id, cancellationToken).ConfigureAwait(false);
|
||||
return await db.Archives.GetAsync(archive.Id, cancellationToken).ConfigureAwait(false) ?? archive;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or NewerFormatException)
|
||||
{
|
||||
// The settings as last read: the run still works on the archive, the next one reads them again.
|
||||
Log.Warning("schedules", $"The settings of {archive.RootPath} could not be read again", ex);
|
||||
return archive;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The desktop runs every action its engine has a handler for.</summary>
|
||||
public string? Unavailable(string action) => null;
|
||||
|
||||
/// <summary>Settings › Analysis › After a scan, read at every run: a scheduled scan follows it as a scan started by hand does.</summary>
|
||||
public bool DeepAnalysisAfterScan => settings.DeepAnalysisAfterScan;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The desktop's clean-up step <c>cache-trim</c> (owner review 2, R10): brings the cache folder down to Settings › Storage ›
|
||||
/// Cache limit, oldest files first, skipping files in use (<see cref="CacheStore.Trim"/>). The proxies of server sequences
|
||||
/// (complete sets the sync keeps), the render node's folder (it trims its own downloads to the same limit) and the copies an
|
||||
/// import to the server stages are never trimmed; Settings › Storage › Clear still empties everything.
|
||||
/// </summary>
|
||||
public sealed class CacheTrimStep(Func<string> folder, Func<long> limitBytes) : ICleanupStep
|
||||
{
|
||||
public const string StepName = "cache-trim";
|
||||
|
||||
/// <summary>Folders of the cache the trim leaves whole.</summary>
|
||||
public static IReadOnlyList<string> Kept { get; } = ["proxies", "render-node", "server-import"];
|
||||
|
||||
public string Name => StepName;
|
||||
|
||||
public Task<string> RunAsync(CleanupContext context, CleanupParameters parameters)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var limit = limitBytes();
|
||||
return Task.Run(() =>
|
||||
{
|
||||
var result = CacheStore.Trim(folder(), limit, Kept, context.Cancellation);
|
||||
if (result is null) return Loc.L("Jobs.Log.CacheNotOwned");
|
||||
return result.Deleted == 0
|
||||
? Loc.L("Jobs.Log.CacheKept", Gigabytes(result.After), Gigabytes(limit))
|
||||
: Loc.L("Jobs.Log.CacheTrimmed", Gigabytes(result.After), Gigabytes(limit), Gigabytes(result.Freed));
|
||||
}, context.Cancellation);
|
||||
}
|
||||
|
||||
/// <summary>"12.4 GB" in the binary gigabytes of Settings › Storage › Cache limit.</summary>
|
||||
private static string Gigabytes(long bytes) => Loc.L("Common.Size.GB", (bytes / (double)(1L << 30)).ToString("0.#", Loc.Culture));
|
||||
}
|
||||
@@ -13,9 +13,10 @@ public enum JobNotice
|
||||
/// <summary>
|
||||
/// Which job endings raise a toast (BRIEF §12.1 "toasts for job completion"): the long operations the user asked for
|
||||
/// end with one toast, whichever screen started them. Background work (thumbnails, proxies, light analysis, the
|
||||
/// analysis queued after an import) and scans (the archive is rescanned every 10 minutes) end silently; an import
|
||||
/// analysis queued after an import) and scans (the archive scan schedule runs every 10 minutes) end silently; an import
|
||||
/// has its own toast when it ends well, and a download shows on its Library card and Server row. Every other failure
|
||||
/// is said. Cancelled jobs were stopped on purpose.
|
||||
/// is said. A schedule's background run (owner review 2, R10: the index backup, a weekly verify) is said only when it
|
||||
/// fails, unless it is upkeep the next run repeats. Cancelled jobs were stopped on purpose.
|
||||
/// </summary>
|
||||
public static class JobNotices
|
||||
{
|
||||
@@ -26,7 +27,9 @@ public static class JobNotices
|
||||
public static JobNotice For(JobState? before, Job job)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(job);
|
||||
if (before is JobState.Done or JobState.Failed or JobState.Cancelled || job.Priority == JobPriority.Background) return JobNotice.None;
|
||||
if (before is JobState.Done or JobState.Failed or JobState.Cancelled) return JobNotice.None;
|
||||
if (job.Priority == JobPriority.Background)
|
||||
return job.ScheduleId is not null && job.State == JobState.Failed && !IsUpkeep(job.Kind) ? JobNotice.Failed : JobNotice.None;
|
||||
return job.State switch
|
||||
{
|
||||
JobState.Done when Announces(job.Kind) => JobNotice.Done,
|
||||
@@ -39,9 +42,12 @@ public static class JobNotices
|
||||
kind is JobKind.Render or JobKind.DeepAnalyse or JobKind.Verify or JobKind.Rebuild or JobKind.Maintenance or JobKind.UploadCommit
|
||||
or JobKind.Move or JobKind.Adopt;
|
||||
|
||||
/// <summary>Work that keeps the index and its previews current: the next run repeats it, the Archive screen shows what is missing.</summary>
|
||||
/// <summary>
|
||||
/// Work that keeps the index and its previews current: the next run repeats it, the Archive screen shows what is missing.
|
||||
/// Clean-ups too: the housekeeping schedule runs them again (a failed index backup is said).
|
||||
/// </summary>
|
||||
private static bool IsUpkeep(JobKind kind) =>
|
||||
kind is JobKind.Scan or JobKind.Thumbs or JobKind.Proxies or JobKind.LightAnalyse;
|
||||
kind is JobKind.Scan or JobKind.Thumbs or JobKind.Proxies or JobKind.LightAnalyse or JobKind.Cleanup;
|
||||
}
|
||||
|
||||
/// <summary>Endings said in one toast: one job, or several of a batch.</summary>
|
||||
|
||||
@@ -36,6 +36,9 @@ public sealed class JobRowViewModel : ObservableObject
|
||||
|
||||
public string Target => _entry.Job.TargetLabel ?? string.Empty;
|
||||
|
||||
/// <summary>A schedule queued the job (owner review 2, R10): the row shows a "Scheduled" pill.</summary>
|
||||
public bool IsScheduled => _entry.Job.ScheduleId is not null;
|
||||
|
||||
/// <summary>"Render · Harbour sunset → 4K HEVC": the row's name for screen readers.</summary>
|
||||
public string AccessibleName => JobText.Name(_entry.Job);
|
||||
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Chronos.Ui.Controls;assembly=Chronos.Ui"
|
||||
xmlns:v="clr-namespace:Chronos.Ui.Visuals;assembly=Chronos.Ui"
|
||||
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
|
||||
xmlns:j="clr-namespace:Chronos.App.Jobs"
|
||||
xmlns:infra="clr-namespace:Chronos.App.Infrastructure">
|
||||
<!-- The in-window schedule editor of Jobs › Scheduled (owner review 2, R10), with the dialog kit of the Archive screen. -->
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="pack://application:,,,/Chronos;component/Archive/ArchiveDialogs.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
|
||||
<!-- One editor row: the label column grows with the longest label (DESIGN §2), the controls take the rest. -->
|
||||
<Style x:Key="Grid.EditorRow" TargetType="Grid">
|
||||
<Setter Property="Margin" Value="0,0,0,10" />
|
||||
<Setter Property="MinHeight" Value="32" />
|
||||
</Style>
|
||||
|
||||
<!-- A choice of the action list: one this PC cannot run is disabled, its reason in the tooltip. -->
|
||||
<Style x:Key="ComboBoxItem.Action" TargetType="ComboBoxItem" BasedOn="{StaticResource {x:Type ComboBoxItem}}">
|
||||
<Setter Property="IsEnabled" Value="{Binding IsAvailable}" />
|
||||
<Setter Property="ToolTip" Value="{Binding ToolTip}" />
|
||||
<Setter Property="ToolTipService.ShowOnDisabled" Value="True" />
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding Label}" />
|
||||
<Setter Property="AutomationProperties.HelpText" Value="{Binding ToolTip}" />
|
||||
</Style>
|
||||
|
||||
<!-- A day of the week: a 44 px toggle, its full name in the tooltip. -->
|
||||
<Style x:Key="ToggleButton.Day" TargetType="ToggleButton" BasedOn="{StaticResource {x:Type ToggleButton}}">
|
||||
<Setter Property="MinWidth" Value="44" />
|
||||
<Setter Property="Padding" Value="8,0" />
|
||||
<Setter Property="Margin" Value="0,0,6,6" />
|
||||
</Style>
|
||||
|
||||
<DataTemplate DataType="{x:Type j:ScheduleEditorViewModel}">
|
||||
<Border Style="{StaticResource Border.Dialog}" Width="600" MaxHeight="720">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
|
||||
<ScrollViewer Grid.Row="1" Margin="0,14,0,0" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Focusable="False">
|
||||
<StackPanel Grid.IsSharedSizeScope="True">
|
||||
<!-- Name: a system schedule keeps its own. -->
|
||||
<Grid Style="{StaticResource Grid.EditorRow}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.Name}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<TextBox Grid.Column="1" Text="{Binding Name.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" ToolTip="{Binding Name.ToolTip}"
|
||||
MaxLength="100" AutomationProperties.Name="{l:Loc Jobs.Editor.Name}"
|
||||
Visibility="{Binding IsSystem, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding SystemName}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" ToolTip="{Binding Name.ToolTip}"
|
||||
Visibility="{Binding IsSystem, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.Action}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<ComboBox Grid.Column="1" Width="240" HorizontalAlignment="Left" ItemsSource="{Binding ActionOptions}" SelectedItem="{Binding SelectedAction}"
|
||||
DisplayMemberPath="Label" ItemContainerStyle="{StaticResource ComboBoxItem.Action}" ToolTip="{Binding ActionToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" IsEnabled="{Binding CanChangeAction}"
|
||||
AutomationProperties.Name="{l:Loc Jobs.Editor.Action}" />
|
||||
</Grid>
|
||||
|
||||
<!-- When: the kind, then its own fields. -->
|
||||
<Grid Style="{StaticResource Grid.EditorRow}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.Repeat}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<v:SegmentedControl Grid.Column="1" HorizontalAlignment="Left" SelectedIndex="{Binding KindIndex}" AutomationProperties.Name="{l:Loc Jobs.Editor.Repeat}">
|
||||
<v:SegmentedItem Content="{l:Loc Jobs.Editor.Every}" ToolTip="{l:Loc Tooltips.Jobs.Editor.KindEvery}" AutomationProperties.Name="{l:Loc Jobs.Editor.Every}" />
|
||||
<v:SegmentedItem Content="{l:Loc Jobs.Editor.Daily}" ToolTip="{l:Loc Tooltips.Jobs.Editor.KindDaily}" AutomationProperties.Name="{l:Loc Jobs.Editor.Daily}" />
|
||||
<v:SegmentedItem Content="{l:Loc Jobs.Editor.Weekly}" ToolTip="{l:Loc Tooltips.Jobs.Editor.KindWeekly}" AutomationProperties.Name="{l:Loc Jobs.Editor.Weekly}" />
|
||||
<v:SegmentedItem Content="{l:Loc Jobs.Editor.Monthly}" ToolTip="{l:Loc Tooltips.Jobs.Editor.KindMonthly}" AutomationProperties.Name="{l:Loc Jobs.Editor.Monthly}" />
|
||||
</v:SegmentedControl>
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding IsEvery, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.Interval}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal">
|
||||
<TextBox Style="{StaticResource TextBox.Number}" Text="{Binding Every.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
ToolTip="{Binding Every.ToolTip}" AutomationProperties.Name="{l:Loc Jobs.Editor.Interval}" />
|
||||
<ComboBox Width="120" Margin="8,0,0,0" ItemsSource="{Binding Units}" SelectedItem="{Binding SelectedUnit}" DisplayMemberPath="Label"
|
||||
ToolTip="{l:Loc Tooltips.Jobs.Editor.Unit}" AutomationProperties.Name="{l:Loc Jobs.Editor.Unit}" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding IsWeekly, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.Days}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Top" Margin="0,7,14,0" />
|
||||
<ItemsControl Grid.Column="1" ItemsSource="{Binding Days}" Focusable="False" AutomationProperties.Name="{l:Loc Jobs.Editor.Days}">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<WrapPanel />
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<ToggleButton Style="{StaticResource ToggleButton.Day}" Content="{Binding Label}" IsChecked="{Binding IsChecked}" ToolTip="{Binding ToolTip}"
|
||||
AutomationProperties.Name="{Binding ToolTip}" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding IsMonthly, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.DayOfMonth}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<TextBox Grid.Column="1" Style="{StaticResource TextBox.Number}" HorizontalAlignment="Left"
|
||||
Text="{Binding DayOfMonth.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" ToolTip="{Binding DayOfMonth.ToolTip}"
|
||||
AutomationProperties.Name="{l:Loc Jobs.Editor.DayOfMonth}" />
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding HasTime, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.Time}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<!-- Hours and minutes stay in their order in every language. -->
|
||||
<TextBox Grid.Column="1" Style="{StaticResource TextBox.Number}" HorizontalAlignment="Left" FlowDirection="LeftToRight"
|
||||
Text="{Binding Time.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" ToolTip="{Binding Time.ToolTip}"
|
||||
AutomationProperties.Name="{l:Loc Jobs.Editor.Time}" />
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<!-- The recurrence as the table will show it. -->
|
||||
<TextBlock Grid.Column="1" Text="{Binding WhenText}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis"
|
||||
ToolTip="{l:Loc Tooltips.Jobs.Editor.When}" AutomationProperties.LiveSetting="Polite" infra:LiveRegion.Text="{Binding WhenText}" />
|
||||
</Grid>
|
||||
|
||||
<!-- The action's parameters. -->
|
||||
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding ShowsOlderThan, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{Binding OlderThanLabel}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal">
|
||||
<TextBox Style="{StaticResource TextBox.Number}" Text="{Binding OlderThan.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
ToolTip="{Binding OlderThan.ToolTip}" AutomationProperties.Name="{Binding OlderThanLabel}" />
|
||||
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Jobs.Editor.DaysUnit}" Margin="8,0,0,0" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding ShowsPercent, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.Percent}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal">
|
||||
<TextBox Style="{StaticResource TextBox.Number}" Text="{Binding Percent.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
ToolTip="{Binding Percent.ToolTip}" AutomationProperties.Name="{l:Loc Jobs.Editor.Percent}" />
|
||||
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Jobs.Editor.PercentUnit}" Margin="8,0,0,0" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding ShowsKeep, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.Keep}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<TextBox Grid.Column="1" Style="{StaticResource TextBox.Number}" HorizontalAlignment="Left"
|
||||
Text="{Binding Keep.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" ToolTip="{Binding Keep.ToolTip}"
|
||||
AutomationProperties.Name="{l:Loc Jobs.Editor.Keep}" />
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding ShowsSteps, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.Steps}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Top" Margin="0,4,14,0" />
|
||||
<ItemsControl Grid.Column="1" ItemsSource="{Binding Steps}" Focusable="False" AutomationProperties.Name="{l:Loc Jobs.Editor.Steps}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<CheckBox Content="{Binding Label}" IsChecked="{Binding IsChecked}" ToolTip="{Binding ToolTip}" Margin="0,0,0,6" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding HasSwitches, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<WrapPanel Grid.Column="1" VerticalAlignment="Center">
|
||||
<CheckBox Content="{Binding ForceLabel}" IsChecked="{Binding Force}" ToolTip="{Binding ForceToolTip}" Margin="0,0,20,6"
|
||||
Visibility="{Binding ShowsForce, Converter={StaticResource BoolToVisibility}}" />
|
||||
<CheckBox Content="{l:Loc Jobs.Editor.Deep}" IsChecked="{Binding Deep}" ToolTip="{Binding DeepToolTip}" Margin="0,0,20,6"
|
||||
Visibility="{Binding ShowsDeep, Converter={StaticResource BoolToVisibility}}" />
|
||||
<CheckBox Content="{l:Loc Jobs.Editor.DryRun}" IsChecked="{Binding DryRun}" ToolTip="{l:Loc Tooltips.Jobs.Editor.DryRun}" Margin="0,0,20,6"
|
||||
Visibility="{Binding ShowsDryRun, Converter={StaticResource BoolToVisibility}}" />
|
||||
</WrapPanel>
|
||||
</Grid>
|
||||
|
||||
<!-- How its jobs run. -->
|
||||
<Grid Style="{StaticResource Grid.EditorRow}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.Priority}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<ComboBox Grid.Column="1" Width="160" HorizontalAlignment="Left" ItemsSource="{Binding Priorities}" SelectedItem="{Binding SelectedPriority}"
|
||||
DisplayMemberPath="Label" ToolTip="{l:Loc Tooltips.Jobs.Editor.Priority}" AutomationProperties.Name="{l:Loc Jobs.Editor.Priority}" />
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}" Margin="0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<WrapPanel Grid.Column="1" VerticalAlignment="Center">
|
||||
<CheckBox Content="{l:Loc Jobs.Editor.CatchUp}" IsChecked="{Binding CatchUp}" ToolTip="{l:Loc Tooltips.Jobs.Editor.CatchUp}" Margin="0,0,20,0" />
|
||||
<CheckBox Content="{l:Loc Jobs.Editor.Enabled}" IsChecked="{Binding Enabled}" ToolTip="{l:Loc Tooltips.Jobs.Editor.Enabled}" />
|
||||
</WrapPanel>
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
<DockPanel Grid.Row="2" Margin="0,18,0,0">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Jobs.Editor.Save}" Command="{Binding SaveCommand}"
|
||||
ToolTip="{Binding SaveToolTip}" ToolTipService.ShowOnDisabled="True" MinWidth="96" Margin="8,0,0,0" />
|
||||
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{l:Loc Tooltips.Jobs.Editor.Cancel}" IsCancel="True"
|
||||
MinWidth="96" />
|
||||
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" HorizontalAlignment="Left" />
|
||||
</DockPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ResourceDictionary>
|
||||
@@ -0,0 +1,582 @@
|
||||
using System.Collections;
|
||||
using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Jobs;
|
||||
|
||||
/// <summary>A text field of the schedule editor: checked as it is typed, its problem in the tooltip (DESIGN §4 inputs).</summary>
|
||||
public sealed class ScheduleField : ObservableObject, INotifyDataErrorInfo
|
||||
{
|
||||
private readonly Func<string, string?> _validate;
|
||||
private readonly Func<string> _toolTip;
|
||||
private string _text;
|
||||
private string? _error;
|
||||
|
||||
public ScheduleField(string text, Func<string, string?> validate, Func<string> toolTip)
|
||||
{
|
||||
_text = text;
|
||||
_validate = validate;
|
||||
_toolTip = toolTip;
|
||||
_error = validate(text);
|
||||
}
|
||||
|
||||
/// <summary>The text changed, or its problem did.</summary>
|
||||
public event Action? Changed;
|
||||
|
||||
public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged;
|
||||
|
||||
public string Text
|
||||
{
|
||||
get => _text;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _text, value ?? string.Empty)) return;
|
||||
Validate();
|
||||
Changed?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The problem of the text; null when it is valid.</summary>
|
||||
public string? Error => _error;
|
||||
|
||||
public bool HasErrors => _error is not null;
|
||||
|
||||
/// <summary>The problem while invalid, otherwise what the field is for.</summary>
|
||||
public string ToolTip => _error ?? _toolTip();
|
||||
|
||||
public IEnumerable GetErrors(string? propertyName) =>
|
||||
_error is not null && propertyName is null or "" or nameof(Text) ? new[] { _error } : Array.Empty<string>();
|
||||
|
||||
/// <summary>Checks the text again (a rule it depends on changed: the interval's unit).</summary>
|
||||
public void Validate()
|
||||
{
|
||||
var error = _validate(_text);
|
||||
if (error == _error) return;
|
||||
_error = error;
|
||||
OnPropertyChanged(nameof(Error));
|
||||
OnPropertyChanged(nameof(HasErrors));
|
||||
OnPropertyChanged(nameof(ToolTip));
|
||||
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Text)));
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
internal void Refresh()
|
||||
{
|
||||
_error = _validate(_text);
|
||||
OnPropertyChanged(string.Empty);
|
||||
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Text)));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An action of the editor's list: unavailable ones are shown disabled, their reason in the tooltip.</summary>
|
||||
public sealed record ScheduleActionOption(string Name, bool IsAvailable, string? Reason)
|
||||
{
|
||||
public string Label => ScheduleText.Action(Name);
|
||||
|
||||
public string ToolTip => IsAvailable ? ScheduleText.ActionToolTip(Name) : ScheduleText.Unavailable(Reason);
|
||||
|
||||
public override string ToString() => Label;
|
||||
}
|
||||
|
||||
/// <summary>A checkable choice of the editor (a day of the week, a clean-up step).</summary>
|
||||
public sealed class ScheduleChoice<T>(T value, Func<string> label, Func<string> toolTip, bool isChecked, Action changed) : ObservableObject
|
||||
{
|
||||
private bool _isChecked = isChecked;
|
||||
|
||||
public T Value { get; } = value;
|
||||
|
||||
public string Label => label();
|
||||
|
||||
public string ToolTip => toolTip();
|
||||
|
||||
public bool IsChecked
|
||||
{
|
||||
get => _isChecked;
|
||||
set
|
||||
{
|
||||
if (Set(ref _isChecked, value)) changed();
|
||||
}
|
||||
}
|
||||
|
||||
internal void Refresh() => OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The in-window editor of a schedule (owner review 2, R10): its name (a system schedule keeps its own), its action (those
|
||||
/// this PC cannot run are disabled, their reason in the tooltip), when it runs (every n minutes, hours or days; daily,
|
||||
/// weekly or monthly at a time of this PC's zone), the action's parameters, the priority of its jobs, catch-up and on/off.
|
||||
/// Every field is checked as it is typed with the scheduler's own limits; Save stays off while one is invalid and its
|
||||
/// tooltip names the first problem. One primary action, one way out (Cancel, Esc).
|
||||
/// </summary>
|
||||
public sealed class ScheduleEditorViewModel : LocalizedViewModel
|
||||
{
|
||||
private readonly SchedulesViewModel _owner;
|
||||
private readonly ScheduleDto? _schedule;
|
||||
private ScheduleActionOption _action;
|
||||
private int _kindIndex;
|
||||
private SettingsOption<RecurrenceUnit> _unit;
|
||||
private SettingsOption<JobPriority> _priority;
|
||||
private bool _catchUp;
|
||||
private bool _enabled;
|
||||
private bool _force;
|
||||
private bool _deep;
|
||||
private bool _dryRun;
|
||||
private bool _isBusy;
|
||||
private string? _errorText;
|
||||
private string? _errorToolTip;
|
||||
private IReadOnlyList<ScheduleChoice<string>> _steps = [];
|
||||
|
||||
internal ScheduleEditorViewModel(SchedulesViewModel owner, ScheduleDto? schedule)
|
||||
{
|
||||
_owner = owner;
|
||||
_schedule = schedule;
|
||||
ActionOptions = BuildActionOptions();
|
||||
_action = schedule is not null
|
||||
? ActionOptions.FirstOrDefault(o => o.Name == schedule.Action) ?? new ScheduleActionOption(schedule.Action, false, null)
|
||||
: ActionOptions.FirstOrDefault(o => o.IsAvailable) ?? ActionOptions[0];
|
||||
|
||||
Name = new ScheduleField(schedule is null ? string.Empty : schedule.Name, ValidateName, () => Loc.L(IsSystem ? "Tooltips.Jobs.Editor.SystemName" : "Tooltips.Jobs.Editor.Name"));
|
||||
|
||||
// When: the stored recurrence, or every day at 03:00 for a new schedule.
|
||||
var recurrence = ScheduleMapping.FromDto(schedule?.Recurrence) ?? ScheduleRecurrence.DailyAt(new TimeOnly(3, 0));
|
||||
_kindIndex = (int)recurrence.Kind;
|
||||
Units = BuildUnits();
|
||||
_unit = Units.First(u => u.Value == (recurrence.Kind == RecurrenceKind.Every ? recurrence.Unit : RecurrenceUnit.Hours));
|
||||
Every = new ScheduleField(Number(recurrence.Kind == RecurrenceKind.Every ? recurrence.Every : 6), ValidateEvery, () => Loc.L("Tooltips.Jobs.Editor.Every"));
|
||||
Time = new ScheduleField(recurrence.Time.ToString("HH:mm", CultureInfo.InvariantCulture), ValidateTime, () => Loc.L("Tooltips.Jobs.Editor.Time"));
|
||||
var weekly = recurrence.Kind == RecurrenceKind.Weekly ? recurrence.Days : [DayOfWeek.Monday];
|
||||
var first = Loc.Culture.DateTimeFormat.FirstDayOfWeek;
|
||||
Days = [.. Enumerable.Range(0, 7).Select(i => (DayOfWeek)(((int)first + i) % 7)).Select(d =>
|
||||
new ScheduleChoice<DayOfWeek>(d, () => ScheduleText.DayShort(d), () => ScheduleText.DayLong(d), weekly.Contains(d), OnChanged))];
|
||||
DayOfMonth = new ScheduleField(Number(recurrence.Kind == RecurrenceKind.Monthly ? recurrence.DayOfMonth : 1), ValidateDayOfMonth,
|
||||
() => Loc.L("Tooltips.Jobs.Editor.DayOfMonth"));
|
||||
|
||||
OlderThan = new ScheduleField(string.Empty, v => ValidateNumber(v, 0, ScheduleActions.MaxDays), () => Loc.L(IsVerify ? "Tooltips.Jobs.Editor.Unverified" : "Tooltips.Jobs.Editor.OlderThan"));
|
||||
Percent = new ScheduleField(string.Empty, v => ValidateNumber(v, 1, 100), () => Loc.L("Tooltips.Jobs.Editor.Percent"));
|
||||
Keep = new ScheduleField(string.Empty, v => ValidateNumber(v, 1, 100), () => Loc.L("Tooltips.Jobs.Editor.Keep"));
|
||||
LoadParameters(schedule?.Parameters ?? ScheduleActions.Defaults(_action.Name));
|
||||
|
||||
Priorities = BuildPriorities();
|
||||
var priority = schedule is not null && JobWire.TryParsePriority(schedule.Priority, out var stored) ? stored : JobPriority.Background;
|
||||
_priority = Priorities.First(p => p.Value == priority);
|
||||
_catchUp = schedule?.CatchUp ?? true;
|
||||
_enabled = schedule?.Enabled ?? true;
|
||||
|
||||
foreach (var field in new[] { Name, Every, Time, DayOfMonth, OlderThan, Percent, Keep }) field.Changed += OnChanged;
|
||||
SaveCommand = new AsyncRelayCommand(SaveAsync, () => !_isBusy && Problem() is null);
|
||||
CloseCommand = new RelayCommand(() => _owner.CloseEditor(this), () => !_isBusy);
|
||||
}
|
||||
|
||||
/// <summary>The schedule edited; null for a new one.</summary>
|
||||
public Guid? ScheduleId => _schedule?.Id;
|
||||
|
||||
public bool IsNew => _schedule is null;
|
||||
|
||||
/// <summary>A system schedule keeps its name and action.</summary>
|
||||
public bool IsSystem => _schedule?.SystemKey is not null;
|
||||
|
||||
public string Heading => _schedule is null ? Loc.L("Jobs.Schedule.New") : Loc.L("Jobs.Editor.Heading", ScheduleText.Name(_schedule));
|
||||
|
||||
public ScheduleField Name { get; }
|
||||
|
||||
/// <summary>The name shown for a system schedule, which is not edited.</summary>
|
||||
public string SystemName => _schedule is null ? string.Empty : ScheduleText.Name(_schedule);
|
||||
|
||||
/// <summary>Every action, with whether this PC runs it as last read; built again when that or the UI language changes.</summary>
|
||||
public IReadOnlyList<ScheduleActionOption> ActionOptions { get; private set; }
|
||||
|
||||
public ScheduleActionOption SelectedAction
|
||||
{
|
||||
get => _action;
|
||||
set
|
||||
{
|
||||
if (value is null || !value.IsAvailable || IsSystem || !Set(ref _action, value)) return;
|
||||
// Another action starts from its own defaults, as the scheduler does.
|
||||
LoadParameters(ScheduleActions.Defaults(value.Name));
|
||||
OnPropertyChanged(string.Empty);
|
||||
OnChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public string ActionToolTip => IsSystem ? Loc.L("Tooltips.Jobs.Editor.SystemAction") : _action.ToolTip;
|
||||
|
||||
/// <summary>The action can be chosen (not for a system schedule).</summary>
|
||||
public bool CanChangeAction => !IsSystem;
|
||||
|
||||
// ---------------- When ----------------
|
||||
|
||||
/// <summary>0 every, 1 daily, 2 weekly, 3 monthly (the segmented control's index; <see cref="RecurrenceKind"/> order).</summary>
|
||||
public int KindIndex
|
||||
{
|
||||
get => _kindIndex;
|
||||
set
|
||||
{
|
||||
if (value is < 0 or > 3 || !Set(ref _kindIndex, value)) return;
|
||||
OnPropertyChanged(nameof(IsEvery));
|
||||
OnPropertyChanged(nameof(HasTime));
|
||||
OnPropertyChanged(nameof(IsWeekly));
|
||||
OnPropertyChanged(nameof(IsMonthly));
|
||||
OnChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public RecurrenceKind Kind => (RecurrenceKind)_kindIndex;
|
||||
|
||||
public bool IsEvery => Kind == RecurrenceKind.Every;
|
||||
public bool HasTime => Kind != RecurrenceKind.Every;
|
||||
public bool IsWeekly => Kind == RecurrenceKind.Weekly;
|
||||
public bool IsMonthly => Kind == RecurrenceKind.Monthly;
|
||||
|
||||
public ScheduleField Every { get; }
|
||||
|
||||
public IReadOnlyList<SettingsOption<RecurrenceUnit>> Units { get; private set; }
|
||||
|
||||
public SettingsOption<RecurrenceUnit> SelectedUnit
|
||||
{
|
||||
get => _unit;
|
||||
set
|
||||
{
|
||||
if (value is null || !Set(ref _unit, value)) return;
|
||||
Every.Validate();
|
||||
OnChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public ScheduleField Time { get; }
|
||||
|
||||
/// <summary>The days of a weekly schedule, from the first day of the UI language's week.</summary>
|
||||
public IReadOnlyList<ScheduleChoice<DayOfWeek>> Days { get; }
|
||||
|
||||
public ScheduleField DayOfMonth { get; }
|
||||
|
||||
/// <summary>"Daily at 03:00": the recurrence as the table will show it; "—" while a field is invalid.</summary>
|
||||
public string WhenText => Recurrence() is { } recurrence ? ScheduleText.When(recurrence) : "—";
|
||||
|
||||
// ---------------- Parameters ----------------
|
||||
|
||||
public bool ShowsForce => _action.Name is ScheduleActions.Scan or ScheduleActions.Thumbnails or ScheduleActions.Proxies;
|
||||
/// <summary>Analysis only: a scan's deep analysis follows Settings › Analysis › After a scan at every run.</summary>
|
||||
public bool ShowsDeep => _action.Name == ScheduleActions.Analysis;
|
||||
public bool ShowsOlderThan => _action.Name is ScheduleActions.Verify or ScheduleActions.Cleanup;
|
||||
public bool ShowsPercent => _action.Name == ScheduleActions.Verify;
|
||||
public bool ShowsDryRun => _action.Name == ScheduleActions.Maintenance;
|
||||
public bool ShowsKeep => _action.Name == ScheduleActions.Backup;
|
||||
public bool ShowsSteps => _action.Name == ScheduleActions.Cleanup;
|
||||
|
||||
/// <summary>The action has on/off parameters (full scan, deep analysis, report only), shown together on one row.</summary>
|
||||
public bool HasSwitches => ShowsForce || ShowsDeep || ShowsDryRun;
|
||||
|
||||
public bool Force
|
||||
{
|
||||
get => _force;
|
||||
set => Set(ref _force, value);
|
||||
}
|
||||
|
||||
public string ForceLabel => Loc.L(_action.Name == ScheduleActions.Scan ? "Jobs.Editor.FullScan" : "Jobs.Editor.RebuildAll");
|
||||
|
||||
public string ForceToolTip => Loc.L(_action.Name == ScheduleActions.Scan ? "Tooltips.Jobs.Editor.FullScan" : "Tooltips.Jobs.Editor.RebuildAll");
|
||||
|
||||
public bool Deep
|
||||
{
|
||||
get => _deep;
|
||||
set => Set(ref _deep, value);
|
||||
}
|
||||
|
||||
public string DeepToolTip => Loc.L("Tooltips.Jobs.Editor.DeepAnalysis");
|
||||
|
||||
public bool DryRun
|
||||
{
|
||||
get => _dryRun;
|
||||
set => Set(ref _dryRun, value);
|
||||
}
|
||||
|
||||
public ScheduleField OlderThan { get; }
|
||||
|
||||
public string OlderThanLabel => Loc.L(IsVerify ? "Jobs.Editor.Unverified" : "Jobs.Editor.OlderThan");
|
||||
|
||||
public ScheduleField Percent { get; }
|
||||
|
||||
public ScheduleField Keep { get; }
|
||||
|
||||
/// <summary>The clean-up steps this PC runs, those of the schedule checked.</summary>
|
||||
public IReadOnlyList<ScheduleChoice<string>> Steps
|
||||
{
|
||||
get => _steps;
|
||||
private set => Set(ref _steps, value);
|
||||
}
|
||||
|
||||
// ---------------- Options ----------------
|
||||
|
||||
public IReadOnlyList<SettingsOption<JobPriority>> Priorities { get; private set; }
|
||||
|
||||
public SettingsOption<JobPriority> SelectedPriority
|
||||
{
|
||||
get => _priority;
|
||||
set
|
||||
{
|
||||
if (value is not null) Set(ref _priority, value);
|
||||
}
|
||||
}
|
||||
|
||||
public bool CatchUp
|
||||
{
|
||||
get => _catchUp;
|
||||
set => Set(ref _catchUp, value);
|
||||
}
|
||||
|
||||
public bool Enabled
|
||||
{
|
||||
get => _enabled;
|
||||
set => Set(ref _enabled, value);
|
||||
}
|
||||
|
||||
// ---------------- Save ----------------
|
||||
|
||||
public ICommand SaveCommand { get; }
|
||||
|
||||
/// <summary>Cancel: closes without saving.</summary>
|
||||
public ICommand CloseCommand { get; }
|
||||
|
||||
public string SaveToolTip => Problem() ?? Loc.L(IsNew ? "Tooltips.Jobs.Editor.Create" : "Tooltips.Jobs.Editor.Save");
|
||||
|
||||
public bool IsBusy
|
||||
{
|
||||
get => _isBusy;
|
||||
private set
|
||||
{
|
||||
if (!Set(ref _isBusy, value)) return;
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Why the last save did not happen; null when nothing failed.</summary>
|
||||
public string? ErrorText
|
||||
{
|
||||
get => _errorText;
|
||||
private set => Set(ref _errorText, value);
|
||||
}
|
||||
|
||||
public string? ErrorToolTip
|
||||
{
|
||||
get => _errorToolTip;
|
||||
private set => Set(ref _errorToolTip, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The first invalid field's problem, in the order of the dialog (name, when, parameters); null when the schedule can
|
||||
/// be saved.
|
||||
/// </summary>
|
||||
public string? Problem()
|
||||
{
|
||||
if (!IsSystem && Name.Error is { } name) return name;
|
||||
switch (Kind)
|
||||
{
|
||||
case RecurrenceKind.Every when Every.Error is { } every:
|
||||
return every;
|
||||
case RecurrenceKind.Every:
|
||||
break;
|
||||
default:
|
||||
if (Time.Error is { } time) return time;
|
||||
if (Kind == RecurrenceKind.Weekly && !Days.Any(d => d.IsChecked)) return Loc.L("Tooltips.Jobs.Editor.NoDays");
|
||||
if (Kind == RecurrenceKind.Monthly && DayOfMonth.Error is { } day) return day;
|
||||
break;
|
||||
}
|
||||
if (ShowsOlderThan && OlderThan.Error is { } older) return older;
|
||||
if (ShowsPercent && Percent.Error is { } percent) return percent;
|
||||
if (ShowsKeep && Keep.Error is { } keep) return keep;
|
||||
if (ShowsSteps && !Steps.Any(s => s.IsChecked)) return Loc.L("Tooltips.Jobs.Editor.NoSteps");
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The recurrence the fields describe; null while one of them is invalid.</summary>
|
||||
public RecurrenceDto? Recurrence()
|
||||
{
|
||||
var time = Time.Error is null && TryTime(Time.Text, out var at) ? at.ToString("HH:mm", CultureInfo.InvariantCulture) : null;
|
||||
RecurrenceDto? dto = Kind switch
|
||||
{
|
||||
RecurrenceKind.Every when TryNumber(Every.Text, out var every) => new RecurrenceDto("every", Every: every, Unit: ScheduleMapping.Unit(_unit.Value)),
|
||||
RecurrenceKind.Daily when time is not null => new RecurrenceDto("daily", Time: time),
|
||||
RecurrenceKind.Weekly when time is not null && Days.Any(d => d.IsChecked) =>
|
||||
new RecurrenceDto("weekly", Time: time, Days: [.. Days.Where(d => d.IsChecked).Select(d => ScheduleRecurrence.DayName(d.Value))]),
|
||||
RecurrenceKind.Monthly when time is not null && TryNumber(DayOfMonth.Text, out var day) => new RecurrenceDto("monthly", Time: time, DayOfMonth: day),
|
||||
_ => null,
|
||||
};
|
||||
return ScheduleMapping.FromDto(dto) is not null ? dto : null;
|
||||
}
|
||||
|
||||
/// <summary>The action's parameters as the fields hold them (only the action's own).</summary>
|
||||
public ScheduleParametersDto Parameters() => ScheduleActions.Normalize(_action.Name, new ScheduleParametersDto(
|
||||
OlderThanDays: ShowsOlderThan && TryNumber(OlderThan.Text, out var days) ? days : null,
|
||||
Percent: ShowsPercent && TryNumber(Percent.Text, out var percent) ? percent : null,
|
||||
Deep: ShowsDeep ? _deep : null,
|
||||
DryRun: ShowsDryRun ? _dryRun : null,
|
||||
Force: ShowsForce ? _force : null,
|
||||
Steps: ShowsSteps ? [.. Steps.Where(s => s.IsChecked).Select(s => s.Value)] : null,
|
||||
Keep: ShowsKeep && TryNumber(Keep.Text, out var keep) ? keep : null));
|
||||
|
||||
internal CreateScheduleRequest BuildCreate() =>
|
||||
new(Name.Text.Trim(), _action.Name, Recurrence()!, Parameters(), _catchUp, JobWire.Priority(_priority.Value), _enabled);
|
||||
|
||||
/// <summary>Every field the dialog shows; a system schedule's name and action are left out (they stay).</summary>
|
||||
internal UpdateScheduleRequest BuildUpdate() =>
|
||||
new(IsSystem ? null : Name.Text.Trim(), IsSystem ? null : _action.Name, Recurrence(), Parameters(), _catchUp, JobWire.Priority(_priority.Value), _enabled);
|
||||
|
||||
/// <summary>Whether this PC runs each action was read again (<see cref="SchedulesViewModel.RefreshActionsAsync"/>).</summary>
|
||||
internal void RefreshActions() => RebuildActionOptions();
|
||||
|
||||
protected override void OnLanguageChanged()
|
||||
{
|
||||
foreach (var field in new[] { Name, Every, Time, DayOfMonth, OlderThan, Percent, Keep }) field.Refresh();
|
||||
foreach (var day in Days) day.Refresh();
|
||||
foreach (var step in Steps) step.Refresh();
|
||||
// The dropdowns' choices carry their labels: new ones in the new language, the same values chosen. Each list is
|
||||
// announced before its choice, so a dropdown finds the choice among its items.
|
||||
RebuildActionOptions();
|
||||
Units = BuildUnits();
|
||||
_unit = Units.First(u => u.Value == _unit.Value);
|
||||
OnPropertyChanged(nameof(Units));
|
||||
OnPropertyChanged(nameof(SelectedUnit));
|
||||
Priorities = BuildPriorities();
|
||||
_priority = Priorities.First(p => p.Value == _priority.Value);
|
||||
OnPropertyChanged(nameof(Priorities));
|
||||
OnPropertyChanged(nameof(SelectedPriority));
|
||||
base.OnLanguageChanged();
|
||||
}
|
||||
|
||||
/// <summary>The actions again, from the owner's last read; the chosen one stays chosen.</summary>
|
||||
private void RebuildActionOptions()
|
||||
{
|
||||
ActionOptions = BuildActionOptions();
|
||||
_action = ActionOptions.FirstOrDefault(o => o.Name == _action.Name) ?? _action;
|
||||
OnPropertyChanged(nameof(ActionOptions));
|
||||
OnPropertyChanged(nameof(SelectedAction));
|
||||
OnPropertyChanged(nameof(ActionToolTip));
|
||||
}
|
||||
|
||||
private ScheduleActionOption[] BuildActionOptions()
|
||||
{
|
||||
var available = _owner.Actions;
|
||||
return [.. ScheduleActions.All.Select(a => available.FirstOrDefault(x => x.Name == a) is { } info
|
||||
? new ScheduleActionOption(a, info.Available, info.Reason)
|
||||
: new ScheduleActionOption(a, true, null))];
|
||||
}
|
||||
|
||||
private static SettingsOption<RecurrenceUnit>[] BuildUnits() =>
|
||||
[.. Enum.GetValues<RecurrenceUnit>().Select(u => new SettingsOption<RecurrenceUnit>(u, Loc.L("Jobs.Editor.Unit." + u)))];
|
||||
|
||||
private static SettingsOption<JobPriority>[] BuildPriorities() =>
|
||||
[.. new[] { JobPriority.Background, JobPriority.Normal, JobPriority.User }.Select(p => new SettingsOption<JobPriority>(p, ScheduleText.Priority(p)))];
|
||||
|
||||
private bool IsVerify => _action.Name == ScheduleActions.Verify;
|
||||
|
||||
/// <summary>Save: the schedule as the fields hold it; the editor closes once it is stored, or says why it was not.</summary>
|
||||
internal async Task SaveAsync()
|
||||
{
|
||||
if (Problem() is not null) return;
|
||||
IsBusy = true;
|
||||
ErrorText = null;
|
||||
ErrorToolTip = null;
|
||||
try
|
||||
{
|
||||
var result = await _owner.SaveAsync(this);
|
||||
if (result.Problem is { } problem)
|
||||
{
|
||||
ErrorText = Loc.L("Jobs.Editor.Refused");
|
||||
ErrorToolTip = Loc.L("Tooltips.Jobs.Editor.Refused", problem);
|
||||
return;
|
||||
}
|
||||
IsBusy = false;
|
||||
_owner.CloseEditor(this);
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException)
|
||||
{
|
||||
Log.Warning("schedules", "A schedule could not be saved", ex);
|
||||
ErrorText = Loc.L("Jobs.Editor.SaveFailed");
|
||||
ErrorToolTip = ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Fills the parameter fields from <paramref name="parameters"/> (normalised for the current action).</summary>
|
||||
private void LoadParameters(ScheduleParametersDto parameters)
|
||||
{
|
||||
var p = ScheduleActions.Normalize(_action.Name, parameters);
|
||||
var defaults = ScheduleActions.Defaults(ScheduleActions.Verify);
|
||||
_force = p.Force ?? false;
|
||||
_deep = p.Deep ?? false;
|
||||
_dryRun = p.DryRun ?? false;
|
||||
OlderThan.Text = Number(p.OlderThanDays ?? defaults.OlderThanDays ?? 30);
|
||||
// Its tooltip names what the days count (unverified, or older), which follows the action.
|
||||
OlderThan.Refresh();
|
||||
Percent.Text = Number(p.Percent ?? defaults.Percent ?? 100);
|
||||
Keep.Text = Number(p.Keep ?? DatabaseBackups.Keep);
|
||||
var chosen = p.Steps ?? [];
|
||||
// The steps this PC runs, then any the schedule names that it does not (kept, shown by their wire name).
|
||||
var names = _owner.Steps.Concat(chosen.Where(s => !_owner.Steps.Contains(s))).ToList();
|
||||
Steps = [.. names.Select(s => new ScheduleChoice<string>(s, () => ScheduleText.Step(s), () => ScheduleText.StepToolTip(s), chosen.Contains(s), OnChanged))];
|
||||
}
|
||||
|
||||
private void OnChanged()
|
||||
{
|
||||
OnPropertyChanged(nameof(WhenText));
|
||||
OnPropertyChanged(nameof(SaveToolTip));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
|
||||
private string? ValidateName(string text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text)) return Loc.L("Tooltips.Jobs.Editor.NameMissing");
|
||||
return text.Trim().Length > Scheduler.MaxNameLength ? Loc.L("Tooltips.Jobs.Editor.NameLong", Scheduler.MaxNameLength) : null;
|
||||
}
|
||||
|
||||
private string? ValidateEvery(string text)
|
||||
{
|
||||
var (min, max) = _unit.Value switch
|
||||
{
|
||||
RecurrenceUnit.Minutes => (ScheduleRecurrence.MinMinutes, ScheduleRecurrence.MaxMinutes),
|
||||
RecurrenceUnit.Days => (1, ScheduleRecurrence.MaxDays),
|
||||
_ => (1, ScheduleRecurrence.MaxHours),
|
||||
};
|
||||
return ValidateNumber(text, min, max);
|
||||
}
|
||||
|
||||
private static string? ValidateDayOfMonth(string text) => ValidateNumber(text, 1, ScheduleRecurrence.MaxDayOfMonth);
|
||||
|
||||
private static string? ValidateTime(string text) => TryTime(text, out _) ? null : Loc.L("Tooltips.Jobs.Editor.TimeInvalid");
|
||||
|
||||
private static string? ValidateNumber(string text, int min, int max) =>
|
||||
TryNumber(text, out var value) && value >= min && value <= max ? null : Loc.L("Tooltips.Jobs.Editor.Number", Number(min), Number(max));
|
||||
|
||||
private static string Number(int value) => value.ToString(CultureInfo.CurrentCulture);
|
||||
|
||||
/// <summary>A whole number as the user's culture writes it (no sign, no thousands).</summary>
|
||||
private static bool TryNumber(string text, out int value) =>
|
||||
int.TryParse(text.Trim(), NumberStyles.None, CultureInfo.CurrentCulture, out value) || int.TryParse(text.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out value);
|
||||
|
||||
/// <summary>"03:00", "3:00", "3.00": hours and minutes of a 24-hour clock.</summary>
|
||||
internal static bool TryTime(string text, out TimeOnly time)
|
||||
{
|
||||
time = default;
|
||||
var parts = text.Trim().Split(':', '.');
|
||||
if (parts is not [var h, var m] || h.Length is < 1 or > 2 || m.Length != 2) return false;
|
||||
if (!int.TryParse(h, NumberStyles.None, CultureInfo.InvariantCulture, out var hour) || !int.TryParse(m, NumberStyles.None, CultureInfo.InvariantCulture, out var minute)
|
||||
|| hour > 23 || minute > 59)
|
||||
return false;
|
||||
time = new TimeOnly(hour, minute);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// One row of Jobs › Scheduled (owner review 2, R10): the on/off switch, name, action, when it runs, the next run and the
|
||||
/// last result, and its commands (Run now, Edit, then Reset for a system schedule or Delete for one the user created).
|
||||
/// </summary>
|
||||
public sealed class ScheduleRowViewModel : ObservableObject
|
||||
{
|
||||
private readonly SchedulesViewModel _owner;
|
||||
private ScheduleDto _schedule;
|
||||
private Job? _lastJob;
|
||||
private long _lastJobStamp;
|
||||
private bool _isEnabled;
|
||||
|
||||
internal ScheduleRowViewModel(ScheduleDto schedule, SchedulesViewModel owner)
|
||||
{
|
||||
_schedule = schedule;
|
||||
_owner = owner;
|
||||
_isEnabled = schedule.Enabled;
|
||||
RunNowCommand = new AsyncRelayCommand(() => owner.RunNowAsync(this), () => IsAvailable);
|
||||
EditCommand = new RelayCommand(() => owner.Edit(this));
|
||||
DeleteCommand = new AsyncRelayCommand(() => owner.DeleteAsync(this), () => !IsSystem);
|
||||
ResetCommand = new AsyncRelayCommand(() => owner.ResetAsync(this), () => IsSystem);
|
||||
}
|
||||
|
||||
public ScheduleDto Schedule => _schedule;
|
||||
public Guid Id => _schedule.Id;
|
||||
|
||||
/// <summary>A system schedule: one of the host's timers, reset instead of deleted.</summary>
|
||||
public bool IsSystem => _schedule.SystemKey is not null;
|
||||
|
||||
/// <summary>The job the last run queued, when it is known.</summary>
|
||||
public Job? LastJob => _lastJob;
|
||||
|
||||
public string Name => ScheduleText.Name(_schedule);
|
||||
|
||||
public string NameToolTip => IsSystem ? Loc.L("Tooltips.Jobs.Schedule.System", Name) : Name;
|
||||
|
||||
public string ActionText => ScheduleText.Action(_schedule.Action);
|
||||
|
||||
/// <summary>What the action does, or why this PC does not run it.</summary>
|
||||
public string ActionToolTip => IsAvailable ? ScheduleText.ActionToolTip(_schedule.Action) : ScheduleText.Unavailable(_owner.UnavailableReason(_schedule.Action));
|
||||
|
||||
/// <summary>This PC runs the schedule's action.</summary>
|
||||
public bool IsAvailable => _owner.IsAvailable(_schedule.Action);
|
||||
|
||||
public string WhenText => ScheduleText.When(_schedule.Recurrence);
|
||||
|
||||
/// <summary>When it runs, whether a missed run is caught up, and the priority of its jobs.</summary>
|
||||
public string WhenToolTip => string.Join(Loc.Separator, WhenText,
|
||||
Loc.L(_schedule.CatchUp ? "Tooltips.Jobs.Schedule.CatchUpOn" : "Tooltips.Jobs.Schedule.CatchUpOff"),
|
||||
Loc.L("Tooltips.Jobs.Schedule.PriorityIs", ScheduleText.Priority(Priority)));
|
||||
|
||||
public string NextText => ScheduleText.Next(_schedule.NextRun, _schedule.Enabled);
|
||||
|
||||
public string NextToolTip => !_schedule.Enabled ? Loc.L("Tooltips.Jobs.Schedule.NextOff")
|
||||
: _schedule.NextRun is { } next ? Loc.L("Tooltips.Jobs.Schedule.Next", Formatting.Date(next) + " " + Formatting.TimeOfDay(next))
|
||||
: Loc.L("Tooltips.Jobs.Schedule.NextPending");
|
||||
|
||||
public string LastText => ScheduleText.Outcome(_schedule.LastOutcome, _lastJob);
|
||||
|
||||
public string LastToolTip => ScheduleText.OutcomeToolTip(_schedule.LastOutcome, _schedule.LastRun, _lastJob);
|
||||
|
||||
public StatusKind LastKind => ScheduleText.OutcomeKind(_schedule.LastOutcome, _lastJob);
|
||||
|
||||
/// <summary>Off, a schedule never runs by itself (Run now still runs it). Turning it on or off saves at once.</summary>
|
||||
public bool IsEnabled
|
||||
{
|
||||
get => _isEnabled;
|
||||
set
|
||||
{
|
||||
if (Set(ref _isEnabled, value)) _ = _owner.SetEnabledAsync(this, value);
|
||||
}
|
||||
}
|
||||
|
||||
public string EnabledToolTip => Loc.L(_isEnabled ? "Tooltips.Jobs.Schedule.EnabledOn" : "Tooltips.Jobs.Schedule.EnabledOff");
|
||||
|
||||
/// <summary>"Index backup · Index backup · Daily at 03:00": the row's name for screen readers.</summary>
|
||||
public string AccessibleName => string.Join(Loc.Separator, Name, ActionText, WhenText);
|
||||
|
||||
public ICommand RunNowCommand { get; }
|
||||
public ICommand EditCommand { get; }
|
||||
public ICommand DeleteCommand { get; }
|
||||
public ICommand ResetCommand { get; }
|
||||
|
||||
public string RunNowToolTip => IsAvailable ? Loc.L("Tooltips.Jobs.Schedule.RunNow") : ScheduleText.Unavailable(_owner.UnavailableReason(_schedule.Action));
|
||||
|
||||
/// <summary>"Run now: Index backup", what each row button is called for screen readers.</summary>
|
||||
public string RunNowName => Loc.L("Jobs.ActionFor", Loc.L("Jobs.Schedule.RunNow"), Name);
|
||||
public string EditName => Loc.L("Jobs.ActionFor", Loc.L("Jobs.Schedule.Edit"), Name);
|
||||
public string DeleteName => Loc.L("Jobs.ActionFor", Loc.L("Jobs.Schedule.Delete"), Name);
|
||||
public string ResetName => Loc.L("Jobs.ActionFor", Loc.L("Jobs.Schedule.Reset"), Name);
|
||||
public string EnabledName => Loc.L("Jobs.ActionFor", Loc.L("Jobs.Schedule.Enabled"), Name);
|
||||
|
||||
private JobPriority Priority => JobWire.TryParsePriority(_schedule.Priority, out var priority) ? priority : JobPriority.Background;
|
||||
|
||||
/// <summary>A newer copy of the schedule (an edit, a run, a correction of its next run).</summary>
|
||||
internal void Update(ScheduleDto schedule)
|
||||
{
|
||||
if (schedule.LastJobId != _schedule.LastJobId)
|
||||
{
|
||||
// A read of the previous job no longer applies.
|
||||
_lastJob = null;
|
||||
_lastJobStamp++;
|
||||
}
|
||||
_schedule = schedule;
|
||||
_isEnabled = schedule.Enabled;
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
/// <summary>The job the last run queued changed (live, from the engine): the last result follows its state.</summary>
|
||||
internal void SetLastJob(Job? job)
|
||||
{
|
||||
if (job is not null && job.Id != _schedule.LastJobId) return;
|
||||
_lastJobStamp++;
|
||||
ShowLastJob(job);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A read of the last job from the index starts; its result applies only while nothing newer arrived (a live change,
|
||||
/// another job, a later read): see <see cref="SetLoadedLastJob"/>.
|
||||
/// </summary>
|
||||
internal long BeginLastJobRead() => ++_lastJobStamp;
|
||||
|
||||
/// <summary>The last job as the read begun at <paramref name="read"/> found it; ignored when that read is stale.</summary>
|
||||
internal void SetLoadedLastJob(Job? job, long read)
|
||||
{
|
||||
if (read != _lastJobStamp || (job is not null && job.Id != _schedule.LastJobId)) return;
|
||||
ShowLastJob(job);
|
||||
}
|
||||
|
||||
private void ShowLastJob(Job? job)
|
||||
{
|
||||
_lastJob = job;
|
||||
OnPropertyChanged(nameof(LastJob));
|
||||
OnPropertyChanged(nameof(LastText));
|
||||
OnPropertyChanged(nameof(LastToolTip));
|
||||
OnPropertyChanged(nameof(LastKind));
|
||||
}
|
||||
|
||||
/// <summary>The switch goes back to the stored state (the change was refused).</summary>
|
||||
internal void RevertEnabled()
|
||||
{
|
||||
_isEnabled = _schedule.Enabled;
|
||||
OnPropertyChanged(nameof(IsEnabled));
|
||||
OnPropertyChanged(nameof(EnabledToolTip));
|
||||
}
|
||||
|
||||
internal void Refresh() => OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
/// <summary>A job a schedule queued, in the selected schedule's last runs: kind, target, when, state, and Show in queue.</summary>
|
||||
public sealed class ScheduleRunViewModel : ObservableObject
|
||||
{
|
||||
private Job _job;
|
||||
|
||||
internal ScheduleRunViewModel(Job job, Func<Guid, Task> show)
|
||||
{
|
||||
_job = job;
|
||||
ShowCommand = new AsyncRelayCommand(() => show(_job.Id));
|
||||
}
|
||||
|
||||
public Job Job => _job;
|
||||
public Guid Id => _job.Id;
|
||||
|
||||
public string Kind => JobText.Kind(_job.Kind);
|
||||
|
||||
public string Target => _job.TargetLabel ?? string.Empty;
|
||||
|
||||
/// <summary>When the run queued it ("Today 03:00").</summary>
|
||||
public string WhenText => ScheduleText.Moment(_job.Created);
|
||||
|
||||
public string StateText => JobText.State(new JobEntry(_job));
|
||||
|
||||
public string StateToolTip => string.Join(Loc.Separator, StateText,
|
||||
_job.Error is { Length: > 0 } error ? error : Loc.L("Tooltips.Jobs.State." + _job.State));
|
||||
|
||||
public StatusKind StateKind => _job.State switch
|
||||
{
|
||||
JobState.Running => StatusKind.Running,
|
||||
JobState.Queued => StatusKind.Queued,
|
||||
JobState.Paused => StatusKind.Paused,
|
||||
JobState.Done => StatusKind.Done,
|
||||
JobState.Failed => StatusKind.Failed,
|
||||
_ => StatusKind.Offline,
|
||||
};
|
||||
|
||||
/// <summary>"Verify · Archive · 2024: done": the row for screen readers.</summary>
|
||||
public string AccessibleName => Loc.L("Jobs.Row.State", JobText.Name(_job), StateText);
|
||||
|
||||
public string ShowName => Loc.L("Jobs.ActionFor", Loc.L("Jobs.Schedule.ShowJob"), JobText.Name(_job));
|
||||
|
||||
public ICommand ShowCommand { get; }
|
||||
|
||||
internal void Update(Job job)
|
||||
{
|
||||
_job = job;
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
internal void Refresh() => OnAllPropertiesChanged();
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Housekeeping;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Ui.Controls;
|
||||
|
||||
namespace Chronos.App.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Localized texts of schedules (Jobs › Scheduled, owner review 2, R10): names, actions, clean-up steps, when they run,
|
||||
/// their next run and what their last run did. Wire names (<c>scan</c>, <c>skipped-pending</c>, <c>job-history</c>) never
|
||||
/// reach the screen; an unknown one (a newer build's) is shown as it is.
|
||||
/// </summary>
|
||||
public static class ScheduleText
|
||||
{
|
||||
/// <summary>A system schedule by its key in the user's language; a user's schedule by the name they gave it.</summary>
|
||||
public static string Name(ScheduleDto schedule)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schedule);
|
||||
return schedule.SystemKey is { } key && SystemKeyName(key) is { } name ? Loc.L(name) : schedule.Name;
|
||||
}
|
||||
|
||||
/// <summary>"Archive scan", "Index backup", …</summary>
|
||||
public static string Action(string action) => ScheduleActions.IsKnown(action) ? Loc.L("Jobs.Schedule.Action." + Pascal(action)) : action;
|
||||
|
||||
/// <summary>What the action does.</summary>
|
||||
public static string ActionToolTip(string action) =>
|
||||
ScheduleActions.IsKnown(action) ? Loc.L("Tooltips.Jobs.Schedule.Action." + Pascal(action)) : Loc.L("Tooltips.Jobs.Schedule.Unavailable.Other");
|
||||
|
||||
/// <summary>Why this PC does not run an action (<see cref="ScheduleUnavailable"/>, or a code of the host's own).</summary>
|
||||
public static string Unavailable(string? reason) => reason switch
|
||||
{
|
||||
ScheduleUnavailable.NoHandler => Loc.L("Tooltips.Jobs.Schedule.Unavailable.NoHandler"),
|
||||
ScheduleUnavailable.Postgres => Loc.L("Tooltips.Jobs.Schedule.Unavailable.Postgres"),
|
||||
ScheduleUnavailable.NoIndexFile => Loc.L("Tooltips.Jobs.Schedule.Unavailable.NoIndexFile"),
|
||||
ScheduleUnavailable.ProxiesDisabled => Loc.L("Tooltips.Jobs.Schedule.Unavailable.ProxiesDisabled"),
|
||||
_ => Loc.L("Tooltips.Jobs.Schedule.Unavailable.Other"),
|
||||
};
|
||||
|
||||
/// <summary>"Job history", "Cache trim", …: a clean-up step; an unknown one by its wire name.</summary>
|
||||
public static string Step(string step) => StepKey(step) is { } key ? Loc.L("Jobs.Schedule.Step." + key) : step;
|
||||
|
||||
public static string StepToolTip(string step) => StepKey(step) is { } key ? Loc.L("Tooltips.Jobs.Schedule.Step." + key) : step;
|
||||
|
||||
/// <summary>"Every 10 minutes", "Daily at 03:00", "Mon, Thu at 02:30", "Monthly, day 1 at 04:00".</summary>
|
||||
public static string When(RecurrenceDto? recurrence) =>
|
||||
ScheduleMapping.FromDto(recurrence) is { } parsed ? When(parsed) : Loc.L("Jobs.Schedule.When.Invalid");
|
||||
|
||||
/// <inheritdoc cref="When(RecurrenceDto?)"/>
|
||||
public static string When(ScheduleRecurrence recurrence)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(recurrence);
|
||||
return recurrence.Kind switch
|
||||
{
|
||||
RecurrenceKind.Every => Loc.Plural("Jobs.Schedule.When." + recurrence.Unit, recurrence.Every),
|
||||
RecurrenceKind.Daily => Loc.L("Jobs.Schedule.When.Daily", Time(recurrence.Time)),
|
||||
RecurrenceKind.Weekly when recurrence.Days.Count == 7 => Loc.L("Jobs.Schedule.When.Daily", Time(recurrence.Time)),
|
||||
RecurrenceKind.Weekly => Loc.L("Jobs.Schedule.When.Weekly", Days(recurrence.Days), Time(recurrence.Time)),
|
||||
_ => Loc.L("Jobs.Schedule.When.Monthly", recurrence.DayOfMonth, Time(recurrence.Time)),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Mon, Thu": the days in the order of the UI language's week, from its first day as the editor lists them (Sunday
|
||||
/// first in English, Monday first in Italian), short names of the UI language.
|
||||
/// </summary>
|
||||
public static string Days(IEnumerable<DayOfWeek> days)
|
||||
{
|
||||
var first = (int)Loc.Culture.DateTimeFormat.FirstDayOfWeek;
|
||||
return days.OrderBy(d => ((int)d - first + 7) % 7).Select(DayShort).Aggregate((a, b) => Loc.L("Jobs.Schedule.DayList", a, b));
|
||||
}
|
||||
|
||||
/// <summary>"Mon" in the UI language.</summary>
|
||||
public static string DayShort(DayOfWeek day) => Loc.Culture.DateTimeFormat.GetAbbreviatedDayName(day);
|
||||
|
||||
/// <summary>"Monday" in the UI language.</summary>
|
||||
public static string DayLong(DayOfWeek day) => Loc.Culture.DateTimeFormat.GetDayName(day);
|
||||
|
||||
/// <summary>A wall-clock time in the UI language's short format ("03:00", "3:00 AM").</summary>
|
||||
public static string Time(TimeOnly time) => DateTime.MinValue.Add(time.ToTimeSpan()).ToString("t", Loc.Culture);
|
||||
|
||||
/// <summary>
|
||||
/// The next run as the table shows it: "Today 03:00", "Tomorrow 03:00", a date and time further away, "Off" for a
|
||||
/// disabled schedule, "—" while it has none yet.
|
||||
/// </summary>
|
||||
public static string Next(DateTimeOffset? next, bool enabled)
|
||||
{
|
||||
if (!enabled) return Loc.L("Jobs.Schedule.Off");
|
||||
return next is { } at ? Moment(at) : "—";
|
||||
}
|
||||
|
||||
/// <summary>"Today 03:00", "Tomorrow 03:00", "Yesterday 03:00", or the short date and time.</summary>
|
||||
public static string Moment(DateTimeOffset at)
|
||||
{
|
||||
var local = at.ToLocalTime();
|
||||
var days = (local.Date - AppClock.Today).Days;
|
||||
var time = Formatting.TimeOfDay(at);
|
||||
return days switch
|
||||
{
|
||||
0 => Loc.L("Jobs.Schedule.Today", time),
|
||||
1 => Loc.L("Jobs.Schedule.Tomorrow", time),
|
||||
-1 => Loc.L("Jobs.Schedule.Yesterday", time),
|
||||
_ => Formatting.Date(at) + " " + time,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the last run did: the state of the job it queued when that is known ("done", "failed", "running"), else the
|
||||
/// outcome ("skipped: busy", "nothing to do", …); "never run" before the first run.
|
||||
/// </summary>
|
||||
public static string Outcome(string? outcome, Job? lastJob)
|
||||
{
|
||||
if (outcome is null) return Loc.L("Jobs.Schedule.Outcome.Never");
|
||||
if (outcome == ScheduleOutcome.Queued && lastJob is not null) return Loc.L("Jobs.State." + lastJob.State);
|
||||
if (ScheduleOutcome.IsFailed(outcome, out _)) return Loc.L("Jobs.Schedule.Outcome.Failed");
|
||||
return OutcomeKey(outcome) is { } key ? Loc.L("Jobs.Schedule.Outcome." + key) : outcome;
|
||||
}
|
||||
|
||||
/// <summary>The outcome explained, with when the last run was and the reason of a failure.</summary>
|
||||
public static string OutcomeToolTip(string? outcome, DateTimeOffset? lastRun, Job? lastJob)
|
||||
{
|
||||
if (outcome is null || lastRun is not { } at) return Loc.L("Tooltips.Jobs.Schedule.Outcome.Never");
|
||||
var when = Loc.L("Jobs.Schedule.LastRun", Moment(at));
|
||||
string why;
|
||||
if (ScheduleOutcome.IsFailed(outcome, out var reason)) why = Loc.L("Tooltips.Jobs.Schedule.Outcome.Failed", reason);
|
||||
else if (outcome == ScheduleOutcome.Queued && lastJob is { Error: { Length: > 0 } error }) why = error;
|
||||
else if (outcome == ScheduleOutcome.Queued && lastJob is not null) why = Loc.L("Tooltips.Jobs.State." + lastJob.State);
|
||||
else why = OutcomeKey(outcome) is { } key ? Loc.L("Tooltips.Jobs.Schedule.Outcome." + key) : outcome;
|
||||
return string.Join(Loc.Separator, when, why);
|
||||
}
|
||||
|
||||
/// <summary>Glyph of the last result, paired with its word.</summary>
|
||||
public static StatusKind OutcomeKind(string? outcome, Job? lastJob)
|
||||
{
|
||||
if (outcome is null) return StatusKind.Offline;
|
||||
if (ScheduleOutcome.IsFailed(outcome, out _)) return StatusKind.Failed;
|
||||
if (outcome == ScheduleOutcome.Queued && lastJob is not null)
|
||||
{
|
||||
return lastJob.State switch
|
||||
{
|
||||
JobState.Running => StatusKind.Running,
|
||||
JobState.Queued => StatusKind.Queued,
|
||||
JobState.Paused => StatusKind.Paused,
|
||||
JobState.Done => StatusKind.Done,
|
||||
JobState.Failed => StatusKind.Failed,
|
||||
_ => StatusKind.Offline,
|
||||
};
|
||||
}
|
||||
return outcome switch
|
||||
{
|
||||
ScheduleOutcome.Queued => StatusKind.Queued,
|
||||
ScheduleOutcome.SkippedNothing => StatusKind.Done,
|
||||
ScheduleOutcome.SkippedPending => StatusKind.Paused,
|
||||
ScheduleOutcome.Unavailable => StatusKind.Warning,
|
||||
_ => StatusKind.Offline,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>"Background", "Normal", "High": the priority of the jobs a schedule queues.</summary>
|
||||
public static string Priority(JobPriority priority) => Loc.L("Jobs.Schedule.Priority." + priority);
|
||||
|
||||
private static string? SystemKeyName(string key) => key switch
|
||||
{
|
||||
DesktopScheduleHost.ArchiveScan => "Jobs.Schedule.System.ArchiveScan",
|
||||
DesktopScheduleHost.IndexBackup => "Jobs.Schedule.System.IndexBackup",
|
||||
DesktopScheduleHost.Housekeeping => "Jobs.Schedule.System.Housekeeping",
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private static string? StepKey(string step) => step switch
|
||||
{
|
||||
CleanupSteps.JobHistory => "JobHistory",
|
||||
CleanupSteps.Audit => "Audit",
|
||||
CleanupSteps.TrashReport => "TrashReport",
|
||||
CacheTrimStep.StepName => "CacheTrim",
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private static string? OutcomeKey(string outcome) => outcome switch
|
||||
{
|
||||
ScheduleOutcome.Queued => "Queued",
|
||||
ScheduleOutcome.SkippedPending => "SkippedPending",
|
||||
ScheduleOutcome.SkippedOffline => "SkippedOffline",
|
||||
ScheduleOutcome.SkippedNothing => "SkippedNothing",
|
||||
ScheduleOutcome.Unavailable => "Unavailable",
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary><c>scan</c> → <c>Scan</c>: the resource name of a wire name.</summary>
|
||||
private static string Pascal(string name) => string.Concat(name.Split('-').Select(p => p.Length == 0 ? p : char.ToUpperInvariant(p[0]) + p[1..]));
|
||||
}
|
||||
@@ -0,0 +1,544 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Housekeeping;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Jobs › Scheduled (owner review 2, R10): every schedule of this PC's <see cref="Scheduler"/> (the system ones that stand
|
||||
/// for its timers first), each with its switch, next run and last result, kept current by the scheduler's events and by
|
||||
/// the jobs its runs queued; the selected schedule's last runs, each one shown in the queue on request; the in-window
|
||||
/// editor of a new or existing schedule. Calls to the scheduler run off the UI thread; their results and its events are
|
||||
/// applied on it. WPF-free apart from the commands: tests drive it with a scheduler of their own.
|
||||
/// </summary>
|
||||
public sealed class SchedulesViewModel : LocalizedViewModel
|
||||
{
|
||||
/// <summary>Runs listed for the selected schedule.</summary>
|
||||
public const int RunsShown = 20;
|
||||
|
||||
private readonly Func<Scheduler?> _scheduler;
|
||||
private readonly Func<ChronosDatabase?> _database;
|
||||
private readonly Func<ConfirmRequest, bool> _confirm;
|
||||
private readonly Action<string, string?, bool> _notify;
|
||||
private readonly Func<Guid, Task> _showJob;
|
||||
private readonly Dictionary<Guid, ScheduleRowViewModel> _rows = [];
|
||||
private SynchronizationContext? _context;
|
||||
private Scheduler? _attached;
|
||||
private IReadOnlyList<ScheduleActionDto> _actions = [];
|
||||
private IReadOnlyList<string> _steps = [];
|
||||
private ScheduleRowViewModel? _selected;
|
||||
private ScheduleEditorViewModel? _editor;
|
||||
private bool _isLoaded;
|
||||
private int _runsRequest;
|
||||
private Task? _attach;
|
||||
|
||||
/// <param name="scheduler">The running scheduler (once <see cref="AttachAsync"/> was told it runs).</param>
|
||||
/// <param name="database">The index, to read the jobs the runs queued.</param>
|
||||
/// <param name="confirm">Asks before a delete or a reset.</param>
|
||||
/// <param name="notify">A toast: title, message, whether something did not happen.</param>
|
||||
/// <param name="showJob">Shows a job in the queue tab.</param>
|
||||
public SchedulesViewModel(Func<Scheduler?> scheduler, Func<ChronosDatabase?> database, Func<ConfirmRequest, bool> confirm,
|
||||
Action<string, string?, bool> notify, Func<Guid, Task> showJob)
|
||||
{
|
||||
_scheduler = scheduler;
|
||||
_database = database;
|
||||
_confirm = confirm;
|
||||
_notify = notify;
|
||||
_showJob = showJob;
|
||||
NewCommand = new RelayCommand(New, () => IsRunning && _editor is null);
|
||||
}
|
||||
|
||||
/// <summary>A schedule changed in a way the history text depends on (the housekeeping's job-history days).</summary>
|
||||
public event Action? HistoryChanged;
|
||||
|
||||
/// <summary>System schedules first, then the user's, oldest first (the scheduler's order).</summary>
|
||||
public ObservableCollection<ScheduleRowViewModel> Rows { get; } = [];
|
||||
|
||||
/// <summary>The jobs the selected schedule queued, newest first.</summary>
|
||||
public ObservableCollection<ScheduleRunViewModel> Runs { get; } = [];
|
||||
|
||||
public ICommand NewCommand { get; }
|
||||
|
||||
public string NewToolTip => IsRunning ? Loc.L("Tooltips.Jobs.Schedule.New") : Loc.L("Tooltips.Jobs.Schedule.NotRunning");
|
||||
|
||||
/// <summary>The scheduler of this PC runs (it does not without an index, or while it failed to start).</summary>
|
||||
public bool IsRunning => _attached is not null;
|
||||
|
||||
/// <summary>The schedules were read, or it is known that there are none to read.</summary>
|
||||
public bool IsLoaded => _isLoaded;
|
||||
|
||||
public bool HasRows => Rows.Count > 0;
|
||||
|
||||
/// <summary>The empty state: the scheduler does not run here.</summary>
|
||||
public bool IsUnavailable => _isLoaded && !IsRunning;
|
||||
|
||||
public ScheduleRowViewModel? Selected
|
||||
{
|
||||
get => _selected;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _selected, value)) return;
|
||||
OnPropertyChanged(nameof(HasSelection));
|
||||
OnPropertyChanged(nameof(RunsHeading));
|
||||
RunsLoading = LoadRunsAsync();
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasSelection => _selected is not null;
|
||||
|
||||
/// <summary>"Last runs · Index backup".</summary>
|
||||
public string RunsHeading => _selected is { } row ? Loc.L("Jobs.Row.Name", Loc.L("Jobs.Schedule.Runs"), row.Name) : Loc.L("Jobs.Schedule.Runs");
|
||||
|
||||
public bool HasRuns => Runs.Count > 0;
|
||||
|
||||
public bool IsRunsEmpty => _selected is not null && Runs.Count == 0;
|
||||
|
||||
/// <summary>The open editor; null when none.</summary>
|
||||
public ScheduleEditorViewModel? Editor
|
||||
{
|
||||
get => _editor;
|
||||
private set
|
||||
{
|
||||
if (!Set(ref _editor, value)) return;
|
||||
OnPropertyChanged(nameof(IsEditorOpen));
|
||||
OnPropertyChanged(nameof(IsContentEnabled));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsEditorOpen => _editor is not null;
|
||||
|
||||
/// <summary>The screen behind an open editor takes neither clicks nor keyboard focus.</summary>
|
||||
public bool IsContentEnabled => _editor is null;
|
||||
|
||||
/// <summary>The actions with whether this PC runs them, as last read.</summary>
|
||||
public IReadOnlyList<ScheduleActionDto> Actions => _actions;
|
||||
|
||||
/// <summary>The clean-up steps this PC's clean-up jobs run.</summary>
|
||||
public IReadOnlyList<string> Steps => _steps;
|
||||
|
||||
/// <summary>
|
||||
/// Days of job history the housekeeping schedule keeps: its age limit while it is on and removes job history; null
|
||||
/// while it keeps every job; the product's default before the schedules are read.
|
||||
/// </summary>
|
||||
public int? HistoryDays
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!_isLoaded || !IsRunning) return CleanupSteps.DefaultHistoryDays;
|
||||
var housekeeping = Rows.FirstOrDefault(r => r.Schedule.SystemKey == DesktopScheduleHost.Housekeeping)?.Schedule;
|
||||
if (housekeeping is not { Enabled: true, Action: ScheduleActions.Cleanup } || housekeeping.Parameters.Steps?.Contains(CleanupSteps.JobHistory) != true)
|
||||
return null;
|
||||
return housekeeping.Parameters.OlderThanDays is > 0 and var days ? days : null;
|
||||
}
|
||||
}
|
||||
|
||||
internal Scheduler? Scheduler => _attached;
|
||||
|
||||
/// <summary>The last read of the selected schedule's runs (capture, tests).</summary>
|
||||
internal Task RunsLoading { get; private set; } = Task.CompletedTask;
|
||||
|
||||
/// <summary>Completes once <see cref="AttachAsync"/> has read the schedules, or knows there are none.</summary>
|
||||
public Task Attached => _attach ?? Task.CompletedTask;
|
||||
|
||||
/// <summary>
|
||||
/// Waits for the scheduler (<paramref name="ready"/>: true once it runs), then follows its events and reads the
|
||||
/// schedules. Call on the UI thread, once: events are brought back to it.
|
||||
/// </summary>
|
||||
public Task AttachAsync(Task<bool> ready)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ready);
|
||||
return _attach ??= AttachCoreAsync(ready);
|
||||
}
|
||||
|
||||
private async Task AttachCoreAsync(Task<bool> ready)
|
||||
{
|
||||
_context = SynchronizationContext.Current;
|
||||
bool running;
|
||||
try
|
||||
{
|
||||
running = await ready;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Warning("schedules", "The schedules did not start", ex);
|
||||
running = false;
|
||||
}
|
||||
if (!running || _scheduler() is not { } scheduler)
|
||||
{
|
||||
_isLoaded = true;
|
||||
RaiseState();
|
||||
return;
|
||||
}
|
||||
_attached = scheduler;
|
||||
scheduler.ScheduleChanged += OnScheduleChanged;
|
||||
scheduler.ScheduleDeleted += OnScheduleDeleted;
|
||||
await ReloadAsync();
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
if (_attached is not null)
|
||||
{
|
||||
_attached.ScheduleChanged -= OnScheduleChanged;
|
||||
_attached.ScheduleDeleted -= OnScheduleDeleted;
|
||||
}
|
||||
_editor?.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>Reads every schedule, the actions' availability and the jobs of the last runs again.</summary>
|
||||
public async Task ReloadAsync()
|
||||
{
|
||||
if (_attached is not { } scheduler) return;
|
||||
SchedulesDto list;
|
||||
try
|
||||
{
|
||||
list = await Task.Run(() => scheduler.ListAsync());
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException)
|
||||
{
|
||||
Log.Warning("schedules", "The schedules could not be read", ex);
|
||||
_isLoaded = true;
|
||||
RaiseState();
|
||||
return;
|
||||
}
|
||||
_actions = list.Actions;
|
||||
_steps = list.Steps ?? [];
|
||||
var wanted = list.Items.Select(s => s.Id).ToHashSet();
|
||||
foreach (var gone in _rows.Keys.Where(id => !wanted.Contains(id)).ToList()) Remove(gone);
|
||||
for (var i = 0; i < list.Items.Count; i++)
|
||||
{
|
||||
var dto = list.Items[i];
|
||||
if (!_rows.TryGetValue(dto.Id, out var row))
|
||||
{
|
||||
row = new ScheduleRowViewModel(dto, this);
|
||||
_rows[dto.Id] = row;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Every text again: the actions' availability may have changed too.
|
||||
row.Update(dto);
|
||||
}
|
||||
var at = Rows.IndexOf(row);
|
||||
if (at == i) continue;
|
||||
if (at >= 0) Rows.Move(at, i);
|
||||
else Rows.Insert(i, row);
|
||||
}
|
||||
_isLoaded = true;
|
||||
RaiseState();
|
||||
HistoryChanged?.Invoke();
|
||||
foreach (var row in Rows.ToList()) await LoadLastJobAsync(row);
|
||||
if (_selected is not null) await LoadRunsAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads again whether this PC runs each action (Jobs › Scheduled is shown: proxies may have been turned on or off,
|
||||
/// another archive chosen): the rows' Run now and tooltips, and the actions of the editor, follow it.
|
||||
/// </summary>
|
||||
public async Task RefreshActionsAsync()
|
||||
{
|
||||
if (_attached is not { } scheduler) return;
|
||||
SchedulesDto list;
|
||||
try
|
||||
{
|
||||
list = await Task.Run(() => scheduler.ListAsync());
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException)
|
||||
{
|
||||
Log.Warning("schedules", "The actions could not be read again", ex);
|
||||
return;
|
||||
}
|
||||
_actions = list.Actions;
|
||||
_steps = list.Steps ?? [];
|
||||
foreach (var row in Rows) row.Refresh();
|
||||
_editor?.RefreshActions();
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
|
||||
/// <summary>A job changed (UI thread, from the Jobs screen's flush): the last result and the last runs follow it.</summary>
|
||||
public void OnJob(Job job)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(job);
|
||||
if (job.ScheduleId is not { } id || !_rows.TryGetValue(id, out var row)) return;
|
||||
if (row.Schedule.LastJobId == job.Id) row.SetLastJob(job);
|
||||
if (!ReferenceEquals(_selected, row)) return;
|
||||
if (Runs.FirstOrDefault(r => r.Id == job.Id) is { } run)
|
||||
{
|
||||
run.Update(job);
|
||||
}
|
||||
else
|
||||
{
|
||||
Runs.Insert(0, new ScheduleRunViewModel(job, _showJob));
|
||||
while (Runs.Count > RunsShown) Runs.RemoveAt(Runs.Count - 1);
|
||||
RaiseRuns();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Whether this PC runs <paramref name="action"/> (unknown until the list is read: yes).</summary>
|
||||
public bool IsAvailable(string action) => _actions.FirstOrDefault(a => a.Name == action) is not { Available: false };
|
||||
|
||||
public string? UnavailableReason(string action) => _actions.FirstOrDefault(a => a.Name == action)?.Reason;
|
||||
|
||||
protected override void OnLanguageChanged()
|
||||
{
|
||||
foreach (var row in Rows) row.Refresh();
|
||||
foreach (var run in Runs) run.Refresh();
|
||||
HistoryChanged?.Invoke();
|
||||
base.OnLanguageChanged();
|
||||
}
|
||||
|
||||
// ---------------- Row commands ----------------
|
||||
|
||||
/// <summary>Runs the schedule now, as its next run would; says so when nothing was queued.</summary>
|
||||
internal async Task RunNowAsync(ScheduleRowViewModel row)
|
||||
{
|
||||
if (_attached is not { } scheduler) return;
|
||||
var run = await Call(() => scheduler.RunNowAsync(row.Id, null));
|
||||
if (run is null)
|
||||
{
|
||||
await ReloadAsync();
|
||||
return;
|
||||
}
|
||||
Apply(run.Schedule);
|
||||
if (run.Outcome == ScheduleOutcome.Queued) return;
|
||||
// This PC no longer runs the action: the row says so from now on.
|
||||
if (run.Outcome == ScheduleOutcome.Unavailable) await RefreshActionsAsync();
|
||||
_notify(Loc.L("Jobs.Row.Name", row.Name, ScheduleText.Outcome(run.Outcome, null)), ScheduleText.OutcomeToolTip(run.Outcome, run.Schedule.LastRun, null),
|
||||
ScheduleOutcome.IsFailed(run.Outcome, out _) || run.Outcome == ScheduleOutcome.Unavailable);
|
||||
}
|
||||
|
||||
/// <summary>Turns a schedule on or off (its switch); a refused change puts the switch back.</summary>
|
||||
internal async Task SetEnabledAsync(ScheduleRowViewModel row, bool enabled)
|
||||
{
|
||||
if (_attached is not { } scheduler) return;
|
||||
var result = await Call(() => scheduler.UpdateAsync(row.Id, new UpdateScheduleRequest(Enabled: enabled)));
|
||||
if (result?.Schedule is { } saved)
|
||||
{
|
||||
Apply(saved);
|
||||
return;
|
||||
}
|
||||
row.RevertEnabled();
|
||||
if (result is { NotFound: true }) await ReloadAsync();
|
||||
}
|
||||
|
||||
internal void Edit(ScheduleRowViewModel row)
|
||||
{
|
||||
if (_editor is not null) return;
|
||||
Editor = new ScheduleEditorViewModel(this, row.Schedule);
|
||||
}
|
||||
|
||||
/// <summary>Deletes a schedule the user created, after asking.</summary>
|
||||
internal async Task DeleteAsync(ScheduleRowViewModel row)
|
||||
{
|
||||
if (_attached is not { } scheduler || row.IsSystem) return;
|
||||
var confirmed = _confirm(new ConfirmRequest
|
||||
{
|
||||
Heading = Loc.L("Jobs.Schedule.DeleteHeading", row.Name),
|
||||
Message = Loc.L("Jobs.Schedule.DeleteMessage"),
|
||||
SafeText = Loc.L("Jobs.Schedule.Keep"),
|
||||
SafeToolTip = Loc.L("Tooltips.Jobs.Schedule.Keep"),
|
||||
ActionText = Loc.L("Jobs.Schedule.Delete"),
|
||||
ActionToolTip = Loc.L("Tooltips.Jobs.Schedule.Delete"),
|
||||
IsDestructive = true,
|
||||
});
|
||||
if (!confirmed) return;
|
||||
// Nullable: a failed call is null, not the enum's first value (Deleted), so its row stays.
|
||||
var outcome = await Call<ScheduleDeleteOutcome?>(async () => await scheduler.DeleteAsync(row.Id));
|
||||
if (outcome is ScheduleDeleteOutcome.Deleted or ScheduleDeleteOutcome.NotFound) Remove(row.Id);
|
||||
}
|
||||
|
||||
/// <summary>Puts a system schedule back to this PC's defaults, after asking.</summary>
|
||||
internal async Task ResetAsync(ScheduleRowViewModel row)
|
||||
{
|
||||
if (_attached is not { } scheduler || !row.IsSystem) return;
|
||||
var confirmed = _confirm(new ConfirmRequest
|
||||
{
|
||||
Heading = Loc.L("Jobs.Schedule.ResetHeading", row.Name),
|
||||
Message = Loc.L("Jobs.Schedule.ResetMessage"),
|
||||
SafeText = Loc.L("Jobs.Schedule.Keep"),
|
||||
SafeToolTip = Loc.L("Tooltips.Jobs.Schedule.KeepEdits"),
|
||||
ActionText = Loc.L("Jobs.Schedule.Reset"),
|
||||
ActionToolTip = Loc.L("Tooltips.Jobs.Schedule.Reset"),
|
||||
});
|
||||
if (!confirmed) return;
|
||||
var result = await Call(() => scheduler.ResetAsync(row.Id));
|
||||
if (result?.Schedule is { } saved) Apply(saved);
|
||||
else await ReloadAsync();
|
||||
}
|
||||
|
||||
// ---------------- Editor ----------------
|
||||
|
||||
private void New()
|
||||
{
|
||||
if (_editor is not null || !IsRunning) return;
|
||||
Editor = new ScheduleEditorViewModel(this, null);
|
||||
}
|
||||
|
||||
/// <summary>Saves what the editor holds: a new schedule, or the fields of the one it edits.</summary>
|
||||
internal async Task<ScheduleEditResult> SaveAsync(ScheduleEditorViewModel editor)
|
||||
{
|
||||
if (_attached is not { } scheduler) return new ScheduleEditResult(null, null);
|
||||
var result = editor.ScheduleId is { } id
|
||||
? await Task.Run(() => scheduler.UpdateAsync(id, editor.BuildUpdate()))
|
||||
: await Task.Run(() => scheduler.CreateAsync(editor.BuildCreate(), null));
|
||||
if (result.Schedule is { } saved)
|
||||
{
|
||||
Apply(saved);
|
||||
if (editor.ScheduleId is null && _rows.TryGetValue(saved.Id, out var created)) Selected = created;
|
||||
}
|
||||
else if (result.NotFound)
|
||||
{
|
||||
await ReloadAsync();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Closes <paramref name="editor"/> if it is still the open one.</summary>
|
||||
internal void CloseEditor(ScheduleEditorViewModel editor)
|
||||
{
|
||||
if (!ReferenceEquals(_editor, editor)) return;
|
||||
editor.Dispose();
|
||||
Editor = null;
|
||||
}
|
||||
|
||||
// ---------------- Events and rows ----------------
|
||||
|
||||
private void OnScheduleChanged(ScheduleDto schedule) => Post(() => Apply(schedule));
|
||||
|
||||
private void OnScheduleDeleted(Guid id) => Post(() => Remove(id));
|
||||
|
||||
private void Post(Action action)
|
||||
{
|
||||
if (_context is null || SynchronizationContext.Current == _context) action();
|
||||
else _context.Post(_ => action(), null);
|
||||
}
|
||||
|
||||
/// <summary>A schedule as the scheduler returned or announced it: its row changes, or joins the list in the scheduler's order.</summary>
|
||||
private void Apply(ScheduleDto schedule)
|
||||
{
|
||||
if (_rows.TryGetValue(schedule.Id, out var row))
|
||||
{
|
||||
var newRun = row.Schedule.LastRun != schedule.LastRun;
|
||||
var newJob = schedule.LastJobId is { } job && job != row.LastJob?.Id;
|
||||
row.Update(schedule);
|
||||
if (newJob) _ = LoadLastJobAsync(row);
|
||||
if (newRun && ReferenceEquals(_selected, row)) RunsLoading = LoadRunsAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
row = new ScheduleRowViewModel(schedule, this);
|
||||
_rows[schedule.Id] = row;
|
||||
Rows.Insert(InsertionIndex(schedule), row);
|
||||
_ = LoadLastJobAsync(row);
|
||||
RaiseState();
|
||||
}
|
||||
if (schedule.SystemKey == DesktopScheduleHost.Housekeeping) HistoryChanged?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>Where a new row goes: system schedules first, then by creation.</summary>
|
||||
private int InsertionIndex(ScheduleDto schedule)
|
||||
{
|
||||
for (var i = 0; i < Rows.Count; i++)
|
||||
{
|
||||
var other = Rows[i].Schedule;
|
||||
var before = (schedule.SystemKey is not null, other.SystemKey is not null) switch
|
||||
{
|
||||
(true, false) => true,
|
||||
(false, true) => false,
|
||||
_ => schedule.Created < other.Created,
|
||||
};
|
||||
if (before) return i;
|
||||
}
|
||||
return Rows.Count;
|
||||
}
|
||||
|
||||
private void Remove(Guid id)
|
||||
{
|
||||
if (!_rows.Remove(id, out var row)) return;
|
||||
Rows.Remove(row);
|
||||
if (ReferenceEquals(_selected, row)) Selected = null;
|
||||
RaiseState();
|
||||
}
|
||||
|
||||
/// <summary>Reads the job of the schedule's last run; a change of it announced meanwhile, or a later read, wins.</summary>
|
||||
private async Task LoadLastJobAsync(ScheduleRowViewModel row)
|
||||
{
|
||||
if (row.Schedule.LastJobId is not { } id || _database() is not { } db) return;
|
||||
var read = row.BeginLastJobRead();
|
||||
try
|
||||
{
|
||||
row.SetLoadedLastJob(await db.Jobs.GetAsync(id), read);
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning("schedules", $"The last job of schedule {row.Id} could not be read", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The selected schedule's jobs, newest first; a later selection wins over a slower read.</summary>
|
||||
private async Task LoadRunsAsync()
|
||||
{
|
||||
var request = ++_runsRequest;
|
||||
var row = _selected;
|
||||
IReadOnlyList<Job> jobs = [];
|
||||
if (row is not null && _database() is { } db)
|
||||
{
|
||||
try
|
||||
{
|
||||
jobs = await db.Jobs.ListByScheduleAsync(row.Id, RunsShown);
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning("schedules", $"The runs of schedule {row.Id} could not be read", ex);
|
||||
}
|
||||
}
|
||||
if (request != _runsRequest) return;
|
||||
Runs.Clear();
|
||||
foreach (var job in jobs) Runs.Add(new ScheduleRunViewModel(job, _showJob));
|
||||
RaiseRuns();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs a scheduler call off the UI thread; a failure becomes a toast and null (for a value type, ask for its nullable
|
||||
/// type: its default would read as a result).
|
||||
/// </summary>
|
||||
private async Task<T?> Call<T>(Func<Task<T>> call)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await Task.Run(call);
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException)
|
||||
{
|
||||
Log.Warning("schedules", "A schedule could not be changed", ex);
|
||||
_notify(Loc.L("Jobs.Schedule.Failed"), ex.Message, true);
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
private void RaiseState()
|
||||
{
|
||||
OnPropertyChanged(nameof(IsRunning));
|
||||
OnPropertyChanged(nameof(IsLoaded));
|
||||
OnPropertyChanged(nameof(HasRows));
|
||||
OnPropertyChanged(nameof(IsUnavailable));
|
||||
OnPropertyChanged(nameof(NewToolTip));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
|
||||
private void RaiseRuns()
|
||||
{
|
||||
OnPropertyChanged(nameof(HasRuns));
|
||||
OnPropertyChanged(nameof(IsRunsEmpty));
|
||||
}
|
||||
}
|
||||
@@ -189,7 +189,7 @@ public sealed class ArchiveViewModel : SectionViewModel
|
||||
|
||||
public ICommand BackupCommand { get; }
|
||||
|
||||
/// <summary>"Maintenance ▾ › Restore database…" (BRIEF §12.5): Settings › Advanced, where a daily copy is compared and restored (§6.2).</summary>
|
||||
/// <summary>"Maintenance ▾ › Restore database…" (BRIEF §12.5): Settings › Advanced, where a backup copy is compared and restored (§6.2).</summary>
|
||||
public ICommand RestoreCommand { get; }
|
||||
|
||||
public ICommand MaintenanceCommand { get; }
|
||||
@@ -844,7 +844,7 @@ public sealed class ArchiveViewModel : SectionViewModel
|
||||
if (Services.Database is not { } db) return;
|
||||
try
|
||||
{
|
||||
var path = await db.BackupAsync(Services.Environment.BackupDirectory);
|
||||
var path = await db.BackupAsync(Services.Environment.BackupDirectory, await DatabaseBackups.KeptAsync(db));
|
||||
Shell.Notify(Loc.L("Settings.Advanced.BackupDone"), Formatting.LeftToRight(Path.GetFileName(path)), Loc.L("Library.Export.Show"),
|
||||
Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
|
||||
}
|
||||
|
||||
@@ -2,229 +2,268 @@
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Chronos.Ui.Controls;assembly=Chronos.Ui"
|
||||
xmlns:v="clr-namespace:Chronos.Ui.Visuals;assembly=Chronos.Ui"
|
||||
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
|
||||
xmlns:s="clr-namespace:Chronos.App.Sections"
|
||||
xmlns:infra="clr-namespace:Chronos.App.Infrastructure"
|
||||
xmlns:j="clr-namespace:Chronos.App.Jobs">
|
||||
<UserControl.Resources>
|
||||
<Style x:Key="Text.Muted" TargetType="TextBlock" BasedOn="{StaticResource Text.Cell}">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsDimmed}" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
<!-- Numbers stay right-aligned in both reading directions (DESIGN §4 tables). -->
|
||||
<Style x:Key="Text.MutedNumber" TargetType="TextBlock" BasedOn="{StaticResource Text.Muted}">
|
||||
<Setter Property="TextAlignment" Value="Right" />
|
||||
<Setter Property="FlowDirection" Value="LeftToRight" />
|
||||
</Style>
|
||||
<!-- Speeds and times left carry the language's unit ("2 د"): they read in its direction, at the end of the cell like their header. -->
|
||||
<Style x:Key="Text.MutedEnd" TargetType="TextBlock" BasedOn="{StaticResource Text.Muted}">
|
||||
<Setter Property="TextAlignment" Value="Right" />
|
||||
</Style>
|
||||
<Style x:Key="Text.HeaderEnd" TargetType="TextBlock" BasedOn="{StaticResource Text.Header}">
|
||||
<Setter Property="TextAlignment" Value="Right" />
|
||||
</Style>
|
||||
<Style x:Key="ProgressBar.Job" TargetType="ProgressBar" BasedOn="{StaticResource {x:Type ProgressBar}}">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsDone}" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Success}" />
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding IsFailed}" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Error}" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
<ItemsPanelTemplate x:Key="Panel.Row">
|
||||
<StackPanel Orientation="Horizontal" />
|
||||
</ItemsPanelTemplate>
|
||||
<ItemsPanelTemplate x:Key="Panel.Wrap">
|
||||
<WrapPanel />
|
||||
</ItemsPanelTemplate>
|
||||
<!-- Filter chip (Jobs.html, aria-pressed): one of a group, so screen readers hear which filter is on. -->
|
||||
<Style x:Key="RadioButton.Chip" TargetType="RadioButton" BasedOn="{StaticResource Button.Base}">
|
||||
<Setter Property="Height" Value="30" />
|
||||
<Setter Property="Padding" Value="12,0" />
|
||||
<Setter Property="Typography.NumeralAlignment" Value="Tabular" />
|
||||
<Setter Property="ui:ControlState.CornerRadius" Value="15" />
|
||||
<Style.Triggers>
|
||||
<Trigger Property="IsChecked" Value="True">
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter Property="ui:ControlState.HoverBorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
</Trigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
<!-- A row reads as its job and state; Tab goes to its buttons. -->
|
||||
<Style x:Key="ListBoxItem.Job" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.PlainRow}">
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding AccessibleName}" />
|
||||
<Setter Property="AutomationProperties.ItemStatus" Value="{Binding StateText}" />
|
||||
</Style>
|
||||
<ResourceDictionary>
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<!-- The schedule editor (Jobs › Scheduled) opens over the whole screen. -->
|
||||
<ResourceDictionary Source="pack://application:,,,/Chronos;component/Jobs/ScheduleDialogs.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
<Style x:Key="Text.Muted" TargetType="TextBlock" BasedOn="{StaticResource Text.Cell}">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsDimmed}" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
<!-- Numbers stay right-aligned in both reading directions (DESIGN §4 tables). -->
|
||||
<Style x:Key="Text.MutedNumber" TargetType="TextBlock" BasedOn="{StaticResource Text.Muted}">
|
||||
<Setter Property="TextAlignment" Value="Right" />
|
||||
<Setter Property="FlowDirection" Value="LeftToRight" />
|
||||
</Style>
|
||||
<!-- Speeds and times left carry the language's unit ("2 د"): they read in its direction, at the end of the cell like their header. -->
|
||||
<Style x:Key="Text.MutedEnd" TargetType="TextBlock" BasedOn="{StaticResource Text.Muted}">
|
||||
<Setter Property="TextAlignment" Value="Right" />
|
||||
</Style>
|
||||
<Style x:Key="Text.HeaderEnd" TargetType="TextBlock" BasedOn="{StaticResource Text.Header}">
|
||||
<Setter Property="TextAlignment" Value="Right" />
|
||||
</Style>
|
||||
<Style x:Key="ProgressBar.Job" TargetType="ProgressBar" BasedOn="{StaticResource {x:Type ProgressBar}}">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsDone}" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Success}" />
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding IsFailed}" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Error}" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
<ItemsPanelTemplate x:Key="Panel.Row">
|
||||
<StackPanel Orientation="Horizontal" />
|
||||
</ItemsPanelTemplate>
|
||||
<ItemsPanelTemplate x:Key="Panel.Wrap">
|
||||
<WrapPanel />
|
||||
</ItemsPanelTemplate>
|
||||
<!-- Filter chip (Jobs.html, aria-pressed): one of a group, so screen readers hear which filter is on. -->
|
||||
<Style x:Key="RadioButton.Chip" TargetType="RadioButton" BasedOn="{StaticResource Button.Base}">
|
||||
<Setter Property="Height" Value="30" />
|
||||
<Setter Property="Padding" Value="12,0" />
|
||||
<Setter Property="Typography.NumeralAlignment" Value="Tabular" />
|
||||
<Setter Property="ui:ControlState.CornerRadius" Value="15" />
|
||||
<Style.Triggers>
|
||||
<Trigger Property="IsChecked" Value="True">
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter Property="ui:ControlState.HoverBorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
</Trigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
<!-- A row reads as its job and state; Tab goes to its buttons. -->
|
||||
<Style x:Key="ListBoxItem.Job" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.PlainRow}">
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding AccessibleName}" />
|
||||
<Setter Property="AutomationProperties.ItemStatus" Value="{Binding StateText}" />
|
||||
</Style>
|
||||
</ResourceDictionary>
|
||||
</UserControl.Resources>
|
||||
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
<Grid IsEnabled="{Binding IsContentEnabled}">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Toolbar in visual (and Tab) order: state chips · search, then workers, Pause all, Clear done. The search moves under
|
||||
the chips before anything is cut (+40 % text at 1200 px). -->
|
||||
<Grid Margin="20,12">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<WrapPanel VerticalAlignment="Center">
|
||||
<ItemsControl ItemsSource="{Binding Chips}" ItemsPanel="{StaticResource Panel.Wrap}" Focusable="False" VerticalAlignment="Center">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type s:JobFilterChip}">
|
||||
<RadioButton Style="{StaticResource RadioButton.Chip}" GroupName="JobFilters" Content="{Binding Text}" IsChecked="{Binding IsSelected, Mode=OneWay}"
|
||||
Command="{Binding SelectCommand}" ToolTip="{Binding ToolTip}" Margin="0,1,8,1" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<StackPanel Orientation="Horizontal" Margin="0,1,0,1">
|
||||
<Border Width="1" Height="22" Background="{DynamicResource Brush.Stroke}" Margin="6,0,14,0" VerticalAlignment="Center" />
|
||||
<TextBox Width="240" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}" ui:Field.Glyph="{StaticResource Icon.Search}"
|
||||
ui:Field.Placeholder="{l:Loc Jobs.Search}" ToolTip="{l:Loc Tooltips.Jobs.Search}" AutomationProperties.Name="{l:Loc Jobs.Search}" />
|
||||
</StackPanel>
|
||||
</WrapPanel>
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center" Margin="12,0,0,0" Visibility="{Binding HasEngine, Converter={StaticResource BoolToVisibility}}">
|
||||
<Border Style="{StaticResource Pill.Auto}" Margin="0,0,10,0" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.Jobs.PriorityQueue}"
|
||||
Visibility="{Binding IsPriorityQueueOn, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{l:Loc Jobs.PriorityQueue}" FontSize="{StaticResource Size.Chip}" Foreground="{DynamicResource Brush.Accent}" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<TextBlock Text="{Binding ParallelismText}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center"
|
||||
Typography.NumeralAlignment="Tabular" ToolTip="{l:Loc Tooltips.Jobs.Parallelism}" />
|
||||
</StackPanel>
|
||||
<Button Grid.Column="2" Content="{l:Loc Jobs.PauseAll}" Command="{Binding PauseAllCommand}" ToolTip="{l:Loc Tooltips.Jobs.PauseAll}" Margin="12,0,0,0" VerticalAlignment="Center" />
|
||||
<Button Grid.Column="3" Content="{l:Loc Jobs.ClearDone}" Command="{Binding ClearDoneCommand}" ToolTip="{l:Loc Tooltips.Jobs.ClearDone}" Margin="8,0,0,0" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
<!-- Toolbar: Queue | Scheduled (owner review 2, R10), then the tab's own tools. -->
|
||||
<DockPanel Margin="20,12">
|
||||
<v:SegmentedControl DockPanel.Dock="Left" VerticalAlignment="Center" SelectedIndex="{Binding TabIndex}" AutomationProperties.Name="{l:Loc Jobs.Tab.Name}">
|
||||
<v:SegmentedItem Content="{l:Loc Jobs.Tab.Queue}" ToolTip="{l:Loc Tooltips.Jobs.Tab.Queue}" AutomationProperties.Name="{l:Loc Jobs.Tab.Queue}" />
|
||||
<v:SegmentedItem Content="{l:Loc Jobs.Tab.Scheduled}" ToolTip="{l:Loc Tooltips.Jobs.Tab.Scheduled}" AutomationProperties.Name="{l:Loc Jobs.Tab.Scheduled}" />
|
||||
</v:SegmentedControl>
|
||||
<Border DockPanel.Dock="Left" Width="1" Height="22" Background="{DynamicResource Brush.Stroke}" Margin="14,0" VerticalAlignment="Center" />
|
||||
<Button DockPanel.Dock="Right" Content="{l:Loc Jobs.Schedule.New}" Command="{Binding Schedules.NewCommand}" ToolTip="{Binding Schedules.NewToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" VerticalAlignment="Center" Visibility="{Binding IsScheduled, Converter={StaticResource BoolToVisibility}}" />
|
||||
<!-- Queue toolbar in visual (and Tab) order: state chips · search, then workers, Pause all, Clear done. The search moves under
|
||||
the chips before anything is cut (+40 % text at 1200 px). -->
|
||||
<Grid Visibility="{Binding IsQueue, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<WrapPanel VerticalAlignment="Center">
|
||||
<ItemsControl ItemsSource="{Binding Chips}" ItemsPanel="{StaticResource Panel.Wrap}" Focusable="False" VerticalAlignment="Center">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type s:JobFilterChip}">
|
||||
<RadioButton Style="{StaticResource RadioButton.Chip}" GroupName="JobFilters" Content="{Binding Text}" IsChecked="{Binding IsSelected, Mode=OneWay}"
|
||||
Command="{Binding SelectCommand}" ToolTip="{Binding ToolTip}" Margin="0,1,8,1" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<StackPanel Orientation="Horizontal" Margin="0,1,0,1">
|
||||
<Border Width="1" Height="22" Background="{DynamicResource Brush.Stroke}" Margin="6,0,14,0" VerticalAlignment="Center" />
|
||||
<TextBox Width="240" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}" ui:Field.Glyph="{StaticResource Icon.Search}"
|
||||
ui:Field.Placeholder="{l:Loc Jobs.Search}" ToolTip="{l:Loc Tooltips.Jobs.Search}" AutomationProperties.Name="{l:Loc Jobs.Search}" />
|
||||
</StackPanel>
|
||||
</WrapPanel>
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center" Margin="12,0,0,0" Visibility="{Binding HasEngine, Converter={StaticResource BoolToVisibility}}">
|
||||
<Border Style="{StaticResource Pill.Auto}" Margin="0,0,10,0" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.Jobs.PriorityQueue}"
|
||||
Visibility="{Binding IsPriorityQueueOn, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{l:Loc Jobs.PriorityQueue}" FontSize="{StaticResource Size.Chip}" Foreground="{DynamicResource Brush.Accent}" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<TextBlock Text="{Binding ParallelismText}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center"
|
||||
Typography.NumeralAlignment="Tabular" ToolTip="{l:Loc Tooltips.Jobs.Parallelism}" />
|
||||
</StackPanel>
|
||||
<Button Grid.Column="2" Content="{l:Loc Jobs.PauseAll}" Command="{Binding PauseAllCommand}" ToolTip="{l:Loc Tooltips.Jobs.PauseAll}" Margin="12,0,0,0" VerticalAlignment="Center" />
|
||||
<Button Grid.Column="3" Content="{l:Loc Jobs.ClearDone}" Command="{Binding ClearDoneCommand}" ToolTip="{l:Loc Tooltips.Jobs.ClearDone}" Margin="8,0,0,0" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</DockPanel>
|
||||
|
||||
<Border Grid.Row="1" Style="{StaticResource Border.Panel}" Margin="20,0,20,12" Visibility="{Binding HasRows, Converter={StaticResource BoolToVisibility}}">
|
||||
<!-- Header and rows share their columns (Jobs.html grid-template-columns): the same 14 px padding, the actions column sized
|
||||
by its widest row in every row, and the list's scroll-bar gutter always kept (10 px), mirrored on the header's right. -->
|
||||
<Grid Grid.IsSharedSizeScope="True">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<!-- ===================== Queue ===================== -->
|
||||
<Grid Grid.Row="1" Visibility="{Binding IsQueue, Converter={StaticResource BoolToVisibility}}">
|
||||
<Border Style="{StaticResource Border.Panel}" Margin="20,0,20,12" Visibility="{Binding HasRows, Converter={StaticResource BoolToVisibility}}">
|
||||
<!-- Header and rows share their columns (Jobs.html grid-template-columns): the same 14 px padding, the actions column sized
|
||||
by its widest row in every row, and the list's scroll-bar gutter always kept (10 px), mirrored on the header's right. -->
|
||||
<Grid Grid.IsSharedSizeScope="True">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Header -->
|
||||
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="14,8,24,8">
|
||||
<Grid>
|
||||
<!-- Kind, Where and State share the width with Target and Progress (Target, whose name is in its tooltip, gives way first), so the actions keep
|
||||
their room at 1200 px beside the 200 px rail in every language; a cut kind, place, state or header shows whole in its tooltip. On wide
|
||||
windows Kind, Where and State stop growing and Target takes the rest (Jobs.html). -->
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="28" />
|
||||
<ColumnDefinition Width="0.7*" MinWidth="90" MaxWidth="140" />
|
||||
<ColumnDefinition Width="1.6*" MinWidth="84" />
|
||||
<ColumnDefinition Width="*" MinWidth="104" MaxWidth="240" />
|
||||
<ColumnDefinition Width="90" />
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition Width="0.6*" MinWidth="80" MaxWidth="140" />
|
||||
<ColumnDefinition Width="0.7*" MinWidth="116" MaxWidth="170" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="150" SharedSizeGroup="JobActions" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Kind}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Kind}" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Target}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Target}" />
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Progress}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Progress}" />
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.HeaderEnd}" Text="{l:Loc Jobs.Column.Speed}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Speed}" />
|
||||
<TextBlock Grid.Column="5" Style="{StaticResource Text.HeaderEnd}" Text="{l:Loc Jobs.Column.Left}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Left}" />
|
||||
<TextBlock Grid.Column="6" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Where}" Margin="16,0,0,0" ToolTip="{l:Loc Jobs.Column.Where}" />
|
||||
<TextBlock Grid.Column="7" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.State}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.State}" />
|
||||
<!-- Header -->
|
||||
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="14,8,24,8">
|
||||
<Grid>
|
||||
<!-- Kind, Where and State share the width with Target and Progress (Target, whose name is in its tooltip, gives way first), so the actions keep
|
||||
their room at 1200 px beside the 200 px rail in every language; a cut kind, place, state or header shows whole in its tooltip. On wide
|
||||
windows Kind, Where and State stop growing and Target takes the rest (Jobs.html). -->
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="28" />
|
||||
<ColumnDefinition Width="0.7*" MinWidth="90" MaxWidth="140" />
|
||||
<ColumnDefinition Width="1.6*" MinWidth="84" />
|
||||
<ColumnDefinition Width="*" MinWidth="104" MaxWidth="240" />
|
||||
<ColumnDefinition Width="90" />
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition Width="0.6*" MinWidth="80" MaxWidth="140" />
|
||||
<ColumnDefinition Width="0.7*" MinWidth="116" MaxWidth="170" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="150" SharedSizeGroup="JobActions" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Kind}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Kind}" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Target}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Target}" />
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Progress}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Progress}" />
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.HeaderEnd}" Text="{l:Loc Jobs.Column.Speed}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Speed}" />
|
||||
<TextBlock Grid.Column="5" Style="{StaticResource Text.HeaderEnd}" Text="{l:Loc Jobs.Column.Left}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Left}" />
|
||||
<TextBlock Grid.Column="6" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Where}" Margin="16,0,0,0" ToolTip="{l:Loc Jobs.Column.Where}" />
|
||||
<TextBlock Grid.Column="7" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.State}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.State}" />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Rows: queue order, then the history; expandable log tail. Tab walks every row button (the rows take no focus). -->
|
||||
<ListBox x:Name="JobList" Grid.Row="1" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.Job}"
|
||||
VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.ScrollUnit="Pixel"
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.ScrollChanged="OnScrollChanged"
|
||||
KeyboardNavigation.TabNavigation="Continue" AutomationProperties.Name="{l:Loc Shell.Nav.Jobs}">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type j:JobRowViewModel}">
|
||||
<StackPanel>
|
||||
<Border x:Name="Row" Height="38" Background="Transparent" Padding="14,0">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="28" />
|
||||
<ColumnDefinition Width="0.7*" MinWidth="90" MaxWidth="140" />
|
||||
<ColumnDefinition Width="1.6*" MinWidth="84" />
|
||||
<ColumnDefinition Width="*" MinWidth="104" MaxWidth="240" />
|
||||
<ColumnDefinition Width="90" />
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition Width="0.6*" MinWidth="80" MaxWidth="140" />
|
||||
<ColumnDefinition Width="0.7*" MinWidth="116" MaxWidth="170" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="150" SharedSizeGroup="JobActions" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Button x:Name="Toggle" Style="{StaticResource Button.IconSubtle}" Width="22" Height="22" MinWidth="22" HorizontalAlignment="Left"
|
||||
ui:ButtonIcon.Glyph="{StaticResource Icon.ChevronRight}" Command="{Binding ToggleLogCommand}"
|
||||
ToolTip="{Binding ToggleToolTip}" AutomationProperties.Name="{Binding ToggleName}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Muted}" Text="{Binding Kind}" Margin="10,0,0,0" ToolTip="{Binding Kind}" />
|
||||
<!-- A job a schedule queued carries the "Scheduled" pill after its target, which gives way first. -->
|
||||
<DockPanel Grid.Column="2" Margin="10,0,0,0">
|
||||
<Border DockPanel.Dock="Right" Style="{StaticResource Pill.Auto}" Height="20" Padding="7,0" Margin="8,0,0,0" VerticalAlignment="Center"
|
||||
ToolTip="{l:Loc Tooltips.Jobs.Scheduled}" Visibility="{Binding IsScheduled, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{l:Loc Jobs.Scheduled}" FontSize="{StaticResource Size.Chip}" Foreground="{DynamicResource Brush.Accent}" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Target}" ToolTip="{Binding Target}" />
|
||||
</DockPanel>
|
||||
<Grid Grid.Column="3" Margin="10,0,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="44" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ProgressBar Style="{StaticResource ProgressBar.Job}" Maximum="1" Value="{Binding Progress, Mode=OneWay}" VerticalAlignment="Center"
|
||||
AutomationProperties.Name="{Binding AccessibleName}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.MutedNumber}" Text="{Binding PercentText}" />
|
||||
</Grid>
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.MutedEnd}" Text="{Binding SpeedText}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="5" Style="{StaticResource Text.MutedEnd}" Text="{Binding LeftText}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="6" Style="{StaticResource Text.Muted}" Text="{Binding WhereText}" Margin="16,0,0,0" ToolTip="{Binding WhereText}" />
|
||||
<!-- A new state is announced with its job; progress ticks are not. -->
|
||||
<ui:StatusGlyph Grid.Column="7" Kind="{Binding StateKind}" Text="{Binding StateText}" ToolTip="{Binding StateToolTip}"
|
||||
FontSize="13" VerticalAlignment="Center" Margin="10,0,0,0"
|
||||
AutomationProperties.LiveSetting="Polite" infra:LiveRegion.Text="{Binding StateAnnouncement}" />
|
||||
<ItemsControl Grid.Column="8" ItemsSource="{Binding Actions}" ItemsPanel="{StaticResource Panel.Row}" Focusable="False"
|
||||
VerticalAlignment="Center" Margin="10,0,0,0">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type j:JobAction}">
|
||||
<Button Style="{StaticResource Button.Row}" Content="{Binding Text}" Command="{Binding Command}" ToolTip="{Binding ToolTip}"
|
||||
AutomationProperties.Name="{Binding AccessibleName}" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</Grid>
|
||||
</Border>
|
||||
<!-- The log keeps its left-to-right lines (times, paths, numbers) in every language. -->
|
||||
<Border x:Name="Log" Background="{DynamicResource Brush.Bg}" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0"
|
||||
Padding="52,10,14,12" Visibility="Collapsed">
|
||||
<TextBlock Style="{StaticResource Text.Log}" Text="{Binding LogText}" FlowDirection="LeftToRight" />
|
||||
</Border>
|
||||
</StackPanel>
|
||||
<DataTemplate.Triggers>
|
||||
<DataTrigger Binding="{Binding IsExpanded}" Value="True">
|
||||
<Setter TargetName="Log" Property="Visibility" Value="Visible" />
|
||||
<Setter TargetName="Row" Property="Background" Value="{DynamicResource Brush.Card}" />
|
||||
<Setter TargetName="Toggle" Property="ui:ButtonIcon.Glyph" Value="{StaticResource Icon.ChevronDown}" />
|
||||
</DataTrigger>
|
||||
</DataTemplate.Triggers>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
|
||||
<!-- Footer -->
|
||||
<Border Grid.Row="2" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0" Padding="14,8">
|
||||
<DockPanel LastChildFill="False" TextElement.FontSize="12">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Jobs.RenderingSettings}" Command="{Binding RenderingSettingsCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Jobs.RenderingSettings}" />
|
||||
<TextBlock Text="{Binding HistoryText}" Foreground="{DynamicResource Brush.TextMuted}" ToolTip="{l:Loc Tooltips.Jobs.History}" />
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Rows: queue order, then the history; expandable log tail. Tab walks every row button (the rows take no focus). -->
|
||||
<ListBox x:Name="JobList" Grid.Row="1" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.Job}"
|
||||
VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.ScrollUnit="Pixel"
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.ScrollChanged="OnScrollChanged"
|
||||
KeyboardNavigation.TabNavigation="Continue" AutomationProperties.Name="{l:Loc Shell.Nav.Jobs}">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type j:JobRowViewModel}">
|
||||
<StackPanel>
|
||||
<Border x:Name="Row" Height="38" Background="Transparent" Padding="14,0">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="28" />
|
||||
<ColumnDefinition Width="0.7*" MinWidth="90" MaxWidth="140" />
|
||||
<ColumnDefinition Width="1.6*" MinWidth="84" />
|
||||
<ColumnDefinition Width="*" MinWidth="104" MaxWidth="240" />
|
||||
<ColumnDefinition Width="90" />
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition Width="0.6*" MinWidth="80" MaxWidth="140" />
|
||||
<ColumnDefinition Width="0.7*" MinWidth="116" MaxWidth="170" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="150" SharedSizeGroup="JobActions" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Button x:Name="Toggle" Style="{StaticResource Button.IconSubtle}" Width="22" Height="22" MinWidth="22" HorizontalAlignment="Left"
|
||||
ui:ButtonIcon.Glyph="{StaticResource Icon.ChevronRight}" Command="{Binding ToggleLogCommand}"
|
||||
ToolTip="{Binding ToggleToolTip}" AutomationProperties.Name="{Binding ToggleName}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Muted}" Text="{Binding Kind}" Margin="10,0,0,0" ToolTip="{Binding Kind}" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding Target}" Margin="10,0,0,0" ToolTip="{Binding Target}" />
|
||||
<Grid Grid.Column="3" Margin="10,0,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="44" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ProgressBar Style="{StaticResource ProgressBar.Job}" Maximum="1" Value="{Binding Progress, Mode=OneWay}" VerticalAlignment="Center"
|
||||
AutomationProperties.Name="{Binding AccessibleName}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.MutedNumber}" Text="{Binding PercentText}" />
|
||||
</Grid>
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.MutedEnd}" Text="{Binding SpeedText}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="5" Style="{StaticResource Text.MutedEnd}" Text="{Binding LeftText}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="6" Style="{StaticResource Text.Muted}" Text="{Binding WhereText}" Margin="16,0,0,0" ToolTip="{Binding WhereText}" />
|
||||
<!-- A new state is announced with its job; progress ticks are not. -->
|
||||
<ui:StatusGlyph Grid.Column="7" Kind="{Binding StateKind}" Text="{Binding StateText}" ToolTip="{Binding StateToolTip}"
|
||||
FontSize="13" VerticalAlignment="Center" Margin="10,0,0,0"
|
||||
AutomationProperties.LiveSetting="Polite" infra:LiveRegion.Text="{Binding StateAnnouncement}" />
|
||||
<ItemsControl Grid.Column="8" ItemsSource="{Binding Actions}" ItemsPanel="{StaticResource Panel.Row}" Focusable="False"
|
||||
VerticalAlignment="Center" Margin="10,0,0,0">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type j:JobAction}">
|
||||
<Button Style="{StaticResource Button.Row}" Content="{Binding Text}" Command="{Binding Command}" ToolTip="{Binding ToolTip}"
|
||||
AutomationProperties.Name="{Binding AccessibleName}" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</Grid>
|
||||
</Border>
|
||||
<!-- The log keeps its left-to-right lines (times, paths, numbers) in every language. -->
|
||||
<Border x:Name="Log" Background="{DynamicResource Brush.Bg}" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0"
|
||||
Padding="52,10,14,12" Visibility="Collapsed">
|
||||
<TextBlock Style="{StaticResource Text.Log}" Text="{Binding LogText}" FlowDirection="LeftToRight" />
|
||||
</Border>
|
||||
</StackPanel>
|
||||
<DataTemplate.Triggers>
|
||||
<DataTrigger Binding="{Binding IsExpanded}" Value="True">
|
||||
<Setter TargetName="Log" Property="Visibility" Value="Visible" />
|
||||
<Setter TargetName="Row" Property="Background" Value="{DynamicResource Brush.Card}" />
|
||||
<Setter TargetName="Toggle" Property="ui:ButtonIcon.Glyph" Value="{StaticResource Icon.ChevronDown}" />
|
||||
</DataTrigger>
|
||||
</DataTemplate.Triggers>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
|
||||
<!-- Footer -->
|
||||
<Border Grid.Row="2" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0" Padding="14,8">
|
||||
<DockPanel LastChildFill="False" TextElement.FontSize="12">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Jobs.RenderingSettings}" Command="{Binding RenderingSettingsCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Jobs.RenderingSettings}" />
|
||||
<TextBlock Text="{Binding HistoryText}" Foreground="{DynamicResource Brush.TextMuted}" ToolTip="{l:Loc Tooltips.Jobs.History}" />
|
||||
</DockPanel>
|
||||
</Border>
|
||||
<ui:EmptyState Message="{l:Loc Jobs.Empty}" Visibility="{Binding IsEmpty, Converter={StaticResource BoolToVisibility}}">
|
||||
<Button Content="{l:Loc Shell.Nav.Import}" Command="{Binding ImportCommand}" ToolTip="{l:Loc Tooltips.Jobs.Import}" />
|
||||
</ui:EmptyState>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<ui:EmptyState Grid.Row="1" Message="{l:Loc Jobs.Empty}" Visibility="{Binding IsEmpty, Converter={StaticResource BoolToVisibility}}">
|
||||
<Button Content="{l:Loc Shell.Nav.Import}" Command="{Binding ImportCommand}" ToolTip="{l:Loc Tooltips.Jobs.Import}" />
|
||||
</ui:EmptyState>
|
||||
<!-- ===================== Scheduled ===================== -->
|
||||
<ContentControl Grid.Row="1" Content="{Binding Schedules}" Focusable="False" Visibility="{Binding IsScheduled, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
|
||||
<!-- The schedule editor over a scrim; the keyboard stays inside it. -->
|
||||
<Grid DataContext="{Binding Schedules}" Visibility="{Binding IsEditorOpen, Converter={StaticResource BoolToVisibility}}" KeyboardNavigation.TabNavigation="Cycle"
|
||||
KeyboardNavigation.ControlTabNavigation="Cycle" KeyboardNavigation.DirectionalNavigation="Contained">
|
||||
<Border Background="{DynamicResource Brush.Scrim}" />
|
||||
<ContentPresenter x:Name="DialogHost" Content="{Binding Editor}" Margin="20" />
|
||||
</Grid>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -1,10 +1,23 @@
|
||||
using System.ComponentModel;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Threading;
|
||||
using Chronos.App.Jobs;
|
||||
|
||||
namespace Chronos.App.Sections;
|
||||
|
||||
public partial class JobsView : UserControl
|
||||
{
|
||||
public JobsView() => InitializeComponent();
|
||||
private JobsViewModel? _model;
|
||||
private IInputElement? _beforeDialog;
|
||||
|
||||
public JobsView()
|
||||
{
|
||||
InitializeComponent();
|
||||
DataContextChanged += OnDataContextChanged;
|
||||
}
|
||||
|
||||
/// <summary>Loads older history when the list scrolls near its end.</summary>
|
||||
private void OnScrollChanged(object sender, ScrollChangedEventArgs e)
|
||||
@@ -12,4 +25,51 @@ public partial class JobsView : UserControl
|
||||
if (DataContext is not JobsViewModel vm || e.ExtentHeight <= 0) return;
|
||||
if (e.VerticalOffset + e.ViewportHeight >= e.ExtentHeight - Math.Max(e.ViewportHeight, 200)) _ = vm.LoadMoreAsync();
|
||||
}
|
||||
|
||||
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (_model is not null)
|
||||
{
|
||||
_model.RowRevealRequested -= OnRevealRequested;
|
||||
_model.Schedules.PropertyChanged -= OnSchedulesChanged;
|
||||
}
|
||||
_model = e.NewValue as JobsViewModel;
|
||||
if (_model is not null)
|
||||
{
|
||||
_model.RowRevealRequested += OnRevealRequested;
|
||||
_model.Schedules.PropertyChanged += OnSchedulesChanged;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A job shown from Jobs › Scheduled: its row comes into view (the list is visible again by then) and takes the keyboard.</summary>
|
||||
private void OnRevealRequested(JobRowViewModel row) =>
|
||||
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () =>
|
||||
{
|
||||
JobList.ScrollIntoView(row);
|
||||
JobList.UpdateLayout();
|
||||
if (JobList.ItemContainerGenerator.ContainerFromItem(row) is ListBoxItem item) item.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// The schedule editor takes the keyboard when it opens (its first field); when it closes, the keyboard goes back to the
|
||||
/// control that opened it while that can still take it.
|
||||
/// </summary>
|
||||
private void OnSchedulesChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.PropertyName != nameof(SchedulesViewModel.Editor) || _model is not { } model) return;
|
||||
if (model.Schedules.Editor is not null)
|
||||
{
|
||||
if (!IsVisible) return;
|
||||
_beforeDialog ??= Keyboard.FocusedElement is Visual focused && IsAncestorOf(focused) ? Keyboard.FocusedElement : null;
|
||||
Dispatcher.BeginInvoke(DispatcherPriority.Input, () => DialogHost.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)));
|
||||
return;
|
||||
}
|
||||
var back = _beforeDialog;
|
||||
_beforeDialog = null;
|
||||
if (!IsVisible) return;
|
||||
Dispatcher.BeginInvoke(DispatcherPriority.Input, () =>
|
||||
{
|
||||
if (back is UIElement { IsVisible: true, IsEnabled: true, Focusable: true } element) element.Focus();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -49,10 +49,11 @@ public sealed class JobFilterChip(JobFilter filter, Action<JobFilter> select) :
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Jobs (BRIEF §12.6, Jobs.html): queue and history with live progress from the engine (batched to about 10
|
||||
/// updates a second), filters, queue order, an expandable log tail per job, and the row actions. Also feeds the
|
||||
/// shell's job bar, the status strip and the rail badge (running jobs, and failures not seen on this screen yet), and
|
||||
/// raises the toast of a long operation that ends (<see cref="JobNotices"/>), whichever screen started it.
|
||||
/// Jobs (BRIEF §12.6, Jobs.html), two tabs: Queue, the queue and history with live progress from the engine (batched to
|
||||
/// about 10 updates a second), filters, queue order, an expandable log tail per job, and the row actions; Scheduled
|
||||
/// (owner review 2, R10), the schedules of this PC (<see cref="SchedulesViewModel"/>). Also feeds the shell's job bar, the
|
||||
/// status strip and the rail badge (running jobs, and failures not seen on this screen yet), and raises the toast of a
|
||||
/// long operation that ends (<see cref="JobNotices"/>), whichever screen started it.
|
||||
/// </summary>
|
||||
public sealed class JobsViewModel : SectionViewModel
|
||||
{
|
||||
@@ -77,6 +78,7 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
private bool _hasMore;
|
||||
private bool _loading;
|
||||
private bool _hasLoaded;
|
||||
private int _tabIndex;
|
||||
|
||||
public JobsViewModel(ShellViewModel shell)
|
||||
: base(SectionKey.Jobs, "Icon.Jobs")
|
||||
@@ -94,10 +96,43 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
});
|
||||
LoadMoreCommand = new RelayCommand(() => _ = LoadMoreAsync());
|
||||
ImportCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Import));
|
||||
Schedules = new SchedulesViewModel(() => Shell.Services.Scheduler, () => Shell.Services.Database, request => Shell.Services.Dialogs.Confirm(request),
|
||||
(title, message, isError) => Shell.Notify(title, message, isError: isError), ShowJobAsync);
|
||||
Schedules.HistoryChanged += () => OnPropertyChanged(nameof(HistoryText));
|
||||
Schedules.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName is nameof(SchedulesViewModel.IsContentEnabled) or "" or null) OnPropertyChanged(nameof(IsContentEnabled));
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A row the screen should bring into view and expand (a job shown from Jobs › Scheduled).</summary>
|
||||
public event Action<JobRowViewModel>? RowRevealRequested;
|
||||
|
||||
public ShellViewModel Shell { get; }
|
||||
|
||||
/// <summary>Jobs › Scheduled.</summary>
|
||||
public SchedulesViewModel Schedules { get; }
|
||||
|
||||
/// <summary>0 = Queue, 1 = Scheduled (the segmented control's index). Scheduled, shown, reads the actions' availability again.</summary>
|
||||
public int TabIndex
|
||||
{
|
||||
get => _tabIndex;
|
||||
set
|
||||
{
|
||||
if (value is < 0 or > 1 || !Set(ref _tabIndex, value)) return;
|
||||
OnPropertyChanged(nameof(IsQueue));
|
||||
OnPropertyChanged(nameof(IsScheduled));
|
||||
if (IsScheduled) _ = Schedules.RefreshActionsAsync();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsQueue => _tabIndex == 0;
|
||||
|
||||
public bool IsScheduled => _tabIndex == 1;
|
||||
|
||||
/// <summary>The screen behind the schedule editor takes neither clicks nor keyboard focus.</summary>
|
||||
public bool IsContentEnabled => Schedules.IsContentEnabled;
|
||||
|
||||
/// <summary>Rows in display order for the current filter and search.</summary>
|
||||
public ObservableCollection<JobRowViewModel> Rows { get; } = [];
|
||||
|
||||
@@ -141,8 +176,8 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
/// <summary>The priority queue of Settings › Rendering is on: higher jobs pause the running one.</summary>
|
||||
public bool IsPriorityQueueOn => HasEngine && Shell.Services.Settings.PriorityQueue;
|
||||
|
||||
/// <summary>"History keeps 90 days".</summary>
|
||||
public string HistoryText => Loc.Plural("Jobs.History", (long)new JobEngineOptions().HistoryRetention.TotalDays);
|
||||
/// <summary>"History keeps 90 days": the age limit of the housekeeping schedule's job-history step; "Full history kept" without one.</summary>
|
||||
public string HistoryText => Schedules.HistoryDays is { } days ? Loc.Plural("Jobs.History", days) : Loc.L("Jobs.HistoryKept");
|
||||
|
||||
public bool IsEmpty => _hasLoaded && Rows.Count == 0;
|
||||
|
||||
@@ -154,9 +189,11 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
|
||||
private DateTimeOffset? ClearedAt => Shell.Services.Settings.JobsClearedAt;
|
||||
|
||||
/// <summary>Subscribes to the engine and loads the first page of jobs.</summary>
|
||||
/// <summary>Subscribes to the engine and loads the first page of jobs; the Scheduled tab follows the schedules once they run.</summary>
|
||||
public void Attach()
|
||||
{
|
||||
// Without an index the Scheduled tab says the schedules do not run.
|
||||
_ = Schedules.AttachAsync(Shell.Services.SchedulerReady);
|
||||
_queue = Shell.Services.Jobs;
|
||||
if (_queue is null)
|
||||
{
|
||||
@@ -178,6 +215,7 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
_queue.Progress -= OnProgress;
|
||||
}
|
||||
_throttle?.Dispose();
|
||||
Schedules.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
@@ -234,6 +272,7 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
var before = _model[job.Id]?.State;
|
||||
_model.Apply(job);
|
||||
Follow(before, job);
|
||||
Schedules.OnJob(job);
|
||||
}
|
||||
foreach (var p in progress) _model.Apply(p);
|
||||
foreach (var ending in _endings.Take(_model.IsBusy)) Shell.ShowToast(ToastFor(ending));
|
||||
@@ -241,9 +280,13 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
UpdateShell();
|
||||
}
|
||||
|
||||
/// <summary>Failures seen on this screen no longer count on the rail.</summary>
|
||||
/// <summary>
|
||||
/// Failures seen on this screen no longer count on the rail; back on Scheduled (from Settings, say), the actions'
|
||||
/// availability is read again.
|
||||
/// </summary>
|
||||
protected override void OnActivated()
|
||||
{
|
||||
if (IsScheduled) _ = Schedules.RefreshActionsAsync();
|
||||
if (_unseenFailures.Count == 0) return;
|
||||
_unseenFailures.Clear();
|
||||
UpdateShell();
|
||||
@@ -344,6 +387,38 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
|
||||
private void SelectFilter(JobFilter filter) => Filter = filter;
|
||||
|
||||
/// <summary>
|
||||
/// Shows a job in the Queue tab (from a schedule's last runs): every filter off, its row read when the list has not
|
||||
/// loaded it yet, expanded with its log, and brought into view.
|
||||
/// </summary>
|
||||
internal async Task ShowJobAsync(Guid jobId)
|
||||
{
|
||||
TabIndex = 0;
|
||||
Filter = JobFilter.All;
|
||||
SearchText = string.Empty;
|
||||
if (_model[jobId] is null && _queue is not null)
|
||||
{
|
||||
var stamp = _model.Stamp;
|
||||
try
|
||||
{
|
||||
if (await _queue.GetAsync(jobId) is { } job) _model.ApplyLoaded(job, stamp);
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning("jobs", $"Job {jobId} could not be read", ex);
|
||||
}
|
||||
SyncRows();
|
||||
}
|
||||
if (!_rows.TryGetValue(jobId, out var row) || !Rows.Contains(row))
|
||||
{
|
||||
// Hidden by Clear done: the history keeps it, the list no longer shows it.
|
||||
Shell.Notify(Loc.L("Jobs.Schedule.JobHidden"), Loc.L("Tooltips.Jobs.Schedule.JobHidden"));
|
||||
return;
|
||||
}
|
||||
row.IsExpanded = true;
|
||||
RowRevealRequested?.Invoke(row);
|
||||
}
|
||||
|
||||
/// <summary>Brings <see cref="Rows"/> to the model's order with moves (rows keep their expanded log).</summary>
|
||||
private void SyncRows()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
<UserControl x:Class="Chronos.App.Sections.SchedulesView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Chronos.Ui.Controls;assembly=Chronos.Ui"
|
||||
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
|
||||
xmlns:infra="clr-namespace:Chronos.App.Infrastructure"
|
||||
xmlns:j="clr-namespace:Chronos.App.Jobs">
|
||||
<!-- Jobs › Scheduled (owner review 2, R10): the schedules of this PC, and the last runs of the selected one. -->
|
||||
<UserControl.Resources>
|
||||
<Style x:Key="Text.Muted" TargetType="TextBlock" BasedOn="{StaticResource Text.Cell}">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
|
||||
</Style>
|
||||
<!-- A schedule row: selecting it shows its last runs; it reads as its name, action and recurrence, its last result as its status. -->
|
||||
<Style x:Key="ListBoxItem.Schedule" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
|
||||
<Setter Property="Padding" Value="0" />
|
||||
<Setter Property="FocusVisualStyle" Value="{StaticResource Focus.Inset}" />
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding AccessibleName}" />
|
||||
<Setter Property="AutomationProperties.ItemStatus" Value="{Binding LastText}" />
|
||||
</Style>
|
||||
<Style x:Key="ListBoxItem.Run" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.PlainRow}">
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding AccessibleName}" />
|
||||
</Style>
|
||||
</UserControl.Resources>
|
||||
|
||||
<Grid Margin="20,0,20,12">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="*" MinHeight="150" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<Border Style="{StaticResource Border.Panel}" Visibility="{Binding HasRows, Converter={StaticResource BoolToVisibility}}">
|
||||
<!-- Header and rows share their columns: the same 14 px padding, the actions column sized by its widest row, the scroll-bar gutter kept. -->
|
||||
<Grid Grid.IsSharedSizeScope="True">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="14,8,24,8">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="56" />
|
||||
<ColumnDefinition Width="1.2*" MinWidth="120" />
|
||||
<ColumnDefinition Width="0.9*" MinWidth="100" MaxWidth="190" />
|
||||
<ColumnDefinition Width="1.1*" MinWidth="120" MaxWidth="240" />
|
||||
<ColumnDefinition Width="0.8*" MinWidth="110" MaxWidth="170" />
|
||||
<ColumnDefinition Width="0.8*" MinWidth="110" MaxWidth="180" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="200" SharedSizeGroup="ScheduleActions" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Schedule.Column.On}" ToolTip="{l:Loc Jobs.Schedule.Column.On}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Schedule.Column.Name}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Schedule.Column.Name}" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Schedule.Column.Action}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Schedule.Column.Action}" />
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Schedule.Column.When}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Schedule.Column.When}" />
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Schedule.Column.Next}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Schedule.Column.Next}" />
|
||||
<TextBlock Grid.Column="5" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Schedule.Column.Last}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Schedule.Column.Last}" />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Rows: the arrow keys move the selection; Tab walks the switch and the buttons of each row. -->
|
||||
<ListBox x:Name="ScheduleList" Grid.Row="1" ItemsSource="{Binding Rows}" SelectedItem="{Binding Selected}" ItemContainerStyle="{StaticResource ListBoxItem.Schedule}"
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Visible" KeyboardNavigation.TabNavigation="Continue"
|
||||
AutomationProperties.Name="{l:Loc Jobs.Tab.Scheduled}">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type j:ScheduleRowViewModel}">
|
||||
<Grid Height="38" Margin="14,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="56" />
|
||||
<ColumnDefinition Width="1.2*" MinWidth="120" />
|
||||
<ColumnDefinition Width="0.9*" MinWidth="100" MaxWidth="190" />
|
||||
<ColumnDefinition Width="1.1*" MinWidth="120" MaxWidth="240" />
|
||||
<ColumnDefinition Width="0.8*" MinWidth="110" MaxWidth="170" />
|
||||
<ColumnDefinition Width="0.8*" MinWidth="110" MaxWidth="180" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="200" SharedSizeGroup="ScheduleActions" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<CheckBox Style="{StaticResource CheckBox.Switch}" IsChecked="{Binding IsEnabled}" ToolTip="{Binding EnabledToolTip}" VerticalAlignment="Center"
|
||||
HorizontalAlignment="Left" AutomationProperties.Name="{Binding EnabledName}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Name}" ToolTip="{Binding NameToolTip}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Muted}" Text="{Binding ActionText}" ToolTip="{Binding ActionToolTip}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.Cell}" Text="{Binding WhenText}" ToolTip="{Binding WhenToolTip}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.Muted}" Text="{Binding NextText}" ToolTip="{Binding NextToolTip}" Margin="10,0,0,0" />
|
||||
<!-- A new result is announced with its schedule. -->
|
||||
<ui:StatusGlyph Grid.Column="5" Kind="{Binding LastKind}" Text="{Binding LastText}" ToolTip="{Binding LastToolTip}" FontSize="13" VerticalAlignment="Center"
|
||||
Margin="10,0,0,0" AutomationProperties.LiveSetting="Polite" infra:LiveRegion.Text="{Binding LastText}" />
|
||||
<StackPanel Grid.Column="6" Orientation="Horizontal" VerticalAlignment="Center" Margin="10,0,0,0">
|
||||
<Button Style="{StaticResource Button.Row}" Content="{l:Loc Jobs.Schedule.RunNow}" Command="{Binding RunNowCommand}" ToolTip="{Binding RunNowToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{Binding RunNowName}" />
|
||||
<Button Style="{StaticResource Button.Row}" Content="{l:Loc Jobs.Schedule.Edit}" Command="{Binding EditCommand}" ToolTip="{l:Loc Tooltips.Jobs.Schedule.Edit}"
|
||||
AutomationProperties.Name="{Binding EditName}" />
|
||||
<Button Style="{StaticResource Button.Row}" Content="{l:Loc Jobs.Schedule.Reset}" Command="{Binding ResetCommand}" ToolTip="{l:Loc Tooltips.Jobs.Schedule.Reset}"
|
||||
AutomationProperties.Name="{Binding ResetName}" Visibility="{Binding IsSystem, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Style="{StaticResource Button.Row}" Content="{l:Loc Jobs.Schedule.Delete}" Command="{Binding DeleteCommand}" ToolTip="{l:Loc Tooltips.Jobs.Schedule.Delete}"
|
||||
AutomationProperties.Name="{Binding DeleteName}"
|
||||
Visibility="{Binding IsSystem, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- The selected schedule's last runs: Show in queue opens the job's row in the Queue tab. -->
|
||||
<Border Grid.Row="1" Style="{StaticResource Border.Panel}" Margin="0,12,0,0" MaxHeight="260" Visibility="{Binding HasSelection, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="14,8">
|
||||
<TextBlock Text="{Binding RunsHeading}" Style="{StaticResource Text.PanelTitle}" FontSize="13" TextTrimming="CharacterEllipsis" ToolTip="{l:Loc Tooltips.Jobs.Schedule.Runs}" />
|
||||
</Border>
|
||||
<ListBox Grid.Row="1" ItemsSource="{Binding Runs}" ItemContainerStyle="{StaticResource ListBoxItem.Run}" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
|
||||
KeyboardNavigation.TabNavigation="Continue" AutomationProperties.Name="{Binding RunsHeading}"
|
||||
Visibility="{Binding HasRuns, Converter={StaticResource BoolToVisibility}}">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type j:ScheduleRunViewModel}">
|
||||
<Grid Height="34" Margin="14,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="0.6*" MinWidth="110" MaxWidth="170" />
|
||||
<ColumnDefinition Width="0.7*" MinWidth="90" MaxWidth="150" />
|
||||
<ColumnDefinition Width="1.4*" MinWidth="120" />
|
||||
<ColumnDefinition Width="0.8*" MinWidth="110" MaxWidth="190" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Muted}" Text="{Binding WhenText}" ToolTip="{l:Loc Tooltips.Jobs.Schedule.RunWhen}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Muted}" Text="{Binding Kind}" ToolTip="{Binding Kind}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding Target}" ToolTip="{Binding Target}" Margin="10,0,0,0" />
|
||||
<ui:StatusGlyph Grid.Column="3" Kind="{Binding StateKind}" Text="{Binding StateText}" ToolTip="{Binding StateToolTip}" FontSize="13" VerticalAlignment="Center"
|
||||
Margin="10,0,0,0" />
|
||||
<Button Grid.Column="4" Style="{StaticResource Button.Row}" Content="{l:Loc Jobs.Schedule.ShowJob}" Command="{Binding ShowCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Jobs.Schedule.ShowJob}" AutomationProperties.Name="{Binding ShowName}" VerticalAlignment="Center" Margin="10,0,0,0" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
<TextBlock Grid.Row="1" Text="{l:Loc Jobs.Schedule.NoRuns}" Foreground="{DynamicResource Brush.TextMuted}" Margin="14,10"
|
||||
Visibility="{Binding IsRunsEmpty, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<ui:EmptyState Grid.RowSpan="2" Message="{l:Loc Jobs.Schedule.NotRunning}" Visibility="{Binding IsUnavailable, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,9 @@
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace Chronos.App.Sections;
|
||||
|
||||
/// <summary>Jobs › Scheduled: the view of <see cref="Jobs.SchedulesViewModel"/>.</summary>
|
||||
public partial class SchedulesView : UserControl
|
||||
{
|
||||
public SchedulesView() => InitializeComponent();
|
||||
}
|
||||
@@ -192,10 +192,6 @@
|
||||
<ComboBox Width="140" HorizontalAlignment="Left" ItemsSource="{Binding ThumbnailSizes}" SelectedItem="{Binding SelectedThumbnailSize}" DisplayMemberPath="Label"
|
||||
ToolTip="{l:Loc Tooltips.Settings.ThumbnailSize}" AutomationProperties.Name="{l:Loc Settings.Archive.Thumbnails}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Archive.Polling}">
|
||||
<ComboBox Width="140" HorizontalAlignment="Left" ItemsSource="{Binding ScanIntervals}" SelectedItem="{Binding SelectedScanInterval}" DisplayMemberPath="Label"
|
||||
ToolTip="{l:Loc Tooltips.Settings.Polling}" AutomationProperties.Name="{l:Loc Settings.Archive.Polling}" />
|
||||
</HeaderedContentControl>
|
||||
</StackPanel>
|
||||
|
||||
<!-- ================= Import: defaults of new cards and folders ================= -->
|
||||
@@ -617,6 +613,31 @@
|
||||
<Button Grid.Column="1" Content="{l:Loc Common.Open}" Command="{Binding OpenLogsCommand}" ToolTip="{l:Loc Tooltips.Common.OpenLogs}" Margin="10,0,0,0" />
|
||||
</Grid>
|
||||
</HeaderedContentControl>
|
||||
<!-- Owner review 2, R11: what the log files keep; a choice applies to them at once. -->
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.LogLevel}">
|
||||
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding Logs.Levels}" SelectedItem="{Binding Logs.SelectedLevel}" DisplayMemberPath="Label"
|
||||
ToolTip="{l:Loc Tooltips.Settings.LogLevel}" AutomationProperties.Name="{l:Loc Settings.Advanced.LogLevel}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.KeepLogs}">
|
||||
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding Logs.RetentionChoices}" SelectedItem="{Binding Logs.SelectedRetention}"
|
||||
DisplayMemberPath="Label" ToolTip="{l:Loc Tooltips.Settings.KeepLogs}" AutomationProperties.Name="{l:Loc Settings.Advanced.KeepLogs}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.FileSize}">
|
||||
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding Logs.FileSizeChoices}" SelectedItem="{Binding Logs.SelectedFileSize}"
|
||||
DisplayMemberPath="Label" ToolTip="{l:Loc Tooltips.Settings.LogFileSize}" AutomationProperties.Name="{l:Loc Settings.Advanced.FileSize}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.LogsTotal}">
|
||||
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding Logs.TotalSizeChoices}" SelectedItem="{Binding Logs.SelectedTotalSize}"
|
||||
DisplayMemberPath="Label" ToolTip="{l:Loc Tooltips.Settings.LogsTotal}" AutomationProperties.Name="{l:Loc Settings.Advanced.LogsTotal}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.Rotation}">
|
||||
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding Logs.Rotations}" SelectedItem="{Binding Logs.SelectedRotation}" DisplayMemberPath="Label"
|
||||
ToolTip="{l:Loc Tooltips.Settings.Rotation}" AutomationProperties.Name="{l:Loc Settings.Advanced.Rotation}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.DiagnosticsLogs}">
|
||||
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding Logs.DiagnosticsChoices}" SelectedItem="{Binding Logs.SelectedDiagnostics}"
|
||||
DisplayMemberPath="Label" ToolTip="{l:Loc Tooltips.Settings.DiagnosticsLogs}" AutomationProperties.Name="{l:Loc Settings.Advanced.DiagnosticsLogs}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.Diagnostics}">
|
||||
<Button HorizontalAlignment="Left" Content="{l:Loc Settings.Advanced.ExportBundle}" Command="{Binding ExportDiagnosticsCommand}" ToolTip="{l:Loc Tooltips.Settings.Diagnostics}"
|
||||
ui:ButtonIcon.Glyph="{StaticResource Icon.Export}" />
|
||||
@@ -625,7 +646,7 @@
|
||||
<Button HorizontalAlignment="Left" Content="{l:Loc Settings.Advanced.BackupNow}" Command="{Binding BackupDatabaseCommand}" ToolTip="{l:Loc Tooltips.Settings.Backup}"
|
||||
ui:ButtonIcon.Glyph="{StaticResource Icon.Database}" />
|
||||
</HeaderedContentControl>
|
||||
<!-- Restore: a daily copy, its dry run and confirmation; it replaces the index at the next start. -->
|
||||
<!-- Restore: a backup copy of the index, its dry run and confirmation; it replaces the index at the next start. -->
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.Restore}">
|
||||
<WrapPanel>
|
||||
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Settings.Advanced.NoBackups}" Margin="0,0,12,0"
|
||||
|
||||
@@ -30,8 +30,8 @@ namespace Chronos.App.Sections;
|
||||
/// Archive rows show and change the open archive's own settings (archive.json, through the archive engine) and are the
|
||||
/// defaults of new archives; Import and Analysis feed the defaults of new cards and the analysis jobs; Rendering feeds
|
||||
/// the jobs from the next one on; Formats lists the decode tier per format on this PC with the codec extensions to
|
||||
/// install; Advanced restores the index from a daily backup at the next start; About, the last page, shows this copy
|
||||
/// (<see cref="ShellViewModel.About"/>, whose update notice Updates shows).
|
||||
/// install; Advanced sets the log files (<see cref="Logs"/>) and restores the index from a backup at the next start;
|
||||
/// About, the last page, shows this copy (<see cref="ShellViewModel.About"/>, whose update notice Updates shows).
|
||||
/// </summary>
|
||||
public sealed class SettingsViewModel : SectionViewModel
|
||||
{
|
||||
@@ -73,7 +73,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
new(SettingsPage.General, ["Settings.General.Language", "Settings.General.Theme", .. ShowsStartup ? (string[])["Settings.General.Startup"] : [],
|
||||
"Settings.General.Notifications", .. ProductFeatures.AdsEnabled ? (string[])["Settings.General.Usage"] : []]),
|
||||
new(SettingsPage.Archive, ["Settings.Archive.Root", "Settings.Archive.Folders", "Settings.Archive.Files", "Settings.Archive.Proxies",
|
||||
"Settings.Archive.Thumbnails", "Settings.Archive.Polling"]),
|
||||
"Settings.Archive.Thumbnails"]),
|
||||
new(SettingsPage.Import, ["Import.Scan.Sessions", "Import.Label.Scan", "Import.Scan.Subfolders", "Import.Scan.Verify", "Import.Label.Duplicates",
|
||||
"Import.Label.After", "Import.After.Eject"]),
|
||||
new(SettingsPage.Analysis, ["Settings.Analysis.Width", "Settings.Analysis.Night", "Settings.Analysis.Stars", "Settings.Analysis.Deep"]),
|
||||
@@ -83,8 +83,9 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
new(SettingsPage.Storage, ["Settings.Storage.Folder", "Settings.Storage.Thumbnails", "Settings.Storage.Limit"]),
|
||||
new(SettingsPage.Server, ["Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates"]),
|
||||
new(SettingsPage.Updates, ["Settings.General.CheckOnStart", "Settings.Updates.Latest", "About.Update.Check", "About.Releases"]),
|
||||
new(SettingsPage.Advanced, ["Settings.Advanced.DataFolder", "Settings.Advanced.Logs", "Settings.Advanced.Diagnostics", "Settings.Advanced.Backup",
|
||||
"Settings.Advanced.Restore", "Settings.Advanced.Reset"]),
|
||||
new(SettingsPage.Advanced, ["Settings.Advanced.DataFolder", "Settings.Advanced.Logs", "Settings.Advanced.LogLevel", "Settings.Advanced.KeepLogs",
|
||||
"Settings.Advanced.FileSize", "Settings.Advanced.LogsTotal", "Settings.Advanced.Rotation", "Settings.Advanced.Diagnostics",
|
||||
"Settings.Advanced.DiagnosticsLogs", "Settings.Advanced.Backup", "Settings.Advanced.Restore", "Settings.Advanced.Reset"]),
|
||||
// The translation row shows outside English only, and the language changes while Settings is open.
|
||||
new(SettingsPage.About, () => ["Shell.AppName", "About.Build", "About.Runtime", "About.System", "About.Licence", "About.ThirdParty",
|
||||
.. Shell.About.IsTranslated ? (string[])["About.Translation"] : []]),
|
||||
@@ -156,6 +157,10 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
}, () => Loc.L("Tooltips.Settings.Parallelism"));
|
||||
JobPriorities = [.. PriorityKinds.Select(k => new JobPriorityRow(k, kind => Shell.Services.PriorityQueue.LevelOf(kind), SetJobPriority))];
|
||||
|
||||
// ---- Advanced ----
|
||||
// Saving applies them to the log files (App.SaveSettings).
|
||||
Logs = new LogSettingsRows(_s, Save);
|
||||
|
||||
// ---- Storage ----
|
||||
CacheFolder = new EditableField(CacheStore.Folder(shell.Services.Environment, _s), v => ArchiveLocations.Validate(v), v =>
|
||||
{
|
||||
@@ -435,23 +440,6 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<SettingsOption<int>> ScanIntervals =>
|
||||
[.. new[] { 5, 10, 15, 30, 60 }.Select(m => new SettingsOption<int>(m, Formatting.Duration(TimeSpan.FromMinutes(m))))];
|
||||
|
||||
/// <summary>How often this PC rescans the open archive for changes made elsewhere (BRIEF §7: polling).</summary>
|
||||
public SettingsOption<int> SelectedScanInterval
|
||||
{
|
||||
get => ScanIntervals.FirstOrDefault(p => p.Value == _s.ScanIntervalMinutes) ?? ScanIntervals[1];
|
||||
set
|
||||
{
|
||||
if (value is null || value.Value == _s.ScanIntervalMinutes) return;
|
||||
_s.ScanIntervalMinutes = value.Value;
|
||||
// Saving applies it: the running rescan timer takes the new period.
|
||||
Save();
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- Import ----------------
|
||||
|
||||
public EditableField SessionGap { get; }
|
||||
@@ -765,12 +753,16 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
public string DataFolder => Shell.Services.Environment.DataDirectory;
|
||||
public string LogsFolder => Shell.Services.Environment.LogDirectory;
|
||||
public string PortableText => Loc.L(Shell.Services.Environment.IsPortable ? "Settings.Advanced.PortableOn" : "Settings.Advanced.PortableOff");
|
||||
|
||||
/// <summary>Level, retention, size limits and rotation of the log files, and the diagnostics bundle's share of each.</summary>
|
||||
public LogSettingsRows Logs { get; }
|
||||
|
||||
public ICommand OpenDataFolderCommand { get; }
|
||||
public ICommand OpenLogsCommand { get; }
|
||||
public ICommand ExportDiagnosticsCommand { get; }
|
||||
public ICommand BackupDatabaseCommand { get; }
|
||||
|
||||
/// <summary>The daily copies of the index, newest first (Restore).</summary>
|
||||
/// <summary>The copies of the index in the backups folder (the Index backup schedule's, Back up now's), newest first (Restore).</summary>
|
||||
public IReadOnlyList<BackupOption> Backups
|
||||
{
|
||||
get => _backups;
|
||||
@@ -807,10 +799,10 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
public ICommand ResetSectionCommand { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Advanced holds no setting with a default (paths and actions only), Formats only shows this PC and About only this
|
||||
/// copy: they have no Reset section.
|
||||
/// Formats only shows this PC and About only this copy: they have no Reset section. Advanced's resets its log rows
|
||||
/// (owner review 2, R11); its paths and actions have no default.
|
||||
/// </summary>
|
||||
public bool CanResetSection => _page is not (SettingsPage.Advanced or SettingsPage.Formats or SettingsPage.About);
|
||||
public bool CanResetSection => _page is not (SettingsPage.Formats or SettingsPage.About);
|
||||
public ICommand ExportSettingsCommand { get; }
|
||||
public ICommand ImportSettingsCommand { get; }
|
||||
|
||||
@@ -1138,6 +1130,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
[
|
||||
JobKind.Render, JobKind.Import, JobKind.Download, JobKind.UploadCommit, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse,
|
||||
JobKind.DeepAnalyse, JobKind.Thumbs, JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move,
|
||||
JobKind.Backup, JobKind.Cleanup,
|
||||
];
|
||||
|
||||
/// <summary>Stores <paramref name="level"/> for <paramref name="kind"/>, keeping only the levels that differ from the defaults.</summary>
|
||||
@@ -1310,7 +1303,8 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
if (Shell.Services.Database is not { } db) return;
|
||||
try
|
||||
{
|
||||
var path = await db.BackupAsync(Shell.Services.Environment.BackupDirectory, DatabaseBackups.Keep);
|
||||
// As many copies stay as the backup schedules keep (Jobs › Scheduled › Index backup › Copies kept).
|
||||
var path = await db.BackupAsync(Shell.Services.Environment.BackupDirectory, await DatabaseBackups.KeptAsync(db));
|
||||
Shell.Notify(Loc.L("Settings.Advanced.BackupDone"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or IOException or NotSupportedException)
|
||||
@@ -1344,7 +1338,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
/// Restore (BRIEF §6.2, §12.8): a dry run reads what the chosen copy holds against the index now (shown as unreadable
|
||||
/// when the index did not open, the case a restore exists for); after the user's destructive confirmation the copy is
|
||||
/// staged beside the index for the next start, where the index as it is then is kept first and replaced before it is
|
||||
/// opened (<see cref="DatabaseBackups.RestoreStagedAsync"/>; the staged copy is out of reach of the pruning to three
|
||||
/// opened (<see cref="DatabaseBackups.RestoreStagedAsync"/>; the staged copy is out of reach of the pruning of the
|
||||
/// copies). Nothing replaces the index while Chronos runs.
|
||||
/// </summary>
|
||||
private async Task RestoreDatabaseAsync()
|
||||
@@ -1494,6 +1488,9 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
case SettingsPage.Updates:
|
||||
_s.CheckForUpdates = defaults.CheckForUpdates;
|
||||
break;
|
||||
case SettingsPage.Advanced:
|
||||
Logs.Reset();
|
||||
break;
|
||||
}
|
||||
Save();
|
||||
OnAllPropertiesChanged();
|
||||
@@ -1514,7 +1511,6 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
_s.FileTemplate = defaults.FileTemplate;
|
||||
_s.ProxyLongEdge = defaults.ProxyLongEdge;
|
||||
_s.ThumbnailLongEdge = defaults.ThumbnailLongEdge;
|
||||
_s.ScanIntervalMinutes = defaults.ScanIntervalMinutes;
|
||||
FolderTemplate.Load(_s.FolderTemplate);
|
||||
FileTemplate.Load(_s.FileTemplate);
|
||||
UpdatePreview();
|
||||
@@ -1599,6 +1595,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
DefaultServer.Load(ServerAddress.Display(_s.ServerUrl));
|
||||
_interfacePriority?.Update();
|
||||
foreach (var row in JobPriorities) row.Refresh();
|
||||
Logs.Refresh();
|
||||
UpdatePreview();
|
||||
LoadCertificates();
|
||||
OnAllPropertiesChanged();
|
||||
@@ -1673,6 +1670,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
foreach (var row in JobPriorities) row.Refresh();
|
||||
foreach (var row in Formats) row.Refresh();
|
||||
foreach (var row in MissingExtensions) row.Refresh();
|
||||
Logs.Refresh();
|
||||
ArchiveRoot.Refresh();
|
||||
FolderTemplate.Refresh();
|
||||
FileTemplate.Refresh();
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// The log rows of Settings › Advanced (owner review 2, R11): level, retention, file size, total size and rotation of this
|
||||
/// PC's log files, and how much of each the diagnostics bundle keeps. Each choice is stored and saved at once, and saving
|
||||
/// applies it to the files (<see cref="AppLogging"/>). The rows show the values the files get: one set elsewhere (an
|
||||
/// imported or hand-edited settings file) is brought within range as <see cref="AppLogging.Options"/> does, then listed
|
||||
/// with the presets. File sizes above the total and totals below the file size are not offered
|
||||
/// (<see cref="LogFileOptions.TotalBelowFile"/>).
|
||||
/// </summary>
|
||||
public sealed class LogSettingsRows(AppSettings settings, Action save) : ObservableObject
|
||||
{
|
||||
public static readonly int[] RetentionPresets = [1, 3, 7, 14, 30, 90, 365];
|
||||
public static readonly int[] FileSizePresets = [10, 20, 50, 100, 200, 500];
|
||||
public static readonly int[] TotalSizePresets = [256, 512, 1024, 2048, 5120, 10240];
|
||||
public static readonly int[] DiagnosticsPresets = [1, 2, 4, 8, 16, 32];
|
||||
|
||||
public IReadOnlyList<SettingsOption<LogLevel>> Levels =>
|
||||
[.. Enum.GetValues<LogLevel>().Select(l => new SettingsOption<LogLevel>(l, Loc.L("Settings.Advanced.Level." + l)))];
|
||||
|
||||
public SettingsOption<LogLevel> SelectedLevel
|
||||
{
|
||||
get => Levels.FirstOrDefault(l => l.Value == settings.LogLevel) ?? Levels.First(l => l.Value == LogLevel.Info);
|
||||
set => Store(value, settings.LogLevel, v => settings.LogLevel = v);
|
||||
}
|
||||
|
||||
public IReadOnlyList<SettingsOption<int>> RetentionChoices =>
|
||||
[.. With(RetentionPresets, Applied.RetentionDays).Select(n => new SettingsOption<int>(n, Loc.Plural("Settings.Advanced.Days", n)))];
|
||||
|
||||
public SettingsOption<int> SelectedRetention
|
||||
{
|
||||
get => Selected(RetentionChoices, Applied.RetentionDays);
|
||||
set => Store(value, settings.LogRetentionDays, v => settings.LogRetentionDays = v);
|
||||
}
|
||||
|
||||
public IReadOnlyList<SettingsOption<int>> FileSizeChoices
|
||||
{
|
||||
get
|
||||
{
|
||||
var applied = Applied;
|
||||
return Sizes(FileSizePresets, applied.MaxFileMb, n => !LogFileOptions.TotalBelowFile(n, applied.MaxTotalMb));
|
||||
}
|
||||
}
|
||||
|
||||
public SettingsOption<int> SelectedFileSize
|
||||
{
|
||||
get => Selected(FileSizeChoices, Applied.MaxFileMb);
|
||||
set
|
||||
{
|
||||
// The totals offered depend on the file size.
|
||||
if (Store(value, settings.LogMaxFileMb, v => settings.LogMaxFileMb = v)) Changed(nameof(TotalSizeChoices), nameof(SelectedTotalSize));
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<SettingsOption<int>> TotalSizeChoices
|
||||
{
|
||||
get
|
||||
{
|
||||
var applied = Applied;
|
||||
return Sizes(TotalSizePresets, applied.MaxTotalMb, n => !LogFileOptions.TotalBelowFile(applied.MaxFileMb, n));
|
||||
}
|
||||
}
|
||||
|
||||
public SettingsOption<int> SelectedTotalSize
|
||||
{
|
||||
get => Selected(TotalSizeChoices, Applied.MaxTotalMb);
|
||||
set
|
||||
{
|
||||
if (Store(value, settings.LogMaxTotalMb, v => settings.LogMaxTotalMb = v)) Changed(nameof(FileSizeChoices), nameof(SelectedFileSize));
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<SettingsOption<LogRotation>> Rotations =>
|
||||
[.. Enum.GetValues<LogRotation>().Select(r => new SettingsOption<LogRotation>(r, Loc.L("Settings.Advanced.Rotation." + r)))];
|
||||
|
||||
public SettingsOption<LogRotation> SelectedRotation
|
||||
{
|
||||
get => Rotations.FirstOrDefault(r => r.Value == settings.LogRotation) ?? Rotations[0];
|
||||
set => Store(value, settings.LogRotation, v => settings.LogRotation = v);
|
||||
}
|
||||
|
||||
public IReadOnlyList<SettingsOption<int>> DiagnosticsChoices =>
|
||||
[.. With(DiagnosticsPresets, AppliedDiagnosticsMb).Select(n => new SettingsOption<int>(n, Megabytes(n)))];
|
||||
|
||||
public SettingsOption<int> SelectedDiagnostics
|
||||
{
|
||||
get => Selected(DiagnosticsChoices, AppliedDiagnosticsMb);
|
||||
set => Store(value, settings.DiagnosticsLogMb, v => settings.DiagnosticsLogMb = v);
|
||||
}
|
||||
|
||||
/// <summary>The defaults of every row (Reset section on Advanced); the caller saves.</summary>
|
||||
public void Reset()
|
||||
{
|
||||
var defaults = new AppSettings();
|
||||
settings.LogLevel = defaults.LogLevel;
|
||||
settings.LogRetentionDays = defaults.LogRetentionDays;
|
||||
settings.LogMaxFileMb = defaults.LogMaxFileMb;
|
||||
settings.LogMaxTotalMb = defaults.LogMaxTotalMb;
|
||||
settings.LogRotation = defaults.LogRotation;
|
||||
settings.DiagnosticsLogMb = defaults.DiagnosticsLogMb;
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>Labels in the current language, values as the settings have them now.</summary>
|
||||
internal void Refresh() => OnAllPropertiesChanged();
|
||||
|
||||
/// <summary>The values the log files get from the settings now.</summary>
|
||||
private LogFileOptions Applied => AppLogging.Options(settings);
|
||||
|
||||
private int AppliedDiagnosticsMb => (int)(AppLogging.DiagnosticsTailBytes(settings) / LogFileOptions.BytesPerMb);
|
||||
|
||||
/// <summary>
|
||||
/// Stores a choice that differs from the stored value (<paramref name="current"/>, which may lie out of range: choosing
|
||||
/// the value shown then saves it as applied) and saves; false when there was nothing to store.
|
||||
/// </summary>
|
||||
private bool Store<T>(SettingsOption<T>? choice, T current, Action<T> set, [System.Runtime.CompilerServices.CallerMemberName] string? property = null)
|
||||
{
|
||||
if (choice is null || EqualityComparer<T>.Default.Equals(choice.Value, current)) return false;
|
||||
set(choice.Value);
|
||||
save();
|
||||
OnPropertyChanged(property);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void Changed(string choices, string selected)
|
||||
{
|
||||
OnPropertyChanged(choices);
|
||||
OnPropertyChanged(selected);
|
||||
}
|
||||
|
||||
private static SettingsOption<int> Selected(IReadOnlyList<SettingsOption<int>> choices, int value) => choices.FirstOrDefault(c => c.Value == value) ?? choices[0];
|
||||
|
||||
/// <summary>
|
||||
/// The presets <paramref name="offered"/> in order, then "No limit" (0); <paramref name="current"/> joins them when it
|
||||
/// is another size.
|
||||
/// </summary>
|
||||
private static IReadOnlyList<SettingsOption<int>> Sizes(int[] presets, int current, Func<int, bool> offered) =>
|
||||
[
|
||||
.. With(presets.Where(offered).ToArray(), current).Where(n => n > 0).Select(n => new SettingsOption<int>(n, Megabytes(n))),
|
||||
new(0, Loc.L("Settings.Advanced.NoLimit")),
|
||||
];
|
||||
|
||||
private static IEnumerable<int> With(int[] presets, int current) => (presets.Contains(current) ? presets : presets.Append(current)).Order();
|
||||
|
||||
private static string Megabytes(int n) => Loc.L("Common.Size.MB", Formatting.Count(n));
|
||||
}
|
||||
@@ -70,6 +70,9 @@ public static class ScreenCapture
|
||||
await sample.FillAsync();
|
||||
await shell.Library.RefreshAsync();
|
||||
await shell.Jobs.ReloadAsync();
|
||||
// The sample wrote its schedules into the index, past the scheduler's events.
|
||||
await shell.Jobs.Schedules.Attached;
|
||||
await shell.Jobs.Schedules.ReloadAsync();
|
||||
await shell.Services.Server.RestoreAsync();
|
||||
await shell.Services.Sync.RefreshAsync();
|
||||
await shell.Server.Sync.ReloadAsync();
|
||||
@@ -103,6 +106,7 @@ public static class ScreenCapture
|
||||
shell.Navigate(SectionKey.Jobs);
|
||||
if (shell.Jobs.Rows.Count > 0) shell.Jobs.Rows[0].IsExpanded = true;
|
||||
written += await SaveAsync(window, directory, "jobs", theme);
|
||||
written += await CaptureSchedulesAsync(window, shell, directory, theme);
|
||||
|
||||
shell.Navigate(SectionKey.Server);
|
||||
written += await SaveAsync(window, directory, "server", theme);
|
||||
@@ -195,6 +199,29 @@ public static class ScreenCapture
|
||||
return written;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>jobs-scheduled</c> (owner review 2, R10: the Scheduled tab with the weekly integrity check selected and its last
|
||||
/// run) and <c>jobs-schedule-editor</c> (that schedule in the editor), then the Queue tab again.
|
||||
/// </summary>
|
||||
private static async Task<int> CaptureSchedulesAsync(MainWindow window, ShellViewModel shell, string directory, AppTheme theme)
|
||||
{
|
||||
var schedules = shell.Jobs.Schedules;
|
||||
shell.Jobs.TabIndex = 1;
|
||||
var written = 0;
|
||||
if ((schedules.Rows.FirstOrDefault(r => !r.IsSystem && r.IsEnabled) ?? schedules.Rows.FirstOrDefault()) is { } row)
|
||||
{
|
||||
schedules.Selected = row;
|
||||
await schedules.RunsLoading;
|
||||
written += await SaveAsync(window, directory, "jobs-scheduled", theme);
|
||||
row.EditCommand.Execute(null);
|
||||
written += await SaveAsync(window, directory, "jobs-schedule-editor", theme);
|
||||
schedules.Editor?.CloseCommand.Execute(null);
|
||||
schedules.Selected = null;
|
||||
}
|
||||
shell.Jobs.TabIndex = 0;
|
||||
return written;
|
||||
}
|
||||
|
||||
private static void SelectSyncFilter(ShellViewModel shell, SyncFilter filter) =>
|
||||
shell.Server.Sync.Chips.First(c => c.Filter == filter).SelectCommand.Execute(null);
|
||||
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:s="clr-namespace:Chronos.App.Sections">
|
||||
xmlns:s="clr-namespace:Chronos.App.Sections"
|
||||
xmlns:j="clr-namespace:Chronos.App.Jobs">
|
||||
<!-- Section view model → view. -->
|
||||
<DataTemplate DataType="{x:Type s:LibraryViewModel}"><s:LibraryView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:ImportViewModel}"><s:ImportView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:SequenceViewModel}"><s:SequenceView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:ArchiveViewModel}"><s:ArchiveView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:JobsViewModel}"><s:JobsView /></DataTemplate>
|
||||
<!-- Jobs › Scheduled, the second tab of Jobs (owner review 2, R10). -->
|
||||
<DataTemplate DataType="{x:Type j:SchedulesViewModel}"><s:SchedulesView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:ServerViewModel}"><s:ServerView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:SettingsViewModel}"><s:SettingsView /></DataTemplate>
|
||||
</ResourceDictionary>
|
||||
@@ -0,0 +1,278 @@
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Chronos.Core.Diagnostics;
|
||||
|
||||
/// <summary>How often a <see cref="FileLogSink"/> starts a new file (UTC).</summary>
|
||||
public enum LogRotation
|
||||
{
|
||||
/// <summary>One file per day: <c>prefix-yyyyMMdd.log</c>.</summary>
|
||||
Daily,
|
||||
|
||||
/// <summary>One file per hour: <c>prefix-yyyyMMdd-HH.log</c>.</summary>
|
||||
Hourly,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What a <see cref="FileLogSink"/> writes and keeps (owner review 2, R11): the least severe level written, the days files
|
||||
/// are kept, the size at which a file continues in a numbered one, the size the sink's files may take together (0: no
|
||||
/// limit for either size) and the rotation period. Sizes are in MB of 2²⁰ bytes, like the diagnostics tail.
|
||||
/// </summary>
|
||||
public sealed record LogFileOptions
|
||||
{
|
||||
public const int DefaultRetentionDays = 14;
|
||||
public const int DefaultMaxFileMb = 50;
|
||||
public const int DefaultMaxTotalMb = 1024;
|
||||
|
||||
/// <summary>Bytes in one MB of the limits.</summary>
|
||||
public const long BytesPerMb = 1L << 20;
|
||||
|
||||
public LogLevel Level { get; init; } = LogLevel.Info;
|
||||
|
||||
/// <summary>Files last written longer ago are deleted; 0 or less keeps them whatever their age.</summary>
|
||||
public int RetentionDays { get; init; } = DefaultRetentionDays;
|
||||
|
||||
/// <summary>A file this large continues in the next numbered file (<c>.1.log</c>, <c>.2.log</c>…); 0 = no limit.</summary>
|
||||
public int MaxFileMb { get; init; } = DefaultMaxFileMb;
|
||||
|
||||
/// <summary>While the sink's files together are larger, the oldest are deleted (never the one being written); 0 = no limit.</summary>
|
||||
public int MaxTotalMb { get; init; } = DefaultMaxTotalMb;
|
||||
|
||||
public LogRotation Rotation { get; init; } = LogRotation.Daily;
|
||||
|
||||
/// <summary>
|
||||
/// Whether a total of <paramref name="maxTotalMb"/> is below one file of <paramref name="maxFileMb"/>: each finished file
|
||||
/// would be deleted as soon as the next one opens. The server refuses such settings; the desktop raises the total.
|
||||
/// </summary>
|
||||
public static bool TotalBelowFile(int maxFileMb, int maxTotalMb) => maxTotalMb > 0 && maxFileMb > maxTotalMb;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends log lines to rotating files: <c>prefix-yyyyMMdd.log</c> (daily) or <c>prefix-yyyyMMdd-HH.log</c> (hourly, UTC);
|
||||
/// a file that reaches <see cref="LogFileOptions.MaxFileMb"/> continues in <c>prefix-yyyyMMdd[-HH].1.log</c>, <c>.2</c>…
|
||||
/// At every new file (and when the options change) files older than the retention are deleted, then the oldest while
|
||||
/// the sink's files exceed <see cref="LogFileOptions.MaxTotalMb"/>; only names this sink writes are touched, never the
|
||||
/// file being written. Lines are flushed one by one; one that cannot be written (the folder removed, a full disk) is dropped
|
||||
/// and the next opens the file again. <see cref="Configure"/> applies new options from the next line.
|
||||
/// </summary>
|
||||
public sealed class FileLogSink : ILogSink, IDisposable
|
||||
{
|
||||
private readonly string _directory;
|
||||
private readonly string _prefix;
|
||||
private readonly TimeProvider _time;
|
||||
private readonly Regex _ownName;
|
||||
private readonly Lock _gate = new();
|
||||
private LogFileOptions _options;
|
||||
private FileStream? _stream;
|
||||
private StreamWriter? _writer;
|
||||
private string? _stem;
|
||||
private int _part;
|
||||
private string? _path;
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>Daily files kept for <paramref name="retainDays"/>, with the default size limits.</summary>
|
||||
public FileLogSink(string directory, string prefix, int retainDays = LogFileOptions.DefaultRetentionDays)
|
||||
: this(directory, prefix, new LogFileOptions { RetentionDays = retainDays })
|
||||
{
|
||||
}
|
||||
|
||||
public FileLogSink(string directory, string prefix, LogFileOptions options, TimeProvider? time = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
_directory = Path.GetFullPath(directory);
|
||||
_prefix = prefix;
|
||||
_options = options;
|
||||
_time = time ?? TimeProvider.System;
|
||||
_ownName = new Regex("^" + Regex.Escape(prefix) + @"-\d{8}(-\d{2})?(\.\d+)?\.log$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
Directory.CreateDirectory(_directory);
|
||||
}
|
||||
|
||||
public LogFileOptions Options
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return _options;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The file being written; before the first line, the one it will go to.</summary>
|
||||
public string CurrentPath
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return _path ?? PathOf(Stem(Now), 0);
|
||||
}
|
||||
}
|
||||
|
||||
private DateTime Now => _time.GetUtcNow().UtcDateTime;
|
||||
|
||||
public void Write(LogLevel level, string category, string message, Exception? exception)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed || level < _options.Level) return;
|
||||
var now = Now;
|
||||
try
|
||||
{
|
||||
EnsureFile(now);
|
||||
_writer!.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{now:O} {level,-7} {category}: {message}"));
|
||||
if (exception is not null) _writer.WriteLine(exception.ToString());
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// The folder is gone, the disk is full or the file is locked: the line is dropped and the next one opens
|
||||
// the file again.
|
||||
Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>New options from the next line on; a change of retention or limits prunes at once.</summary>
|
||||
public void Configure(LogFileOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
lock (_gate)
|
||||
{
|
||||
var prune = options.RetentionDays != _options.RetentionDays || options.MaxTotalMb != _options.MaxTotalMb;
|
||||
_options = options;
|
||||
if (prune) Prune(Now);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Deletes the files older than the retention, then the oldest while the total exceeds the limit.</summary>
|
||||
public void PruneNow()
|
||||
{
|
||||
lock (_gate) Prune(Now);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_disposed = true;
|
||||
Close();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Opens the file of this period, or the next part when the current one is full, and prunes when it changes.</summary>
|
||||
private void EnsureFile(DateTime now)
|
||||
{
|
||||
var stem = Stem(now);
|
||||
var newPeriod = _writer is null || stem != _stem;
|
||||
if (!newPeriod && !IsFull) return;
|
||||
Close();
|
||||
if (newPeriod)
|
||||
{
|
||||
// A restart continues the newest file of the period.
|
||||
_stem = stem;
|
||||
_part = LastPart(stem);
|
||||
}
|
||||
else
|
||||
{
|
||||
_part++;
|
||||
}
|
||||
Open();
|
||||
if (IsFull)
|
||||
{
|
||||
Close();
|
||||
_part++;
|
||||
Open();
|
||||
}
|
||||
Prune(now);
|
||||
}
|
||||
|
||||
private bool IsFull => _options.MaxFileMb > 0 && _stream is { } stream && stream.Position >= _options.MaxFileMb * LogFileOptions.BytesPerMb;
|
||||
|
||||
private void Open()
|
||||
{
|
||||
_path = PathOf(_stem!, _part);
|
||||
_stream = new FileStream(_path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
|
||||
_writer = new StreamWriter(_stream) { AutoFlush = true };
|
||||
}
|
||||
|
||||
private void Close()
|
||||
{
|
||||
var writer = _writer;
|
||||
_writer = null;
|
||||
_stream = null;
|
||||
try
|
||||
{
|
||||
writer?.Dispose();
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// What it still held could not be flushed (a full disk); its file is closed all the same.
|
||||
}
|
||||
}
|
||||
|
||||
private string Stem(DateTime now) => _options.Rotation == LogRotation.Hourly
|
||||
? string.Create(CultureInfo.InvariantCulture, $"{_prefix}-{now:yyyyMMdd-HH}")
|
||||
: string.Create(CultureInfo.InvariantCulture, $"{_prefix}-{now:yyyyMMdd}");
|
||||
|
||||
private string PathOf(string stem, int part) =>
|
||||
Path.Combine(_directory, part == 0 ? stem + ".log" : string.Create(CultureInfo.InvariantCulture, $"{stem}.{part}.log"));
|
||||
|
||||
/// <summary>The highest part of <paramref name="stem"/> on disk (0 when there is none).</summary>
|
||||
private int LastPart(string stem)
|
||||
{
|
||||
var last = 0;
|
||||
try
|
||||
{
|
||||
foreach (var file in Directory.EnumerateFiles(_directory, stem + ".*.log"))
|
||||
{
|
||||
var name = Path.GetFileName(file);
|
||||
if (name.Length <= stem.Length + 5 || !name.StartsWith(stem + ".", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
if (int.TryParse(name[(stem.Length + 1)..^4], NumberStyles.None, CultureInfo.InvariantCulture, out var part)) last = int.Max(last, part);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
private void Prune(DateTime now)
|
||||
{
|
||||
List<FileInfo> files;
|
||||
try
|
||||
{
|
||||
files = [.. new DirectoryInfo(_directory).EnumerateFiles(_prefix + "-*.log").Where(f => _ownName.IsMatch(f.Name))];
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var kept = new List<FileInfo>();
|
||||
var cutoff = _options.RetentionDays > 0 ? now.AddDays(-_options.RetentionDays) : DateTime.MinValue;
|
||||
foreach (var file in files)
|
||||
{
|
||||
if (!IsCurrent(file) && file.LastWriteTimeUtc < cutoff && TryDelete(file)) continue;
|
||||
kept.Add(file);
|
||||
}
|
||||
if (_options.MaxTotalMb <= 0) return;
|
||||
var limit = _options.MaxTotalMb * LogFileOptions.BytesPerMb;
|
||||
// The directory may report a stale size for the file still open: its stream knows.
|
||||
var total = kept.Sum(f => IsCurrent(f) && _stream is { } stream ? stream.Length : f.Length);
|
||||
foreach (var file in kept.Where(f => !IsCurrent(f)).OrderBy(f => f.LastWriteTimeUtc).ThenBy(f => f.Name, StringComparer.Ordinal))
|
||||
{
|
||||
if (total <= limit) break;
|
||||
var length = file.Length;
|
||||
if (TryDelete(file)) total -= length;
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsCurrent(FileInfo file) => _path is not null && string.Equals(file.FullName, _path, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static bool TryDelete(FileInfo file)
|
||||
{
|
||||
try
|
||||
{
|
||||
file.Delete();
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,13 +17,22 @@ public interface ILogSink
|
||||
void Write(LogLevel level, string category, string message, Exception? exception);
|
||||
}
|
||||
|
||||
/// <summary>Tiny engine-wide logger. Core code logs through it; hosts plug in a sink.</summary>
|
||||
/// <summary>
|
||||
/// Tiny engine-wide logger. Core code logs through it; hosts plug in a sink. <see cref="MinimumLevel"/> drops lines no sink
|
||||
/// wants before they are formatted: hosts set it to the lowest level of their sinks, which each keep their own (a
|
||||
/// <see cref="FileLogSink"/> its <see cref="LogFileOptions.Level"/>, the server's console and files their filters).
|
||||
/// Logging never throws: a line a sink cannot write is dropped, so code that logs from its error handling (the job engine
|
||||
/// marking a job failed, the scheduler's loop) always goes on to its next step.
|
||||
/// </summary>
|
||||
public static class Log
|
||||
{
|
||||
private static ILogSink _sink = new ConsoleSink();
|
||||
|
||||
public static LogLevel MinimumLevel { get; set; } = LogLevel.Info;
|
||||
|
||||
/// <summary>Where lines go now (a test that replaces it puts this one back).</summary>
|
||||
public static ILogSink Sink => _sink;
|
||||
|
||||
public static void SetSink(ILogSink sink) => _sink = sink ?? throw new ArgumentNullException(nameof(sink));
|
||||
|
||||
public static void Debug(string category, string message) => Write(LogLevel.Debug, category, message, null);
|
||||
@@ -38,9 +47,11 @@ public static class Log
|
||||
{
|
||||
_sink.Write(level, category, message, exception);
|
||||
}
|
||||
catch (IOException)
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// Logging must never take the process down.
|
||||
// Logging must never take the process down, nor skip what its caller does next: a log folder removed, a full
|
||||
// disk or the logger of a host already gone (Microsoft.Extensions.Logging wraps what its providers throw in an
|
||||
// AggregateException) only lose the line.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,72 +66,22 @@ public static class Log
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Appends log lines to rotating files (one per day, kept for <c>retainDays</c>).</summary>
|
||||
public sealed class FileLogSink : ILogSink, IDisposable
|
||||
{
|
||||
private readonly string _directory;
|
||||
private readonly string _prefix;
|
||||
private readonly int _retainDays;
|
||||
private readonly Lock _gate = new();
|
||||
private StreamWriter? _writer;
|
||||
private DateOnly _day;
|
||||
|
||||
public FileLogSink(string directory, string prefix, int retainDays = 14)
|
||||
{
|
||||
_directory = directory;
|
||||
_prefix = prefix;
|
||||
_retainDays = retainDays;
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
public string CurrentPath => Path.Combine(_directory, $"{_prefix}-{_day:yyyyMMdd}.log");
|
||||
|
||||
public void Write(LogLevel level, string category, string message, Exception? exception)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var today = DateOnly.FromDateTime(DateTime.UtcNow);
|
||||
if (_writer is null || today != _day)
|
||||
{
|
||||
_writer?.Dispose();
|
||||
_day = today;
|
||||
_writer = new StreamWriter(new FileStream(CurrentPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) { AutoFlush = true };
|
||||
Prune();
|
||||
}
|
||||
_writer.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{DateTime.UtcNow:O} {level,-7} {category}: {message}"));
|
||||
if (exception is not null) _writer.WriteLine(exception.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
private void Prune()
|
||||
{
|
||||
foreach (var file in Directory.EnumerateFiles(_directory, _prefix + "-*.log"))
|
||||
{
|
||||
if (File.GetLastWriteTimeUtc(file) < DateTime.UtcNow.AddDays(-_retainDays))
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(file);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate) _writer?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Writes every event to several sinks.</summary>
|
||||
/// <summary>Writes every event to several sinks; one that cannot write it does not keep it from the others.</summary>
|
||||
public sealed class TeeLogSink(params ILogSink[] sinks) : ILogSink
|
||||
{
|
||||
public void Write(LogLevel level, string category, string message, Exception? exception)
|
||||
{
|
||||
foreach (var sink in sinks) sink.Write(level, category, message, exception);
|
||||
foreach (var sink in sinks)
|
||||
{
|
||||
try
|
||||
{
|
||||
sink.Write(level, category, message, exception);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// That sink loses the line (see Log.Write).
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -182,6 +182,63 @@ public sealed record Job
|
||||
public DateTimeOffset Created { get; init; }
|
||||
public DateTimeOffset? Started { get; init; }
|
||||
public DateTimeOffset? Finished { get; init; }
|
||||
|
||||
/// <summary>The schedule that queued this job; null for jobs queued by a user or by other jobs (owner review 2, R10).</summary>
|
||||
public Guid? ScheduleId { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A recurring job (owner review 2, R10): an action (scan, verify, backup, …) with its parameters, run on a recurrence
|
||||
/// in the host's time zone. System schedules (<see cref="SystemKey"/> set) stand for the timers a host used to run out of
|
||||
/// sight; they are seeded once, can be edited and reset, never deleted.
|
||||
/// </summary>
|
||||
public sealed record Schedule
|
||||
{
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>Stable key of a host's system schedule (<c>archive-scan</c>); null for schedules a user created.</summary>
|
||||
public string? SystemKey { get; init; }
|
||||
|
||||
public required string Name { get; init; }
|
||||
|
||||
/// <summary>Wire name of the action (<c>scan</c>, <c>verify</c>, <c>backup</c>…).</summary>
|
||||
public required string Action { get; init; }
|
||||
|
||||
/// <summary>What the action works on: <c>current</c>, the host's archive.</summary>
|
||||
public string Target { get; init; } = "current";
|
||||
|
||||
/// <summary>The action's parameters as JSON (camelCase, only the fields the action reads).</summary>
|
||||
public string? ParametersJson { get; init; }
|
||||
|
||||
/// <summary>The recurrence in its text form (<c>every:10m</c>, <c>daily:03:00</c>, <c>weekly:mon,thu@02:30</c>, <c>monthly:1@04:00</c>).</summary>
|
||||
public required string Recurrence { get; init; }
|
||||
|
||||
/// <summary>A run missed while the host was off happens once when it comes back; otherwise it is skipped.</summary>
|
||||
public bool CatchUp { get; init; } = true;
|
||||
|
||||
/// <summary>Priority of the jobs it queues.</summary>
|
||||
public JobPriority Priority { get; init; } = JobPriority.Background;
|
||||
|
||||
public bool Enabled { get; init; } = true;
|
||||
|
||||
/// <summary>When it fires next (UTC); null while disabled or not computed yet.</summary>
|
||||
public DateTimeOffset? NextRun { get; init; }
|
||||
|
||||
public DateTimeOffset? LastRun { get; init; }
|
||||
|
||||
/// <summary>The first job the last run queued.</summary>
|
||||
public Guid? LastJobId { get; init; }
|
||||
|
||||
/// <summary>What the last run did: <c>queued</c>, <c>skipped-pending</c>, <c>skipped-offline</c>, <c>skipped-nothing</c>,
|
||||
/// <c>unavailable</c> or <c>failed:<reason></c>.</summary>
|
||||
public string? LastOutcome { get; init; }
|
||||
|
||||
public Guid? CreatedBy { get; init; }
|
||||
public DateTimeOffset Created { get; init; }
|
||||
public DateTimeOffset Updated { get; init; }
|
||||
|
||||
/// <summary>True for a host's system schedule.</summary>
|
||||
public bool IsSystem => SystemKey is not null;
|
||||
}
|
||||
|
||||
/// <summary>A memory card known to this client (BRIEF §13).</summary>
|
||||
|
||||
@@ -81,6 +81,12 @@ public enum JobKind
|
||||
|
||||
/// <summary>Client: originals or proxies of a server sequence fetched into this PC (BRIEF §14.5).</summary>
|
||||
Download,
|
||||
|
||||
/// <summary>A <c>VACUUM INTO</c> copy of an SQLite index into the backups folder (owner review 2, R10); stored as 16.</summary>
|
||||
Backup = 16,
|
||||
|
||||
/// <summary>Housekeeping steps: job history, audit log, trash report and the host's own (owner review 2, R10); stored as 17.</summary>
|
||||
Cleanup = 17,
|
||||
}
|
||||
|
||||
public enum JobState
|
||||
|
||||
@@ -40,6 +40,8 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
Images = new ArchiveImages(db, _writer, Indexer);
|
||||
Imports = new ImportService(db, Ingest);
|
||||
Trash = new SequenceTrash(db, _writer, Indexer);
|
||||
var shared = Housekeeping.CleanupSteps.Shared(Trash);
|
||||
CleanupSteps = [.. shared, .. _writer.Options.CleanupSteps.Where(s => !shared.Any(o => o.Name == s.Name))];
|
||||
}
|
||||
|
||||
public ArchiveIndexer Indexer { get; }
|
||||
@@ -56,7 +58,19 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
/// <summary>Deletes sequences into the archive's trash and restores them.</summary>
|
||||
public SequenceTrash Trash { get; }
|
||||
|
||||
/// <summary>Handlers for scan, rebuild, verify, import, thumbs, proxies and maintenance jobs; register them on the <see cref="JobEngine"/>.</summary>
|
||||
/// <summary>
|
||||
/// The steps this host's <see cref="JobKind.Cleanup"/> jobs can run: the shared ones (<see cref="Housekeeping.CleanupSteps.Shared"/>),
|
||||
/// then the host's (<see cref="ArchiveServiceOptions.CleanupSteps"/>). A schedule host lists their names.
|
||||
/// </summary>
|
||||
public IReadOnlyList<Housekeeping.ICleanupStep> CleanupSteps { get; }
|
||||
|
||||
/// <summary>Where this engine's <see cref="JobKind.Backup"/> jobs put their copies (<see cref="ArchiveServiceOptions.BackupDirectory"/>; null: next to the index).</summary>
|
||||
public string? BackupDirectory => _writer.Options.BackupDirectory;
|
||||
|
||||
/// <summary>
|
||||
/// Handlers for scan, rebuild, verify, import, thumbs, proxies and maintenance jobs, the read-only duplicates and orphans
|
||||
/// reports, index backups and clean-ups (owner review 2, R10); register them on the <see cref="JobEngine"/>.
|
||||
/// </summary>
|
||||
public IReadOnlyList<IJobHandler> CreateJobHandlers() =>
|
||||
[
|
||||
new ScanJobHandler(_db, Indexer, JobKind.Scan, _writer.Options.ImagesAfterScan),
|
||||
@@ -66,6 +80,10 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
new ImageJobHandler(_db, Images, JobKind.Thumbs),
|
||||
new ImageJobHandler(_db, Images, JobKind.Proxies),
|
||||
new MaintenanceJobHandler(_db, Maintenance),
|
||||
new DuplicatesJobHandler(_db, Maintenance),
|
||||
new OrphansJobHandler(_db, Maintenance),
|
||||
new Housekeeping.BackupJobHandler(_db, _writer.Options.BackupDirectory),
|
||||
new Housekeeping.CleanupJobHandler(_db, CleanupSteps, TimeProvider.System),
|
||||
];
|
||||
|
||||
/// <summary>Makes <paramref name="root"/> a new, empty archive and indexes it.</summary>
|
||||
@@ -482,6 +500,24 @@ public static class ArchiveJobs
|
||||
new(JobKind.Maintenance, [archive.Id], archive.Name, Json(new MaintenanceParameters(dryRun), ArchiveJobJson.Default.MaintenanceParameters),
|
||||
JobPriority.Normal);
|
||||
|
||||
/// <summary><see cref="JobKind.Duplicates"/>: a read-only report of the archive's duplicate photos into the job log.</summary>
|
||||
public static ArchiveJobRequest Duplicates(Archive archive) => new(JobKind.Duplicates, [archive.Id], archive.Name, null, JobPriority.Normal);
|
||||
|
||||
/// <summary><see cref="JobKind.Orphans"/>: a read-only report of where the index and the disk disagree into the job log.</summary>
|
||||
public static ArchiveJobRequest Orphans(Archive archive) => new(JobKind.Orphans, [archive.Id], archive.Name, null, JobPriority.Normal);
|
||||
|
||||
/// <summary><see cref="JobKind.Backup"/>: a copy of the SQLite index into the backups folder, keeping the newest <paramref name="keep"/>.</summary>
|
||||
public static ArchiveJobRequest Backup(int keep = DatabaseBackups.Keep) =>
|
||||
new(JobKind.Backup, [], null, Json(new BackupParameters(keep), ArchiveJobJson.Default.BackupParameters), JobPriority.Normal);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Cleanup"/>: the clean-up <paramref name="steps"/> (by name, in order) with their age limit; the
|
||||
/// archive, when given, is what archive steps (the trash report) look at.
|
||||
/// </summary>
|
||||
public static ArchiveJobRequest Cleanup(Archive? archive, IReadOnlyList<string> steps, int olderThanDays) =>
|
||||
new(JobKind.Cleanup, archive is null ? [] : [archive.Id], archive?.Name,
|
||||
Json(new CleanupParameters(steps, olderThanDays), ArchiveJobJson.Default.CleanupParameters), JobPriority.Normal);
|
||||
|
||||
public static Task<Job> EnqueueAsync(this JobEngine engine, ArchiveJobRequest request, Guid? createdBy = null, CancellationToken cancellationToken = default) =>
|
||||
engine.EnqueueAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority, createdBy, cancellationToken);
|
||||
|
||||
|
||||
@@ -22,6 +22,15 @@ public sealed record MaintenanceParameters(bool DryRun);
|
||||
/// <summary><see cref="JobKind.Import"/>: the exact plan the user confirmed.</summary>
|
||||
public sealed record ImportJobParameters(Guid ArchiveId, ImportPlan Plan, Guid? CardId, bool Verify, Guid? UserId);
|
||||
|
||||
/// <summary><see cref="JobKind.Backup"/>: no target; the newest <paramref name="Keep"/> copies are kept.</summary>
|
||||
public sealed record BackupParameters(int Keep);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Cleanup"/>: target = the archive (or none); the clean-up steps to run, by name and in order, and
|
||||
/// the age in days from which what they clean goes (0 keeps everything).
|
||||
/// </summary>
|
||||
public sealed record CleanupParameters(IReadOnlyList<string> Steps, int OlderThanDays);
|
||||
|
||||
/// <summary>A job ready to enqueue.</summary>
|
||||
public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets, string? Label, string? ParametersJson, JobPriority Priority);
|
||||
|
||||
@@ -31,6 +40,8 @@ public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets
|
||||
[JsonSerializable(typeof(ImageJobParameters))]
|
||||
[JsonSerializable(typeof(MaintenanceParameters))]
|
||||
[JsonSerializable(typeof(ImportJobParameters))]
|
||||
[JsonSerializable(typeof(BackupParameters))]
|
||||
[JsonSerializable(typeof(CleanupParameters))]
|
||||
[JsonSerializable(typeof(CardProfile))]
|
||||
internal sealed partial class ArchiveJobJson : JsonSerializerContext
|
||||
{
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
|
||||
namespace Chronos.Data.Archiving.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Duplicates"/> as a job (owner review 2, R10): the archive's groups of photos sharing a hash, counted and
|
||||
/// the largest listed in the job log. Read-only: the Archive screen's Duplicates tab and the maintenance job's duplicate flags
|
||||
/// stay what acts on them. This makes the kind runnable on the server too (scheduled reports).
|
||||
/// </summary>
|
||||
internal sealed class DuplicatesJobHandler(ChronosDatabase db, ArchiveMaintenance maintenance) : IJobHandler
|
||||
{
|
||||
/// <summary>Groups listed one per log line, the largest first; the summary counts them all.</summary>
|
||||
private const int ListedGroups = 20;
|
||||
|
||||
public JobKind Kind => JobKind.Duplicates;
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
{
|
||||
var archive = await JobArchive.LoadAsync(db, context.Job, context.Cancellation).ConfigureAwait(false);
|
||||
await context.ReportAsync(0, 1).ConfigureAwait(false);
|
||||
var groups = await maintenance.FindDuplicatesAsync(archive.Id, context.Cancellation).ConfigureAwait(false);
|
||||
foreach (var group in groups.OrderByDescending(g => g.Frames.Count).ThenBy(g => g.Frames[0].RelativePath, StringComparer.Ordinal).Take(ListedGroups))
|
||||
context.Log(Loc.L("Archive.Log.DuplicateGroup", group.Frames[0].RelativePath, group.Frames.Count - 1));
|
||||
context.Log(Loc.L("Archive.Log.DuplicatesDone", groups.Count, groups.Sum(g => g.Frames.Count - 1)));
|
||||
context.Log(Loc.L("Archive.Log.ReportOnly"));
|
||||
await context.ReportAsync(1, 1).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Orphans"/> as a job (owner review 2, R10): where the index and the disk disagree — photos the index
|
||||
/// does not list, frames whose file is gone, sequences without their folder, folders not indexed yet — counted and listed in
|
||||
/// the job log. Read-only: the Archive screen's fixes and a scan stay what acts on them. The archive must be reachable.
|
||||
/// </summary>
|
||||
internal sealed class OrphansJobHandler(ChronosDatabase db, ArchiveMaintenance maintenance) : IJobHandler
|
||||
{
|
||||
/// <summary>Folders listed one per log line; the summary counts them all.</summary>
|
||||
private const int ListedFolders = 20;
|
||||
|
||||
public JobKind Kind => JobKind.Orphans;
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
{
|
||||
var archive = await JobArchive.LoadAsync(db, context.Job, context.Cancellation).ConfigureAwait(false);
|
||||
await context.ReportAsync(0, 1).ConfigureAwait(false);
|
||||
var report = await maintenance.FindOrphansAsync(archive, context.Cancellation).ConfigureAwait(false);
|
||||
foreach (var missing in report.MissingSequences.Take(ListedFolders))
|
||||
context.Log(Loc.L("Archive.Log.FolderMissing", missing.Folder));
|
||||
foreach (var folder in report.UnindexedFolders.Take(ListedFolders))
|
||||
context.Log(Loc.L("Archive.Log.FolderUnindexed", folder));
|
||||
context.Log(Loc.L("Archive.Log.Orphans", report.UnindexedFiles, report.MissingFiles));
|
||||
context.Log(Loc.L("Archive.Log.OrphanFolders", report.MissingSequences.Count, report.UnindexedFolders.Count));
|
||||
context.Log(Loc.L("Archive.Log.ReportOnly"));
|
||||
await context.ReportAsync(1, 1).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,19 @@ public sealed record ArchiveServiceOptions
|
||||
/// </summary>
|
||||
public Func<long> MemoryBudget { get; init; } = () => DefaultMemoryBudget;
|
||||
|
||||
/// <summary>
|
||||
/// The host's own clean-up steps (the server's uploads sweep, the desktop's cache trim), run by
|
||||
/// <see cref="Core.Model.JobKind.Cleanup"/> jobs after the shared ones of <see cref="Housekeeping.CleanupSteps"/> when a
|
||||
/// schedule names them (owner review 2, R10). A name the shared steps use already is ignored.
|
||||
/// </summary>
|
||||
public IReadOnlyList<Housekeeping.ICleanupStep> CleanupSteps { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Folder of the copies <see cref="Core.Model.JobKind.Backup"/> jobs make; null: the <c>backups</c> folder next to the
|
||||
/// SQLite index (<see cref="DatabaseBackups.DefaultDirectory"/>), where the desktop and the server keep them.
|
||||
/// </summary>
|
||||
public string? BackupDirectory { get; init; }
|
||||
|
||||
/// <summary>Half the logical cores, at least one: the parallelism when the host sets none.</summary>
|
||||
public static int DefaultParallelism => Math.Max(1, Environment.ProcessorCount / 2);
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ public abstract class ChronosRepositories
|
||||
Tags = new TagRepository(access);
|
||||
Audit = new AuditRepository(access);
|
||||
Uploads = new UploadRepository(access);
|
||||
Schedules = new ScheduleRepository(access);
|
||||
}
|
||||
|
||||
public ArchiveRepository Archives { get; }
|
||||
@@ -37,6 +38,9 @@ public abstract class ChronosRepositories
|
||||
public TagRepository Tags { get; }
|
||||
public AuditRepository Audit { get; }
|
||||
public UploadRepository Uploads { get; }
|
||||
|
||||
/// <summary>Scheduled jobs (owner review 2, R10).</summary>
|
||||
public ScheduleRepository Schedules { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -13,22 +13,43 @@ public sealed record DatabaseBackup(string Path, DateTimeOffset Created, long By
|
||||
public sealed record DatabaseSummary(int SchemaVersion, int Archives, int Sequences, long Photos);
|
||||
|
||||
/// <summary>
|
||||
/// Backups of the SQLite index (BRIEF §6.2): a <c>VACUUM INTO</c> copy made once a day while the host runs (at start
|
||||
/// when the newest copy is a day old, then checked every hour), the three newest kept; and their restore from
|
||||
/// Settings › Advanced. A restore never swaps the file under a running host: the chosen copy is staged next to the
|
||||
/// index and replaces it at the next start, before the host opens the index (so it also recovers an index that no
|
||||
/// longer opens), once the index it replaces has been kept.
|
||||
/// Backups of the SQLite index (BRIEF §6.2): <c>VACUUM INTO</c> copies in the backups folder, made by the
|
||||
/// <see cref="Core.Model.JobKind.Backup"/> jobs of the hosts' <c>index-backup</c> system schedule (owner review 2, R10: every
|
||||
/// day on the desktop, at 03:00 on the server; its recurrence and Copies kept can be edited, three by default), by Back up
|
||||
/// now, and of the index a restore replaces. Every copy keeps as many as the backup schedules keep
|
||||
/// (<see cref="KeptAsync"/>). A restore, from Settings › Advanced, never swaps the file under a running host: the chosen
|
||||
/// copy is staged next to the index and replaces it at the next start, before the host opens the index (so it also
|
||||
/// recovers an index that no longer opens), once the index it replaces has been kept.
|
||||
/// </summary>
|
||||
public static partial class DatabaseBackups
|
||||
{
|
||||
/// <summary>Copies kept (BRIEF §6.2: ×3).</summary>
|
||||
/// <summary>Copies kept by default (BRIEF §6.2: ×3).</summary>
|
||||
public const int Keep = 3;
|
||||
|
||||
/// <summary>Age of the newest copy from which the next one is due.</summary>
|
||||
public static readonly TimeSpan Interval = TimeSpan.FromDays(1);
|
||||
/// <summary>The hosts' system schedule that makes the copies.</summary>
|
||||
public const string ScheduleKey = "index-backup";
|
||||
|
||||
/// <summary>How often a running host checks whether a copy is due.</summary>
|
||||
public static readonly TimeSpan CheckInterval = TimeSpan.FromHours(1);
|
||||
/// <summary>Name of the folder next to the index that holds its copies (the desktop's and the server's).</summary>
|
||||
public const string DirectoryName = "backups";
|
||||
|
||||
/// <summary>The backups folder of the index at <paramref name="databasePath"/>: <c>backups</c> next to it.</summary>
|
||||
public static string DefaultDirectory(string databasePath) =>
|
||||
Path.Combine(Path.GetDirectoryName(Path.GetFullPath(databasePath)) ?? ".", DirectoryName);
|
||||
|
||||
/// <summary>
|
||||
/// Why <paramref name="db"/> cannot be copied by <see cref="ChronosDatabase.BackupAsync"/> (a <see cref="Scheduling.ScheduleUnavailable"/>
|
||||
/// code: <c>postgres</c>, or <c>no-index-file</c> for an index in memory); null for an SQLite index file.
|
||||
/// </summary>
|
||||
public static string? Unavailable(ChronosDatabase db)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
return db.Database switch
|
||||
{
|
||||
SqliteDatabase { Path: not null } => null,
|
||||
SqliteDatabase => Scheduling.ScheduleUnavailable.NoIndexFile,
|
||||
_ => Scheduling.ScheduleUnavailable.Postgres,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The copies of the index at <paramref name="databasePath"/> in <paramref name="directory"/>, newest first. Their
|
||||
@@ -58,39 +79,48 @@ public static partial class DatabaseBackups
|
||||
return backups;
|
||||
}
|
||||
|
||||
/// <summary>True when there is no copy yet or the newest one is at least <see cref="Interval"/> old.</summary>
|
||||
public static bool IsDue(IReadOnlyList<DatabaseBackup> backups, DateTimeOffset now) => backups.Count == 0 || now - backups[0].Created >= Interval;
|
||||
|
||||
/// <summary>
|
||||
/// Makes the daily copy of a SQLite index into <paramref name="directory"/> until <paramref name="cancellationToken"/>
|
||||
/// is cancelled: now when one is due, then whenever an hourly check finds one due. A failed copy is logged and tried
|
||||
/// again at the next check. Returns at once for PostgreSQL, which its own server tools back up.
|
||||
/// When the newest copy of <paramref name="db"/>'s index file in <paramref name="directory"/> (null: <see cref="DefaultDirectory"/>)
|
||||
/// was made; null when there is none, the index has no file, or the folder cannot be read. The hosts seed their index
|
||||
/// backup schedule with it (<see cref="Scheduling.SystemSchedule.LastDone"/>): the first copy after an upgrade is due at
|
||||
/// once only when this one is at least a whole period of the schedule's recurrence old; otherwise, and with no copy, it
|
||||
/// comes at the recurrence's first occurrence.
|
||||
/// </summary>
|
||||
public static async Task RunDailyAsync(ChronosDatabase db, string directory, TimeProvider? time = null, CancellationToken cancellationToken = default)
|
||||
public static DateTimeOffset? Newest(ChronosDatabase db, string? directory)
|
||||
{
|
||||
if (db.Database is not SqliteDatabase { Path: { } path }) return;
|
||||
var clock = time ?? TimeProvider.System;
|
||||
using var timer = new PeriodicTimer(CheckInterval, clock);
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
if (db.Database is not SqliteDatabase { Path: { } path }) return null;
|
||||
try
|
||||
{
|
||||
do
|
||||
{
|
||||
try
|
||||
{
|
||||
if (IsDue(List(directory, path), clock.GetUtcNow())) await db.BackupAsync(directory, Keep, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
|
||||
{
|
||||
Log.Warning("backup", $"The daily index backup into {directory} failed; it is tried again within the hour", ex);
|
||||
}
|
||||
}
|
||||
while (await timer.WaitForNextTickAsync(cancellationToken).ConfigureAwait(false));
|
||||
return List(directory ?? DefaultDirectory(path), path) is [var newest, ..] ? newest.Created : null;
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// How many copies the backups folder keeps: the largest Copies kept of the backup schedules, the <see cref="ScheduleKey"/>
|
||||
/// system schedule's among them, enabled or not (<see cref="Keep"/> with none). Every copy prunes to it, so Back up now, the
|
||||
/// copy kept before a restore and a schedule that keeps fewer never delete copies another schedule keeps.
|
||||
/// </summary>
|
||||
public static async Task<int> KeptAsync(ChronosDatabase db, CancellationToken cancellationToken = default) =>
|
||||
await ScheduledKeepAsync(db, cancellationToken).ConfigureAwait(false) is > 0 and var kept ? kept : Keep;
|
||||
|
||||
/// <summary>The largest Copies kept of the backup schedules (1 to <see cref="Housekeeping.BackupJobHandler.MaxKeep"/>); 0 without any.</summary>
|
||||
internal static async Task<int> ScheduledKeepAsync(ChronosDatabase db, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
var kept = 0;
|
||||
foreach (var schedule in await db.Schedules.ListAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (schedule.Action == Scheduling.ScheduleActions.Backup && Scheduling.ScheduleMapping.Parameters(schedule).Keep is { } keep)
|
||||
kept = int.Max(kept, int.Clamp(keep, 1, Housekeeping.BackupJobHandler.MaxKeep));
|
||||
}
|
||||
return kept;
|
||||
}
|
||||
|
||||
/// <summary>Counts what the index holds (the current one, for the restore's comparison).</summary>
|
||||
public static async Task<DatabaseSummary> SummarizeAsync(ChronosDatabase db, CancellationToken cancellationToken = default)
|
||||
{
|
||||
@@ -174,7 +204,7 @@ public static partial class DatabaseBackups
|
||||
/// Carries out a staged restore before the host opens the index at <paramref name="databasePath"/>, so it also
|
||||
/// recovers an index that no longer opens. The staged copy is checked first (<see cref="SummarizeBackupAsync"/>:
|
||||
/// <c>quick_check</c>, open, migration). The index as it is now is kept in <paramref name="backupDirectory"/>: as a
|
||||
/// fresh <c>VACUUM INTO</c> copy among the daily ones, or, when it cannot be read, copied there whole (with its WAL) as
|
||||
/// fresh <c>VACUUM INTO</c> copy among the others, or, when it cannot be read, copied there whole (with its WAL) as
|
||||
/// <c><name>-replaced-<stamp>.db</c>, outside the rotation, so it never pushes a good copy out. Only then is
|
||||
/// the staged copy renamed over the index: the rename consumes it, so it is never applied twice. The host's open then
|
||||
/// migrates it to this build's schema. False when none was staged.
|
||||
@@ -209,14 +239,16 @@ public static partial class DatabaseBackups
|
||||
|
||||
/// <summary>
|
||||
/// The index about to be replaced, kept in <paramref name="backupDirectory"/>: a <c>VACUUM INTO</c> copy when it opens,
|
||||
/// else the file itself with its WAL, set aside under a name the pruning of the daily copies never matches.
|
||||
/// pruning to what its backup schedules keep (<see cref="KeptAsync"/>), else the file itself with its WAL, set aside under
|
||||
/// a name the pruning of the copies never matches.
|
||||
/// </summary>
|
||||
private static async Task<string> KeepAsync(string path, string backupDirectory, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var current = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(path), cancellationToken).ConfigureAwait(false);
|
||||
return await current.BackupAsync(backupDirectory, Keep, cancellationToken).ConfigureAwait(false);
|
||||
var keep = await KeptAsync(current, cancellationToken).ConfigureAwait(false);
|
||||
return await current.BackupAsync(backupDirectory, keep, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or SchemaTooNewException)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
|
||||
namespace Chronos.Data.Housekeeping;
|
||||
|
||||
/// <summary>
|
||||
/// One step of a <see cref="JobKind.Cleanup"/> job (owner review 2, R10). The shared steps are in <see cref="CleanupSteps"/>;
|
||||
/// a host adds its own (the server's uploads sweep, the desktop's cache trim) through
|
||||
/// <see cref="ArchiveServiceOptions.CleanupSteps"/>. A step must be safe to run again at any time, honour
|
||||
/// <see cref="CleanupContext.Cancellation"/>, and never delete user data (BRIEF §0.2 rule 8): only what the product made
|
||||
/// and no longer needs (history, temporary files), never originals or the trash.
|
||||
/// </summary>
|
||||
public interface ICleanupStep
|
||||
{
|
||||
/// <summary>Wire name, kebab-case (<c>job-history</c>): what a schedule's <c>steps</c> list.</summary>
|
||||
string Name { get; }
|
||||
|
||||
/// <summary>Runs the step and returns the line the job log shows for it (localized).</summary>
|
||||
Task<string> RunAsync(CleanupContext context, CleanupParameters parameters);
|
||||
}
|
||||
|
||||
/// <summary>What a clean-up step works with: the index, the job's archive (if any), the running job and the time it started.</summary>
|
||||
public sealed class CleanupContext(ChronosDatabase database, Archive? archive, JobContext job, DateTimeOffset now)
|
||||
{
|
||||
public ChronosDatabase Database { get; } = database;
|
||||
|
||||
/// <summary>The archive the job targets; null when it targets none (no archive open).</summary>
|
||||
public Archive? Archive { get; } = archive;
|
||||
|
||||
/// <summary>The running clean-up job: its log and cancellation.</summary>
|
||||
public JobContext Job { get; } = job;
|
||||
|
||||
/// <summary>When the job started its steps (UTC); ages count from it.</summary>
|
||||
public DateTimeOffset Now { get; } = now;
|
||||
|
||||
public CancellationToken Cancellation => Job.Cancellation;
|
||||
|
||||
/// <summary>The instant before which things are <paramref name="olderThanDays"/> old; null for 0, which keeps everything.</summary>
|
||||
public DateTimeOffset? Before(int olderThanDays) => olderThanDays > 0 ? Now - TimeSpan.FromDays(olderThanDays) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The clean-up steps every host has (owner review 2, R10): <see cref="JobHistory"/> (finished jobs, which the job engine
|
||||
/// purged at start before), <see cref="Audit"/> (the audit log; 0 days keeps it) and <see cref="TrashReport"/> (lists the
|
||||
/// archive's trash entries older than the limit with their sizes; it never deletes: emptying the trash stays a user action).
|
||||
/// </summary>
|
||||
public static class CleanupSteps
|
||||
{
|
||||
public const string JobHistory = "job-history";
|
||||
public const string Audit = "audit";
|
||||
public const string TrashReport = "trash-report";
|
||||
|
||||
/// <summary>Days of job history the housekeeping schedule keeps unless the host says otherwise (BRIEF §14.6: 90).</summary>
|
||||
public const int DefaultHistoryDays = 90;
|
||||
|
||||
/// <summary>Age in days from which the trash report lists an entry unless the schedule says otherwise.</summary>
|
||||
public const int DefaultTrashDays = 30;
|
||||
|
||||
/// <summary>Trash entries listed one per log line; the report counts them all.</summary>
|
||||
internal const int ListedTrashEntries = 20;
|
||||
|
||||
/// <summary>The shared steps, in the order a host lists them: job history, audit log, trash report.</summary>
|
||||
public static IReadOnlyList<ICleanupStep> Shared(SequenceTrash trash) => [new JobHistoryStep(), new AuditStep(), new TrashReportStep(trash)];
|
||||
|
||||
/// <summary>"12.4 MB" in the language of the log.</summary>
|
||||
internal static string Megabytes(long bytes) => Loc.L("Common.Size.MB", (bytes / 1e6).ToString("0.#", Loc.Culture));
|
||||
|
||||
private sealed class JobHistoryStep : ICleanupStep
|
||||
{
|
||||
public string Name => JobHistory;
|
||||
|
||||
public async Task<string> RunAsync(CleanupContext context, CleanupParameters parameters)
|
||||
{
|
||||
if (context.Before(parameters.OlderThanDays) is not { } before) return Loc.L("Archive.Log.HistoryKept");
|
||||
var removed = await context.Database.Jobs.PurgeHistoryAsync(before, context.Cancellation).ConfigureAwait(false);
|
||||
return Loc.L("Archive.Log.HistoryPurged", removed);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class AuditStep : ICleanupStep
|
||||
{
|
||||
public string Name => Audit;
|
||||
|
||||
public async Task<string> RunAsync(CleanupContext context, CleanupParameters parameters)
|
||||
{
|
||||
if (context.Before(parameters.OlderThanDays) is not { } before) return Loc.L("Archive.Log.AuditKept");
|
||||
var removed = await context.Database.Audit.PurgeAsync(before, context.Cancellation).ConfigureAwait(false);
|
||||
return Loc.L("Archive.Log.AuditPurged", removed);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads the trash and reports; nothing is moved or deleted (BRIEF §0.2 rule 8).</summary>
|
||||
private sealed class TrashReportStep(SequenceTrash trash) : ICleanupStep
|
||||
{
|
||||
public string Name => TrashReport;
|
||||
|
||||
public async Task<string> RunAsync(CleanupContext context, CleanupParameters parameters)
|
||||
{
|
||||
if (context.Archive is not { } archive || ArchiveVolume.Probe(new ArchivePaths(archive.RootPath)) == ArchiveAvailability.Offline)
|
||||
return Loc.L("Archive.Log.TrashOffline");
|
||||
var before = context.Before(parameters.OlderThanDays);
|
||||
var old = (await trash.ListAsync(archive, context.Cancellation).ConfigureAwait(false))
|
||||
.Where(e => before is null || e.DeletedAt < before).OrderBy(e => e.DeletedAt).ToList();
|
||||
foreach (var entry in old.Take(ListedTrashEntries))
|
||||
{
|
||||
context.Job.Log(Loc.L("Archive.Log.TrashEntry", entry.DeletedAt.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture),
|
||||
entry.Title, Megabytes(entry.Bytes)));
|
||||
}
|
||||
return Loc.L("Archive.Log.TrashReport", old.Count, Megabytes(old.Sum(e => e.Bytes)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Sqlite;
|
||||
|
||||
namespace Chronos.Data.Housekeeping;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Backup"/> (owner review 2, R10): a <c>VACUUM INTO</c> copy of the SQLite index into
|
||||
/// <paramref name="directory"/> (by default the <c>backups</c> folder next to the index, <see cref="DatabaseBackups.DefaultDirectory"/>),
|
||||
/// keeping the newest <see cref="BackupParameters.Keep"/>, or more when a backup schedule keeps more (one folder, one
|
||||
/// retention: <see cref="DatabaseBackups.KeptAsync"/>). A PostgreSQL index, or one without a file, cannot be
|
||||
/// copied this way (<see cref="DatabaseBackups.Unavailable"/>): the job fails with that reason, and schedules do not queue it.
|
||||
/// </summary>
|
||||
internal sealed class BackupJobHandler(ChronosDatabase db, string? directory) : IJobHandler
|
||||
{
|
||||
/// <summary>Most copies a schedule may keep.</summary>
|
||||
public const int MaxKeep = 100;
|
||||
|
||||
public JobKind Kind => JobKind.Backup;
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
{
|
||||
if (db.Database is not SqliteDatabase { Path: { } path })
|
||||
throw new NotSupportedException(DatabaseBackups.Unavailable(db) == Scheduling.ScheduleUnavailable.Postgres
|
||||
? "Backups of a PostgreSQL database are made with the server's own tools."
|
||||
: "An index without a file cannot be backed up.");
|
||||
var own = Math.Clamp(ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.BackupParameters, new BackupParameters(DatabaseBackups.Keep)).Keep, 1, MaxKeep);
|
||||
var keep = int.Max(own, await DatabaseBackups.ScheduledKeepAsync(db, context.Cancellation).ConfigureAwait(false));
|
||||
await context.ReportAsync(0, 1).ConfigureAwait(false);
|
||||
var copy = await db.BackupAsync(directory ?? DatabaseBackups.DefaultDirectory(path), keep, context.Cancellation).ConfigureAwait(false);
|
||||
context.Log(Loc.L("Archive.Log.BackupDone", copy, CleanupSteps.Megabytes(new FileInfo(copy).Length), keep));
|
||||
await context.ReportAsync(1, 1).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Cleanup"/> (owner review 2, R10): runs the named steps of <see cref="CleanupParameters"/> in order,
|
||||
/// each with the job's age limit, and logs one line per step. A step that fails is logged and the others still run; the job
|
||||
/// then fails naming it. Steps are quick and safe to repeat, so a resumed job runs them all again (no checkpoint). An
|
||||
/// unknown name (a step of another host, or of a newer build) is logged and skipped.
|
||||
/// </summary>
|
||||
internal sealed class CleanupJobHandler(ChronosDatabase db, IReadOnlyList<ICleanupStep> steps, TimeProvider time) : IJobHandler
|
||||
{
|
||||
public JobKind Kind => JobKind.Cleanup;
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
{
|
||||
var parameters = ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.CleanupParameters, new CleanupParameters([], 0));
|
||||
var archive = context.Job.TargetIds.Count > 0 ? await db.Archives.GetAsync(context.Job.TargetIds[0], context.Cancellation).ConfigureAwait(false) : null;
|
||||
var cleanup = new CleanupContext(db, archive, context, time.GetUtcNow());
|
||||
var names = parameters.Steps;
|
||||
var failed = new List<string>();
|
||||
for (var i = 0; i < names.Count; i++)
|
||||
{
|
||||
context.Cancellation.ThrowIfCancellationRequested();
|
||||
await context.ReportAsync(i, names.Count).ConfigureAwait(false);
|
||||
var step = steps.FirstOrDefault(s => string.Equals(s.Name, names[i], StringComparison.Ordinal));
|
||||
if (step is null)
|
||||
{
|
||||
context.Log(Loc.L("Archive.Log.StepUnknown", names[i]));
|
||||
continue;
|
||||
}
|
||||
try
|
||||
{
|
||||
context.Log(await step.RunAsync(cleanup, parameters).ConfigureAwait(false));
|
||||
}
|
||||
catch (Exception ex) when (!(ex is OperationCanceledException && context.Cancellation.IsCancellationRequested))
|
||||
{
|
||||
Log.Warning("jobs", $"Clean-up step {step.Name} of job {context.Job.Id} failed", ex);
|
||||
context.Log(Loc.L("Archive.Log.StepFailed", step.Name, ex.Message));
|
||||
failed.Add(step.Name);
|
||||
}
|
||||
}
|
||||
await context.ReportAsync(names.Count, names.Count).ConfigureAwait(false);
|
||||
if (failed.Count > 0) throw new InvalidOperationException($"Clean-up steps failed: {string.Join(", ", failed)}.");
|
||||
}
|
||||
}
|
||||
@@ -25,9 +25,6 @@ public sealed record JobEngineOptions
|
||||
/// <summary>Fallback poll for jobs enqueued by other processes; also how often the priority queue is reviewed.</summary>
|
||||
public TimeSpan PollInterval { get; init; } = TimeSpan.FromSeconds(3);
|
||||
|
||||
/// <summary>Finished jobs older than this are purged (BRIEF §14.6: 90 days).</summary>
|
||||
public TimeSpan HistoryRetention { get; init; } = TimeSpan.FromDays(90);
|
||||
|
||||
/// <summary>Clock of the throughput windows and the checkpoint interval (tests pass their own).</summary>
|
||||
public TimeProvider Time { get; init; } = TimeProvider.System;
|
||||
|
||||
@@ -38,7 +35,8 @@ public sealed record JobEngineOptions
|
||||
/// <summary>
|
||||
/// Persistent job queue runner (BRIEF §14.6, amended by owner review 1): one worker claims queued jobs from the database
|
||||
/// in claim order, runs the registered handler, checkpoints progress, and survives crashes (running jobs are requeued at
|
||||
/// start with their checkpoints). Used by the desktop client (local mode) and the server. Jobs an
|
||||
/// start with their checkpoints). Used by the desktop client (local mode) and the server. The history of finished jobs is
|
||||
/// purged by the housekeeping schedule's job-history clean-up step, not here (owner review 2, R10). Jobs an
|
||||
/// <see cref="ISelectiveJobHandler"/> declines stay queued for other claimers. With the priority queue on
|
||||
/// (<see cref="JobEngineOptions.PriorityQueue"/>) a queued job of a higher level makes the running job of a lower level
|
||||
/// yield: it goes back to the queue with its checkpoint and resumes by itself afterwards, never interrupted by the
|
||||
@@ -87,12 +85,11 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
/// <summary>The priority queue as it is now (<see cref="JobEngineOptions.PriorityQueue"/>).</summary>
|
||||
public JobPriorityQueue PriorityQueue => Options.PriorityQueue?.Invoke() ?? JobPriorityQueue.Off;
|
||||
|
||||
/// <summary>Requeues this worker's interrupted jobs, purges old history and starts the worker and the queue's review.</summary>
|
||||
/// <summary>Requeues this worker's interrupted jobs and starts the worker and the queue's review.</summary>
|
||||
public async Task StartAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var requeued = await _db.Jobs.RequeueRunningAsync(Options.WorkerId, cancellationToken).ConfigureAwait(false);
|
||||
if (requeued > 0) Log.Info("jobs", $"Requeued {requeued} interrupted job(s)");
|
||||
await _db.Jobs.PurgeHistoryAsync(DateTimeOffset.UtcNow - Options.HistoryRetention, cancellationToken).ConfigureAwait(false);
|
||||
// Only kinds this engine can run: an empty filter would claim (and fail) every job, render-node work included.
|
||||
_kinds = [.. (Options.Kinds ?? _handlers.Keys).Where(_handlers.ContainsKey).Distinct()];
|
||||
_selective = _kinds.Select(k => _handlers[k]).OfType<ISelectiveJobHandler>().ToDictionary(h => h.Kind);
|
||||
@@ -118,7 +115,18 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
/// <summary>Queues a job and wakes a worker.</summary>
|
||||
public Task<Job> EnqueueAsync(JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel = null, string? parametersJson = null,
|
||||
JobPriority priority = JobPriority.Normal, Guid? createdBy = null, CancellationToken cancellationToken = default) =>
|
||||
EnqueueAsync(Guid.CreateVersion7(), kind, targets, targetLabel, parametersJson, priority, createdBy, cancellationToken);
|
||||
EnqueueAsync(Guid.CreateVersion7(), kind, targets, targetLabel, parametersJson, priority, createdBy, null, cancellationToken);
|
||||
|
||||
/// <summary>Queues a job that the schedule <paramref name="scheduleId"/> fired (<see cref="Job.ScheduleId"/>) and wakes a worker.</summary>
|
||||
public Task<Job> EnqueueAsync(JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel, string? parametersJson, JobPriority priority,
|
||||
Guid? createdBy, Guid? scheduleId, CancellationToken cancellationToken = default) =>
|
||||
EnqueueAsync(Guid.CreateVersion7(), kind, targets, targetLabel, parametersJson, priority, createdBy, scheduleId, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// True when this engine runs jobs of <paramref name="kind"/>: it has a handler for it and <see cref="JobEngineOptions.Kinds"/>
|
||||
/// does not leave it out. Known before <see cref="StartAsync"/>, so a host that does not start the engine still answers.
|
||||
/// </summary>
|
||||
public bool CanRun(JobKind kind) => _handlers.ContainsKey(kind) && (Options.Kinds is null || Options.Kinds.Contains(kind));
|
||||
|
||||
/// <summary>Cancels a queued or running job; a running handler observes its token.</summary>
|
||||
public Task CancelAsync(Guid id, CancellationToken cancellationToken = default) => TransitionAsync(id, JobState.Cancelled, cancellationToken);
|
||||
@@ -212,7 +220,7 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
var id = Guid.CreateVersion7();
|
||||
// Known before the job is queued, so the review its queueing starts already leaves the parent running.
|
||||
if (_running.TryGetValue(parent, out var run)) run.FollowUps.TryAdd(id, 0);
|
||||
return await EnqueueAsync(id, kind, targets, label, parametersJson, priority, createdBy, cancellationToken).ConfigureAwait(false);
|
||||
return await EnqueueAsync(id, kind, targets, label, parametersJson, priority, createdBy, null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal void StopJob(Guid id)
|
||||
@@ -242,7 +250,7 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
}
|
||||
|
||||
private async Task<Job> EnqueueAsync(Guid id, JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel, string? parametersJson,
|
||||
JobPriority priority, Guid? createdBy, CancellationToken cancellationToken)
|
||||
JobPriority priority, Guid? createdBy, Guid? scheduleId, CancellationToken cancellationToken)
|
||||
{
|
||||
var job = new Job
|
||||
{
|
||||
@@ -255,6 +263,7 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
State = JobState.Queued,
|
||||
CreatedBy = createdBy,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
ScheduleId = scheduleId,
|
||||
};
|
||||
await _db.Jobs.EnqueueAsync(job, cancellationToken).ConfigureAwait(false);
|
||||
JobChanged?.Invoke(job);
|
||||
|
||||
@@ -21,7 +21,10 @@ public enum JobKindPriority
|
||||
/// </summary>
|
||||
public sealed record JobPriorityQueue
|
||||
{
|
||||
/// <summary>The levels a kind has unless the user changed it: renders, imports and downloads first; the long passes that resume anywhere last.</summary>
|
||||
/// <summary>
|
||||
/// The levels a kind has unless the user changed it: renders, imports and downloads first; the long passes that resume
|
||||
/// anywhere, and the housekeeping of the schedules (backups, clean-ups), last.
|
||||
/// </summary>
|
||||
public static IReadOnlyDictionary<JobKind, JobKindPriority> DefaultLevels { get; } = new Dictionary<JobKind, JobKindPriority>
|
||||
{
|
||||
[JobKind.Render] = JobKindPriority.High,
|
||||
@@ -29,6 +32,8 @@ public sealed record JobPriorityQueue
|
||||
[JobKind.Download] = JobKindPriority.High,
|
||||
[JobKind.Verify] = JobKindPriority.Low,
|
||||
[JobKind.Proxies] = JobKindPriority.Low,
|
||||
[JobKind.Backup] = JobKindPriority.Low,
|
||||
[JobKind.Cleanup] = JobKindPriority.Low,
|
||||
};
|
||||
|
||||
/// <summary>The strict queue: no levels, no interruptions.</summary>
|
||||
|
||||
@@ -56,6 +56,7 @@ public static class JobWire
|
||||
Created = dto.Created,
|
||||
Started = dto.Started,
|
||||
Finished = dto.Finished,
|
||||
ScheduleId = dto.ScheduleId,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
-- Scheduled jobs (owner review 2, R10): one row per schedule, the timers a host used to run out of sight included as
|
||||
-- system schedules (system_key set, seeded by the host at start, never here). next_run is claimed by compare-and-set,
|
||||
-- so one process fires each run. Jobs remember the schedule that queued them. Mirrors sqlite/0007_schedules.sql.
|
||||
|
||||
CREATE TABLE schedules (
|
||||
id uuid NOT NULL PRIMARY KEY,
|
||||
system_key text COLLATE "C" UNIQUE,
|
||||
name text NOT NULL,
|
||||
action text NOT NULL,
|
||||
target text NOT NULL DEFAULT 'current',
|
||||
parameters_json jsonb,
|
||||
recurrence text NOT NULL,
|
||||
catch_up boolean NOT NULL DEFAULT TRUE,
|
||||
priority integer NOT NULL DEFAULT 0,
|
||||
enabled boolean NOT NULL DEFAULT TRUE,
|
||||
next_run timestamptz,
|
||||
last_run timestamptz,
|
||||
last_job_id uuid,
|
||||
last_outcome text,
|
||||
created_by uuid,
|
||||
created timestamptz NOT NULL,
|
||||
updated timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX ix_schedules_due ON schedules (enabled, next_run);
|
||||
|
||||
ALTER TABLE jobs ADD COLUMN schedule_id uuid;
|
||||
CREATE INDEX ix_jobs_schedule ON jobs (schedule_id, created);
|
||||
@@ -0,0 +1,27 @@
|
||||
-- Scheduled jobs (owner review 2, R10): one row per schedule, the timers a host used to run out of sight included as
|
||||
-- system schedules (system_key set, seeded by the host at start, never here). next_run is claimed by compare-and-set,
|
||||
-- so one process fires each run. Jobs remember the schedule that queued them. Mirrors postgres/0007_schedules.sql.
|
||||
|
||||
CREATE TABLE schedules (
|
||||
id TEXT NOT NULL PRIMARY KEY,
|
||||
system_key TEXT UNIQUE,
|
||||
name TEXT NOT NULL,
|
||||
action TEXT NOT NULL,
|
||||
target TEXT NOT NULL DEFAULT 'current',
|
||||
parameters_json TEXT,
|
||||
recurrence TEXT NOT NULL,
|
||||
catch_up INTEGER NOT NULL DEFAULT 1,
|
||||
priority INTEGER NOT NULL DEFAULT 0,
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
next_run TEXT,
|
||||
last_run TEXT,
|
||||
last_job_id TEXT,
|
||||
last_outcome TEXT,
|
||||
created_by TEXT,
|
||||
created TEXT NOT NULL,
|
||||
updated TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX ix_schedules_due ON schedules (enabled, next_run);
|
||||
|
||||
ALTER TABLE jobs ADD COLUMN schedule_id TEXT;
|
||||
CREATE INDEX ix_jobs_schedule ON jobs (schedule_id, created);
|
||||
@@ -2,7 +2,7 @@ using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.Data.Repositories;
|
||||
|
||||
/// <summary>Append-only record of who did what (BRIEF §5 AuditLog, §14.2).</summary>
|
||||
/// <summary>Append-only record of who did what (BRIEF §5 AuditLog, §14.2); old entries leave only through a retention (<see cref="PurgeAsync"/>).</summary>
|
||||
public sealed class AuditRepository
|
||||
{
|
||||
private const string Columns = "id, at, user_id, username, action, target_kind, target_id, details, remote_address";
|
||||
@@ -16,6 +16,10 @@ public sealed class AuditRepository
|
||||
[entry.Id, entry.At, entry.UserId, entry.Username, entry.Action, entry.TargetKind, entry.TargetId, entry.Details, entry.RemoteAddress],
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <summary>Deletes the entries written before <paramref name="before"/> (the audit retention's clean-up step); returns how many.</summary>
|
||||
public Task<int> PurgeAsync(DateTimeOffset before, CancellationToken cancellationToken = default) =>
|
||||
_db.ExecuteAsync("DELETE FROM audit_log WHERE at < $1", [before], cancellationToken);
|
||||
|
||||
/// <summary>Entries newest first, optionally of one user.</summary>
|
||||
public Task<Page<AuditEntry>> ListAsync(Guid? userId = null, int limit = 100, string? cursor = null, CancellationToken cancellationToken = default) =>
|
||||
ListAsync(userId, action: null, limit, cursor, cancellationToken);
|
||||
|
||||
@@ -15,7 +15,11 @@ public sealed class JobRepository
|
||||
{
|
||||
private const string Columns =
|
||||
"id, kind, target_ids, target_label, parameters_json, state, priority, progress_done, progress_total, items_per_second, " +
|
||||
"eta_seconds, checkpoint, log_tail, created_by, node_id, attempts, error, created, started, finished";
|
||||
"eta_seconds, checkpoint, log_tail, created_by, node_id, attempts, error, created, started, finished, schedule_id";
|
||||
|
||||
/// <summary>The states of a job that has not ended: queued, running, paused.</summary>
|
||||
private static readonly string PendingStates =
|
||||
string.Join(", ", new[] { JobState.Queued, JobState.Running, JobState.Paused }.Select(s => ((int)s).ToString(CultureInfo.InvariantCulture)));
|
||||
|
||||
private readonly DbAccess _db;
|
||||
|
||||
@@ -23,11 +27,11 @@ public sealed class JobRepository
|
||||
|
||||
public async Task EnqueueAsync(Job job, CancellationToken cancellationToken = default) =>
|
||||
await _db.ExecuteAsync(
|
||||
$"INSERT INTO jobs ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)",
|
||||
$"INSERT INTO jobs ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21)",
|
||||
[
|
||||
job.Id, (int)job.Kind, string.Join(',', job.TargetIds), job.TargetLabel, DbParam.Json(job.ParametersJson), (int)job.State,
|
||||
(int)job.Priority, job.ProgressDone, job.ProgressTotal, job.ItemsPerSecond, job.Eta?.TotalSeconds, job.Checkpoint, job.LogTail,
|
||||
job.CreatedBy, job.NodeId, job.Attempts, job.Error, job.Created, job.Started, job.Finished,
|
||||
job.CreatedBy, job.NodeId, job.Attempts, job.Error, job.Created, job.Started, job.Finished, job.ScheduleId,
|
||||
], cancellationToken).ConfigureAwait(false);
|
||||
|
||||
public Task<Job?> GetAsync(Guid id, CancellationToken cancellationToken = default) =>
|
||||
@@ -173,6 +177,73 @@ public sealed class JobRepository
|
||||
$"SELECT count(*) FROM jobs WHERE state = {(int)JobState.Queued} AND kind = $1 AND target_ids = $2",
|
||||
[(int)kind, targetId.ToString()], cancellationToken).ConfigureAwait(false) > 0;
|
||||
|
||||
/// <summary>
|
||||
/// True when a job of one of <paramref name="kinds"/> is queued, running or paused; with <paramref name="targetIds"/>,
|
||||
/// only such a job that targets at least one of them (an archive, sequences) counts. A schedule does not queue its
|
||||
/// action again while one waits (owner review 2, R10).
|
||||
/// </summary>
|
||||
public async Task<bool> HasPendingAsync(IReadOnlyCollection<JobKind> kinds, IReadOnlyCollection<Guid>? targetIds = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(kinds);
|
||||
if (kinds.Count == 0 || targetIds is { Count: 0 }) return false;
|
||||
var p = new SqlParameters();
|
||||
var sql = $"SELECT count(*) FROM jobs WHERE state IN ({PendingStates}) AND kind IN ({KindList(kinds)})";
|
||||
// Target ids are stored comma-joined as lower-case text, which never holds a LIKE wildcard.
|
||||
if (targetIds is not null)
|
||||
sql += $" AND ({string.Join(" OR ", targetIds.Distinct().Select(id => $"target_ids LIKE {p.Add(SqlDialect.ContainsPattern(id.ToString()))} ESCAPE '\\'"))})";
|
||||
return await _db.ScalarAsync<long>(sql, p.ToArray(), cancellationToken).ConfigureAwait(false) > 0;
|
||||
}
|
||||
|
||||
/// <summary>The targets of the queued, running and paused jobs of <paramref name="kind"/> (the newest 5000 such jobs).</summary>
|
||||
public Task<HashSet<Guid>> ListPendingTargetsAsync(JobKind kind, CancellationToken cancellationToken = default) =>
|
||||
_db.RunAsync(async session =>
|
||||
{
|
||||
var rows = await session.QueryListAsync(
|
||||
$"SELECT target_ids FROM jobs WHERE kind = $1 AND state IN ({PendingStates}) ORDER BY created DESC, id DESC LIMIT 5000",
|
||||
[(int)kind], r => r.GetString(0), cancellationToken).ConfigureAwait(false);
|
||||
var ids = new HashSet<Guid>();
|
||||
foreach (var text in rows)
|
||||
{
|
||||
if (text.Length == 0) continue;
|
||||
foreach (var id in text.Split(',')) ids.Add(Guid.Parse(id));
|
||||
}
|
||||
return ids;
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>The jobs the schedule <paramref name="scheduleId"/> queued, newest first.</summary>
|
||||
public Task<IReadOnlyList<Job>> ListByScheduleAsync(Guid scheduleId, int limit = 20, CancellationToken cancellationToken = default) =>
|
||||
_db.ListAsync($"SELECT {Columns} FROM jobs WHERE schedule_id = $1 ORDER BY created DESC, id DESC LIMIT $2",
|
||||
[scheduleId, Cursor.ClampLimit(limit)], Map, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// The jobs the schedule <paramref name="scheduleId"/> queued, newest first, a page at a time (the runs a schedule's
|
||||
/// row lists in the admin panel); <paramref name="cursor"/> continues after the previous page.
|
||||
/// </summary>
|
||||
public Task<Page<Job>> PageByScheduleAsync(Guid scheduleId, int limit = 20, string? cursor = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var p = new SqlParameters();
|
||||
var where = $"schedule_id = {p.Add(scheduleId)}";
|
||||
if (cursor is not null)
|
||||
{
|
||||
var (value, id) = Cursor.Decode("schedule-runs", cursor);
|
||||
where += " AND " + Cursor.After("created", "id", descending: true, value, id, p.Add);
|
||||
}
|
||||
var take = Cursor.ClampLimit(limit);
|
||||
var sql = $"SELECT {Columns} FROM jobs WHERE {where} ORDER BY created DESC, id DESC LIMIT {p.Add(take + 1)}";
|
||||
return _db.RunAsync(async session =>
|
||||
{
|
||||
var jobs = await session.QueryListAsync(sql, p.ToArray(), Map, cancellationToken).ConfigureAwait(false);
|
||||
string? next = null;
|
||||
if (jobs.Count > take)
|
||||
{
|
||||
jobs.RemoveAt(take);
|
||||
next = Cursor.Encode("schedule-runs", jobs[^1].Created, jobs[^1].Id);
|
||||
}
|
||||
return new Page<Job>(jobs, next);
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Claims one specific queued job for <paramref name="nodeId"/> (render nodes pick by capability); null when another
|
||||
/// claimer was faster or the job is no longer queued.
|
||||
@@ -245,5 +316,6 @@ public sealed class JobRepository
|
||||
Created = r.GetDateTimeOffset(17),
|
||||
Started = r.GetDateTimeOffsetOrNull(18),
|
||||
Finished = r.GetDateTimeOffsetOrNull(19),
|
||||
ScheduleId = r.GetGuidOrNull(20),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Scheduling;
|
||||
|
||||
namespace Chronos.Data.Repositories;
|
||||
|
||||
/// <summary>
|
||||
/// Scheduled jobs (owner review 2, R10). A run is claimed by moving <c>next_run</c> with a compare-and-set
|
||||
/// (<see cref="TryAdvanceAsync"/>), so when several processes share one database (server instances on one PostgreSQL)
|
||||
/// exactly one fires it. System schedules are seeded without touching rows that exist (<see cref="EnsureSystemAsync"/>), so
|
||||
/// what the user changed stays, and they are never deleted (<see cref="DeleteAsync"/>).
|
||||
/// </summary>
|
||||
public sealed class ScheduleRepository
|
||||
{
|
||||
private const string Columns =
|
||||
"id, system_key, name, action, target, parameters_json, recurrence, catch_up, priority, enabled, next_run, last_run, last_job_id, " +
|
||||
"last_outcome, created_by, created, updated";
|
||||
|
||||
private const string InsertSql =
|
||||
$"INSERT INTO schedules ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)";
|
||||
|
||||
/// <summary>System schedules first, then the others, oldest first.</summary>
|
||||
private const string Order = "CASE WHEN system_key IS NULL THEN 1 ELSE 0 END, created, id";
|
||||
|
||||
private readonly DbAccess _db;
|
||||
|
||||
internal ScheduleRepository(DbAccess db) => _db = db;
|
||||
|
||||
/// <summary>Every schedule: the system ones first, then the others, oldest first.</summary>
|
||||
public Task<IReadOnlyList<Schedule>> ListAsync(CancellationToken cancellationToken = default) =>
|
||||
_db.ListAsync($"SELECT {Columns} FROM schedules ORDER BY {Order}", [], Map, cancellationToken);
|
||||
|
||||
public Task<Schedule?> GetAsync(Guid id, CancellationToken cancellationToken = default) =>
|
||||
_db.SingleAsync($"SELECT {Columns} FROM schedules WHERE id = $1", [id], Map, cancellationToken);
|
||||
|
||||
public Task<Schedule?> GetBySystemKeyAsync(string systemKey, CancellationToken cancellationToken = default) =>
|
||||
_db.SingleAsync($"SELECT {Columns} FROM schedules WHERE system_key = $1", [systemKey], Map, cancellationToken);
|
||||
|
||||
/// <summary>Adds a schedule; a <see cref="Schedule.SystemKey"/> another row has already fails (unique).</summary>
|
||||
public async Task InsertAsync(Schedule schedule, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schedule);
|
||||
await _db.ExecuteAsync(InsertSql, Values(schedule), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores what a user edits — name, action, target, parameters, recurrence, catch-up, priority, enabled — and the update
|
||||
/// time; with <paramref name="setNextRun"/> the next run too, otherwise it stays as stored (a run the scheduler claims
|
||||
/// meanwhile is not undone). The key, the creation and the last run stay as stored. False when the schedule is gone.
|
||||
/// </summary>
|
||||
public async Task<bool> UpdateAsync(Schedule schedule, bool setNextRun = true, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schedule);
|
||||
return await _db.ExecuteAsync(
|
||||
"UPDATE schedules SET name = $2, action = $3, target = $4, parameters_json = $5, recurrence = $6, catch_up = $7, priority = $8, " +
|
||||
$"enabled = $9, updated = $10{(setNextRun ? ", next_run = $11" : string.Empty)} WHERE id = $1",
|
||||
[
|
||||
schedule.Id, schedule.Name, schedule.Action, schedule.Target, DbParam.Json(schedule.ParametersJson), schedule.Recurrence,
|
||||
schedule.CatchUp, (int)schedule.Priority, schedule.Enabled, schedule.Updated, .. setNextRun ? new DbParam[] { schedule.NextRun } : [],
|
||||
], cancellationToken).ConfigureAwait(false) > 0;
|
||||
}
|
||||
|
||||
/// <summary>Deletes a schedule a user created; false when it is unknown or a system schedule (those are disabled, never deleted).</summary>
|
||||
public async Task<bool> DeleteAsync(Guid id, CancellationToken cancellationToken = default) =>
|
||||
await _db.ExecuteAsync("DELETE FROM schedules WHERE id = $1 AND system_key IS NULL", [id], cancellationToken).ConfigureAwait(false) > 0;
|
||||
|
||||
/// <summary>
|
||||
/// Inserts each system schedule whose key no row has yet (<c>INSERT … ON CONFLICT (system_key) DO NOTHING</c>), with
|
||||
/// no next run (the scheduler computes it), or due at <paramref name="now"/> when it is enabled and its work was last
|
||||
/// done a period or more before (<see cref="SystemSchedule.LastDone"/>); rows that exist keep whatever the user changed.
|
||||
/// Rows added together are stamped a microsecond apart, so listings keep the host's order. Returns how many were added.
|
||||
/// </summary>
|
||||
public Task<int> EnsureSystemAsync(IEnumerable<SystemSchedule> schedules, DateTimeOffset now, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schedules);
|
||||
var rows = schedules.Select((s, i) => FromSystem(s, now.AddTicks(i * TimeSpan.TicksPerMicrosecond)) with
|
||||
{
|
||||
NextRun = s.Enabled && s.LastDone is { } done && now - done >= s.Recurrence.Period ? now : null,
|
||||
}).ToList();
|
||||
return rows.Count == 0 ? Task.FromResult(0) : _db.InTransactionAsync(async session =>
|
||||
{
|
||||
var added = 0;
|
||||
foreach (var row in rows)
|
||||
added += await session.ExecuteAsync(InsertSql + " ON CONFLICT (system_key) DO NOTHING", Values(row), cancellationToken).ConfigureAwait(false);
|
||||
return added;
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts the system schedule <paramref name="systemKey"/> back to <paramref name="defaults"/> (name, action, parameters,
|
||||
/// recurrence, catch-up, priority, enabled) with no next run, so the scheduler computes it again; its history stays.
|
||||
/// False when no row has that key.
|
||||
/// </summary>
|
||||
public async Task<bool> ResetSystemAsync(string systemKey, SystemSchedule defaults, DateTimeOffset now, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(defaults);
|
||||
var row = FromSystem(defaults, now);
|
||||
return await _db.ExecuteAsync(
|
||||
"UPDATE schedules SET name = $2, action = $3, target = $4, parameters_json = $5, recurrence = $6, catch_up = $7, priority = $8, " +
|
||||
"enabled = $9, next_run = NULL, updated = $10 WHERE system_key = $1",
|
||||
[
|
||||
systemKey, row.Name, row.Action, row.Target, DbParam.Json(row.ParametersJson), row.Recurrence, row.CatchUp, (int)row.Priority, row.Enabled,
|
||||
now,
|
||||
], cancellationToken).ConfigureAwait(false) > 0;
|
||||
}
|
||||
|
||||
/// <summary>Enabled schedules whose next run is at or before <paramref name="nowUtc"/>, the longest due first.</summary>
|
||||
public Task<IReadOnlyList<Schedule>> ListDueAsync(DateTimeOffset nowUtc, CancellationToken cancellationToken = default) =>
|
||||
_db.ListAsync($"SELECT {Columns} FROM schedules WHERE enabled = TRUE AND next_run IS NOT NULL AND next_run <= $1 ORDER BY next_run, id",
|
||||
[nowUtc], Map, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Moves an enabled schedule's next run from <paramref name="expectedNextRun"/> (null: none yet) to
|
||||
/// <paramref name="nextRun"/>, only if it still is <paramref name="expectedNextRun"/>: true for the one caller that won.
|
||||
/// Claiming a due run this way is what keeps two processes from both firing it.
|
||||
/// </summary>
|
||||
public async Task<bool> TryAdvanceAsync(Guid id, DateTimeOffset? expectedNextRun, DateTimeOffset? nextRun, CancellationToken cancellationToken = default) =>
|
||||
await (expectedNextRun is { } expected
|
||||
? _db.ExecuteAsync("UPDATE schedules SET next_run = $2 WHERE id = $1 AND enabled = TRUE AND next_run = $3", [id, nextRun, expected], cancellationToken)
|
||||
: _db.ExecuteAsync("UPDATE schedules SET next_run = $2 WHERE id = $1 AND enabled = TRUE AND next_run IS NULL", [id, nextRun], cancellationToken))
|
||||
.ConfigureAwait(false) > 0;
|
||||
|
||||
/// <summary>
|
||||
/// Records a run: when (<paramref name="atUtc"/>), what it did (<see cref="ScheduleOutcome"/>) and the first job it
|
||||
/// queued; a run that queued nothing keeps the previous job, so the next run still sees whether it is pending.
|
||||
/// </summary>
|
||||
public async Task<bool> RecordOutcomeAsync(Guid id, Guid? jobId, string outcome, DateTimeOffset atUtc, CancellationToken cancellationToken = default) =>
|
||||
await _db.ExecuteAsync("UPDATE schedules SET last_run = $2, last_job_id = COALESCE($3, last_job_id), last_outcome = $4 WHERE id = $1",
|
||||
[id, atUtc, jobId, outcome], cancellationToken).ConfigureAwait(false) > 0;
|
||||
|
||||
private static Schedule FromSystem(SystemSchedule system, DateTimeOffset now) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
SystemKey = system.SystemKey,
|
||||
Name = system.Name,
|
||||
Action = system.Action,
|
||||
ParametersJson = ScheduleMapping.ParametersJson(system.Action, system.Parameters),
|
||||
Recurrence = system.Recurrence.Format(),
|
||||
CatchUp = system.CatchUp,
|
||||
Priority = system.Priority,
|
||||
Enabled = system.Enabled,
|
||||
Created = now,
|
||||
Updated = now,
|
||||
};
|
||||
|
||||
private static DbParam[] Values(Schedule s) =>
|
||||
[
|
||||
s.Id, s.SystemKey, s.Name, s.Action, s.Target, DbParam.Json(s.ParametersJson), s.Recurrence, s.CatchUp, (int)s.Priority, s.Enabled, s.NextRun,
|
||||
s.LastRun, s.LastJobId, s.LastOutcome, s.CreatedBy, s.Created, s.Updated,
|
||||
];
|
||||
|
||||
private static Schedule Map(DbRow r) => new()
|
||||
{
|
||||
Id = r.GetGuid(0),
|
||||
SystemKey = r.GetStringOrNull(1),
|
||||
Name = r.GetString(2),
|
||||
Action = r.GetString(3),
|
||||
Target = r.GetString(4),
|
||||
ParametersJson = r.GetStringOrNull(5),
|
||||
Recurrence = r.GetString(6),
|
||||
CatchUp = r.GetBool(7),
|
||||
Priority = (JobPriority)r.GetInt32(8),
|
||||
Enabled = r.GetBool(9),
|
||||
NextRun = r.GetDateTimeOffsetOrNull(10),
|
||||
LastRun = r.GetDateTimeOffsetOrNull(11),
|
||||
LastJobId = r.GetGuidOrNull(12),
|
||||
LastOutcome = r.GetStringOrNull(13),
|
||||
CreatedBy = r.GetGuidOrNull(14),
|
||||
Created = r.GetDateTimeOffset(15),
|
||||
Updated = r.GetDateTimeOffset(16),
|
||||
};
|
||||
}
|
||||
@@ -389,6 +389,21 @@ public sealed class SequenceRepository
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sequences of <paramref name="archiveId"/> a rolling verification checks next (owner review 2, R10): those never
|
||||
/// verified first, then the longest unverified, at most <paramref name="limit"/>. With <paramref name="verifiedBefore"/>
|
||||
/// only those never verified or last verified before it are listed. Sequences without frames are left out.
|
||||
/// </summary>
|
||||
public Task<IReadOnlyList<Guid>> ListVerifyCandidatesAsync(Guid archiveId, DateTimeOffset? verifiedBefore, int limit,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var p = new SqlParameters();
|
||||
var where = $"archive_id = {p.Add(archiveId)} AND frame_count > 0";
|
||||
if (verifiedBefore is { } before) where += $" AND (verified_at IS NULL OR verified_at < {p.Add(before)})";
|
||||
return _db.ListAsync($"SELECT id FROM sequences WHERE {where} ORDER BY verified_at ASC NULLS FIRST, id LIMIT {p.Add(Math.Max(1, limit))}",
|
||||
p.ToArray(), r => r.GetGuid(0), cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Folder and title of every sequence of an archive, by folder.</summary>
|
||||
public Task<IReadOnlyList<SequenceLocation>> ListLocationsAsync(Guid archiveId, CancellationToken cancellationToken = default) =>
|
||||
_db.ListAsync("SELECT id, folder, title FROM sequences WHERE archive_id = $1 ORDER BY folder, id", [archiveId],
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.Data.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// What a host (the server, the desktop) tells its <see cref="Scheduler"/> (owner review 2, R10): its time zone, the archive
|
||||
/// schedules work on, the system schedules standing for its timers, the clean-up steps its jobs run, and the actions it
|
||||
/// cannot run. Called from the scheduler's loop, off any UI thread; members must be thread-safe.
|
||||
/// </summary>
|
||||
public interface IScheduleHost
|
||||
{
|
||||
/// <summary>The zone of daily, weekly and monthly times: the PC's on the desktop, the container's (TZ) on the server.</summary>
|
||||
TimeZoneInfo TimeZone { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The archive schedules targeting <c>current</c> work on (the server's archive, the desktop's current one), with its
|
||||
/// settings as fresh as the host keeps them; null when there is none yet or it cannot be reached. The scheduler probes
|
||||
/// whether it is online itself.
|
||||
/// </summary>
|
||||
ValueTask<Archive?> GetArchiveAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// The system schedules: every timer that queues work on this host, as a visible schedule. Seeded at start by key and
|
||||
/// never overwritten (the user's edits stay); <see cref="Scheduler.ResetAsync"/> puts one back to these values.
|
||||
/// </summary>
|
||||
IReadOnlyList<SystemSchedule> SystemSchedules { get; }
|
||||
|
||||
/// <summary>The names of the clean-up steps this host's <see cref="JobKind.Cleanup"/> jobs run (normally those of <c>ArchiveService.CleanupSteps</c>).</summary>
|
||||
IReadOnlyList<string> CleanupSteps { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether a scan whose schedule leaves its <c>deep</c> parameter unset gives the sequences it finds a deep analysis.
|
||||
/// Read at every run, so the desktop's scans follow Settings › Analysis › After a scan as it is then; false on the server.
|
||||
/// </summary>
|
||||
bool DeepAnalysisAfterScan { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Why this host does not run <paramref name="action"/> (a short code, e.g. <c>not-here</c>), or null when it may. Asked
|
||||
/// before the scheduler's own checks (<see cref="ScheduleUnavailable"/>), for the action list and at every run.
|
||||
/// </summary>
|
||||
string? Unavailable(string action);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A host's system schedule: <paramref name="SystemKey"/> identifies it across starts (<c>archive-scan</c>,
|
||||
/// <c>index-backup</c>, <c>housekeeping</c>…); the rest is what it is seeded with and reset to. <paramref name="Name"/> is
|
||||
/// stored as given; clients show system schedules by their key in the user's language. <paramref name="LastDone"/> is when
|
||||
/// the host last did this work before the schedule existed (the newest index copy), read only when the row is seeded: an
|
||||
/// enabled row seeded at least a whole period of its recurrence after it is due at once; otherwise, and without it, its
|
||||
/// first run is the recurrence's first occurrence.
|
||||
/// </summary>
|
||||
public sealed record SystemSchedule(
|
||||
string SystemKey,
|
||||
string Name,
|
||||
string Action,
|
||||
ScheduleRecurrence Recurrence,
|
||||
ScheduleParametersDto? Parameters = null,
|
||||
bool Enabled = true,
|
||||
bool CatchUp = true,
|
||||
JobPriority Priority = JobPriority.Background,
|
||||
DateTimeOffset? LastDone = null);
|
||||
@@ -0,0 +1,295 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Housekeeping;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.Data.Scheduling;
|
||||
|
||||
/// <summary>Whether a host runs an action, and why not (<see cref="ScheduleUnavailable"/> or the host's own code).</summary>
|
||||
public sealed record ScheduleActionInfo(string Name, bool Available, string? Reason);
|
||||
|
||||
/// <summary>
|
||||
/// What a schedule's run comes to: the jobs to queue (<see cref="ScheduleOutcome.Queued"/>), or none and why
|
||||
/// (<see cref="ScheduleOutcome.SkippedPending"/>, <see cref="ScheduleOutcome.SkippedOffline"/>,
|
||||
/// <see cref="ScheduleOutcome.SkippedNothing"/>, <see cref="ScheduleOutcome.Unavailable"/>).
|
||||
/// </summary>
|
||||
public sealed record ScheduleResolution(IReadOnlyList<ArchiveJobRequest> Requests, string Outcome)
|
||||
{
|
||||
public static ScheduleResolution Skip(string outcome) => new([], outcome);
|
||||
|
||||
public static ScheduleResolution Queue(IReadOnlyList<ArchiveJobRequest> requests) => new(requests, ScheduleOutcome.Queued);
|
||||
}
|
||||
|
||||
/// <summary>What resolving an action needs: the index, the host, which job kinds the host's engine runs, and the time of the run.</summary>
|
||||
public sealed record ScheduleActionContext(ChronosDatabase Database, IScheduleHost Host, Func<JobKind, bool> CanRun, DateTimeOffset Now);
|
||||
|
||||
/// <summary>
|
||||
/// The actions a schedule can take (owner review 2, R10), shared by the server and the desktop: their names, parameters
|
||||
/// (<see cref="ScheduleParametersDto"/>, normalised to the fields each reads), availability, and the archive jobs a run
|
||||
/// queues for the host's current archive. Rebuild and render are not schedulable. Every action that works on an archive
|
||||
/// skips a run while the archive is missing or offline (or read-only, for one that writes), and while a job doing the same
|
||||
/// work on it is pending; a run that finds nothing to do queues nothing.
|
||||
/// </summary>
|
||||
public static class ScheduleActions
|
||||
{
|
||||
/// <summary>
|
||||
/// Incremental scan of the archive (<c>force</c>: a full one; <c>deep</c>: deep analysis of what it indexes; unset, as the
|
||||
/// host says at the run, <see cref="IScheduleHost.DeepAnalysisAfterScan"/>).
|
||||
/// </summary>
|
||||
public const string Scan = "scan";
|
||||
|
||||
/// <summary>Integrity check of the originals, the least recently verified first (<c>olderThanDays</c>, <c>percent</c>).</summary>
|
||||
public const string Verify = "verify";
|
||||
|
||||
/// <summary>Thumbnails of the sequences without them (<c>force</c>: of every sequence).</summary>
|
||||
public const string Thumbnails = "thumbnails";
|
||||
|
||||
/// <summary>Proxies of the sequences without them, when the archive makes proxies (<c>force</c>: of every sequence).</summary>
|
||||
public const string Proxies = "proxies";
|
||||
|
||||
/// <summary>Light analysis of the sequences without a current one (<c>deep</c>: deep analysis of those without one).</summary>
|
||||
public const string Analysis = "analysis";
|
||||
|
||||
/// <summary>The archive's maintenance job (<c>dryRun</c>: report only).</summary>
|
||||
public const string Maintenance = "maintenance";
|
||||
|
||||
/// <summary>A copy of the SQLite index (<c>keep</c>: copies kept). Not on PostgreSQL.</summary>
|
||||
public const string Backup = "backup";
|
||||
|
||||
/// <summary>Clean-up steps (<c>steps</c>, <c>olderThanDays</c>): job history, audit log, trash report, the host's own.</summary>
|
||||
public const string Cleanup = "cleanup";
|
||||
|
||||
/// <summary>Report of the duplicate photos into the job log.</summary>
|
||||
public const string Duplicates = "duplicates";
|
||||
|
||||
/// <summary>Report of where the index and the disk disagree into the job log.</summary>
|
||||
public const string Orphans = "orphans";
|
||||
|
||||
/// <summary>Most days a schedule's age limits accept (ten years).</summary>
|
||||
public const int MaxDays = 3650;
|
||||
|
||||
/// <summary>Sequences per job a run queues: a larger set becomes several jobs.</summary>
|
||||
public const int SequencesPerJob = 500;
|
||||
|
||||
/// <summary>Every action, in the order clients list them.</summary>
|
||||
public static IReadOnlyList<string> All { get; } = [Scan, Verify, Thumbnails, Proxies, Analysis, Maintenance, Backup, Cleanup, Duplicates, Orphans];
|
||||
|
||||
public static bool IsKnown(string? action) => action is not null && All.Contains(action, StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The job kinds <paramref name="action"/> queues (analysis: light, or deep with <c>deep</c>); empty for an unknown one.</summary>
|
||||
public static IReadOnlyList<JobKind> KindsOf(string action) => action switch
|
||||
{
|
||||
Scan => [JobKind.Scan],
|
||||
Verify => [JobKind.Verify],
|
||||
Thumbnails => [JobKind.Thumbs],
|
||||
Proxies => [JobKind.Proxies],
|
||||
Analysis => [JobKind.LightAnalyse, JobKind.DeepAnalyse],
|
||||
Maintenance => [JobKind.Maintenance],
|
||||
Backup => [JobKind.Backup],
|
||||
Cleanup => [JobKind.Cleanup],
|
||||
Duplicates => [JobKind.Duplicates],
|
||||
Orphans => [JobKind.Orphans],
|
||||
_ => [],
|
||||
};
|
||||
|
||||
/// <summary>The parameters a new schedule of <paramref name="action"/> starts with.</summary>
|
||||
public static ScheduleParametersDto Defaults(string action) => action switch
|
||||
{
|
||||
// No deep: a scan follows the host's choice at run time (IScheduleHost.DeepAnalysisAfterScan) unless its schedule sets one.
|
||||
Scan => new(Force: false),
|
||||
Verify => new(OlderThanDays: 30, Percent: 100),
|
||||
Thumbnails or Proxies => new(Force: false),
|
||||
Analysis => new(Deep: false),
|
||||
Maintenance => new(DryRun: false),
|
||||
Backup => new(Keep: DatabaseBackups.Keep),
|
||||
Cleanup => new(Steps: [CleanupSteps.JobHistory], OlderThanDays: CleanupSteps.DefaultHistoryDays),
|
||||
_ => new(),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="parameters"/> reduced to the fields <paramref name="action"/> reads, each missing one taken from
|
||||
/// <see cref="Defaults"/>; clean-up steps keep their order without repeats.
|
||||
/// </summary>
|
||||
public static ScheduleParametersDto Normalize(string action, ScheduleParametersDto? parameters)
|
||||
{
|
||||
var p = parameters ?? new ScheduleParametersDto();
|
||||
var d = Defaults(action);
|
||||
return action switch
|
||||
{
|
||||
Scan => new(Force: p.Force ?? d.Force, Deep: p.Deep),
|
||||
Verify => new(OlderThanDays: p.OlderThanDays ?? d.OlderThanDays, Percent: p.Percent ?? d.Percent),
|
||||
Thumbnails or Proxies => new(Force: p.Force ?? d.Force),
|
||||
Analysis => new(Deep: p.Deep ?? d.Deep),
|
||||
Maintenance => new(DryRun: p.DryRun ?? d.DryRun),
|
||||
Backup => new(Keep: p.Keep ?? d.Keep),
|
||||
Cleanup => new(Steps: p.Steps is { } steps ? [.. steps.Distinct(StringComparer.Ordinal)] : d.Steps, OlderThanDays: p.OlderThanDays ?? d.OlderThanDays),
|
||||
_ => new(),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The first invalid field of a schedule's action and parameters, by its API name (<c>action</c>,
|
||||
/// <c>parameters.percent</c>, <c>parameters.steps</c>…); null when they are valid. <paramref name="steps"/> are the
|
||||
/// clean-up steps the host runs.
|
||||
/// </summary>
|
||||
public static string? Problem(string action, ScheduleParametersDto? parameters, IReadOnlyCollection<string> steps)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(steps);
|
||||
if (!IsKnown(action)) return "action";
|
||||
var p = Normalize(action, parameters);
|
||||
if (p.OlderThanDays is < 0 or > MaxDays) return "parameters.olderThanDays";
|
||||
if (p.Percent is < 1 or > 100) return "parameters.percent";
|
||||
if (p.Keep is < 1 or > BackupJobHandler.MaxKeep) return "parameters.keep";
|
||||
if (action == Cleanup && (p.Steps is not { Count: > 0 } named || named.Any(s => !steps.Contains(s)))) return "parameters.steps";
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every action with whether this host runs it: not when the host says so (<see cref="IScheduleHost.Unavailable"/>), its
|
||||
/// engine has no handler for the kind (<see cref="ScheduleUnavailable.NoHandler"/>), the index cannot be copied (backup:
|
||||
/// <see cref="ScheduleUnavailable.Postgres"/>, <see cref="ScheduleUnavailable.NoIndexFile"/>), or the current archive makes
|
||||
/// no proxies (<see cref="ScheduleUnavailable.ProxiesDisabled"/>). A missing or offline archive leaves actions available:
|
||||
/// their runs are skipped until it is back.
|
||||
/// </summary>
|
||||
public static async Task<IReadOnlyList<ScheduleActionInfo>> AvailabilityAsync(ScheduleActionContext context, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var archive = await context.Host.GetArchiveAsync(cancellationToken).ConfigureAwait(false);
|
||||
return [.. All.Select(a => Unavailable(context, a, null, archive) is { } reason ? new ScheduleActionInfo(a, false, reason) : new ScheduleActionInfo(a, true, null))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What a run of <paramref name="action"/> with <paramref name="parameters"/> queues now for the host's current archive,
|
||||
/// or why it queues nothing (see the type's remarks). Read-only: nothing is queued here.
|
||||
/// </summary>
|
||||
public static async Task<ScheduleResolution> ResolveAsync(ScheduleActionContext context, string action, ScheduleParametersDto? parameters,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
if (!IsKnown(action)) return ScheduleResolution.Skip(ScheduleOutcome.Unavailable);
|
||||
var p = Normalize(action, parameters);
|
||||
var db = context.Database;
|
||||
var archive = await context.Host.GetArchiveAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (Unavailable(context, action, p, archive) is not null) return ScheduleResolution.Skip(ScheduleOutcome.Unavailable);
|
||||
switch (action)
|
||||
{
|
||||
case Backup:
|
||||
return ScheduleResolution.Queue([ArchiveJobs.Backup(p.Keep!.Value)]);
|
||||
case Cleanup:
|
||||
return ScheduleResolution.Queue([ArchiveJobs.Cleanup(archive, p.Steps!, p.OlderThanDays!.Value)]);
|
||||
}
|
||||
|
||||
if (archive is null) return ScheduleResolution.Skip(ScheduleOutcome.SkippedOffline);
|
||||
var availability = ArchiveService.GetAvailability(archive);
|
||||
var writes = action is not (Verify or Duplicates or Orphans) && !(action == Maintenance && p.DryRun == true);
|
||||
if (availability == ArchiveAvailability.Offline || (writes && availability != ArchiveAvailability.Online))
|
||||
return ScheduleResolution.Skip(ScheduleOutcome.SkippedOffline);
|
||||
|
||||
switch (action)
|
||||
{
|
||||
case Scan:
|
||||
return await PendingAsync(db, [JobKind.Scan, JobKind.Rebuild], archive, cancellationToken).ConfigureAwait(false)
|
||||
?? ScheduleResolution.Queue([ArchiveJobs.Scan(archive, full: p.Force == true, deepAnalysis: p.Deep ?? context.Host.DeepAnalysisAfterScan)]);
|
||||
case Verify:
|
||||
return await PendingAsync(db, [JobKind.Verify], archive, cancellationToken).ConfigureAwait(false)
|
||||
?? await VerifyAsync(context, archive, p, cancellationToken).ConfigureAwait(false);
|
||||
case Thumbnails:
|
||||
case Proxies:
|
||||
{
|
||||
var kind = action == Thumbnails ? JobKind.Thumbs : JobKind.Proxies;
|
||||
var built = action == Thumbnails ? SequenceStatus.ThumbsBuilt : SequenceStatus.ProxiesBuilt;
|
||||
var ids = await SequencesAsync(db, archive.Id, p.Force == true ? SequenceStatus.None : built, cancellationToken).ConfigureAwait(false);
|
||||
return await ChunkedAsync(db, kind, ids, chunk => action == Thumbnails
|
||||
? ArchiveJobs.Thumbnails(chunk, archive.Name, p.Force == true)
|
||||
: ArchiveJobs.Proxies(chunk, archive.Name, p.Force == true), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
case Analysis:
|
||||
{
|
||||
var deep = p.Deep == true;
|
||||
var ids = deep
|
||||
? await SequencesAsync(db, archive.Id, SequenceStatus.AnalyzedDeep, cancellationToken).ConfigureAwait(false)
|
||||
: await AnalysisFollowUp.UnanalysedAsync(db, archive.Id, cancellationToken).ConfigureAwait(false);
|
||||
return await ChunkedAsync(db, deep ? JobKind.DeepAnalyse : JobKind.LightAnalyse, ids, chunk => deep
|
||||
? ProcessingJobs.DeepAnalysis(chunk, archive.Name)
|
||||
: ProcessingJobs.LightAnalysis(chunk, archive.Name), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
case Maintenance:
|
||||
return await PendingAsync(db, [JobKind.Maintenance], archive, cancellationToken).ConfigureAwait(false)
|
||||
?? ScheduleResolution.Queue([ArchiveJobs.Maintenance(archive, p.DryRun == true)]);
|
||||
case Duplicates:
|
||||
return await PendingAsync(db, [JobKind.Duplicates], archive, cancellationToken).ConfigureAwait(false)
|
||||
?? ScheduleResolution.Queue([ArchiveJobs.Duplicates(archive)]);
|
||||
default:
|
||||
return await PendingAsync(db, [JobKind.Orphans], archive, cancellationToken).ConfigureAwait(false)
|
||||
?? ScheduleResolution.Queue([ArchiveJobs.Orphans(archive)]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Why <paramref name="action"/> cannot run here; null when it can. With <paramref name="parameters"/>, the kind it would queue must run.</summary>
|
||||
private static string? Unavailable(ScheduleActionContext context, string action, ScheduleParametersDto? parameters, Archive? archive)
|
||||
{
|
||||
if (context.Host.Unavailable(action) is { } reason) return reason;
|
||||
var kinds = KindsOf(action);
|
||||
var kind = action == Analysis && parameters?.Deep == true ? JobKind.DeepAnalyse : kinds[0];
|
||||
if (!context.CanRun(kind)) return ScheduleUnavailable.NoHandler;
|
||||
if (action == Backup && DatabaseBackups.Unavailable(context.Database) is { } backup) return backup;
|
||||
if (action == Proxies && archive is { ProxyLongEdge: ProxyPolicy.Disabled }) return ScheduleUnavailable.ProxiesDisabled;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary><see cref="ScheduleOutcome.SkippedPending"/> while a job of <paramref name="kinds"/> on the archive is queued, running or paused.</summary>
|
||||
private static async Task<ScheduleResolution?> PendingAsync(ChronosDatabase db, IReadOnlyCollection<JobKind> kinds, Archive archive,
|
||||
CancellationToken cancellationToken) =>
|
||||
await db.Jobs.HasPendingAsync(kinds, [archive.Id], cancellationToken).ConfigureAwait(false) ? ScheduleResolution.Skip(ScheduleOutcome.SkippedPending) : null;
|
||||
|
||||
/// <summary>
|
||||
/// The least recently verified sequences: those not verified for <c>olderThanDays</c> (0: any), at most
|
||||
/// <c>percent</c> of the archive's sequences (rounded up). All of them at 100 % and 0 days, as one archive-wide job.
|
||||
/// </summary>
|
||||
private static async Task<ScheduleResolution> VerifyAsync(ScheduleActionContext context, Archive archive, ScheduleParametersDto p, CancellationToken cancellationToken)
|
||||
{
|
||||
var db = context.Database;
|
||||
var total = await db.Sequences.CountAsync(new SequenceQuery { ArchiveId = archive.Id }, cancellationToken).ConfigureAwait(false);
|
||||
if (total == 0) return ScheduleResolution.Skip(ScheduleOutcome.SkippedNothing);
|
||||
var days = p.OlderThanDays ?? 0;
|
||||
var percent = p.Percent ?? 100;
|
||||
if (days == 0 && percent >= 100) return ScheduleResolution.Queue([ArchiveJobs.Verify(archive)]);
|
||||
var limit = (int)Math.Ceiling(total * percent / 100.0);
|
||||
var ids = await db.Sequences.ListVerifyCandidatesAsync(archive.Id, days > 0 ? context.Now - TimeSpan.FromDays(days) : null, limit, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return ids.Count == 0 ? ScheduleResolution.Skip(ScheduleOutcome.SkippedNothing) : ScheduleResolution.Queue([ArchiveJobs.Verify(archive, ids)]);
|
||||
}
|
||||
|
||||
/// <summary>The sequences of an archive with frames and without <paramref name="without"/> (none: every one), oldest capture first.</summary>
|
||||
private static async Task<List<Guid>> SequencesAsync(ChronosDatabase db, Guid archiveId, SequenceStatus without, CancellationToken cancellationToken)
|
||||
{
|
||||
var ids = new List<Guid>();
|
||||
var query = new SequenceQuery { ArchiveId = archiveId, WithoutStatus = without, Sort = SequenceSort.Oldest, Limit = 1000 };
|
||||
do
|
||||
{
|
||||
var page = await db.Sequences.ListAsync(query, cancellationToken).ConfigureAwait(false);
|
||||
ids.AddRange(page.Items.Where(s => s.FrameCount > 0).Select(s => s.Id));
|
||||
query = query with { Cursor = page.NextCursor };
|
||||
}
|
||||
while (query.Cursor is not null);
|
||||
return ids;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The jobs for <paramref name="ids"/> less those a pending job of <paramref name="kind"/> already covers, at most
|
||||
/// <see cref="SequencesPerJob"/> per job; <see cref="ScheduleOutcome.SkippedNothing"/> when none is left.
|
||||
/// </summary>
|
||||
private static async Task<ScheduleResolution> ChunkedAsync(ChronosDatabase db, JobKind kind, IReadOnlyList<Guid> ids,
|
||||
Func<IReadOnlyList<Guid>, ArchiveJobRequest> request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (ids.Count == 0) return ScheduleResolution.Skip(ScheduleOutcome.SkippedNothing);
|
||||
var pending = await db.Jobs.ListPendingTargetsAsync(kind, cancellationToken).ConfigureAwait(false);
|
||||
var left = ids.Where(id => !pending.Contains(id)).Distinct().ToList();
|
||||
if (left.Count == 0) return ScheduleResolution.Skip(pending.Count > 0 ? ScheduleOutcome.SkippedPending : ScheduleOutcome.SkippedNothing);
|
||||
return ScheduleResolution.Queue([.. left.Chunk(SequencesPerJob).Select(chunk => request(chunk))]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.Data.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Schedules between the model and API v1 (<see cref="ScheduleDto"/>, <see cref="RecurrenceDto"/>), and the stored form of
|
||||
/// their parameters (<see cref="ScheduleParametersDto"/> as camelCase JSON, normalised to the fields the action reads).
|
||||
/// </summary>
|
||||
public static class ScheduleMapping
|
||||
{
|
||||
/// <summary>Wire names of <see cref="RecurrenceKind"/>: <c>every</c>, <c>daily</c>, <c>weekly</c>, <c>monthly</c>.</summary>
|
||||
public static string Kind(RecurrenceKind kind) => kind.ToString().ToLowerInvariant();
|
||||
|
||||
/// <summary>Wire names of <see cref="RecurrenceUnit"/>: <c>minutes</c>, <c>hours</c>, <c>days</c>.</summary>
|
||||
public static string Unit(RecurrenceUnit unit) => unit.ToString().ToLowerInvariant();
|
||||
|
||||
public static ScheduleDto ToDto(Schedule schedule)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schedule);
|
||||
var recurrence = ScheduleRecurrence.TryParse(schedule.Recurrence, out var parsed) ? ToDto(parsed) : new RecurrenceDto(schedule.Recurrence);
|
||||
return new ScheduleDto(schedule.Id, schedule.SystemKey, schedule.Name, schedule.Action, schedule.Target, Parameters(schedule), recurrence,
|
||||
schedule.CatchUp, JobWire.Priority(schedule.Priority), schedule.Enabled, schedule.NextRun, schedule.LastRun, schedule.LastJobId,
|
||||
schedule.LastOutcome, schedule.CreatedBy, schedule.Created, schedule.Updated);
|
||||
}
|
||||
|
||||
public static RecurrenceDto ToDto(ScheduleRecurrence recurrence)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(recurrence);
|
||||
var time = recurrence.Time.ToString("HH:mm", CultureInfo.InvariantCulture);
|
||||
return recurrence.Kind switch
|
||||
{
|
||||
RecurrenceKind.Every => new RecurrenceDto(Kind(recurrence.Kind), Every: recurrence.Every, Unit: Unit(recurrence.Unit)),
|
||||
RecurrenceKind.Daily => new RecurrenceDto(Kind(recurrence.Kind), Time: time),
|
||||
RecurrenceKind.Weekly => new RecurrenceDto(Kind(recurrence.Kind), Time: time, Days: [.. recurrence.Days.Select(ScheduleRecurrence.DayName)]),
|
||||
_ => new RecurrenceDto(Kind(recurrence.Kind), Time: time, DayOfMonth: recurrence.DayOfMonth),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The recurrence <paramref name="dto"/> describes; null when it is missing or invalid (out of range, unknown names).</summary>
|
||||
public static ScheduleRecurrence? FromDto(RecurrenceDto? dto)
|
||||
{
|
||||
if (dto is null) return null;
|
||||
var text = dto.Kind?.ToLowerInvariant() switch
|
||||
{
|
||||
"every" when dto.Every is { } every && Enum.TryParse<RecurrenceUnit>(dto.Unit, ignoreCase: true, out var unit) && Enum.IsDefined(unit)
|
||||
=> string.Create(CultureInfo.InvariantCulture, $"every:{every}{Unit(unit)[0]}"),
|
||||
"daily" => "daily:" + dto.Time,
|
||||
"weekly" when dto.Days is { Count: > 0 } days => $"weekly:{string.Join(',', days)}@{dto.Time}",
|
||||
"monthly" when dto.DayOfMonth is { } day => string.Create(CultureInfo.InvariantCulture, $"monthly:{day}@{dto.Time}"),
|
||||
_ => null,
|
||||
};
|
||||
return ScheduleRecurrence.TryParse(text, out var recurrence) ? recurrence : null;
|
||||
}
|
||||
|
||||
public static ScheduleActionDto ToDto(ScheduleActionInfo info)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(info);
|
||||
return new ScheduleActionDto(info.Name, info.Available, info.Reason);
|
||||
}
|
||||
|
||||
/// <summary>The schedule's parameters, normalised for its action (stored JSON that cannot be read counts as none).</summary>
|
||||
public static ScheduleParametersDto Parameters(Schedule schedule)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schedule);
|
||||
ScheduleParametersDto? stored = null;
|
||||
if (schedule.ParametersJson is { Length: > 0 } json)
|
||||
{
|
||||
try
|
||||
{
|
||||
stored = JsonSerializer.Deserialize(json, ProtocolJson.Default.ScheduleParametersDto);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
}
|
||||
}
|
||||
return ScheduleActions.Normalize(schedule.Action, stored);
|
||||
}
|
||||
|
||||
/// <summary>The stored form of <paramref name="parameters"/> for <paramref name="action"/>; null for an action without parameters.</summary>
|
||||
public static string? ParametersJson(string action, ScheduleParametersDto? parameters)
|
||||
{
|
||||
var normalized = ScheduleActions.Normalize(action, parameters);
|
||||
return normalized == new ScheduleParametersDto() ? null : JsonSerializer.Serialize(normalized, ProtocolJson.Default.ScheduleParametersDto);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
namespace Chronos.Data.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// What a schedule's run did (<see cref="Core.Model.Schedule.LastOutcome"/>), as stored and sent over the API. Clients
|
||||
/// show them in their own words; <see cref="Failed(string)"/> carries the reason as text.
|
||||
/// </summary>
|
||||
public static class ScheduleOutcome
|
||||
{
|
||||
/// <summary>The action's jobs were queued (the schedule keeps the first one's id).</summary>
|
||||
public const string Queued = "queued";
|
||||
|
||||
/// <summary>Not queued: the schedule's previous job, or a job doing the same work, is still queued, running or paused.</summary>
|
||||
public const string SkippedPending = "skipped-pending";
|
||||
|
||||
/// <summary>Not queued: the archive the action works on is missing, offline, or read-only for an action that writes.</summary>
|
||||
public const string SkippedOffline = "skipped-offline";
|
||||
|
||||
/// <summary>Not queued: nothing to do (every sequence verified recently, every thumbnail built…).</summary>
|
||||
public const string SkippedNothing = "skipped-nothing";
|
||||
|
||||
/// <summary>Not queued: this host cannot run the action (<see cref="ScheduleUnavailable"/> says why).</summary>
|
||||
public const string Unavailable = "unavailable";
|
||||
|
||||
/// <summary>Prefix of <see cref="Failed(string)"/>.</summary>
|
||||
public const string FailedPrefix = "failed:";
|
||||
|
||||
/// <summary>Longest reason kept after <see cref="FailedPrefix"/>.</summary>
|
||||
public const int MaxReasonLength = 200;
|
||||
|
||||
/// <summary><c>failed:<reason></c>: resolving or queueing the action threw; the reason is the error's message, shortened.</summary>
|
||||
public static string Failed(string reason)
|
||||
{
|
||||
var text = string.IsNullOrWhiteSpace(reason) ? "error" : reason.ReplaceLineEndings(" ").Trim();
|
||||
return FailedPrefix + (text.Length > MaxReasonLength ? text[..MaxReasonLength] : text);
|
||||
}
|
||||
|
||||
/// <summary>True for a <c>failed:</c> outcome, with its reason.</summary>
|
||||
public static bool IsFailed(string? outcome, out string reason)
|
||||
{
|
||||
var failed = outcome?.StartsWith(FailedPrefix, StringComparison.Ordinal) == true;
|
||||
reason = failed ? outcome![FailedPrefix.Length..] : string.Empty;
|
||||
return failed;
|
||||
}
|
||||
|
||||
/// <summary>The outcomes without a reason, for clients that name each one.</summary>
|
||||
public static IReadOnlyList<string> Plain { get; } = [Queued, SkippedPending, SkippedOffline, SkippedNothing, Unavailable];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why an action cannot run on a host (<see cref="ScheduleActionInfo.Reason"/>, <c>ScheduleActionDto.reason</c>). A host's
|
||||
/// own hook (<see cref="IScheduleHost.Unavailable"/>) may answer with codes of its own; clients show unknown codes as
|
||||
/// "not available here".
|
||||
/// </summary>
|
||||
public static class ScheduleUnavailable
|
||||
{
|
||||
/// <summary>This host's job engine has no handler for the action's job kind.</summary>
|
||||
public const string NoHandler = "no-handler";
|
||||
|
||||
/// <summary>Index backups: the index is on PostgreSQL, which its own tools back up.</summary>
|
||||
public const string Postgres = "postgres";
|
||||
|
||||
/// <summary>Index backups: the SQLite index has no file (in memory).</summary>
|
||||
public const string NoIndexFile = "no-index-file";
|
||||
|
||||
/// <summary>Proxies: the archive's proxy policy makes none.</summary>
|
||||
public const string ProxiesDisabled = "proxies-disabled";
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Chronos.Data.Scheduling;
|
||||
|
||||
/// <summary>The shape of a <see cref="ScheduleRecurrence"/>.</summary>
|
||||
public enum RecurrenceKind
|
||||
{
|
||||
/// <summary>A fixed interval: every n minutes, hours or days.</summary>
|
||||
Every,
|
||||
|
||||
/// <summary>Every day at a wall-clock time.</summary>
|
||||
Daily,
|
||||
|
||||
/// <summary>On some days of the week at a wall-clock time.</summary>
|
||||
Weekly,
|
||||
|
||||
/// <summary>On one day of the month (1–28) at a wall-clock time.</summary>
|
||||
Monthly,
|
||||
}
|
||||
|
||||
/// <summary>Unit of an <see cref="RecurrenceKind.Every"/> interval.</summary>
|
||||
public enum RecurrenceUnit
|
||||
{
|
||||
Minutes,
|
||||
Hours,
|
||||
Days,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When a schedule fires (owner review 2, R10), in an in-house text form instead of cron: <c>every:<n>m|h|d</c>
|
||||
/// (at least 5 minutes), <c>daily:HH:MM</c>, <c>weekly:mon,tue,…@HH:MM</c> and <c>monthly:<1–28>@HH:MM</c>.
|
||||
/// Intervals are fixed durations anchored to the previous due time, so they never drift and the occurrences missed meanwhile
|
||||
/// collapse into one; days of an interval are 24 hours, whatever the clocks do. Daily, weekly and monthly times are wall-clock
|
||||
/// times of the host's zone: a time a spring-forward gap skips moves forward by the gap (02:30 becomes 03:30), and a time the
|
||||
/// clocks go back over happens once, at its first occurrence. Instances compare by value.
|
||||
/// </summary>
|
||||
public sealed record ScheduleRecurrence
|
||||
{
|
||||
/// <summary>The shortest interval: a schedule never fires more than every 5 minutes.</summary>
|
||||
public const int MinMinutes = 5;
|
||||
|
||||
public const int MaxMinutes = 24 * 60;
|
||||
public const int MaxHours = 7 * 24;
|
||||
public const int MaxDays = 366;
|
||||
|
||||
/// <summary>The last day a monthly schedule can name: every month has it.</summary>
|
||||
public const int MaxDayOfMonth = 28;
|
||||
|
||||
/// <summary>Wire names of the days, Monday first, as the text form and the API write them.</summary>
|
||||
public static IReadOnlyList<string> DayNames { get; } = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
|
||||
|
||||
private static readonly DayOfWeek[] WeekOrder =
|
||||
[DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday, DayOfWeek.Saturday, DayOfWeek.Sunday];
|
||||
|
||||
/// <summary>Bit <c>1 << (int)DayOfWeek</c> per weekly day; a field, so equality compares the days.</summary>
|
||||
private readonly int _days;
|
||||
|
||||
private ScheduleRecurrence(RecurrenceKind kind, int every, RecurrenceUnit unit, TimeOnly time, int days, int dayOfMonth)
|
||||
{
|
||||
Kind = kind;
|
||||
Every = every;
|
||||
Unit = unit;
|
||||
Time = time;
|
||||
_days = days;
|
||||
DayOfMonth = dayOfMonth;
|
||||
}
|
||||
|
||||
public RecurrenceKind Kind { get; }
|
||||
|
||||
/// <summary>The interval's count of <see cref="Unit"/>; 0 for the other kinds.</summary>
|
||||
public int Every { get; }
|
||||
|
||||
/// <summary>The interval's unit (<see cref="RecurrenceKind.Every"/> only).</summary>
|
||||
public RecurrenceUnit Unit { get; }
|
||||
|
||||
/// <summary>Wall-clock time of a daily, weekly or monthly schedule, to the minute; midnight for an interval.</summary>
|
||||
public TimeOnly Time { get; }
|
||||
|
||||
/// <summary>The days of a weekly schedule, Monday first; empty for the other kinds.</summary>
|
||||
public IReadOnlyList<DayOfWeek> Days => [.. WeekOrder.Where(d => (_days & Bit(d)) != 0)];
|
||||
|
||||
/// <summary>Day of the month of a monthly schedule (1–28); 0 for the other kinds.</summary>
|
||||
public int DayOfMonth { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The longest time between two occurrences: the interval, a day, a week, or 31 days for a monthly schedule. A next run
|
||||
/// further away than two of them means the clock went back, and the next run is computed again.
|
||||
/// </summary>
|
||||
public TimeSpan Period => Kind switch
|
||||
{
|
||||
RecurrenceKind.Every => Unit switch
|
||||
{
|
||||
RecurrenceUnit.Minutes => TimeSpan.FromMinutes(Every),
|
||||
RecurrenceUnit.Hours => TimeSpan.FromHours(Every),
|
||||
_ => TimeSpan.FromDays(Every),
|
||||
},
|
||||
RecurrenceKind.Daily => TimeSpan.FromDays(1),
|
||||
RecurrenceKind.Weekly => TimeSpan.FromDays(7),
|
||||
_ => TimeSpan.FromDays(31),
|
||||
};
|
||||
|
||||
/// <summary>Every <paramref name="every"/> <paramref name="unit"/> (at least <see cref="MinMinutes"/> minutes).</summary>
|
||||
/// <exception cref="ArgumentOutOfRangeException">The interval is shorter than 5 minutes or longer than its unit allows.</exception>
|
||||
public static ScheduleRecurrence Interval(int every, RecurrenceUnit unit)
|
||||
{
|
||||
var (min, max) = unit switch
|
||||
{
|
||||
RecurrenceUnit.Minutes => (MinMinutes, MaxMinutes),
|
||||
RecurrenceUnit.Hours => (1, MaxHours),
|
||||
RecurrenceUnit.Days => (1, MaxDays),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(unit), unit, "Unknown unit."),
|
||||
};
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(every, min);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(every, max);
|
||||
return new ScheduleRecurrence(RecurrenceKind.Every, every, unit, default, 0, 0);
|
||||
}
|
||||
|
||||
/// <summary>Every day at <paramref name="time"/> (seconds are dropped).</summary>
|
||||
public static ScheduleRecurrence DailyAt(TimeOnly time) => new(RecurrenceKind.Daily, 0, default, Minute(time), 0, 0);
|
||||
|
||||
/// <summary>On <paramref name="days"/> at <paramref name="time"/>.</summary>
|
||||
/// <exception cref="ArgumentException">No day given.</exception>
|
||||
public static ScheduleRecurrence WeeklyAt(IEnumerable<DayOfWeek> days, TimeOnly time)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(days);
|
||||
var mask = 0;
|
||||
foreach (var day in days)
|
||||
{
|
||||
if (!Enum.IsDefined(day)) throw new ArgumentOutOfRangeException(nameof(days), day, "Unknown day.");
|
||||
mask |= Bit(day);
|
||||
}
|
||||
if (mask == 0) throw new ArgumentException("A weekly schedule needs at least one day.", nameof(days));
|
||||
return new ScheduleRecurrence(RecurrenceKind.Weekly, 0, default, Minute(time), mask, 0);
|
||||
}
|
||||
|
||||
/// <summary>On day <paramref name="dayOfMonth"/> (1–28) of every month at <paramref name="time"/>.</summary>
|
||||
public static ScheduleRecurrence MonthlyAt(int dayOfMonth, TimeOnly time)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(dayOfMonth, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(dayOfMonth, MaxDayOfMonth);
|
||||
return new ScheduleRecurrence(RecurrenceKind.Monthly, 0, default, Minute(time), 0, dayOfMonth);
|
||||
}
|
||||
|
||||
/// <summary>The recurrence written as <paramref name="text"/> (any case, spaces around parts allowed).</summary>
|
||||
/// <exception cref="FormatException">The text is not a valid recurrence.</exception>
|
||||
public static ScheduleRecurrence Parse(string text) =>
|
||||
TryParse(text, out var recurrence) ? recurrence : throw new FormatException($"'{text}' is not a schedule recurrence.");
|
||||
|
||||
/// <summary>Parses the text form; false for anything else, values out of range included.</summary>
|
||||
public static bool TryParse([NotNullWhen(true)] string? text, [NotNullWhen(true)] out ScheduleRecurrence? recurrence)
|
||||
{
|
||||
recurrence = null;
|
||||
if (string.IsNullOrWhiteSpace(text)) return false;
|
||||
var colon = text.IndexOf(':', StringComparison.Ordinal);
|
||||
if (colon <= 0) return false;
|
||||
var kind = text[..colon].Trim().ToLowerInvariant();
|
||||
var rest = text[(colon + 1)..].Trim();
|
||||
try
|
||||
{
|
||||
recurrence = kind switch
|
||||
{
|
||||
"every" => ParseInterval(rest),
|
||||
"daily" => TryTime(rest, out var time) ? DailyAt(time) : null,
|
||||
"weekly" => ParseWeekly(rest),
|
||||
"monthly" => ParseMonthly(rest),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
// A value out of range (every:4m, monthly:29@…).
|
||||
recurrence = null;
|
||||
}
|
||||
return recurrence is not null;
|
||||
}
|
||||
|
||||
/// <summary>The canonical text form: <c>every:10m</c>, <c>daily:03:00</c>, <c>weekly:mon,thu@02:30</c>, <c>monthly:1@04:00</c>.</summary>
|
||||
public string Format()
|
||||
{
|
||||
var time = Time.ToString("HH:mm", CultureInfo.InvariantCulture);
|
||||
return Kind switch
|
||||
{
|
||||
RecurrenceKind.Every => string.Create(CultureInfo.InvariantCulture,
|
||||
$"every:{Every}{Unit switch { RecurrenceUnit.Minutes => 'm', RecurrenceUnit.Hours => 'h', _ => 'd' }}"),
|
||||
RecurrenceKind.Daily => "daily:" + time,
|
||||
RecurrenceKind.Weekly => new StringBuilder("weekly:").AppendJoin(',', Days.Select(DayName)).Append('@').Append(time).ToString(),
|
||||
_ => string.Create(CultureInfo.InvariantCulture, $"monthly:{DayOfMonth}@{time}"),
|
||||
};
|
||||
}
|
||||
|
||||
public override string ToString() => Format();
|
||||
|
||||
/// <summary>The wire name of <paramref name="day"/>: <c>mon</c> … <c>sun</c>.</summary>
|
||||
public static string DayName(DayOfWeek day) => DayNames[Array.IndexOf(WeekOrder, day)];
|
||||
|
||||
/// <summary>The day named <paramref name="name"/> (<see cref="DayNames"/>, any case); false for anything else.</summary>
|
||||
public static bool TryParseDay(string? name, out DayOfWeek day)
|
||||
{
|
||||
var index = IndexOfDay(name);
|
||||
day = index < 0 ? default : WeekOrder[index];
|
||||
return index >= 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The first occurrence strictly after <paramref name="afterUtc"/>, in UTC and to the minute. An interval is laid on the
|
||||
/// grid of <paramref name="anchorUtc"/> (the previous due time: no drift, missed occurrences collapse into the next one),
|
||||
/// or starts one interval after <paramref name="afterUtc"/>'s minute without an anchor. Daily, weekly and monthly times
|
||||
/// are read in <paramref name="zone"/> (see the type's remarks for clock changes); they need no anchor.
|
||||
/// </summary>
|
||||
public DateTimeOffset Next(DateTimeOffset afterUtc, TimeZoneInfo zone, DateTimeOffset? anchorUtc = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(zone);
|
||||
var after = afterUtc.ToUniversalTime();
|
||||
if (Kind == RecurrenceKind.Every)
|
||||
{
|
||||
var period = Period.Ticks;
|
||||
if (anchorUtc is not { } anchor) return Truncate(after) + Period;
|
||||
var behind = after.UtcTicks - anchor.UtcTicks;
|
||||
var steps = behind / period;
|
||||
if (behind % period != 0 && behind < 0) steps--;
|
||||
return new DateTimeOffset(anchor.UtcTicks + (steps + 1) * period, TimeSpan.Zero);
|
||||
}
|
||||
var local = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(after, zone).DateTime);
|
||||
// From the day before: a time a gap moves forward can land after a later midnight.
|
||||
for (var i = -1; i <= 400; i++)
|
||||
{
|
||||
var day = local.AddDays(i);
|
||||
if (!Matches(day)) continue;
|
||||
var at = ToUtc(day.ToDateTime(Time), zone);
|
||||
if (at > after) return at;
|
||||
}
|
||||
throw new InvalidOperationException($"No occurrence of {Format()} within a year.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The UTC instant of the wall-clock time <paramref name="local"/> in <paramref name="zone"/>: a time inside a
|
||||
/// spring-forward gap moves forward by the gap, an ambiguous one takes its first occurrence (still on the larger offset).
|
||||
/// </summary>
|
||||
public static DateTimeOffset ToUtc(DateTime local, TimeZoneInfo zone)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(zone);
|
||||
local = DateTime.SpecifyKind(local, DateTimeKind.Unspecified);
|
||||
TimeSpan offset;
|
||||
if (zone.IsInvalidTime(local)) offset = zone.GetUtcOffset(local.AddHours(-12));
|
||||
else if (zone.IsAmbiguousTime(local)) offset = zone.GetAmbiguousTimeOffsets(local).Max();
|
||||
else offset = zone.GetUtcOffset(local);
|
||||
return new DateTimeOffset(local.Ticks - offset.Ticks, TimeSpan.Zero);
|
||||
}
|
||||
|
||||
/// <summary><c>10m</c>, <c>6h</c>, <c>7d</c>; null for anything else.</summary>
|
||||
private static ScheduleRecurrence? ParseInterval(string text)
|
||||
{
|
||||
if (text.Length < 2) return null;
|
||||
RecurrenceUnit? unit = char.ToLowerInvariant(text[^1]) switch
|
||||
{
|
||||
'm' => RecurrenceUnit.Minutes,
|
||||
'h' => RecurrenceUnit.Hours,
|
||||
'd' => RecurrenceUnit.Days,
|
||||
_ => null,
|
||||
};
|
||||
return unit is { } u && TryNumber(text[..^1], out var every) ? Interval(every, u) : null;
|
||||
}
|
||||
|
||||
/// <summary><c>mon,thu@02:30</c>; null for anything else.</summary>
|
||||
private static ScheduleRecurrence? ParseWeekly(string text)
|
||||
{
|
||||
var at = text.LastIndexOf('@');
|
||||
if (at <= 0 || !TryTime(text[(at + 1)..], out var time)) return null;
|
||||
var days = new List<DayOfWeek>();
|
||||
foreach (var name in text[..at].Split(','))
|
||||
{
|
||||
if (!TryParseDay(name.Trim(), out var day)) return null;
|
||||
days.Add(day);
|
||||
}
|
||||
return WeeklyAt(days, time);
|
||||
}
|
||||
|
||||
/// <summary><c>1@04:00</c>; null for anything else.</summary>
|
||||
private static ScheduleRecurrence? ParseMonthly(string text)
|
||||
{
|
||||
var at = text.LastIndexOf('@');
|
||||
return at > 0 && TryNumber(text[..at], out var day) && TryTime(text[(at + 1)..], out var time) ? MonthlyAt(day, time) : null;
|
||||
}
|
||||
|
||||
private bool Matches(DateOnly day) => Kind switch
|
||||
{
|
||||
RecurrenceKind.Daily => true,
|
||||
RecurrenceKind.Weekly => (_days & Bit(day.DayOfWeek)) != 0,
|
||||
_ => day.Day == DayOfMonth,
|
||||
};
|
||||
|
||||
private static int Bit(DayOfWeek day) => 1 << (int)day;
|
||||
|
||||
private static TimeOnly Minute(TimeOnly time) => new(time.Hour, time.Minute);
|
||||
|
||||
private static DateTimeOffset Truncate(DateTimeOffset utc) => new(utc.UtcTicks - utc.UtcTicks % TimeSpan.TicksPerMinute, TimeSpan.Zero);
|
||||
|
||||
private static int IndexOfDay(string? name)
|
||||
{
|
||||
for (var i = 0; i < DayNames.Count; i++)
|
||||
{
|
||||
if (string.Equals(DayNames[i], name, StringComparison.OrdinalIgnoreCase)) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static bool TryNumber(string text, out int value) =>
|
||||
int.TryParse(text.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out value);
|
||||
|
||||
private static bool TryTime(string text, out TimeOnly time)
|
||||
{
|
||||
time = default;
|
||||
var parts = text.Trim().Split(':');
|
||||
if (parts is not [var h, var m] || h.Length is < 1 or > 2 || m.Length != 2
|
||||
|| !TryNumber(h, out var hour) || !TryNumber(m, out var minute) || hour > 23 || minute > 59)
|
||||
return false;
|
||||
time = new TimeOnly(hour, minute);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
using System.Threading.Channels;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.Data.Scheduling;
|
||||
|
||||
/// <summary>How a <see cref="Scheduler"/> keeps time.</summary>
|
||||
public sealed record SchedulerOptions
|
||||
{
|
||||
/// <summary>Clock of the runs (tests pass their own); its timers pace the loop.</summary>
|
||||
public TimeProvider Time { get; init; } = TimeProvider.System;
|
||||
|
||||
/// <summary>How often the loop looks for due schedules (and for schedules other processes changed).</summary>
|
||||
public TimeSpan Tick { get; init; } = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <summary>
|
||||
/// How late a run may be and still count as on time. A schedule further behind (the host was off, the PC slept) missed
|
||||
/// its run: with catch-up it fires once, without it moves to its next occurrence without running.
|
||||
/// </summary>
|
||||
public TimeSpan CatchUpGrace { get; init; } = TimeSpan.FromMinutes(5);
|
||||
}
|
||||
|
||||
/// <summary>What a schedule's run did: the outcome (<see cref="ScheduleOutcome"/>) and the first job it queued.</summary>
|
||||
internal sealed record ScheduleFire(Guid ScheduleId, string Outcome, Guid? JobId);
|
||||
|
||||
/// <summary>A schedule created or edited, or the first invalid field by its API name (<c>name</c>, <c>recurrence</c>, <c>parameters.steps</c>…).</summary>
|
||||
public sealed record ScheduleEditResult(ScheduleDto? Schedule, string? Problem)
|
||||
{
|
||||
/// <summary>True when the schedule to edit does not exist.</summary>
|
||||
public bool NotFound => Schedule is null && Problem is null;
|
||||
}
|
||||
|
||||
/// <summary>What <see cref="Scheduler.DeleteAsync"/> did.</summary>
|
||||
public enum ScheduleDeleteOutcome
|
||||
{
|
||||
Deleted,
|
||||
NotFound,
|
||||
|
||||
/// <summary>A system schedule: disable it instead.</summary>
|
||||
System,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the schedules of one host (owner review 2, R10), in the style of the <see cref="JobEngine"/> it queues jobs on.
|
||||
/// <see cref="StartAsync"/> seeds the host's system schedules (edits kept), gives enabled schedules without a next run one,
|
||||
/// moves past the runs that schedules without catch-up missed, fires those with catch-up once, then looks every
|
||||
/// <see cref="SchedulerOptions.Tick"/> (or at <see cref="Wake"/>). A due run is claimed by moving its next run with a
|
||||
/// compare-and-set, so several processes on one database fire it once; the claimed run then queues the action's jobs (at the
|
||||
/// schedule's priority, with its id) unless the schedule's previous job is still pending, and records the outcome. A crash
|
||||
/// between the claim and the queueing loses that one run (it is logged as claimed first). A next run more than two periods
|
||||
/// ahead means the clock went back: it is computed again. Edits go through this class so the next run follows them.
|
||||
/// </summary>
|
||||
public sealed class Scheduler : IAsyncDisposable
|
||||
{
|
||||
/// <summary>Longest schedule name.</summary>
|
||||
public const int MaxNameLength = 100;
|
||||
|
||||
/// <summary>The only target so far: the host's archive.</summary>
|
||||
public const string CurrentTarget = "current";
|
||||
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly JobEngine _engine;
|
||||
private readonly Channel<bool> _wake = Channel.CreateBounded<bool>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
|
||||
private readonly CancellationTokenSource _shutdown = new();
|
||||
private readonly Lock _gate = new();
|
||||
private IScheduleHost? _host;
|
||||
private Task _loop = Task.CompletedTask;
|
||||
|
||||
public Scheduler(ChronosDatabase db, JobEngine engine, SchedulerOptions? options = null)
|
||||
{
|
||||
_db = db ?? throw new ArgumentNullException(nameof(db));
|
||||
_engine = engine ?? throw new ArgumentNullException(nameof(engine));
|
||||
Options = options ?? new SchedulerOptions();
|
||||
}
|
||||
|
||||
public SchedulerOptions Options { get; }
|
||||
|
||||
/// <summary>The host given to <see cref="StartAsync"/>; null before.</summary>
|
||||
public IScheduleHost? Host => Volatile.Read(ref _host);
|
||||
|
||||
/// <summary>A schedule was created, edited, reset or ran (also by the loop). Raised on the caller's or the loop's thread.</summary>
|
||||
public event Action<ScheduleDto>? ScheduleChanged;
|
||||
|
||||
/// <summary>A schedule was deleted.</summary>
|
||||
public event Action<Guid>? ScheduleDeleted;
|
||||
|
||||
/// <summary>
|
||||
/// Seeds <paramref name="host"/>'s system schedules, settles the runs missed while the host was off (see the type's
|
||||
/// remarks) and starts the loop. The first pass runs before this returns.
|
||||
/// </summary>
|
||||
public Task StartAsync(IScheduleHost host, CancellationToken cancellationToken = default) => StartAsync(host, null, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="StartAsync(IScheduleHost, CancellationToken)"/>, calling <paramref name="beforeFirstPass"/> once the system
|
||||
/// schedules are seeded and edits are possible, before the first pass: what it changes (a value an environment variable
|
||||
/// fixes) applies to the runs caught up at start too.
|
||||
/// </summary>
|
||||
public async Task StartAsync(IScheduleHost host, Func<CancellationToken, Task>? beforeFirstPass, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(host);
|
||||
if (Host is not null) throw new InvalidOperationException("The scheduler has started already.");
|
||||
var added = await _db.Schedules.EnsureSystemAsync(host.SystemSchedules, Now(), cancellationToken).ConfigureAwait(false);
|
||||
if (added > 0) Log.Info("schedules", $"Added {added} system schedule(s)");
|
||||
if (Interlocked.CompareExchange(ref _host, host, null) is not null) throw new InvalidOperationException("The scheduler has started already.");
|
||||
if (beforeFirstPass is not null) await beforeFirstPass(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await RunDueAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
Log.Warning("schedules", "The schedules could not be run at start; the loop tries again", ex);
|
||||
}
|
||||
var shutdown = _shutdown.Token;
|
||||
lock (_gate) _loop = Task.Run(() => LoopAsync(shutdown), CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>Makes the loop look for due schedules now (another process changed them, the archive came back).</summary>
|
||||
public void Wake() => _wake.Writer.TryWrite(true);
|
||||
|
||||
/// <summary>
|
||||
/// One pass of the loop: corrects next runs (missing, clock gone back, missed without catch-up), then claims and fires
|
||||
/// every due schedule. Returns how many fired here.
|
||||
/// </summary>
|
||||
public async Task<int> RunDueAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var host = RequireHost();
|
||||
var now = Now();
|
||||
foreach (var schedule in await _db.Schedules.ListAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (schedule.Enabled) await CorrectAsync(host, schedule, now, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
var fired = 0;
|
||||
foreach (var schedule in await _db.Schedules.ListDueAsync(now, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
DateTimeOffset? next = ScheduleRecurrence.TryParse(schedule.Recurrence, out var recurrence)
|
||||
? recurrence.Next(now, host.TimeZone, schedule.NextRun)
|
||||
: null;
|
||||
// The claim: one process wins the run; the others see the moved next run and leave it.
|
||||
if (!await _db.Schedules.TryAdvanceAsync(schedule.Id, schedule.NextRun, next, cancellationToken).ConfigureAwait(false)) continue;
|
||||
if (next is null)
|
||||
{
|
||||
Log.Warning("schedules", $"Schedule {schedule.Id} has an invalid recurrence '{schedule.Recurrence}'; it stops until edited");
|
||||
await RecordAsync(schedule.Id, null, ScheduleOutcome.Failed("recurrence"), cancellationToken).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
Log.Debug("schedules", $"{schedule.Name} ({schedule.Action}) due {schedule.NextRun:O} claimed; next {next:O}");
|
||||
await FireAsync(host, schedule, schedule.CreatedBy, manual: false, cancellationToken).ConfigureAwait(false);
|
||||
fired++;
|
||||
}
|
||||
return fired;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the schedule now, as its next run would (also a disabled one), without moving its next run; null when it does
|
||||
/// not exist. <paramref name="userId"/> is stamped on the jobs it queues.
|
||||
/// </summary>
|
||||
public async Task<ScheduleRunDto?> RunNowAsync(Guid id, Guid? userId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var host = RequireHost();
|
||||
if (await _db.Schedules.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } schedule) return null;
|
||||
var fire = await FireAsync(host, schedule, userId ?? schedule.CreatedBy, manual: true, cancellationToken).ConfigureAwait(false);
|
||||
var dto = await GetAsync(id, cancellationToken).ConfigureAwait(false) ?? ScheduleMapping.ToDto(schedule);
|
||||
return new ScheduleRunDto(dto, fire.Outcome, fire.JobId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the system schedule <paramref name="systemKey"/> now (<see cref="RunNowAsync"/>, which skips while its work is
|
||||
/// pending) when it is enabled and has not run since <paramref name="since"/>; null when it did not run. The hosts' archive
|
||||
/// scan once at start, as their polling did, and on the desktop when its archive is opened again (owner review 2, R10).
|
||||
/// </summary>
|
||||
public async Task<ScheduleRunDto?> RunSystemNowAsync(string systemKey, DateTimeOffset? since = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_ = RequireHost();
|
||||
if (await _db.Schedules.GetBySystemKeyAsync(systemKey, cancellationToken).ConfigureAwait(false) is not { Enabled: true } schedule
|
||||
|| schedule.LastRun >= since) return null;
|
||||
return await RunNowAsync(schedule.Id, null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The schedules (system ones first), the actions with their availability here, the host's time zone and clean-up steps.</summary>
|
||||
public async Task<SchedulesDto> ListAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var host = RequireHost();
|
||||
var items = await _db.Schedules.ListAsync(cancellationToken).ConfigureAwait(false);
|
||||
var actions = await ScheduleActions.AvailabilityAsync(Context(host), cancellationToken).ConfigureAwait(false);
|
||||
return new SchedulesDto([.. items.Select(ScheduleMapping.ToDto)], [.. actions.Select(ScheduleMapping.ToDto)], host.TimeZone.Id, host.CleanupSteps);
|
||||
}
|
||||
|
||||
public async Task<ScheduleDto?> GetAsync(Guid id, CancellationToken cancellationToken = default) =>
|
||||
await _db.Schedules.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } schedule ? ScheduleMapping.ToDto(schedule) : null;
|
||||
|
||||
/// <summary>Creates a schedule (enabled ones get their next run at once); the result names the first invalid field instead when there is one.</summary>
|
||||
public async Task<ScheduleEditResult> CreateAsync(CreateScheduleRequest request, Guid? createdBy, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var host = RequireHost();
|
||||
if (Problem(host, request.Name, request.Action, request.Target, request.Recurrence, request.Parameters, request.Priority) is { } problem)
|
||||
return new ScheduleEditResult(null, problem);
|
||||
var recurrence = ScheduleMapping.FromDto(request.Recurrence)!;
|
||||
var now = Now();
|
||||
var schedule = new Schedule
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Name = request.Name.Trim(),
|
||||
Action = request.Action,
|
||||
Target = CurrentTarget,
|
||||
ParametersJson = ScheduleMapping.ParametersJson(request.Action, request.Parameters),
|
||||
Recurrence = recurrence.Format(),
|
||||
CatchUp = request.CatchUp,
|
||||
Priority = Priority(request.Priority, JobPriority.Background),
|
||||
Enabled = request.Enabled,
|
||||
NextRun = request.Enabled ? recurrence.Next(now, host.TimeZone) : null,
|
||||
CreatedBy = createdBy,
|
||||
Created = now,
|
||||
Updated = now,
|
||||
};
|
||||
await _db.Schedules.InsertAsync(schedule, cancellationToken).ConfigureAwait(false);
|
||||
Log.Info("schedules", $"Schedule {schedule.Name} ({schedule.Action}, {schedule.Recurrence}) created");
|
||||
return new ScheduleEditResult(Changed(schedule), null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Changes the fields <paramref name="request"/> gives. The next run is computed again when the recurrence changes or
|
||||
/// the schedule is enabled; a disabled schedule has none. A system schedule keeps its name and action (asking to change
|
||||
/// them is a problem of field <c>name</c> or <c>action</c>).
|
||||
/// </summary>
|
||||
public async Task<ScheduleEditResult> UpdateAsync(Guid id, UpdateScheduleRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var host = RequireHost();
|
||||
if (await _db.Schedules.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } current) return new ScheduleEditResult(null, null);
|
||||
if (current.IsSystem && request.Name is { } name && name.Trim() != current.Name) return new ScheduleEditResult(null, "name");
|
||||
if (current.IsSystem && request.Action is { } changed && changed != current.Action) return new ScheduleEditResult(null, "action");
|
||||
var action = request.Action ?? current.Action;
|
||||
// Another action starts from its own defaults; the same one keeps the stored values the request leaves out.
|
||||
var parameters = request.Parameters ?? (action == current.Action ? ScheduleMapping.Parameters(current) : null);
|
||||
var recurrenceDto = request.Recurrence ?? (ScheduleRecurrence.TryParse(current.Recurrence, out var stored) ? ScheduleMapping.ToDto(stored) : null);
|
||||
if (Problem(host, request.Name ?? current.Name, action, null, recurrenceDto, parameters, request.Priority) is { } problem)
|
||||
return new ScheduleEditResult(null, problem);
|
||||
var recurrence = ScheduleMapping.FromDto(recurrenceDto)!;
|
||||
var now = Now();
|
||||
var enabled = request.Enabled ?? current.Enabled;
|
||||
var reschedule = !enabled || !current.Enabled || current.NextRun is null || recurrence.Format() != current.Recurrence;
|
||||
var schedule = current with
|
||||
{
|
||||
Name = (request.Name ?? current.Name).Trim(),
|
||||
Action = action,
|
||||
ParametersJson = ScheduleMapping.ParametersJson(action, parameters),
|
||||
Recurrence = recurrence.Format(),
|
||||
CatchUp = request.CatchUp ?? current.CatchUp,
|
||||
Priority = Priority(request.Priority, current.Priority),
|
||||
Enabled = enabled,
|
||||
NextRun = !enabled ? null : reschedule ? recurrence.Next(now, host.TimeZone) : current.NextRun,
|
||||
Updated = now,
|
||||
};
|
||||
if (!await _db.Schedules.UpdateAsync(schedule, reschedule, cancellationToken).ConfigureAwait(false)) return new ScheduleEditResult(null, null);
|
||||
Log.Info("schedules", $"Schedule {schedule.Name} ({schedule.Action}, {schedule.Recurrence}, {(enabled ? "enabled" : "disabled")}) changed");
|
||||
var saved = await _db.Schedules.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? schedule;
|
||||
return new ScheduleEditResult(Changed(saved), null);
|
||||
}
|
||||
|
||||
/// <summary>Deletes a schedule a user created; a system schedule is refused (<see cref="ScheduleDeleteOutcome.System"/>).</summary>
|
||||
public async Task<ScheduleDeleteOutcome> DeleteAsync(Guid id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (await _db.Schedules.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } schedule) return ScheduleDeleteOutcome.NotFound;
|
||||
if (schedule.IsSystem) return ScheduleDeleteOutcome.System;
|
||||
if (!await _db.Schedules.DeleteAsync(id, cancellationToken).ConfigureAwait(false)) return ScheduleDeleteOutcome.NotFound;
|
||||
Log.Info("schedules", $"Schedule {schedule.Name} ({schedule.Action}) deleted");
|
||||
ScheduleDeleted?.Invoke(id);
|
||||
return ScheduleDeleteOutcome.Deleted;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts a system schedule back to the host's defaults (<see cref="IScheduleHost.SystemSchedules"/>) with a new next
|
||||
/// run. A schedule a user created, or one the host no longer defines, is a problem of field <c>systemKey</c>.
|
||||
/// </summary>
|
||||
public async Task<ScheduleEditResult> ResetAsync(Guid id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var host = RequireHost();
|
||||
if (await _db.Schedules.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } current) return new ScheduleEditResult(null, null);
|
||||
if (current.SystemKey is not { } key || host.SystemSchedules.FirstOrDefault(s => s.SystemKey == key) is not { } defaults)
|
||||
return new ScheduleEditResult(null, "systemKey");
|
||||
var now = Now();
|
||||
await _db.Schedules.ResetSystemAsync(key, defaults, now, cancellationToken).ConfigureAwait(false);
|
||||
if (defaults.Enabled) await _db.Schedules.TryAdvanceAsync(id, null, defaults.Recurrence.Next(now, host.TimeZone), cancellationToken).ConfigureAwait(false);
|
||||
Log.Info("schedules", $"System schedule {key} reset");
|
||||
var saved = await _db.Schedules.GetAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
return saved is null ? new ScheduleEditResult(null, null) : new ScheduleEditResult(Changed(saved), null);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
Task loop;
|
||||
lock (_gate) loop = _loop;
|
||||
await _shutdown.CancelAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await loop.ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
_shutdown.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fills in a missing next run, computes it again after the clock went back, and moves a schedule without catch-up past
|
||||
/// a run it missed. Compare-and-set like a claim, so concurrent passes agree.
|
||||
/// </summary>
|
||||
private async Task CorrectAsync(IScheduleHost host, Schedule schedule, DateTimeOffset now, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!ScheduleRecurrence.TryParse(schedule.Recurrence, out var recurrence)) return;
|
||||
DateTimeOffset next;
|
||||
string why;
|
||||
if (schedule.NextRun is not { } due)
|
||||
{
|
||||
next = recurrence.Next(now, host.TimeZone);
|
||||
why = "first run";
|
||||
}
|
||||
else if (due - now > recurrence.Period * 2)
|
||||
{
|
||||
next = recurrence.Next(now, host.TimeZone);
|
||||
why = "the clock went back";
|
||||
}
|
||||
else if (!schedule.CatchUp && now - due > Options.CatchUpGrace)
|
||||
{
|
||||
next = recurrence.Next(now, host.TimeZone, due);
|
||||
why = $"missed the run of {due:O} (no catch-up)";
|
||||
}
|
||||
else
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (!await _db.Schedules.TryAdvanceAsync(schedule.Id, schedule.NextRun, next, cancellationToken).ConfigureAwait(false)) return;
|
||||
Log.Info("schedules", $"{schedule.Name} ({schedule.Action}): next run {next:O} ({why})");
|
||||
Changed(schedule with { NextRun = next });
|
||||
}
|
||||
|
||||
/// <summary>Queues the schedule's action unless its previous job is pending, records the outcome and logs one line.</summary>
|
||||
private async Task<ScheduleFire> FireAsync(IScheduleHost host, Schedule schedule, Guid? createdBy, bool manual, CancellationToken cancellationToken)
|
||||
{
|
||||
string outcome;
|
||||
Guid? jobId = null;
|
||||
try
|
||||
{
|
||||
if (schedule.LastJobId is { } last
|
||||
&& await _db.Jobs.GetAsync(last, cancellationToken).ConfigureAwait(false) is { State: JobState.Queued or JobState.Running or JobState.Paused })
|
||||
{
|
||||
outcome = ScheduleOutcome.SkippedPending;
|
||||
}
|
||||
else
|
||||
{
|
||||
var resolution = await ScheduleActions.ResolveAsync(Context(host), schedule.Action, ScheduleMapping.Parameters(schedule), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
outcome = resolution.Outcome;
|
||||
foreach (var request in resolution.Requests)
|
||||
{
|
||||
var job = await _engine.EnqueueAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, schedule.Priority, createdBy,
|
||||
schedule.Id, cancellationToken).ConfigureAwait(false);
|
||||
jobId ??= job.Id;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning("schedules", $"{schedule.Name} ({schedule.Action}) could not run", ex);
|
||||
outcome = ScheduleOutcome.Failed(ex.Message);
|
||||
}
|
||||
await RecordAsync(schedule.Id, jobId, outcome, CancellationToken.None).ConfigureAwait(false);
|
||||
Log.Info("schedules", $"{schedule.Name} ({schedule.Action}{(manual ? ", run now" : string.Empty)}): {outcome}{(jobId is { } id ? $", job {id}" : string.Empty)}");
|
||||
return new ScheduleFire(schedule.Id, outcome, jobId);
|
||||
}
|
||||
|
||||
private async Task RecordAsync(Guid id, Guid? jobId, string outcome, CancellationToken cancellationToken)
|
||||
{
|
||||
await _db.Schedules.RecordOutcomeAsync(id, jobId, outcome, Now(), cancellationToken).ConfigureAwait(false);
|
||||
if (await _db.Schedules.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } saved) Changed(saved);
|
||||
}
|
||||
|
||||
private async Task LoopAsync(CancellationToken shutdown)
|
||||
{
|
||||
while (!shutdown.IsCancellationRequested)
|
||||
{
|
||||
await WaitAsync(shutdown).ConfigureAwait(false);
|
||||
if (shutdown.IsCancellationRequested) return;
|
||||
try
|
||||
{
|
||||
await RunDueAsync(shutdown).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (shutdown.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Nothing a pass throws ends the loop (a database briefly away, a host hook that failed).
|
||||
Log.Warning("schedules", "The schedules could not be run; the next tick tries again", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Waits for <see cref="Wake"/>, the tick or shutdown, whichever comes first.</summary>
|
||||
private async Task WaitAsync(CancellationToken shutdown)
|
||||
{
|
||||
using var tick = new CancellationTokenSource(Options.Tick, Options.Time);
|
||||
using var either = CancellationTokenSource.CreateLinkedTokenSource(shutdown, tick.Token);
|
||||
try
|
||||
{
|
||||
await _wake.Reader.ReadAsync(either.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Tick elapsed or shutdown.
|
||||
}
|
||||
}
|
||||
|
||||
private ScheduleDto Changed(Schedule schedule)
|
||||
{
|
||||
var dto = ScheduleMapping.ToDto(schedule);
|
||||
ScheduleChanged?.Invoke(dto);
|
||||
return dto;
|
||||
}
|
||||
|
||||
private ScheduleActionContext Context(IScheduleHost host) => new(_db, host, _engine.CanRun, Now());
|
||||
|
||||
private DateTimeOffset Now() => Options.Time.GetUtcNow();
|
||||
|
||||
private IScheduleHost RequireHost() => Host ?? throw new InvalidOperationException("Start the scheduler with its host first.");
|
||||
|
||||
private static JobPriority Priority(string? wire, JobPriority fallback) => wire is not null && JobWire.TryParsePriority(wire, out var priority) ? priority : fallback;
|
||||
|
||||
/// <summary>The first invalid field of a schedule as given, by its API name; null when it is valid.</summary>
|
||||
private static string? Problem(IScheduleHost host, string? name, string? action, string? target, RecurrenceDto? recurrence,
|
||||
ScheduleParametersDto? parameters, string? priority)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(name) || name.Trim().Length > MaxNameLength) return "name";
|
||||
if (action is null) return "action";
|
||||
if (ScheduleActions.Problem(action, parameters, host.CleanupSteps) is { } invalid) return invalid;
|
||||
if (target is not null && target != CurrentTarget) return "target";
|
||||
if (ScheduleMapping.FromDto(recurrence) is null) return "recurrence";
|
||||
if (priority is not null && !JobWire.TryParsePriority(priority, out _)) return "priority";
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,14 @@ namespace Chronos.Protocol;
|
||||
|
||||
/// <summary>
|
||||
/// <c>GET/PUT /api/v1/server/settings</c> (admin): the editable part of the server configuration. Settings named in
|
||||
/// <see cref="Locked"/> come from environment variables and cannot be changed here; <see cref="RestartRequired"/> says
|
||||
/// that saved values (ports, TLS, chunk size, job history) wait for a restart. <see cref="ProxyWarning"/> is set in
|
||||
/// responses when TLS mode is proxy and the request did not come through a trusted proxy over HTTPS (ignored when saving).
|
||||
/// <see cref="Locked"/> come from environment variables and cannot be changed here; <see cref="LockedBy"/> names the
|
||||
/// variable that fixes each of them (ignored when saving); <see cref="RestartRequired"/> says
|
||||
/// that saved values (ports, TLS, chunk size) wait for a restart; <see cref="JobHistoryDays"/> is what the housekeeping
|
||||
/// schedule is reset to (owner review 2, R10). <see cref="ProxyWarning"/> is set in responses when TLS mode is proxy and
|
||||
/// the request did not come through a trusted proxy over HTTPS (ignored when saving).
|
||||
/// <see cref="Parallelism"/> is how many photos the running job processes at once (jobs run one at a time), and
|
||||
/// <see cref="PriorityQueue"/> with <see cref="JobPriorities"/> the priority queue (owner review 1); both apply at once.
|
||||
/// <see cref="PriorityQueue"/> with <see cref="JobPriorities"/> the priority queue (owner review 1); both apply at once, as
|
||||
/// do <see cref="Logs"/> (owner review 2, R11; a request without them keeps them as they are).
|
||||
/// </summary>
|
||||
public sealed record ServerSettingsDto(
|
||||
string ServerName,
|
||||
@@ -25,10 +28,32 @@ public sealed record ServerSettingsDto(
|
||||
int JobHistoryDays,
|
||||
int TokenLifetimeDays,
|
||||
int UploadRetentionHours,
|
||||
LogSettingsDto Logs,
|
||||
IReadOnlyList<string> Locked,
|
||||
IReadOnlyDictionary<string, string> LockedBy,
|
||||
bool RestartRequired,
|
||||
bool ProxyWarning);
|
||||
|
||||
/// <summary>
|
||||
/// The log settings of <see cref="ServerSettingsDto"/> (owner review 2, R11): the least severe level of the files and of the
|
||||
/// console (<c>trace</c>, <c>debug</c>, <c>information</c>, <c>warning</c>, <c>error</c>, <c>critical</c>, <c>none</c>), the
|
||||
/// days log files are kept, the size at which a file continues in a numbered one and the size of all of them (MB of 2²⁰
|
||||
/// bytes, 0 = no limit), the rotation (<c>daily</c> or <c>hourly</c>, UTC), the days audit entries are kept (the audit
|
||||
/// clean-up schedule's age limit; 0 = forever, as while that schedule is off) and the MB of the end of each log file in
|
||||
/// the diagnostics zip. Their locks use the server.json names (<c>LogLevel</c>, <c>ConsoleLogLevel</c>,
|
||||
/// <c>LogRetentionDays</c>, <c>LogMaxFileMb</c>, <c>LogMaxTotalMb</c>, <c>LogRotation</c>, <c>AuditRetentionDays</c>,
|
||||
/// <c>DiagnosticsLogMb</c>).
|
||||
/// </summary>
|
||||
public sealed record LogSettingsDto(
|
||||
string FileLevel,
|
||||
string ConsoleLevel,
|
||||
int RetentionDays,
|
||||
int MaxFileMb,
|
||||
int MaxTotalMb,
|
||||
string Rotation,
|
||||
int AuditRetentionDays,
|
||||
int DiagnosticsLogMb);
|
||||
|
||||
/// <summary>A kind of job (<c>render</c>) and its level in the server's priority queue: <c>high</c>, <c>normal</c> or <c>low</c>.</summary>
|
||||
public sealed record JobPriorityDto(string Kind, string Level);
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ namespace Chronos.Protocol;
|
||||
|
||||
/// <summary>
|
||||
/// Messages pushed on <c>WS /api/v1/events</c>. Each frame is one JSON object with a <c>type</c> discriminator:
|
||||
/// jobProgress, jobState, sequenceChanged, cardEvent, nodeState.
|
||||
/// jobProgress, jobState, sequenceChanged, cardEvent, nodeState, scheduleChanged.
|
||||
/// </summary>
|
||||
[JsonPolymorphic(TypeDiscriminatorPropertyName = "type")]
|
||||
[JsonDerivedType(typeof(JobProgressEvent), "jobProgress")]
|
||||
@@ -12,6 +12,7 @@ namespace Chronos.Protocol;
|
||||
[JsonDerivedType(typeof(SequenceChangedEvent), "sequenceChanged")]
|
||||
[JsonDerivedType(typeof(CardEvent), "cardEvent")]
|
||||
[JsonDerivedType(typeof(NodeStateEvent), "nodeState")]
|
||||
[JsonDerivedType(typeof(ScheduleChangedEvent), "scheduleChanged")]
|
||||
public abstract record ServerEvent;
|
||||
|
||||
public sealed record JobProgressEvent(Guid JobId, long Done, long Total, double? ItemsPerSecond, double? EtaSeconds) : ServerEvent;
|
||||
@@ -41,3 +42,9 @@ public static class CardImportStates
|
||||
}
|
||||
|
||||
public sealed record NodeStateEvent(Guid NodeId, string ClientName, string State) : ServerEvent;
|
||||
|
||||
/// <summary>
|
||||
/// A schedule of the server was created, edited, reset, deleted (<see cref="Deleted"/>) or ran, a run that queued nothing
|
||||
/// included, or its next run moved (owner review 2, R10): the admin panel's Scheduled tab reads the list again.
|
||||
/// </summary>
|
||||
public sealed record ScheduleChangedEvent(Guid ScheduleId, bool Deleted) : ServerEvent;
|
||||
@@ -1,5 +1,6 @@
|
||||
namespace Chronos.Protocol;
|
||||
|
||||
/// <summary>A job of the queue. <see cref="ScheduleId"/>: the schedule that queued it (owner review 2, R10), absent otherwise.</summary>
|
||||
public sealed record JobDto(
|
||||
Guid Id,
|
||||
string Kind,
|
||||
@@ -17,7 +18,8 @@ public sealed record JobDto(
|
||||
string? Error,
|
||||
DateTimeOffset Created,
|
||||
DateTimeOffset? Started,
|
||||
DateTimeOffset? Finished);
|
||||
DateTimeOffset? Finished,
|
||||
Guid? ScheduleId = null);
|
||||
|
||||
/// <summary><c>POST /api/v1/jobs</c>: kind = render, deep-analyse, proxies, thumbs, verify, scan, rebuild, maintenance…</summary>
|
||||
public sealed record CreateJobRequest(string Kind, IReadOnlyList<Guid> Target, string? ParametersJson);
|
||||
|
||||
@@ -64,4 +64,13 @@ namespace Chronos.Protocol;
|
||||
[JsonSerializable(typeof(List<LogFileDto>))]
|
||||
[JsonSerializable(typeof(LogTailDto))]
|
||||
[JsonSerializable(typeof(DashboardDto))]
|
||||
[JsonSerializable(typeof(ScheduleParametersDto))]
|
||||
[JsonSerializable(typeof(RecurrenceDto))]
|
||||
[JsonSerializable(typeof(ScheduleDto))]
|
||||
[JsonSerializable(typeof(List<ScheduleDto>))]
|
||||
[JsonSerializable(typeof(ScheduleActionDto))]
|
||||
[JsonSerializable(typeof(SchedulesDto))]
|
||||
[JsonSerializable(typeof(CreateScheduleRequest))]
|
||||
[JsonSerializable(typeof(UpdateScheduleRequest))]
|
||||
[JsonSerializable(typeof(ScheduleRunDto))]
|
||||
public sealed partial class ProtocolJson : JsonSerializerContext;
|
||||
@@ -0,0 +1,97 @@
|
||||
namespace Chronos.Protocol;
|
||||
|
||||
/// <summary>
|
||||
/// The parameters of a schedule's action (owner review 2, R10), flat: each action reads its own fields, the others stay
|
||||
/// null (and are not stored). <c>scan</c>: <see cref="Force"/> (full scan), <see cref="Deep"/> (background deep analysis of
|
||||
/// what it indexes). <c>verify</c>: <see cref="OlderThanDays"/> (only sequences not verified for that many days; 0: any),
|
||||
/// <see cref="Percent"/> (share of the archive's sequences per run, least recently verified first). <c>thumbnails</c>,
|
||||
/// <c>proxies</c>: <see cref="Force"/> (make again those already made). <c>analysis</c>: <see cref="Deep"/> (deep instead of
|
||||
/// light). <c>maintenance</c>: <see cref="DryRun"/>. <c>backup</c>: <see cref="Keep"/> (copies kept). <c>cleanup</c>:
|
||||
/// <see cref="Steps"/> (step names) and <see cref="OlderThanDays"/> (what is older goes; 0 keeps everything).
|
||||
/// <c>duplicates</c>, <c>orphans</c>: none.
|
||||
/// </summary>
|
||||
public sealed record ScheduleParametersDto(
|
||||
int? OlderThanDays = null,
|
||||
int? Percent = null,
|
||||
bool? Deep = null,
|
||||
bool? DryRun = null,
|
||||
bool? Force = null,
|
||||
IReadOnlyList<string>? Steps = null,
|
||||
int? Keep = null);
|
||||
|
||||
/// <summary>
|
||||
/// When a schedule fires, structured. <see cref="Kind"/> = <c>every</c> (<see cref="Every"/> and <see cref="Unit"/>:
|
||||
/// <c>minutes</c>, <c>hours</c> or <c>days</c>; at least 5 minutes), <c>daily</c> (<see cref="Time"/>), <c>weekly</c>
|
||||
/// (<see cref="Days"/>: <c>mon</c> … <c>sun</c>; <see cref="Time"/>) or <c>monthly</c> (<see cref="DayOfMonth"/> 1–28;
|
||||
/// <see cref="Time"/>). <see cref="Time"/> is <c>HH:MM</c>, wall-clock time of the host's time zone.
|
||||
/// </summary>
|
||||
public sealed record RecurrenceDto(
|
||||
string Kind,
|
||||
int? Every = null,
|
||||
string? Unit = null,
|
||||
string? Time = null,
|
||||
IReadOnlyList<string>? Days = null,
|
||||
int? DayOfMonth = null);
|
||||
|
||||
/// <summary>
|
||||
/// A schedule (owner review 2, R10). <see cref="SystemKey"/> is set on the host's system schedules (the timers it runs,
|
||||
/// shown so nothing runs out of sight): they can be edited, disabled and reset, never deleted. <see cref="Priority"/> is the
|
||||
/// priority of the jobs it queues (<c>background</c>, <c>normal</c>, <c>user</c>). <see cref="LastOutcome"/>:
|
||||
/// <c>queued</c>, <c>skipped-pending</c>, <c>skipped-offline</c>, <c>skipped-nothing</c>, <c>unavailable</c> or
|
||||
/// <c>failed:<reason></c>. <see cref="NextRun"/> is null while the schedule is disabled.
|
||||
/// </summary>
|
||||
public sealed record ScheduleDto(
|
||||
Guid Id,
|
||||
string? SystemKey,
|
||||
string Name,
|
||||
string Action,
|
||||
string Target,
|
||||
ScheduleParametersDto Parameters,
|
||||
RecurrenceDto Recurrence,
|
||||
bool CatchUp,
|
||||
string Priority,
|
||||
bool Enabled,
|
||||
DateTimeOffset? NextRun,
|
||||
DateTimeOffset? LastRun,
|
||||
Guid? LastJobId,
|
||||
string? LastOutcome,
|
||||
Guid? CreatedBy,
|
||||
DateTimeOffset Created,
|
||||
DateTimeOffset Updated);
|
||||
|
||||
/// <summary>An action a schedule can take and whether this host runs it; <see cref="Reason"/> says why not (a code: <c>no-handler</c>, <c>postgres</c>, <c>proxies-disabled</c>…).</summary>
|
||||
public sealed record ScheduleActionDto(string Name, bool Available, string? Reason);
|
||||
|
||||
/// <summary>
|
||||
/// <c>GET /api/v1/schedules</c>: the schedules, system ones first, the actions with their availability, the host's time
|
||||
/// zone (IANA or Windows id, as the host names it) and the clean-up steps its <c>cleanup</c> action runs.
|
||||
/// </summary>
|
||||
public sealed record SchedulesDto(IReadOnlyList<ScheduleDto> Items, IReadOnlyList<ScheduleActionDto> Actions, string TimeZone,
|
||||
IReadOnlyList<string>? Steps = null);
|
||||
|
||||
/// <summary><c>POST /api/v1/schedules</c>: a new schedule; <see cref="Target"/> defaults to <c>current</c>, <see cref="Priority"/> to <c>background</c>.</summary>
|
||||
public sealed record CreateScheduleRequest(
|
||||
string Name,
|
||||
string Action,
|
||||
RecurrenceDto Recurrence,
|
||||
ScheduleParametersDto? Parameters = null,
|
||||
bool CatchUp = true,
|
||||
string? Priority = null,
|
||||
bool Enabled = true,
|
||||
string? Target = null);
|
||||
|
||||
/// <summary>
|
||||
/// <c>PATCH /api/v1/schedules/{id}</c>: the fields given replace the stored ones (<see cref="Parameters"/> as a whole). A
|
||||
/// system schedule keeps its name and action.
|
||||
/// </summary>
|
||||
public sealed record UpdateScheduleRequest(
|
||||
string? Name = null,
|
||||
string? Action = null,
|
||||
RecurrenceDto? Recurrence = null,
|
||||
ScheduleParametersDto? Parameters = null,
|
||||
bool? CatchUp = null,
|
||||
string? Priority = null,
|
||||
bool? Enabled = null);
|
||||
|
||||
/// <summary><c>POST /api/v1/schedules/{id}/run</c>: what running the schedule now did, and the schedule afterwards.</summary>
|
||||
public sealed record ScheduleRunDto(ScheduleDto Schedule, string Outcome, Guid? JobId);
|
||||
@@ -223,9 +223,24 @@ svg.chart .label { fill: var(--text-muted); }
|
||||
.table.nodes.fit-1 .col-owner, .table.nodes.fit-1 .col-heartbeat { display: none; }
|
||||
.table.audit.fit-1 { grid-template-columns: max-content minmax(70px, .8fr) minmax(90px, max-content) minmax(100px, 2fr); }
|
||||
.table.audit.fit-1 .col-from { display: none; }
|
||||
/* Scheduled jobs (owner review 2, R10): name, action, when, next run, last result, switch, actions. */
|
||||
.table.schedules { grid-template-columns: minmax(130px, 1.3fr) minmax(80px, max-content) minmax(110px, 1fr) max-content minmax(90px, max-content) max-content max-content; }
|
||||
.table.schedules.fit-1 { grid-template-columns: minmax(130px, 1.3fr) minmax(110px, 1fr) max-content minmax(90px, max-content) max-content max-content; }
|
||||
.table.schedules.fit-1 .col-action { display: none; }
|
||||
.table.schedules.fit-2 { grid-template-columns: minmax(120px, 1.3fr) minmax(100px, 1fr) max-content max-content max-content; }
|
||||
.table.schedules.fit-2 .col-last { display: none; }
|
||||
.table-foot { display: flex; align-items: center; gap: 16px; padding: 10px 18px; font-size: 12px; }
|
||||
.table-foot a { white-space: nowrap; }
|
||||
.row-actions { display: flex; gap: 6px; justify-content: flex-end; }
|
||||
/* A name with a pill after it (a system schedule, a job a schedule queued). */
|
||||
.name-cell { display: flex; align-items: center; gap: 8px; min-width: 0; }
|
||||
.pill { flex: none; display: inline-flex; align-items: center; height: 20px; padding: 0 8px; border: 1px solid var(--stroke); border-radius: 12px; font-size: 11px; color: var(--text-muted); white-space: nowrap; text-decoration: none; }
|
||||
a.pill:hover { border-color: var(--accent); color: var(--accent); }
|
||||
/* The runs of a schedule, under its row: kind, state, time and a link to the job. */
|
||||
.runs { display: grid; grid-template-columns: minmax(0, max-content) max-content max-content max-content; gap: 6px 18px; align-items: center; padding: 10px 18px; background: var(--bg); border-top: 1px solid var(--stroke); }
|
||||
.runs .run { display: contents; }
|
||||
.runs .more { grid-column: 1 / -1; justify-self: start; }
|
||||
.table .row.log-row .empty { background: var(--bg); border-top: 1px solid var(--stroke); }
|
||||
.person { display: flex; align-items: center; gap: 10px; min-width: 0; }
|
||||
.stack { display: flex; flex-direction: column; min-width: 0; }
|
||||
.stack small { font-size: 11px; color: var(--text-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
@@ -253,6 +268,11 @@ pre.log.tall { max-height: 60vh; border-top: 0; }
|
||||
.form legend { color: var(--text-muted); margin-bottom: 8px; padding: 0; }
|
||||
.form h2 { font-size: 16px; }
|
||||
.inline { display: flex; align-items: center; gap: 8px; }
|
||||
.form-group { display: grid; gap: 12px; }
|
||||
.form-group:empty { display: none; }
|
||||
.days { display: flex; flex-wrap: wrap; gap: 8px 14px; }
|
||||
/* Each tab of a page draws into its own body; its children lay out as the page's own. */
|
||||
.tab-body { display: contents; }
|
||||
.buttons { display: flex; gap: 8px; justify-content: flex-end; }
|
||||
.error { color: var(--error); min-height: 18px; }
|
||||
.settings { display: grid; gap: 20px; }
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
// Audit entries as the dashboard and the Logs page show them: server codes (actions, job kinds, roles, changed
|
||||
// fields) in words; names, titles and templates stay as recorded.
|
||||
// fields, schedule recurrences) in words, system schedules by their names in the panel's language; other names, titles
|
||||
// and templates stay as recorded.
|
||||
import { t, has, plural } from "./i18n.js";
|
||||
import { formatBytes } from "./ui.js";
|
||||
import { kindLabel, pascal } from "./jobs.js";
|
||||
import { actionLabel as scheduleAction, outcomeLabel, scheduleName, recurrenceText, parseRecurrence } from "./schedules.js";
|
||||
|
||||
const SYSTEM = "system:";
|
||||
|
||||
export function actionLabel(action) {
|
||||
const key = `Admin.Logs.Action.${pascal(action)}`;
|
||||
@@ -35,6 +39,28 @@ export function detailText(entry) {
|
||||
case "user_updated":
|
||||
case "sequence_updated":
|
||||
return details.split(", ").map(changeLabel).join(", ");
|
||||
case "schedule_run": {
|
||||
// "[system:<key> · ]name · outcome"
|
||||
const parts = details.split(" · ");
|
||||
if (parts.length < 2) return details;
|
||||
const outcome = parts.pop();
|
||||
return `${scheduleNameIn(parts)} · ${outcomeLabel(outcome)}`;
|
||||
}
|
||||
case "schedule_created":
|
||||
case "schedule_updated":
|
||||
case "schedule_deleted":
|
||||
case "schedule_reset": {
|
||||
// "[system:<key> · ]name · action · recurrence[ · off]", read from the end: a name may hold the separator.
|
||||
const parts = details.split(" · ");
|
||||
const off = parts.at(-1) === "off";
|
||||
if (off) parts.pop();
|
||||
if (parts.length < 3) return details;
|
||||
const code = parts.pop();
|
||||
const action = parts.pop();
|
||||
const recurrence = parseRecurrence(code);
|
||||
const shown = [scheduleNameIn(parts), scheduleAction(action), recurrence ? recurrenceText(recurrence) : code];
|
||||
return (off ? [...shown, t("Admin.Schedules.Off")] : shown).join(" · ");
|
||||
}
|
||||
default:
|
||||
return details;
|
||||
}
|
||||
@@ -53,6 +79,15 @@ function changeLabel(change) {
|
||||
return has(key) ? t(key) : change;
|
||||
}
|
||||
|
||||
/**
|
||||
* A schedule's name from the leading parts of audit details: after "system:<key>" a system schedule's in the panel's
|
||||
* language, as the Scheduled tab names it; else (a user's, or one recorded before keys were) as recorded.
|
||||
*/
|
||||
function scheduleNameIn(parts) {
|
||||
const systemKey = parts.length > 1 && parts[0].startsWith(SYSTEM) ? parts[0].slice(SYSTEM.length) : null;
|
||||
return scheduleName({ systemKey, name: (systemKey ? parts.slice(1) : parts).join(" · ") });
|
||||
}
|
||||
|
||||
function splitLast(details) {
|
||||
const at = details.lastIndexOf(" · ");
|
||||
return at < 0 ? [details] : [details.slice(0, at), details.slice(at + 3)];
|
||||
|
||||
@@ -1,18 +1,60 @@
|
||||
// Jobs (BRIEF §14.8): queue and history with cancel/pause/resume/retry/priority, log tails, render nodes.
|
||||
// Jobs (BRIEF §14.8): two tabs in the header. Queue: queue and history with cancel/pause/resume/retry/priority, log tails,
|
||||
// render nodes; #/jobs?job=<id> opens that job's log. Scheduled (#/jobs?tab=schedules, owner review 2, R10): the server's
|
||||
// schedules, its system ones included (schedules.js).
|
||||
import { t, plural, applyStrings } from "../i18n.js";
|
||||
import { escapeHtml, attr, formatTime, formatDateTime, toast, errorText, confirmDialog, emptyState, redraw, fitColumns } from "../ui.js";
|
||||
import { escapeHtml, attr, formatTime, formatDateTime, toast, errorText, confirmDialog, emptyState, redraw, fitColumns, routeParams } from "../ui.js";
|
||||
import { kindLabel, nodeLabel, progressCell, stateCell, stateLabel, encoders, logText } from "../jobs.js";
|
||||
import { renderSchedules } from "../schedules.js";
|
||||
|
||||
const TABS = ["queue", "schedules"];
|
||||
const FILTERS = ["all", "running", "queued", "paused", "failed", "done", "cancelled"];
|
||||
const PRIORITIES = ["background", "normal", "user"];
|
||||
|
||||
export async function render(root, { api, setMeta, onEvent }) {
|
||||
export async function render(root, context) {
|
||||
const { actions, onEvent } = context;
|
||||
let tab = TABS.includes(routeParams().get("tab")) ? routeParams().get("tab") : "queue";
|
||||
// The open tab's event handler: the page subscribes once, a tab that was left hears nothing more.
|
||||
let handler = null;
|
||||
onEvent((e) => handler?.(e));
|
||||
|
||||
actions.innerHTML = `<div class="segmented" role="group" aria-label="${attr(t("Admin.Nav.Jobs"))}">${TABS.map((name) =>
|
||||
`<button class="btn" data-tab="${name}" aria-pressed="${name === tab}" data-i18n="Admin.Jobs.Tab.${cap(name)}" data-i18n-title="Admin.Jobs.Tab.${cap(name)}.Tip"></button>`).join("")}</div>
|
||||
<span class="actions" id="tab-actions"></span>`;
|
||||
applyStrings(actions);
|
||||
const tabActions = actions.querySelector("#tab-actions");
|
||||
actions.querySelectorAll("[data-tab]").forEach((b) => b.addEventListener("click", () => {
|
||||
if (b.dataset.tab === tab) return;
|
||||
tab = b.dataset.tab;
|
||||
actions.querySelectorAll("[data-tab]").forEach((x) => x.setAttribute("aria-pressed", String(x === b)));
|
||||
history.replaceState(null, "", tab === "queue" ? "#/jobs" : "#/jobs?tab=schedules");
|
||||
show();
|
||||
}));
|
||||
|
||||
async function show() {
|
||||
handler = null;
|
||||
tabActions.innerHTML = "";
|
||||
// Each tab draws into a body of its own, so a late answer of the tab that was left never touches the new one.
|
||||
root.innerHTML = `<div class="tab-body"></div>`;
|
||||
const body = root.firstElementChild;
|
||||
const scoped = { ...context, actions: tabActions, onEvent: (fn) => { handler = fn; } };
|
||||
if (tab === "queue") await renderQueue(body, scoped, routeParams().get("job"));
|
||||
else await renderSchedules(body, scoped, routeParams().get("schedule"));
|
||||
}
|
||||
|
||||
await show();
|
||||
}
|
||||
|
||||
/** The Queue tab; <paramref name="focusJob"/> (a job id from a schedule's runs) is shown first with its log open. */
|
||||
async function renderQueue(root, { api, setMeta, onEvent }, focusJob) {
|
||||
let filter = "all";
|
||||
let jobs = [];
|
||||
let nodes = [];
|
||||
let running = 0;
|
||||
let cursor = null;
|
||||
const expanded = new Set();
|
||||
// The job a schedule's run links to stays first while the list does not hold it; it gets the focus once.
|
||||
const pinId = focusJob;
|
||||
let pinned = null;
|
||||
const expanded = new Set(pinId ? [pinId] : []);
|
||||
let timer = null;
|
||||
|
||||
root.innerHTML = `
|
||||
@@ -47,6 +89,7 @@ export async function render(root, { api, setMeta, onEvent }) {
|
||||
}
|
||||
|
||||
async function load(more = false) {
|
||||
if (!root.isConnected) return;
|
||||
try {
|
||||
const state = filter === "all" ? "" : `&state=${filter}`;
|
||||
const [page, list, active] = await Promise.all([
|
||||
@@ -59,20 +102,29 @@ export async function render(root, { api, setMeta, onEvent }) {
|
||||
cursor = page.nextCursor;
|
||||
nodes = list;
|
||||
running = active.items.length;
|
||||
pinned = pinId && !jobs.some((j) => j.id === pinId) ? await api.get(`/api/v1/jobs/${pinId}`).catch(() => null) : null;
|
||||
} catch (err) {
|
||||
toast(errorText(err), true);
|
||||
return;
|
||||
}
|
||||
if (!root.isConnected) return;
|
||||
setMeta(`${plural("Admin.Jobs.RunningCount", running)} · ${plural("Admin.Jobs.NodesOnline", nodes.filter((n) => n.state !== "offline").length)}`);
|
||||
draw();
|
||||
if (focusJob) {
|
||||
root.querySelector(`[data-toggle="${CSS.escape(focusJob)}"]`)?.focus();
|
||||
root.querySelector(`[data-key="${CSS.escape(focusJob)}"]`)?.scrollIntoView({ block: "center" });
|
||||
focusJob = null;
|
||||
}
|
||||
}
|
||||
|
||||
function draw() {
|
||||
const host = root.querySelector("#rows");
|
||||
const shown = pinned ? [pinned, ...jobs] : jobs;
|
||||
redraw(host, () => {
|
||||
host.innerHTML = jobs.map((j) => `
|
||||
host.innerHTML = shown.map((j) => `
|
||||
<div class="row" role="row" data-key="${attr(j.id)}">
|
||||
<span role="cell"><button class="link ellipsis" data-toggle="${attr(j.id)}" aria-expanded="${expanded.has(j.id)}" aria-controls="log-${attr(j.id)}" data-i18n-title="Admin.Jobs.Log.Tip">${escapeHtml(kindLabel(j.kind))}</button></span>
|
||||
<span class="name-cell" role="cell"><button class="link ellipsis" data-toggle="${attr(j.id)}" aria-expanded="${expanded.has(j.id)}" aria-controls="log-${attr(j.id)}" data-i18n-title="Admin.Jobs.Log.Tip">${escapeHtml(kindLabel(j.kind))}</button>${j.scheduleId
|
||||
? `<a class="pill" href="#/jobs?tab=schedules&schedule=${attr(j.scheduleId)}" data-i18n="Admin.Jobs.Scheduled" data-i18n-title="Admin.Jobs.Scheduled.Tip"></a>` : ""}</span>
|
||||
<span class="ellipsis" role="cell" dir="auto" title="${attr(j.targetLabel ?? "")}">${escapeHtml(j.targetLabel ?? "")}</span>
|
||||
<span class="col-node ellipsis" role="cell" dir="auto">${escapeHtml(nodeLabel(j, nodes))}</span>
|
||||
<span class="progress" role="cell">${progressCell(j)}</span>
|
||||
@@ -175,7 +227,7 @@ export async function render(root, { api, setMeta, onEvent }) {
|
||||
|
||||
onEvent((e) => {
|
||||
if (e.type === "jobProgress") {
|
||||
const job = jobs.find((j) => j.id === e.jobId);
|
||||
const job = jobs.find((j) => j.id === e.jobId) ?? (pinned?.id === e.jobId ? pinned : null);
|
||||
if (job) {
|
||||
job.progressDone = e.done;
|
||||
job.progressTotal = e.total;
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
// Settings (BRIEF §14.8): server name, ports, TLS, discovery, jobs, limits, language, retention. Values fixed by environment
|
||||
// variables are read-only here; ports, TLS, chunk size and job history apply at the next restart. Jobs run one at a time
|
||||
// (owner review 1): the parallelism (photos at once) and the priority queue apply at once. About (version, API, database,
|
||||
// uptime) is the last group, read-only (owner review 2); #/about opens here on it.
|
||||
// Settings (BRIEF §14.8): server name, ports, TLS, discovery, jobs, limits, language, retention, logs. Values fixed by
|
||||
// environment variables are read-only here; ports, TLS and chunk size apply at the next restart. How long job history is
|
||||
// kept is a parameter of the Job history clean-up schedule (Jobs › Scheduled, owner review 2, R10); Keep audit shows the
|
||||
// Audit log clean-up schedule's age limit (0 while it is off), and saving a new one sets it. Jobs run one at a time
|
||||
// (owner review 1): the parallelism (photos at once) and the priority queue apply at once, as do the log levels,
|
||||
// retention, size limits and rotation (owner review 2, R11). About (version, API, database, uptime) is the last group,
|
||||
// read-only (owner review 2); #/about opens here on it.
|
||||
import { t, applyStrings, languages } from "../i18n.js";
|
||||
import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, formatDuration, markInvalid, clearInvalid, invalidText, escapeReverts, routeParams, PROXY_WARNING } from "../ui.js";
|
||||
import { kindLabel } from "../jobs.js";
|
||||
|
||||
/** Setting → environment variable that can fix it (BRIEF §14.9). */
|
||||
const VARIABLES = {
|
||||
serverName: "CHRONOS_SERVER_NAME", httpPort: "CHRONOS_HTTP_PORT", httpsPort: "CHRONOS_HTTPS_PORT", tlsMode: "CHRONOS_TLS_MODE",
|
||||
tlsCert: "CHRONOS_TLS_CERT", tlsKey: "CHRONOS_TLS_KEY", language: "CHRONOS_LANG", parallelism: "CHRONOS_PARALLELISM", discovery: "CHRONOS_DISCOVERY",
|
||||
priorityQueue: "CHRONOS_PRIORITY_QUEUE",
|
||||
};
|
||||
/** Levels of the priority queue, highest first. */
|
||||
const LEVELS = ["high", "normal", "low"];
|
||||
/** Log levels, least severe first (the server's wire names). */
|
||||
const LOG_LEVELS = ["trace", "debug", "information", "warning", "error", "critical", "none"];
|
||||
const ROTATIONS = ["daily", "hourly"];
|
||||
/** Settings the server names in error details whose field here has another name. */
|
||||
const FIELDS = { maxuploadbytes: "maxUploadMb", chunksizebytes: "chunkSizeMib" };
|
||||
const PEM_FILES = ["tlsCert", "tlsKey"];
|
||||
@@ -37,11 +37,19 @@ export async function render(root, { api, info, setMeta, actions }) {
|
||||
actions.innerHTML = `<button class="btn primary" type="submit" form="settings-form" data-i18n="Admin.Common.Save" data-i18n-title="Admin.Common.Save.Tip"></button>`;
|
||||
applyStrings(actions);
|
||||
|
||||
const locked = (name) => settings.locked.some((l) => l.toLowerCase() === name.toLowerCase());
|
||||
const lock = (name) => locked(name) ? `disabled title="${attr(t("Admin.Settings.Locked.Tip", VARIABLES[name] ?? name))}"` : `data-i18n-title="Admin.Settings.${cap(name)}.Tip"`;
|
||||
const same = (a, b) => a.toLowerCase() === b.toLowerCase();
|
||||
const locked = (name) => settings.locked.some((l) => same(l, name));
|
||||
// The server names the variable that fixes each locked setting: CHRONOS_LOG_LEVEL fixes the console's level too, unless
|
||||
// CHRONOS_LOG_CONSOLE_LEVEL sets its own (BRIEF §14.9).
|
||||
const variable = (name) => Object.entries(settings.lockedBy ?? {}).find(([setting]) => same(setting, name))?.[1] ?? name;
|
||||
const lock = (name) => locked(name) ? `disabled title="${attr(t("Admin.Settings.Locked.Tip", variable(name)))}"` : `data-i18n-title="Admin.Settings.${cap(name)}.Tip"`;
|
||||
const field = (name, input) => `<label class="field"><span data-i18n="Admin.Settings.${cap(name)}"></span>${input}</label>`;
|
||||
const number = (name, value, attrs = "") => field(name, `<input class="input narrow num" type="number" name="${name}" value="${attr(value)}" ${attrs} ${lock(name)}>`);
|
||||
const text = (name, value, attrs = "dir=\"auto\"") => field(name, `<input class="input" name="${name}" value="${attr(value ?? "")}" ${attrs} ${lock(name)}>`);
|
||||
// A value this page does not know stays listed, so saving the other settings never changes it.
|
||||
const choice = (name, value, values, label) => field(name, `<select class="input" name="${name}" ${lock(name)}>${values.concat(values.includes(value) ? [] : [value])
|
||||
.map((v) => `<option value="${attr(v)}" ${v === value ? "selected" : ""}>${escapeHtml(t(label(v)))}</option>`).join("")}</select>`);
|
||||
const level = (name, value) => choice(name, value, LOG_LEVELS, (l) => `Admin.Settings.Level.${cap(l)}`);
|
||||
|
||||
function draw() {
|
||||
root.innerHTML = `
|
||||
@@ -81,7 +89,17 @@ export async function render(root, { api, info, setMeta, actions }) {
|
||||
${number("chunkSizeMib", settings.chunkSizeBytes / MIB, 'min="0.0625" max="64" step="0.0625"')}
|
||||
${number("tokenLifetimeDays", settings.tokenLifetimeDays, 'min="1" max="365"')}
|
||||
${number("uploadRetentionHours", settings.uploadRetentionHours, 'min="1" max="8760"')}
|
||||
${number("jobHistoryDays", settings.jobHistoryDays, 'min="1" max="3650"')}
|
||||
</section>
|
||||
<section class="panel" aria-labelledby="logs-title">
|
||||
<h2 id="logs-title" data-i18n="Admin.Settings.Logs"></h2>
|
||||
${level("logLevel", settings.logs.fileLevel)}
|
||||
${level("consoleLogLevel", settings.logs.consoleLevel)}
|
||||
${number("logRetentionDays", settings.logs.retentionDays, 'min="1" max="3650"')}
|
||||
${number("logMaxFileMb", settings.logs.maxFileMb, 'min="0" max="10240"')}
|
||||
${number("logMaxTotalMb", settings.logs.maxTotalMb, 'min="0" max="1048576"')}
|
||||
${choice("logRotation", settings.logs.rotation, ROTATIONS, (r) => `Admin.Settings.Rotation.${cap(r)}`)}
|
||||
${number("auditRetentionDays", settings.logs.auditRetentionDays, 'min="0" max="3650"')}
|
||||
${number("diagnosticsLogMb", settings.logs.diagnosticsLogMb, 'min="1" max="1024"')}
|
||||
</section>
|
||||
</form>
|
||||
${about()}`;
|
||||
@@ -156,7 +174,16 @@ export async function render(root, { api, info, setMeta, actions }) {
|
||||
chunkSizeBytes: Math.round(Number(data.get("chunkSizeMib")) * MIB),
|
||||
tokenLifetimeDays: Number(data.get("tokenLifetimeDays")),
|
||||
uploadRetentionHours: Number(data.get("uploadRetentionHours")),
|
||||
jobHistoryDays: Number(data.get("jobHistoryDays")),
|
||||
logs: {
|
||||
fileLevel: String(value("logLevel", settings.logs.fileLevel)),
|
||||
consoleLevel: String(value("consoleLogLevel", settings.logs.consoleLevel)),
|
||||
retentionDays: Number(value("logRetentionDays", settings.logs.retentionDays)),
|
||||
maxFileMb: Number(value("logMaxFileMb", settings.logs.maxFileMb)),
|
||||
maxTotalMb: Number(value("logMaxTotalMb", settings.logs.maxTotalMb)),
|
||||
rotation: String(value("logRotation", settings.logs.rotation)),
|
||||
auditRetentionDays: Number(value("auditRetentionDays", settings.logs.auditRetentionDays)),
|
||||
diagnosticsLogMb: Number(value("diagnosticsLogMb", settings.logs.diagnosticsLogMb)),
|
||||
},
|
||||
};
|
||||
try {
|
||||
settings = await api.put("/api/v1/server/settings", request);
|
||||
|
||||
@@ -0,0 +1,623 @@
|
||||
// Scheduled jobs (owner review 2, R10): the Scheduled tab of the Jobs page (#/jobs?tab=schedules). Every schedule of the
|
||||
// server, its system schedules first (the timers it runs, shown so nothing runs out of sight), with when it runs, its next
|
||||
// run, its last result (every time in the server's time zone) and a switch; Run now, Edit, Delete (user schedules) and Reset
|
||||
// (system schedules). A schedule's name opens its last runs, each linking to its job on the Queue tab. A side panel
|
||||
// creates and edits schedules: the action (those the server cannot run are disabled, their reason in the tooltip), the
|
||||
// recurrence, the action's parameters, priority, catch-up and the switch.
|
||||
import { t, plural, has, applyStrings, culture } from "./i18n.js";
|
||||
import { escapeHtml, attr, formatNumber, toast, errorText, confirmDialog, emptyState, redraw, focusPlace, restoreFocus, fitColumns,
|
||||
markInvalid, clearInvalid, invalidText } from "./ui.js";
|
||||
import { kindLabel, pascal, stateCell } from "./jobs.js";
|
||||
|
||||
const KINDS = ["every", "daily", "weekly", "monthly"];
|
||||
const UNITS = ["minutes", "hours", "days"];
|
||||
/** The unit letters of an interval's server code (every:10m). */
|
||||
const UNIT_CODES = { m: "minutes", h: "hours", d: "days" };
|
||||
/** Day names of the API, Monday first; 1 January 2001 was a Monday. */
|
||||
const DAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
|
||||
const PRIORITIES = ["background", "normal", "user"];
|
||||
/** The parameters each action reads (ScheduleActions.Normalize), in the order the form shows them. */
|
||||
const PARAMETERS = {
|
||||
scan: ["force", "deep"], verify: ["olderThanDays", "percent"], thumbnails: ["force"], proxies: ["force"], analysis: ["deep"],
|
||||
maintenance: ["dryRun"], backup: ["keep"], cleanup: ["steps", "olderThanDays"], duplicates: [], orphans: [],
|
||||
};
|
||||
/** What a new schedule of an action starts with (ScheduleActions.Defaults); absent values are false or off. */
|
||||
const DEFAULTS = { verify: { olderThanDays: 30, percent: 100 }, backup: { keep: 3 }, cleanup: { steps: ["job-history"], olderThanDays: 90 } };
|
||||
/** A parameter's label and tooltip by action, under Admin.Schedules.Param. */
|
||||
const PARAM_KEYS = {
|
||||
"scan.force": "FullScan", "scan.deep": "DeepAfterScan", "thumbnails.force": "MakeAgain", "proxies.force": "MakeAgain", "analysis.deep": "Deep",
|
||||
"verify.olderThanDays": "UncheckedDays", "verify.percent": "Percent", "maintenance.dryRun": "DryRun", "backup.keep": "Keep",
|
||||
"cleanup.steps": "Steps", "cleanup.olderThanDays": "OlderDays",
|
||||
};
|
||||
const NUMBERS = { olderThanDays: 'min="0" max="3650"', percent: 'min="1" max="100"', keep: 'min="1" max="100"' };
|
||||
/**
|
||||
* Settings an environment variable fixes for a system schedule's age limit (ServerScheduleHost.LockedAgeOf): the setting,
|
||||
* its variable and the steps the limit deletes with (ServerScheduleHost.AgedSteps).
|
||||
*/
|
||||
const LOCKED_AGES = { "audit-cleanup": { setting: "AuditRetentionDays", variable: "CHRONOS_AUDIT_RETENTION_DAYS", steps: ["audit"] } };
|
||||
|
||||
/** A schedule's name: a system schedule's in the panel's language (by its key), a user's as typed. */
|
||||
export function scheduleName(schedule) {
|
||||
const key = schedule.systemKey ? `Admin.Schedules.System.${pascal(schedule.systemKey)}` : null;
|
||||
return key && has(key) ? t(key) : schedule.name;
|
||||
}
|
||||
|
||||
export function actionLabel(action) {
|
||||
const key = `Admin.Schedules.Action.${pascal(action)}`;
|
||||
return has(key) ? t(key) : action;
|
||||
}
|
||||
|
||||
/** "Queued", "Skipped: busy", "Failed"… for an outcome code (failed:<reason> included). */
|
||||
export function outcomeLabel(outcome) {
|
||||
if (String(outcome).startsWith("failed:")) return t("Admin.Schedules.Outcome.Failed");
|
||||
const key = `Admin.Schedules.Outcome.${pascal(outcome ?? "")}`;
|
||||
return has(key) ? t(key) : String(outcome ?? "");
|
||||
}
|
||||
|
||||
/** What an outcome means, as one sentence (a failure with its reason). */
|
||||
export function outcomeTip(outcome) {
|
||||
const text = String(outcome ?? "");
|
||||
if (text.startsWith("failed:")) return t("Admin.Schedules.Outcome.Failed.Tip", text.slice("failed:".length));
|
||||
const key = `Admin.Schedules.Outcome.${pascal(text)}.Tip`;
|
||||
return has(key) ? t(key) : text;
|
||||
}
|
||||
|
||||
/** "Every 10 minutes", "Daily at 03:00", "Mon, Thu at 02:30", "Day 1 of each month at 04:00" in the panel's language. */
|
||||
export function recurrenceText(r) {
|
||||
switch (r?.kind) {
|
||||
case "every": return UNITS.includes(r.unit) ? plural(`Admin.Schedules.Every.${cap(r.unit)}`, r.every) : `${r.every} ${r.unit}`;
|
||||
case "daily": return t("Admin.Schedules.DailyAt", timeText(r.time));
|
||||
case "weekly": return t("Admin.Schedules.WeeklyAt", dayList(r.days ?? []), timeText(r.time));
|
||||
case "monthly": return t("Admin.Schedules.MonthlyAt", formatNumber(r.dayOfMonth), timeText(r.time));
|
||||
default: return r?.kind ?? "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The recurrence a server code describes (ScheduleRecurrence.Format: every:10m, daily:03:00, weekly:mon,thu@02:30,
|
||||
* monthly:1@04:00), in the API's shape for recurrenceText; null for anything else.
|
||||
*/
|
||||
export function parseRecurrence(code) {
|
||||
const match = /^(every|daily|weekly|monthly):(.+)$/.exec(String(code ?? ""));
|
||||
if (!match) return null;
|
||||
const [, kind, rest] = match;
|
||||
const isTime = (s) => /^\d{2}:\d{2}$/.test(s ?? "");
|
||||
if (kind === "every") {
|
||||
const every = /^(\d+)([mhd])$/.exec(rest);
|
||||
return every ? { kind, every: Number(every[1]), unit: UNIT_CODES[every[2]] } : null;
|
||||
}
|
||||
if (kind === "daily") return isTime(rest) ? { kind, time: rest } : null;
|
||||
const [what, time] = rest.split("@");
|
||||
if (!isTime(time)) return null;
|
||||
if (kind === "weekly") {
|
||||
const days = what.split(",");
|
||||
return days.every((d) => DAYS.includes(d)) ? { kind, days, time } : null;
|
||||
}
|
||||
return /^\d+$/.test(what) ? { kind, dayOfMonth: Number(what), time } : null;
|
||||
}
|
||||
|
||||
export async function renderSchedules(root, { api, setMeta, actions, onEvent }, focusSchedule) {
|
||||
let schedules = [];
|
||||
let available = [];
|
||||
let steps = [];
|
||||
let zone = "UTC";
|
||||
let locked = [];
|
||||
let lastJobs = new Map();
|
||||
const runs = new Map();
|
||||
const expanded = new Set(focusSchedule ? [focusSchedule] : []);
|
||||
let opener = null;
|
||||
let timer = null;
|
||||
|
||||
actions.innerHTML = `<button class="btn primary" id="new" data-i18n="Admin.Schedules.New" data-i18n-title="Admin.Schedules.New.Tip"></button>`;
|
||||
applyStrings(actions);
|
||||
actions.querySelector("#new").addEventListener("click", () => openForm(null));
|
||||
|
||||
root.innerHTML = `
|
||||
<div class="split">
|
||||
<section class="panel flush">
|
||||
<div class="table schedules" data-levels="2" role="table" aria-label="${attr(t("Admin.Jobs.Tab.Schedules"))}">
|
||||
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Schedules.Name"></span><span role="columnheader" class="col-action" data-i18n="Admin.Schedules.Action"></span>
|
||||
<span role="columnheader" data-i18n="Admin.Schedules.When"></span><span role="columnheader" data-i18n="Admin.Schedules.NextRun"></span>
|
||||
<span role="columnheader" class="col-last" data-i18n="Admin.Schedules.LastResult"></span><span role="columnheader" data-i18n="Admin.Schedules.Enabled"></span>
|
||||
<span role="columnheader"><span class="sr-only" data-i18n="Admin.Common.Actions"></span></span></div>
|
||||
<div id="rows" role="rowgroup"></div>
|
||||
</div>
|
||||
</section>
|
||||
<aside class="panel side" id="side" hidden></aside>
|
||||
</div>`;
|
||||
applyStrings(root);
|
||||
const table = root.querySelector(".table");
|
||||
const side = root.querySelector("#side");
|
||||
side.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
closeSide();
|
||||
}
|
||||
});
|
||||
|
||||
async function load() {
|
||||
if (!root.isConnected) return;
|
||||
try {
|
||||
const [list, settings] = await Promise.all([api.get("/api/v1/schedules"), api.get("/api/v1/server/settings").catch(() => null)]);
|
||||
schedules = list.items;
|
||||
available = list.actions;
|
||||
steps = list.steps ?? [];
|
||||
zone = list.timeZone;
|
||||
locked = settings?.locked ?? [];
|
||||
// A schedule deleted meanwhile (here or by another administrator), or the one a job of the Queue tab links to after
|
||||
// its deletion, is simply not shown: its runs are not asked for.
|
||||
for (const id of expanded) {
|
||||
if (!find(id)) forget(id);
|
||||
}
|
||||
if (focusSchedule && !find(focusSchedule)) focusSchedule = null;
|
||||
// The state of each schedule's last job, for the Last result column (a job the history no longer has shows the outcome).
|
||||
const ids = [...new Set(schedules.filter((s) => s.lastJobId && s.lastOutcome === "queued").map((s) => s.lastJobId))];
|
||||
const jobs = await Promise.all(ids.map((id) => api.get(`/api/v1/jobs/${id}`).catch(() => null)));
|
||||
lastJobs = new Map(jobs.filter(Boolean).map((j) => [j.id, j]));
|
||||
// One schedule's runs that cannot be read (deleted since the list) close it; the table is drawn all the same.
|
||||
await Promise.all([...expanded].map((id) => loadRuns(id).catch(() => forget(id))));
|
||||
} catch (err) {
|
||||
toast(errorText(err), true);
|
||||
return;
|
||||
}
|
||||
if (!root.isConnected) return;
|
||||
setMeta(`${plural("Admin.Schedules.Count", schedules.length)} · ${t("Admin.Schedules.TimeZone", zone)}`);
|
||||
draw();
|
||||
if (focusSchedule) {
|
||||
root.querySelector(`[data-key="${CSS.escape(focusSchedule)}"]`)?.scrollIntoView({ block: "center" });
|
||||
root.querySelector(`[data-toggle="${CSS.escape(focusSchedule)}"]`)?.focus();
|
||||
focusSchedule = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The first page of a schedule's runs, or the next one with more. */
|
||||
async function loadRuns(id, more = false) {
|
||||
const known = runs.get(id);
|
||||
const cursor = more && known?.cursor ? `&cursor=${encodeURIComponent(known.cursor)}` : "";
|
||||
const page = await api.get(`/api/v1/schedules/${id}/runs?limit=10${cursor}`);
|
||||
runs.set(id, { items: more && known ? known.items.concat(page.items) : page.items, cursor: page.nextCursor });
|
||||
}
|
||||
|
||||
function draw() {
|
||||
const host = root.querySelector("#rows");
|
||||
redraw(host, () => {
|
||||
host.innerHTML = schedules.map(rowHtml).join("") || `<div class="row" role="row"><div class="wide" role="cell">${emptyState("Admin.Schedules.Empty",
|
||||
`<button class="btn small" id="empty-new" data-i18n="Admin.Schedules.New" data-i18n-title="Admin.Schedules.New.Tip"></button>`)}</div></div>`;
|
||||
applyStrings(host);
|
||||
});
|
||||
host.querySelectorAll("[data-toggle]").forEach((b) => b.addEventListener("click", () => toggle(b.dataset.toggle)));
|
||||
host.querySelectorAll("[data-act]").forEach((b) => b.addEventListener("click", () => act(b.dataset.act, find(b.closest("[data-key]").dataset.key))));
|
||||
host.querySelectorAll("[data-enable]").forEach((box) => box.addEventListener("change", () => setEnabled(find(box.dataset.enable), box)));
|
||||
host.querySelectorAll("[data-more-runs]").forEach((b) => b.addEventListener("click", () => moreRuns(b.dataset.moreRuns)));
|
||||
host.querySelectorAll("[data-run-first]").forEach((b) => b.addEventListener("click", () => act("run", find(b.dataset.runFirst))));
|
||||
host.querySelector("#empty-new")?.addEventListener("click", () => openForm(null));
|
||||
fitColumns(table);
|
||||
}
|
||||
|
||||
function find(id) {
|
||||
return schedules.find((s) => s.id === id);
|
||||
}
|
||||
|
||||
/**
|
||||
* What an environment variable fixes on the system schedule <paramref name="systemKey"/> whose age limit is
|
||||
* <paramref name="days"/> (LOCKED_AGES), with the attributes of its fixed controls; null when nothing is fixed. While the
|
||||
* limit deletes (more than 0 days) its switch and the steps it deletes with are fixed too (ScheduleEndpoints.ChangesLocked).
|
||||
*/
|
||||
function ageLock(systemKey, days) {
|
||||
const age = LOCKED_AGES[systemKey];
|
||||
if (!age || !locked.some((l) => l.toLowerCase() === age.setting.toLowerCase())) return null;
|
||||
return { ...age, deletes: days > 0, attrs: `disabled title="${attr(t("Admin.Settings.Locked.Tip", age.variable))}"` };
|
||||
}
|
||||
|
||||
/** Closes a schedule's runs and drops them. */
|
||||
function forget(id) {
|
||||
expanded.delete(id);
|
||||
runs.delete(id);
|
||||
}
|
||||
|
||||
function rowHtml(s) {
|
||||
const name = scheduleName(s);
|
||||
const button = (act, key, extra = "") => `<button class="btn small${extra}" data-act="${act}" data-i18n="Admin.Schedules.${key}" data-i18n-title="Admin.Schedules.${key}.Tip"></button>`;
|
||||
const buttons = button("run", "Run") + button("edit", "Edit") + (s.systemKey ? button("reset", "Reset") : button("delete", "Delete", " destructive"));
|
||||
const when = recurrenceText(s.recurrence);
|
||||
const lock = ageLock(s.systemKey, s.parameters?.olderThanDays ?? 0);
|
||||
return `
|
||||
<div class="row${s.enabled ? "" : " dim"}" role="row" data-key="${attr(s.id)}">
|
||||
<span class="name-cell" role="cell"><button class="link ellipsis" data-toggle="${attr(s.id)}" aria-expanded="${expanded.has(s.id)}" aria-controls="runs-${attr(s.id)}"
|
||||
dir="auto" data-i18n-title="Admin.Schedules.Runs.Tip">${escapeHtml(name)}</button>${s.systemKey
|
||||
? `<span class="pill" data-i18n="Admin.Schedules.System" data-i18n-title="Admin.Schedules.System.Tip"></span>` : ""}</span>
|
||||
<span class="col-action ellipsis" role="cell" title="${attr(actionTip(s.action))}">${escapeHtml(actionLabel(s.action))}</span>
|
||||
<span class="ellipsis" role="cell" title="${attr(t("Admin.Schedules.When.Tip", zone))}">${escapeHtml(when)}</span>
|
||||
<span class="num nowrap" role="cell" title="${attr(t("Admin.Schedules.NextRun.Tip", zone))}">${escapeHtml(s.enabled ? zonedTime(s.nextRun, zone) : t("Admin.Schedules.Off"))}</span>
|
||||
<span class="col-last ellipsis" role="cell">${lastResult(s)}</span>
|
||||
<span role="cell"><input type="checkbox" role="switch" data-enable="${attr(s.id)}" ${s.enabled ? "checked" : ""}
|
||||
aria-label="${attr(t("Admin.Schedules.EnabledFor", name))}" ${lock?.deletes ? lock.attrs : `title="${attr(t("Admin.Schedules.Enabled.Tip"))}"`}></span>
|
||||
<span class="row-actions" role="cell">${buttons}</span>
|
||||
</div>
|
||||
${expanded.has(s.id) ? `<div class="row log-row" role="row"><div class="wide" role="cell" id="runs-${attr(s.id)}">${runsHtml(s)}</div></div>` : ""}`;
|
||||
}
|
||||
|
||||
/** The last result: the last job's state when the run queued one, else what the run did; when, in the tooltip's words. */
|
||||
function lastResult(s) {
|
||||
if (!s.lastRun) return `<span class="muted" data-i18n="Admin.Schedules.Never"></span>`;
|
||||
const when = `<span class="muted"> · ${escapeHtml(zonedShort(s.lastRun, zone))}</span>`;
|
||||
const tip = `${outcomeTip(s.lastOutcome)} · ${zonedDateTime(s.lastRun, zone)}`;
|
||||
const job = s.lastOutcome === "queued" ? lastJobs.get(s.lastJobId) : null;
|
||||
if (job) return `<span title="${attr(tip)}">${stateCell(job.state)}${when}</span>`;
|
||||
const failed = String(s.lastOutcome).startsWith("failed:");
|
||||
return `<span class="${failed ? "state failed" : ""}" title="${attr(tip)}">${escapeHtml(outcomeLabel(s.lastOutcome))}${when}</span>`;
|
||||
}
|
||||
|
||||
function runsHtml(s) {
|
||||
const page = runs.get(s.id);
|
||||
if (!page) return "";
|
||||
if (page.items.length === 0) {
|
||||
return emptyState("Admin.Schedules.NoRuns", `<button class="btn small" data-run-first="${attr(s.id)}" data-i18n="Admin.Schedules.Run" data-i18n-title="Admin.Schedules.Run.Tip"></button>`);
|
||||
}
|
||||
return `<div class="runs" role="list" aria-label="${attr(t("Admin.Schedules.RunsOf", scheduleName(s)))}">${page.items.map((j) => `
|
||||
<div class="run" role="listitem"><span class="ellipsis">${escapeHtml(kindLabel(j.kind))}</span><span>${stateCell(j.state)}</span>
|
||||
<span class="muted nowrap num">${escapeHtml(zonedDateTime(j.created, zone))}</span>
|
||||
<a class="btn small" href="#/jobs?job=${attr(j.id)}" data-i18n="Admin.Schedules.OpenJob" data-i18n-title="Admin.Schedules.OpenJob.Tip"></a></div>`).join("")}
|
||||
${page.cursor ? `<button class="btn small more" data-more-runs="${attr(s.id)}" data-i18n="Admin.Common.More" data-i18n-title="Admin.Common.More.Tip"></button>` : ""}</div>`;
|
||||
}
|
||||
|
||||
async function toggle(id) {
|
||||
if (expanded.delete(id)) {
|
||||
draw();
|
||||
return;
|
||||
}
|
||||
expanded.add(id);
|
||||
try {
|
||||
await loadRuns(id);
|
||||
} catch (err) {
|
||||
forget(id);
|
||||
toast(errorText(err), true);
|
||||
}
|
||||
draw();
|
||||
}
|
||||
|
||||
async function moreRuns(id) {
|
||||
try {
|
||||
await loadRuns(id, true);
|
||||
} catch (err) {
|
||||
toast(errorText(err), true);
|
||||
return;
|
||||
}
|
||||
draw();
|
||||
}
|
||||
|
||||
async function act(action, schedule) {
|
||||
if (!schedule) return;
|
||||
try {
|
||||
if (action === "edit") return openForm(schedule);
|
||||
if (action === "run") {
|
||||
const run = await api.post(`/api/v1/schedules/${schedule.id}/run`);
|
||||
toast(outcomeTip(run.outcome), String(run.outcome).startsWith("failed:"));
|
||||
runs.delete(schedule.id);
|
||||
} else if (action === "delete") {
|
||||
const confirmed = await confirmDialog({
|
||||
title: t("Admin.Schedules.DeleteTitle", scheduleName(schedule)),
|
||||
confirm: t("Admin.Schedules.Delete"),
|
||||
confirmTip: t("Admin.Schedules.Delete.Tip"),
|
||||
cancel: t("Admin.Common.Keep"),
|
||||
cancelTip: t("Admin.Common.Keep.Tip"),
|
||||
});
|
||||
if (!confirmed) return;
|
||||
await api.del(`/api/v1/schedules/${schedule.id}`);
|
||||
forget(schedule.id);
|
||||
} else if (action === "reset") {
|
||||
const confirmed = await confirmDialog({
|
||||
title: t("Admin.Schedules.ResetTitle", scheduleName(schedule)),
|
||||
confirm: t("Admin.Schedules.Reset"),
|
||||
confirmTip: t("Admin.Schedules.Reset.Tip"),
|
||||
cancel: t("Admin.Common.Keep"),
|
||||
cancelTip: t("Admin.Common.Keep.Tip"),
|
||||
});
|
||||
if (!confirmed) return;
|
||||
await api.post(`/api/v1/schedules/${schedule.id}/reset`);
|
||||
}
|
||||
await load();
|
||||
} catch (err) {
|
||||
toast(errorText(err), true);
|
||||
}
|
||||
}
|
||||
|
||||
async function setEnabled(schedule, box) {
|
||||
try {
|
||||
await api.put(`/api/v1/schedules/${schedule.id}`, { enabled: box.checked });
|
||||
await load();
|
||||
} catch (err) {
|
||||
box.checked = !box.checked;
|
||||
toast(errorText(err), true);
|
||||
}
|
||||
}
|
||||
|
||||
/** Shows the side panel, remembering which control opened it so closing returns the keyboard there. */
|
||||
function openSide(html) {
|
||||
if (side.hidden) {
|
||||
const scope = actions.contains(document.activeElement) ? actions : root;
|
||||
opener = { scope, place: focusPlace(scope) };
|
||||
}
|
||||
side.hidden = false;
|
||||
side.innerHTML = html;
|
||||
applyStrings(side);
|
||||
fitColumns(table);
|
||||
side.querySelector("#close").addEventListener("click", closeSide);
|
||||
}
|
||||
|
||||
function closeSide() {
|
||||
side.hidden = true;
|
||||
side.innerHTML = "";
|
||||
fitColumns(table);
|
||||
if (opener) restoreFocus(opener.scope, opener.place);
|
||||
opener = null;
|
||||
}
|
||||
|
||||
function openForm(schedule) {
|
||||
const editing = schedule !== null;
|
||||
const system = editing && Boolean(schedule.systemKey);
|
||||
const first = available.find((a) => a.available)?.name ?? "scan";
|
||||
const draft = { recurrence: { every: 1, unit: "hours", time: "03:00", days: ["mon"], dayOfMonth: 1, ...(schedule?.recurrence ?? { kind: "daily" }) } };
|
||||
const fixed = `disabled title="${attr(t("Admin.Schedules.Fixed.Tip"))}"`;
|
||||
const lock = editing ? ageLock(schedule.systemKey, schedule.parameters?.olderThanDays ?? 0) : null;
|
||||
const actionOptions = (editing && !available.some((a) => a.name === schedule.action) ? [{ name: schedule.action, available: false }] : available).map((a) =>
|
||||
`<option value="${attr(a.name)}" ${a.name === (schedule?.action ?? first) ? "selected" : ""} ${a.available || a.name === schedule?.action ? "" : "disabled"}
|
||||
title="${attr(a.available ? actionTip(a.name) : reasonTip(a.reason))}">${escapeHtml(actionLabel(a.name))}</option>`).join("");
|
||||
openSide(`
|
||||
<form class="form" novalidate>
|
||||
<h2 data-i18n="${editing ? "Admin.Schedules.EditTitle" : "Admin.Schedules.New"}"></h2>
|
||||
<label><span data-i18n="Admin.Schedules.Name"></span>
|
||||
<input class="input" name="name" required maxlength="100" autocomplete="off" dir="auto" value="${attr(editing ? scheduleName(schedule) : "")}" ${system ? fixed : `data-i18n-title="Admin.Schedules.Name.Tip"`}></label>
|
||||
<label><span data-i18n="Admin.Schedules.Action"></span>
|
||||
<select class="input" name="action" ${system ? fixed : `data-i18n-title="Admin.Schedules.Action.Tip"`}>${actionOptions}</select></label>
|
||||
<label><span data-i18n="Admin.Schedules.Repeat"></span>
|
||||
<select class="input" name="kind" data-i18n-title="Admin.Schedules.Repeat.Tip">${KINDS.map((k) =>
|
||||
`<option value="${k}" ${k === draft.recurrence.kind ? "selected" : ""}>${escapeHtml(t(`Admin.Schedules.Kind.${cap(k)}`))}</option>`).join("")}</select></label>
|
||||
<div class="form-group" id="recurrence"></div>
|
||||
<div class="form-group" id="parameters"></div>
|
||||
<label><span data-i18n="Admin.Schedules.Priority"></span>
|
||||
<select class="input" name="priority" data-i18n-title="Admin.Schedules.Priority.Tip">${PRIORITIES.map((p) =>
|
||||
`<option value="${p}" ${p === (schedule?.priority ?? "background") ? "selected" : ""}>${escapeHtml(t(`Admin.Jobs.Priority.${cap(p)}`))}</option>`).join("")}</select></label>
|
||||
<label class="check"><input type="checkbox" name="catchUp" ${schedule?.catchUp ?? true ? "checked" : ""} data-i18n-title="Admin.Schedules.CatchUp.Tip"><span data-i18n="Admin.Schedules.CatchUp"></span></label>
|
||||
<label class="check"><input type="checkbox" name="enabled" ${schedule?.enabled ?? true ? "checked" : ""} ${lock?.deletes ? lock.attrs : `data-i18n-title="Admin.Schedules.Enabled.Tip"`}><span data-i18n="Admin.Schedules.Enabled"></span></label>
|
||||
<div class="buttons">
|
||||
<button class="btn" type="button" id="close" data-i18n="Admin.Common.Cancel" data-i18n-title="Admin.Common.Cancel.Tip"></button>
|
||||
<button class="btn primary" type="submit" data-i18n="${editing ? "Admin.Common.Save" : "Admin.Schedules.Create"}" data-i18n-title="${editing ? "Admin.Common.Save.Tip" : "Admin.Schedules.Create.Tip"}"></button>
|
||||
</div>
|
||||
</form>`);
|
||||
const form = side.querySelector("form");
|
||||
const values = (action) => action === schedule?.action ? schedule.parameters : (DEFAULTS[action] ?? {});
|
||||
drawRecurrence(form, draft.recurrence);
|
||||
drawParameters(form, schedule?.action ?? first, values(schedule?.action ?? first), schedule?.systemKey);
|
||||
form.elements.kind.addEventListener("change", () => {
|
||||
// The fields drawn are still those of the kind chosen before.
|
||||
draft.recurrence = { ...draft.recurrence, ...shownFields(form, draft.recurrence.kind), kind: form.elements.kind.value };
|
||||
drawRecurrence(form, draft.recurrence);
|
||||
});
|
||||
form.elements.action.addEventListener("change", () => drawParameters(form, form.elements.action.value, values(form.elements.action.value), schedule?.systemKey));
|
||||
form.addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
form.querySelectorAll("[aria-invalid]").forEach(clearInvalid);
|
||||
const action = form.elements.action.value;
|
||||
const body = {
|
||||
recurrence: recurrenceOf(form),
|
||||
parameters: parametersOf(form, action),
|
||||
priority: form.elements.priority.value,
|
||||
catchUp: form.elements.catchUp.checked,
|
||||
enabled: form.elements.enabled.checked,
|
||||
};
|
||||
if (!system) Object.assign(body, { name: form.elements.name.value.trim(), action });
|
||||
try {
|
||||
if (editing) await api.put(`/api/v1/schedules/${schedule.id}`, body);
|
||||
else await api.post("/api/v1/schedules", body);
|
||||
closeSide();
|
||||
toast(t("Admin.Common.Saved"));
|
||||
await load();
|
||||
} catch (err) {
|
||||
fieldError(form, err, schedule);
|
||||
}
|
||||
});
|
||||
(form.querySelector("input:not([disabled]), select:not([disabled])"))?.focus();
|
||||
}
|
||||
|
||||
/** The fields of the recurrence's kind, filled from <paramref name="r"/> (values of the other kinds are kept for a switch back). */
|
||||
function drawRecurrence(form, r) {
|
||||
const host = form.querySelector("#recurrence");
|
||||
const time = `<label><span data-i18n="Admin.Schedules.Time"></span>
|
||||
<input class="input narrow num" type="time" name="time" required value="${attr(r.time ?? "03:00")}" title="${attr(t("Admin.Schedules.Time.Tip", zone))}"></label>`;
|
||||
switch (r.kind) {
|
||||
case "every":
|
||||
host.innerHTML = `<label><span data-i18n="Admin.Schedules.Interval"></span><span class="inline">
|
||||
<input class="input narrow num" type="number" name="every" min="1" value="${attr(r.every ?? 1)}" data-i18n-title="Admin.Schedules.Interval.Tip">
|
||||
<select class="input narrow" name="unit" data-i18n-title="Admin.Schedules.Unit.Tip">${UNITS.map((u) =>
|
||||
`<option value="${u}" ${u === r.unit ? "selected" : ""}>${escapeHtml(t(`Admin.Schedules.Unit.${cap(u)}`))}</option>`).join("")}</select></span></label>`;
|
||||
break;
|
||||
case "weekly":
|
||||
host.innerHTML = `<fieldset><legend data-i18n="Admin.Schedules.Days"></legend><div class="days">${DAYS.map((d) => `<label class="check">
|
||||
<input type="checkbox" name="day-${d}" ${(r.days ?? []).includes(d) ? "checked" : ""} title="${attr(t("Admin.Schedules.Day.Tip", dayName(d, "long")))}"><span>${escapeHtml(dayName(d))}</span></label>`).join("")}</div></fieldset>${time}`;
|
||||
break;
|
||||
case "monthly":
|
||||
host.innerHTML = `<label><span data-i18n="Admin.Schedules.DayOfMonth"></span>
|
||||
<input class="input narrow num" type="number" name="dayOfMonth" min="1" max="28" value="${attr(r.dayOfMonth ?? 1)}" data-i18n-title="Admin.Schedules.DayOfMonth.Tip"></label>${time}`;
|
||||
break;
|
||||
default:
|
||||
host.innerHTML = time;
|
||||
}
|
||||
applyStrings(host);
|
||||
}
|
||||
|
||||
/** The parameters <paramref name="action"/> reads, filled from <paramref name="p"/>. */
|
||||
function drawParameters(form, action, p, systemKey) {
|
||||
const host = form.querySelector("#parameters");
|
||||
const lock = ageLock(systemKey, p.olderThanDays ?? 0);
|
||||
host.innerHTML = (PARAMETERS[action] ?? []).map((name) => {
|
||||
const key = `Admin.Schedules.Param.${PARAM_KEYS[`${action}.${name}`]}`;
|
||||
if (name === "steps") {
|
||||
const tip = (step) => lock?.deletes && lock.steps.includes(step) ? lock.attrs : `title="${attr(stepTip(step))}"`;
|
||||
return `<fieldset><legend data-i18n="${key}"></legend>${steps.map((step) => `<label class="check">
|
||||
<input type="checkbox" name="step-${attr(step)}" value="${attr(step)}" ${(p.steps ?? []).includes(step) ? "checked" : ""} ${tip(step)}><span>${escapeHtml(stepLabel(step))}</span></label>`).join("")}</fieldset>`;
|
||||
}
|
||||
if (name in NUMBERS) {
|
||||
const fixed = name === "olderThanDays" && lock ? lock.attrs : `data-i18n-title="${key}.Tip"`;
|
||||
return `<label><span data-i18n="${key}"></span><input class="input narrow num" type="number" name="${name}" ${NUMBERS[name]} value="${attr(p[name] ?? 0)}" ${fixed}></label>`;
|
||||
}
|
||||
return `<label class="check"><input type="checkbox" name="${name}" ${p[name] ? "checked" : ""} data-i18n-title="${key}.Tip"><span data-i18n="${key}"></span></label>`;
|
||||
}).join("");
|
||||
applyStrings(host);
|
||||
}
|
||||
|
||||
/**
|
||||
* An API failure on the side form of <paramref name="schedule"/> (null for a new one): the field it concerns gets the error
|
||||
* border, the message and the focus; a toast announces it.
|
||||
*/
|
||||
function fieldError(form, err, schedule) {
|
||||
const field = err.code === "setting_locked" ? lockedField(form, schedule) : fieldOf(form, err.code === "invalid_schedule" ? err.details : null);
|
||||
const message = field && err.code === "invalid_schedule" ? invalidText(field) : errorText(err);
|
||||
if (field) {
|
||||
markInvalid(field, message);
|
||||
field.focus();
|
||||
}
|
||||
toast(message, true);
|
||||
}
|
||||
|
||||
setMeta("");
|
||||
onEvent((e) => {
|
||||
// A schedule changed or ran (also a run that queued nothing, or an edit by another administrator), or a job it queued
|
||||
// changed state (the Last result column); the burst of one pass is read once.
|
||||
if (e.type === "jobState" || e.type === "scheduleChanged") {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(load, 800);
|
||||
}
|
||||
});
|
||||
await load();
|
||||
}
|
||||
|
||||
/** The recurrence the form describes (RecurrenceDto). */
|
||||
function recurrenceOf(form) {
|
||||
const kind = form.elements.kind.value;
|
||||
return { kind, ...shownFields(form, kind) };
|
||||
}
|
||||
|
||||
/** The values of the recurrence fields the form shows for <paramref name="kind"/>. */
|
||||
function shownFields(form, kind) {
|
||||
const el = form.elements;
|
||||
switch (kind) {
|
||||
case "every": return { every: Number(el.every.value), unit: el.unit.value };
|
||||
case "weekly": return { time: el.time.value, days: DAYS.filter((d) => el[`day-${d}`].checked) };
|
||||
case "monthly": return { time: el.time.value, dayOfMonth: Number(el.dayOfMonth.value) };
|
||||
default: return { time: el.time.value };
|
||||
}
|
||||
}
|
||||
|
||||
/** The parameters of <paramref name="action"/> the form holds (disabled fields included: an age limit an environment variable fixes). */
|
||||
function parametersOf(form, action) {
|
||||
const parameters = {};
|
||||
for (const name of PARAMETERS[action] ?? []) {
|
||||
if (name === "steps") parameters.steps = [...form.querySelectorAll('input[name^="step-"]')].filter((b) => b.checked).map((b) => b.value);
|
||||
else if (name in NUMBERS) parameters[name] = Number(form.elements[name].value);
|
||||
else parameters[name] = form.elements[name].checked;
|
||||
}
|
||||
return parameters;
|
||||
}
|
||||
|
||||
/** The form field an invalid API field (<c>recurrence</c>, <c>parameters.percent</c>…) belongs to. */
|
||||
function fieldOf(form, apiField) {
|
||||
if (!apiField) return null;
|
||||
const el = form.elements;
|
||||
if (apiField === "recurrence") {
|
||||
const kind = el.kind.value;
|
||||
if (kind === "every") return el.every;
|
||||
if (kind === "weekly" && !DAYS.some((d) => el[`day-${d}`].checked)) return el["day-mon"];
|
||||
if (kind === "monthly" && !(Number(el.dayOfMonth.value) >= 1 && Number(el.dayOfMonth.value) <= 28)) return el.dayOfMonth;
|
||||
return el.time;
|
||||
}
|
||||
if (apiField === "parameters.steps") return form.querySelector('input[name^="step-"]');
|
||||
const name = apiField.startsWith("parameters.") ? apiField.slice("parameters.".length) : apiField;
|
||||
return el[name] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The form field a <c>setting_locked</c> refusal concerns, in the server's order (ScheduleEndpoints.ChangesLocked): the
|
||||
* switch turned off while the limit deletes, the age limit changed, a step the limit deletes with unticked; else the age limit.
|
||||
*/
|
||||
function lockedField(form, schedule) {
|
||||
const el = form.elements;
|
||||
const days = schedule?.parameters?.olderThanDays ?? 0;
|
||||
if (days > 0 && !el.enabled.checked) return el.enabled;
|
||||
if (el.olderThanDays && Number(el.olderThanDays.value) !== days) return el.olderThanDays;
|
||||
const step = days > 0 ? (LOCKED_AGES[schedule?.systemKey]?.steps ?? []).map((s) => el[`step-${s}`]).find((box) => box && !box.checked) : null;
|
||||
return step ?? el.olderThanDays ?? null;
|
||||
}
|
||||
|
||||
function actionTip(action) {
|
||||
const key = `Admin.Schedules.Action.${pascal(action)}.Tip`;
|
||||
return has(key) ? t(key) : action;
|
||||
}
|
||||
|
||||
/** Why the server cannot run an action (ScheduleUnavailable codes; unknown codes read "not available here"). */
|
||||
function reasonTip(reason) {
|
||||
const key = `Admin.Schedules.Reason.${pascal(reason ?? "")}.Tip`;
|
||||
return has(key) ? t(key) : t("Admin.Schedules.Reason.Unknown.Tip");
|
||||
}
|
||||
|
||||
function stepLabel(step) {
|
||||
const key = `Admin.Schedules.Step.${pascal(step)}`;
|
||||
return has(key) ? t(key) : step;
|
||||
}
|
||||
|
||||
function stepTip(step) {
|
||||
const key = `Admin.Schedules.Step.${pascal(step)}.Tip`;
|
||||
return has(key) ? t(key) : step;
|
||||
}
|
||||
|
||||
/**
|
||||
* An instant in the server's time zone, as every time of this tab is ("Times in …": schedule times are its wall-clock
|
||||
* times); in the browser's when the zone is unknown here.
|
||||
*/
|
||||
function zoned(iso, zone, options) {
|
||||
const date = new Date(iso);
|
||||
try {
|
||||
return new Intl.DateTimeFormat(culture(), { ...options, timeZone: zone }).format(date);
|
||||
} catch {
|
||||
return new Intl.DateTimeFormat(culture(), options).format(date);
|
||||
}
|
||||
}
|
||||
|
||||
function zonedTime(iso, zone) {
|
||||
return iso ? zoned(iso, zone, { dateStyle: "short", timeStyle: "short" }) : "—";
|
||||
}
|
||||
|
||||
function zonedDateTime(iso, zone) {
|
||||
return iso ? zoned(iso, zone, { dateStyle: "short", timeStyle: "medium" }) : "—";
|
||||
}
|
||||
|
||||
/** Like formatTime in the server's time zone: the time when the instant falls on today there, else the date. */
|
||||
function zonedShort(iso, zone) {
|
||||
if (!iso) return "—";
|
||||
const day = (instant) => zoned(instant, zone, { dateStyle: "short" });
|
||||
return zoned(iso, zone, day(iso) === day(Date.now()) ? { timeStyle: "short" } : { dateStyle: "medium" });
|
||||
}
|
||||
|
||||
/** "03:00" as the panel's language writes a time of day. */
|
||||
function timeText(hhmm) {
|
||||
const [h, m] = String(hhmm ?? "").split(":").map(Number);
|
||||
if (!Number.isFinite(h) || !Number.isFinite(m)) return String(hhmm ?? "");
|
||||
return new Intl.DateTimeFormat(culture(), { timeStyle: "short", timeZone: "UTC" }).format(Date.UTC(2001, 0, 1, h, m));
|
||||
}
|
||||
|
||||
function dayName(day, style = "short") {
|
||||
return new Intl.DateTimeFormat(culture(), { weekday: style, timeZone: "UTC" }).format(Date.UTC(2001, 0, 1 + DAYS.indexOf(day)));
|
||||
}
|
||||
|
||||
function dayList(days) {
|
||||
const names = DAYS.filter((d) => days.includes(d)).map((d) => dayName(d));
|
||||
try {
|
||||
return new Intl.ListFormat(culture(), { style: "short", type: "conjunction" }).format(names);
|
||||
} catch {
|
||||
return names.join(", ");
|
||||
}
|
||||
}
|
||||
|
||||
function cap(s) {
|
||||
return s.charAt(0).toUpperCase() + s.slice(1);
|
||||
}
|
||||
@@ -19,8 +19,8 @@ public static class AdminEndpoints
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
api.MapGet("/server/dashboard", DashboardAsync).Requires(Permissions.ManageArchive | Permissions.ManageUsers);
|
||||
api.MapGet("/server/settings", (HttpContext context, ServerSettingsStore store, ServerOptions options) =>
|
||||
Results.Json(store.Current() with { ProxyWarning = AdminPanel.BypassesProxy(context, options) }, ProtocolJson.Default.ServerSettingsDto))
|
||||
api.MapGet("/server/settings", async (HttpContext context, ServerSettingsStore store, ServerOptions options, SchedulerHost schedules) =>
|
||||
Results.Json(await SettingsAsync(context, store, options, schedules), ProtocolJson.Default.ServerSettingsDto))
|
||||
.Requires(Permissions.ManageArchive);
|
||||
api.MapPut("/server/settings", SaveSettingsAsync).Requires(Permissions.ManageArchive);
|
||||
api.MapGet("/audit", AuditAsync).Requires(Permissions.ManageUsers | Permissions.ManageArchive);
|
||||
@@ -74,8 +74,19 @@ public static class AdminEndpoints
|
||||
}
|
||||
|
||||
private static async Task<IResult> SaveSettingsAsync(HttpContext context, Caller caller, ServerSettingsDto request, ServerSettingsStore store, ServerOptions options,
|
||||
AuditLog audit, JobEngineHost jobs)
|
||||
AuditLog audit, JobEngineHost jobs, SchedulerHost schedules)
|
||||
{
|
||||
// Keep audit shows the audit clean-up schedule's age limit (SettingsAsync): sent back as shown it is no change, so
|
||||
// the default stored in server.json (and an environment variable's lock) is left alone. Like every setting of the
|
||||
// panel it is last-writer-wins: a value that differs from the limit in force now replaces it, also a limit set in
|
||||
// Jobs › Scheduled after this page was read.
|
||||
var shown = await schedules.AuditRetentionAsync(context.RequestAborted) ?? options.AuditRetentionDays;
|
||||
int? auditDays = null;
|
||||
if (request.Logs is { } logs)
|
||||
{
|
||||
if (logs.AuditRetentionDays != shown) auditDays = logs.AuditRetentionDays;
|
||||
else request = request with { Logs = logs with { AuditRetentionDays = options.AuditRetentionDays } };
|
||||
}
|
||||
switch (store.Save(request))
|
||||
{
|
||||
case ("setting_locked", var setting):
|
||||
@@ -85,8 +96,22 @@ public static class AdminEndpoints
|
||||
}
|
||||
// A priority queue turned on, or a level raised, may make the running job yield at once.
|
||||
jobs.Engine.Wake();
|
||||
// The audit retention is the audit clean-up schedule's age limit: a new one goes there (owner review 2, R10, R11).
|
||||
if (auditDays is { } days) await schedules.ApplyAuditRetentionAsync(days, context.RequestAborted);
|
||||
await audit.WriteAsync(caller, context, "server_settings", "server", null, request.ServerName);
|
||||
return Results.Json(store.Current() with { ProxyWarning = AdminPanel.BypassesProxy(context, options) }, ProtocolJson.Default.ServerSettingsDto);
|
||||
return Results.Json(await SettingsAsync(context, store, options, schedules), ProtocolJson.Default.ServerSettingsDto);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The settings as the panel shows them. Keep audit is the audit retention in force, the audit clean-up schedule's age
|
||||
/// limit (0 while it is off), wherever it was last set; <see cref="ServerOptions.AuditRetentionDays"/> is only what the
|
||||
/// schedule is reset to (owner review 2, R10, R11).
|
||||
/// </summary>
|
||||
private static async Task<ServerSettingsDto> SettingsAsync(HttpContext context, ServerSettingsStore store, ServerOptions options, SchedulerHost schedules)
|
||||
{
|
||||
var settings = store.Current();
|
||||
var audit = await schedules.AuditRetentionAsync(context.RequestAborted) ?? settings.Logs.AuditRetentionDays;
|
||||
return settings with { Logs = settings.Logs with { AuditRetentionDays = audit }, ProxyWarning = AdminPanel.BypassesProxy(context, options) };
|
||||
}
|
||||
|
||||
/// <summary>The audit log, newest first; <c>action</c> may list several actions separated by commas (<c>login,login_failed</c>).</summary>
|
||||
|
||||
@@ -50,7 +50,7 @@ public static class DiagnosticsEndpoints
|
||||
bundle.AddJson("settings.json", settings);
|
||||
bundle.AddText("encoders.txt", encoders);
|
||||
bundle.AddJobs("jobs-failed.json", failures);
|
||||
bundle.AddLogs(options.LogPath, cancellationToken: ct);
|
||||
bundle.AddLogs(options.LogPath, tailBytes: options.DiagnosticsLogMb * LogFileOptions.BytesPerMb, cancellationToken: ct);
|
||||
}, ct);
|
||||
file.Position = 0;
|
||||
}
|
||||
|
||||
@@ -27,7 +27,8 @@ public static class Dto
|
||||
|
||||
public static JobDto Job(Job j) => new(
|
||||
j.Id, JobWire.Kind(j.Kind), j.TargetIds, j.TargetLabel, JobWire.State(j.State), JobWire.Priority(j.Priority), j.ProgressDone,
|
||||
j.ProgressTotal, j.ItemsPerSecond, j.Eta?.TotalSeconds, j.LogTail, j.NodeId, j.Attempts, j.Error, j.Created, j.Started, j.Finished);
|
||||
j.ProgressTotal, j.ItemsPerSecond, j.Eta?.TotalSeconds, j.LogTail, j.NodeId, j.Attempts, j.Error, j.Created, j.Started, j.Finished,
|
||||
j.ScheduleId);
|
||||
|
||||
public static AuditEntryDto Audit(AuditEntry a) => new(a.Id, a.At, a.UserId, a.Username, a.Action, a.TargetKind, a.TargetId, a.Details, a.RemoteAddress);
|
||||
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Jobs;
|
||||
using Chronos.Server.Security;
|
||||
|
||||
namespace Chronos.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/v1/schedules</c> (owner review 2, R10; ManageArchive): the server's scheduled jobs, its system schedules
|
||||
/// included, with the actions it can run and its time zone; create, edit (<c>PUT</c> or <c>PATCH</c>, the fields given),
|
||||
/// delete (409 <c>schedule_system</c> for a system schedule), run now (409 <c>schedule_pending</c> while its last job is
|
||||
/// queued, running or paused), reset a system schedule (409 <c>schedule_no_defaults</c> otherwise) and the jobs a schedule
|
||||
/// queued, newest first. An invalid field is 400 <c>invalid_schedule</c> with its name as details (<c>name</c>,
|
||||
/// <c>recurrence</c>, <c>parameters.percent</c>…); changing an age limit an environment variable fixes, or turning its
|
||||
/// schedule off or unticking the steps it deletes with, is 409 <c>setting_locked</c>. Every change is audited.
|
||||
/// </summary>
|
||||
public static class ScheduleEndpoints
|
||||
{
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
var schedules = api.MapGroup("/schedules").Requires(Permissions.ManageArchive);
|
||||
schedules.MapGet("", async (HttpContext context, SchedulerHost host) =>
|
||||
Results.Json(await host.Scheduler.ListAsync(context.RequestAborted), ProtocolJson.Default.SchedulesDto));
|
||||
schedules.MapPost("", CreateAsync);
|
||||
schedules.MapGet("/{id:guid}", async (HttpContext context, Guid id, SchedulerHost host) =>
|
||||
await host.Scheduler.GetAsync(id, context.RequestAborted) is { } schedule
|
||||
? Results.Json(schedule, ProtocolJson.Default.ScheduleDto)
|
||||
: ApiErrors.NotFound(context, "schedule"));
|
||||
schedules.MapPut("/{id:guid}", UpdateAsync);
|
||||
schedules.MapPatch("/{id:guid}", UpdateAsync);
|
||||
schedules.MapDelete("/{id:guid}", DeleteAsync);
|
||||
schedules.MapPost("/{id:guid}/run", RunAsync);
|
||||
schedules.MapPost("/{id:guid}/reset", ResetAsync);
|
||||
schedules.MapGet("/{id:guid}/runs", RunsAsync);
|
||||
}
|
||||
|
||||
private static async Task<IResult> CreateAsync(HttpContext context, Caller caller, CreateScheduleRequest request, SchedulerHost host, AuditLog audit)
|
||||
{
|
||||
var result = await host.Scheduler.CreateAsync(request, caller.Id, context.RequestAborted);
|
||||
if (result.Problem is { } problem) return ApiErrors.BadRequest(context, "invalid_schedule", problem, problem);
|
||||
var schedule = result.Schedule!;
|
||||
await audit.WriteAsync(caller, context, "schedule_created", "schedule", schedule.Id.ToString(), Describe(schedule));
|
||||
return Results.Json(schedule, ProtocolJson.Default.ScheduleDto, statusCode: StatusCodes.Status201Created);
|
||||
}
|
||||
|
||||
private static async Task<IResult> UpdateAsync(HttpContext context, Caller caller, Guid id, UpdateScheduleRequest request, SchedulerHost host, AuditLog audit)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (await host.Scheduler.GetAsync(id, ct) is not { } current) return ApiErrors.NotFound(context, "schedule");
|
||||
if (host.Host.LockedAgeOf(current.SystemKey) is { } locked && ChangesLocked(host.Host, current, request, locked))
|
||||
return ApiErrors.Conflict(context, "setting_locked", locked.Setting);
|
||||
var result = await host.Scheduler.UpdateAsync(id, request, ct);
|
||||
if (result.NotFound) return ApiErrors.NotFound(context, "schedule");
|
||||
if (result.Problem is { } problem) return ApiErrors.BadRequest(context, "invalid_schedule", problem, problem);
|
||||
var schedule = result.Schedule!;
|
||||
await audit.WriteAsync(caller, context, "schedule_updated", "schedule", id.ToString(), Describe(schedule));
|
||||
return Results.Json(schedule, ProtocolJson.Default.ScheduleDto);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="request"/> changes what an environment variable fixes for the system schedule
|
||||
/// <paramref name="current"/>: its age limit (parameters are replaced as a whole, so a missing one would fall back to the
|
||||
/// action's default) and, while the limit deletes (more than 0 days), its switch and the steps the limit deletes with
|
||||
/// (<see cref="ServerScheduleHost.AgedSteps"/>): turned off, or without them, it would keep what the variable asks to delete.
|
||||
/// </summary>
|
||||
private static bool ChangesLocked(ServerScheduleHost host, ScheduleDto current, UpdateScheduleRequest request, LockedAge locked)
|
||||
{
|
||||
if (locked.Days > 0 && request.Enabled == false) return true;
|
||||
if (request.Parameters is not { } parameters) return false;
|
||||
var normalized = ScheduleActions.Normalize(current.Action, parameters);
|
||||
if (normalized.OlderThanDays != locked.Days) return true;
|
||||
return locked.Days > 0 && host.AgedSteps(current.SystemKey).Except(normalized.Steps ?? []).Any();
|
||||
}
|
||||
|
||||
private static async Task<IResult> DeleteAsync(HttpContext context, Caller caller, Guid id, SchedulerHost host, AuditLog audit)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
var current = await host.Scheduler.GetAsync(id, ct);
|
||||
switch (await host.Scheduler.DeleteAsync(id, ct))
|
||||
{
|
||||
case ScheduleDeleteOutcome.System:
|
||||
return ApiErrors.Conflict(context, "schedule_system");
|
||||
case ScheduleDeleteOutcome.NotFound:
|
||||
return ApiErrors.NotFound(context, "schedule");
|
||||
}
|
||||
await audit.WriteAsync(caller, context, "schedule_deleted", "schedule", id.ToString(), current is null ? null : Describe(current));
|
||||
return Results.NoContent();
|
||||
}
|
||||
|
||||
/// <summary>Runs the schedule now, as its next run would (also a disabled one), unless its last job has not ended.</summary>
|
||||
private static async Task<IResult> RunAsync(HttpContext context, Caller caller, Guid id, SchedulerHost host, ChronosDatabase db, AuditLog audit)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (await host.Scheduler.GetAsync(id, ct) is not { } schedule) return ApiErrors.NotFound(context, "schedule");
|
||||
if (schedule.LastJobId is { } last && await db.Jobs.GetAsync(last, ct) is { State: JobState.Queued or JobState.Running or JobState.Paused })
|
||||
return ApiErrors.Conflict(context, "schedule_pending", last.ToString());
|
||||
if (await host.Scheduler.RunNowAsync(id, caller.Id, ct) is not { } run) return ApiErrors.NotFound(context, "schedule");
|
||||
await audit.WriteAsync(caller, context, "schedule_run", "schedule", id.ToString(), $"{Named(run.Schedule)} · {run.Outcome}");
|
||||
return Results.Json(run, ProtocolJson.Default.ScheduleRunDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> ResetAsync(HttpContext context, Caller caller, Guid id, SchedulerHost host, AuditLog audit)
|
||||
{
|
||||
var result = await host.Scheduler.ResetAsync(id, context.RequestAborted);
|
||||
if (result.NotFound) return ApiErrors.NotFound(context, "schedule");
|
||||
if (result.Problem is not null) return ApiErrors.Conflict(context, "schedule_no_defaults");
|
||||
var schedule = result.Schedule!;
|
||||
await audit.WriteAsync(caller, context, "schedule_reset", "schedule", id.ToString(), Describe(schedule));
|
||||
return Results.Json(schedule, ProtocolJson.Default.ScheduleDto);
|
||||
}
|
||||
|
||||
/// <summary>The jobs the schedule queued, newest first; <c>cursor</c> continues a page.</summary>
|
||||
private static async Task<IResult> RunsAsync(HttpContext context, Guid id, SchedulerHost host, ChronosDatabase db, string? cursor, int? limit)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (await host.Scheduler.GetAsync(id, ct) is null) return ApiErrors.NotFound(context, "schedule");
|
||||
var page = await db.Jobs.PageByScheduleAsync(id, limit ?? 20, string.IsNullOrEmpty(cursor) ? null : cursor, ct);
|
||||
return Results.Json(new Page<JobDto>([.. page.Items.Select(Dto.Job)], page.NextCursor, null), ProtocolJson.Default.PageJobDto);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The audit details of a schedule: its name, action and recurrence code (<c>Weekly check · verify · weekly:mon@02:30</c>),
|
||||
/// and "off" while disabled. A system schedule's name follows its key (<c>system:archive-scan · Archive scan · scan ·
|
||||
/// every:10m</c>): the admin panel shows the name in its language, as its Scheduled tab does, and the recurrence in words.
|
||||
/// </summary>
|
||||
private static string Describe(ScheduleDto schedule)
|
||||
{
|
||||
var recurrence = ScheduleMapping.FromDto(schedule.Recurrence)?.Format() ?? schedule.Recurrence.Kind;
|
||||
return $"{Named(schedule)} · {schedule.Action} · {recurrence}{(schedule.Enabled ? string.Empty : " · off")}";
|
||||
}
|
||||
|
||||
/// <summary>The schedule's name in audit details, after <c>system:<key> · </c> for a system schedule.</summary>
|
||||
private static string Named(ScheduleDto schedule) => schedule.SystemKey is { } key ? $"system:{key} · {schedule.Name}" : schedule.Name;
|
||||
}
|
||||
@@ -3,7 +3,10 @@ using System.Net;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Server.Hosting;
|
||||
using LogFileOptions = Chronos.Core.Diagnostics.LogFileOptions;
|
||||
using LogRotation = Chronos.Core.Diagnostics.LogRotation;
|
||||
|
||||
namespace Chronos.Server.Configuration;
|
||||
|
||||
@@ -65,7 +68,16 @@ public sealed class ServerOptions
|
||||
("CHRONOS_PARALLELISM", nameof(Parallelism), (o, v) => o.Parallelism = Int("CHRONOS_PARALLELISM", v)),
|
||||
("CHRONOS_PRIORITY_QUEUE", nameof(PriorityQueue), (o, v) => o.PriorityQueue = bool.Parse(v)),
|
||||
("CHRONOS_DISCOVERY", nameof(Discovery), (o, v) => o.Discovery = bool.Parse(v)),
|
||||
("CHRONOS_LOG_LEVEL", nameof(LogLevel), (o, v) => o.LogLevel = Enum.Parse<LogLevel>(v, ignoreCase: true)),
|
||||
// The level of the files and, unless CHRONOS_LOG_CONSOLE_LEVEL (listed after it) sets its own, of the console.
|
||||
("CHRONOS_LOG_LEVEL", nameof(LogLevel), (o, v) => o.LogLevel = ServerLogging.ParseLevel("CHRONOS_LOG_LEVEL", v)),
|
||||
("CHRONOS_LOG_LEVEL", nameof(ConsoleLogLevel), (o, v) => o.ConsoleLogLevel = ServerLogging.ParseLevel("CHRONOS_LOG_LEVEL", v)),
|
||||
("CHRONOS_LOG_CONSOLE_LEVEL", nameof(ConsoleLogLevel), (o, v) => o.ConsoleLogLevel = ServerLogging.ParseLevel("CHRONOS_LOG_CONSOLE_LEVEL", v)),
|
||||
("CHRONOS_LOG_RETENTION_DAYS", nameof(LogRetentionDays), (o, v) => o.LogRetentionDays = Int("CHRONOS_LOG_RETENTION_DAYS", v)),
|
||||
("CHRONOS_LOG_MAX_FILE_MB", nameof(LogMaxFileMb), (o, v) => o.LogMaxFileMb = Int("CHRONOS_LOG_MAX_FILE_MB", v)),
|
||||
("CHRONOS_LOG_MAX_TOTAL_MB", nameof(LogMaxTotalMb), (o, v) => o.LogMaxTotalMb = Int("CHRONOS_LOG_MAX_TOTAL_MB", v)),
|
||||
("CHRONOS_LOG_ROTATION", nameof(LogRotation), (o, v) => o.LogRotation = ServerLogging.ParseRotation("CHRONOS_LOG_ROTATION", v)),
|
||||
(AuditRetentionVariable, nameof(AuditRetentionDays), (o, v) => o.AuditRetentionDays = Int(AuditRetentionVariable, v)),
|
||||
("CHRONOS_DIAGNOSTICS_LOG_MB", nameof(DiagnosticsLogMb), (o, v) => o.DiagnosticsLogMb = Int("CHRONOS_DIAGNOSTICS_LOG_MB", v)),
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
@@ -76,8 +88,11 @@ public sealed class ServerOptions
|
||||
/// </summary>
|
||||
public const string DefaultTrustedProxies = "127.0.0.0/8, ::1/128";
|
||||
|
||||
/// <summary>The environment variable that sets <paramref name="setting"/> (of two, the one that wins), or null.</summary>
|
||||
public static string? VariableOf(string setting) => Variables.LastOrDefault(v => v.Setting == setting).Variable;
|
||||
|
||||
/// <summary>The environment variables the server reads (<c>--help</c> lists them all).</summary>
|
||||
public static IEnumerable<string> EnvironmentVariables => Variables.Select(v => v.Variable).Prepend("CHRONOS_DATA_PATH");
|
||||
public static IEnumerable<string> EnvironmentVariables => Variables.Select(v => v.Variable).Distinct(StringComparer.Ordinal).Prepend("CHRONOS_DATA_PATH");
|
||||
|
||||
public string ServerName { get; set; } = "Chronos Server";
|
||||
public string ArchivePath { get; set; } = OperatingSystem.IsWindows() ? @"C:\ChronosArchive" : "/archive";
|
||||
@@ -167,11 +182,53 @@ public sealed class ServerOptions
|
||||
public bool FormerWorkersVariable { get; private set; }
|
||||
public bool Discovery { get; set; } = true;
|
||||
|
||||
/// <summary>Least severe level written to the console and the log files.</summary>
|
||||
/// <summary>
|
||||
/// Least severe level written to the log files (<c>/data/logs</c>); <c>CHRONOS_LOG_LEVEL</c> also sets the console's.
|
||||
/// Owner review 2, R11: before, the files never took lines below Information whatever this said.
|
||||
/// </summary>
|
||||
public LogLevel LogLevel { get; set; } = LogLevel.Information;
|
||||
|
||||
/// <summary>Least severe level written to the console (the container's log).</summary>
|
||||
public LogLevel ConsoleLogLevel { get; set; } = LogLevel.Information;
|
||||
|
||||
/// <summary>Log files last written longer ago are deleted.</summary>
|
||||
public int LogRetentionDays { get; set; } = LogFileOptions.DefaultRetentionDays;
|
||||
|
||||
/// <summary>A log file this large (MB of 2²⁰ bytes) continues in a numbered one; 0 = no limit.</summary>
|
||||
public int LogMaxFileMb { get; set; } = LogFileOptions.DefaultMaxFileMb;
|
||||
|
||||
/// <summary>While the log files together are larger (MB), the oldest are deleted, never the current one; 0 = no limit.</summary>
|
||||
public int LogMaxTotalMb { get; set; } = LogFileOptions.DefaultMaxTotalMb;
|
||||
|
||||
/// <summary>One log file per UTC day or per hour.</summary>
|
||||
public LogRotation LogRotation { get; set; } = LogRotation.Daily;
|
||||
|
||||
/// <summary>MB kept from the end of each log file in the diagnostics zip.</summary>
|
||||
public int DiagnosticsLogMb { get; set; } = (int)(Chronos.Core.Diagnostics.DiagnosticsArchive.DefaultLogTailBytes / LogFileOptions.BytesPerMb);
|
||||
public long MaxUploadBytes { get; set; } = 2L * 1024 * 1024 * 1024;
|
||||
public int ChunkSizeBytes { get; set; } = 8 * 1024 * 1024;
|
||||
|
||||
/// <summary>
|
||||
/// Days of job history the <c>housekeeping</c> system schedule keeps when it is created or reset (owner review 2, R10);
|
||||
/// afterwards the schedule's own value applies (admin panel › Jobs › Scheduled).
|
||||
/// </summary>
|
||||
public int JobHistoryDays { get; set; } = 90;
|
||||
|
||||
/// <summary>The environment variable that fixes <see cref="AuditRetentionDays"/>.</summary>
|
||||
public const string AuditRetentionVariable = "CHRONOS_AUDIT_RETENTION_DAYS";
|
||||
|
||||
/// <summary>Most days <see cref="AuditRetentionDays"/> accepts: the most a schedule's age limit takes (ten years).</summary>
|
||||
public const int MaxAuditRetentionDays = ScheduleActions.MaxDays;
|
||||
|
||||
/// <summary>
|
||||
/// Days of audit log the <c>audit-cleanup</c> system schedule keeps when it is created or reset (owner review 2, R10,
|
||||
/// R11); 0, the default, keeps it all, the schedule off. Afterwards the schedule's own age limit applies: Settings › Logs
|
||||
/// shows it (0 while the schedule is off), and saving a new one there sets the schedule and stores it here too. Set by
|
||||
/// <c>CHRONOS_AUDIT_RETENTION_DAYS</c>, it is applied to the schedule at every start, before any run, and cannot be
|
||||
/// changed in the panel or on the schedule.
|
||||
/// </summary>
|
||||
public int AuditRetentionDays { get; set; }
|
||||
|
||||
public int TokenLifetimeDays { get; set; } = 30;
|
||||
|
||||
/// <summary>Uploads untouched for this long are abandoned: their partial files are deleted.</summary>
|
||||
@@ -191,9 +248,16 @@ public sealed class ServerOptions
|
||||
/// <summary>Chunk uploads one user may run at the same time; more are answered 429.</summary>
|
||||
public int ConcurrentChunksPerUser { get; set; } = 8;
|
||||
|
||||
/// <summary>Settings fixed by environment variables (names of the properties above).</summary>
|
||||
/// <summary>Settings fixed by environment variables (names of the properties above); tests set it directly.</summary>
|
||||
[JsonIgnore]
|
||||
public IReadOnlyCollection<string> Locked { get; private set; } = [];
|
||||
public IReadOnlyCollection<string> Locked { get; internal set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// The environment variable that fixes each setting of <see cref="Locked"/>, which the admin panel names: of two that
|
||||
/// set one (<c>CHRONOS_LOG_LEVEL</c> and <c>CHRONOS_LOG_CONSOLE_LEVEL</c>), the one that wins.
|
||||
/// </summary>
|
||||
[JsonIgnore]
|
||||
public IReadOnlyDictionary<string, string> LockedBy { get; internal set; } = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
|
||||
[JsonIgnore]
|
||||
public string LogPath => Path.Combine(DataPath, "logs");
|
||||
@@ -239,6 +303,7 @@ public sealed class ServerOptions
|
||||
options.DataPath = dataPath;
|
||||
|
||||
var locked = new List<string>();
|
||||
var lockedBy = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var (variable, setting, apply) in Variables)
|
||||
{
|
||||
if (Env(variable) is not { } value) continue;
|
||||
@@ -251,8 +316,11 @@ public sealed class ServerOptions
|
||||
throw new InvalidOperationException($"{variable} has an invalid value.", ex);
|
||||
}
|
||||
locked.Add(setting);
|
||||
// Listed in the order they apply: a later variable wins.
|
||||
lockedBy[setting] = variable;
|
||||
}
|
||||
options.Locked = [.. locked.Distinct(StringComparer.Ordinal)];
|
||||
options.LockedBy = lockedBy;
|
||||
// The admin panel saves only values it accepts: one it cannot change (an environment variable) must be one of them.
|
||||
options.Parallelism = Math.Clamp(options.Parallelism, 1, MaxParallelism);
|
||||
options.Validate();
|
||||
@@ -297,6 +365,10 @@ public sealed class ServerOptions
|
||||
throw new InvalidOperationException("The chunk size must be between 64 KiB and 64 MiB.");
|
||||
if (MaxUploadBytes < 1 || TokenLifetimeDays < 1 || JobHistoryDays < 1 || UploadRetentionHours < 1)
|
||||
throw new InvalidOperationException("Upload size, token lifetime, job history and upload retention must be positive.");
|
||||
if (ServerLogging.Problem(LogRetentionDays, LogMaxFileMb, LogMaxTotalMb, AuditRetentionDays, DiagnosticsLogMb) is { } log)
|
||||
throw new InvalidOperationException($"{log} is out of range: {ServerLogging.Ranges}.");
|
||||
if (!ServerLogging.IsLevel(LogLevel) || !ServerLogging.IsLevel(ConsoleLogLevel) || !Enum.IsDefined(LogRotation))
|
||||
throw new InvalidOperationException("CHRONOS_LOG_LEVEL, CHRONOS_LOG_CONSOLE_LEVEL or CHRONOS_LOG_ROTATION has an unknown value.");
|
||||
}
|
||||
|
||||
/// <summary>The parsed <see cref="TrustedProxies"/>; a single address is a network of one.</summary>
|
||||
|
||||
@@ -5,21 +5,27 @@ using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Hosting;
|
||||
using LogRotation = Chronos.Core.Diagnostics.LogRotation;
|
||||
|
||||
namespace Chronos.Server.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// The admin panel's view of the configuration (BRIEF §14.8 Settings). Saving writes <c>/data/server.json</c> (only the
|
||||
/// edited keys; secrets and environment values are never written) and applies what can change while running, the
|
||||
/// parallelism and the priority queue included (owner review 1); ports, TLS, chunk size and job history wait for a restart.
|
||||
/// parallelism and the priority queue included (owner review 1), and the log settings through <see cref="ServerLogging"/>
|
||||
/// (owner review 2, R11); ports, TLS and chunk size wait for a restart. Job history is what the housekeeping system
|
||||
/// schedule is reset to (owner review 2, R10): the schedule's own value applies. The audit retention kept here is what the
|
||||
/// audit clean-up schedule is reset to; the endpoint shows that schedule's age limit in its place and puts a new one there
|
||||
/// (<c>SchedulerHost.AuditRetentionAsync</c>, <c>SchedulerHost.ApplyAuditRetentionAsync</c>).
|
||||
/// </summary>
|
||||
public sealed class ServerSettingsStore(ServerOptions options)
|
||||
public sealed class ServerSettingsStore(ServerOptions options, ServerLogging logging)
|
||||
{
|
||||
/// <summary>The kinds of job the server runs, in the order the admin panel lists their levels (downloads and uploads are a client's).</summary>
|
||||
public static IReadOnlyList<JobKind> Kinds { get; } =
|
||||
[
|
||||
JobKind.Render, JobKind.Import, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse, JobKind.DeepAnalyse, JobKind.Thumbs,
|
||||
JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move,
|
||||
JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move, JobKind.Backup, JobKind.Cleanup,
|
||||
];
|
||||
|
||||
private readonly Lock _gate = new();
|
||||
@@ -36,6 +42,8 @@ public sealed class ServerSettingsStore(ServerOptions options)
|
||||
/// <summary>Validates and saves; returns the error code and the offending setting, or null on success.</summary>
|
||||
public (string Code, string Setting)? Save(ServerSettingsDto request)
|
||||
{
|
||||
// A panel without the log group keeps the log settings as they are.
|
||||
if (request.Logs is null) request = request with { Logs = Current().Logs };
|
||||
if (Validate(request) is { } invalid) return ("invalid_setting", invalid);
|
||||
lock (_gate)
|
||||
{
|
||||
@@ -57,18 +65,31 @@ public sealed class ServerSettingsStore(ServerOptions options)
|
||||
options.MaxUploadBytes = request.MaxUploadBytes;
|
||||
options.TokenLifetimeDays = request.TokenLifetimeDays;
|
||||
options.UploadRetentionHours = request.UploadRetentionHours;
|
||||
options.JobHistoryDays = request.JobHistoryDays;
|
||||
options.Parallelism = request.Parallelism;
|
||||
options.PriorityQueue = request.PriorityQueue;
|
||||
options.JobPriorities = JobPriorityQueue.Changed(Levels(request.JobPriorities));
|
||||
var logs = request.Logs;
|
||||
options.LogLevel = Level(logs.FileLevel);
|
||||
options.ConsoleLogLevel = Level(logs.ConsoleLevel);
|
||||
options.LogRetentionDays = logs.RetentionDays;
|
||||
options.LogMaxFileMb = logs.MaxFileMb;
|
||||
options.LogMaxTotalMb = logs.MaxTotalMb;
|
||||
options.LogRotation = Rotation(logs.Rotation);
|
||||
options.AuditRetentionDays = logs.AuditRetentionDays;
|
||||
options.DiagnosticsLogMb = logs.DiagnosticsLogMb;
|
||||
logging.Apply(options);
|
||||
var restart = request.HttpPort != options.HttpPort || request.HttpsPort != options.HttpsPort
|
||||
|| !string.Equals(request.TlsMode, options.TlsMode.ToString(), StringComparison.OrdinalIgnoreCase)
|
||||
|| request.TlsCert != options.TlsCert || request.TlsKey != options.TlsKey
|
||||
|| request.ChunkSizeBytes != options.ChunkSizeBytes || request.JobHistoryDays != options.JobHistoryDays;
|
||||
|| request.ChunkSizeBytes != options.ChunkSizeBytes;
|
||||
_saved = request with
|
||||
{
|
||||
ServerName = request.ServerName.Trim(),
|
||||
JobPriorities = Priorities(PriorityQueue(options)),
|
||||
Logs = Logs(options),
|
||||
Locked = [.. options.Locked],
|
||||
LockedBy = LockedBy(options),
|
||||
RestartRequired = restart,
|
||||
ProxyWarning = false,
|
||||
};
|
||||
@@ -79,7 +100,20 @@ public sealed class ServerSettingsStore(ServerOptions options)
|
||||
private static ServerSettingsDto Snapshot(ServerOptions o, bool restartRequired) => new(
|
||||
o.ServerName, o.HttpPort, o.HttpsPort, o.TlsMode.ToString().ToLowerInvariant(), o.TlsCert, o.TlsKey, o.Language, o.Parallelism, o.PriorityQueue,
|
||||
Priorities(PriorityQueue(o)), o.Discovery, o.MaxUploadBytes, o.ChunkSizeBytes, o.JobHistoryDays, o.TokenLifetimeDays, o.UploadRetentionHours,
|
||||
[.. o.Locked], restartRequired, ProxyWarning: false);
|
||||
Logs(o), [.. o.Locked], LockedBy(o), restartRequired, ProxyWarning: false);
|
||||
|
||||
/// <summary>The variable that fixes every locked setting (for one a test locks directly, the variable that would).</summary>
|
||||
private static Dictionary<string, string> LockedBy(ServerOptions o) => o.Locked.Distinct(StringComparer.Ordinal).ToDictionary(s => s,
|
||||
s => o.LockedBy.TryGetValue(s, out var variable) ? variable : ServerOptions.VariableOf(s) ?? s, StringComparer.Ordinal);
|
||||
|
||||
private static LogSettingsDto Logs(ServerOptions o) => new(ServerLogging.Wire(o.LogLevel), ServerLogging.Wire(o.ConsoleLogLevel), o.LogRetentionDays,
|
||||
o.LogMaxFileMb, o.LogMaxTotalMb, ServerLogging.Wire(o.LogRotation), o.AuditRetentionDays, o.DiagnosticsLogMb);
|
||||
|
||||
/// <summary>A level <see cref="Validate"/> has checked.</summary>
|
||||
private static LogLevel Level(string wire) => ServerLogging.TryParseLevel(wire, out var level) ? level : LogLevel.Information;
|
||||
|
||||
/// <summary>A rotation <see cref="Validate"/> has checked.</summary>
|
||||
private static LogRotation Rotation(string wire) => ServerLogging.TryParseRotation(wire, out var rotation) ? rotation : LogRotation.Daily;
|
||||
|
||||
/// <summary>The level of every kind the server runs in <paramref name="queue"/>.</summary>
|
||||
private static List<JobPriorityDto> Priorities(JobPriorityQueue queue) =>
|
||||
@@ -113,7 +147,11 @@ public sealed class ServerSettingsStore(ServerOptions options)
|
||||
if (r.JobHistoryDays is < 1 or > 3650) return nameof(ServerOptions.JobHistoryDays);
|
||||
if (r.TokenLifetimeDays is < 1 or > 365) return nameof(ServerOptions.TokenLifetimeDays);
|
||||
if (r.UploadRetentionHours is < 1 or > 8760) return nameof(ServerOptions.UploadRetentionHours);
|
||||
return null;
|
||||
var logs = r.Logs;
|
||||
if (!ServerLogging.TryParseLevel(logs.FileLevel, out _)) return nameof(ServerOptions.LogLevel);
|
||||
if (!ServerLogging.TryParseLevel(logs.ConsoleLevel, out _)) return nameof(ServerOptions.ConsoleLogLevel);
|
||||
if (!ServerLogging.TryParseRotation(logs.Rotation, out _)) return nameof(ServerOptions.LogRotation);
|
||||
return ServerLogging.Problem(logs.RetentionDays, logs.MaxFileMb, logs.MaxTotalMb, logs.AuditRetentionDays, logs.DiagnosticsLogMb);
|
||||
}
|
||||
|
||||
/// <summary>Settings whose value differs, as server.json keys and JSON values.</summary>
|
||||
@@ -144,6 +182,15 @@ public sealed class ServerSettingsStore(ServerOptions options)
|
||||
Add(nameof(ServerOptions.JobHistoryDays), a.JobHistoryDays, b.JobHistoryDays, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.TokenLifetimeDays), a.TokenLifetimeDays, b.TokenLifetimeDays, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.UploadRetentionHours), a.UploadRetentionHours, b.UploadRetentionHours, v => JsonValue.Create(v));
|
||||
// Levels and the rotation are stored by name, as server.json reads them ("Debug", "Hourly").
|
||||
Add(nameof(ServerOptions.LogLevel), Level(a.Logs.FileLevel), Level(b.Logs.FileLevel), v => JsonValue.Create(v.ToString()));
|
||||
Add(nameof(ServerOptions.ConsoleLogLevel), Level(a.Logs.ConsoleLevel), Level(b.Logs.ConsoleLevel), v => JsonValue.Create(v.ToString()));
|
||||
Add(nameof(ServerOptions.LogRetentionDays), a.Logs.RetentionDays, b.Logs.RetentionDays, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.LogMaxFileMb), a.Logs.MaxFileMb, b.Logs.MaxFileMb, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.LogMaxTotalMb), a.Logs.MaxTotalMb, b.Logs.MaxTotalMb, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.LogRotation), Rotation(a.Logs.Rotation), Rotation(b.Logs.Rotation), v => JsonValue.Create(v.ToString()));
|
||||
Add(nameof(ServerOptions.AuditRetentionDays), a.Logs.AuditRetentionDays, b.Logs.AuditRetentionDays, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.DiagnosticsLogMb), a.Logs.DiagnosticsLogMb, b.Logs.DiagnosticsLogMb, v => JsonValue.Create(v));
|
||||
return changes;
|
||||
}
|
||||
}
|
||||
@@ -4,31 +4,27 @@ using MsLogLevel = Microsoft.Extensions.Logging.LogLevel;
|
||||
|
||||
namespace Chronos.Server.Hosting;
|
||||
|
||||
/// <summary>In-house structured file logging for ASP.NET Core (rotating daily files under /data/logs).</summary>
|
||||
public sealed class FileLoggerProvider(FileLogSink sink) : ILoggerProvider
|
||||
/// <summary>
|
||||
/// In-house structured file logging for ASP.NET Core: the rotating files of <see cref="ServerLogging.Sink"/> under
|
||||
/// /data/logs, at <see cref="ServerLogging.FileLevel"/> of the moment (owner review 2, R11: it was fixed at Information,
|
||||
/// so Debug and Trace never reached the files).
|
||||
/// </summary>
|
||||
public sealed class FileLoggerProvider(ServerLogging logging) : ILoggerProvider
|
||||
{
|
||||
public ILogger CreateLogger(string categoryName) => new FileLogger(sink, categoryName);
|
||||
public ILogger CreateLogger(string categoryName) => new FileLogger(logging, categoryName);
|
||||
|
||||
public void Dispose() => sink.Dispose();
|
||||
public void Dispose() => logging.Sink.Dispose();
|
||||
|
||||
private sealed class FileLogger(FileLogSink sink, string category) : ILogger
|
||||
private sealed class FileLogger(ServerLogging logging, string category) : ILogger
|
||||
{
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
|
||||
public bool IsEnabled(MsLogLevel logLevel) => logLevel >= MsLogLevel.Information;
|
||||
public bool IsEnabled(MsLogLevel logLevel) => logLevel != MsLogLevel.None && logLevel >= logging.FileLevel;
|
||||
|
||||
public void Log<TState>(MsLogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
if (!IsEnabled(logLevel)) return;
|
||||
var level = logLevel switch
|
||||
{
|
||||
MsLogLevel.Trace => CoreLogLevel.Trace,
|
||||
MsLogLevel.Debug => CoreLogLevel.Debug,
|
||||
MsLogLevel.Information => CoreLogLevel.Info,
|
||||
MsLogLevel.Warning => CoreLogLevel.Warning,
|
||||
_ => CoreLogLevel.Error,
|
||||
};
|
||||
sink.Write(level, category, formatter(state, exception), exception);
|
||||
logging.Sink.Write(ServerLogging.Core(logLevel), category, formatter(state, exception), exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -56,8 +52,16 @@ public sealed class LoggerSink(ILoggerFactory factory) : ILogSink
|
||||
CoreLogLevel.Warning => MsLogLevel.Warning,
|
||||
_ => MsLogLevel.Error,
|
||||
};
|
||||
try
|
||||
{
|
||||
#pragma warning disable CA2254 // Engine messages are preformatted.
|
||||
logger.Log(ms, exception, message);
|
||||
logger.Log(ms, exception, message);
|
||||
#pragma warning restore CA2254
|
||||
}
|
||||
catch (AggregateException)
|
||||
{
|
||||
// A provider could not write it (Microsoft.Extensions.Logging gathers what they throw): the line is dropped, as
|
||||
// Log.Write would drop it, so the engine code that logs goes on.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,15 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
|
||||
CHRONOS_PARALLELISM photos the running job processes at once (jobs run one at a time; default: half the
|
||||
cores); CHRONOS_WORKERS, its former name, still sets it
|
||||
CHRONOS_PRIORITY_QUEUE a job of a higher level pauses the running one, which resumes afterwards (true | false)
|
||||
CHRONOS_LOG_LEVEL (Trace | Debug | Information | Warning | Error)
|
||||
CHRONOS_LOG_LEVEL least severe level of the log files and the console (Trace | Debug | Information |
|
||||
Warning | Error | Critical | None; default Information)
|
||||
CHRONOS_LOG_CONSOLE_LEVEL the console's own level (default: CHRONOS_LOG_LEVEL's)
|
||||
CHRONOS_LOG_RETENTION_DAYS days log files are kept (default 14)
|
||||
CHRONOS_LOG_MAX_FILE_MB size at which a log file continues in a numbered one (default 50; 0: no limit)
|
||||
CHRONOS_LOG_MAX_TOTAL_MB size of all log files; beyond it the oldest are deleted (default 1024; 0: no limit)
|
||||
CHRONOS_LOG_ROTATION a new log file every day or every hour, UTC (daily | hourly; default daily)
|
||||
CHRONOS_AUDIT_RETENTION_DAYS days of audit log the audit-cleanup schedule keeps (default 0: forever)
|
||||
CHRONOS_DIAGNOSTICS_LOG_MB MB from the end of each log file in the diagnostics zip (default 4)
|
||||
CHRONOS_DISCOVERY LAN beacon (true | false); in a container it needs host networking
|
||||
CHRONOS_PUBLIC_HTTP_PORT, CHRONOS_PUBLIC_HTTPS_PORT
|
||||
ports clients reach when the container's ports are published as other host ports
|
||||
@@ -50,7 +58,7 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
|
||||
CHRONOS_TRUSTED_PROXIES proxy mode: addresses or networks (CIDR) whose X-Forwarded-* headers count
|
||||
(default: loopback only; list a proxy in another container or on another machine)
|
||||
|
||||
Container image only: PUID, PGID (user and group the server runs as, owners of /data), TZ (local time zone)
|
||||
Container image only: PUID, PGID (user and group the server runs as, owners of /data), TZ (time zone of the schedules)
|
||||
""";
|
||||
|
||||
public static ServerCommandLine Parse(IReadOnlyList<string> args)
|
||||
|
||||
@@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Server.Kestrel.Core;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Housekeeping;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Api;
|
||||
using Chronos.Server.Configuration;
|
||||
@@ -36,18 +37,16 @@ public static class ServerHost
|
||||
var archiveOpenToOthers = DataFolderAccess.PrepareArchive(options.ArchivePath);
|
||||
|
||||
var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions { Args = args, ContentRootPath = AppContext.BaseDirectory });
|
||||
builder.Logging.ClearProviders();
|
||||
builder.Logging.SetMinimumLevel(options.LogLevel);
|
||||
builder.Logging.AddSimpleConsole(c => c.SingleLine = true);
|
||||
builder.Logging.AddProvider(new FileLoggerProvider(new FileLogSink(options.LogPath, "server")));
|
||||
builder.Logging.AddFilter("Microsoft.AspNetCore", Microsoft.Extensions.Logging.LogLevel.Warning);
|
||||
builder.Logging.AddFilter("Microsoft.Hosting.Lifetime", options.LogLevel > Microsoft.Extensions.Logging.LogLevel.Information ? options.LogLevel : Microsoft.Extensions.Logging.LogLevel.Information);
|
||||
// The console and the files each follow their own level, which the admin panel changes while the server runs.
|
||||
var logging = new ServerLogging(options);
|
||||
logging.AddTo(builder.Logging);
|
||||
builder.Services.AddSingleton(logging);
|
||||
|
||||
// The archive module registers first, so a missing piece stops the server before it touches the database.
|
||||
configureServices?.Invoke(builder.Services);
|
||||
RequireArchiveModule(builder.Services);
|
||||
|
||||
using var bootLoggerFactory = LoggerFactory.Create(l => l.AddSimpleConsole(c => c.SingleLine = true).SetMinimumLevel(options.LogLevel));
|
||||
using var bootLoggerFactory = LoggerFactory.Create(l => l.AddSimpleConsole(c => c.SingleLine = true).SetMinimumLevel(options.ConsoleLogLevel));
|
||||
var bootLogger = bootLoggerFactory.CreateLogger("Chronos.Server");
|
||||
var certificate = CertificateStore.Load(options, bootLogger);
|
||||
var database = ServerDatabase.OpenAsync(options, bootLogger, CancellationToken.None).GetAwaiter().GetResult();
|
||||
@@ -146,10 +145,16 @@ public static class ServerHost
|
||||
services.AddSingleton<RenderNodeService>();
|
||||
services.AddSingleton<JobEngineHost>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<JobEngineHost>());
|
||||
// After the engine's host: the scheduler queues on its engine, starts after it and stops before it (owner review 2, R10).
|
||||
services.AddSingleton<ServerScheduleHost>();
|
||||
services.AddSingleton<SchedulerHost>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<SchedulerHost>());
|
||||
services.AddSingleton<RenderNodeMonitor>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<RenderNodeMonitor>());
|
||||
// Recovers interrupted commits at start; its sweep is the clean-up step of the upload-cleanup schedule.
|
||||
services.AddSingleton<UploadMaintenance>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<UploadMaintenance>());
|
||||
services.AddSingleton<ICleanupStep, UploadCleanupStep>();
|
||||
services.AddSingleton<DiscoveryBeaconService>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<DiscoveryBeaconService>());
|
||||
}
|
||||
@@ -171,6 +176,7 @@ public static class ServerHost
|
||||
FileEndpoints.Map(api);
|
||||
UploadEndpoints.Map(api);
|
||||
JobEndpoints.Map(api);
|
||||
ScheduleEndpoints.Map(api);
|
||||
NodeEndpoints.Map(api);
|
||||
ArchiveEndpoints.Map(api);
|
||||
AdminEndpoints.Map(api);
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
using Microsoft.Extensions.Logging.Console;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Server.Configuration;
|
||||
using CoreLogLevel = Chronos.Core.Diagnostics.LogLevel;
|
||||
using MsLogLevel = Microsoft.Extensions.Logging.LogLevel;
|
||||
|
||||
namespace Chronos.Server.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// The server's logging (BRIEF §14.1; owner review 2, R11): the console and the files of <c>/data/logs</c>, each with its
|
||||
/// own level, which the logging filters read at every line so a change in the admin panel applies at once; the file
|
||||
/// sink's retention, size limits and rotation; and the engine's <see cref="Log.MinimumLevel"/>, the lower of the two
|
||||
/// levels, so engine lines reach whichever output wants them. ASP.NET Core's own categories never write below Warning and
|
||||
/// the host's lifetime never below Information, whatever the levels.
|
||||
/// </summary>
|
||||
public sealed class ServerLogging
|
||||
{
|
||||
public const int MaxRetentionDays = 3650;
|
||||
public const int MaxFileMb = 10 * 1024;
|
||||
public const int MaxTotalMb = 1024 * 1024;
|
||||
public const int MaxAuditRetentionDays = ServerOptions.MaxAuditRetentionDays;
|
||||
public const int MaxDiagnosticsLogMb = 1024;
|
||||
|
||||
/// <summary>The ranges <see cref="Problem"/> checks, for the start-up error.</summary>
|
||||
public const string Ranges = "log retention 1 to 3650 days, log file 0 to 10240 MB, logs total 0 to 1048576 MB and not below the log file, "
|
||||
+ "audit retention 0 to 3650 days, diagnostics logs 1 to 1024 MB";
|
||||
|
||||
/// <summary>The levels the settings accept, least severe first; their wire names are lower case (<c>information</c>).</summary>
|
||||
public static IReadOnlyList<MsLogLevel> Levels { get; } =
|
||||
[MsLogLevel.Trace, MsLogLevel.Debug, MsLogLevel.Information, MsLogLevel.Warning, MsLogLevel.Error, MsLogLevel.Critical, MsLogLevel.None];
|
||||
|
||||
private volatile MsLogLevel _file;
|
||||
private volatile MsLogLevel _console;
|
||||
|
||||
/// <summary>Opens the log files of <paramref name="options"/> and applies its levels (call once the data folder is prepared).</summary>
|
||||
public ServerLogging(ServerOptions options)
|
||||
{
|
||||
Sink = new FileLogSink(options.LogPath, "server", FileOptions(options));
|
||||
Apply(options);
|
||||
}
|
||||
|
||||
public FileLogSink Sink { get; }
|
||||
|
||||
public MsLogLevel FileLevel => _file;
|
||||
|
||||
public MsLogLevel ConsoleLevel => _console;
|
||||
|
||||
/// <summary>The console and the file provider, each behind a filter that reads its level now.</summary>
|
||||
public void AddTo(ILoggingBuilder logging)
|
||||
{
|
||||
logging.ClearProviders();
|
||||
// Every level reaches the filters; they decide with the levels of the moment.
|
||||
logging.SetMinimumLevel(MsLogLevel.Trace);
|
||||
logging.AddSimpleConsole(c => c.SingleLine = true);
|
||||
logging.AddProvider(new FileLoggerProvider(this));
|
||||
logging.AddFilter<ConsoleLoggerProvider>((category, level) => Allows(category, level, ConsoleLevel));
|
||||
logging.AddFilter<FileLoggerProvider>((category, level) => Allows(category, level, FileLevel));
|
||||
}
|
||||
|
||||
/// <summary>The levels, retention, limits and rotation of <paramref name="options"/>, from the next line on.</summary>
|
||||
public void Apply(ServerOptions options)
|
||||
{
|
||||
_file = options.LogLevel;
|
||||
_console = options.ConsoleLogLevel;
|
||||
Sink.Configure(FileOptions(options));
|
||||
Log.MinimumLevel = Core(options.LogLevel < options.ConsoleLogLevel ? options.LogLevel : options.ConsoleLogLevel);
|
||||
}
|
||||
|
||||
public static LogFileOptions FileOptions(ServerOptions options) => new()
|
||||
{
|
||||
Level = Core(options.LogLevel),
|
||||
RetentionDays = options.LogRetentionDays,
|
||||
MaxFileMb = options.LogMaxFileMb,
|
||||
MaxTotalMb = options.LogMaxTotalMb,
|
||||
Rotation = options.LogRotation,
|
||||
};
|
||||
|
||||
/// <summary>Whether a line of <paramref name="category"/> at <paramref name="level"/> is written by an output at <paramref name="threshold"/>.</summary>
|
||||
public static bool Allows(string? category, MsLogLevel level, MsLogLevel threshold)
|
||||
{
|
||||
if (level == MsLogLevel.None || level < threshold) return false;
|
||||
if (category is null) return true;
|
||||
// A line per request below Warning would bury everything else.
|
||||
if (category.StartsWith("Microsoft.AspNetCore", StringComparison.OrdinalIgnoreCase)) return level >= MsLogLevel.Warning;
|
||||
if (category.StartsWith("Microsoft.Hosting.Lifetime", StringComparison.OrdinalIgnoreCase)) return level >= MsLogLevel.Information;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The engine's level of an ASP.NET Core level (Critical and None become Error, the engine's most severe).</summary>
|
||||
public static CoreLogLevel Core(MsLogLevel level) => level switch
|
||||
{
|
||||
MsLogLevel.Trace => CoreLogLevel.Trace,
|
||||
MsLogLevel.Debug => CoreLogLevel.Debug,
|
||||
MsLogLevel.Information => CoreLogLevel.Info,
|
||||
MsLogLevel.Warning => CoreLogLevel.Warning,
|
||||
_ => CoreLogLevel.Error,
|
||||
};
|
||||
|
||||
public static bool IsLevel(MsLogLevel level) => Levels.Contains(level);
|
||||
|
||||
/// <summary><c>information</c>.</summary>
|
||||
public static string Wire(MsLogLevel level) => level.ToString().ToLowerInvariant();
|
||||
|
||||
/// <summary><c>daily</c> or <c>hourly</c>.</summary>
|
||||
public static string Wire(LogRotation rotation) => rotation.ToString().ToLowerInvariant();
|
||||
|
||||
/// <summary>A level by name, any case; <c>info</c>, <c>warn</c> and <c>off</c> are accepted too. Numbers are not levels.</summary>
|
||||
public static bool TryParseLevel(string? text, out MsLogLevel level)
|
||||
{
|
||||
level = MsLogLevel.Information;
|
||||
var name = text?.Trim();
|
||||
if (string.IsNullOrEmpty(name)) return false;
|
||||
if (name.Equals("info", StringComparison.OrdinalIgnoreCase)) name = nameof(MsLogLevel.Information);
|
||||
else if (name.Equals("warn", StringComparison.OrdinalIgnoreCase)) name = nameof(MsLogLevel.Warning);
|
||||
else if (name.Equals("off", StringComparison.OrdinalIgnoreCase)) name = nameof(MsLogLevel.None);
|
||||
foreach (var candidate in Levels)
|
||||
{
|
||||
if (!candidate.ToString().Equals(name, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
level = candidate;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool TryParseRotation(string? text, out LogRotation rotation)
|
||||
{
|
||||
rotation = LogRotation.Daily;
|
||||
foreach (var candidate in Enum.GetValues<LogRotation>())
|
||||
{
|
||||
if (!candidate.ToString().Equals(text?.Trim(), StringComparison.OrdinalIgnoreCase)) continue;
|
||||
rotation = candidate;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <exception cref="FormatException">Not a level.</exception>
|
||||
public static MsLogLevel ParseLevel(string variable, string value) => TryParseLevel(value, out var level)
|
||||
? level
|
||||
: throw new FormatException($"{variable} must be Trace, Debug, Information, Warning, Error, Critical or None.");
|
||||
|
||||
/// <exception cref="FormatException">Neither daily nor hourly.</exception>
|
||||
public static LogRotation ParseRotation(string variable, string value) => TryParseRotation(value, out var rotation)
|
||||
? rotation
|
||||
: throw new FormatException($"{variable} must be daily or hourly.");
|
||||
|
||||
/// <summary>The setting (a <see cref="ServerOptions"/> property name) whose value is out of range, or null.</summary>
|
||||
public static string? Problem(int retentionDays, int maxFileMb, int maxTotalMb, int auditRetentionDays, int diagnosticsLogMb)
|
||||
{
|
||||
if (retentionDays is < 1 or > MaxRetentionDays) return nameof(ServerOptions.LogRetentionDays);
|
||||
if (maxFileMb is < 0 or > MaxFileMb) return nameof(ServerOptions.LogMaxFileMb);
|
||||
if (maxTotalMb is < 0 or > MaxTotalMb || LogFileOptions.TotalBelowFile(maxFileMb, maxTotalMb)) return nameof(ServerOptions.LogMaxTotalMb);
|
||||
if (auditRetentionDays is < 0 or > MaxAuditRetentionDays) return nameof(ServerOptions.AuditRetentionDays);
|
||||
if (diagnosticsLogMb is < 1 or > MaxDiagnosticsLogMb) return nameof(ServerOptions.DiagnosticsLogMb);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,6 @@ public sealed class JobEngineHost : IHostedService
|
||||
{
|
||||
WorkerId = WorkerId,
|
||||
Kinds = _kinds,
|
||||
HistoryRetention = TimeSpan.FromDays(options.JobHistoryDays),
|
||||
PriorityQueue = () => ServerSettingsStore.PriorityQueue(options),
|
||||
});
|
||||
Engine.JobChanged += OnJobChanged;
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Events;
|
||||
|
||||
namespace Chronos.Server.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Hosts the server's <see cref="Scheduler"/> (owner review 2, R10) on the <see cref="JobEngineHost"/>'s engine with the
|
||||
/// <see cref="ServerScheduleHost"/>: registered after the engine's host, so it starts after it and stops before it. At start
|
||||
/// (<see cref="Scheduler.StartAsync(IScheduleHost, Func{CancellationToken, Task}, CancellationToken)"/>) it seeds the system
|
||||
/// schedules, puts the age limits that environment variables fix into them (<see cref="ServerScheduleHost.LockedAgeOf"/>)
|
||||
/// before the first pass, so a run caught up at start already uses them, and settles missed runs; then it runs the archive
|
||||
/// scan once in the background, as the former polling did, so the photos of an adopted folder are indexed without waiting
|
||||
/// for its first interval (only while that schedule is enabled). Every <see cref="ServerScheduleHost.ScanMinutes"/> it
|
||||
/// takes the settings another writer put into archive.json, as the polling did, whatever the scan schedule does. The audit
|
||||
/// retention in force is the audit clean-up schedule's age limit, 0 while it is off or without its audit step:
|
||||
/// Settings › Logs shows it (<see cref="AuditRetentionAsync"/>) and sets it (<see cref="ApplyAuditRetentionAsync"/>);
|
||||
/// <see cref="ServerOptions.AuditRetentionDays"/> is only what the schedule is seeded and reset with, or what an environment
|
||||
/// variable fixes. Every schedule change and run goes out as a <see cref="ScheduleChangedEvent"/>.
|
||||
/// </summary>
|
||||
public sealed class SchedulerHost : IHostedService
|
||||
{
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly TimeProvider _time;
|
||||
private readonly ILogger<SchedulerHost> _logger;
|
||||
private readonly CancellationTokenSource _stopping = new();
|
||||
private Task _startScan = Task.CompletedTask;
|
||||
private Task _refresh = Task.CompletedTask;
|
||||
private int _stopped;
|
||||
|
||||
public SchedulerHost(ChronosDatabase db, JobEngineHost jobs, ServerScheduleHost host, EventHub events, TimeProvider time, ILogger<SchedulerHost> logger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(jobs);
|
||||
ArgumentNullException.ThrowIfNull(events);
|
||||
_db = db;
|
||||
_time = time;
|
||||
_logger = logger;
|
||||
Host = host;
|
||||
Scheduler = new Scheduler(db, jobs.Engine, new SchedulerOptions { Time = time });
|
||||
// The Scheduled tab of the admin panel follows them, the runs that queue no job included.
|
||||
Scheduler.ScheduleChanged += schedule => events.Publish(new ScheduleChangedEvent(schedule.Id, Deleted: false));
|
||||
Scheduler.ScheduleDeleted += id => events.Publish(new ScheduleChangedEvent(id, Deleted: true));
|
||||
}
|
||||
|
||||
public Scheduler Scheduler { get; }
|
||||
|
||||
public ServerScheduleHost Host { get; }
|
||||
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var started = Scheduler.Options.Time.GetUtcNow();
|
||||
await Scheduler.StartAsync(Host, ApplyLockedAgesAsync, cancellationToken);
|
||||
var stopping = _stopping.Token;
|
||||
_startScan = Task.Run(() => ScanAtStartAsync(started, stopping), CancellationToken.None);
|
||||
// Created here, so its first period counts from the start.
|
||||
var timer = new PeriodicTimer(TimeSpan.FromMinutes(ServerScheduleHost.ScanMinutes), _time);
|
||||
_refresh = Task.Run(() => RefreshArchiveAsync(timer, stopping), CancellationToken.None);
|
||||
}
|
||||
|
||||
public async Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _stopped, 1) == 1) return;
|
||||
await _stopping.CancelAsync();
|
||||
await _startScan;
|
||||
await _refresh;
|
||||
await Scheduler.DisposeAsync();
|
||||
_stopping.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The audit retention in force (owner review 2, R10, R11): the audit clean-up schedule's age limit, 0 while the schedule
|
||||
/// is off or its steps leave out the audit step (nothing is deleted); null before the schedule is seeded.
|
||||
/// </summary>
|
||||
public async Task<int?> AuditRetentionAsync(CancellationToken cancellationToken = default) =>
|
||||
await _db.Schedules.GetBySystemKeyAsync(ServerScheduleHost.AuditCleanup, cancellationToken) is { } row ? InForce(row) : null;
|
||||
|
||||
/// <summary>
|
||||
/// Puts the audit retention saved in Settings › Logs into the audit clean-up schedule, the one source of truth (owner
|
||||
/// review 2, R10, R11): enabled with a limit and the audit step, off at 0, which keeps everything.
|
||||
/// </summary>
|
||||
public Task ApplyAuditRetentionAsync(int days, CancellationToken cancellationToken = default) =>
|
||||
ApplyAgeAsync(ServerScheduleHost.AuditCleanup, days, "Settings › Logs", cancellationToken);
|
||||
|
||||
/// <summary>The audit clean-up schedule's age limit, 0 while it is off or without the audit step, which alone deletes by it.</summary>
|
||||
private static int InForce(Schedule row) =>
|
||||
row.Enabled && ScheduleMapping.Parameters(row) is { Steps: { } steps } parameters && steps.Contains(Chronos.Data.Housekeeping.CleanupSteps.Audit)
|
||||
? parameters.OlderThanDays ?? 0
|
||||
: 0;
|
||||
|
||||
/// <summary>The age limits environment variables fix, put into their system schedules at every start, before the first pass.</summary>
|
||||
private async Task ApplyLockedAgesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var system in Host.SystemSchedules)
|
||||
{
|
||||
if (Host.LockedAgeOf(system.SystemKey) is { } locked) await ApplyAgeAsync(system.SystemKey, locked.Days, locked.Variable, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the age limit of the system schedule <paramref name="systemKey"/> to <paramref name="days"/>, enabling it when it
|
||||
/// has a limit now and disabling it at 0; a limit also ticks again the steps it deletes with
|
||||
/// (<see cref="ServerScheduleHost.AgedSteps"/>) when they were unticked. Nothing when it already holds the value, with those
|
||||
/// steps, and is on (off at 0). A schedule kept enabled keeps its next run, so a missed run is still caught up, with the
|
||||
/// new limit.
|
||||
/// </summary>
|
||||
private async Task ApplyAgeAsync(string systemKey, int days, string source, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await _db.Schedules.GetBySystemKeyAsync(systemKey, cancellationToken) is not { } row) return;
|
||||
var parameters = ScheduleMapping.Parameters(row);
|
||||
var steps = parameters.Steps ?? [];
|
||||
var missing = days > 0 ? Host.AgedSteps(systemKey).Except(steps).ToList() : [];
|
||||
if (parameters.OlderThanDays == days && row.Enabled == (days > 0) && missing.Count == 0) return;
|
||||
var result = await Scheduler.UpdateAsync(row.Id,
|
||||
new UpdateScheduleRequest(Parameters: parameters with { OlderThanDays = days, Steps = missing.Count == 0 ? parameters.Steps : [.. steps, .. missing] },
|
||||
Enabled: days > 0),
|
||||
cancellationToken);
|
||||
if (result.Problem is { } problem) _logger.LogWarning("{Source} could not be applied to the {Schedule} schedule ({Problem})", source, row.Name, problem);
|
||||
else _logger.LogInformation("{Source} sets the {Schedule} schedule to {Days} day(s)", source, row.Name, days);
|
||||
}
|
||||
|
||||
/// <summary>The archive scan's run at start, unless the first pass already fired it or it is disabled.</summary>
|
||||
private async Task ScanAtStartAsync(DateTimeOffset started, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Scheduler.RunSystemNowAsync(ServerScheduleHost.ArchiveScan, started, cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "The archive scan at start could not be queued; its schedule queues the next one");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes the settings a desktop sharing the archive put into archive.json at every tick of <paramref name="timer"/>
|
||||
/// (<see cref="ServerScheduleHost.GetArchiveAsync"/>), so uploads follow them although the scan schedule's runs, which
|
||||
/// read them too, are skipped while a long scan is pending, or are rare or off.
|
||||
/// </summary>
|
||||
private async Task RefreshArchiveAsync(PeriodicTimer timer, CancellationToken cancellationToken)
|
||||
{
|
||||
using (timer)
|
||||
{
|
||||
try
|
||||
{
|
||||
while (await timer.WaitForNextTickAsync(cancellationToken))
|
||||
{
|
||||
try
|
||||
{
|
||||
await Host.GetArchiveAsync(cancellationToken);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogWarning(ex, "The archive's archive.json could not be read; the next tick tries again");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Storage;
|
||||
|
||||
namespace Chronos.Server.Jobs;
|
||||
|
||||
/// <summary>An age limit an environment variable fixes for a system schedule: the setting it comes from, the variable and the days.</summary>
|
||||
public sealed record LockedAge(string Setting, string Variable, int Days);
|
||||
|
||||
/// <summary>
|
||||
/// What the server tells its <see cref="Scheduler"/> (owner review 2, R10): the container's time zone (TZ), the archive it
|
||||
/// serves with the settings another writer put into archive.json (read again at every run and, whatever the runs do, every
|
||||
/// <see cref="ScanMinutes"/> by <see cref="SchedulerHost"/>, as the former polling did), the server's own clean-up steps,
|
||||
/// and its system schedules, which stand for every timer it ran out of sight before: the archive scan every 10 minutes
|
||||
/// (no catch-up), the uploads sweep every 6 hours, the nightly copy of an SQLite index, the job history and the audit log
|
||||
/// retentions. They are seeded from <see cref="ServerOptions"/> once (the user's edits stay) and reset to the options as
|
||||
/// they are then.
|
||||
/// </summary>
|
||||
public sealed class ServerScheduleHost : IScheduleHost
|
||||
{
|
||||
public const string ArchiveScan = "archive-scan";
|
||||
public const string UploadCleanup = "upload-cleanup";
|
||||
public const string IndexBackup = DatabaseBackups.ScheduleKey;
|
||||
public const string Housekeeping = "housekeeping";
|
||||
public const string AuditCleanup = "audit-cleanup";
|
||||
|
||||
/// <summary>Minutes between two archive scans (the desktop's rhythm, as the polling had).</summary>
|
||||
public const int ScanMinutes = 10;
|
||||
|
||||
/// <summary>
|
||||
/// Hours between two sweeps of abandoned uploads: rare enough to keep the job history readable (four clean-up jobs a
|
||||
/// day); an idle upload still expires after <see cref="ServerOptions.UploadRetentionHours"/>, at most this much later.
|
||||
/// </summary>
|
||||
public const int UploadSweepHours = 6;
|
||||
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly ServerOptions _options;
|
||||
private readonly ServerArchive _archive;
|
||||
private readonly ArchiveService? _archives;
|
||||
private readonly ILogger<ServerScheduleHost> _logger;
|
||||
|
||||
public ServerScheduleHost(ChronosDatabase db, ServerOptions options, ServerArchive archive, IServiceProvider services, ILogger<ServerScheduleHost> logger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
_db = db;
|
||||
_options = options;
|
||||
_archive = archive;
|
||||
_logger = logger;
|
||||
// Without the archive module (tests with a fake ingest) nothing refreshes archive.json and no clean-up step exists.
|
||||
_archives = services.GetService<ArchiveService>();
|
||||
CleanupSteps = _archives is null ? [] : [.. _archives.CleanupSteps.Select(s => s.Name)];
|
||||
TimeZone = ResolveTimeZone(Environment.GetEnvironmentVariable("TZ"), logger);
|
||||
}
|
||||
|
||||
public TimeZoneInfo TimeZone { get; }
|
||||
|
||||
public IReadOnlyList<string> CleanupSteps { get; }
|
||||
|
||||
/// <summary>Built from the options as they are now, so a reset follows a changed <see cref="ServerOptions.AuditRetentionDays"/>.</summary>
|
||||
public IReadOnlyList<SystemSchedule> SystemSchedules
|
||||
{
|
||||
get
|
||||
{
|
||||
var nightly = (Backup: new TimeOnly(3, 0), History: new TimeOnly(4, 0), Audit: new TimeOnly(4, 30));
|
||||
var list = new List<SystemSchedule>
|
||||
{
|
||||
// A missed scan is not caught up: the next one comes within minutes and SchedulerHost scans once at start.
|
||||
new(ArchiveScan, "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(ScanMinutes, RecurrenceUnit.Minutes), CatchUp: false),
|
||||
new(UploadCleanup, "Upload clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.Interval(UploadSweepHours, RecurrenceUnit.Hours),
|
||||
new ScheduleParametersDto(OlderThanDays: UploadMaintenance.FinishedRetentionDays, Steps: [UploadCleanupStep.StepName])),
|
||||
};
|
||||
// PostgreSQL is backed up with its own tools (BRIEF §6.2): no schedule that could never run. Seeded due at once
|
||||
// when the newest copy is a day old, as the daily loop it replaced made one at start.
|
||||
if (DatabaseBackups.Unavailable(_db) is null)
|
||||
{
|
||||
list.Add(new(IndexBackup, "Index backup", ScheduleActions.Backup, ScheduleRecurrence.DailyAt(nightly.Backup),
|
||||
new ScheduleParametersDto(Keep: DatabaseBackups.Keep), LastDone: DatabaseBackups.Newest(_db, _archives?.BackupDirectory)));
|
||||
}
|
||||
list.Add(new(Housekeeping, "Housekeeping", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(nightly.History),
|
||||
new ScheduleParametersDto(OlderThanDays: _options.JobHistoryDays, Steps: [Chronos.Data.Housekeeping.CleanupSteps.JobHistory])));
|
||||
var audit = _options.AuditRetentionDays;
|
||||
list.Add(new(AuditCleanup, "Audit log clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(nightly.Audit),
|
||||
new ScheduleParametersDto(OlderThanDays: audit, Steps: [Chronos.Data.Housekeeping.CleanupSteps.Audit]), Enabled: audit > 0));
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The served archive, after taking the settings another writer sharing it (a desktop) put into its archive.json, as
|
||||
/// the former polling did; while it is offline, or the file cannot be read, as the index has it.
|
||||
/// </summary>
|
||||
public async ValueTask<Archive?> GetArchiveAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var current = _archive.Current;
|
||||
if (_archives is null || ArchiveService.GetAvailability(current) == ArchiveAvailability.Offline) return current;
|
||||
try
|
||||
{
|
||||
return await _archive.RefreshAsync(_archives, _db, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogWarning(ex, "The settings in the archive's archive.json could not be read; schedules use those of the index");
|
||||
return _archive.Current;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The server runs every action it has a handler for; the scheduler finds the rest out itself.</summary>
|
||||
public string? Unavailable(string action) => null;
|
||||
|
||||
/// <summary>The server has no such setting: a scan schedule's own <c>deep</c> parameter decides, off when unset.</summary>
|
||||
public bool DeepAnalysisAfterScan => false;
|
||||
|
||||
/// <summary>
|
||||
/// The age limit of the system schedule <paramref name="systemKey"/> that an environment variable fixes
|
||||
/// (<c>CHRONOS_AUDIT_RETENTION_DAYS</c> for <see cref="AuditCleanup"/>); null when the schedule's own value applies.
|
||||
/// </summary>
|
||||
public LockedAge? LockedAgeOf(string? systemKey) =>
|
||||
systemKey == AuditCleanup && _options.Locked.Contains(nameof(ServerOptions.AuditRetentionDays))
|
||||
? new LockedAge(nameof(ServerOptions.AuditRetentionDays), ServerOptions.AuditRetentionVariable, _options.AuditRetentionDays)
|
||||
: null;
|
||||
|
||||
/// <summary>
|
||||
/// The steps the age limit of the system schedule <paramref name="systemKey"/> deletes with: its default steps
|
||||
/// (<see cref="SystemSchedules"/>), <c>audit</c> for <see cref="AuditCleanup"/>; none for another key.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> AgedSteps(string? systemKey) =>
|
||||
SystemSchedules.FirstOrDefault(s => s.SystemKey == systemKey)?.Parameters?.Steps ?? [];
|
||||
|
||||
/// <summary>
|
||||
/// The zone of schedule times: the process's local zone (TZ in a container), by its IANA id where the platform maps it
|
||||
/// (the admin panel formats times with it); UTC, with a warning, when TZ names a zone this system does not know (no
|
||||
/// tzdata in the image).
|
||||
/// </summary>
|
||||
public static TimeZoneInfo ResolveTimeZone(string? tz, ILogger logger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(logger);
|
||||
var name = tz?.Trim().TrimStart(':');
|
||||
// TZ may also be a path to a zone file, which the runtime reads itself.
|
||||
if (!string.IsNullOrEmpty(name) && !Path.IsPathRooted(name) && !OperatingSystem.IsWindows() && !TimeZoneInfo.TryFindSystemTimeZoneById(name, out _))
|
||||
{
|
||||
logger.LogWarning("TZ is {Zone}, a time zone this system does not know (is tzdata installed?): schedules run in UTC", name);
|
||||
return TimeZoneInfo.Utc;
|
||||
}
|
||||
var local = TimeZoneInfo.Local;
|
||||
if (!local.HasIanaId && TimeZoneInfo.TryConvertWindowsIdToIanaId(local.Id, out var iana) && TimeZoneInfo.TryFindSystemTimeZoneById(iana, out var zone))
|
||||
return zone;
|
||||
return local;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using Chronos.Core.Imaging.Decoders;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Housekeeping;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Server.Configuration;
|
||||
|
||||
@@ -8,10 +9,11 @@ namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// The archive engine behind the server (BRIEF §7, §14.4): ingest of verified uploads, lookup of proxies and
|
||||
/// thumbnails, its job handlers (scan, rebuild, verify, import, thumbnails, proxies, maintenance) and the periodic
|
||||
/// incremental scan (<see cref="ArchivePolling"/>); a scan queues thumbnails and proxies of what it indexes, as an upload
|
||||
/// does. Decoding is managed only (BRIEF §4.2). The daily backup of an SQLite index runs with it
|
||||
/// (<see cref="DatabaseBackupService"/>).
|
||||
/// thumbnails, and its job handlers (scan, rebuild, verify, import, thumbnails, proxies, maintenance, the duplicates and
|
||||
/// orphans reports, index backups and clean-ups with the server's own steps, the <see cref="ICleanupStep"/>s in DI); a scan
|
||||
/// queues thumbnails and proxies of what it indexes, as an upload does. Decoding is managed only (BRIEF §4.2). Recurring
|
||||
/// work (the periodic scan, the nightly backup of an SQLite index, clean-ups) is queued by the server's system schedules
|
||||
/// (<see cref="Jobs.ServerScheduleHost"/>, owner review 2, R10).
|
||||
/// </summary>
|
||||
public static class ArchiveModule
|
||||
{
|
||||
@@ -24,14 +26,19 @@ public static class ArchiveModule
|
||||
{
|
||||
var options = sp.GetRequiredService<ServerOptions>();
|
||||
// Photos the running job processes at once: the settings' value as it is when each sequence starts (owner review 1).
|
||||
return new ArchiveService(sp.GetRequiredService<ChronosDatabase>(),
|
||||
new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = Owner, ImagesAfterScan = true, Parallelism = () => options.Parallelism });
|
||||
return new ArchiveService(sp.GetRequiredService<ChronosDatabase>(), new ArchiveServiceOptions
|
||||
{
|
||||
Decoder = DecoderFactory.CreateServer(),
|
||||
Owner = Owner,
|
||||
ImagesAfterScan = true,
|
||||
Parallelism = () => options.Parallelism,
|
||||
CleanupSteps = [.. sp.GetServices<ICleanupStep>()],
|
||||
// Next to the index in the data folder, where the daily backups always went.
|
||||
BackupDirectory = Path.Combine(options.DataPath, DatabaseBackups.DirectoryName),
|
||||
});
|
||||
});
|
||||
services.AddSingleton<IArchiveIngest>(sp => sp.GetRequiredService<ArchiveService>().Ingest);
|
||||
services.AddSingleton<IJobHandlerProvider>(sp => sp.GetRequiredService<ArchiveService>());
|
||||
services.AddSingleton<IFrameAssetLocator, ArchiveAssetLocator>();
|
||||
services.AddHostedService<DatabaseBackupService>();
|
||||
services.AddSingleton<ArchivePolling>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<ArchivePolling>());
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Server.Jobs;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Polls the archive (BRIEF §7: by modification time and size, no file-system watchers): an incremental scan at start
|
||||
/// and every <see cref="Interval"/> while the archive is online, so photos already in an adopted folder and sequences
|
||||
/// another writer adds (a desktop sharing the archive, files copied in by hand) are indexed without an administrator's
|
||||
/// rescan. Settings such a writer changed in archive.json reach the index first, so uploads and the admin panel follow
|
||||
/// them. A scan or rebuild of the archive that is waiting, running or paused is not queued again.
|
||||
/// </summary>
|
||||
public sealed class ArchivePolling(ChronosDatabase db, ServerArchive archive, ArchiveService archives, JobEngineHost jobs, TimeProvider time,
|
||||
ILogger<ArchivePolling> logger)
|
||||
: BackgroundService
|
||||
{
|
||||
/// <summary>The desktop's rhythm (it polls its archive the same way).</summary>
|
||||
public static readonly TimeSpan Interval = TimeSpan.FromMinutes(10);
|
||||
|
||||
private static readonly JobState[] Pending = [JobState.Queued, JobState.Running, JobState.Paused];
|
||||
|
||||
/// <summary>Queues an incremental scan of an online archive unless one is pending; returns it, or null when none was queued.</summary>
|
||||
public async Task<Job?> PollAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (!jobs.CanRun(JobKind.Scan)) return null;
|
||||
var current = archive.Current;
|
||||
if (ArchiveService.GetAvailability(current) != ArchiveAvailability.Online) return null;
|
||||
current = await archive.RefreshAsync(archives, db, cancellationToken);
|
||||
foreach (var kind in new[] { JobKind.Scan, JobKind.Rebuild })
|
||||
{
|
||||
foreach (var state in Pending)
|
||||
{
|
||||
if ((await db.Jobs.ListAsync(state, kind, 50, null, cancellationToken)).Items.Any(j => j.TargetIds.Contains(current.Id))) return null;
|
||||
}
|
||||
}
|
||||
var scan = ArchiveJobs.Scan(current);
|
||||
// Behind what users asked for (BRIEF §14.6).
|
||||
return await jobs.Engine.EnqueueAsync(scan.Kind, scan.Targets, scan.Label, scan.ParametersJson, JobPriority.Background,
|
||||
cancellationToken: cancellationToken);
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
await PollAsync(stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "The archive could not be polled");
|
||||
}
|
||||
try
|
||||
{
|
||||
await Task.Delay(Interval, time, stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
using Chronos.Data;
|
||||
using Chronos.Server.Configuration;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// The daily <c>VACUUM INTO</c> copy of the index of a Windows server on SQLite (BRIEF §6.2: nightly, kept ×3) into
|
||||
/// <c>{DataPath}/backups</c>. A server on PostgreSQL is backed up with PostgreSQL's own tools; this service then does nothing.
|
||||
/// </summary>
|
||||
public sealed class DatabaseBackupService(ChronosDatabase db, ServerOptions options, TimeProvider time, ILogger<DatabaseBackupService> logger) : BackgroundService
|
||||
{
|
||||
/// <summary>Folder of the copies.</summary>
|
||||
public string Directory => Path.Combine(options.DataPath, "backups");
|
||||
|
||||
protected override Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
if (db.Dialect != Dialect.Sqlite) return Task.CompletedTask;
|
||||
logger.LogInformation("Daily index backups go to {Directory}", Directory);
|
||||
return DatabaseBackups.RunDailyAsync(db, Directory, time, stoppingToken);
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ public sealed class ServerArchive(Archive archive)
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="Current"/> once it and the index row hold the settings another writer sharing the archive (a desktop)
|
||||
/// put into its archive.json (<see cref="ArchiveService.RefreshSettingsAsync"/>): uploads, the polling and the admin
|
||||
/// put into its archive.json (<see cref="ArchiveService.RefreshSettingsAsync"/>): uploads, the schedules and the admin
|
||||
/// panel, whose form saves every field, never work from older ones. Unchanged while the file cannot be read.
|
||||
/// </summary>
|
||||
public async Task<Archive> RefreshAsync(ArchiveService archives, ChronosDatabase db, CancellationToken cancellationToken)
|
||||
|
||||
@@ -1,20 +1,28 @@
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Housekeeping;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Server.Configuration;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>What one sweep of <see cref="UploadMaintenance.SweepAsync"/> removed.</summary>
|
||||
public sealed record UploadSweep(int Expired, int Files, int Records, int Tokens);
|
||||
|
||||
/// <summary>
|
||||
/// Upload housekeeping (BRIEF §14.4): at start, uploads a crash left half-committed are settled; then every half hour
|
||||
/// abandoned uploads expire, orphaned partial and staging files are removed, old upload records and dead tokens purged.
|
||||
/// Upload housekeeping (BRIEF §14.4): at start, uploads a crash left half-committed are settled; the sweep (abandoned
|
||||
/// uploads expire, orphaned partial and staging files are removed, old upload records and dead tokens purged) is the
|
||||
/// <see cref="UploadCleanupStep"/> of the <c>upload-cleanup</c> system schedule (owner review 2, R10), no longer a timer.
|
||||
/// </summary>
|
||||
public sealed class UploadMaintenance(ChronosDatabase db, ServerOptions options, ServerArchive archive, UploadStore store, TimeProvider time,
|
||||
ILogger<UploadMaintenance> logger)
|
||||
: BackgroundService
|
||||
{
|
||||
private static readonly TimeSpan Interval = TimeSpan.FromMinutes(30);
|
||||
private static readonly TimeSpan FinishedRetention = TimeSpan.FromDays(90);
|
||||
/// <summary>Days a finished upload's record is kept unless the schedule says otherwise.</summary>
|
||||
public const int FinishedRetentionDays = 90;
|
||||
|
||||
private static readonly TimeSpan StagingRetention = TimeSpan.FromDays(1);
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
@@ -27,22 +35,6 @@ public sealed class UploadMaintenance(ChronosDatabase db, ServerOptions options,
|
||||
{
|
||||
logger.LogError(ex, "Upload recovery failed");
|
||||
}
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await SweepAsync(stoppingToken);
|
||||
await Task.Delay(Interval, time, stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Upload cleanup failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -77,7 +69,12 @@ public sealed class UploadMaintenance(ChronosDatabase db, ServerOptions options,
|
||||
return UploadRules.StandIn(archive.Root, copies, target);
|
||||
}
|
||||
|
||||
public async Task SweepAsync(CancellationToken cancellationToken)
|
||||
/// <summary>
|
||||
/// Expires uploads untouched for <see cref="ServerOptions.UploadRetentionHours"/>, deletes partial files no upload
|
||||
/// receives into and this server's staging files older than a day, purges the records of uploads finished more than
|
||||
/// <paramref name="finishedDays"/> days ago (0 keeps them) and expired tokens. Safe to run at any time.
|
||||
/// </summary>
|
||||
public async Task<UploadSweep> SweepAsync(int finishedDays = FinishedRetentionDays, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var now = time.GetUtcNow();
|
||||
var abandonedBefore = now - TimeSpan.FromHours(options.UploadRetentionHours);
|
||||
@@ -92,23 +89,49 @@ public sealed class UploadMaintenance(ChronosDatabase db, ServerOptions options,
|
||||
var active = new HashSet<Guid>();
|
||||
foreach (var state in new[] { UploadState.Receiving, UploadState.Committing })
|
||||
active.UnionWith((await db.Uploads.ListByStateAsync(state, cancellationToken)).Select(u => u.Id));
|
||||
var files = 0;
|
||||
foreach (var (id, _) in store.List().ToList())
|
||||
{
|
||||
if (!active.Contains(id)) store.Delete(id);
|
||||
if (active.Contains(id)) continue;
|
||||
store.Delete(id);
|
||||
if (!store.Exists(id)) files++;
|
||||
}
|
||||
if (Directory.Exists(options.StagingPath))
|
||||
{
|
||||
// Only this server's staging files (named by upload id) are touched; clients may share the archive.
|
||||
foreach (var file in new DirectoryInfo(options.StagingPath).EnumerateFiles())
|
||||
{
|
||||
if (Guid.TryParseExact(Path.GetFileNameWithoutExtension(file.Name), "N", out var id) && !active.Contains(id)
|
||||
&& file.LastWriteTimeUtc < now.UtcDateTime - StagingRetention)
|
||||
UploadStore.TryDelete(file.FullName);
|
||||
if (!Guid.TryParseExact(Path.GetFileNameWithoutExtension(file.Name), "N", out var id) || active.Contains(id)
|
||||
|| file.LastWriteTimeUtc >= now.UtcDateTime - StagingRetention)
|
||||
continue;
|
||||
UploadStore.TryDelete(file.FullName);
|
||||
if (!File.Exists(file.FullName)) files++;
|
||||
}
|
||||
}
|
||||
|
||||
await db.Uploads.PurgeFinishedAsync(now - FinishedRetention, cancellationToken);
|
||||
await db.Tokens.PurgeAsync(now, cancellationToken);
|
||||
var records = finishedDays > 0 ? await db.Uploads.PurgeFinishedAsync(now - TimeSpan.FromDays(finishedDays), cancellationToken) : 0;
|
||||
var tokens = await db.Tokens.PurgeAsync(now, cancellationToken);
|
||||
if (expired > 0) logger.LogInformation("Expired {Count} abandoned upload(s)", expired);
|
||||
return new UploadSweep(expired, files, records, tokens);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The server's own clean-up step <c>uploads</c> (owner review 2, R10): <see cref="UploadMaintenance.SweepAsync"/>, with the
|
||||
/// clean-up's age limit as the days finished upload records are kept. It deletes only what uploads left behind, never a
|
||||
/// photo of the archive.
|
||||
/// </summary>
|
||||
public sealed class UploadCleanupStep(UploadMaintenance maintenance) : ICleanupStep
|
||||
{
|
||||
public const string StepName = "uploads";
|
||||
|
||||
public string Name => StepName;
|
||||
|
||||
public async Task<string> RunAsync(CleanupContext context, CleanupParameters parameters)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
ArgumentNullException.ThrowIfNull(parameters);
|
||||
var sweep = await maintenance.SweepAsync(parameters.OlderThanDays, context.Cancellation).ConfigureAwait(false);
|
||||
return Loc.L("Server.Log.UploadsSwept", sweep.Expired, sweep.Files, sweep.Records, sweep.Tokens);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user