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;
///
/// The desktop's (owner review 2, R10). Times are the PC's; schedules work on the archive at
/// Settings › Archive's folder (), 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, , once:
/// a row that exists keeps the user's edits), the daily index backup, the housekeeping clean-up at 04:00 (job history,
/// cache trim), and the workspace's clean-up at 04:30 (phase 5c: its media, a report of its trash). Scans give what they find a deep analysis as Settings › Analysis › After a scan says at each run
/// (), like the scans started by hand. Thread-safe: the scheduler calls it from its loop.
///
public sealed class DesktopScheduleHost(AppSettings settings, Func database, Func archives) : IScheduleHost
{
/// Incremental scan of the archive, every (10) minutes, no catch-up.
public const string ArchiveScan = "archive-scan";
///
/// 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.
///
public const string IndexBackup = DatabaseBackups.ScheduleKey;
/// Clean-up of the job history and the cache, daily at 04:00, with catch-up.
public const string Housekeeping = "housekeeping";
/// When the housekeeping runs.
public static readonly TimeOnly HousekeepingTime = new(4, 0);
///
/// Clean-up of the workspace (phase 5c), daily at 04:30, with catch-up: the media of projects past Settings › Workspace ›
/// Clean after or Size limit (), and a report of its trash (),
/// which it never empties. It runs whether an archive is open or not.
///
public const string WorkspaceCleanup = "workspace-cleanup";
/// When the workspace clean-up runs: after the housekeeping.
public static readonly TimeOnly WorkspaceCleanupTime = new(4, 30);
/// The PC's zone; tests set another.
public TimeZoneInfo TimeZone { get; init; } = TimeZoneInfo.Local;
public IReadOnlyList 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)),
// The ages and the limit are Settings › Workspace's, read at each run: the schedule holds no days of its own.
new(WorkspaceCleanup, "Workspace clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(WorkspaceCleanupTime),
new ScheduleParametersDto(Steps: [WorkspaceCleanStep.StepName, WorkspaceTrashStep.StepName], OlderThanDays: 0)),
];
public IReadOnlyList CleanupSteps => archives()?.CleanupSteps.Select(s => s.Name).ToList() ?? [];
///
/// 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).
///
public static int ScanMinutes(AppSettings settings)
{
ArgumentNullException.ThrowIfNull(settings);
return int.Clamp(settings.ScanIntervalMinutes, ScheduleRecurrence.MinMinutes, ScheduleRecurrence.MaxMinutes);
}
public async ValueTask GetArchiveAsync(CancellationToken cancellationToken)
{
if (database() is not { } db || archives() is not { } service) return null;
var listed = await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false);
// Never a server's originals archive in place of this PC's (owner review 5): the app scans those after this one.
var originals = settings.KnownServers.Select(k => k.OriginalsArchiveId).OfType().ToHashSet();
var archive = (settings.LastArchivePath is { Length: > 0 } last ? CurrentArchive.At(listed, last) : null)
?? CurrentArchive.Pick([.. listed.Where(a => !originals.Contains(a.Id))], null) ?? CurrentArchive.Pick(listed, null);
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;
}
}
/// The desktop runs every action its engine has a handler for.
public string? Unavailable(string action) => null;
/// Settings › Analysis › After a scan, read at every run: a scheduled scan follows it as a scan started by hand does.
public bool DeepAnalysisAfterScan => settings.DeepAnalysisAfterScan;
}
///
/// The desktop's clean-up step cache-trim (owner review 2, R10): brings the cache folder down to Settings › Storage ›
/// Cache limit, oldest files first, skipping files in use (). 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, in the former shared folders and in each server's own (servers,
/// owner review 5); Settings › Storage › Clear still empties everything.
///
public sealed class CacheTrimStep(Func folder, Func limitBytes) : ICleanupStep
{
public const string StepName = "cache-trim";
/// Folders of the cache the trim leaves whole.
public static IReadOnlyList Kept { get; } = ["proxies", "render-node", "server-import", Chronos.Core.IO.HomeFolders.Servers];
public string Name => StepName;
public Task 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);
}
/// "12.4 GB" in the binary gigabytes of Settings › Storage › Cache limit.
private static string Gigabytes(long bytes) => Loc.L("Common.Size.GB", (bytes / (double)(1L << 30)).ToString("0.#", Loc.Culture));
}