From f30eb2904acb7f8d4b5062ab75cc777b71840609 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Sun, 15 Nov 2026 16:19:56 +0100 Subject: [PATCH] fix: address the owner review 5 review Setup: a kept 1.0 Uploader no longer fixes the scope and folder, the Remove tooltip promises kept files only with a hashed log, and a single-program setup preselects it. The Uploader always downloads the setup. Sync links move to the server id at every sign-in while folders wait for jobs and open editors; jobs of a pending homes sort still find their projects. A shared library exposes only the shared archive's client-visible jobs and events, render nodes take only client renders, and the share counts as its own while starting. Progress: a new step waits a quarter interval and a trailing timer publishes the last state; the job bar tooltip carries the whole line; Recent maintenance and the Server jobs list pick up jobs that start while they are shown. Refs #64 #65 #66 #67 Co-Authored-By: Claude Opus 5.5 --- docs/BRIEF.md | 4 +- docs/CHANGELOG.md | 26 ++++- docs/DECISIONS.md | 10 ++ i18n/en/Tooltips.resx | 3 +- i18n/it/Tooltips.it.resx | 3 +- src/Chronos.App/Archive/MaintenanceReports.cs | 13 +++ .../Editor/WorkspaceSequenceSource.cs | 7 +- src/Chronos.App/Jobs/JobText.cs | 9 +- src/Chronos.App/Sections/ArchiveViewModel.cs | 24 ++++- src/Chronos.App/Sections/JobsViewModel.cs | 3 +- src/Chronos.App/Sections/SequenceViewModel.cs | 6 +- src/Chronos.App/Server/LibraryShare.cs | 16 ++- src/Chronos.App/Server/ServerJobsViewModel.cs | 63 ++++++++++-- src/Chronos.App/Server/SyncHost.cs | 21 ++-- src/Chronos.App/Shell/MainWindow.xaml | 2 +- src/Chronos.App/Shell/ShellViewModel.cs | 12 ++- src/Chronos.App/Workspace/WorkspaceHost.cs | 40 ++++++++ src/Chronos.Data/Homes/HomeLayoutMigration.cs | 32 ++++-- src/Chronos.Data/Jobs/JobEngine.cs | 10 +- src/Chronos.Data/Jobs/JobHandler.cs | 73 ++++++++++++-- .../Workspaces/WorkspaceCopyJobHandler.cs | 6 +- .../Workspaces/WorkspaceRenderJobHandler.cs | 2 +- .../Workspaces/WorkspaceSendJobHandler.cs | 2 +- src/Chronos.Data/Workspaces/WorkspaceStore.cs | 14 +++ src/Chronos.Server/Api/JobEndpoints.cs | 16 ++- src/Chronos.Server/Hosting/HostedServer.cs | 4 +- src/Chronos.Server/Hosting/ServerHost.cs | 6 +- src/Chronos.Server/Jobs/JobEngineHost.cs | 99 ++++++++++++++++++- src/Chronos.Server/Jobs/ProgressGate.cs | 12 ++- src/Chronos.Server/Jobs/RenderNodeService.cs | 5 + .../Storage/ServerEventBridge.cs | 22 +++-- src/Chronos.Setup/Engine/InstallPlan.cs | 23 +++-- src/Chronos.Setup/Engine/SilentSetup.cs | 8 ++ src/Chronos.Setup/Views/SetupViewModel.cs | 27 ++++- .../Commands/PackInstallerCommand.cs | 7 +- src/Chronos.Uploader/App.xaml.cs | 2 +- .../Infrastructure/UploaderUpdates.cs | 14 +-- .../Shell/UpdatesViewModel.cs | 10 +- .../Archive/ArchiveLogicTests.cs | 24 +++++ tests/Chronos.App.Tests/Jobs/JobTextTests.cs | 15 +++ .../Jobs/ServerJobsListTests.cs | 18 ++++ .../Setup/SingleSetupTests.cs | 43 ++++++++ .../Uploader/UploaderUpdatesTests.cs | 11 ++- .../Workspace/WorkspaceHostTests.cs | 19 ++++ .../Homes/HomeLayoutMigrationTests.cs | 5 + .../Jobs/JobContextProgressTests.cs | 50 +++++++++- .../Jobs/JobThroughputTests.cs | 59 ++++++++++- .../Sync/SyncLinkRekeyTests.cs | 30 ++++++ .../Events/ProgressEventTests.cs | 17 ++++ .../Hosting/HostedServerTests.cs | 54 ++++++++++ .../PackInstallerCommandTests.cs | 16 +++ 51 files changed, 895 insertions(+), 122 deletions(-) diff --git a/docs/BRIEF.md b/docs/BRIEF.md index 8a404599..3591e49b 100644 --- a/docs/BRIEF.md +++ b/docs/BRIEF.md @@ -3237,8 +3237,8 @@ merged into it at the first update. 2026-10-23, R2.) Chronos Uploader checks too (amended 2026-11-15, owner review 5 R1): Settings › Updates with *Check on start* (setting `CheckForUpdates`, on by default, so a 1.0 `uploader.json` without it opts in), *Check now*, *Download* and *Show setup*, through - the same `UpdateFlow`, feed and `Chronos-Setup-*` asset (the portable zip for a portable - copy) verified against `SHA256SUMS` in `%TEMP%\Chronos\updates`; a newer release found at + the same `UpdateFlow`, feed and `Chronos-Setup-*` asset (a portable Uploader too: the + portable zip holds no Uploader) verified against `SHA256SUMS` in `%TEMP%\Chronos\updates`; a newer release found at start shows an in-window toast with *Download*. The start-up check is skipped when `Chronos.exe` sits in the Uploader's folder (the desktop's notice covers the same setup); *Check now* is always offered. The update code lives in `Chronos.Core/Updates` and diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index e5488db2..3fd72db4 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -14,13 +14,13 @@ separate Uploader and later updates come through the Uploader's own check. ### Added - **One setup** (R1, #64): - One setup installs Chronos Desktop, Chronos Uploader or both, and adds or removes either in place. Only Chronos - Desktop is preselected; `/COMPONENTS=Desktop,Uploader` works. + Desktop is preselected (a setup that holds one program preselects it); `/COMPONENTS=Desktop,Uploader` works. - The setup shows what an update changes (programs added, removed or replaced) before it runs. With every program unticked it offers Uninstall. - A file you changed since setup installed it is never deleted ("N changed files kept"). - **Uploader updates** (R1, #64): Chronos Uploader checks for updates. Settings › Updates has Check on start (on by - default), Check now, Download and Show setup. Download fetches the single Chronos setup (the portable zip for a - portable copy), verifies it against the release's `SHA256SUMS` and shows it in Explorer. A newer release found at + default), Check now, Download and Show setup. Download fetches the single Chronos setup (a portable copy too: the + portable zip holds no Uploader), verifies it against the release's `SHA256SUMS` and shows it in Explorer. A newer release found at start shows a toast with Download. - **What a job does now** (R2, #65): - Every job reports a structured progress detail: step, item, photo x of y, and sequence, folder, output or step n @@ -74,8 +74,11 @@ separate Uploader and later updates come through the Uploader's own check. - Duplicates, orphans and index backup jobs report no total while running, so the bar runs without a count instead of standing at 0 %. - Thumbnail and proxy passes report every frame, not only at checkpoints. - - The job bar keeps at most 60 characters of the status line, dropping the item first; its tooltip is the whole bar - text. Recent maintenance updates live, at most twice a second. + - A new step goes out once a quarter of a second has passed since the last publish, and a job gone quiet shows its + latest state within half a second. + - The job bar keeps at most 60 characters of the status line, dropping the item first; its tooltip is the whole line + with the item. Recent maintenance updates live, at most twice a second, and a maintenance job queued while the + screen is shown joins it. - **Homes** (R3, #66): - On first start, 1.1 sorts a 1.0 workspace and cache into homes. It only renames, checks every rename, and resumes after a crash. Projects in use, an unplugged workspace drive and an unfinished workspace move wait for a later @@ -109,6 +112,19 @@ separate Uploader and later updates come through the Uploader's own check. ### Fixed - The job bar counter of byte jobs (verify, import) shows sizes, not raw byte counts. +- Owner review 5 review: + - Keeping a 1.0 Chronos Uploader (Uploader unticked) no longer fixes the setup's scope and folder to the Uploader's; + `/DIR` and `/ALLUSERS` are ignored, with a log line, only when the Uploader replaces it. + - The Changes row's Remove tooltip no longer promises that changed files are kept when the install log has no + hashes (a 1.0 log). + - A setup built for the Uploader alone preselects it. + - Links move to the server's ID at every sign-in; the workspace folders wait while a copy, send or render job is + pending or a project is open in the editor. + - Workspace copy, send and render jobs of a sorted 1.0 workspace find their projects while folders are pending. + - While sharing, clients receive no events for the desktop's own jobs, the workspace's or another archive's, and + render nodes take only renders queued by a client on the shared archive. + - The desktop recognises its own share while it is still starting. + - The Server section lists a job that started between its list and its live events once the job reports progress. - Signing in to the same server at another address, or by name and by IP, no longer shows its workspace projects as offline, nor gives it a second set of links, projects and proxy cache (the phase 5b limitation). diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 74352d8e..a390f98b 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -882,3 +882,13 @@ One line per decision: date · decision · alternative · reason. | 2026-11-15 | Not built in v1.1 yet: the tray lifetime for sharing (closing the window stops it), the firewall status row, the 1.0 service probe in the desktop, in-process refresh of the Library on client changes | Hold the release for them | The share works while the window is open; each is a follow-up issue | | 2026-11-15 | Owner review 5 merge: the parcels ran in parallel worktrees with per-file ownership and were merged in the order p1b, p1a, p21, p22, p23, p4 (with p31, p32); Tooltips rows were inserted in sorted position per key prefix, never `i18n prune`; the unused `Server.Service.*` keys were removed line by line in all 38 cultures; the 36 other cultures, docs and baselines are done once at the merge step | Sequential parcels | Four issues in one release; ownership kept the merges to three conflicts | | 2026-11-15 | The sample data applies `SampleJobDetails` to every sample job, the server transfer jobs included | Only `Jobs()` | The Server screen's running upload and paused download show the detail like the Jobs screen | +| 2026-11-15 | A new step bypasses the twice-a-second publish gate only once a quarter interval (125 ms) has passed, in JobContext and in the server's ProgressGate; a dropped report arms a one-shot timer that publishes the latest state when the interval falls due | Every new step at once; no trailing publish | Jobs that alternate steps per item published at every report; a job that went quiet after a dropped report showed a stale step for minutes | +| 2026-11-15 | Chronos Uploader always downloads `Chronos-Setup-*`, portable or not (amends the Uploader update row above) | The portable zip for a portable Uploader | The portable zip holds only Chronos Desktop; a portable Uploader updated from it stays at its version | +| 2026-11-15 | A 1.0 Uploader fixes the setup's scope and folder only when the Uploader is ticked (and replaces it); unticking it frees them again, and ticking it back resets them to the 1.0 copy's | Always fixed by a found 1.0 Uploader | A desktop-only install would land in the Uploader's folder and scope for no reason | +| 2026-11-15 | The Remove tooltip of the Changes row says changed files are kept only when the install log has per-file hashes (format 2); a format-1 log gets a tooltip without that promise | One tooltip | A 1.0 log has no hashes: every file is removed | +| 2026-11-15 | pack-installer preselects the component of a single-component payload | Desktop always preselected | A setup of the Uploader alone opened with nothing ticked, offering Uninstall | +| 2026-11-15 | Sync links are re-keyed to `id:` at every sign-in; the workspace folders are re-keyed only when no copy, send or render job is pending and no project is open in the editor (`WorkspaceHost.HoldInEditor`), else at a later sign-in | Hold links and folders together; lock the folder per project | Links never depend on the folders, and a held link re-key left the server's projects offline until every job ended; an editor writes in its folder without a job | +| 2026-11-15 | Workspace copy, send and render jobs open a split homes parent through the legacy-view store (`WorkspaceStore.ForJob`) | Fail until the migration completes | A pending 1.0 sort leaves the projects in the parent; their jobs must still run | +| 2026-11-15 | While sharing, the job events and the job API expose only kinds clients may see whose first target is the shared archive or one of its sequences; sequence and project events skip sequences of other archives; render nodes never take a render without `CreatedBy` (the desktop's own) or of a sequence the share does not own | Expose every job of the engine | The desktop's engine also runs its workspace and private jobs; clients must not see or take them | +| 2026-11-15 | The desktop counts its share as its own from the moment the hosted server is built, not only once it has started | Only after start | A LAN beacon or a sign-in during the start would otherwise reach itself | +| 2026-11-15 | The Server section reads a job it does not list once, on its first progress event, and lists it if running or paused | Reload the list on unknown progress | A job that started between the list and the event socket stayed hidden until the next reload; one read per job is cheap | diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index b81501f7..d900793e 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -896,6 +896,7 @@ The separate copy in {0} is installed for all users, so it stays · remove it in Settings › Apps Removes its files and shortcuts · a file changed since setup installed it is kept · your data is kept Removes {0} and the Windows service that runs it · its data in %ProgramData%\Chronos Server is kept + Removes its files and shortcuts · your data is kept Moves the separate copy in {0} here with its sign-in entry and shortcuts, then removes it · your data is kept Close setup Ask the running programs to close · each one handles its unsaved work @@ -974,9 +975,7 @@ Look for a newer Chronos release when the Uploader starts · skipped when Chronos Desktop is installed alongside, whose own notice covers the same setup Download the setup, check it against the release's SHA-256 list and show it in Explorer · {0} Open the page of this release in the browser - Download the portable zip, check it against the release's SHA-256 list and show it in Explorer · {0} The releases page could not be reached · try again later - Show the verified zip in Explorer; close Chronos and the Uploader and unpack it over this folder to upgrade. The data folder is kept Show the verified setup in Explorer; close the Uploader and run it to upgrade. Queue and settings are kept You run the newest stable release Your user name on the Chronos Server diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index 30cadddb..bf528ceb 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -997,6 +997,7 @@ La copia separata in {0} è installata per tutti gli utenti, quindi resta · rimuovila da Impostazioni › App Rimuove i suoi file e collegamenti · un file modificato dopo l'installazione resta · i tuoi dati restano Rimuove {0} e il servizio Windows che lo esegue · i suoi dati in %ProgramData%\Chronos Server restano + Rimuove i suoi file e collegamenti · i tuoi dati restano Sposta qui la copia separata in {0} con la voce di avvio e i collegamenti, poi la rimuove · i tuoi dati restano Chiudi l'installazione Chiedi ai programmi aperti di chiudersi · ognuno gestisce il lavoro non salvato @@ -1075,9 +1076,7 @@ Cerca una versione più recente di Chronos all'avvio dell'Uploader · saltato quando accanto è installato Chronos Desktop, il cui avviso copre lo stesso installer Scarica l'installer, lo confronta con l'elenco SHA-256 della versione e lo mostra in Esplora file · {0} Apre la pagina di questa versione nel browser - Scarica lo zip portatile, lo confronta con l'elenco SHA-256 della versione e lo mostra in Esplora file · {0} Non è stato possibile raggiungere la pagina delle versioni · riprova più tardi - Mostra in Esplora file lo zip verificato; chiudi Chronos e l'Uploader ed estrailo sopra questa cartella per aggiornare. La cartella dei dati resta invariata Mostra in Esplora file l'installer verificato; chiudi l'Uploader ed eseguilo per aggiornare. Coda e impostazioni restano invariate Usi la versione stabile più recente Il tuo nome utente sul Chronos Server diff --git a/src/Chronos.App/Archive/MaintenanceReports.cs b/src/Chronos.App/Archive/MaintenanceReports.cs index 527a94ad..0978a276 100644 --- a/src/Chronos.App/Archive/MaintenanceReports.cs +++ b/src/Chronos.App/Archive/MaintenanceReports.cs @@ -109,6 +109,19 @@ public static class MaintenanceReports return rows; } + /// + /// with in place of its earlier state, or added when it is a maintenance + /// job of not among them yet (queued or started while the screen is shown, owner review 5, + /// #65); itself for any other job. + /// + public static IReadOnlyList Track(IReadOnlyList jobs, Job changed, Guid archiveId) + { + ArgumentNullException.ThrowIfNull(jobs); + ArgumentNullException.ThrowIfNull(changed); + if (!MaintenanceKinds.Contains(changed.Kind) || !changed.TargetIds.Contains(archiveId)) return jobs; + return [changed, .. jobs.Where(j => j.Id != changed.Id)]; + } + /// /// The latest jobs as "Recent maintenance" lines; a running one shows its percentage and what it /// does now from its progress when there is some (owner review 5, #65), else from its stored snapshot. diff --git a/src/Chronos.App/Editor/WorkspaceSequenceSource.cs b/src/Chronos.App/Editor/WorkspaceSequenceSource.cs index 93b4882d..c42c6e36 100644 --- a/src/Chronos.App/Editor/WorkspaceSequenceSource.cs +++ b/src/Chronos.App/Editor/WorkspaceSequenceSource.cs @@ -84,6 +84,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders, private readonly ImageDecoder _decoder; private readonly JobEngine? _engine; private readonly WorkspaceServerHome? _server; + private readonly IDisposable? _hold; private readonly Lock _gate = new(); private readonly List _retired = []; private IRenderFrameSource? _frames; @@ -104,7 +105,9 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders, private int _disposed; /// The server the project's home is (phase 5b); null for a project of this PC's archive. - public WorkspaceSequenceSource(WorkspaceSync sync, Guid projectId, ChronosDatabase db, ImageDecoder decoder, JobEngine? engine, WorkspaceServerHome? server = null) + /// Released when the source is disposed: what marks the project open in the editor (). + public WorkspaceSequenceSource(WorkspaceSync sync, Guid projectId, ChronosDatabase db, ImageDecoder decoder, JobEngine? engine, WorkspaceServerHome? server = null, + IDisposable? hold = null) { ArgumentNullException.ThrowIfNull(sync); ArgumentNullException.ThrowIfNull(db); @@ -114,6 +117,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders, _decoder = decoder; _engine = engine; _server = server; + _hold = hold; ProjectId = projectId; // This PC's engine runs the copies of the media (Update media), whatever the home. if (engine is not null) engine.JobChanged += OnJobChanged; @@ -729,6 +733,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders, public async ValueTask DisposeAsync() { if (Interlocked.Exchange(ref _disposed, 1) == 1) return; + _hold?.Dispose(); if (_engine is not null) _engine.JobChanged -= OnJobChanged; List sources; ServerJobs? jobs; diff --git a/src/Chronos.App/Jobs/JobText.cs b/src/Chronos.App/Jobs/JobText.cs index c6064590..8f64a267 100644 --- a/src/Chronos.App/Jobs/JobText.cs +++ b/src/Chronos.App/Jobs/JobText.cs @@ -210,12 +210,17 @@ public static class JobText /// job does now in place of the counter ("Scan · Archive 2024 · Indexing photo 1,240 of 3,600 · folder 12 of 340 · 41/s · /// 3 min left", at most characters of it); a job that counts bytes shows sizes. /// - public static string Bar(JobEntry entry) + public static string Bar(JobEntry entry) => Bar(entry, BarStatusLength); + + /// The job bar's tooltip: its line with what the job does now whole, the item (sequence, folder) included. + public static string BarToolTip(JobEntry entry) => Bar(entry, int.MaxValue); + + private static string Bar(JobEntry entry, int statusLength) { ArgumentNullException.ThrowIfNull(entry); var parts = new List(5) { Kind(entry.Job.Kind) }; if (!string.IsNullOrWhiteSpace(entry.Job.TargetLabel)) parts.Add(entry.Job.TargetLabel!); - if (Status(entry.Detail, BarStatusLength) is { Length: > 0 } status) parts.Add(status); + if (Status(entry.Detail, statusLength) is { Length: > 0 } status) parts.Add(status); else if (Counter(entry.Job.Kind, entry.Done, entry.Total) is { Length: > 0 } counter) parts.Add(counter); if (Speed(entry.Job.Kind, entry.ItemsPerSecond) is { Length: > 0 } speed) parts.Add(speed); if (entry.Eta is { } eta) parts.Add(Loc.L("Jobs.Bar.Left", Formatting.Duration(eta))); diff --git a/src/Chronos.App/Sections/ArchiveViewModel.cs b/src/Chronos.App/Sections/ArchiveViewModel.cs index 14c5c6ad..677fca87 100644 --- a/src/Chronos.App/Sections/ArchiveViewModel.cs +++ b/src/Chronos.App/Sections/ArchiveViewModel.cs @@ -706,6 +706,24 @@ public sealed class ArchiveViewModel : SectionViewModel _recentThrottle?.Signal(); } + /// A maintenance job changed state: its Recent line shows it, and its progress counts while it runs (UI thread). + private void TrackRecent(Job job) + { + if (_archive is not { } archive || !_loaded) return; + var jobs = MaintenanceReports.Track(_recentJobs, job, archive.Id); + if (ReferenceEquals(jobs, _recentJobs)) return; + _recentJobs = jobs; + var running = new HashSet(Volatile.Read(ref _recentRunning)); + if (job.State == JobState.Running) running.Add(job.Id); + else + { + running.Remove(job.Id); + _recentLive.Remove(job.Id); + } + Volatile.Write(ref _recentRunning, running); + Recent = MaintenanceReports.Recent(_recentJobs, RecentCount, _recentLive); + } + /// The running Recent lines with their latest progress (UI thread). private void FlushRecent() { @@ -720,11 +738,13 @@ public sealed class ArchiveViewModel : SectionViewModel } /// - /// A finished job on this archive or its sequences changes the figures: read them again once the jobs settle (a - /// burst of analyses after an import reloads once). Jobs of other archives are none of this screen's business. + /// A maintenance job of this archive queued, started, paused or ended: its Recent line follows it, live while it runs + /// (owner review 5, #65). A finished job on this archive or its sequences changes the figures: read them again once the + /// jobs settle (a burst of analyses after an import reloads once). Jobs of other archives are none of this screen's business. /// private void OnJobChanged(Job job) { + if (MaintenanceReports.MaintenanceKinds.Contains(job.Kind)) System.Windows.Application.Current?.Dispatcher.BeginInvoke(() => TrackRecent(job)); if (job.State is not (JobState.Done or JobState.Failed)) return; if (job.Kind is not (JobKind.Scan or JobKind.Rebuild or JobKind.Verify or JobKind.Maintenance or JobKind.Import or JobKind.Proxies or JobKind.Thumbs or JobKind.LightAnalyse or JobKind.DeepAnalyse or JobKind.Move or JobKind.Convert)) return; diff --git a/src/Chronos.App/Sections/JobsViewModel.cs b/src/Chronos.App/Sections/JobsViewModel.cs index 33cc5b4e..1c9aa794 100644 --- a/src/Chronos.App/Sections/JobsViewModel.cs +++ b/src/Chronos.App/Sections/JobsViewModel.cs @@ -457,7 +457,8 @@ public sealed class JobsViewModel : SectionViewModel private void UpdateShell() { if (_model.Current is { } current) - Shell.SetJob(JobText.Bar(current), current.Fraction ?? 0, indeterminate: current.Fraction is null, name: JobText.Name(current.Job)); + Shell.SetJob(JobText.Bar(current), current.Fraction ?? 0, indeterminate: current.Fraction is null, name: JobText.Name(current.Job), + toolTip: JobText.BarToolTip(current)); else Shell.SetJob(null, 0); // The status strip and the Running chip count the same jobs: running or paused (Jobs.html). The rail badge adds the diff --git a/src/Chronos.App/Sections/SequenceViewModel.cs b/src/Chronos.App/Sections/SequenceViewModel.cs index e9987ec0..2e18c0b6 100644 --- a/src/Chronos.App/Sections/SequenceViewModel.cs +++ b/src/Chronos.App/Sections/SequenceViewModel.cs @@ -643,7 +643,8 @@ public sealed class SequenceViewModel : SectionViewModel { workspace.Remember(row.Id, entry.ProjectId); workspace.RecordOpened(entry.ProjectId); - return (new WorkspaceSequenceSource(workspace.SyncOf(entry.ProjectId), entry.ProjectId, db, decoder, services.Engine), row.DisplayTitle); + return (new WorkspaceSequenceSource(workspace.SyncOf(entry.ProjectId), entry.ProjectId, db, decoder, services.Engine, + hold: workspace.HoldInEditor(entry.ProjectId)), row.DisplayTitle); } var projectId = entry?.ProjectId ?? request?.ProjectId; string? newName = null; @@ -750,7 +751,8 @@ public sealed class SequenceViewModel : SectionViewModel var server = entry.Home.Server; var editorHome = new WorkspaceServerHome(() => sync.Identity.Same(sync.Server, server) ? sync.ConnectEditor() : null, () => sync.Session); - return new ServerOpen((new WorkspaceSequenceSource(workspace.SyncOf(entry.ProjectId), entry.ProjectId, db, decoder, services.Engine, editorHome), entry.SequenceTitle)); + return new ServerOpen((new WorkspaceSequenceSource(workspace.SyncOf(entry.ProjectId), entry.ProjectId, db, decoder, services.Engine, editorHome, + workspace.HoldInEditor(entry.ProjectId)), entry.SequenceTitle)); } // An account that may not edit checks nothing out: it is shown with proxies, read-only, as on an older server. if (!sync.Policy.CanEdit || sync.ServerHome(remoteId) is not { } home) return null; diff --git a/src/Chronos.App/Server/LibraryShare.cs b/src/Chronos.App/Server/LibraryShare.cs index a27a8cf7..7c9adfc4 100644 --- a/src/Chronos.App/Server/LibraryShare.cs +++ b/src/Chronos.App/Server/LibraryShare.cs @@ -46,6 +46,9 @@ public sealed class LibraryShare : ObservableObject, IAsyncDisposable private readonly AppServices _services; private readonly SemaphoreSlim _gate = new(1, 1); private HostedServer? _server; + + /// The server being started: its certificate and id are known before it listens and its first beacon goes out. + private HostedServer? _starting; private ShareSettings? _running; private string? _archiveRoot; private ShareState _state = ShareState.Off; @@ -224,7 +227,7 @@ public sealed class LibraryShare : ObservableObject, IAsyncDisposable /// True for this PC's own shared library, by its certificate or its server id: the desktop never connects to itself. public bool IsOwn(string? fingerprint, Guid? serverId) { - if (_server is not { } server) return false; + if ((Volatile.Read(ref _server) ?? Volatile.Read(ref _starting)) is not { } server) return false; if (serverId is { } id && server.ServerId == id) return true; return fingerprint is { Length: > 0 } && string.Equals(fingerprint, server.Fingerprint, StringComparison.OrdinalIgnoreCase); } @@ -342,17 +345,26 @@ public sealed class LibraryShare : ObservableObject, IAsyncDisposable var options = ServerOptions.ForHosted(Folder, DesktopValues(archive.RootPath)); return ServerHost.BuildHosted(options, new HostedEngine(db, archives, processing, engine, scheduler, archive)); }, cancellationToken).ConfigureAwait(false); + // Its first beacon goes out while it starts: LAN discovery already knows it for this PC's own (owner review 5, #67). + Volatile.Write(ref _starting, server); // Off the caller's thread: the server's own services never continue on the UI thread. await Task.Run(() => server.StartAsync(cancellationToken), cancellationToken).ConfigureAwait(false); } - catch (Exception ex) when (ex is not OperationCanceledException && Failure(ex, share) is { } reason) + catch (OperationCanceledException) { + Volatile.Write(ref _starting, null); + throw; + } + catch (Exception ex) when (Failure(ex, share) is { } reason) + { + Volatile.Write(ref _starting, null); if (server is not null) await DisposeQuietlyAsync(server).ConfigureAwait(false); Log.Error("share", "This library could not be shared", ex); Fail(reason); return; } _server = server; + Volatile.Write(ref _starting, null); _running = share; _archiveRoot = archive.RootPath; server.JobChangedOutside += OnJobChangedOutside; diff --git a/src/Chronos.App/Server/ServerJobsViewModel.cs b/src/Chronos.App/Server/ServerJobsViewModel.cs index 71fb74f1..b1128038 100644 --- a/src/Chronos.App/Server/ServerJobsViewModel.cs +++ b/src/Chronos.App/Server/ServerJobsViewModel.cs @@ -124,7 +124,7 @@ public sealed class ServerJobsViewModel : ObservableObject, IDisposable public async Task ReloadAsync() { if (_watch is not { } watch) return; - await LoadAsync(watch.Api, watch.Stopping.Token); + await LoadAsync(watch.Api, watch, watch.Stopping.Token); Flush(); } @@ -181,11 +181,11 @@ public sealed class ServerJobsViewModel : ObservableObject, IDisposable { try { - await LoadAsync(watch.Api, ct).ConfigureAwait(false); + await LoadAsync(watch.Api, watch, ct).ConfigureAwait(false); await foreach (var e in watch.Api.EventsAsync(ct).ConfigureAwait(false)) { failures = 0; - await OnEventAsync(watch.Api, e, ct).ConfigureAwait(false); + await OnEventAsync(watch.Api, watch, e, ct).ConfigureAwait(false); } } catch (Exception ex) when (ex is not OutOfMemoryException) @@ -208,7 +208,7 @@ public sealed class ServerJobsViewModel : ObservableObject, IDisposable } /// Every running and paused job of the server, all pages (any thread). - private async Task LoadAsync(IServerJobsApi api, CancellationToken ct) + private async Task LoadAsync(IServerJobsApi api, Watch watch, CancellationToken ct) { var jobs = new List(); foreach (var state in ListedStates) @@ -223,37 +223,50 @@ public sealed class ServerJobsViewModel : ObservableObject, IDisposable while (cursor is not null); } _updates.Reset(jobs); + watch.Listed(jobs.Select(j => j.Id)); Signal(); } - private async Task OnEventAsync(IServerJobsApi api, ServerEvent e, CancellationToken ct) + private async Task OnEventAsync(IServerJobsApi api, Watch watch, ServerEvent e, CancellationToken ct) { switch (e) { case JobProgressEvent p: + // A job that started between the list and the event socket: its running state was missed, its progress is + // not. Read once, it joins the list (owner review 5, #65). + if (watch.FirstUnknown(p.JobId)) await FetchAsync(api, watch, p.JobId, ct, signal: false).ConfigureAwait(false); // Kind and target come from the listed job; what matters here is the count, the pace and the detail. _updates.Post(new JobProgressInfo(p.JobId, default, null, p.Done, p.Total, p.ItemsPerSecond, JobEta.FromSeconds(p.EtaSeconds), null, JobWire.FromDto(p.Detail))); Signal(); break; case JobStateEvent s when JobWire.TryParseState(s.State, out var state) && IsListed(state): - await FetchAsync(api, s.JobId, ct).ConfigureAwait(false); + await FetchAsync(api, watch, s.JobId, ct).ConfigureAwait(false); break; case JobStateEvent s: // Queued again, finished or of a state this build does not know: it leaves the list. + watch.Know(s.JobId, false); _updates.Remove(s.JobId); Signal(); break; } } - private async Task FetchAsync(IServerJobsApi api, Guid jobId, CancellationToken ct) + private async Task FetchAsync(IServerJobsApi api, Watch watch, Guid jobId, CancellationToken ct, bool signal = true) { try { - if (JobWire.FromDto(await api.GetJobAsync(jobId, ct).ConfigureAwait(false)) is { } job) _updates.Post(job); - else _updates.Remove(jobId); - Signal(); + if (JobWire.FromDto(await api.GetJobAsync(jobId, ct).ConfigureAwait(false)) is { } job && IsListed(job.State)) + { + watch.Know(jobId, true); + _updates.Post(job); + } + else + { + watch.Know(jobId, false); + _updates.Remove(jobId); + } + if (signal) Signal(); } catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or JsonException || (ex is OperationCanceledException && !ct.IsCancellationRequested)) @@ -327,6 +340,36 @@ public sealed class ServerJobsViewModel : ObservableObject, IDisposable public IServerJobsApi Api { get; } = api; public CancellationTokenSource Stopping { get; } = stopping; public Task? Listening { get; set; } + + /// The jobs the list holds as the listener read them, and those read once on their progress since the last list. + private readonly HashSet _known = []; + private readonly HashSet _fetched = []; + + /// A new list (the listener's, or a reload's): what it holds is known, and every job may be read once again. + public void Listed(IEnumerable ids) + { + lock (_known) + { + _known.Clear(); + _known.UnionWith(ids); + _fetched.Clear(); + } + } + + public void Know(Guid id, bool listed) + { + lock (_known) + { + if (listed) _known.Add(id); + else _known.Remove(id); + } + } + + /// True the first time a job the list does not hold reports progress: it is read once then. + public bool FirstUnknown(Guid id) + { + lock (_known) return !_known.Contains(id) && _fetched.Add(id); + } } /// diff --git a/src/Chronos.App/Server/SyncHost.cs b/src/Chronos.App/Server/SyncHost.cs index 6e3cdadd..65fa45ff 100644 --- a/src/Chronos.App/Server/SyncHost.cs +++ b/src/Chronos.App/Server/SyncHost.cs @@ -45,7 +45,7 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo /// How long a job resumed at start waits for the saved session to be restored. private static readonly TimeSpan RestoreWait = TimeSpan.FromSeconds(30); - /// Jobs that write into the workspace or the servers' homes in the cache: a re-key waits for them. + /// Jobs that write into the workspace or the servers' homes in the cache: the move of the folders to a server's id waits for them. private static readonly JobKind[] RekeyHeldBy = [JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend, JobKind.WorkspaceMove, JobKind.Download, JobKind.UploadCommit, JobKind.VideoCopy]; @@ -429,9 +429,11 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo /// /// Whatever this PC keeps under the address keys the server of was reached by moves to its - /// id (owner review 5, #66: ), before the agent starts. Skipped while a job - /// writes into the workspace or the cache, or the workspace is being moved: a later sign-in does it, and the aliases match - /// meanwhile. A failure is logged: nothing is lost, and the next sign-in goes on. + /// id (owner review 5, #66: ), before the agent starts. The links move at + /// once (): the jobs resumed under the id key look them up by it. The + /// folders wait while a job writes into the workspace or the cache, a project is open in the editor, or the workspace + /// is being moved: a later sign-in moves them, and the aliases match meanwhile. A failure is logged: nothing is lost, + /// and the next sign-in goes on. /// private async Task RekeyAsync(Credentials credentials) { @@ -440,11 +442,6 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo if (aliases.Count == 0) return; try { - if (await db.Jobs.HasPendingAsync(RekeyHeldBy).ConfigureAwait(false)) - { - Log.Info("sync", $"Server {id}: what this PC keeps under its addresses moves to its id at a later sign-in (jobs are under way)"); - return; - } var workspace = services.Workspace; var migration = new HomeLayoutMigration(new HomeLayoutOptions { @@ -454,6 +451,12 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo Identity = Identity, Database = db, }); + await migration.RekeyLinksAsync(id, aliases).ConfigureAwait(false); + if (workspace.HasProjectsInEditor || await db.Jobs.HasPendingAsync(RekeyHeldBy).ConfigureAwait(false)) + { + Log.Info("sync", $"Server {id}: its folders on this PC move from its addresses to its id at a later sign-in (jobs are under way or a project is open)"); + return; + } await migration.RekeyAsync(id, aliases).ConfigureAwait(false); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException) diff --git a/src/Chronos.App/Shell/MainWindow.xaml b/src/Chronos.App/Shell/MainWindow.xaml index 15ee5f2c..7f7cf2f9 100644 --- a/src/Chronos.App/Shell/MainWindow.xaml +++ b/src/Chronos.App/Shell/MainWindow.xaml @@ -92,7 +92,7 @@ - diff --git a/src/Chronos.App/Shell/ShellViewModel.cs b/src/Chronos.App/Shell/ShellViewModel.cs index 79dea1b8..b1e798a2 100644 --- a/src/Chronos.App/Shell/ShellViewModel.cs +++ b/src/Chronos.App/Shell/ShellViewModel.cs @@ -20,6 +20,7 @@ public sealed class ShellViewModel : LocalizedViewModel private bool _isRailCollapsed; private string? _jobText; private string? _jobName; + private string? _jobToolTip; private double _jobProgress; private bool _jobActive; private bool _jobIndeterminate; @@ -227,6 +228,9 @@ public sealed class ShellViewModel : LocalizedViewModel ? _jobText : _queuedCount > 0 ? Loc.Plural("Shell.JobBar.Ready", _queuedCount) : Loc.L("Shell.JobBar.Idle"); + /// The job bar's tooltip: its line uncut, with what the job works on now (the bar cuts it at 60 characters). + public string JobToolTip => _jobActive && _jobToolTip is not null ? _jobToolTip : JobText; + public double JobProgress { get => _jobProgress; private set => Set(ref _jobProgress, value); } public bool IsJobActive { @@ -264,16 +268,19 @@ public sealed class ShellViewModel : LocalizedViewModel /// /// Updates the global job bar and the taskbar button. says which job it is without its - /// progress ("Render: Harbour sunset"); null reads . + /// progress ("Render: Harbour sunset"); null reads . is the line uncut; + /// null shows . /// - public void SetJob(string? text, double progress, bool indeterminate = false, string? name = null) + public void SetJob(string? text, double progress, bool indeterminate = false, string? name = null, string? toolTip = null) { _jobText = text; + _jobToolTip = text is null ? null : toolTip ?? text; _jobName = text is null ? null : name ?? text; IsJobActive = text is not null; JobProgress = progress; IsJobIndeterminate = indeterminate; OnPropertyChanged(nameof(JobText)); + OnPropertyChanged(nameof(JobToolTip)); OnPropertyChanged(nameof(JobAnnouncement)); OnPropertyChanged(nameof(TaskbarState)); OnPropertyChanged(nameof(TaskbarProgress)); @@ -321,6 +328,7 @@ public sealed class ShellViewModel : LocalizedViewModel _queuedCount = queued; OnPropertyChanged(nameof(JobsText)); OnPropertyChanged(nameof(JobText)); + OnPropertyChanged(nameof(JobToolTip)); OnPropertyChanged(nameof(JobAnnouncement)); } diff --git a/src/Chronos.App/Workspace/WorkspaceHost.cs b/src/Chronos.App/Workspace/WorkspaceHost.cs index 97705210..6a579b47 100644 --- a/src/Chronos.App/Workspace/WorkspaceHost.cs +++ b/src/Chronos.App/Workspace/WorkspaceHost.cs @@ -164,6 +164,7 @@ public sealed partial class WorkspaceHost private readonly Func _engine; private readonly Lock _gate = new(); private readonly Dictionary _copies = []; + private readonly Dictionary _inEditor = []; private OpenWorkspace? _open; public WorkspaceHost(AppEnvironment environment, AppSettings settings, Action savePreferences, Func db, Func archives, @@ -245,6 +246,45 @@ public sealed partial class WorkspaceHost /// The project's folder in whichever home holds it; null when the workspace has none. public WorkspaceProject? Find(Guid projectId) => Homes.Find(projectId); + /// + /// Marks open in the editor until the result is disposed. The editor keeps its project's + /// folder for as long as it is open, so the move of a server's home to its id waits meanwhile (owner review 5, #66). + /// + public IDisposable HoldInEditor(Guid projectId) + { + lock (_inEditor) _inEditor[projectId] = _inEditor.GetValueOrDefault(projectId) + 1; + return new EditorHold(this, projectId); + } + + /// A project is open in the editor (). + public bool HasProjectsInEditor + { + get + { + lock (_inEditor) return _inEditor.Count > 0; + } + } + + private void ReleaseInEditor(Guid projectId) + { + lock (_inEditor) + { + if (!_inEditor.TryGetValue(projectId, out var count)) return; + if (count <= 1) _inEditor.Remove(projectId); + else _inEditor[projectId] = count - 1; + } + } + + private sealed class EditorHold(WorkspaceHost host, Guid projectId) : IDisposable + { + private int _released; + + public void Dispose() + { + if (Interlocked.Exchange(ref _released, 1) == 0) host.ReleaseInEditor(projectId); + } + } + /// The sync over the store of the home that holds . /// The workspace has no such project (Errors.Workspace.NotCheckedOut). public WorkspaceSync SyncOf(Guid projectId) => SyncOf(Existing(projectId).Store); diff --git a/src/Chronos.Data/Homes/HomeLayoutMigration.cs b/src/Chronos.Data/Homes/HomeLayoutMigration.cs index 2d354a36..163492b1 100644 --- a/src/Chronos.Data/Homes/HomeLayoutMigration.cs +++ b/src/Chronos.Data/Homes/HomeLayoutMigration.cs @@ -591,20 +591,34 @@ public sealed class HomeLayoutMigration if (Directory.Exists(legacy)) MergeCache(legacy, Path.Combine(target, HomeFolders.Proxies)); } } - if (_options.Database is { } db) - { - var store = new SyncLinkStore(db); - foreach (var alias in keys) - { - var (m, d) = await store.RekeyAsync(alias, idKey, cancellationToken).ConfigureAwait(false); - (links, dropped) = (links + m, dropped + d); - } - } + (links, dropped) = await RekeyLinksAsync(serverId, keys, cancellationToken).ConfigureAwait(false); var result = new HomeRekeyResult(homes, projects, trashed, rewritten, held, links, dropped); Log.Info("homes", $"Server {serverId} re-keyed from {string.Join(", ", keys)}: {result}"); return result; } + /// + /// The links part of alone: the server's links under its address keys + /// move to its id key (), and nothing on disk changes. An index change, safe while + /// jobs run: a download or an upload resumed under the id key then finds its links (owner review 5, #66). Nothing to do + /// without a database. + /// + public async Task<(int Moved, int Dropped)> RekeyLinksAsync(Guid serverId, IReadOnlyCollection aliases, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(aliases); + if (serverId == Guid.Empty) throw new ArgumentException("A server id is never empty.", nameof(serverId)); + if (_options.Database is not { } db) return (0, 0); + var idKey = HomeFolders.IdKey(serverId); + var store = new SyncLinkStore(db); + var (moved, dropped) = (0, 0); + foreach (var alias in aliases.Where(a => !string.IsNullOrWhiteSpace(a) && !ServerIdentity.IsIdKey(a)).Distinct(StringComparer.OrdinalIgnoreCase)) + { + var (m, d) = await store.RekeyAsync(alias, idKey, cancellationToken).ConfigureAwait(false); + (moved, dropped) = (moved + m, dropped + d); + } + return (moved, dropped); + } + /// The projects and trash of the alias home moved into the id home (see ). private (int Moved, int Trashed) MergeWorkspaceHome(string from, string into, Guid serverId) { diff --git a/src/Chronos.Data/Jobs/JobEngine.cs b/src/Chronos.Data/Jobs/JobEngine.cs index 3ef4c784..277a8ed0 100644 --- a/src/Chronos.Data/Jobs/JobEngine.cs +++ b/src/Chronos.Data/Jobs/JobEngine.cs @@ -484,7 +484,15 @@ public sealed class JobEngine : IAsyncDisposable { if (!_handlers.TryGetValue(job.Kind, out var handler)) throw new InvalidOperationException($"No handler for {job.Kind} jobs on this worker."); - await handler.RunAsync(context).ConfigureAwait(false); + try + { + await handler.RunAsync(context).ConfigureAwait(false); + } + finally + { + // The handler returned: no trailing progress follows its final state. + context.End(); + } await PersistAsync(context).ConfigureAwait(false); final = JobState.Done; } diff --git a/src/Chronos.Data/Jobs/JobHandler.cs b/src/Chronos.Data/Jobs/JobHandler.cs index 42021599..701f84ec 100644 --- a/src/Chronos.Data/Jobs/JobHandler.cs +++ b/src/Chronos.Data/Jobs/JobHandler.cs @@ -52,10 +52,13 @@ public sealed record JobProgressInfo(Guid JobId, JobKind Kind, string? TargetLab /// /// Everything a handler needs while it runs. Progress is cheap to report, so a handler may report every photo: the engine -/// publishes it at most once per progress interval (, twice a second) and at -/// once when the step changes, the job's count completes or it is the run's first report; a report it drops costs no -/// allocation, no lock and no rate. It persists progress at most every checkpoint interval (BRIEF §14.6: checkpoints every -/// 5 s), and a checkpoint at once; a persist that falls due also publishes the state it saves when the last report was dropped. +/// publishes it at most once per progress interval (, twice a second), at once +/// when the job's count completes or it is the run's first report, and early when the step changes (at most four times per +/// interval, so a handler that alternates steps does not flood the events); a report it drops costs no allocation, no lock +/// and no rate. A dropped report goes out once its time comes even when no report follows (a job gone quiet in a long step): +/// a single timer on the engine's clock publishes the latest state then. It persists progress at most every checkpoint +/// interval (BRIEF §14.6: checkpoints every 5 s), and a checkpoint at once; a persist that falls due also publishes the state +/// it saves when the last report was dropped. /// public sealed class JobContext { @@ -78,6 +81,12 @@ public sealed class JobContext private long _publishedTotal; private bool _pending; + /// The trailing publish of a dropped report (), made at the first drop; armed while 1. + private ITimer? _trailing; + private int _armed; + private long _armedFor; + private volatile bool _ended; + internal JobContext(JobEngine engine, Job job, CancellationToken cancellation) { _engine = engine; @@ -236,7 +245,11 @@ public sealed class JobContext var now = _time.GetTimestamp(); var due = _time.GetElapsedTime(Interlocked.Read(ref _lastPersist), now) >= _engine.Options.CheckpointInterval; if (Publishes(now)) Publish(now); - else _pending = true; + else + { + _pending = true; + ArmTrailing(now); + } if (!force && !due) return; Interlocked.Exchange(ref _lastPersist, now); // The persist that falls due shows what it saves, so a job that went quiet after a dropped report is not left behind. @@ -246,15 +259,57 @@ public sealed class JobContext } /// - /// Whether this report goes out now: the run's first, a new step, a count that completes (once), or the progress interval - /// passed since the last one. Reads fields and the clock only. + /// Whether this report goes out now: the run's first, a count that completes (once), a new step once a quarter of the + /// progress interval passed since the last publish, or the progress interval passed. Reads fields and the clock only. /// private bool Publishes(long now) { if (!_published) return true; - if ((_detail?.Step ?? JobStep.None) != _publishedStep) return true; if (Total > 0 && Done >= Total && (Done != _publishedDone || Total != _publishedTotal)) return true; - return _time.GetElapsedTime(_lastPublish, now) >= _engine.Options.ProgressInterval; + return _time.GetElapsedTime(_lastPublish, now) >= Wait(); + } + + /// How long after the last publish the current state may go out: a quarter of the interval for a new step. + private TimeSpan Wait() => + (_detail?.Step ?? JobStep.None) != _publishedStep ? _engine.Options.ProgressInterval / 4 : _engine.Options.ProgressInterval; + + /// + /// After a dropped report: publishes the state once its time comes ( after the last publish), unless a + /// publish happens first. One timer per run, armed at most once per publish (again earlier when a new step shortens the + /// wait), so a dropped report allocates nothing. + /// + private void ArmTrailing(long now) + { + if (_ended) return; + var left = Wait() - _time.GetElapsedTime(_lastPublish, now); + if (left < TimeSpan.Zero) left = TimeSpan.Zero; + var at = now + (long)(left.TotalSeconds * _time.TimestampFrequency); + if (Interlocked.CompareExchange(ref _armed, 1, 0) != 0) + { + // Armed already: only a new step's shorter wait moves it. + if (at >= Interlocked.Read(ref _armedFor)) return; + } + Interlocked.Exchange(ref _armedFor, at); + if (_trailing is null) + { + lock (_gate) _trailing ??= _time.CreateTimer(static state => ((JobContext)state!).OnTrailing(), this, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); + } + _trailing.Change(left, Timeout.InfiniteTimeSpan); + } + + /// The trailing publish fires: the latest state goes out when no publish came since the report it waited for. + private void OnTrailing() + { + Volatile.Write(ref _armed, 0); + if (_ended || !_pending) return; + Publish(_time.GetTimestamp()); + } + + /// The run ended (its final state is written next): no trailing publish follows it. + internal void End() + { + _ended = true; + _trailing?.Dispose(); } private void Publish(long now) diff --git a/src/Chronos.Data/Workspaces/WorkspaceCopyJobHandler.cs b/src/Chronos.Data/Workspaces/WorkspaceCopyJobHandler.cs index 2b8a7534..375177d5 100644 --- a/src/Chronos.Data/Workspaces/WorkspaceCopyJobHandler.cs +++ b/src/Chronos.Data/Workspaces/WorkspaceCopyJobHandler.cs @@ -116,7 +116,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService if (!PathsEqual(root, parameters.WorkspaceRoot) && await InsideALibraryAsync(root, ct).ConfigureAwait(false)) throw new InvalidOperationException(Loc.L("Errors.Workspace.InsideLibrary")); parameters = parameters with { WorkspaceRoot = root }; - var store = new WorkspaceStore(root); + var store = WorkspaceStore.ForJob(root); var project = store.Find(parameters.ProjectId) ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.NotCheckedOut")); if (project.ReadBundle().Workspace is not { Home: { IsArchive: true } home } || home.SequenceId != sequenceId) throw new InvalidOperationException(Loc.L("Errors.Workspace.OtherHome")); @@ -167,7 +167,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService { try { - if (new WorkspaceStore(root).Find(parameters.ProjectId) is { } project) + if (WorkspaceStore.ForJob(root).Find(parameters.ProjectId) is { } project) { await RemovePartialMediaAsync(job, project).ConfigureAwait(false); await RemoveCancelledOriginalsAsync(job, project, parameters).ConfigureAwait(false); @@ -496,7 +496,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService if (!PathsEqual(root, parameters.WorkspaceRoot) && await InsideALibraryAsync(root, ct).ConfigureAwait(false)) throw new InvalidOperationException(Loc.L("Errors.Workspace.InsideLibrary")); parameters = parameters with { WorkspaceRoot = root }; - var store = new WorkspaceStore(root); + var store = WorkspaceStore.ForJob(root); var project = store.Find(parameters.ProjectId) ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.NotCheckedOut")); if (project.ReadBundle().Workspace is not { Home: { Kind: BundleHome.ServerKind } home } || home.SequenceId != sequenceId || !(options?.IsSameServer(home.Server, server) ?? string.Equals(home.Server, server, StringComparison.OrdinalIgnoreCase))) diff --git a/src/Chronos.Data/Workspaces/WorkspaceRenderJobHandler.cs b/src/Chronos.Data/Workspaces/WorkspaceRenderJobHandler.cs index c2427e25..4a8568a7 100644 --- a/src/Chronos.Data/Workspaces/WorkspaceRenderJobHandler.cs +++ b/src/Chronos.Data/Workspaces/WorkspaceRenderJobHandler.cs @@ -50,7 +50,7 @@ internal sealed class WorkspaceRenderJobHandler(ChronosDatabase db, ArchiveServi // made where it is not. var root = WorkspaceJobRoots.Resolve(parameters.WorkspaceRoot, parameters.ProjectId, options.CurrentRoot, "Errors.Workspace.RenderProject"); parameters = parameters with { WorkspaceRoot = root }; - var store = new WorkspaceStore(root); + var store = WorkspaceStore.ForJob(root); var project = store.Find(parameters.ProjectId) ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.RenderProject")); var inputs = await ReadInputsAsync(project, parameters, render, cancellation).ConfigureAwait(false); var (sequence, frames, settings, versionId) = (inputs.Sequence, inputs.Frames, inputs.Settings, inputs.VersionId); diff --git a/src/Chronos.Data/Workspaces/WorkspaceSendJobHandler.cs b/src/Chronos.Data/Workspaces/WorkspaceSendJobHandler.cs index 763ea377..ca4381a5 100644 --- a/src/Chronos.Data/Workspaces/WorkspaceSendJobHandler.cs +++ b/src/Chronos.Data/Workspaces/WorkspaceSendJobHandler.cs @@ -53,7 +53,7 @@ internal sealed class WorkspaceSendJobHandler(ChronosDatabase db, ArchiveService // Where the project is now (a workspace moved since the job was queued), never while it is being moved; nothing is // made where it is not. var root = WorkspaceJobRoots.Resolve(parameters.WorkspaceRoot, parameters.ProjectId, options.CurrentRoot, "Errors.Workspace.NotCheckedOut"); - var project = new WorkspaceStore(root).Find(parameters.ProjectId) + var project = WorkspaceStore.ForJob(root).Find(parameters.ProjectId) ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.NotCheckedOut")); var workspace = project.ReadBundle().Workspace ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.NotCheckedOut")); var home = workspace.Home; diff --git a/src/Chronos.Data/Workspaces/WorkspaceStore.cs b/src/Chronos.Data/Workspaces/WorkspaceStore.cs index cc2477f6..b5b1aabd 100644 --- a/src/Chronos.Data/Workspaces/WorkspaceStore.cs +++ b/src/Chronos.Data/Workspaces/WorkspaceStore.cs @@ -186,6 +186,20 @@ public sealed class WorkspaceStore Manifest = manifest; } + /// + /// The store a workspace job opens at (): a split parent, + /// which still holds a project its sorting into homes left in place (one in use then), opens as the view of those projects + /// (owner review 5); any other folder as does. + /// + /// The folder's workspace.json is not a workspace manifest, or a newer one. + /// The folder cannot be made or read. + internal static WorkspaceStore ForJob(string root) + { + ArgumentException.ThrowIfNullOrWhiteSpace(root); + var full = FullRoot(root); + return TryRead(Path.Combine(full, ManifestFile)) is { Layout: WorkspaceHomes.HomesLayout } manifest ? new WorkspaceStore(full, manifest) : new WorkspaceStore(full); + } + public string Root { get; } public WorkspaceManifest Manifest { get; } diff --git a/src/Chronos.Server/Api/JobEndpoints.cs b/src/Chronos.Server/Api/JobEndpoints.cs index d1ce3f6a..0fb489f2 100644 --- a/src/Chronos.Server/Api/JobEndpoints.cs +++ b/src/Chronos.Server/Api/JobEndpoints.cs @@ -33,7 +33,7 @@ public static class JobEndpoints jobs.MapGet("", ListAsync); jobs.MapPost("", CreateAsync); jobs.MapGet("/{id:guid}", async (HttpContext context, Guid id, ChronosDatabase db, JobEngineHost host) => - await db.Jobs.GetAsync(id, context.RequestAborted) is { } job && host.Exposes(job.Kind) + await db.Jobs.GetAsync(id, context.RequestAborted) is { } job && await host.ServesAsync(job, context.RequestAborted) ? Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto) : ApiErrors.NotFound(context, "job")); jobs.MapPost("/{id:guid}/cancel", (HttpContext c, Caller caller, Guid id, ChronosDatabase db, JobEngineHost host) => @@ -64,8 +64,14 @@ public static class JobEndpoints // A job's answer holds no parameters (a conversion's or an import's can name every sequence or file): the list reads none. if (kindFilter is { } wanted && !host.Exposes(wanted)) return Results.Json(new Page([], null, null), ProtocolJson.Default.PageJobDto); var page = await db.Jobs.ListBriefAsync(stateFilter, kindFilter, limit ?? 50, string.IsNullOrEmpty(cursor) ? null : cursor, context.RequestAborted); - // A shared desktop library lists the kinds a server runs alone (owner review 5, #67); the cursor still pages the whole list. - return Results.Json(new Page([.. page.Items.Where(j => host.Exposes(j.Kind)).Select(Dto.Job)], page.NextCursor, null), ProtocolJson.Default.PageJobDto); + // A shared desktop library lists the kinds a server runs alone, on the archive it serves (owner review 5, #67); the + // cursor still pages the whole list. + var served = new List(page.Items.Count); + foreach (var job in page.Items) + { + if (await host.ServesAsync(job, context.RequestAborted)) served.Add(Dto.Job(job)); + } + return Results.Json(new Page(served, page.NextCursor, null), ProtocolJson.Default.PageJobDto); } private static async Task CreateAsync(HttpContext context, Caller caller, CreateJobRequest request, ChronosDatabase db, JobEngineHost host, @@ -227,8 +233,8 @@ public static class JobEndpoints private static async Task ActAsync(HttpContext context, Caller caller, Guid id, ChronosDatabase db, JobState[] allowed, Func action) { var ct = context.RequestAborted; - // A shared desktop library's own jobs (workspace, sync, downloads) are not the server's (owner review 5, #67). - if (await db.Jobs.GetAsync(id, ct) is not { } job || !context.RequestServices.GetRequiredService().Exposes(job.Kind)) + // A shared desktop library's own jobs (workspace, sync, downloads, other archives) are not the server's (owner review 5, #67). + if (await db.Jobs.GetAsync(id, ct) is not { } job || !await context.RequestServices.GetRequiredService().ServesAsync(job, ct)) return ApiErrors.NotFound(context, "job"); if (job.CreatedBy != caller.Id && !caller.Has(Permissions.ManageArchive)) return ApiErrors.Forbidden(context); if (!allowed.Contains(job.State)) return ApiErrors.Conflict(context, "invalid_state", JobWire.State(job.State)); diff --git a/src/Chronos.Server/Hosting/HostedServer.cs b/src/Chronos.Server/Hosting/HostedServer.cs index 815a51b9..82de40d0 100644 --- a/src/Chronos.Server/Hosting/HostedServer.cs +++ b/src/Chronos.Server/Hosting/HostedServer.cs @@ -124,11 +124,11 @@ public sealed class HostedServer : IAsyncDisposable /// The desktop's archive or processing service changed or made sequence : clients are told. public Task SequenceChangedAsync(Guid id, string change, CancellationToken cancellationToken) => ServerEventBridge.SequenceChangedAsync(Services.GetRequiredService(), Events, Services.GetService(), id, change, - cancellationToken); + cancellationToken, Services.GetRequiredService()); /// The desktop's archive service changed a sequence's projects: clients are told. public Task ProjectsChangedAsync(ProjectChangeSet changed, CancellationToken cancellationToken) => - ServerEventBridge.ProjectsChangedAsync(Services.GetRequiredService(), Events, changed, cancellationToken); + ServerEventBridge.ProjectsChangedAsync(Services.GetRequiredService(), Events, changed, cancellationToken, Services.GetRequiredService()); /// The uploads clean-up step of the server: abandoned uploads and old upload records (the upload-cleanup schedule). public Task SweepUploadsAsync(CleanupContext context, CleanupParameters parameters) => diff --git a/src/Chronos.Server/Hosting/ServerHost.cs b/src/Chronos.Server/Hosting/ServerHost.cs index 78fb11f5..e9bbcbfc 100644 --- a/src/Chronos.Server/Hosting/ServerHost.cs +++ b/src/Chronos.Server/Hosting/ServerHost.cs @@ -252,7 +252,11 @@ public static class ServerHost services.AddSingleton(); services.AddSingleton(); if (hosted is null) services.AddSingleton(); - else services.AddSingleton(sp => new JobEngineHost(hosted.Engine, sp.GetRequiredService(), sp.GetRequiredService())); + else + { + services.AddSingleton(sp => new JobEngineHost(hosted.Engine, sp.GetRequiredService(), sp.GetRequiredService(), + sp.GetRequiredService(), sp.GetRequiredService())); + } services.AddHostedService(sp => sp.GetRequiredService()); // After the engine's host: the scheduler queues on its engine, starts after it and stops before it (owner review 2, R10). services.AddSingleton(); diff --git a/src/Chronos.Server/Jobs/JobEngineHost.cs b/src/Chronos.Server/Jobs/JobEngineHost.cs index 959c98de..88bf206c 100644 --- a/src/Chronos.Server/Jobs/JobEngineHost.cs +++ b/src/Chronos.Server/Jobs/JobEngineHost.cs @@ -5,6 +5,7 @@ using Chronos.Protocol; using Chronos.Server.Api; using Chronos.Server.Configuration; using Chronos.Server.Events; +using Chronos.Server.Storage; namespace Chronos.Server.Jobs; @@ -16,8 +17,9 @@ namespace Chronos.Server.Jobs; /// handler accepts them (: managed formats, and MP4 jobs no render node can take); /// render nodes claim the others (BRIEF §14.5, §14.7). On shutdown running jobs stay marked running and are requeued from their checkpoints at the next start. /// When Chronos Desktop shares its library (owner review 5, #67) the engine is the desktop's own: this host relays it while the -/// server runs, never starts, stops or disposes it, and the jobs API shows only the kinds a server runs (): -/// the desktop's workspace, sync and download jobs stay its own. +/// server runs, never starts, stops or disposes it, and the jobs API and the events show only the jobs of the kinds a server +/// runs () on the archive it serves and its sequences (): the desktop's +/// workspace, sync and download jobs, and its jobs on other archives, stay its own. /// Progress goes out through the render nodes share, with what each job does now (owner review 5, #65). /// public sealed class JobEngineHost : IHostedService @@ -25,6 +27,13 @@ public sealed class JobEngineHost : IHostedService private readonly EventHub _events; private readonly HashSet _kinds; private readonly bool _ownsEngine = true; + private readonly ServerArchive? _archive; + private readonly ChronosDatabase? _db; + + /// Hosted: whether each job seen is the shared archive's (its targets never change), and the latest state of one still being looked up. + private readonly Dictionary _served = []; + private readonly Dictionary _deciding = []; + private readonly Lock _decide = new(); private int _subscribed; public JobEngineHost(ChronosDatabase db, IEnumerable handlers, IEnumerable providers, ServerOptions options, @@ -47,15 +56,18 @@ public sealed class JobEngineHost : IHostedService /// /// Relays , an engine Chronos Desktop runs (owner review 5, #67), from to - /// ; the engine stays the desktop's. + /// ; the engine stays the desktop's. With and , only + /// that archive's jobs and its sequences' are relayed and listed (). /// - public JobEngineHost(JobEngine engine, EventHub events, TimeProvider time) + public JobEngineHost(JobEngine engine, EventHub events, TimeProvider time, ServerArchive? archive = null, ChronosDatabase? db = null) { ArgumentNullException.ThrowIfNull(engine); _events = events; Gate = new ProgressGate(time); _ownsEngine = false; _kinds = []; + _archive = archive; + _db = db; Engine = engine; } @@ -80,6 +92,33 @@ public sealed class JobEngineHost : IHostedService /// public bool Exposes(JobKind kind) => _ownsEngine || ServerSettingsStore.Kinds.Contains(kind); + /// + /// Whether the jobs API lists, shows and acts on , and its events go out: every job on a server of + /// its own; on a shared desktop library a job of a kind it exposes () whose target is the served + /// archive or one of its sequences (owner review 5, #67), never the desktop's work on its other archives. + /// + public async ValueTask ServesAsync(Job job, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(job); + if (_ownsEngine) return true; + if (!Exposes(job.Kind)) return false; + if (_archive is null || _db is null) return true; + lock (_decide) + { + if (_served.TryGetValue(job.Id, out var known)) return known; + } + var served = await TargetsServedAsync(job, cancellationToken).ConfigureAwait(false); + lock (_decide) _served[job.Id] = served; + return served; + } + + /// The job's first target is the served archive or one of its sequences (a job without targets is the server's). + private async Task TargetsServedAsync(Job job, CancellationToken cancellationToken) + { + if (job.TargetIds is not [var target, ..] || target == _archive!.Id) return true; + return _archive.Owns(await _db!.Sequences.GetAsync(target, cancellationToken).ConfigureAwait(false)); + } + public Task StartAsync(CancellationToken cancellationToken) { if (_ownsEngine) return Engine.StartAsync(cancellationToken); @@ -125,11 +164,61 @@ public sealed class JobEngineHost : IHostedService private void OnJobChanged(Job job) { if (job.State != JobState.Running) Gate.Forget(job.Id); - _events.Publish(new JobStateEvent(job.Id, JobWire.State(job.State), job.Error)); + // A shared desktop library tells its clients nothing of the desktop's own jobs (owner review 5, #67). + if (!Exposes(job.Kind)) return; + if (_ownsEngine || _archive is null || _db is null) + { + PublishState(job); + return; + } + lock (_decide) + { + // Published under the lock, so the states of one job go out in order while its archive is looked up. + if (_served.TryGetValue(job.Id, out var served)) + { + if (served) PublishState(job); + return; + } + var looking = _deciding.ContainsKey(job.Id); + _deciding[job.Id] = job; + if (looking) return; + } + _ = DecideAsync(job); } + /// Looks up whether the job is the shared archive's, then publishes the latest state it had meanwhile when it is. + private async Task DecideAsync(Job job) + { + bool served; + try + { + served = await TargetsServedAsync(job, CancellationToken.None).ConfigureAwait(false); + } + catch (Exception ex) when (ex is DatabaseException or ObjectDisposedException or InvalidOperationException) + { + // Not known to be the archive's: its clients are told nothing of it. + served = false; + } + lock (_decide) + { + _served[job.Id] = served; + if (_deciding.Remove(job.Id, out var latest) && served) PublishState(latest); + } + } + + private void PublishState(Job job) => _events.Publish(new JobStateEvent(job.Id, JobWire.State(job.State), job.Error)); + private void OnProgress(JobProgressInfo progress) { + if (!Exposes(progress.Kind)) return; + if (!_ownsEngine && _archive is not null && _db is not null) + { + // Only a job known to be the shared archive's: its state, which comes first, decided it. + lock (_decide) + { + if (!_served.TryGetValue(progress.JobId, out var served) || !served) return; + } + } if (!Gate.Passes(progress.JobId, progress.Done, progress.Total, progress.Detail?.Step ?? JobStep.None)) return; _events.Publish(new JobProgressEvent(progress.JobId, progress.Done, progress.Total, progress.ItemsPerSecond, progress.Eta?.TotalSeconds, JobWire.Detail(progress.Detail))); diff --git a/src/Chronos.Server/Jobs/ProgressGate.cs b/src/Chronos.Server/Jobs/ProgressGate.cs index 4c2d8a79..86d07ab5 100644 --- a/src/Chronos.Server/Jobs/ProgressGate.cs +++ b/src/Chronos.Server/Jobs/ProgressGate.cs @@ -5,8 +5,9 @@ namespace Chronos.Server.Jobs; /// /// How often a job's progress goes out on the event socket (owner review 5, #65): at most once per /// per job, for the server's own jobs () and those render nodes run () -/// alike. A job's first report, a new step and a count that completes always pass. A job that stops running is forgotten -/// (), so its next run starts afresh. +/// alike. A job's first report and a count that completes always pass; a new step passes once a quarter of the interval went +/// by, as the job engine publishes it, so a job that alternates steps does not flood the socket. A job that stops running is +/// forgotten (), so its next run starts afresh. /// public sealed class ProgressGate(TimeProvider time) { @@ -19,6 +20,9 @@ public sealed class ProgressGate(TimeProvider time) /// private static readonly TimeSpan Slack = TimeSpan.FromMilliseconds(50); + /// The shortest time before a new step passes: a quarter of , as the job engine publishes one. + private static readonly TimeSpan StepInterval = Interval / 4; + private readonly Dictionary _last = []; private readonly Lock _gate = new(); @@ -28,8 +32,8 @@ public sealed class ProgressGate(TimeProvider time) var now = time.GetTimestamp(); lock (_gate) { - if (_last.TryGetValue(jobId, out var last) && last.Step == step && !(total > 0 && done >= total) - && time.GetElapsedTime(last.At, now) < Interval - Slack) + if (_last.TryGetValue(jobId, out var last) && !(total > 0 && done >= total) + && time.GetElapsedTime(last.At, now) < (last.Step == step ? Interval : StepInterval) - Slack) return false; _last[jobId] = (now, step); return true; diff --git a/src/Chronos.Server/Jobs/RenderNodeService.cs b/src/Chronos.Server/Jobs/RenderNodeService.cs index 5d3adef7..3b2121fc 100644 --- a/src/Chronos.Server/Jobs/RenderNodeService.cs +++ b/src/Chronos.Server/Jobs/RenderNodeService.cs @@ -87,6 +87,11 @@ public sealed class RenderNodeService( // A render the server's own engine started (it left a checkpoint) resumes there: only it knows that attempt's // leftovers and the batch entries it recorded. if (queued.Checkpoint is not null) continue; + // A shared desktop library's queue is the desktop's (owner review 5, #67): a node takes the renders clients queued + // through the API alone, never the desktop's own, which go where its user chose. + if (jobs.Hosted && queued.CreatedBy is null) continue; + // Only renders of the served archive's sequences: an index may hold other archives, whose frames the node cannot fetch. + if (queued.TargetIds is [var target] && await db.Sequences.GetAsync(target, cancellationToken) is { } owner && !archive.Owns(owner)) continue; if (JobEndpoints.ParseRender(queued.ParametersJson) is not { } parameters || capabilities is null || !Renders(capabilities, parameters)) continue; // What the job renders now decides too (owner review 1, phase 4): the sequence's own settings may have changed // since it was queued, and a job of an older server carries no settings format. diff --git a/src/Chronos.Server/Storage/ServerEventBridge.cs b/src/Chronos.Server/Storage/ServerEventBridge.cs index 5715812b..c2077c9b 100644 --- a/src/Chronos.Server/Storage/ServerEventBridge.cs +++ b/src/Chronos.Server/Storage/ServerEventBridge.cs @@ -18,14 +18,18 @@ public static class ServerEventBridge /// /// A Reorganize, a conversion, a render or an analysis changed or made sequence : clients are told - /// (sequenceChanged), and a conversion's or an analysis's settings become Main's next version soon. + /// (sequenceChanged), and a conversion's or an analysis's settings become Main's next version soon. With + /// (a shared desktop library, owner review 5, #67), only of a sequence of that archive: the + /// desktop's other archives are none of its clients' business. /// - public static async Task SequenceChangedAsync(ChronosDatabase db, EventHub events, ProjectCatchUp? projects, Guid id, string change, CancellationToken ct) + public static async Task SequenceChangedAsync(ChronosDatabase db, EventHub events, ProjectCatchUp? projects, Guid id, string change, CancellationToken ct, + ServerArchive? served = null) { ArgumentNullException.ThrowIfNull(db); ArgumentNullException.ThrowIfNull(events); - if (await db.Sequences.GetAsync(id, ct).ConfigureAwait(false) is { } sequence) - events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion)); + var sequence = await db.Sequences.GetAsync(id, ct).ConfigureAwait(false); + if (served is not null && !served.Owns(sequence)) return; + if (sequence is not null) events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion)); // A conversion may leave settings Main has not taken yet, and an analysis writes Auto values (owner review 2, R8). if (change is ConvertedChange or ProcessingOptions.SettingsChange) projects?.Touch(id); } @@ -33,16 +37,20 @@ public static class ServerEventBridge /// /// Every change of a sequence's projects reaches connected clients (owner review 2, R8): a workspace with that project /// checked out knows its home moved, the admin panel lists the projects again. Main's head written into the sequence's - /// settings is a settings change for the clients that read those (an older client, a desktop's sync). + /// settings is a settings change for the clients that read those (an older client, a desktop's sync). With + /// , only of a sequence of that archive (as ). /// - public static async Task ProjectsChangedAsync(ChronosDatabase db, EventHub events, ProjectChangeSet changed, CancellationToken ct) + public static async Task ProjectsChangedAsync(ChronosDatabase db, EventHub events, ProjectChangeSet changed, CancellationToken ct, + ServerArchive? served = null) { ArgumentNullException.ThrowIfNull(db); ArgumentNullException.ThrowIfNull(events); ArgumentNullException.ThrowIfNull(changed); + var sequence = served is not null || changed.SettingsChanged ? await db.Sequences.GetAsync(changed.SequenceId, ct).ConfigureAwait(false) : null; + if (served is not null && !served.Owns(sequence)) return; foreach (var change in changed.Changes) events.Publish(new ProjectChangedEvent(changed.SequenceId, change.ProjectId, change.Change, change.HeadNumber, change.HeadVersionId)); - if (changed.SettingsChanged && await db.Sequences.GetAsync(changed.SequenceId, ct).ConfigureAwait(false) is { } sequence) + if (changed.SettingsChanged && sequence is not null) events.Publish(new SequenceChangedEvent(sequence.Id, "settings", sequence.FramesVersion, sequence.SettingsVersion)); } } diff --git a/src/Chronos.Setup/Engine/InstallPlan.cs b/src/Chronos.Setup/Engine/InstallPlan.cs index 071422d3..4d5d6aa2 100644 --- a/src/Chronos.Setup/Engine/InstallPlan.cs +++ b/src/Chronos.Setup/Engine/InstallPlan.cs @@ -9,7 +9,7 @@ namespace Chronos.Setup.Engine; /// (upgrade in place) and suggests its components; otherwise the switches, then the manifest defaults, apply. A /// component of the previous installation that this payload no longer ships is retained (, kept /// unless the switches leave it out or the user unticks it); a separate 1.0 Uploader product () -/// fixes the scope of a new installation and preselects the Uploader, which replaces it. A component that installs +/// preselects the Uploader, which replaces it, and then fixes the scope and the folder of a new installation. A component that installs /// for all users only () makes a new installation an all-users one, in a /// folder inside Program Files; an installation upgraded in place elsewhere cannot take it. /// @@ -37,8 +37,6 @@ internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOn /// from what was found on this PC (no registry access). public static InstallPlan Resolve(PayloadManifest manifest, SetupArguments arguments, ExistingInstall? existing, InstallLog? previous, LegacyInstall? legacy) { - // Without an installation of its own, a legacy Uploader fixes the scope: its removal needs the same account. - var scope = existing?.Scope ?? legacy?.Scope ?? (arguments.AllUsers ? InstallScope.AllUsers : InstallScope.CurrentUser); var retained = existing is null ? [] : LegacyProducts.Retained(manifest, previous); IReadOnlyList components; @@ -64,10 +62,14 @@ internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOn kept = retained; } + // Without an installation of its own, a legacy Uploader the Uploader replaces fixes the scope and the folder: its + // removal needs the same account. One that stays (the Uploader is not installed) fixes nothing. + var replacing = existing is null && legacy is not null && components.Contains(LegacyProducts.UploaderComponent, StringComparer.OrdinalIgnoreCase); + var scope = existing?.Scope ?? (replacing ? legacy!.Scope : arguments.AllUsers ? InstallScope.AllUsers : InstallScope.CurrentUser); var allUsersOnly = components.Where(id => manifest.FindComponent(id)!.AllUsersOnly).ToList(); - var fixedLocation = existing is not null || legacy is not null; + var fixedLocation = existing is not null || replacing; if (allUsersOnly.Count > 0 && !fixedLocation) scope = InstallScope.AllUsers; - var directory = existing?.Directory ?? (legacy is null ? arguments.Directory : null) ?? SetupPaths.DefaultDirectory(scope, manifest.Product); + var directory = existing?.Directory ?? (replacing ? null : arguments.Directory) ?? SetupPaths.DefaultDirectory(scope, manifest.Product); if (allUsersOnly.Count > 0 && fixedLocation && !IsServiceSafe(scope, directory)) { if (arguments.Components is not null) @@ -81,8 +83,15 @@ internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOn return new InstallPlan(scope, directory, components, existing) { Previous = previous, Retained = retained, Kept = kept, Legacy = legacy }; } - /// False while the folder and scope are fixed: an installation is upgraded in place, or a legacy Uploader sets the scope. - public bool CanChangeLocation => Existing is null && Legacy is null; + /// False while the folder and scope are fixed: an installation is upgraded in place, or a legacy Uploader the planned Uploader replaces sets the scope. + public bool CanChangeLocation => !LocksLocation(Components); + + /// + /// True when installing fixes the folder and the scope: an installation is upgraded in + /// place, or the Uploader among them replaces a legacy Uploader, whose removal needs the same account. + /// + public bool LocksLocation(IEnumerable components) => + Existing is not null || (Legacy is not null && components.Contains(LegacyProducts.UploaderComponent, StringComparer.OrdinalIgnoreCase)); /// /// False for a component that installs for all users only when the folder and scope are fixed and are not an diff --git a/src/Chronos.Setup/Engine/SilentSetup.cs b/src/Chronos.Setup/Engine/SilentSetup.cs index f92f9901..62b522ce 100644 --- a/src/Chronos.Setup/Engine/SilentSetup.cs +++ b/src/Chronos.Setup/Engine/SilentSetup.cs @@ -48,6 +48,14 @@ internal static class SilentSetup var plan = InstallPlan.Resolve(engine.Manifest, arguments); if (plan.Existing is not null && arguments.Directory is not null && !SetupPaths.IsSameOrInside(arguments.Directory, plan.Directory)) Log.Warning("setup", $"/DIR ignored: {engine.Manifest.Product} is already installed in '{plan.Directory}'"); + if (plan.Existing is null && plan.Legacy is { } found && plan.LocksLocation(plan.Components)) + { + // The Uploader replaces the separate 1.0 one, whose removal needs its account: its scope and the default folder win. + if (arguments.Directory is not null && !SetupPaths.IsSameOrInside(arguments.Directory, plan.Directory)) + Log.Warning("setup", $"/DIR ignored: the Uploader replaces the one in '{found.Directory}', so {engine.Manifest.Product} goes in '{plan.Directory}'"); + if (arguments.AllUsers && plan.Scope != InstallScope.AllUsers) + Log.Warning("setup", $"/ALLUSERS ignored: the Uploader replaces the one in '{found.Directory}', installed for the current user"); + } if (!InstallPlan.IsValidDirectory(engine.Manifest, plan.Scope, plan.Directory, plan.Components)) { Log.Error("setup", $"'{plan.Directory}' cannot take {string.Join(", ", plan.Components)} for {plan.Scope}"); diff --git a/src/Chronos.Setup/Views/SetupViewModel.cs b/src/Chronos.Setup/Views/SetupViewModel.cs index 71c05502..5c6256f6 100644 --- a/src/Chronos.Setup/Views/SetupViewModel.cs +++ b/src/Chronos.Setup/Views/SetupViewModel.cs @@ -54,6 +54,7 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo private SetupStage _stage; private string _directory = string.Empty; private bool _allUsers; + private bool _locationLocked; private bool _desktop; private bool _startMenu; private bool _launchAfter; @@ -102,6 +103,7 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo InstalledVersionOf(c.Id), UnavailableReason(c), OnComponentsChanged)), .. _plan!.Retained.Select(r => new ComponentOption(r, _plan.Kept.Any(k => k.Id.Equals(r.Id, StringComparison.OrdinalIgnoreCase)), OnComponentsChanged)), ]; + _locationLocked = !CanChangeLocation; Languages = [.. Core.Localization.Languages.Shipped.Select(c => new LanguageOption(c, Core.Localization.Languages.NativeName(c)))]; PrimaryCommand = new RelayCommand(() => @@ -209,8 +211,11 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo public string RequiredSpaceText => _engine is null ? string.Empty : Loc.L("Setup.Space.Required", ByteSize.Format(_engine.RequiredBytes(SelectedComponents))); - /// False when upgrading (the existing folder and scope are kept) or replacing a legacy Uploader (its scope is). - public bool CanChangeLocation => _plan is null || _plan.CanChangeLocation; + /// + /// False when upgrading (the existing folder and scope are kept) or when the ticked Uploader replaces a legacy one (its + /// scope is); unticking that Uploader frees them again. + /// + public bool CanChangeLocation => _plan is null || !_plan.LocksLocation(SelectedComponents); /// An installation of this product exists: Update replaces it in place. private bool IsUpgrade => _plan?.Existing is not null; @@ -241,12 +246,14 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo var replaces = _plan.Legacy is { } found && LegacyProducts.CanMerge(found, Scope, _directory); if (IsUpgrade) { + // A 1.0 log (format 1) recorded no SHA-256: its files are removed by the list, changed or not. + var removeToolTip = _plan.Previous is { Hashes.Count: > 0 } ? "Tooltips.Setup.Changes.Remove" : "Tooltips.Setup.Changes.RemoveUnchecked"; foreach (var c in Components) { if (c.Retained is { } retained && !c.IsSelected) rows.Add(new ChangeRow(Loc.L("Setup.Changes.Remove", c.Name), Loc.L("Tooltips.Setup.Changes.RemoveRetained", FileList(retained.Files)), true)); else if (!c.IsRetained && c.IsInstalled && !c.IsSelected) - rows.Add(new ChangeRow(Loc.L("Setup.Changes.Remove", c.Name), Loc.L("Tooltips.Setup.Changes.Remove"), true)); + rows.Add(new ChangeRow(Loc.L("Setup.Changes.Remove", c.Name), Loc.L(removeToolTip), true)); // An Uploader that replaces the legacy one is said by "Replaces Chronos Uploader 1.0.0" below. else if (!c.IsRetained && !c.IsInstalled && c.IsSelected && !(replaces && c.Id.Equals(LegacyProducts.UploaderComponent, StringComparison.OrdinalIgnoreCase))) rows.Add(new ChangeRow(Loc.L("Setup.Changes.Add", c.Name), Loc.L("Tooltips.Setup.Changes.Add"), false)); @@ -820,6 +827,20 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo private void OnComponentsChanged() { + // Ticking the Uploader again beside a legacy one brings back the scope and the folder its replacement needs. + var locked = !CanChangeLocation; + if (locked != _locationLocked) + { + _locationLocked = locked; + if (locked && _plan is { Existing: null, Legacy: { } legacy }) + { + IsAllUsers = legacy.Scope == InstallScope.AllUsers; + Directory = DefaultDirectory(); + } + OnPropertyChanged(nameof(CanChangeLocation)); + OnPropertyChanged(nameof(BrowseToolTip)); + OnPropertyChanged(nameof(AllUsersToolTip)); + } // The Server runs as a LocalSystem service, which must not start a program its user can replace: selecting it // moves a new installation to all users (Program Files). if (AllUsersComponent is not null && !_allUsers && CanChangeLocation) IsAllUsers = true; diff --git a/src/Chronos.Tools/Commands/PackInstallerCommand.cs b/src/Chronos.Tools/Commands/PackInstallerCommand.cs index 229b3ca4..4f05cc58 100644 --- a/src/Chronos.Tools/Commands/PackInstallerCommand.cs +++ b/src/Chronos.Tools/Commands/PackInstallerCommand.cs @@ -7,7 +7,9 @@ namespace Chronos.Tools.Commands; /// pack-installer --setup Chronos.Setup.exe --product Chronos --version 1.2.3 --component Id=folder … --out file [--legacy]: /// appends a TPK1 payload (BRIEF §18) to the setup program. Known component ids carry their display name, default /// selection, shortcuts and file types: Chronos (alias Desktop), the desktop app, preselected, and -/// Uploader, not preselected; unknown ids are packed as plain, preselected components. Chronos Server is no +/// Uploader, not preselected; unknown ids are packed as plain, preselected components. A setup of one component +/// preselects it, as the separate 1.0 Uploader setup the CI test stands in for did: a silent run without +/// /COMPONENTS installs it. Chronos Server is no /// longer packed (it ships as a Docker image): Server is refused unless --legacy, which packs it as 1.0 /// named it (not preselected, Start menu shortcut) for the CI test of a retained 1.0 Server, installable for the /// current user so that the test needs no administrator rights. @@ -82,6 +84,9 @@ internal sealed class PackInstallerCommand : ICommand if (known.Association is { } association) associations.Add(association); } + // A single component is what the setup installs: preselected, or a silent run without /COMPONENTS would install nothing. + if (components is [var only] && !only.DefaultSelected) components[0] = only with { DefaultSelected = true }; + var source = new PayloadSource { Product = Required(options, "product"), diff --git a/src/Chronos.Uploader/App.xaml.cs b/src/Chronos.Uploader/App.xaml.cs index 8c222ec2..2a926953 100644 --- a/src/Chronos.Uploader/App.xaml.cs +++ b/src/Chronos.Uploader/App.xaml.cs @@ -125,7 +125,7 @@ public partial class App : Application var dialogs = new UploaderDialogs(); _vm = new MainViewModel(new UploaderServices(settings, SaveSettings, _session, _queue, _engine, startup, dialogs, _watch, _memory, environment.LogDirectory) { - Updates = UploaderUpdates.Host(environment.IsPortable), + Updates = UploaderUpdates.Host(), }); _window = new Shell.MainWindow(_vm, settings); dialogs.Owner = _window; diff --git a/src/Chronos.Uploader/Infrastructure/UploaderUpdates.cs b/src/Chronos.Uploader/Infrastructure/UploaderUpdates.cs index 6d7d8f3a..ddf87b0d 100644 --- a/src/Chronos.Uploader/Infrastructure/UploaderUpdates.cs +++ b/src/Chronos.Uploader/Infrastructure/UploaderUpdates.cs @@ -9,7 +9,8 @@ namespace Chronos.Uploader.Infrastructure; /// /// The Uploader's side of the shared update notice (BRIEF §18, owner review 5): the same releases feed, the same single -/// setup (or the portable zip of a portable copy) and the same %TEMP%\Chronos\updates folder as the desktop. +/// setup and the same %TEMP%\Chronos\updates folder as the desktop. Always the setup, even for a portable copy: the +/// portable zip holds the desktop app alone, so it could not update the Uploader. /// public static class UploaderUpdates { @@ -23,16 +24,15 @@ public static class UploaderUpdates typeof(UploaderUpdates).Assembly.GetCustomAttribute()?.InformationalVersion ?? "0.0.0"; /// The live host: the public releases repository, the shell's browser and Explorer. - public static UpdateHost Host(bool portable) => - Host(Http.Value, DownloadHttp.Value, ProductLinks.Repository, VersionText, portable, UpdateDownload.Root(Path.GetTempPath()), ShellActions.OpenUrl, - ShellActions.Reveal); + public static UpdateHost Host() => + Host(Http.Value, DownloadHttp.Value, ProductLinks.Repository, VersionText, UpdateDownload.Root(Path.GetTempPath()), ShellActions.OpenUrl, ShellActions.Reveal); /// A host over the given clients and releases repository ("https://host/owner/name"); tests pass a fake transport. - public static UpdateHost Host(HttpClient http, HttpClient downloadHttp, string repository, string versionText, bool portable, string downloadRoot, + public static UpdateHost Host(HttpClient http, HttpClient downloadHttp, string repository, string versionText, string downloadRoot, Action openUrl, Action reveal) => - new(UpdateCheck.RunningVersion(versionText), IsCapture: false, portable, + new(UpdateCheck.RunningVersion(versionText), IsCapture: false, IsPortable: false, ct => UpdateCheck.FetchAsync(http, ProductLinks.StableReleasesApiOf(repository), repository, versionText, ct), - (release, progress, ct) => UpdateDownload.DownloadAsync(downloadHttp, release, portable, downloadRoot, versionText, progress, UpdateDownload.IdleTimeout, ct), + (release, progress, ct) => UpdateDownload.DownloadAsync(downloadHttp, release, portable: false, downloadRoot, versionText, progress, UpdateDownload.IdleTimeout, ct), openUrl, reveal) { RunningIsPrerelease = UpdateCheck.IsPrerelease(versionText), diff --git a/src/Chronos.Uploader/Shell/UpdatesViewModel.cs b/src/Chronos.Uploader/Shell/UpdatesViewModel.cs index 8a65b7b5..7512d411 100644 --- a/src/Chronos.Uploader/Shell/UpdatesViewModel.cs +++ b/src/Chronos.Uploader/Shell/UpdatesViewModel.cs @@ -12,7 +12,7 @@ namespace Chronos.Uploader.Shell; /// /// The Updates row of the Uploader's settings panel (BRIEF §18, owner review 5): Check on start (opt-out), Check now, -/// then Download, which fetches the single setup (the portable zip for a portable copy), verifies it against the +/// then Download, which fetches the single setup (also for a portable copy), verifies it against the /// release's SHA256SUMS and shows it in Explorer, and Show setup. The work is the desktop's . /// The start-up check is skipped when Chronos Desktop sits beside the Uploader: its own notice covers the same setup. /// @@ -100,18 +100,18 @@ public sealed class UpdatesViewModel : LocalizedViewModel public bool IsDownloading => _flow.State == UpdateState.Downloading; - /// The verified setup or portable zip is in the temporary folder. + /// The verified setup is in the temporary folder. public bool IsReady => _flow.State == UpdateState.Downloaded; /// The verified package; null until a download succeeded. public string? PackagePath => _flow.PackagePath; - /// What Download does here: fetch and verify the setup or the portable zip (with its size), or open the release page. + /// What Download does here: fetch and verify the setup (with its size), or open the release page. public string DownloadToolTip => _flow.Package is { } package - ? Loc.L(_flow.IsPortable ? "Tooltips.Uploader.Updates.DownloadPortable" : "Tooltips.Uploader.Updates.Download", UploaderText.Bytes(package.Size, Loc.Culture)) + ? Loc.L("Tooltips.Uploader.Updates.Download", UploaderText.Bytes(package.Size, Loc.Culture)) : Loc.L("Tooltips.Uploader.Updates.DownloadPage"); - public string ShowSetupToolTip => Loc.L(_flow.IsPortable ? "Tooltips.Uploader.Updates.ShowPortable" : "Tooltips.Uploader.Updates.ShowSetup"); + public string ShowSetupToolTip => Loc.L("Tooltips.Uploader.Updates.ShowSetup"); /// The start-up check runs when the user left it on and Chronos Desktop is not installed beside the Uploader. public static bool ChecksOnStart(bool enabled, bool desktopBeside) => enabled && !desktopBeside; diff --git a/tests/Chronos.App.Tests/Archive/ArchiveLogicTests.cs b/tests/Chronos.App.Tests/Archive/ArchiveLogicTests.cs index 00cf5afe..4db89605 100644 --- a/tests/Chronos.App.Tests/Archive/ArchiveLogicTests.cs +++ b/tests/Chronos.App.Tests/Archive/ArchiveLogicTests.cs @@ -9,6 +9,7 @@ using Chronos.Core.Localization; using Chronos.Core.Model; using Chronos.Data; using Chronos.Data.Archiving; +using Chronos.Data.Jobs; using Chronos.Data.Repositories; using Chronos.Testing; using Chronos.Ui.Controls; @@ -260,6 +261,29 @@ public sealed class ArchiveLogicTests Assert.SequenceEqual(new[] { "sunset", "dusk" }, changes.Single().Tags); } + [Test] + public void AMaintenanceJobQueuedWhileTheScreenIsShownJoinsRecent() + { + var archive = Guid.NewGuid(); + var now = DateTimeOffset.UtcNow; + IReadOnlyList jobs = [new Job { Id = Guid.NewGuid(), Kind = JobKind.Scan, State = JobState.Done, TargetIds = [archive], Created = now.AddDays(-1), Finished = now.AddDays(-1) }]; + var verify = new Job { Id = Guid.NewGuid(), Kind = JobKind.Verify, State = JobState.Queued, TargetIds = [archive], TargetLabel = "Main", Created = now }; + + jobs = MaintenanceReports.Track(jobs, verify, archive); + Assert.Equal(2, jobs.Count); + var running = verify with { State = JobState.Running, Started = now }; + jobs = MaintenanceReports.Track(jobs, running, archive); + Assert.Equal(2, jobs.Count); + var live = new Dictionary { [verify.Id] = new(verify.Id, JobKind.Verify, "Main", 40, 100, null, null, null) }; + var recent = MaintenanceReports.Recent(jobs, 5, live); + Assert.Equal(verify.Id, recent[0].JobId); + Assert.Equal("40 %", recent[0].StateText); + + // Another archive's job, or another kind of job, leaves the list as it is. + Assert.Same(jobs, MaintenanceReports.Track(jobs, running with { Id = Guid.NewGuid(), TargetIds = [Guid.NewGuid()] }, archive)); + Assert.Same(jobs, MaintenanceReports.Track(jobs, running with { Id = Guid.NewGuid(), Kind = JobKind.Render }, archive)); + } + [Test] public void ReportsListDuplicatesOrphansAndRecentMaintenance() { diff --git a/tests/Chronos.App.Tests/Jobs/JobTextTests.cs b/tests/Chronos.App.Tests/Jobs/JobTextTests.cs index fd110116..0f51020a 100644 --- a/tests/Chronos.App.Tests/Jobs/JobTextTests.cs +++ b/tests/Chronos.App.Tests/Jobs/JobTextTests.cs @@ -96,6 +96,21 @@ public sealed class JobTextTests Assert.Equal("3 / 9", JobText.Counter(JobKind.Scan, 3, 9)); } + [Test] + public void TheBarsTooltipHasTheLineWholeWithItsItem() + { + Loc.SetCulture(CultureInfo.GetCultureInfo("en")); + var job = Job(JobKind.Verify, JobState.Running, "Archive") with + { + Detail = new JobDetail(JobStep.Verify, "2024/2024-09-27 Harbour sunset at the old lighthouse", 812, 2_400, 3, 41, JobPartUnit.Sequence), + }; + var entry = new JobEntry(job); + // The bar cuts the line at 60 characters, dropping the sequence first; the tooltip names it. + Assert.False(JobText.Bar(entry).Contains("Harbour sunset", StringComparison.Ordinal), JobText.Bar(entry)); + Assert.Equal("Verify · Archive · " + JobText.Status(job.Detail), JobText.BarToolTip(entry)); + Assert.Contains("Harbour sunset at the old lighthouse", JobText.BarToolTip(entry)); + } + [Test] public void LiveDetailWinsAndStoppedJobsSayWhere() { diff --git a/tests/Chronos.App.Tests/Jobs/ServerJobsListTests.cs b/tests/Chronos.App.Tests/Jobs/ServerJobsListTests.cs index 7c549bbf..eb725a47 100644 --- a/tests/Chronos.App.Tests/Jobs/ServerJobsListTests.cs +++ b/tests/Chronos.App.Tests/Jobs/ServerJobsListTests.cs @@ -64,6 +64,24 @@ public sealed class ServerJobsListTests Assert.False(vm.HasRows); } + [Test] + public async Task AJobThatStartedBeforeTheEventsOpenedJoinsOnItsProgress() + { + Loc.SetCulture(CultureInfo.GetCultureInfo("en")); + var api = new FakeJobsApi(); + using var vm = new ServerJobsViewModel(() => new ServerJobsAccount("a", false), () => api, new IdleContext()); + await UpdatedAsync(vm, vm.Refresh); + Assert.Empty(vm.Rows); + + // Started between the list and the event socket: its running state was never told, its progress is. + var id = api.Add("thumbs", "Lake", "running"); + await UpdatedAsync(vm, () => api.Events.Writer.TryWrite(new JobProgressEvent(id, 40, 100, 3, 20, + new JobDetailDto("thumbs", "Lake", 40, 100)))); + var row = vm.Rows.Single(); + Assert.Equal(id, row.Id); + Assert.Equal(40d / 100, row.Progress); + } + [Test] public async Task AManagingAccountPausesResumesAndCancels() { diff --git a/tests/Chronos.App.Tests/Setup/SingleSetupTests.cs b/tests/Chronos.App.Tests/Setup/SingleSetupTests.cs index 67c1196f..65b4d3bf 100644 --- a/tests/Chronos.App.Tests/Setup/SingleSetupTests.cs +++ b/tests/Chronos.App.Tests/Setup/SingleSetupTests.cs @@ -193,6 +193,24 @@ public sealed class SingleSetupTests(TestContext context) Assert.Null(LegacyProducts.FindUploader(Manifest("ChronosTest" + Guid.NewGuid().ToString("N")[..12]))); } + [Test] + public void ALegacyUploaderLeftInPlaceFixesNeitherTheScopeNorTheFolder() + { + var manifest = Manifest(); + var root = context.CreateTempDirectory("legacy-kept"); + var legacy = Legacy(Path.Combine(root, "Chronos Uploader"), InstallScope.CurrentUser); + var elsewhere = Path.Combine(root, "Apps", "Chronos"); + + // The Uploader is not installed, so nothing is merged: the switches decide where Chronos goes. + var plan = InstallPlan.Resolve(manifest, new SetupArguments { AllUsers = true, Directory = elsewhere, Components = ["Desktop"] }, null, null, legacy); + Assert.Equal(InstallScope.AllUsers, plan.Scope); + Assert.Equal(elsewhere, plan.Directory); + Assert.SequenceEqual(["Chronos"], plan.Components); + Assert.True(plan.CanChangeLocation); + Assert.Null(plan.LegacyToReplace(plan.Components, plan.Scope, plan.Directory)); + Assert.True(plan.LocksLocation(["Chronos", "Uploader"]), "ticking the Uploader would replace the legacy one"); + } + [Test] [WindowsOnly] public void ReplacingTheLegacyUploaderMovesItsSignInEntryAndKeepsItTurnedOff() @@ -306,6 +324,31 @@ public sealed class SingleSetupTests(TestContext context) Assert.False(replace.CanChangeLocation); Assert.Equal("Replaces Chronos Uploader 1.0.0", replace.ChangesText); Assert.False(replace.IsUninstallAll); + + // Unticked, the Uploader replaces nothing: the folder and the scope can change; ticked again, they are the legacy copy's. + var uploader = Assert.Contains(replace.Components, c => c.Id == "Uploader"); + uploader.IsSelected = false; + Assert.True(replace.CanChangeLocation); + replace.IsAllUsers = true; + replace.Directory = Path.Combine(root, "Apps", "Chronos"); + uploader.IsSelected = true; + Assert.False(replace.CanChangeLocation); + Assert.False(replace.IsAllUsers); + Assert.Equal(SetupPaths.DefaultDirectory(InstallScope.CurrentUser, manifest.Product), replace.Directory); + } + + // Removing a program of a 1.0 installation (its log has no SHA-256) never promises to keep a changed file. + var hashed = ServerLog(directory); + hashed.FormatVersion = 2; + hashed.Components = ["Chronos", "Uploader"]; + hashed.Hashes["Chronos.Uploader.exe"] = new string('2', 64); + foreach (var (log, key) in new[] { (hashed, "Tooltips.Setup.Changes.Remove"), (ServerLog(directory), "Tooltips.Setup.Changes.RemoveUnchecked") }) + { + log.Components = ["Chronos", "Uploader"]; + using var removal = SetupViewModel.ForInstall(new SetupArguments(), payload, InstallPlan.Resolve(manifest, new SetupArguments(), existing, log, null)); + Assert.Contains(removal.Components, c => c.Id == "Uploader").IsSelected = false; + Assert.Count(1, removal.Changes); + Assert.Equal(Loc.L(key), removal.Changes[0].ToolTip); } // A new installation with nothing ticked cannot start, and is no uninstall. diff --git a/tests/Chronos.App.Tests/Uploader/UploaderUpdatesTests.cs b/tests/Chronos.App.Tests/Uploader/UploaderUpdatesTests.cs index fb4720b1..26298cf5 100644 --- a/tests/Chronos.App.Tests/Uploader/UploaderUpdatesTests.cs +++ b/tests/Chronos.App.Tests/Uploader/UploaderUpdatesTests.cs @@ -188,6 +188,15 @@ public sealed class UploaderUpdatesTests(TestContext context) Assert.Equal(UpdateState.Unknown, vm.State); }); + [Test] + public void APortableUploaderIsOfferedTheSetupTheZipHoldsNoUploader() + { + // The portable zip carries the desktop app alone: whatever the copy, the Uploader updates through the setup. + Assert.False(Host(new Feed(), context.CreateTempDirectory(), []).IsPortable); + using var vm = new UpdatesViewModel(Host(new Feed(), context.CreateTempDirectory(), []), new UploaderSettings(), () => { }); + Assert.Equal(Loc.L("Tooltips.Uploader.Updates.ShowSetup"), vm.ShowSetupToolTip); + } + private UpdatesViewModel Notice(Feed feed, out List revealed) { revealed = []; @@ -197,7 +206,7 @@ public sealed class UploaderUpdatesTests(TestContext context) private static UpdateHost Host(Feed feed, string downloadRoot, List revealed) { var http = new HttpClient(feed, disposeHandler: false); - return UploaderUpdates.Host(http, http, Repository, "1.0.0", portable: false, downloadRoot, _ => { }, revealed.Add); + return UploaderUpdates.Host(http, http, Repository, "1.0.0", downloadRoot, _ => { }, revealed.Add); } private static async Task RunAsync(System.Windows.Input.ICommand command) diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs index 908d385b..29423a02 100644 --- a/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs +++ b/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs @@ -58,6 +58,25 @@ public sealed class WorkspaceHostTests(TestContext context) } } + [Test] + public void AProjectOpenInTheEditorIsHeldUntilItsSourceCloses() + { + var installed = AppEnvironment.From(AppPaths.Resolve(context.CreateTempDirectory("app"), context.CreateTempDirectory("local"), [])); + var host = new WorkspaceHost(installed, new AppSettings(), () => { }, () => null, () => null, () => null); + var project = Guid.CreateVersion7(); + Assert.False(host.HasProjectsInEditor); + + // The same project in two editors, then each closing (one twice): held until the last one closes. + var first = host.HoldInEditor(project); + var second = host.HoldInEditor(project); + Assert.True(host.HasProjectsInEditor, "a server's home does not move under an open editor"); + first.Dispose(); + first.Dispose(); + Assert.True(host.HasProjectsInEditor, "the second editor still has it"); + second.Dispose(); + Assert.False(host.HasProjectsInEditor); + } + [Test] public void TheWorkspaceSettingsSurviveTheSettingsFile() { diff --git a/tests/Chronos.Data.Tests/Homes/HomeLayoutMigrationTests.cs b/tests/Chronos.Data.Tests/Homes/HomeLayoutMigrationTests.cs index ad5404bc..893c141b 100644 --- a/tests/Chronos.Data.Tests/Homes/HomeLayoutMigrationTests.cs +++ b/tests/Chronos.Data.Tests/Homes/HomeLayoutMigrationTests.cs @@ -190,6 +190,11 @@ public sealed class HomeLayoutMigrationTests(TestContext context) var homes = new WorkspaceHomes(legacy.Workspace); Assert.Equal(homes.Root, Path.GetDirectoryName(Assert.NotNull(homes.Find(legacy.Local)).Folder)); Assert.Equal(4, homes.List().Count); + // A copy, render or send job of the project left in place still finds it: the parent opens as the view of what it holds. + var root = WorkspaceJobRoots.Resolve(legacy.Workspace, legacy.Local, null, "Errors.Workspace.NotCheckedOut"); + Assert.Equal(WorkspaceStore.FullRoot(legacy.Workspace), root); + Assert.Throws(() => new WorkspaceStore(root)); + Assert.NotNull(WorkspaceStore.ForJob(root).Find(legacy.Local)); } result = await legacy.Migration().ApplyAsync(context.Cancellation); Assert.Equal((1, 0), (result.ProjectsMoved, result.InUse)); diff --git a/tests/Chronos.Data.Tests/Jobs/JobContextProgressTests.cs b/tests/Chronos.Data.Tests/Jobs/JobContextProgressTests.cs index f2c969a9..0c00b675 100644 --- a/tests/Chronos.Data.Tests/Jobs/JobContextProgressTests.cs +++ b/tests/Chronos.Data.Tests/Jobs/JobContextProgressTests.cs @@ -14,6 +14,9 @@ public sealed class JobContextProgressTests(TestContext context) { private static readonly TimeSpan Tick = TimeSpan.FromMilliseconds(10); + /// A quarter of the default publish interval: what a new step waits since the last publish. + private static readonly TimeSpan StepWait = TimeSpan.FromMilliseconds(125); + [Test] public async Task AHundredReportsInASecondGoOutAtMostThreeTimes() { @@ -24,8 +27,46 @@ public sealed class JobContextProgressTests(TestContext context) run.Time.Advance(Tick); } Assert.True(run.Published.Count <= 3, $"{run.Published.Count} publishes"); - // The first at once, then one per half second. - Assert.SequenceEqual([1L, 51L], run.Published.Select(p => p.Done)); + // The first at once, then one per half second: the latest state when its time comes. + Assert.SequenceEqual([1L, 50L, 100L], run.Published.Select(p => p.Done)); + } + + [Test] + public async Task AJobGoneQuietInALongStepShowsItsLatestStateOnTime() + { + await using var run = await StartAsync(); + // Maintenance: its first sub-steps take milliseconds, the third runs for minutes without a report. + await run.Context.ReportAsync(0, 5, new JobDetail(JobStep.Maintenance, "leases", 0, 0, 1, 5, JobPartUnit.Step)); + run.Time.Advance(TimeSpan.FromMilliseconds(30)); + await run.Context.CheckpointAsync("leases", 1, 5, new JobDetail(JobStep.Maintenance, "temp", 0, 0, 2, 5, JobPartUnit.Step)); + run.Time.Advance(TimeSpan.FromMilliseconds(30)); + var packs = new JobDetail(JobStep.Maintenance, "packs", 0, 0, 3, 5, JobPartUnit.Step); + await run.Context.CheckpointAsync("temp", 2, 5, packs); + Assert.Count(1, run.Published); + + run.Time.Advance(TimeSpan.FromMilliseconds(500)); + Assert.Count(2, run.Published); + Assert.Equal((2L, packs), (run.Published[^1].Done, run.Published[^1].Detail)); + // Nothing new: nothing more goes out. + run.Time.Advance(TimeSpan.FromSeconds(10)); + Assert.Count(2, run.Published); + } + + [Test] + public async Task AJobThatAlternatesStepsGoesOutAFewTimesASecond() + { + await using var run = await StartAsync(); + // An incremental scan: every other folder changed, checked and indexed in turn, 200 reports in a second. + for (var i = 0; i < 200; i++) + { + var step = i % 2 == 0 ? JobStep.Check : JobStep.Index; + await run.Context.ReportAsync(i, 10_000, new JobDetail(step, "folder " + i, 0, 0, i + 1, 10_000, JobPartUnit.Folder)); + run.Time.Advance(TimeSpan.FromMilliseconds(5)); + } + Assert.True(run.Published.Count <= 10, $"{run.Published.Count} publishes"); + // The last report still goes out once its time comes. + run.Time.Advance(TimeSpan.FromSeconds(1)); + Assert.Equal(199L, run.Published[^1].Done); } [Test] @@ -36,7 +77,8 @@ public sealed class JobContextProgressTests(TestContext context) await run.Context.ReportAsync(1, 10, new JobDetail(JobStep.List)); run.Time.Advance(Tick); await run.Context.ReportAsync(2, 10, new JobDetail(JobStep.List)); - run.Time.Advance(Tick); + // A new step goes out once a quarter of the interval has passed, not at every switch. + run.Time.Advance(StepWait); await run.Context.ReportAsync(3, 10, index); run.Time.Advance(Tick); await run.Context.ReportItemAsync(4, 10, 2, 5); @@ -91,7 +133,7 @@ public sealed class JobContextProgressTests(TestContext context) Assert.Equal(published, run.Published.Count); var verify = new JobDetail(JobStep.Verify, "Harbour sunset", 1, 9, 1, 3, JobPartUnit.Sequence); - run.Time.Advance(Tick); + run.Time.Advance(StepWait); await run.Context.CheckpointAsync("53", 53, 100, verify); stored = await run.StoredAsync(); Assert.Equal((53L, "53", verify), (stored.ProgressDone, stored.Checkpoint, stored.Detail)); diff --git a/tests/Chronos.Data.Tests/Jobs/JobThroughputTests.cs b/tests/Chronos.Data.Tests/Jobs/JobThroughputTests.cs index e9746bc0..e6981448 100644 --- a/tests/Chronos.Data.Tests/Jobs/JobThroughputTests.cs +++ b/tests/Chronos.Data.Tests/Jobs/JobThroughputTests.cs @@ -5,16 +5,71 @@ using Chronos.Testing; namespace Chronos.Data.Tests.Jobs; -/// A clock the test moves by hand (BCL , no package). +/// +/// A clock the test moves by hand (BCL , no package), whose timers fire only when +/// reaches them, on the test's thread. +/// internal sealed class ManualTime : TimeProvider { + private readonly Lock _gate = new(); + private readonly List _timers = []; private long _ticks; public override long TimestampFrequency => TimeSpan.TicksPerSecond; public override long GetTimestamp() => Interlocked.Read(ref _ticks); - public void Advance(TimeSpan by) => Interlocked.Add(ref _ticks, by.Ticks); + public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) + { + var timer = new Timer(this, callback, state); + timer.Change(dueTime, period); + return timer; + } + + /// Moves the clock on, then fires each one-shot timer due by then. + public void Advance(TimeSpan by) + { + List due; + lock (_gate) + { + var now = Interlocked.Add(ref _ticks, by.Ticks); + due = [.. _timers.Where(t => t.Due <= now)]; + foreach (var timer in due) _timers.Remove(timer); + } + foreach (var timer in due) timer.Fire(); + } + + private void Schedule(Timer timer, TimeSpan dueTime) + { + lock (_gate) + { + _timers.Remove(timer); + if (dueTime == Timeout.InfiniteTimeSpan) return; + timer.Due = Interlocked.Read(ref _ticks) + dueTime.Ticks; + _timers.Add(timer); + } + } + + private sealed class Timer(ManualTime clock, TimerCallback callback, object? state) : ITimer + { + public long Due { get; set; } + + public bool Change(TimeSpan dueTime, TimeSpan period) + { + clock.Schedule(this, dueTime); + return true; + } + + public void Fire() => callback(state); + + public void Dispose() => clock.Schedule(this, Timeout.InfiniteTimeSpan); + + public ValueTask DisposeAsync() + { + Dispose(); + return ValueTask.CompletedTask; + } + } } [Category("jobs")] diff --git a/tests/Chronos.Data.Tests/Sync/SyncLinkRekeyTests.cs b/tests/Chronos.Data.Tests/Sync/SyncLinkRekeyTests.cs index 0d751b17..3c23b455 100644 --- a/tests/Chronos.Data.Tests/Sync/SyncLinkRekeyTests.cs +++ b/tests/Chronos.Data.Tests/Sync/SyncLinkRekeyTests.cs @@ -1,6 +1,9 @@ +using Chronos.Core.IO; +using Chronos.Data.Homes; using Chronos.Data.Sync; using Chronos.Data.Tests.Infrastructure; using Chronos.Data.Tests.Repositories; +using Chronos.Data.Workspaces; using Chronos.Testing; namespace Chronos.Data.Tests.Sync; @@ -59,6 +62,33 @@ public abstract class SyncLinkRekeyTests(TestContext context) : RepositoryTest(c Assert.Equal((0, 0), await store.RekeyAsync(Address, IdKey, Ct)); Assert.Equal((0, 0), await store.RekeyAsync(IdKey, IdKey, Ct)); } + + [Test] + public async Task TheLinksMoveToTheIdWhileTheFoldersWait() + { + var db = await OpenChronosAsync(); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var sequence = TestData.Sequence(archive.Id); + await db.Sequences.UpsertAsync(sequence, Ct); + var store = new SyncLinkStore(db); + var remote = Guid.CreateVersion7(); + await store.UpsertAsync(Link(Address, remote, sequence.Id, TestData.Now), Ct); + var data = Context.CreateTempDirectory("data"); + var workspace = new WorkspaceHomes(Path.Combine(data, "workspace")); + var home = Path.Combine(workspace.Root, "servers", HomeFolders.ServerFolder(Address)); + Directory.CreateDirectory(home); + var migration = new HomeLayoutMigration(new HomeLayoutOptions { DataDirectory = data, WorkspaceRoot = workspace.Root, Database = db }); + + // A download or an upload resumed under the id key finds its link before the folders move (a job held them). + var id = ServerIdentity.IdOf(IdKey)!.Value; + Assert.Equal((1, 0), await migration.RekeyLinksAsync(id, [Address, IdKey], Ct)); + Assert.Equal(sequence.Id, Assert.NotNull(await store.GetAsync(IdKey, remote, Ct)).LocalId); + Assert.Equal(sequence.Id, Assert.NotNull(await store.FindByLocalAsync(IdKey, sequence.Id, Ct)).LocalId); + Assert.Empty(await store.ListAsync(Address, Ct)); + Assert.True(Directory.Exists(home), "the folders wait for the full re-key"); + Assert.Equal((0, 0), await migration.RekeyLinksAsync(id, [Address], Ct)); + } } public sealed class SqliteSyncLinkRekeyTests(TestContext context) : SyncLinkRekeyTests(context) diff --git a/tests/Chronos.Server.Tests/Events/ProgressEventTests.cs b/tests/Chronos.Server.Tests/Events/ProgressEventTests.cs index c66f9bf8..1b0f97d7 100644 --- a/tests/Chronos.Server.Tests/Events/ProgressEventTests.cs +++ b/tests/Chronos.Server.Tests/Events/ProgressEventTests.cs @@ -90,6 +90,23 @@ public sealed class ProgressEventTests(TestContext context) Assert.Equal(TimeSpan.FromMilliseconds(500), ProgressGate.Interval); } + [Test] + public void AJobThatAlternatesStepsStillGoesOutAFewTimesASecond() + { + var clock = new TimestampClock(); + var gate = new ProgressGate(clock); + var job = Guid.CreateVersion7(); + // An incremental scan: every other folder changed, checked and indexed in turn, 200 reports in a second. + var passed = 0; + for (var i = 0; i < 200; i++) + { + if (gate.Passes(job, i, 10_000, i % 2 == 0 ? JobStep.Check : JobStep.Index)) passed++; + clock.Advance(TimeSpan.FromMilliseconds(5)); + } + Assert.True(passed <= 14, $"{passed} passed"); + Assert.True(passed >= 4, $"{passed} passed: a new step still goes out early"); + } + [Test] public async Task TheServerSendsAndSavesWhatItsJobsDo() { diff --git a/tests/Chronos.Server.Tests/Hosting/HostedServerTests.cs b/tests/Chronos.Server.Tests/Hosting/HostedServerTests.cs index 4db81467..59a42d93 100644 --- a/tests/Chronos.Server.Tests/Hosting/HostedServerTests.cs +++ b/tests/Chronos.Server.Tests/Hosting/HostedServerTests.cs @@ -117,6 +117,60 @@ public sealed class HostedServerTests(TestContext context) using (var get = await admin.GetAsync($"/api/v1/jobs/{workspace.Id}")) Assert.Equal(HttpStatusCode.NotFound, get.StatusCode); using (var cancel = await admin.PostAsync($"/api/v1/jobs/{workspace.Id}/cancel", null)) Assert.Equal(HttpStatusCode.NotFound, cancel.StatusCode); Assert.Equal(JobState.Queued, (await desktop.Database.Jobs.GetAsync(workspace.Id))!.State); + + // The events say nothing of the desktop's own jobs, nor of its work on its other archive; the shared archive's go out. + using var events = shared.Events.Subscribe(); + await desktop.Engine.CancelAsync(workspace.Id); + var elsewhere = await desktop.Engine.EnqueueAsync(JobKind.Thumbs, [theirs.Id], "theirs"); + await desktop.WaitAsync(elsewhere.Id); + var served = await desktop.Engine.EnqueueAsync(JobKind.Thumbs, [mine.Id], "mine"); + var finished = JobWire.State((await desktop.WaitAsync(served.Id)).State); + var seen = new List(); + using (var wait = CancellationTokenSource.CreateLinkedTokenSource(context.Cancellation)) + { + wait.CancelAfter(TimeSpan.FromSeconds(30)); + while (await events.Reader.ReadAsync(wait.Token) is var e) + { + seen.Add(e); + if (e is JobStateEvent { State: var state } done && done.JobId == served.Id && state == finished) break; + } + } + Assert.Contains(seen, e => e is JobStateEvent s && s.JobId == served.Id); + Assert.False(seen.Any(e => e is JobStateEvent s && (s.JobId == workspace.Id || s.JobId == elsewhere.Id)), "a private job's state went out"); + Assert.False(seen.Any(e => e is JobProgressEvent p && (p.JobId == workspace.Id || p.JobId == elsewhere.Id)), "a private job's progress went out"); + Assert.False(seen.Any(e => e is SequenceChangedEvent c && c.SequenceId == theirs.Id), "another archive's sequence went out"); + var all = Assert.NotNull(await admin.GetFromJsonAsync("/api/v1/jobs", ProtocolJson.Default.PageJobDto)); + Assert.False(all.Items.Any(j => j.Id == elsewhere.Id), "a job on the desktop's other archive is listed"); + Assert.True(all.Items.Any(j => j.Id == served.Id), "the shared archive's job is listed"); + using (var get = await admin.GetAsync($"/api/v1/jobs/{elsewhere.Id}")) Assert.Equal(HttpStatusCode.NotFound, get.StatusCode); + } + + [Test] + public async Task RenderNodesTakeOnlyTheRendersClientsQueuedOnTheSharedArchive() + { + await using var desktop = await DesktopFixture.StartAsync(context); + var mine = await desktop.SequenceAsync(desktop.Archive); + var other = await desktop.Archives.CreateAsync(context.CreateTempDirectory("other"), "Another archive", cancellationToken: context.Cancellation); + var theirs = await desktop.SequenceAsync(other); + await using var shared = await desktop.ShareAsync(); + using var admin = await desktop.AdminAsync(shared); + var hevc = Jobs.RenderNodeTests.HevcJob; + // Older and as urgent as the client's: the desktop's own render (its export goes where its user chose), and one of + // a sequence of the desktop's other archive. + await desktop.Engine.EnqueueAsync(JobKind.Render, [mine.Id], "desktop", hevc, JobPriority.User); + await desktop.Engine.EnqueueAsync(JobKind.Render, [theirs.Id], "elsewhere", hevc, JobPriority.User, Guid.CreateVersion7()); + using var created = await admin.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("render", [mine.Id], hevc), ProtocolJson.Default.CreateJobRequest); + Assert.Equal(HttpStatusCode.Accepted, created.StatusCode); + var client = Assert.NotNull(await created.Content.ReadFromJsonAsync(ProtocolJson.Default.JobDto)); + + var node = await Jobs.RenderNodeTests.RegisterAsync(admin, "studio-node", "hevc", 8192); + using (var claim = await admin.PostAsync($"/api/v1/nodes/{node.Id}/claim", null)) + { + Assert.Equal(HttpStatusCode.OK, claim.StatusCode); + var claimed = Assert.NotNull(await claim.Content.ReadFromJsonAsync(ProtocolJson.Default.ClaimedJob)); + Assert.Equal(client.Id, claimed.Job.Id); + } + using (var none = await admin.PostAsync($"/api/v1/nodes/{node.Id}/claim", null)) Assert.Equal(HttpStatusCode.NoContent, none.StatusCode); } [Test] diff --git a/tests/Chronos.Tools.Tests/PackInstallerCommandTests.cs b/tests/Chronos.Tools.Tests/PackInstallerCommandTests.cs index 3938ea05..54b8d866 100644 --- a/tests/Chronos.Tools.Tests/PackInstallerCommandTests.cs +++ b/tests/Chronos.Tools.Tests/PackInstallerCommandTests.cs @@ -36,6 +36,22 @@ public sealed class PackInstallerCommandTests(TestContext context) Assert.Equal("Chronos", association.Component); } + [Test] + public async Task ASetupOfTheUploaderAloneHasItPreselectedAsThe10SetupDid() + { + var root = context.CreateTempDirectory("pack"); + var stub = await Stub(root); + var uploader = Program(root, "uploader", "Chronos.Uploader.exe"); + var output = Path.Combine(root, "out", "Chronos-Uploader-Setup.exe"); + + Assert.Equal(0, await new PackInstallerCommand().RunAsync( + ["--setup", stub, "--product", "Chronos Uploader", "--version", "1.0.0", "--component", "Uploader=" + uploader, "--out", output])); + + using var reader = PayloadReader.Open(output); + // A silent run without /COMPONENTS installs it, as the separate 1.0 setup did. + Assert.True(reader.Manifest.FindComponent("Uploader")!.DefaultSelected); + } + [Test] public async Task TheServerIsPackedOnlyForTheMigrationTest() {