The desktop now uses the per-home layout from P3.1: each home keeps its own projects, proxies and originals, and a server is known by its id whichever address reaches it. - Settings keep the known servers (id, name, last address, certificate, aliases, originals archive). Reset and Import keep them; Export leaves them out. - SyncHost records each server the first time it signs in with an id. It names the cache and workspace folders by that id, and re-keys the folders a server had under its addresses at sign-in. The re-key waits while transfer or workspace jobs are pending. - Download originals goes to the server's own archive. It is created beside this PC's archive at the first download, and a toast says where. A sequence that already has a local copy keeps receiving into that copy's archive. A server without an id keeps the 1.0 behaviour. - At start, after the index opens and before any job runs, the folders are sorted into their homes. A toast reports the result: sorted, pending or failed. - The workspace host gives each home's store its own sync. Find, List, usage, clean-up and the trash plan and empty cover every home. Server comparisons go through the identity, so a project stays Online when its server is reached by another address. - The render-node downloads and the server import staging move into the server's folder of the cache. The cache trim keeps `servers`, and the scheduled scan also scans the originals archives. - Settings shows the Home folders rows (Workspace) and the Known servers table (Server). The diagnostics bundle lists the homes. - The dead `AppPaths.CreateDirectories` and `ThumbnailsDirectory` are removed. Refs #66 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
146 lines
8.6 KiB
C#
146 lines
8.6 KiB
C#
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, 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
|
||
/// (<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>
|
||
/// 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 (<see cref="WorkspaceCleanStep"/>), and a report of its trash (<see cref="WorkspaceTrashStep"/>),
|
||
/// which it never empties. It runs whether an archive is open or not.
|
||
/// </summary>
|
||
public const string WorkspaceCleanup = "workspace-cleanup";
|
||
|
||
/// <summary>When the workspace clean-up runs: after the housekeeping.</summary>
|
||
public static readonly TimeOnly WorkspaceCleanupTime = new(4, 30);
|
||
|
||
/// <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)),
|
||
// 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<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 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<Guid>().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;
|
||
}
|
||
}
|
||
|
||
/// <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, in the former shared folders and in each server's own (<c>servers</c>,
|
||
/// owner review 5); 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", Chronos.Core.IO.HomeFolders.Servers];
|
||
|
||
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));
|
||
}
|