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 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-15 16:19:56 +01:00
1 parent 817956e719
commit f30eb2904a
51 files changed
+895 -122

No files matched your search

+2 -2
View File
@@ -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
+21 -5
View File
@@ -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).
+10
View File
@@ -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:<N>` 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 |
+1 -2
View File
@@ -896,6 +896,7 @@
<data name="Tooltips.Setup.Changes.KeptSeparate" xml:space="preserve"><value>The separate copy in {0} is installed for all users, so it stays · remove it in Settings › Apps</value></data>
<data name="Tooltips.Setup.Changes.Remove" xml:space="preserve"><value>Removes its files and shortcuts · a file changed since setup installed it is kept · your data is kept</value></data>
<data name="Tooltips.Setup.Changes.RemoveRetained" xml:space="preserve"><value>Removes {0} and the Windows service that runs it · its data in %ProgramData%\Chronos Server is kept</value></data>
<data name="Tooltips.Setup.Changes.RemoveUnchecked" xml:space="preserve"><value>Removes its files and shortcuts · your data is kept</value></data>
<data name="Tooltips.Setup.Changes.Replace" xml:space="preserve"><value>Moves the separate copy in {0} here with its sign-in entry and shortcuts, then removes it · your data is kept</value></data>
<data name="Tooltips.Setup.Close" xml:space="preserve"><value>Close setup</value></data>
<data name="Tooltips.Setup.ClosePrograms" xml:space="preserve"><value>Ask the running programs to close · each one handles its unsaved work</value></data>
@@ -974,9 +975,7 @@
<data name="Tooltips.Uploader.Updates.CheckOnStart" xml:space="preserve"><value>Look for a newer Chronos release when the Uploader starts · skipped when Chronos Desktop is installed alongside, whose own notice covers the same setup</value></data>
<data name="Tooltips.Uploader.Updates.Download" xml:space="preserve"><value>Download the setup, check it against the release's SHA-256 list and show it in Explorer · {0}</value></data>
<data name="Tooltips.Uploader.Updates.DownloadPage" xml:space="preserve"><value>Open the page of this release in the browser</value></data>
<data name="Tooltips.Uploader.Updates.DownloadPortable" xml:space="preserve"><value>Download the portable zip, check it against the release's SHA-256 list and show it in Explorer · {0}</value></data>
<data name="Tooltips.Uploader.Updates.Failed" xml:space="preserve"><value>The releases page could not be reached · try again later</value></data>
<data name="Tooltips.Uploader.Updates.ShowPortable" xml:space="preserve"><value>Show the verified zip in Explorer; close Chronos and the Uploader and unpack it over this folder to upgrade. The data folder is kept</value></data>
<data name="Tooltips.Uploader.Updates.ShowSetup" xml:space="preserve"><value>Show the verified setup in Explorer; close the Uploader and run it to upgrade. Queue and settings are kept</value></data>
<data name="Tooltips.Uploader.Updates.UpToDate" xml:space="preserve"><value>You run the newest stable release</value></data>
<data name="Tooltips.Uploader.User" xml:space="preserve"><value>Your user name on the Chronos Server</value></data>
+1 -2
View File
@@ -997,6 +997,7 @@
<data name="Tooltips.Setup.Changes.KeptSeparate" xml:space="preserve"><value>La copia separata in {0} è installata per tutti gli utenti, quindi resta · rimuovila da Impostazioni › App</value></data>
<data name="Tooltips.Setup.Changes.Remove" xml:space="preserve"><value>Rimuove i suoi file e collegamenti · un file modificato dopo l'installazione resta · i tuoi dati restano</value></data>
<data name="Tooltips.Setup.Changes.RemoveRetained" xml:space="preserve"><value>Rimuove {0} e il servizio Windows che lo esegue · i suoi dati in %ProgramData%\Chronos Server restano</value></data>
<data name="Tooltips.Setup.Changes.RemoveUnchecked" xml:space="preserve"><value>Rimuove i suoi file e collegamenti · i tuoi dati restano</value></data>
<data name="Tooltips.Setup.Changes.Replace" xml:space="preserve"><value>Sposta qui la copia separata in {0} con la voce di avvio e i collegamenti, poi la rimuove · i tuoi dati restano</value></data>
<data name="Tooltips.Setup.Close" xml:space="preserve"><value>Chiudi l'installazione</value></data>
<data name="Tooltips.Setup.ClosePrograms" xml:space="preserve"><value>Chiedi ai programmi aperti di chiudersi · ognuno gestisce il lavoro non salvato</value></data>
@@ -1075,9 +1076,7 @@
<data name="Tooltips.Uploader.Updates.CheckOnStart" xml:space="preserve"><value>Cerca una versione più recente di Chronos all'avvio dell'Uploader · saltato quando accanto è installato Chronos Desktop, il cui avviso copre lo stesso installer</value></data>
<data name="Tooltips.Uploader.Updates.Download" xml:space="preserve"><value>Scarica l'installer, lo confronta con l'elenco SHA-256 della versione e lo mostra in Esplora file · {0}</value></data>
<data name="Tooltips.Uploader.Updates.DownloadPage" xml:space="preserve"><value>Apre la pagina di questa versione nel browser</value></data>
<data name="Tooltips.Uploader.Updates.DownloadPortable" xml:space="preserve"><value>Scarica lo zip portatile, lo confronta con l'elenco SHA-256 della versione e lo mostra in Esplora file · {0}</value></data>
<data name="Tooltips.Uploader.Updates.Failed" xml:space="preserve"><value>Non è stato possibile raggiungere la pagina delle versioni · riprova più tardi</value></data>
<data name="Tooltips.Uploader.Updates.ShowPortable" xml:space="preserve"><value>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</value></data>
<data name="Tooltips.Uploader.Updates.ShowSetup" xml:space="preserve"><value>Mostra in Esplora file l'installer verificato; chiudi l'Uploader ed eseguilo per aggiornare. Coda e impostazioni restano invariate</value></data>
<data name="Tooltips.Uploader.Updates.UpToDate" xml:space="preserve"><value>Usi la versione stabile più recente</value></data>
<data name="Tooltips.Uploader.User" xml:space="preserve"><value>Il tuo nome utente sul Chronos Server</value></data>
@@ -109,6 +109,19 @@ public static class MaintenanceReports
return rows;
}
/// <summary>
/// <paramref name="jobs"/> with <paramref name="changed"/> in place of its earlier state, or added when it is a maintenance
/// job of <paramref name="archiveId"/> not among them yet (queued or started while the screen is shown, owner review 5,
/// #65); <paramref name="jobs"/> itself for any other job.
/// </summary>
public static IReadOnlyList<Job> Track(IReadOnlyList<Job> 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)];
}
/// <summary>
/// The latest <paramref name="count"/> jobs as "Recent maintenance" lines; a running one shows its percentage and what it
/// does now from its <paramref name="live"/> progress when there is some (owner review 5, #65), else from its stored snapshot.
@@ -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<IRenderFrameSource> _retired = [];
private IRenderFrameSource? _frames;
@@ -104,7 +105,9 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders,
private int _disposed;
/// <param name="server">The server the project's home is (phase 5b); null for a project of this PC's archive.</param>
public WorkspaceSequenceSource(WorkspaceSync sync, Guid projectId, ChronosDatabase db, ImageDecoder decoder, JobEngine? engine, WorkspaceServerHome? server = null)
/// <param name="hold">Released when the source is disposed: what marks the project open in the editor (<see cref="Chronos.App.Workspace.WorkspaceHost.HoldInEditor"/>).</param>
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<IRenderFrameSource> sources;
ServerJobs? jobs;
+7 -2
View File
@@ -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 <see cref="BarStatusLength"/> characters of it); a job that counts bytes shows sizes.
/// </summary>
public static string Bar(JobEntry entry)
public static string Bar(JobEntry entry) => Bar(entry, BarStatusLength);
/// <summary>The job bar's tooltip: its line with what the job does now whole, the item (sequence, folder) included.</summary>
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<string>(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)));
+22 -2
View File
@@ -706,6 +706,24 @@ public sealed class ArchiveViewModel : SectionViewModel
_recentThrottle?.Signal();
}
/// <summary>A maintenance job changed state: its Recent line shows it, and its progress counts while it runs (UI thread).</summary>
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<Guid>(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);
}
/// <summary>The running Recent lines with their latest progress (UI thread).</summary>
private void FlushRecent()
{
@@ -720,11 +738,13 @@ public sealed class ArchiveViewModel : SectionViewModel
}
/// <summary>
/// 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.
/// </summary>
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;
+2 -1
View File
@@ -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
@@ -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;
+14 -2
View File
@@ -46,6 +46,9 @@ public sealed class LibraryShare : ObservableObject, IAsyncDisposable
private readonly AppServices _services;
private readonly SemaphoreSlim _gate = new(1, 1);
private HostedServer? _server;
/// <summary>The server being started: its certificate and id are known before it listens and its first beacon goes out.</summary>
private HostedServer? _starting;
private ShareSettings? _running;
private string? _archiveRoot;
private ShareState _state = ShareState.Off;
@@ -224,7 +227,7 @@ public sealed class LibraryShare : ObservableObject, IAsyncDisposable
/// <summary>True for this PC's own shared library, by its certificate or its server id: the desktop never connects to itself.</summary>
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;
+53 -10
View File
@@ -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
}
/// <summary>Every running and paused job of the server, all pages (any thread).</summary>
private async Task LoadAsync(IServerJobsApi api, CancellationToken ct)
private async Task LoadAsync(IServerJobsApi api, Watch watch, CancellationToken ct)
{
var jobs = new List<Job>();
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; }
/// <summary>The jobs the list holds as the listener read them, and those read once on their progress since the last list.</summary>
private readonly HashSet<Guid> _known = [];
private readonly HashSet<Guid> _fetched = [];
/// <summary>A new list (the listener's, or a reload's): what it holds is known, and every job may be read once again.</summary>
public void Listed(IEnumerable<Guid> 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);
}
}
/// <summary>True the first time a job the list does not hold reports progress: it is read once then.</summary>
public bool FirstUnknown(Guid id)
{
lock (_known) return !_known.Contains(id) && _fetched.Add(id);
}
}
/// <summary>
+12 -9
View File
@@ -45,7 +45,7 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
/// <summary>How long a job resumed at start waits for the saved session to be restored.</summary>
private static readonly TimeSpan RestoreWait = TimeSpan.FromSeconds(30);
/// <summary>Jobs that write into the workspace or the servers' homes in the cache: a re-key waits for them.</summary>
/// <summary>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.</summary>
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
/// <summary>
/// Whatever this PC keeps under the address keys the server of <paramref name="credentials"/> was reached by moves to its
/// id (owner review 5, #66: <see cref="HomeLayoutMigration.RekeyAsync"/>), 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: <see cref="HomeLayoutMigration.RekeyAsync"/>), before the agent starts. The links move at
/// once (<see cref="HomeLayoutMigration.RekeyLinksAsync"/>): 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.
/// </summary>
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)
+1 -1
View File
@@ -92,7 +92,7 @@
<!-- Job bar (DESIGN §4): current job, progress, time left, pause; "Ready" when idle, hidden when idle in the editor.
Screen readers hear which job starts and when the queue empties, not its progress ticks. -->
<ui:JobBar x:Name="JobBar" Text="{Binding JobText}" ToolTip="{Binding JobText}" Progress="{Binding JobProgress}" IsActive="{Binding IsJobActive}" IsIndeterminate="{Binding IsJobIndeterminate}"
<ui:JobBar x:Name="JobBar" Text="{Binding JobText}" ToolTip="{Binding JobToolTip}" Progress="{Binding JobProgress}" IsActive="{Binding IsJobActive}" IsIndeterminate="{Binding IsJobIndeterminate}"
StopCommand="{Binding StopJobCommand}" StopToolTip="{l:Loc Tooltips.Shell.PauseJob}" StopName="{l:Loc Shell.JobBar.Pause}" ActionGlyph="{StaticResource Icon.Pause}"
Visibility="{Binding IsJobBarVisible, Converter={StaticResource BoolToVisibility}}"
AutomationProperties.LiveSetting="Polite" infra:LiveRegion.Text="{Binding JobAnnouncement}" />
+10 -2
View File
@@ -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");
/// <summary>The job bar's tooltip: its line uncut, with what the job works on now (the bar cuts it at 60 characters).</summary>
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
/// <summary>
/// Updates the global job bar and the taskbar button. <paramref name="name"/> says which job it is without its
/// progress ("Render: Harbour sunset"); null reads <paramref name="text"/>.
/// progress ("Render: Harbour sunset"); null reads <paramref name="text"/>. <paramref name="toolTip"/> is the line uncut;
/// null shows <paramref name="text"/>.
/// </summary>
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));
}
@@ -164,6 +164,7 @@ public sealed partial class WorkspaceHost
private readonly Func<JobEngine?> _engine;
private readonly Lock _gate = new();
private readonly Dictionary<Guid, Guid> _copies = [];
private readonly Dictionary<Guid, int> _inEditor = [];
private OpenWorkspace? _open;
public WorkspaceHost(AppEnvironment environment, AppSettings settings, Action savePreferences, Func<ChronosDatabase?> db, Func<ArchiveService?> archives,
@@ -245,6 +246,45 @@ public sealed partial class WorkspaceHost
/// <summary>The project's folder in whichever home holds it; null when the workspace has none.</summary>
public WorkspaceProject? Find(Guid projectId) => Homes.Find(projectId);
/// <summary>
/// Marks <paramref name="projectId"/> 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).
/// </summary>
public IDisposable HoldInEditor(Guid projectId)
{
lock (_inEditor) _inEditor[projectId] = _inEditor.GetValueOrDefault(projectId) + 1;
return new EditorHold(this, projectId);
}
/// <summary>A project is open in the editor (<see cref="HoldInEditor"/>).</summary>
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);
}
}
/// <summary>The sync over the store of the home that holds <paramref name="projectId"/>.</summary>
/// <exception cref="WorkspaceException">The workspace has no such project (<c>Errors.Workspace.NotCheckedOut</c>).</exception>
public WorkspaceSync SyncOf(Guid projectId) => SyncOf(Existing(projectId).Store);
+23 -9
View File
@@ -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;
}
/// <summary>
/// The links part of <see cref="RekeyAsync"/> alone: the server's links under its address keys <paramref name="aliases"/>
/// move to its id key (<see cref="SyncLinkStore.RekeyAsync"/>), 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.
/// </summary>
public async Task<(int Moved, int Dropped)> RekeyLinksAsync(Guid serverId, IReadOnlyCollection<string> 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);
}
/// <summary>The projects and trash of the alias home <paramref name="from"/> moved into the id home <paramref name="into"/> (see <see cref="RekeyAsync"/>).</summary>
private (int Moved, int Trashed) MergeWorkspaceHome(string from, string into, Guid serverId)
{
+9 -1
View File
@@ -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;
}
+64 -9
View File
@@ -52,10 +52,13 @@ public sealed record JobProgressInfo(Guid JobId, JobKind Kind, string? TargetLab
/// <summary>
/// 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 (<see cref="JobEngineOptions.ProgressInterval"/>, 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 (<see cref="JobEngineOptions.ProgressInterval"/>, 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.
/// </summary>
public sealed class JobContext
{
@@ -78,6 +81,12 @@ public sealed class JobContext
private long _publishedTotal;
private bool _pending;
/// <summary>The trailing publish of a dropped report (<see cref="ArmTrailing"/>), made at the first drop; armed while 1.</summary>
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
}
/// <summary>
/// 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.
/// </summary>
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();
}
/// <summary>How long after the last publish the current state may go out: a quarter of the interval for a new step.</summary>
private TimeSpan Wait() =>
(_detail?.Step ?? JobStep.None) != _publishedStep ? _engine.Options.ProgressInterval / 4 : _engine.Options.ProgressInterval;
/// <summary>
/// After a dropped report: publishes the state once its time comes (<see cref="Wait"/> 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.
/// </summary>
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);
}
/// <summary>The trailing publish fires: the latest state goes out when no publish came since the report it waited for.</summary>
private void OnTrailing()
{
Volatile.Write(ref _armed, 0);
if (_ended || !_pending) return;
Publish(_time.GetTimestamp());
}
/// <summary>The run ended (its final state is written next): no trailing publish follows it.</summary>
internal void End()
{
_ended = true;
_trailing?.Dispose();
}
private void Publish(long now)
@@ -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)))
@@ -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);
@@ -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;
@@ -186,6 +186,20 @@ public sealed class WorkspaceStore
Manifest = manifest;
}
/// <summary>
/// The store a workspace job opens at <paramref name="root"/> (<see cref="WorkspaceJobRoots.Resolve"/>): 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 <see cref="WorkspaceStore(string)"/> does.
/// </summary>
/// <exception cref="InvalidDataException">The folder's <c>workspace.json</c> is not a workspace manifest, or a newer one.</exception>
/// <exception cref="IOException">The folder cannot be made or read.</exception>
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; }
+11 -5
View File
@@ -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<JobDto>([], 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<JobDto>([.. 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<JobDto>(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<JobDto>(served, page.NextCursor, null), ProtocolJson.Default.PageJobDto);
}
private static async Task<IResult> CreateAsync(HttpContext context, Caller caller, CreateJobRequest request, ChronosDatabase db, JobEngineHost host,
@@ -227,8 +233,8 @@ public static class JobEndpoints
private static async Task<IResult> ActAsync(HttpContext context, Caller caller, Guid id, ChronosDatabase db, JobState[] allowed, Func<Job, CancellationToken, Task> 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<JobEngineHost>().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<JobEngineHost>().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));
+2 -2
View File
@@ -124,11 +124,11 @@ public sealed class HostedServer : IAsyncDisposable
/// <summary>The desktop's archive or processing service changed or made sequence <paramref name="id"/>: clients are told.</summary>
public Task SequenceChangedAsync(Guid id, string change, CancellationToken cancellationToken) =>
ServerEventBridge.SequenceChangedAsync(Services.GetRequiredService<ChronosDatabase>(), Events, Services.GetService<ProjectCatchUp>(), id, change,
cancellationToken);
cancellationToken, Services.GetRequiredService<ServerArchive>());
/// <summary>The desktop's archive service changed a sequence's projects: clients are told.</summary>
public Task ProjectsChangedAsync(ProjectChangeSet changed, CancellationToken cancellationToken) =>
ServerEventBridge.ProjectsChangedAsync(Services.GetRequiredService<ChronosDatabase>(), Events, changed, cancellationToken);
ServerEventBridge.ProjectsChangedAsync(Services.GetRequiredService<ChronosDatabase>(), Events, changed, cancellationToken, Services.GetRequiredService<ServerArchive>());
/// <summary>The <c>uploads</c> clean-up step of the server: abandoned uploads and old upload records (the upload-cleanup schedule).</summary>
public Task<string> SweepUploadsAsync(CleanupContext context, CleanupParameters parameters) =>
+5 -1
View File
@@ -252,7 +252,11 @@ public static class ServerHost
services.AddSingleton<RenderNodeService>();
services.AddSingleton<ClientActivity>();
if (hosted is null) services.AddSingleton<JobEngineHost>();
else services.AddSingleton(sp => new JobEngineHost(hosted.Engine, sp.GetRequiredService<EventHub>(), sp.GetRequiredService<TimeProvider>()));
else
{
services.AddSingleton(sp => new JobEngineHost(hosted.Engine, sp.GetRequiredService<EventHub>(), sp.GetRequiredService<TimeProvider>(),
sp.GetRequiredService<ServerArchive>(), sp.GetRequiredService<ChronosDatabase>()));
}
services.AddHostedService(sp => sp.GetRequiredService<JobEngineHost>());
// After the engine's host: the scheduler queues on its engine, starts after it and stops before it (owner review 2, R10).
services.AddSingleton<ServerScheduleHost>();
+94 -5
View File
@@ -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 (<see cref="ISelectiveJobHandler"/>: 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 (<see cref="Exposes"/>):
/// 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 (<see cref="Exposes"/>) on the archive it serves and its sequences (<see cref="ServesAsync"/>): the desktop's
/// workspace, sync and download jobs, and its jobs on other archives, stay its own.
/// Progress goes out through the <see cref="Gate"/> render nodes share, with what each job does now (owner review 5, #65).
/// </summary>
public sealed class JobEngineHost : IHostedService
@@ -25,6 +27,13 @@ public sealed class JobEngineHost : IHostedService
private readonly EventHub _events;
private readonly HashSet<JobKind> _kinds;
private readonly bool _ownsEngine = true;
private readonly ServerArchive? _archive;
private readonly ChronosDatabase? _db;
/// <summary>Hosted: whether each job seen is the shared archive's (its targets never change), and the latest state of one still being looked up.</summary>
private readonly Dictionary<Guid, bool> _served = [];
private readonly Dictionary<Guid, Job> _deciding = [];
private readonly Lock _decide = new();
private int _subscribed;
public JobEngineHost(ChronosDatabase db, IEnumerable<IJobHandler> handlers, IEnumerable<IJobHandlerProvider> providers, ServerOptions options,
@@ -47,15 +56,18 @@ public sealed class JobEngineHost : IHostedService
/// <summary>
/// Relays <paramref name="engine"/>, an engine Chronos Desktop runs (owner review 5, #67), from <see cref="StartAsync"/> to
/// <see cref="StopAsync"/>; the engine stays the desktop's.
/// <see cref="StopAsync"/>; the engine stays the desktop's. With <paramref name="archive"/> and <paramref name="db"/>, only
/// that archive's jobs and its sequences' are relayed and listed (<see cref="ServesAsync"/>).
/// </summary>
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
/// </summary>
public bool Exposes(JobKind kind) => _ownsEngine || ServerSettingsStore.Kinds.Contains(kind);
/// <summary>
/// Whether the jobs API lists, shows and acts on <paramref name="job"/>, 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 (<see cref="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.
/// </summary>
public async ValueTask<bool> 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;
}
/// <summary>The job's first target is the served archive or one of its sequences (a job without targets is the server's).</summary>
private async Task<bool> 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);
}
/// <summary>Looks up whether the job is the shared archive's, then publishes the latest state it had meanwhile when it is.</summary>
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)));
+8 -4
View File
@@ -5,8 +5,9 @@ namespace Chronos.Server.Jobs;
/// <summary>
/// How often a job's progress goes out on the event socket (owner review 5, #65): at most once per <see cref="Interval"/>
/// per job, for the server's own jobs (<see cref="JobEngineHost"/>) and those render nodes run (<see cref="RenderNodeService"/>)
/// alike. A job's first report, a new step and a count that completes always pass. A job that stops running is forgotten
/// (<see cref="Forget"/>), 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 (<see cref="Forget"/>), so its next run starts afresh.
/// </summary>
public sealed class ProgressGate(TimeProvider time)
{
@@ -19,6 +20,9 @@ public sealed class ProgressGate(TimeProvider time)
/// </summary>
private static readonly TimeSpan Slack = TimeSpan.FromMilliseconds(50);
/// <summary>The shortest time before a new step passes: a quarter of <see cref="Interval"/>, as the job engine publishes one.</summary>
private static readonly TimeSpan StepInterval = Interval / 4;
private readonly Dictionary<Guid, (long At, JobStep Step)> _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;
@@ -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.
@@ -18,14 +18,18 @@ public static class ServerEventBridge
/// <summary>
/// A Reorganize, a conversion, a render or an analysis changed or made sequence <paramref name="id"/>: clients are told
/// (<c>sequenceChanged</c>), and a conversion's or an analysis's settings become Main's next version soon.
/// (<c>sequenceChanged</c>), and a conversion's or an analysis's settings become Main's next version soon. With
/// <paramref name="served"/> (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.
/// </summary>
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
/// <summary>
/// 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
/// <paramref name="served"/>, only of a sequence of that archive (as <see cref="SequenceChangedAsync"/>).
/// </summary>
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));
}
}
+16 -7
View File
@@ -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 (<see cref="Retained"/>, kept
/// unless the switches leave it out or the user unticks it); a separate 1.0 Uploader product (<see cref="Legacy"/>)
/// 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 (<see cref="PayloadComponent.AllUsersOnly"/>) makes a new installation an all-users one, in a
/// folder inside Program Files; an installation upgraded in place elsewhere cannot take it.
/// </summary>
@@ -37,8 +37,6 @@ internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOn
/// <summary><see cref="Resolve(PayloadManifest, SetupArguments)"/> from what was found on this PC (no registry access).</summary>
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<string> 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 };
}
/// <summary>False while the folder and scope are fixed: an installation is upgraded in place, or a legacy Uploader sets the scope.</summary>
public bool CanChangeLocation => Existing is null && Legacy is null;
/// <summary>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.</summary>
public bool CanChangeLocation => !LocksLocation(Components);
/// <summary>
/// True when installing <paramref name="components"/> 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.
/// </summary>
public bool LocksLocation(IEnumerable<string> components) =>
Existing is not null || (Legacy is not null && components.Contains(LegacyProducts.UploaderComponent, StringComparer.OrdinalIgnoreCase));
/// <summary>
/// False for a component that installs for all users only when the folder and scope are fixed and are not an
+8
View File
@@ -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}");
+24 -3
View File
@@ -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)));
/// <summary>False when upgrading (the existing folder and scope are kept) or replacing a legacy Uploader (its scope is).</summary>
public bool CanChangeLocation => _plan is null || _plan.CanChangeLocation;
/// <summary>
/// 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.
/// </summary>
public bool CanChangeLocation => _plan is null || !_plan.LocksLocation(SelectedComponents);
/// <summary>An installation of this product exists: Update replaces it in place.</summary>
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;
@@ -7,7 +7,9 @@ namespace Chronos.Tools.Commands;
/// <c>pack-installer --setup Chronos.Setup.exe --product Chronos --version 1.2.3 --component Id=folder … --out file [--legacy]</c>:
/// appends a TPK1 payload (BRIEF §18) to the setup program. Known component ids carry their display name, default
/// selection, shortcuts and file types: <c>Chronos</c> (alias <c>Desktop</c>), the desktop app, preselected, and
/// <c>Uploader</c>, not preselected; unknown ids are packed as plain, preselected components. Chronos Server is no
/// <c>Uploader</c>, 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
/// <c>/COMPONENTS</c> installs it. Chronos Server is no
/// longer packed (it ships as a Docker image): <c>Server</c> is refused unless <c>--legacy</c>, 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"),
+1 -1
View File
@@ -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;
@@ -9,7 +9,8 @@ namespace Chronos.Uploader.Infrastructure;
/// <summary>
/// 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 <c>%TEMP%\Chronos\updates</c> folder as the desktop.
/// setup and the same <c>%TEMP%\Chronos\updates</c> 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.
/// </summary>
public static class UploaderUpdates
{
@@ -23,16 +24,15 @@ public static class UploaderUpdates
typeof(UploaderUpdates).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
/// <summary>The live host: the public releases repository, the shell's browser and Explorer.</summary>
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);
/// <summary>A host over the given clients and releases repository ("https://host/owner/name"); tests pass a fake transport.</summary>
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<string> openUrl, Action<string> 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),
@@ -12,7 +12,7 @@ namespace Chronos.Uploader.Shell;
/// <summary>
/// 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 <c>SHA256SUMS</c> and shows it in Explorer, and Show setup. The work is the desktop's <see cref="UpdateFlow"/>.
/// The start-up check is skipped when Chronos Desktop sits beside the Uploader: its own notice covers the same setup.
/// </summary>
@@ -100,18 +100,18 @@ public sealed class UpdatesViewModel : LocalizedViewModel
public bool IsDownloading => _flow.State == UpdateState.Downloading;
/// <summary>The verified setup or portable zip is in the temporary folder.</summary>
/// <summary>The verified setup is in the temporary folder.</summary>
public bool IsReady => _flow.State == UpdateState.Downloaded;
/// <summary>The verified package; null until a download succeeded.</summary>
public string? PackagePath => _flow.PackagePath;
/// <summary>What Download does here: fetch and verify the setup or the portable zip (with its size), or open the release page.</summary>
/// <summary>What Download does here: fetch and verify the setup (with its size), or open the release page.</summary>
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");
/// <summary>The start-up check runs when the user left it on and Chronos Desktop is not installed beside the Uploader.</summary>
public static bool ChecksOnStart(bool enabled, bool desktopBeside) => enabled && !desktopBeside;
@@ -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<Job> 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<Guid, JobProgressInfo> { [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()
{
@@ -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()
{
@@ -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()
{
@@ -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.
@@ -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<string> revealed)
{
revealed = [];
@@ -197,7 +206,7 @@ public sealed class UploaderUpdatesTests(TestContext context)
private static UpdateHost Host(Feed feed, string downloadRoot, List<string> 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)
@@ -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()
{
@@ -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<InvalidDataException>(() => 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));
@@ -14,6 +14,9 @@ public sealed class JobContextProgressTests(TestContext context)
{
private static readonly TimeSpan Tick = TimeSpan.FromMilliseconds(10);
/// <summary>A quarter of the default publish interval: what a new step waits since the last publish.</summary>
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));
@@ -5,16 +5,71 @@ using Chronos.Testing;
namespace Chronos.Data.Tests.Jobs;
/// <summary>A clock the test moves by hand (BCL <see cref="TimeProvider"/>, no package).</summary>
/// <summary>
/// A clock the test moves by hand (BCL <see cref="TimeProvider"/>, no package), whose timers fire only when
/// <see cref="Advance"/> reaches them, on the test's thread.
/// </summary>
internal sealed class ManualTime : TimeProvider
{
private readonly Lock _gate = new();
private readonly List<Timer> _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;
}
/// <summary>Moves the clock on, then fires each one-shot timer due by then.</summary>
public void Advance(TimeSpan by)
{
List<Timer> 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")]
@@ -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)
@@ -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()
{
@@ -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<ServerEvent>();
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]
@@ -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()
{