feat: single setup, mass-pass progress, per-server homes, Desktop shares its library (owner review 5, v1.1.0) (#68)
CI / Build and test (push) Successful in 11m36s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 12s
Release / Build, test and publish (push) Successful in 14m56s
CI / PostgreSQL 16 integration (push) Successful in 10m11s
CI / PostgreSQL 17 integration (push) Successful in 10m15s
CI / Docker image (push) Successful in 45s
Release / Server image (push) Successful in 4m55s

Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #68.
This commit is contained in:
Alby96 authored and Alby96 committed 2026-11-15 18:11:43 +01:00
1 parent 988068ee8e
commit 20d64af4a4
793 files changed
+23882 -2096

No files matched your search

@@ -1,7 +1,8 @@
using System.IO;
using Chronos.App.About;
using Chronos.Core.Updates;
using Chronos.Testing;
using Chronos.Ui.Mvvm;
using Chronos.Ui.Updates;
namespace Chronos.App.Tests.About;
@@ -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()
{
@@ -386,6 +386,35 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
Assert.True(api.Disposed, "closing the editor closes its connection");
}
[Test]
public async Task TheServersJobSaysWhatItDoesNow()
{
Loc.SetCulture(System.Globalization.CultureInfo.GetCultureInfo("en"));
var (source, api, _) = Open();
await using (source)
{
await source.LoadAsync(context.Cancellation);
var seen = new List<Job>();
source.JobChanged += job =>
{
lock (seen) seen.Add(job);
};
var id = Guid.CreateVersion7();
api.Jobs[id] = api.Job(id, "render", "running");
api.Publish(new JobStateEvent(id, "running", null));
await WaitAsync(() => Last(seen).Id == id);
// Owner review 5, #65: the progress event carries the step, and an older server's event without one keeps it.
api.Publish(new JobProgressEvent(id, 40, 300, 11.3, 20, new JobDetailDto("encode", null, 40, 300)));
await WaitAsync(() => Last(seen).ProgressDone == 40);
Assert.Equal(new JobDetail(JobStep.Encode, null, 40, 300), Last(seen).Detail);
Assert.Contains("Encoding frame 40 of 300", EditorText.ServerJobDetail(Last(seen), "Studio NAS"));
api.Publish(new JobProgressEvent(id, 41, 300, 11.3, 19));
await WaitAsync(() => Last(seen).ProgressDone == 41);
Assert.Equal(JobStep.Encode, Last(seen).Detail?.Step);
}
}
[Test]
public async Task ASequenceGoneFromTheServerReadsAsMissing()
{
@@ -0,0 +1,186 @@
using System.Globalization;
using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Testing;
namespace Chronos.App.Tests.Jobs;
/// <summary>The status line of a running job (owner review 5, #65): what it does now, in the job bar, the Jobs table and the tooltips.</summary>
public sealed class JobTextTests
{
private static readonly DateTimeOffset T0 = new(2026, 9, 28, 10, 0, 0, TimeSpan.Zero);
[Test]
public void TheStatusLineSaysStepItemAndPart()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var verify = new JobDetail(JobStep.Verify, "Harbour sunset", 812, 2_400, 3, 41, JobPartUnit.Sequence);
Assert.Equal("Verifying photo 812 of 2,400 · Harbour sunset · sequence 3 of 41", JobText.Status(verify));
// Not counted: the step word alone; a single part is not said.
Assert.Equal("Listing folders", JobText.Status(new JobDetail(JobStep.List)));
Assert.Equal("Encoding frame 10 of 300", JobText.Status(new JobDetail(JobStep.Encode, null, 10, 300, 1, 1, JobPartUnit.Render)));
// A part without a unit is counted plainly.
Assert.Equal("Analysing · Lake · 120 of 4,812", JobText.Status(new JobDetail(JobStep.Analyse, "Lake", Part: 120, Parts: 4_812)));
Assert.Equal(string.Empty, JobText.Status(null));
}
[Test]
public void EveryStepAndPartHasItsWordsInEnglishAndItalian()
{
foreach (var culture in new[] { "en", "it" })
{
var c = CultureInfo.GetCultureInfo(culture);
foreach (var step in Enum.GetValues<JobStep>().Where(s => s != JobStep.None))
Assert.True(Loc.Get("Jobs.Step." + step, c) is not null, $"{culture} {step}");
foreach (var unit in Enum.GetValues<JobPartUnit>().Where(u => u != JobPartUnit.None))
Assert.True(Loc.Get("Jobs.Part." + unit, c) is not null, $"{culture} {unit}");
foreach (var sub in new[] { "Leases", "Temp", "Packs", "Duplicates", "Vacuum" })
Assert.True(Loc.Get("Jobs.Maintenance.Step." + sub, c) is not null, $"{culture} {sub}");
}
}
[Test]
public void SubStepsNameThemselvesAndUnknownOnesShowCountsOnly()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
Assert.Equal("Compacting thumbnails · step 3 of 5", JobText.Status(new JobDetail(JobStep.Maintenance, "packs", Part: 3, Parts: 5, PartUnit: JobPartUnit.Step)));
Assert.Equal("Job history", JobText.Status(new JobDetail(JobStep.Cleanup, "job-history")));
// A sub-step key of a newer server is never shown as text.
Assert.Equal("Maintenance · step 6 of 6", JobText.Status(new JobDetail(JobStep.Maintenance, "re-index", Part: 6, Parts: 6, PartUnit: JobPartUnit.Step)));
// A step this build does not know (JobStep.None from the wire) shows its counts and item only.
Assert.Equal("4 of 10 · Lake", JobText.Status(new JobDetail(JobStep.None, "Lake", 4, 10)));
Assert.Equal(JobStep.None, JobWire.FromDto(new Chronos.Protocol.JobDetailDto("teleport", "Lake", 4, 10))!.Step);
}
[Test]
public void FoldersStayLeftToRight()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var status = JobText.Status(new JobDetail(JobStep.Index, "2024/2024-09-27 Harbour", 1, 2));
Assert.Contains(Formatting.LeftToRight("2024/2024-09-27 Harbour"), status);
}
[Test]
public void ALongLineDropsTheItemFirstThenIsCut()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var detail = new JobDetail(JobStep.Verify, new string('x', 120), 812, 2_400, 3, 41, JobPartUnit.Sequence);
Assert.Equal("Verifying photo 812 of 2,400 · sequence 3 of 41", JobText.Status(detail, JobText.BarStatusLength));
var cut = JobText.Status(detail, 20);
Assert.Equal(20, cut.Length);
Assert.True(cut.EndsWith('…'));
// A cut folder island is closed again.
var folder = JobText.Status(new JobDetail(JobStep.Index, "2024/" + new string('y', 80)), 30);
Assert.Equal(folder.Count(c => c == '‪'), folder.Count(c => c == '‬'));
}
[Test]
public void TheBarSaysWhatTheJobDoesNow()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var job = Job(JobKind.Verify, JobState.Running, "Harbour sunset") with
{
Detail = new JobDetail(JobStep.Verify, "Harbour sunset", 812, 2_400, 3, 41, JobPartUnit.Sequence),
};
// The bar keeps 60 characters of the line: the item (already the target here) goes first.
var entry = new JobEntry(job);
Assert.Equal("Verify · Harbour sunset · Verifying photo 812 of 2,400 · sequence 3 of 41", JobText.Bar(entry));
// Without a detail the counter stays, in bytes for a byte job.
var bytes = new JobEntry(Job(JobKind.Import, JobState.Running, "Card") with { ProgressDone = 2_000_000, ProgressTotal = 8_000_000 });
Assert.Equal($"Import · Card · {Formatting.Bytes(2_000_000)} / {Formatting.Bytes(8_000_000)}", JobText.Bar(bytes));
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()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var job = Job(JobKind.Thumbs, JobState.Running, "Lake") with { Detail = new JobDetail(JobStep.Thumbs, "Lake", 1, 10) };
var entry = new JobEntry(job)
{
Live = new JobProgressInfo(job.Id, job.Kind, "Lake", 5, 10, 2.5, TimeSpan.FromMinutes(2), null, new JobDetail(JobStep.Thumbs, "Lake", 5, 10)),
};
Assert.Equal("Thumbnail 5 of 10 · Lake", JobText.RowStatus(entry));
Assert.Equal("Thumbnail 5 of 10 · Lake · 2.5 fps · 2 min left", JobText.RowStatusToolTip(entry));
var paused = new JobEntry(job with { State = JobState.Paused });
Assert.Equal("Stopped at Thumbnail 1 of 10 · Lake", JobText.RowStatus(paused));
Assert.Equal(string.Empty, JobText.RowStatus(new JobEntry(job with { State = JobState.Queued })));
Assert.Equal(string.Empty, JobText.RowStatus(new JobEntry(job with { State = JobState.Done })));
}
[Test]
public void RecentMaintenanceFollowsLiveProgress()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var verify = Job(JobKind.Verify, JobState.Running, "ChronosArchive") with { ProgressDone = 10, ProgressTotal = 100 };
var scan = Job(JobKind.Scan, JobState.Paused, "Archive") with { Detail = new JobDetail(JobStep.Index, null, 4, 9) };
var live = new Dictionary<Guid, JobProgressInfo>
{
[verify.Id] = new(verify.Id, verify.Kind, null, 71, 100, null, null, null, new JobDetail(JobStep.Verify, "Harbour sunset", 3, 9)),
// Progress of a job that is not running is not shown.
[scan.Id] = new(scan.Id, scan.Kind, null, 99, 100, null, null, null, new JobDetail(JobStep.Index, null, 8, 9)),
};
var recent = Chronos.App.Archiving.MaintenanceReports.Recent([verify, scan], 5, live);
var running = recent.Single(r => r.JobId == verify.Id);
Assert.Equal("71 %", running.StateText);
Assert.Equal("Verifying photo 3 of 9 · Harbour sunset", running.Detail);
Assert.True(running.HasDetail);
var paused = recent.Single(r => r.JobId == scan.Id);
Assert.Equal("Stopped at Indexing photo 4 of 9", paused.Detail);
// Without live progress the stored snapshot speaks.
Assert.Equal("10 %", Chronos.App.Archiving.MaintenanceReports.Recent([verify], 5).Single().StateText);
}
private static Job Job(JobKind kind, JobState state, string label) => new()
{
Id = Guid.CreateVersion7(),
Kind = kind,
State = state,
TargetLabel = label,
Created = T0,
Started = state == JobState.Queued ? null : T0,
};
}
/// <summary>The status line in Italian. It switches the process-wide UI language, so the class is serial.</summary>
[Serial]
public sealed class JobTextLanguageTests
{
[Test]
public void ItalianWordsTheSameLine()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("it"));
try
{
var verify = new JobDetail(JobStep.Verify, "Tramonto", 812, 2_400, 3, 41, JobPartUnit.Sequence);
Assert.Equal($"Verifica foto 812 di {Formatting.Count(2_400)} · Tramonto · sequenza 3 di 41", JobText.Status(verify));
Assert.Equal("Elaborazione foto 5 di 9", JobText.Status(new JobDetail(JobStep.Process, null, 5, 9)));
Assert.Equal("Fermo a Miniatura 1 di 10", Loc.L("Jobs.Detail.StoppedAt", JobText.Status(new JobDetail(JobStep.Thumbs, null, 1, 10))));
}
finally
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
}
}
@@ -0,0 +1,239 @@
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Threading.Channels;
using Chronos.App.Server;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.App.Tests.Jobs;
/// <summary>The Server section's list of the server's jobs (owner review 5, #65, the owner's answer to Q2).</summary>
public sealed class ServerJobsListTests
{
private static readonly DateTimeOffset T0 = new(2026, 9, 28, 10, 0, 0, TimeSpan.Zero);
[Test]
public async Task AReadOnlyAccountSeesRunningAndPausedJobsWithoutActions()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var api = new FakeJobsApi();
var verify = api.Add("verify", "Harbour sunset", "running", new JobDetailDto("verify", "Harbour sunset", 812, 2_400, 3, 41, "sequence"));
api.Add("proxies", "Lake", "paused", new JobDetailDto("proxies", "Lake", 300, 1_800));
api.Add("thumbs", "Queued one", "queued");
using var vm = new ServerJobsViewModel(() => new ServerJobsAccount("a", CanControl: false), () => api, new IdleContext());
await UpdatedAsync(vm, vm.Refresh);
Assert.True(vm.IsWatching);
Assert.False(vm.CanControl);
Assert.Equal(Loc.L("Tooltips.Server.Jobs.ReadOnly"), vm.TitleToolTip);
Assert.Equal(2, vm.Rows.Count);
Assert.True(vm.HasRows);
var running = vm.Rows[0];
Assert.Equal(verify, running.Id);
Assert.Equal("Verifying photo 812 of 2,400 · Harbour sunset · sequence 3 of 41", running.StatusText);
Assert.Equal(StatusKindOf(JobState.Running), running.StateKind);
Assert.Empty(running.Actions);
Assert.Equal("Stopped at Proxy 300 of 1,800 · Lake", vm.Rows[1].StatusText);
Assert.Empty(vm.Rows[1].Actions);
// Without the right, nothing reaches the server.
await vm.ActAsync(verify, (a, id, ct) => a.PauseJobAsync(id, ct));
Assert.Equal(0, api.Actions);
}
[Test]
public async Task ProgressEventsMoveTheLineAndAFinishedJobLeaves()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var api = new FakeJobsApi();
var id = api.Add("verify", "Harbour sunset", "running", new JobDetailDto("verify", "Harbour sunset", 1, 2_400, 3, 41, "sequence"));
using var vm = new ServerJobsViewModel(() => new ServerJobsAccount("a", false), () => api, new IdleContext());
await UpdatedAsync(vm, vm.Refresh);
await UpdatedAsync(vm, () => api.Events.Writer.TryWrite(new JobProgressEvent(id, 900, 2_400, 52, 60,
new JobDetailDto("verify", "Alpine lake", 20, 100, 4, 41, "sequence"))));
var row = vm.Rows.Single();
Assert.Equal("Verifying photo 20 of 100 · Alpine lake · sequence 4 of 41", row.StatusText);
Assert.Equal(900d / 2_400, row.Progress);
Assert.Equal("1 min", row.LeftText);
await UpdatedAsync(vm, () => api.Events.Writer.TryWrite(new JobStateEvent(id, "done", null)));
Assert.Empty(vm.Rows);
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()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var api = new FakeJobsApi();
var id = api.Add("thumbs", "Lake", "running");
using var vm = new ServerJobsViewModel(() => new ServerJobsAccount("a", CanControl: true), () => api, new IdleContext());
await UpdatedAsync(vm, vm.Refresh);
Assert.True(vm.CanControl);
Assert.Equal(Loc.L("Tooltips.Server.Jobs"), vm.TitleToolTip);
Assert.SequenceEqual(new[] { Loc.L("Jobs.Action.Pause"), Loc.L("Jobs.Action.Cancel") }, vm.Rows.Single().Actions.Select(a => a.Text));
await vm.ActAsync(id, (a, job, ct) => a.PauseJobAsync(job, ct));
Assert.Equal(StatusKindOf(JobState.Paused), vm.Rows.Single().StateKind);
Assert.SequenceEqual(new[] { Loc.L("Jobs.Action.Resume"), Loc.L("Jobs.Action.Cancel") }, vm.Rows.Single().Actions.Select(a => a.Text));
await vm.ActAsync(id, (a, job, ct) => a.CancelJobAsync(job, ct));
Assert.Empty(vm.Rows);
Assert.Equal(2, api.Actions);
}
[Test]
public async Task ARefusedActionIsSaidAndTheListStays()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var api = new FakeJobsApi { Refuse = true };
var id = api.Add("thumbs", "Lake", "running");
string? said = null;
using var vm = new ServerJobsViewModel(() => new ServerJobsAccount("a", true), () => api, new IdleContext(), (title, reason) => said = $"{title}: {reason}");
await UpdatedAsync(vm, vm.Refresh);
await vm.ActAsync(id, (a, job, ct) => a.PauseJobAsync(job, ct));
Assert.Equal($"{Loc.L("Server.Jobs.NotChanged")}: The job cannot do that in its current state.", said);
Assert.Equal(StatusKindOf(JobState.Running), vm.Rows.Single().StateKind);
}
[Test]
public async Task SigningOutEmptiesTheListAndClosesTheConnection()
{
var api = new FakeJobsApi();
api.Add("verify", "Harbour sunset", "running");
ServerJobsAccount? account = new("a", false);
using var vm = new ServerJobsViewModel(() => account, () => api, new IdleContext());
await UpdatedAsync(vm, vm.Refresh);
Assert.Equal(1, vm.Rows.Count);
account = null;
vm.Refresh();
Assert.False(vm.IsWatching);
Assert.Empty(vm.Rows);
await api.Disposed.Task.WaitAsync(TimeSpan.FromSeconds(10));
// Without an account nothing is opened.
var opened = 0;
using var signedOut = new ServerJobsViewModel(() => null, () => { opened++; return api; }, new IdleContext());
signedOut.Refresh();
Assert.Equal(0, opened);
Assert.False(signedOut.HasRows);
}
private static Chronos.Ui.Controls.StatusKind StatusKindOf(JobState state) =>
state == JobState.Paused ? Chronos.Ui.Controls.StatusKind.Paused : Chronos.Ui.Controls.StatusKind.Running;
/// <summary>Runs <paramref name="act"/>, waits for the listener to post what follows, then applies it as the UI would.</summary>
private static async Task UpdatedAsync(ServerJobsViewModel vm, Action act)
{
var posted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
void OnPosted() => posted.TrySetResult();
vm.Posted += OnPosted;
try
{
act();
await posted.Task.WaitAsync(TimeSpan.FromSeconds(10));
}
finally
{
vm.Posted -= OnPosted;
}
vm.Flush();
}
/// <summary>A UI context that never runs what is posted to it: the test applies the updates itself.</summary>
private sealed class IdleContext : SynchronizationContext
{
public override void Post(SendOrPostCallback d, object? state)
{
}
}
private sealed class FakeJobsApi : IServerJobsApi
{
private readonly List<JobDto> _jobs = [];
public Channel<ServerEvent> Events { get; } = Channel.CreateUnbounded<ServerEvent>();
public TaskCompletionSource Disposed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public bool Refuse { get; init; }
public int Actions { get; private set; }
public Guid Add(string kind, string target, string state, JobDetailDto? detail = null)
{
var id = Guid.CreateVersion7();
lock (_jobs)
{
_jobs.Add(new JobDto(id, kind, [], target, state, "background", 10, 100, null, null, null, null, 1, null, T0, T0.AddMinutes(_jobs.Count), null, null,
detail));
}
return id;
}
public Task<Page<JobDto>> ListJobsAsync(string state, string? cursor, CancellationToken cancellationToken)
{
lock (_jobs)
{
var items = _jobs.Where(j => j.State == state).ToList();
return Task.FromResult(new Page<JobDto>(items, null, items.Count));
}
}
public Task<JobDto> GetJobAsync(Guid id, CancellationToken cancellationToken)
{
lock (_jobs) return Task.FromResult(_jobs.Single(j => j.Id == id));
}
public Task<JobDto> PauseJobAsync(Guid id, CancellationToken cancellationToken) => Set(id, "paused");
public Task<JobDto> ResumeJobAsync(Guid id, CancellationToken cancellationToken) => Set(id, "running");
public Task<JobDto> CancelJobAsync(Guid id, CancellationToken cancellationToken) => Set(id, "cancelled");
public async IAsyncEnumerable<ServerEvent> EventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
await foreach (var e in Events.Reader.ReadAllAsync(cancellationToken)) yield return e;
}
public void Dispose() => Disposed.TrySetResult();
private Task<JobDto> Set(Guid id, string state)
{
if (Refuse)
throw new Chronos.Protocol.Client.ChronosApiException(System.Net.HttpStatusCode.Conflict,
new ApiError("invalid_state", "The job cannot do that in its current state.", null));
Actions++;
lock (_jobs)
{
var index = _jobs.FindIndex(j => j.Id == id);
var job = _jobs[index] with { State = state };
_jobs[index] = job;
return Task.FromResult(job);
}
}
}
}
@@ -41,6 +41,27 @@ public sealed class ConnectFlowTests
Assert.Contains(Fingerprint, server.Created[^1]);
}
/// <summary>Owner review 5, #67: this PC's own shared library is refused before the trust question, and once trusted.</summary>
[Test]
public async Task ThisPcsOwnSharedLibraryIsRefused()
{
var server = new FakeServer { SelfSigned = true };
var trust = new MemoryTrust();
using var flow = new ConnectFlow(server, trust) { IsOwnLibrary = (fingerprint, _) => fingerprint == Fingerprint };
Assert.Equal(ConnectStep.Failed, await flow.ProbeAsync("localhost:8443"));
Assert.Equal(ConnectError.OwnLibrary, flow.Error);
Assert.Null(flow.PendingFingerprint);
Assert.Empty(trust.Fingerprints);
trust.Trust("https://localhost:8443", Fingerprint);
Assert.Equal(ConnectStep.Failed, await flow.ProbeAsync("localhost:8443"));
Assert.Equal(ConnectError.OwnLibrary, flow.Error);
Assert.Equal(0, server.Logins);
flow.IsOwnLibrary = (_, _) => false;
Assert.Equal(ConnectStep.AwaitingCredentials, await flow.ProbeAsync("localhost:8443"));
}
[Test]
public async Task RejectingTheCertificateSendsNothing()
{
@@ -0,0 +1,192 @@
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.App.Server;
using Chronos.App.Tests.Uploader;
using Chronos.Core.Localization;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Server.Jobs;
using Chronos.Testing;
namespace Chronos.App.Tests.Server;
/// <summary>Settings › Server › Share this library (owner review 5, #67): the server Chronos hosts over its own index and engines.</summary>
[WindowsOnly]
[Serial] // the hosted server's logging and Kestrel share the process with the other tests' Log sink
[Timeout(180_000)]
public sealed class LibraryShareTests
{
private sealed class NoDialogs : IAppDialogs
{
public string? PickFolder(string title, string? initialFolder = null) => null;
public string? PickJsonFile(string title) => null;
public bool Confirm(ConfirmRequest request) => false;
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
}
[Test]
public void A10SettingsFileSharesNothingOnDockersPortsAndResetTurnsSharingOff()
{
var settings = Assert.NotNull(AppSettings.Parse("""{ "Language": "en" }"""));
Assert.False(settings.Share.Enabled);
Assert.Equal((8443, 8080, true), (settings.Share.HttpsPort, settings.Share.HttpPort, settings.Share.Discovery));
Assert.Null(settings.Share.PublicHttpsPort);
settings.Share.Enabled = true;
settings.Share.HttpsPort = 9443;
var copy = Assert.NotNull(AppSettings.Parse(settings.ToJson()));
Assert.True(copy.Share.Enabled);
Assert.Equal(9443, copy.Share.HttpsPort);
Assert.False(settings.ResetKeepingState().Share.Enabled);
Assert.Equal(8443, settings.ResetKeepingState().Share.HttpsPort);
}
[Test]
public void TheSharedLibrarysCleanUpsAreScheduledOnlyWhileSharing()
{
var settings = new AppSettings();
var host = new DesktopScheduleHost(settings, () => null, () => null);
Assert.False(host.SystemSchedules.Any(s => s.SystemKey == ServerScheduleHost.UploadCleanup));
settings.Share.Enabled = true;
var keys = host.SystemSchedules.Select(s => s.SystemKey).ToList();
Assert.Contains(ServerScheduleHost.UploadCleanup, keys);
Assert.Contains(ServerScheduleHost.AuditCleanup, keys);
Assert.Contains(DesktopScheduleHost.ArchiveScan, keys);
}
[Test]
public void SharingStartsAfterTheSchedulesOnTheDesktopsEngineAndStopsFirst()
{
var environment = AppEnvironment.ForCapture();
try
{
SingleThreadedContext.Run(async () =>
{
var root = await ArchiveAsync(environment);
var (https, http) = (FreePort(), FreePort());
var settings = Settings(root, https, http);
var services = new AppServices(environment, settings, () => { }, new NoDialogs());
try
{
await services.OpenAsync(environment.DatabasePath);
Assert.True(await services.SchedulerReady, "the schedules started");
await WaitAsync(services.Share, ShareState.On);
var share = services.Share;
Assert.Equal((https, http), (share.HttpsPort, share.HttpPort));
Assert.True(share.Addresses.Count > 0, "addresses");
Assert.True(share.Addresses.All(a => a.StartsWith("https://", StringComparison.Ordinal) && a.EndsWith($":{https}", StringComparison.Ordinal)),
string.Join(", ", share.Addresses));
var fingerprint = Assert.NotNull(share.Fingerprint);
Assert.True(share.IsOwn(fingerprint, null), "own by fingerprint");
Assert.True(share.IsOwn(null, share.Server!.ServerId), "own by id");
Assert.False(share.IsOwn("00:11", Guid.NewGuid()), "another server");
Assert.NotNull(share.AdminPassword);
Assert.Same(services.Engine, share.Server.Services.GetService(typeof(JobEngineHost)) is JobEngineHost jobs ? jobs.Engine : null);
using (var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) })
{
using var health = await client.GetAsync($"http://127.0.0.1:{http}/health");
Assert.Equal(HttpStatusCode.OK, health.StatusCode);
}
Assert.NotNull(await services.Database!.Schedules.GetBySystemKeyAsync(ServerScheduleHost.UploadCleanup));
Assert.True(Directory.Exists(environment.ShareDirectory), "the share's folder");
// Stopped, the engine and the index run on; started again, the same certificate.
await share.StopAsync();
Assert.Equal(ShareState.Off, share.State);
Assert.Null(share.Server);
Assert.NotNull(await services.Database.Archives.ListAsync());
await share.RestartAsync();
Assert.Equal(ShareState.On, share.State);
Assert.Equal(fingerprint, share.Fingerprint);
// Sharing turned off in Settings stops it.
settings.Share.Enabled = false;
share.Apply();
await WaitAsync(share, ShareState.Off);
}
finally
{
Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(20)), "services stopped");
}
Assert.Null(services.Share.Server);
});
}
finally
{
environment.DeleteCaptureData();
}
}
[Test]
public void APortInUseLeavesSharingNotStartedNamingThePort()
{
var environment = AppEnvironment.ForCapture();
try
{
SingleThreadedContext.Run(async () =>
{
var root = await ArchiveAsync(environment);
// Held as another server would (both address families, exclusively): Windows lets a second program share a port otherwise.
using var taken = new TcpListener(IPAddress.IPv6Any, 0) { ExclusiveAddressUse = true };
taken.Server.DualMode = true;
taken.Start();
var https = ((IPEndPoint)taken.LocalEndpoint).Port;
var services = new AppServices(environment, Settings(root, https, FreePort()), () => { }, new NoDialogs());
try
{
await services.OpenAsync(environment.DatabasePath);
Assert.True(await services.SchedulerReady, "the schedules started");
await WaitAsync(services.Share, ShareState.Failed);
Assert.Equal(Loc.L("Errors.Share.PortInUse", https), services.Share.Reason);
Assert.Null(services.Share.Server);
Assert.False(services.Share.IsOwn(null, null), "nothing shared");
}
finally
{
Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(20)), "services stopped");
}
});
}
finally
{
environment.DeleteCaptureData();
}
}
private static AppSettings Settings(string root, int https, int http) => new()
{
Language = "en",
LastArchivePath = root,
Share = new ShareSettings { Enabled = true, HttpsPort = https, HttpPort = http, Discovery = false },
};
private static async Task<string> ArchiveAsync(AppEnvironment environment)
{
var root = Path.Combine(environment.DataDirectory, "archive");
await using var setup = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(environment.DataDirectory, "setup.db")));
await new ArchiveService(setup).CreateAsync(root, "Shared");
return root;
}
private static int FreePort()
{
using var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
return ((IPEndPoint)listener.LocalEndpoint).Port;
}
private static async Task WaitAsync(LibraryShare share, ShareState state)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(60);
while (share.State != state)
{
Assert.True(DateTime.UtcNow < until, $"sharing is {share.State} ({share.Reason}), not {state}");
await Task.Delay(50);
}
}
}
@@ -0,0 +1,91 @@
using System.Globalization;
using Chronos.App.Server;
using Chronos.App.Shell;
using Chronos.Core.Localization;
using Chronos.Core.Windows.Services;
using Chronos.Testing;
namespace Chronos.App.Tests.Server;
/// <summary>
/// The desktop's lifetime while it shares its library (owner review 5, #67): closing hides to the tray while sharing, Exit
/// asks first when clients are active, a start at sign-in waits in the tray; with sharing off nothing changes.
/// </summary>
public sealed class ShareTrayTests
{
public ShareTrayTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
[Test]
public void ChronosOutlivesItsWindowOnlyWhileSharingIsOnOrOnItsWay()
{
Assert.True(ShareLifetime.KeepsRunning(shareEnabled: true, ShareState.On));
Assert.True(ShareLifetime.KeepsRunning(shareEnabled: true, ShareState.Starting));
// On in the settings, not started yet: the index is opening, or the archive's drive is unplugged.
Assert.True(ShareLifetime.KeepsRunning(shareEnabled: true, ShareState.Off));
Assert.False(ShareLifetime.KeepsRunning(shareEnabled: true, ShareState.Failed));
// Turned off and still stopping: the icon stays until it has stopped.
Assert.True(ShareLifetime.KeepsRunning(shareEnabled: false, ShareState.On));
Assert.False(ShareLifetime.KeepsRunning(shareEnabled: false, ShareState.Off));
Assert.False(ShareLifetime.KeepsRunning(shareEnabled: false, ShareState.Failed));
}
[Test]
public void ClosingHidesToTheTrayWhileSharingAndExitsOtherwise()
{
Assert.Equal(CloseAction.HideToTray, ShareLifetime.OnClose(exiting: false, keepsRunning: true));
Assert.Equal(CloseAction.Exit, ShareLifetime.OnClose(exiting: false, keepsRunning: false));
// Tray › Exit, or Windows ending the session: the window closes for real.
Assert.Equal(CloseAction.Exit, ShareLifetime.OnClose(exiting: true, keepsRunning: true));
Assert.Equal(CloseAction.Exit, ShareLifetime.OnClose(exiting: true, keepsRunning: false));
}
[Test]
public void ExitAsksFirstOnlyWhenClientsUseTheSharedLibrary()
{
Assert.True(ShareLifetime.AsksBeforeExit(ShareState.On, 1));
Assert.True(ShareLifetime.AsksBeforeExit(ShareState.On, 3));
Assert.False(ShareLifetime.AsksBeforeExit(ShareState.On, 0));
Assert.False(ShareLifetime.AsksBeforeExit(ShareState.Starting, 2));
Assert.False(ShareLifetime.AsksBeforeExit(ShareState.Failed, 2));
Assert.False(ShareLifetime.AsksBeforeExit(ShareState.Off, 2));
}
[Test]
public void TheExitQuestionKeepsSharingByDefaultAndCountsTheClients()
{
var one = ShellTray.ExitRequest(1);
Assert.Equal("Stop sharing?", one.Heading);
Assert.Equal("1 client used this library in the last minutes. Exiting Chronos stops sharing it.", one.Message);
Assert.Equal(("Keep sharing", "Exit"), (one.SafeText, one.ActionText));
Assert.False(one.IsDestructive);
Assert.Null(one.TypedConfirmation);
Assert.Contains("4 clients used", ShellTray.ExitRequest(4).Message);
}
[Test]
public void AStartAtSignInWaitsInTheTrayWhileSharingIsOn()
{
Assert.Equal(StartWindow.Tray, ShareLifetime.Start(minimized: true, shareEnabled: true));
Assert.Equal(StartWindow.Minimized, ShareLifetime.Start(minimized: true, shareEnabled: false));
Assert.Equal(StartWindow.Shown, ShareLifetime.Start(minimized: false, shareEnabled: true));
Assert.Equal(StartWindow.Shown, ShareLifetime.Start(minimized: false, shareEnabled: false));
}
[Test]
public void TheTrayToolTipNamesTheLibraryOrThisPc()
{
Assert.Equal("Chronos · sharing Studio", ShareLifetime.ToolTip(" Studio ", "STUDIO-PC"));
Assert.Equal("Chronos · sharing STUDIO-PC", ShareLifetime.ToolTip(null, "STUDIO-PC"));
Assert.Equal("Chronos · sharing STUDIO-PC", ShareLifetime.ToolTip(" ", "STUDIO-PC"));
}
[Test]
[WindowsOnly]
public void TheServiceProbeFindsInstalledServicesOnly()
{
// The event log service runs on every Windows; the probe asks connect and query-status rights only.
Assert.True(ServiceProbe.IsInstalled("EventLog"));
Assert.False(ServiceProbe.IsInstalled("ChronosNoSuchService" + Guid.NewGuid().ToString("N")));
Assert.Equal("ChronosServer", ServiceProbe.LegacyServer);
}
}
@@ -0,0 +1,441 @@
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Win32;
using Chronos.Core.Localization;
using Chronos.Core.Packaging;
using Chronos.Setup.Cli;
using Chronos.Setup.Engine;
using Chronos.Setup.Views;
using Chronos.Testing;
namespace Chronos.App.Tests.Setup;
/// <summary>
/// One setup for Chronos Desktop and Chronos Uploader: what a run installs, keeps and removes. A 1.0 Server for Windows
/// is retained until the user unticks it or the switches leave it out, the separate 1.0 Uploader is replaced, a file
/// changed since setup installed it is never deleted, and the Changes line is the dry-run plan of all of it.
/// </summary>
public sealed class SingleSetupTests(TestContext context)
{
private const string TestsKey = @"Software\Chronos.Tests";
/// <summary>The StartupApproved state Task Manager writes for an entry it turned off.</summary>
private static readonly byte[] TurnedOff = [0x03, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
static SingleSetupTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
[Test]
public void ANewInstallationTakesTheDesktopAppAndDesktopNamesIt()
{
var manifest = Manifest();
var plan = InstallPlan.Resolve(manifest, new SetupArguments(), null, null, null);
Assert.SequenceEqual(["Chronos"], plan.Components);
Assert.Empty(plan.Retained);
Assert.True(plan.CanChangeLocation);
Assert.Equal(InstallScope.CurrentUser, plan.Scope);
var both = InstallPlan.Resolve(manifest, new SetupArguments { Components = ["Desktop", "Uploader"] }, null, null, null);
Assert.SequenceEqual(["Chronos", "Uploader"], both.Components);
Assert.SequenceEqual(["Uploader"], InstallPlan.Resolve(manifest, new SetupArguments { Components = ["uploader"] }, null, null, null).Components);
// The Server is no longer offered: asking for it without a 1.0 Server installed is a wrong switch.
var refused = Assert.Throws<SetupException>(() => InstallPlan.Resolve(manifest, new SetupArguments { Components = ["Server"] }, null, null, null));
Assert.Equal(SetupExitCode.InvalidArguments, refused.Code);
}
[Test]
public void A10ServerIsRetainedUntilTheSwitchesLeaveItOut()
{
var manifest = Manifest();
var directory = context.CreateTempDirectory("retained");
var previous = ServerLog(directory);
var existing = new ExistingInstall(InstallScope.AllUsers, directory, "1.0.0");
// Nothing said: the desktop app and the Uploader are updated, the Server is kept with every file this payload
// does not know (a format 1 log does not say which component installed what), and its own shortcut.
var plan = InstallPlan.Resolve(manifest, new SetupArguments(), existing, previous, null);
Assert.SequenceEqual(["Chronos", "Uploader"], plan.Components);
var server = Assert.Contains(plan.Retained, r => r.Id == "Server");
Assert.Count(1, plan.Retained);
Assert.Equal("1.0.0", server.Version);
Assert.SequenceEqual(["Chronos.Server.exe", "legacy.txt"], server.Files);
Assert.SequenceEqual([Path.Combine(directory, "Chronos Server.lnk")], server.Shortcuts);
Assert.SequenceEqual(["Server"], plan.Kept.Select(k => k.Id));
Assert.Empty(plan.Removed(plan.Kept));
Assert.False(plan.CanChangeLocation);
// Its program keeps running: it is not among those setup closes or whose service it stops.
previous.Save(directory);
var programs = InstallPlan.Programs(manifest, directory, plan.Kept).ToList();
Assert.Contains("Chronos.Uploader.exe", programs);
Assert.DoesNotContain("Chronos.Server.exe", programs);
Assert.DoesNotContain("legacy.txt", programs);
Assert.Contains("Chronos.Server.exe", InstallPlan.Programs(manifest, directory, []));
// Switches are exact: leaving the Server out removes it; naming it keeps it.
var desktop = InstallPlan.Resolve(manifest, new SetupArguments { Components = ["Desktop"] }, existing, previous, null);
Assert.SequenceEqual(["Chronos"], desktop.Components);
Assert.Empty(desktop.Kept);
Assert.SequenceEqual(["Server"], desktop.Removed(desktop.Kept).Select(r => r.Id));
var kept = InstallPlan.Resolve(manifest, new SetupArguments { Components = ["Desktop", "Server"] }, existing, previous, null);
Assert.SequenceEqual(["Chronos"], kept.Components);
Assert.SequenceEqual(["Server"], kept.Kept.Select(k => k.Id));
}
[Test]
public void AFormat2LogKeepsOnlyTheFilesOfTheRetainedComponent()
{
var manifest = Manifest();
var log = new InstallLog
{
FormatVersion = InstallLog.CurrentFormat,
Product = "Chronos",
Version = "1.1.0",
Scope = InstallScope.AllUsers,
Components = ["Chronos", "Server"],
Files = ["Chronos.exe", "old.dll", "Chronos.Server.exe"],
ComponentFiles = { ["Chronos"] = ["Chronos.exe", "old.dll"], ["Server"] = ["Chronos.Server.exe"] },
ComponentVersions = { ["Chronos"] = "1.1.0", ["Server"] = "1.0.0" },
Hashes = { ["Chronos.Server.exe"] = new string('a', 64) },
};
var server = Assert.Contains(LegacyProducts.Retained(manifest, log), r => r.Id == "Server");
Assert.Equal("1.0.0", server.Version);
Assert.SequenceEqual(["Chronos.Server.exe"], server.Files);
Assert.Equal(new string('a', 64), server.Hashes["chronos.server.exe"]);
Assert.Empty(LegacyProducts.Retained(manifest, null));
// Without an installation of its own (only a log), nothing is retained.
Assert.Empty(InstallPlan.Resolve(manifest, new SetupArguments(), null, log, null).Retained);
}
[Test]
public void TheInstallLogRecordsEachComponentAndStillReadsA10Log()
{
var log = new InstallLog
{
FormatVersion = InstallLog.CurrentFormat,
Product = "Chronos",
Version = "1.1.0",
Components = ["Chronos", "Server"],
Files = ["Chronos.exe", "Chronos.Server.exe"],
ComponentFiles = { ["Chronos"] = ["Chronos.exe"], ["Server"] = ["Chronos.Server.exe"] },
ComponentShortcuts = { ["Chronos"] = [@"C:\Links\Chronos.lnk"], ["Server"] = [] },
ComponentVersions = { ["Chronos"] = "1.1.0", ["Server"] = "1.0.0" },
Hashes = { ["Chronos.exe"] = new string('b', 64) },
};
var read = Assert.NotNull(InstallLog.FromJson(log.ToJson()));
Assert.Equal(2, read.FormatVersion);
Assert.True(read.HasComponentFiles);
Assert.SequenceEqual(["Chronos.Server.exe"], read.FilesOf("server")!);
Assert.SequenceEqual([@"C:\Links\Chronos.lnk"], read.ShortcutsOf("Chronos")!);
Assert.Equal("1.0.0", read.VersionOf("Server"));
Assert.Equal(new string('b', 64), read.HashOf("CHRONOS.EXE"));
Assert.Empty(read.FilesOf("Uploader")!);
// As Chronos 1.0 wrote it: no format, no record of which component installed what.
var old = Assert.NotNull(InstallLog.FromJson("""
{"product":"Chronos","version":"1.0.0","scope":"CurrentUser","components":["Chronos","Server"],
"files":["Chronos.exe","Chronos.Server.exe"],"shortcuts":[],"associations":[]}
"""u8));
Assert.Equal(1, old.FormatVersion);
Assert.False(old.HasComponentFiles);
Assert.Null(old.FilesOf("Server"));
Assert.Equal("1.0.0", old.VersionOf("Server"));
Assert.Null(old.HashOf("Chronos.exe"));
}
[Test]
public void AFileChangedSinceSetupInstalledItIsNeverDeleted()
{
var directory = context.CreateTempDirectory("changed");
var same = Encoding.UTF8.GetBytes("as installed");
File.WriteAllBytes(Path.Combine(directory, "same.exe"), same);
File.WriteAllText(Path.Combine(directory, "edited.exe"), "changed since");
File.WriteAllText(Path.Combine(directory, "unknown.exe"), "a 1.0 log has no hash");
var hash = Convert.ToHexStringLower(SHA256.HashData(same));
var log = new InstallLog
{
FormatVersion = InstallLog.CurrentFormat,
Product = "Chronos",
Version = "1.1.0",
Hashes = { ["same.exe"] = hash, ["edited.exe"] = hash, ["gone.exe"] = hash },
};
// Only the edited file is kept; a missing file or one without a recorded hash is removed as before.
Assert.SequenceEqual(["edited.exe"], InstallEngine.Changed(directory, log, ["same.exe", "edited.exe", "unknown.exe", "gone.exe"]));
}
[Test]
public void ALegacyUploaderPreselectsTheUploaderAndFixesTheScope()
{
var manifest = Manifest();
var root = context.CreateTempDirectory("legacy");
var legacy = Legacy(Path.Combine(root, "Chronos Uploader"), InstallScope.CurrentUser);
// Its removal needs the same account, so the scope is the legacy copy's whatever the switches say.
var plan = InstallPlan.Resolve(manifest, new SetupArguments { AllUsers = true, Directory = Path.Combine(root, "Elsewhere") }, null, null, legacy);
Assert.Equal(InstallScope.CurrentUser, plan.Scope);
Assert.Equal(SetupPaths.DefaultDirectory(InstallScope.CurrentUser, manifest.Product), plan.Directory);
Assert.SequenceEqual(["Uploader"], plan.Components);
Assert.False(plan.CanChangeLocation);
Assert.Same(legacy, plan.LegacyToReplace(plan.Components, plan.Scope, plan.Directory));
Assert.Null(plan.LegacyToReplace(["Chronos"], plan.Scope, plan.Directory));
// An all-users copy stays under a per-user installation (its removal needs administrator approval), and a
// copy is never replaced by an installation in its own folder.
var allUsers = Legacy(Path.Combine(root, "Program Files", "Chronos Uploader"), InstallScope.AllUsers);
Assert.False(LegacyProducts.CanMerge(allUsers, InstallScope.CurrentUser, Path.Combine(root, "Chronos")));
Assert.True(LegacyProducts.CanMerge(allUsers, InstallScope.AllUsers, Path.Combine(root, "Program Files", "Chronos")));
Assert.False(LegacyProducts.CanMerge(legacy, InstallScope.CurrentUser, legacy.Directory));
Assert.False(LegacyProducts.CanMerge(legacy, InstallScope.CurrentUser, Path.Combine(legacy.Directory, "Chronos")));
// Another product's setup leaves the 1.0 Uploader alone.
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()
{
var root = context.CreateTempDirectory("merge");
var legacyDir = Path.Combine(root, "Chronos Uploader");
var directory = Path.Combine(root, "Chronos");
Directory.CreateDirectory(directory);
File.WriteAllBytes(Path.Combine(directory, "Chronos.Uploader.exe"), [0x4D, 0x5A]);
var programs = LegacyProducts.StartupPrograms(Manifest(), directory);
Assert.SequenceEqual(["Chronos Uploader"], programs.Keys);
var keyPath = TestsKey + @"\" + Guid.NewGuid().ToString("N");
try
{
using var run = Registry.CurrentUser.CreateSubKey(keyPath + @"\Run", writable: true);
using var approval = Registry.CurrentUser.CreateSubKey(keyPath + @"\Approved", writable: true);
run.SetValue("Chronos Uploader", $"\"{Path.Combine(legacyDir, "Chronos.Uploader.exe")}\" --tray");
approval.SetValue("Chronos Uploader", TurnedOff, RegistryValueKind.Binary);
var dropped = CommandProgram.FullPaths(legacyDir, ["Chronos.Uploader.exe", "Uninstall Chronos Uploader.exe"]);
Assert.SequenceEqual(["Chronos Uploader"], SetupRegistry.MoveStartupEntries(run, approval, dropped, programs));
Assert.Equal($"\"{Path.Combine(directory, "Chronos.Uploader.exe")}\" --tray", run.GetValue("Chronos Uploader"));
Assert.SequenceEqual(["Chronos Uploader"], approval.GetValueNames());
}
finally
{
Registry.CurrentUser.DeleteSubKeyTree(keyPath, throwOnMissingSubKey: false);
bool empty;
using (var tests = Registry.CurrentUser.OpenSubKey(TestsKey)) empty = tests is { SubKeyCount: 0, ValueCount: 0 };
if (empty) Registry.CurrentUser.DeleteSubKey(TestsKey, throwOnMissingSubKey: false);
}
}
[Test]
[WindowsOnly]
public void ReplacingTheLegacyUploaderRemovesItsEntryAndFolder()
{
var root = context.CreateTempDirectory("merge");
// A product name no machine has, so the entry written and removed is the test's own.
var product = "ChronosTest" + Guid.NewGuid().ToString("N")[..12];
var legacyDir = Path.Combine(root, product);
Directory.CreateDirectory(legacyDir);
File.WriteAllBytes(Path.Combine(legacyDir, "Chronos.Uploader.exe"), [0x4D, 0x5A]);
var log = new InstallLog { Product = product, Version = "1.0.0", Scope = InstallScope.CurrentUser, Components = ["Uploader"], Files = ["Chronos.Uploader.exe"] };
log.Save(legacyDir);
File.WriteAllBytes(Path.Combine(legacyDir, log.UninstallerName), [0x4D, 0x5A]);
var key = SetupPaths.ProductKey(product);
try
{
SetupRegistry.WriteUninstallEntry(InstallScope.CurrentUser, key, new UninstallEntry(product, "1.0.0", "Chronos", legacyDir,
Path.Combine(legacyDir, log.UninstallerName), Path.Combine(legacyDir, "Chronos.Uploader.exe"), 2, null));
Assert.NotNull(SetupRegistry.FindInstall(key));
var directory = Path.Combine(root, "Chronos");
Directory.CreateDirectory(directory);
LegacyProducts.Merge(new LegacyInstall(new InstalledProduct(legacyDir, log), InstallScope.CurrentUser), Manifest(), directory);
Assert.Null(SetupRegistry.FindInstall(key));
Assert.False(Directory.Exists(legacyDir), "the legacy folder is removed");
Assert.True(Directory.Exists(directory));
}
finally
{
SetupRegistry.DeleteUninstallEntry(InstallScope.CurrentUser, key);
}
}
[Test]
[WindowsOnly]
public void TheChangesLineIsTheDryRunPlanAndNothingTickedUninstalls()
{
var root = context.CreateTempDirectory("changes");
using var payload = PayloadReader.Open(WritePayload(root));
var manifest = payload.Manifest;
var directory = Path.Combine(root, "Installed");
var existing = new ExistingInstall(InstallScope.AllUsers, directory, "1.0.0");
var previous = ServerLog(directory);
previous.Components = ["Chronos", "Server"];
// Updating keeps the Server and adds nothing: nothing to say.
using (var update = SetupViewModel.ForInstall(new SetupArguments(), payload, InstallPlan.Resolve(manifest, new SetupArguments(), existing, previous, null)))
{
Assert.Equal("Update", update.InstallText);
Assert.False(update.HasChanges);
var server = Assert.Contains(update.Components, c => c.IsRetained);
Assert.Equal("Chronos Server 1.0.0", server.Name);
Assert.Equal("No longer offered", server.StateText);
Assert.Contains(update.Components, c => c.Id == "Uploader").IsSelected = true;
Assert.Equal("Adds Chronos Uploader", update.ChangesText);
server.IsSelected = false;
Assert.Equal("Adds Chronos Uploader · Removes Chronos Server 1.0.0", update.ChangesText);
Assert.True(update.Changes[1].IsRemoval);
Assert.Contains("Chronos.Server.exe", update.Changes[1].ToolTip);
// Every program unticked: the primary action removes the installation, and Cancel is the default.
foreach (var c in update.Components) c.IsSelected = false;
Assert.True(update.IsUninstallAll);
Assert.True(update.IsUninstallAllPrimary);
Assert.False(update.IsInstallPrimary);
Assert.True(update.IsCancelDefault);
Assert.False(update.HasChanges);
}
// A new installation beside the separate 1.0 Uploader replaces it, and says so.
var legacy = Legacy(Path.Combine(root, "Chronos Uploader"), InstallScope.CurrentUser);
using (var replace = SetupViewModel.ForInstall(new SetupArguments(), payload, InstallPlan.Resolve(manifest, new SetupArguments(), null, null, legacy)))
{
Assert.Equal("Install", replace.InstallText);
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.
using var fresh = SetupViewModel.ForInstall(new SetupArguments(), payload, InstallPlan.Resolve(manifest, new SetupArguments(), null, null, null));
Assert.Equal("Install", fresh.InstallText);
foreach (var c in fresh.Components) c.IsSelected = false;
Assert.False(fresh.IsUninstallAll);
Assert.False(fresh.PrimaryCommand.CanExecute(null));
}
/// <summary>The single setup's payload as pack-installer writes it, its programs one byte each.</summary>
private static PayloadManifest Manifest(string product = "Chronos") => new()
{
Product = product,
Version = "1.1.0",
Components =
[
new PayloadComponent { Id = "Chronos", DisplayName = "Chronos Desktop", DefaultSelected = true },
new PayloadComponent { Id = "Uploader", DisplayName = "Chronos Uploader" },
],
Files =
[
new PayloadFile { Path = "Chronos.exe", Component = "Chronos", Sha256 = new string('1', 64) },
new PayloadFile { Path = "Chronos.Uploader.exe", Component = "Uploader", Sha256 = new string('2', 64) },
],
Shortcuts =
[
new PayloadShortcut { Component = "Chronos", Name = "Chronos", Target = "Chronos.exe", StartMenu = true, Desktop = true },
new PayloadShortcut { Component = "Uploader", Name = "Chronos Uploader", Target = "Chronos.Uploader.exe", StartMenu = true, Desktop = true },
],
};
/// <summary>The log Chronos 1.0 wrote for the desktop app, the Uploader and the Server for Windows (format 1).</summary>
private static InstallLog ServerLog(string directory) => new()
{
Product = "Chronos",
Version = "1.0.0",
Scope = InstallScope.AllUsers,
Components = ["Chronos", "Uploader", "Server"],
Files = ["Chronos.exe", "Chronos.Uploader.exe", "Chronos.Server.exe", "legacy.txt"],
Shortcuts =
[
Path.Combine(directory, "Chronos.lnk"),
Path.Combine(directory, "Chronos Uploader.lnk"),
Path.Combine(directory, "Chronos Server.lnk"),
],
};
private static LegacyInstall Legacy(string directory, InstallScope scope) =>
new(new InstalledProduct(directory, new InstallLog
{
Product = LegacyProducts.UploaderProduct,
Version = "1.0.0",
Scope = scope,
Components = ["Uploader"],
Files = ["Chronos.Uploader.exe"],
}), scope);
/// <summary>Writes the single setup's payload (the two programs, the desktop app preselected) to a scratch installer.</summary>
private static string WritePayload(string root)
{
var stub = Path.Combine(root, "stub.exe");
var bytes = new byte[4096];
new Random(7).NextBytes(bytes);
"MZ"u8.CopyTo(bytes);
File.WriteAllBytes(stub, bytes);
foreach (var (id, program) in (ReadOnlySpan<(string, string)>)[("Chronos", "Chronos.exe"), ("Uploader", "Chronos.Uploader.exe")])
{
var folder = Directory.CreateDirectory(Path.Combine(root, "payload", id)).FullName;
File.WriteAllText(Path.Combine(folder, program), "MZ " + program);
}
var installer = Path.Combine(root, "setup.exe");
PayloadWriter.Write(stub, new PayloadSource
{
Product = "Chronos",
Version = "1.1.0",
Components =
[
new PayloadComponentSource("Chronos", "Chronos Desktop", true, Path.Combine(root, "payload", "Chronos")),
new PayloadComponentSource("Uploader", "Chronos Uploader", false, Path.Combine(root, "payload", "Uploader")),
],
Shortcuts =
[
new PayloadShortcut { Component = "Chronos", Name = "Chronos", Target = "Chronos.exe", StartMenu = true, Desktop = true },
new PayloadShortcut { Component = "Uploader", Name = "Chronos Uploader", Target = "Chronos.Uploader.exe", StartMenu = true, Desktop = true },
],
}, installer);
return installer;
}
}
@@ -0,0 +1,260 @@
using System.IO;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using Chronos.Core.Localization;
using Chronos.Core.Updates;
using Chronos.Testing;
using Chronos.Ui.Mvvm;
using Chronos.Ui.Updates;
using Chronos.Uploader.Infrastructure;
using Chronos.Uploader.Shell;
namespace Chronos.App.Tests.Uploader;
/// <summary>
/// The Uploader's update check (owner review 5, #64): on by default, also for a 1.0 settings file; skipped on start when
/// Chronos Desktop sits beside it while Check now still works; Check now reads the releases feed; Download verifies the
/// single setup against <c>SHA256SUMS</c> and Show setup reveals it.
/// </summary>
public sealed class UploaderUpdatesTests(TestContext context)
{
private const string Repository = "https://gitea.example/o/r";
private const string SetupName = "Chronos-Setup-1.1.0.exe";
private static readonly byte[] Setup = Encoding.UTF8.GetBytes("the single setup of Chronos 1.1.0");
[Test]
public void CheckOnStartIsOnByDefaultAndA10SettingsFileKeepsIt()
{
Assert.True(new UploaderSettings().CheckForUpdates);
var folder = context.CreateTempDirectory();
var path = Path.Combine(folder, "uploader.json");
// An Uploader 1.0 settings file: no checkForUpdates key.
File.WriteAllText(path, """
{
"serverUrl": "https://nas.local:8443/",
"username": "alberto",
"bandwidthLimit": 50,
"minimizeToTray": true,
"deleteAfterUpload": false,
"target": "Sessions",
"watchFolders": [],
"theme": "Dark"
}
""");
var loaded = UploaderSettings.Load(path);
Assert.True(loaded.CheckForUpdates, "a 1.0 file loads with the check on");
Assert.Equal("alberto", loaded.Username);
loaded.CheckForUpdates = false;
loaded.Save(path);
Assert.Contains("\"checkForUpdates\": false", File.ReadAllText(path));
Assert.False(UploaderSettings.Load(path).CheckForUpdates, "the opt-out survives a restart");
}
[Test]
public void TheDesktopIsFoundBesideTheUploader()
{
var folder = context.CreateTempDirectory();
Assert.False(UploaderEnvironment.IsDesktopBeside(folder));
File.WriteAllText(Path.Combine(folder, UploaderEnvironment.DesktopExecutable), "desktop");
Assert.True(UploaderEnvironment.IsDesktopBeside(folder));
}
[Test]
public void TheStartUpCheckIsSkippedBesideTheDesktopWhileCheckNowStillWorks() => SingleThreadedContext.Run(async () =>
{
Assert.True(UpdatesViewModel.ChecksOnStart(enabled: true, desktopBeside: false));
Assert.False(UpdatesViewModel.ChecksOnStart(enabled: true, desktopBeside: true));
Assert.False(UpdatesViewModel.ChecksOnStart(enabled: false, desktopBeside: false));
var feed = new Feed().Release("v1.1.0");
using var vm = Notice(feed, out _);
ReleaseInfo? found = null;
vm.Found += r => found = r;
await vm.CheckOnStartAsync(desktopBeside: true);
Assert.Equal(0, feed.FeedRequests);
Assert.Equal(UpdateState.Unknown, vm.State);
Assert.Null(vm.StatusText);
await RunAsync(vm.CheckCommand);
Assert.Equal(1, feed.FeedRequests);
Assert.Equal(Loc.L("Uploader.Updates.Available", "1.1.0"), vm.StatusText);
Assert.Null(found, "Check now reports in the panel, not in a toast");
});
[Test]
public void TheStartUpCheckFollowsTheOptOutAndOffersANewerRelease() => SingleThreadedContext.Run(async () =>
{
var feed = new Feed().Release("v1.1.0");
var settings = new UploaderSettings { CheckForUpdates = false };
var saves = 0;
using var vm = new UpdatesViewModel(Host(feed, context.CreateTempDirectory(), []), settings, () => saves++);
ReleaseInfo? found = null;
vm.Found += r => found = r;
await vm.CheckOnStartAsync(desktopBeside: false);
Assert.Equal(0, feed.FeedRequests);
vm.CheckOnStart = true;
Assert.True(settings.CheckForUpdates);
Assert.Equal(1, saves);
await vm.CheckOnStartAsync(desktopBeside: false);
Assert.Equal(1, feed.FeedRequests);
Assert.Equal("v1.1.0", found?.Tag);
Assert.True(vm.IsDownloadOffered);
});
[Test]
public void CheckNowShowsUpToDateAvailableOrFailed() => SingleThreadedContext.Run(async () =>
{
var current = new Feed().Release("v1.0.0");
using (var vm = Notice(current, out _))
{
await RunAsync(vm.CheckCommand);
Assert.Equal(UpdateState.UpToDate, vm.State);
Assert.Equal(Loc.L("Uploader.Updates.UpToDate"), vm.StatusText);
Assert.Equal(Loc.L("Tooltips.Uploader.Updates.UpToDate"), vm.StatusToolTip);
Assert.False(vm.IsDownloadOffered);
}
var newer = new Feed().Release("v1.1.0");
using (var vm = Notice(newer, out _))
{
await RunAsync(vm.CheckCommand);
Assert.Equal(Loc.L("Uploader.Updates.Available", "1.1.0"), vm.StatusText);
Assert.Equal(Loc.L("Tooltips.Uploader.Updates.Available"), vm.StatusToolTip);
Assert.True(vm.IsDownloadOffered);
Assert.Contains("SHA-256", vm.DownloadToolTip);
}
foreach (var status in new[] { HttpStatusCode.NotFound, HttpStatusCode.InternalServerError })
{
var broken = new Feed { FeedStatus = status };
using var vm = Notice(broken, out _);
await RunAsync(vm.CheckCommand);
Assert.Equal(UpdateState.Failed, vm.State);
Assert.Equal(Loc.L("Uploader.Updates.Failed"), vm.StatusText);
Assert.Equal(Loc.L("Tooltips.Uploader.Updates.Failed"), vm.StatusToolTip);
}
});
[Test]
public void DownloadVerifiesTheSetupAndShowSetupRevealsIt() => SingleThreadedContext.Run(async () =>
{
var feed = new Feed().Release("v1.1.0");
using var vm = Notice(feed, out var revealed);
await RunAsync(vm.CheckCommand);
await RunAsync(vm.DownloadCommand);
Assert.Equal(UpdateState.Downloaded, vm.State);
Assert.True(vm.IsReady);
Assert.Equal(Loc.L("Uploader.Updates.Ready", "1.1.0"), vm.StatusText);
var path = Assert.NotNull(vm.PackagePath);
Assert.Equal(SetupName, Path.GetFileName(path));
Assert.SequenceEqual(Setup, File.ReadAllBytes(path));
Assert.SequenceEqual(new[] { path }, revealed);
Assert.True(vm.ShowSetupCommand.CanExecute(null));
vm.ShowSetupCommand.Execute(null);
Assert.SequenceEqual(new[] { path, path }, revealed);
});
[Test]
public void ASetupThatDoesNotMatchItsChecksumIsRefused() => SingleThreadedContext.Run(async () =>
{
var feed = new Feed { WrongChecksum = true }.Release("v1.1.0");
using var vm = Notice(feed, out var revealed);
await RunAsync(vm.CheckCommand);
await RunAsync(vm.DownloadCommand);
Assert.Equal(UpdateState.NotVerified, vm.State);
Assert.Equal(Loc.L("Uploader.Updates.NotVerified"), vm.StatusText);
Assert.Null(vm.PackagePath);
Assert.Empty(revealed);
Assert.False(vm.ShowSetupCommand.CanExecute(null));
Assert.True(vm.IsDownloadOffered, "the download can be tried again");
});
[Test]
public void TheCaptureNoticeNeverTouchesTheNetwork() => SingleThreadedContext.Run(async () =>
{
using var vm = new UpdatesViewModel(UploaderUpdates.Offline("1.0.0"), new UploaderSettings(), () => { });
await vm.CheckOnStartAsync(desktopBeside: false);
await RunAsync(vm.CheckCommand);
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 = [];
return new UpdatesViewModel(Host(feed, context.CreateTempDirectory(), revealed), new UploaderSettings(), () => { });
}
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", downloadRoot, _ => { }, revealed.Add);
}
private static async Task RunAsync(System.Windows.Input.ICommand command)
{
var async = (AsyncRelayCommand)command;
async.Execute(null);
for (var i = 0; i < 500 && async.IsRunning; i++) await Task.Delay(10);
Assert.False(async.IsRunning, "the command did not finish");
}
/// <summary>The releases API, the setup and its <c>SHA256SUMS</c>, served from memory.</summary>
private sealed class Feed : HttpMessageHandler
{
private string _json = "[]";
private string _sums = string.Empty;
private string _tag = string.Empty;
public HttpStatusCode FeedStatus { get; init; } = HttpStatusCode.OK;
public bool WrongChecksum { get; init; }
public int FeedRequests { get; private set; }
public Feed Release(string tag)
{
_tag = tag;
var hash = WrongChecksum ? new string('0', 64) : Convert.ToHexStringLower(SHA256.HashData(Setup));
_sums = $"{hash} {SetupName}\n";
_json = $$"""
[{"tag_name":"{{tag}}","draft":false,"prerelease":false,"html_url":"{{Repository}}/releases/tag/{{tag}}",
"assets":[{"name":"{{SetupName}}","size":{{Setup.Length}},"browser_download_url":"x"},
{"name":"SHA256SUMS","size":{{_sums.Length}},"browser_download_url":"x"}]}]
""";
return this;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var path = request.RequestUri!.AbsolutePath;
if (path == "/api/v1/repos/o/r/releases")
{
FeedRequests++;
return Answer(FeedStatus, Encoding.UTF8.GetBytes(_json));
}
if (path == $"/o/r/releases/download/{_tag}/SHA256SUMS") return Answer(HttpStatusCode.OK, Encoding.UTF8.GetBytes(_sums));
if (path == $"/o/r/releases/download/{_tag}/{SetupName}") return Answer(HttpStatusCode.OK, Setup);
return Answer(HttpStatusCode.NotFound, []);
}
private static Task<HttpResponseMessage> Answer(HttpStatusCode status, byte[] body) =>
Task.FromResult(new HttpResponseMessage(status) { Content = new ByteArrayContent(body) });
}
}
@@ -1,4 +1,5 @@
using System.Globalization;
using System.IO;
using System.Text.Json;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
@@ -50,7 +51,7 @@ public sealed class ServerHomeTests(TestContext context)
// Checked out from the server: its media are downloaded by a copy job that names the server, never this PC's archive.
var checkout = await host.CheckoutAsync(named, null, null, cancellationToken: bed.Ct);
var bundle = host.Store.Find(checkout.Project.Id)!.ReadBundle();
var bundle = host.Find(checkout.Project.Id)!.ReadBundle();
Assert.Equal((BundleHome.ServerKind, Server, bed.SequenceId), (bundle.Workspace!.Home.Kind, bundle.Workspace.Home.Server, bundle.Workspace.Home.SequenceId));
using (var parameters = JsonDocument.Parse(checkout.Copy.ParametersJson!))
{
@@ -83,8 +84,8 @@ public sealed class ServerHomeTests(TestContext context)
var other = bed.Host(name: "other-pc");
var otherId = await bed.CheckoutAsync(other);
Assert.Equal(projectId, otherId);
var session = await other.Sync.OpenAsync(projectId, bed.Ct);
await other.Sync.SaveAsync(projectId, session.Working with { HeroFrame = 2 }, bed.Ct);
var session = await other.SyncOf(projectId).OpenAsync(projectId, bed.Ct);
await other.SyncOf(projectId).SaveAsync(projectId, session.Working with { HeroFrame = 2 }, bed.Ct);
await other.SaveVersionAsync(projectId, null, bed.Ct);
status = await host.StatusAsync(projectId, cancellationToken: bed.Ct);
Assert.Equal((WorkspaceState.Behind, 1), (status.State, status.Behind));
@@ -109,13 +110,46 @@ public sealed class ServerHomeTests(TestContext context)
Assert.Equal(Loc.L("Editor.Workspace.State.Gone.Server"), WorkspaceText.State(status, server: true));
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.State.Gone.Server"), WorkspaceText.StateToolTip(status, server: true));
Assert.Equal(StatusKind.Warning, WorkspaceText.Kind(status));
Assert.NotNull(host.Store.Find(projectId)?.ReadMedia());
Assert.NotNull(host.Find(projectId)?.ReadMedia());
// A server that answers 404 for the project itself (deleted with its sequence) is gone too.
server.Deleted.Clear();
server.Missing = true;
Assert.Equal(WorkspaceState.Gone, (await host.StatusAsync(projectId, cancellationToken: bed.Ct)).State);
}
[Test]
public async Task EachHomeChecksOutIntoItsOwnFolderAndTheServerIsOneByItsId()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 3);
var serverId = Guid.CreateVersion7();
var idKey = Chronos.Core.IO.HomeFolders.IdKey(serverId);
var host = bed.Host();
host.Identity = () => new Chronos.Data.Sync.ServerIdentity([new Chronos.Data.Sync.KnownServerKey(serverId, [Server])]);
var server = new FakeServer(bed);
host.ServerHomes = home => host.SameServer(home.Server, idKey) && home.SequenceId == server.Inner.SequenceId ? server : null;
// A server project goes into the server's folder, named by its id even though the project names its address.
var checkout = await host.CheckoutAsync(ServerHome(bed), null, null, cancellationToken: bed.Ct);
var folder = host.Find(checkout.Project.Id)!;
Assert.Equal(Path.Combine(host.Root, "servers", serverId.ToString("N")), folder.Store.Root);
Assert.Equal(Server, folder.ReadBundle().Workspace!.Home.Server);
Assert.True(host.SameServer(Server, idKey), "the address is an alias of the id");
Assert.False(host.SameServer("https://elsewhere:8443", idKey));
// The server told by its id reaches the project that names its address.
var told = new List<WorkspaceHomeChange>();
host.HomeChanged += told.Add;
host.OnServerProjectChanged(idKey, new ProjectChangedEvent(bed.SequenceId, checkout.Project.Id, ProjectChanges.Pushed, 2, Guid.CreateVersion7()));
Assert.Equal(checkout.Project.Id, told.Single().ProjectId);
// A project of this PC's archive goes into local\, and the picker lists both.
var other = bed.Host(name: "second");
var localId = await bed.CheckoutAsync(other);
Assert.Equal(Path.Combine(other.Root, "local"), other.Find(localId)!.Store.Root);
Assert.SequenceEqual([checkout.Project.Id], host.Homes.List().Select(p => p.ProjectId).ToArray());
Assert.Count(1, (await host.ListAsync(bed.Ct)).Where(e => e.ProjectId == checkout.Project.Id));
}
[Test]
public void TheServersProjectChangesReachOnlyTheProjectsItIsHomeOf()
{
@@ -146,7 +180,7 @@ public sealed class ServerHomeTests(TestContext context)
// Opened signed out; the sign-in made later is the one the source connects with.
FakeRemoteSequenceApi? signedIn = null;
var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
var source = new WorkspaceSequenceSource(host.SyncOf(projectId), projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
new WorkspaceServerHome(() => signedIn, () => signedIn));
var content = await source.LoadAsync(bed.Ct);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
@@ -181,7 +215,7 @@ public sealed class ServerHomeTests(TestContext context)
// In step with the server: the render names the version it holds, whose settings the server renders.
Assert.True(await menu.ReadyToRenderAsync(), "nothing to send");
Assert.Empty(ui.Confirmations);
var basis = host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!;
var basis = host.Find(projectId)!.ReadBundle().Workspace!.Base!;
var (held, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Equal<(Guid?, Guid?, string?)>((projectId, basis.VersionId, null), (held.ProjectId, held.ProjectVersionId, held.SettingsJson));
@@ -198,7 +232,7 @@ public sealed class ServerHomeTests(TestContext context)
ui.ConfirmAnswer = true;
Assert.True(await menu.ReadyToRenderAsync(), "saved and sent: the server holds it");
Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
var sent = host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!;
var sent = host.Find(projectId)!.ReadBundle().Workspace!.Base!;
Assert.NotEqual(basis.VersionId, sent.VersionId);
var (version, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Equal<(Guid?, string?)>((sent.VersionId, null), (version.ProjectVersionId, version.SettingsJson));
@@ -219,8 +253,8 @@ public sealed class ServerHomeTests(TestContext context)
// Another PC sends a version and the server says so: the chip reads Server newer at once.
var other = bed.Host(name: "other-pc");
await bed.CheckoutAsync(other);
var theirs = await other.Sync.OpenAsync(projectId, bed.Ct);
await other.Sync.SaveAsync(projectId, theirs.Working with { Exposure = theirs.Working.Exposure with { ExposureOffsetEv = 0.7 } }, bed.Ct);
var theirs = await other.SyncOf(projectId).OpenAsync(projectId, bed.Ct);
await other.SyncOf(projectId).SaveAsync(projectId, theirs.Working with { Exposure = theirs.Working.Exposure with { ExposureOffsetEv = 0.7 } }, bed.Ct);
var stored = (await other.SaveVersionAsync(projectId, null, bed.Ct)).Version!;
host.OnServerProjectChanged(Server, new ProjectChangedEvent(bed.SequenceId, projectId, ProjectChanges.Pushed, stored.Number, stored.Id));
Assert.Equal(projectId, told.Single().ProjectId);
@@ -240,7 +274,7 @@ public sealed class ServerHomeTests(TestContext context)
Assert.Equal(Loc.L("Editor.Workspace.State.Gone.Server"), menu.StateText);
Assert.False(await menu.ReadyToRenderAsync(), "nothing to render it from");
Assert.True(ui.Toasts[^1].IsError);
Assert.NotNull(host.Store.Find(projectId)?.ReadMedia());
Assert.NotNull(host.Find(projectId)?.ReadMedia());
}
}
@@ -260,7 +294,7 @@ public sealed class ServerHomeTests(TestContext context)
var server = new FakeServer(bed) { SettingsFormat = ProjectSettings.BaseVersion };
Connect(host, server);
var projectId = await CheckoutAsync(bed, host);
var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
var source = new WorkspaceSequenceSource(host.SyncOf(projectId), projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
new WorkspaceServerHome(() => null, () => null));
var content = await source.LoadAsync(bed.Ct);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
@@ -282,9 +316,9 @@ public sealed class ServerHomeTests(TestContext context)
Assert.False(menu.SyncCommand.CanExecute(null));
Assert.False(await menu.ReadyToRenderAsync(), "the server cannot read it");
Assert.Equal((Loc.L("Editor.Workspace.RenderHeld"), true), (ui.Toasts[^1].Title, ui.Toasts[^1].IsError));
var before = host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId;
var before = host.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId;
await menu.SyncAsync();
Assert.Equal(before, host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId, "nothing was sent");
Assert.Equal(before, host.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId, "nothing was sent");
// Saved as a version with the turn, then turned back: the working state is of the base format, but the version
// waiting to be sent is not. Sync stays disabled, and the workspace itself never sends it (Send first, Delete,
@@ -300,7 +334,7 @@ public sealed class ServerHomeTests(TestContext context)
var refused = await Assert.ThrowsAsync<WorkspaceSyncException>(() => host.SyncAsync(projectId, bed.Ct));
Assert.True(refused.HomeReadsOlderFormat);
Assert.Equal(Loc.L("Tooltips.Server.NeedsNewerServer"), WorkspaceText.Failure(refused, server: true));
Assert.Equal(before, host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId, "nothing was sent");
Assert.Equal(before, host.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId, "nothing was sent");
// A server of this format takes it.
server.SettingsFormat = ProjectSettings.CurrentVersion;
@@ -323,7 +357,7 @@ public sealed class ServerHomeTests(TestContext context)
private static async Task<Guid> CheckoutAsync(WorkspaceTestBed bed, WorkspaceHost host)
{
var projectId = await bed.CheckoutAsync(host);
var folder = host.Store.Find(projectId)!;
var folder = host.Find(projectId)!;
var bundle = folder.ReadBundle();
folder.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Home = ServerHome(bed) } });
return projectId;
@@ -36,7 +36,7 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
var host = bed.Host(settings);
var mainId = await bed.CheckoutAsync(host);
settings.WorkspaceOpened[mainId] = DateTimeOffset.UtcNow - 40 * Day;
var project = host.Store.Find(mainId)!;
var project = host.Find(mainId)!;
Assert.True(Directory.Exists(project.ProxiesDirectory), "copied");
// Open in Edit: kept, with why.
@@ -66,7 +66,7 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
Assert.Contains("Workspace: projects cleaned: 1", done.LogTail);
Assert.Contains(Loc.L("Jobs.Log.WorkspaceTrash", Formatting.Count(0), Formatting.Bytes(0)), done.LogTail);
Assert.False(Directory.Exists(project.ProxiesDirectory), "the media went");
Assert.True(host.Store.Find(mainId) is not null && File.Exists(project.BundlePath), "the copy and its work stay");
Assert.True(host.Find(mainId) is not null && File.Exists(project.BundlePath), "the copy and its work stay");
Assert.False((await host.FindAsync(mainId))!.HasMedia, "opening it copies the media again");
}
@@ -76,7 +76,7 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var mainId = await bed.CheckoutAsync(host);
var project = host.Store.Find(mainId)!;
var project = host.Find(mainId)!;
Directory.CreateDirectory(project.ExportsDirectory);
File.WriteAllText(project.ExportFile("clip.mp4"), "rendered");
project.WriteRenders(WorkspaceRenders.Empty.With(new WorkspaceRenderEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), "clip.mp4", new string('a', 64), 8,
@@ -90,7 +90,7 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.RemoveLocalCopyAsync(mainId, discard: false));
Assert.Equal(Loc.L("Errors.Workspace.UnsentRenders"), refused.Message);
Assert.NotNull(host.Store.Find(mainId), "nothing was removed");
Assert.NotNull(host.Find(mainId), "nothing was removed");
var sends = (await bed.Db.Jobs.ListAsync(null, JobKind.WorkspaceSend, cancellationToken: bed.Ct)).Items;
var send = Assert.Contains(sends, j => j.TargetIds.Contains(bed.SequenceId));
Assert.Equal(mainId, WorkspaceJobs.SendParameters(send)!.ProjectId);
@@ -102,7 +102,7 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 2);
var host = bed.Host();
Assert.True((await host.PlanTrashAsync()).IsEmpty, "no trash yet");
var folder = WorkspaceTrash.FolderOf(host.Root);
var folder = WorkspaceTrash.FolderOf(host.Homes.Local.Root);
foreach (var name in new[] { "a", "b" })
{
var entry = Directory.CreateDirectory(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + "-" + DateTime.UtcNow.Ticks)).FullName;
@@ -50,7 +50,7 @@ public sealed class WorkspaceEditorTests(TestContext context)
Assert.True(session.Edit(p => Exposure(p, 0.4)));
Assert.True(await session.FlushAsync());
var folder = host.Store.Find(projectId)!;
var folder = host.Find(projectId)!;
Assert.Equal(0.4, folder.ReadBundle().Project.Exposure.ExposureOffsetEv);
Assert.Equal(libraryBefore, (await bed.RowAsync()).SettingsJson, "editing never writes the library");
Assert.Equal(WorkspaceState.Modified, (await host.StatusAsync(projectId)).State);
@@ -72,12 +72,12 @@ public sealed class WorkspaceEditorTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 3);
var host = bed.Host();
var projectId = await bed.CheckoutAsync(host);
var impatient = new WorkspaceSync(host.Store, "Chronos test") { LockWait = TimeSpan.FromMilliseconds(200) };
var impatient = new WorkspaceSync(host.Find(projectId)!.Store, "Chronos test") { LockWait = TimeSpan.FromMilliseconds(200) };
var source = new WorkspaceSequenceSource(impatient, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine);
await using (source)
{
// A long sync or copy holds the project: the editor says so in words, and nothing was read.
using (await host.Store.Find(projectId)!.LockAsync(TimeSpan.FromSeconds(TestTiming.Budget(5)), bed.Ct))
using (await host.Find(projectId)!.LockAsync(TimeSpan.FromSeconds(TestTiming.Budget(5)), bed.Ct))
{
var busy = await Assert.ThrowsAsync<EditorException>(() => source.LoadAsync(bed.Ct));
Assert.Equal(Loc.L("Errors.Workspace.Busy"), busy.Message);
@@ -328,7 +328,7 @@ public sealed class WorkspaceEditorTests(TestContext context)
Assert.Equal(excluded, session.Content.Frames[3].Id);
Assert.True(session.Edit(p => Exposure(p, 0.2)));
Assert.True(await session.FlushAsync(), "saves go on over the new frames");
Assert.SequenceEqual([3], host.Store.Find(projectId)!.ReadBundle().Project.ExcludedFrames);
Assert.SequenceEqual([3], host.Find(projectId)!.ReadBundle().Project.ExcludedFrames);
}
}
}
@@ -62,7 +62,7 @@ public sealed class WorkspaceFallbackTests(TestContext context)
Assert.Equal((Path.GetFullPath(other), before + 1), (settings.WorkspaceFolder, saves));
Assert.Equal(Path.GetFullPath(other), host.Root);
Assert.Empty(await host.ListAsync());
Assert.FileExists(Path.Combine(first, mainId.ToString("N"), WorkspaceProject.BundleFile));
Assert.FileExists(Path.Combine(first, "local", mainId.ToString("N"), WorkspaceProject.BundleFile));
// Chosen back, the default is named by no setting and its project is listed again.
Assert.Equal(new WorkspaceFolderPlan(Path.GetFullPath(other), first, 0, 1, false), await host.PlanFolderAsync(first));
@@ -155,7 +155,7 @@ public sealed class WorkspaceFallbackTests(TestContext context)
Assert.True(await session.FlushAsync());
}
var unsent = (await host.SaveVersionAsync(mainId, "Not sent")).Version!;
var project = host.Store.Find(mainId)!;
var project = host.Find(mainId)!;
await File.WriteAllTextAsync(project.BundlePath, "{ this is not a project", bed.Ct);
// A file this Chronos does not know (a newer one's, the user's own): Discard keeps it too.
await File.WriteAllTextAsync(Path.Combine(project.Folder, "notes.txt"), "kept", bed.Ct);
@@ -195,11 +195,11 @@ public sealed class WorkspaceFallbackTests(TestContext context)
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.RemoveLocalCopyAsync(mainId, discard: false));
Assert.Equal(Loc.L("Errors.Workspace.Damaged"), refused.Message);
Assert.NotNull(host.Store.Find(mainId), "nothing was removed");
Assert.NotNull(host.Find(mainId), "nothing was removed");
await host.RemoveLocalCopyAsync(mainId, discard: true);
Assert.Null(host.Store.Find(mainId));
var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(host.Root, WorkspaceHost.TrashFolder)),
Assert.Null(host.Find(mainId));
var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(host.Homes.LocalRoot, WorkspaceHost.TrashFolder)),
d => Path.GetFileName(d).StartsWith(mainId.ToString("N"), StringComparison.Ordinal));
Assert.Equal("{ this is not a project", await File.ReadAllTextAsync(Path.Combine(aside, WorkspaceProject.BundleFile), bed.Ct), "kept as it was");
Assert.Equal("kept", await File.ReadAllTextAsync(Path.Combine(aside, "notes.txt"), bed.Ct), "every file of the folder is kept, not only the known ones");
@@ -215,7 +215,7 @@ public sealed class WorkspaceFallbackTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var mainId = await bed.CheckoutAsync(host);
var project = host.Store.Find(mainId)!;
var project = host.Find(mainId)!;
// A newer Chronos on this PC rewrote the working state in a format this one does not know (a downgrade since).
var json = System.Text.Json.Nodes.JsonNode.Parse(await File.ReadAllTextAsync(project.BundlePath, bed.Ct))!.AsObject();
json["formatVersion"] = ProjectBundle.CurrentFormatVersion + 1;
@@ -330,7 +330,7 @@ public sealed class WorkspaceFallbackTests(TestContext context)
await host.SaveVersionAsync(mainId, $"Step {i}");
}
}
var project = host.Store.Find(mainId)!;
var project = host.Find(mainId)!;
Assert.SequenceEqual([1, 2, 3, 4, 5, 6], project.Versions().Where(v => v.StoredAt is not null).Select(v => v.Number).Order());
// The library's file of version 2 is damaged: the workspace's copy is the only good one left, so it stays.
@@ -43,7 +43,7 @@ public sealed class WorkspaceHostTests(TestContext context)
var elsewhere = Path.Combine(context.CreateTempDirectory("fast-disk"), "Chronos workspace");
settings.WorkspaceFolder = elsewhere;
Assert.Equal(elsewhere, host.Root);
Assert.Equal(elsewhere, host.Store.Root, "the store follows the folder");
Assert.Equal(elsewhere, host.Homes.Root, "the homes follow the folder");
Assert.FileExists(Path.Combine(elsewhere, WorkspaceStore.ManifestFile));
// A capture (sample data without an engine) edits its library as before.
@@ -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()
{
@@ -142,6 +161,60 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.Count(1, imported.WorkspaceOpened);
}
[Test]
public void TheKnownServersStayOnThisPc()
{
var id = Guid.CreateVersion7();
var originals = Guid.CreateVersion7();
var mine = new AppSettings
{
KnownServers = [new KnownServer { Id = id, Name = "Studio NAS", LastAddress = "https://nas.local:8443", Aliases = ["https://nas.local:8443"], OriginalsArchiveId = originals }],
};
var copy = AppSettings.Parse(mine.ToJson())!;
Assert.Equal(("Studio NAS", originals, "https://nas.local:8443"), (copy.KnownServers.Single().Name, copy.KnownServers.Single().OriginalsArchiveId, copy.KnownServers.Single().Aliases.Single()));
Assert.Equal(id, copy.FindKnownServer(id)?.Id);
Assert.True(copy.KnownIdentity().Same("https://nas.local:8443", Chronos.Core.IO.HomeFolders.IdKey(id)), "an alias names the server by its id");
// Reset and Import keep what this PC knows of its servers; Export leaves it out.
Assert.Equal(id, mine.ResetKeepingState().KnownServers.Single().Id);
Assert.Empty(AppSettings.Parse(mine.ForExport().ToJson())!.KnownServers);
Assert.Equal(id, mine.KeepLocalIn(AppSettings.Parse(new AppSettings().ToJson())!).KnownServers.Single().Id);
}
[Test]
public async Task TheTrashOfEveryHomeIsPlannedAndEmptiedTogether()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 2);
var host = bed.Host(name: "homes");
var homes = host.Homes;
Assert.True(homes.IsSplit, "a new workspace is split into homes");
var server = homes.StoreFor(new BundleHome(BundleHome.ServerKind, Guid.CreateVersion7(), null, "https://nas.test:8443")).Root;
foreach (var (root, name) in new[] { (homes.Local.Root, "a"), (server, "b") })
{
var entry = Directory.CreateDirectory(Path.Combine(WorkspaceTrash.FolderOf(root), $"{Guid.CreateVersion7():N}-{name}"));
File.WriteAllBytes(Path.Combine(entry.FullName, "file.bin"), new byte[100]);
}
// Settings › Workspace › Home folders: this PC first, then the server by what its folder records.
var rows = HomeFolderRow.Of(homes, [], _ => { });
Assert.SequenceEqual([Loc.L("Settings.Workspace.ThisPc"), "https://nas.test:8443"], rows.Select(r => r.Name).ToArray());
Assert.Equal(server, rows[1].Path);
var usage = await host.UsageAsync(bed.Ct);
Assert.Equal((2, 200L), (usage.TrashItems, usage.TrashBytes));
var plan = await host.PlanTrashAsync(bed.Ct);
Assert.Equal((2, 200L, 2), (plan.Items.Count, plan.Bytes, plan.Listings.Count));
// One home's trash changed since the plan: nothing is erased, in either.
File.WriteAllBytes(Path.Combine(WorkspaceTrash.FolderOf(server), "late.bin"), new byte[5]);
await Assert.ThrowsAsync<WorkspaceException>(() => host.EmptyTrashAsync(plan, bed.Ct));
Assert.Equal(3, (await host.UsageAsync(bed.Ct)).TrashItems, "nothing was erased");
var again = await host.PlanTrashAsync(bed.Ct);
Assert.Equal(new WorkspaceTrashResult(3, 205), await host.EmptyTrashAsync(again, bed.Ct));
Assert.Equal(0, (await host.UsageAsync(bed.Ct)).TrashItems);
}
[Test]
public void OpeningAProjectRecordsWhenAndSavesIt()
{
@@ -309,7 +382,7 @@ public sealed class WorkspaceHostTests(TestContext context)
var verticalId2 = (await host.HomeProjectsAsync(bed.SequenceId)).Single(p => !p.IsMain).Id;
await bed.CheckoutAsync(host, verticalId2);
Assert.Equal("Vertical", await host.RenameAsync(verticalId2, " Vertical "));
Assert.Equal("Vertical", host.Store.Find(verticalId2)!.ReadBundle().Workspace!.Name);
Assert.Equal("Vertical", host.Find(verticalId2)!.ReadBundle().Workspace!.Name);
Assert.Contains((await host.HomeProjectsAsync(bed.SequenceId)), p => p.Name == "Vertical");
// Delete project…: confirmed, sent first, then gone from the library's list and from the workspace (kept in the library's trash).
@@ -329,7 +402,7 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.Equal(1, deleting.Closed);
}
Assert.DoesNotContain(verticalId2, (await host.HomeProjectsAsync(bed.SequenceId)).Select(p => p.Id));
Assert.Null(host.Store.Find(verticalId2));
Assert.Null(host.Find(verticalId2));
var row = await bed.RowAsync();
var trash = Path.Combine(new Chronos.Core.Archiving.ArchivePaths((await bed.Db.Archives.GetAsync(row.ArchiveId))!.RootPath).Sequence(row.Folder).ProjectsTrashDirectory);
Assert.True(Directory.EnumerateDirectories(trash).Any(d => Path.GetFileName(d).StartsWith(verticalId2.ToString("N"), StringComparison.Ordinal)),
@@ -375,15 +448,15 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.True(request is { IsDestructive: true, TypedConfirmation: "Main" } && request.TypedPrompt is { Length: > 0 });
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.RemoveLocalCopyAsync(mainId, discard: false));
Assert.Equal(Loc.L("Errors.Workspace.Unsent"), refused.Message);
Assert.NotNull(host.Store.Find(mainId), "nothing was removed");
Assert.NotNull(host.Find(mainId), "nothing was removed");
// Send first: saved and sent, then the library's copy is read back and checked before the local one goes.
await host.SaveVersionAsync(mainId, "Before removal");
await host.SyncAsync(mainId);
Assert.True((await host.PlanRemovalAsync(mainId)).IsSafe);
var folder = host.Store.Find(mainId)!.Folder;
var folder = host.Find(mainId)!.Folder;
await host.RemoveLocalCopyAsync(mainId, discard: false);
Assert.Null(host.Store.Find(mainId));
Assert.Null(host.Find(mainId));
Assert.False(Directory.Exists(Path.Combine(folder, WorkspaceProject.MediaFolder)), "the copied photos are gone");
Assert.Equal(0.3, ProjectSettings.FromJson((await bed.RowAsync()).SettingsJson!).Exposure.ExposureOffsetEv, "the work is in the library");
@@ -397,14 +470,14 @@ public sealed class WorkspaceHostTests(TestContext context)
}
var unsent = (await host.SaveVersionAsync(vertical, "Not sent")).Version!;
await host.RemoveLocalCopyAsync(vertical, discard: true);
Assert.Null(host.Store.Find(vertical));
var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(host.Root, WorkspaceHost.TrashFolder)),
Assert.Null(host.Find(vertical));
var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(host.Homes.LocalRoot, WorkspaceHost.TrashFolder)),
d => Path.GetFileName(d).StartsWith(vertical.ToString("N"), StringComparison.Ordinal));
Assert.FileExists(Path.Combine(aside, WorkspaceProject.BundleFile));
Assert.True(Directory.EnumerateFiles(Path.Combine(aside, WorkspaceProject.VersionsFolder)).Any(f => f.Contains(unsent.Id.ToString("N"), StringComparison.OrdinalIgnoreCase)
|| f.Contains(unsent.Id.ToString(), StringComparison.OrdinalIgnoreCase)), "the version never sent is kept");
Assert.False(Directory.Exists(Path.Combine(aside, WorkspaceProject.MediaFolder)), "the photos, copies the library can make again, are not");
Assert.Empty(host.Store.List());
Assert.Empty(host.Homes.List());
}
[Test]
@@ -413,7 +486,7 @@ public sealed class WorkspaceHostTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var mainId = await bed.CheckoutAsync(host);
var project = host.Store.Find(mainId)!;
var project = host.Find(mainId)!;
var basis = project.ReadBundle().Workspace!.Base!;
var conflict = $$"""
"conflict": { "theirsVersionId": "{{basis.VersionId}}", "theirsNumber": {{basis.Number}}, "baseVersionId": "{{Guid.CreateVersion7()}}",
@@ -449,9 +522,9 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.True((await host.PlanRemovalAsync(vertical)).Gone);
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.RemoveLocalCopyAsync(vertical, discard: false));
Assert.Equal(Loc.L("Errors.Workspace.DeletedAtHome"), refused.Message);
Assert.NotNull(host.Store.Find(vertical), "nothing was removed");
Assert.NotNull(host.Find(vertical), "nothing was removed");
await host.RemoveLocalCopyAsync(vertical, discard: true);
Assert.Null(host.Store.Find(vertical));
Assert.Null(host.Find(vertical));
}
[Test]
@@ -460,7 +533,7 @@ public sealed class WorkspaceHostTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var vertical = await bed.CheckoutAsync(host, newName: "Vertical");
var project = host.Store.Find(vertical)!;
var project = host.Find(vertical)!;
var bundle = File.ReadAllBytes(project.BundlePath);
var held = Path.Combine(project.Folder, "notes.txt");
File.WriteAllText(held, "mine");
@@ -471,13 +544,13 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.SequenceEqual(bundle, File.ReadAllBytes(project.BundlePath), "the working state is back");
Assert.Contains(await host.ListAsync(), e => e.ProjectId == vertical && e.IsReadable);
Assert.True(Directory.Exists(project.MediaDirectory) && Directory.Exists(project.VersionsDirectory), "the copy is whole");
var trash = Path.Combine(host.Root, WorkspaceHost.TrashFolder);
var trash = Path.Combine(host.Homes.LocalRoot, WorkspaceHost.TrashFolder);
Assert.False(Directory.Exists(trash) && Directory.EnumerateDirectories(trash).Any(d => Path.GetFileName(d).StartsWith(vertical.ToString("N"), StringComparison.Ordinal)),
"nothing is left aside");
// The file let go: removed.
await host.RemoveLocalCopyAsync(vertical, discard: true);
Assert.Null(host.Store.Find(vertical));
Assert.Null(host.Find(vertical));
}
[Test]
@@ -496,7 +569,7 @@ public sealed class WorkspaceHostTests(TestContext context)
await host.SaveVersionAsync(mainId, $"Step {i}");
}
}
var project = host.Store.Find(mainId)!;
var project = host.Find(mainId)!;
var kept = project.Versions().Where(v => v.StoredAt is not null).Select(v => v.Number).Order().ToList();
Assert.SequenceEqual([5, 6], kept, "the base and the one before it");
var history = await host.HistoryAsync(mainId);
@@ -44,13 +44,13 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
await bed.WaitForJobAsync(checkout.Copy.Id);
var projectId = checkout.Project.Id;
// Named the server's, as a copy downloaded from the server leaves it.
var folder = host.Store.Find(projectId)!;
var folder = host.Find(projectId)!;
var bundle = folder.ReadBundle();
var home = new BundleHome(BundleHome.ServerKind, bed.SequenceId, null, Server);
folder.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Home = home } });
// Not signed in to the server: a render from the originals runs here all the same.
var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
var source = new WorkspaceSequenceSource(host.SyncOf(projectId), projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
new WorkspaceServerHome((IRemoteSequenceApi?)null));
var content = await source.LoadAsync(bed.Ct);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
@@ -62,7 +62,7 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
Assert.Equal(JobKind.WorkspaceRender, request.Kind);
Assert.SequenceEqual([bed.SequenceId], request.Targets);
var parameters = Assert.NotNull(WorkspaceJobs.RenderParameters(new Job { Id = Guid.CreateVersion7(), Kind = request.Kind, ParametersJson = request.ParametersJson }));
Assert.Equal((projectId, host.Store.Root, Server), (parameters.ProjectId, parameters.WorkspaceRoot, parameters.Server));
Assert.Equal((projectId, host.Find(projectId)!.Store.Root, Server), (parameters.ProjectId, parameters.WorkspaceRoot, parameters.Server));
var (render, _) = ProcessingJobs.ReadRender(parameters.RenderJson);
Assert.NotNull(render.SettingsJson, "the portable settings travel with the job");
@@ -108,7 +108,7 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
var checkout = await host.CheckoutAsync(bed.SequenceId, null, null, BundleMedia.Originals, cancellationToken: bed.Ct);
await bed.WaitForJobAsync(checkout.Copy.Id);
var projectId = checkout.Project.Id;
var folder = host.Store.Find(projectId)!;
var folder = host.Find(projectId)!;
var (source, session) = await bed.OpenAsync(host, projectId);
var ui = new RecordingUi { ConfirmAnswer = false };
await using (session)
@@ -155,7 +155,7 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 2);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var projectId = await bed.CheckoutAsync(host);
var folder = host.Store.Find(projectId)!;
var folder = host.Find(projectId)!;
Assert.False(await host.SendRendersAsync(projectId, bed.Ct), "nothing waits to be sent");
Assert.False(await host.RenderSendPendingAsync(projectId, bed.SequenceId, bed.Ct));
@@ -171,7 +171,7 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
var sends = (await bed.Db.Jobs.ListAsync(null, 50, null, bed.Ct)).Items.Where(j => j.Kind == JobKind.WorkspaceSend).ToList();
Assert.Equal(1, sends.Count);
var parameters = Assert.NotNull(WorkspaceJobs.SendParameters(sends[0]));
Assert.Equal((projectId, host.Store.Root), (parameters.ProjectId, parameters.WorkspaceRoot));
Assert.Equal((projectId, host.Find(projectId)!.Store.Root), (parameters.ProjectId, parameters.WorkspaceRoot));
Assert.Empty(parameters.RenderIds);
}
@@ -189,7 +189,7 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
{
await menu.RefreshAsync();
var folder = host.Store.Find(projectId)!;
var folder = host.Find(projectId)!;
var before = folder.Versions().Count;
// Nothing changed: nothing saved.
@@ -35,7 +35,7 @@ public sealed class WorkspaceMenuTests(TestContext context)
session.ConflictFound += conflicts.Add;
await using (session)
{
var folder = host.Store.Find(projectId)!;
var folder = host.Find(projectId)!;
// A sync wrote another PC's exclusion of frame 5 while the editor's exclusion of frame 2 waited for its save.
var stored = folder.ReadBundle();
folder.WriteBundle(stored with { Project = stored.Project with { ExcludedFrames = [5] } });
@@ -102,7 +102,7 @@ public sealed class WorkspaceMenuTests(TestContext context)
Assert.True(sessionB.Undo());
Assert.Equal((0.7, 0.2), (sessionB.Project.Exposure.ExposureOffsetEv, sessionB.Project.Camera.OffsetY));
Assert.True(await sessionB.FlushAsync());
var working = here.Store.Find(mainId)!.ReadBundle().Project;
var working = here.Find(mainId)!.ReadBundle().Project;
Assert.Equal((0.7, 0.2), (working.Exposure.ExposureOffsetEv, working.Camera.OffsetY), "the values brought back are stored");
}
}
@@ -172,7 +172,7 @@ public sealed class WorkspaceMenuTests(TestContext context)
removing.SendFirstCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => uiB.Open is ConflictDialogViewModel, "the conflict is asked, not hidden behind Discard");
Assert.Equal(0, uiB.Closed, "the editor stays open");
Assert.NotNull(here.Store.Find(mainId), "nothing was removed");
Assert.NotNull(here.Find(mainId), "nothing was removed");
}
}
@@ -211,7 +211,7 @@ public sealed class WorkspaceMenuTests(TestContext context)
Assert.Equal(b.Name, copy.Message, "the copy Save both made is offered");
Assert.False(b.SaveVersionCommand.CanExecute(null), "nothing can be sent to it");
Assert.Equal(0.7, sessionB.Project.Exposure.ExposureOffsetEv, "the work stays in the editor");
Assert.Equal(0.7, here.Store.Find(sideId)!.ReadBundle().Project.Exposure.ExposureOffsetEv);
Assert.Equal(0.7, here.Find(sideId)!.ReadBundle().Project.Exposure.ExposureOffsetEv);
}
}
@@ -254,7 +254,7 @@ public sealed class WorkspaceMenuTests(TestContext context)
await using (session)
{
Assert.False(session.IsReadOnly);
var folder = host.Store.Find(projectId)!;
var folder = host.Find(projectId)!;
var stored = folder.ReadBundle();
folder.WriteBundle(stored with { Project = stored.Project with { Version = ProjectSettings.CurrentVersion + 1 } });
await session.ReloadAsync();
@@ -32,7 +32,7 @@ public sealed class WorkspaceNewerFormatTests(TestContext context)
Assert.True(session.History.CanUndo);
// A pull with nothing of this PC's waiting moved the working state onto a newer Chronos's settings.
var folder = host.Store.Find(projectId)!;
var folder = host.Find(projectId)!;
var stored = folder.ReadBundle();
folder.WriteBundle(stored with { Project = Exposure(stored.Project, 1.5) with { Version = ProjectSettings.CurrentVersion + 1 } });
await session.ReloadAsync();
@@ -64,7 +64,7 @@ public sealed class WorkspaceNewerFormatTests(TestContext context)
Assert.True(session.Edit(p => Exposure(p, 0.4)));
Assert.True(await session.FlushAsync());
Assert.NotNull(await host.CommitAsync(projectId, bed.Ct));
var folder = host.Store.Find(projectId)!;
var folder = host.Find(projectId)!;
var stored = folder.ReadBundle();
// A sync took a newer Chronos's settings while one more edit waited for its save (made during the sync).
folder.WriteBundle(stored with { Project = Exposure(stored.Project, 1.5) with { Version = ProjectSettings.CurrentVersion + 1 } });
@@ -86,7 +86,7 @@ public sealed class WorkspaceNewerFormatTests(TestContext context)
Assert.Equal(0.4, placed.Exposure.ExposureOffsetEv);
Assert.SequenceEqual([2], placed.ExcludedFrames, "the edit as it was, by photo");
Assert.False(folder.Versions().Any(v => v.Id == aside.Id), "outside the chain: never sent");
Assert.Empty(host.Sync.Unpushed(projectId).Where(v => v.Id == aside.Id));
Assert.Empty(host.SyncOf(projectId).Unpushed(projectId).Where(v => v.Id == aside.Id));
// Read again: no throw, nothing more kept aside, the editor as it is.
await session.ReloadAsync();
@@ -97,7 +97,7 @@ public sealed class WorkspaceOpenPolicyTests(TestContext context)
var mainId = section.OpenProjectId!.Value;
var menu = Assert.NotNull(section.Editor!.Project);
Assert.True(menu.HoldsOriginals);
var media = services.Workspace.Store.Find(mainId)!.ReadMedia()!;
var media = services.Workspace.Find(mainId)!.ReadMedia()!;
Assert.True(media.HoldsOriginals && media.Frames.All(f => f.HasOriginal), "every frame has its original");
Assert.True(settings.WorkspaceOpened.ContainsKey(mainId), "the open is recorded for the clean-up");
Assert.True(await section.ConfirmCloseAsync());
@@ -65,7 +65,7 @@ public sealed class WorkspaceSectionTests(TestContext context)
await WorkspaceTestBed.UntilAsync(() => project.Status is not null, "its state is read");
Assert.Equal(WorkspaceState.InSync, project.Status!.State);
Assert.Equal(section.OpenProjectId!.Value, settings.WorkspaceRecent[sequenceId]);
Assert.True(File.Exists(Path.Combine(WorkspaceHost.DefaultRoot(environment), section.OpenProjectId.Value.ToString("N"), WorkspaceProject.BundleFile)),
Assert.True(File.Exists(Path.Combine(WorkspaceHost.DefaultRoot(environment), "local", section.OpenProjectId.Value.ToString("N"), WorkspaceProject.BundleFile)),
"the project lives in the workspace beside the index");
// Edited in the workspace; the library takes it with the version saved.
@@ -231,7 +231,7 @@ public sealed class WorkspaceSectionTests(TestContext context)
Assert.True(await section.ConfirmCloseAsync());
await section.CloseAsync();
shell.KeepSequence(null);
var folder = Path.Combine(services.Workspace.Root, mainId.ToString("N"));
var folder = Path.Combine(services.Workspace.Homes.LocalRoot, mainId.ToString("N"));
var bundle = Path.Combine(folder, WorkspaceProject.BundleFile);
// Saved by a newer Chronos: said at once, nothing offered over it, nothing asked.
@@ -298,7 +298,7 @@ public sealed class WorkspaceSectionTests(TestContext context)
await section.CloseAsync();
shell.KeepSequence(null);
var vertical = (await services.Archives!.Projects.CreateAsync(sequenceId, "Vertical", cancellationToken: context.Cancellation)).Id;
var bundle = Path.Combine(services.Workspace.Root, mainId.ToString("N"), WorkspaceProject.BundleFile);
var bundle = Path.Combine(services.Workspace.Homes.LocalRoot, mainId.ToString("N"), WorkspaceProject.BundleFile);
// Damaged: the sequence has another project, so it is asked which; Main is listed, disabled, why in its tooltip.
await WriteWhenFreeAsync(bundle, "{ not a project");
@@ -120,7 +120,7 @@ internal sealed class WorkspaceTestBed : IAsyncDisposable
/// <summary>The project open in an editor session over the workspace (saves 20 ms after each edit).</summary>
public async Task<(WorkspaceSequenceSource Source, EditorSession Session)> OpenAsync(WorkspaceHost host, Guid projectId)
{
var source = new WorkspaceSequenceSource(host.Sync, projectId, Db, DecoderFactory.CreateClient(null), Engine);
var source = new WorkspaceSequenceSource(host.SyncOf(projectId), projectId, Db, DecoderFactory.CreateClient(null), Engine);
var content = await source.LoadAsync(Ct);
return (source, new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20)));
}
@@ -0,0 +1,90 @@
using System.Security.Cryptography;
using System.Text;
using Chronos.Core.IO;
using Chronos.Testing;
namespace Chronos.Core.Tests.Foundation;
/// <summary>The folders of the homes (owner review 5, #66): this PC's, a server's by id, a server's by address hash.</summary>
public sealed class HomeFoldersTests(TestContext context)
{
private static readonly Guid ServerId = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
[Test]
public void AnIdKeyNamesItsFolderByTheId()
{
var key = HomeFolders.IdKey(ServerId);
Assert.Equal("id:0192a4c17b3e7cc08a512f9d0e6b1a01", key);
Assert.Equal("0192a4c17b3e7cc08a512f9d0e6b1a01", HomeFolders.ServerFolder(key));
Assert.Equal(ServerId, HomeFolders.IdOfKey(key));
Assert.Equal(ServerId, HomeFolders.IdOfKey("ID:0192A4C17B3E7CC08A512F9D0E6B1A01"));
Assert.Equal(ServerId, HomeFolders.IdOfFolder(HomeFolders.ServerFolder(key)));
Assert.Throws<ArgumentException>(() => HomeFolders.IdKey(Guid.Empty));
}
[Test]
public void AnAddressKeyNamesItsFolderAsTheProxyCacheOf10Did()
{
const string key = "https://nas.local:8443";
// ProxyCache 1.0: Convert.ToHexStringLower(SHA256(UTF-8 key))[..16].
var hash = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(key)))[..16];
Assert.Equal(hash, HomeFolders.AddressHash(key));
Assert.Equal("addr-" + hash, HomeFolders.ServerFolder(key));
Assert.Null(HomeFolders.IdOfKey(key));
Assert.True(HomeFolders.IsAddressFolder("addr-" + hash));
Assert.True(HomeFolders.IsServerFolder("addr-" + hash));
Assert.Null(HomeFolders.IdOfFolder("addr-" + hash));
// "id:" with no id after it is an address key like any other.
Assert.Equal("addr-" + HomeFolders.AddressHash("id:nothing"), HomeFolders.ServerFolder("id:nothing"));
}
[Test]
public void OnlyAHomeFolderNameIsAServerHome()
{
Assert.True(HomeFolders.IsServerFolder(ServerId.ToString("N")));
foreach (var name in new[] { null, "", "local", "servers", ".trash", ServerId.ToString("N").ToUpperInvariant(), ServerId.ToString("D"), "addr-", "addr-0123",
"addr-0123456789ABCDEF", "addr-0123456789abcdefa", "xaddr-0123456789abcdef", Guid.Empty.ToString("N") })
Assert.False(HomeFolders.IsServerFolder(name), name ?? "null");
}
[Test]
public void HomePathsLieUnderTheirRoot()
{
var root = context.CreateTempDirectory("homes");
Assert.Equal(Path.Combine(root, "local"), HomeFolders.LocalPath(root));
Assert.Equal(Path.Combine(root, "servers", ServerId.ToString("N")), HomeFolders.ServerPath(root, HomeFolders.IdKey(ServerId)));
Assert.Equal(Path.Combine(root, "servers", "addr-" + HomeFolders.AddressHash("https://x")), HomeFolders.ServerPath(root, "https://x"));
}
[Test]
public void TheOriginalsOfAServerGetAnArchiveBesideThisPcs()
{
var parent = context.CreateTempDirectory("originals");
var archive = Path.Combine(parent, "ChronosArchive");
Directory.CreateDirectory(archive);
Assert.Equal(Path.Combine(parent, "ChronosArchive - Studio NAS"), HomeFolders.OriginalsArchiveRoot(archive, "Studio NAS", Path.Combine(parent, "fallback")));
// Taken: " (2)"; a name Windows refuses is made safe.
Directory.CreateDirectory(Path.Combine(parent, "ChronosArchive - Studio NAS"));
Assert.Equal(Path.Combine(parent, "ChronosArchive - Studio NAS (2)"), HomeFolders.OriginalsArchiveRoot(archive + Path.DirectorySeparatorChar, "Studio NAS", "unused"));
Assert.Equal(Path.Combine(parent, "ChronosArchive - A B C"), HomeFolders.OriginalsArchiveRoot(archive, "A:B/C", "unused"));
Assert.Equal(Path.Combine(parent, "ChronosArchive - Taken (3)"),
HomeFolders.OriginalsArchiveRoot(archive, "Taken", "unused", path => !path.EndsWith("(3)", StringComparison.Ordinal)));
// No archive of this PC's: beside where its first one would go.
var fallback = Path.Combine(parent, "Pictures", "ChronosArchive");
Assert.Equal(Path.Combine(parent, "Pictures", "ChronosArchive - NAS"), HomeFolders.OriginalsArchiveRoot(null, "NAS", fallback));
}
[Test]
public void ASafeNameIsAFolderNameEveryDriveTakes()
{
Assert.Equal("Studio NAS", HomeFolders.SafeName(" Studio \t NAS. "));
Assert.Equal("a b", HomeFolders.SafeName("a<>:\"|?*b"));
Assert.Equal("CON_", HomeFolders.SafeName("con".ToUpperInvariant()));
Assert.Equal("nul.box_", HomeFolders.SafeName("nul.box"));
Assert.Equal("Server", HomeFolders.SafeName("..."));
Assert.Equal("Server", HomeFolders.SafeName(null));
Assert.Equal(HomeFolders.MaxNameLength, HomeFolders.SafeName(new string('x', 200)).Length);
}
}
@@ -1,11 +1,10 @@
using System.Net;
using System.Net.Http;
using System.Text;
using Chronos.App.About;
using Chronos.App.Infrastructure;
using Chronos.Core.Updates;
using Chronos.Testing;
namespace Chronos.App.Tests.About;
namespace Chronos.Core.Tests.Updates;
public sealed class UpdateCheckTests
{
@@ -4,10 +4,10 @@ using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using Chronos.App.About;
using Chronos.Core.Updates;
using Chronos.Testing;
namespace Chronos.App.Tests.About;
namespace Chronos.Core.Tests.Updates;
public sealed class UpdateDownloadTests(TestContext context)
{
@@ -18,11 +18,8 @@ public sealed class AppPathsTests(TestContext context)
Assert.Equal(Path.Combine(app, "data", "chronos.db"), paths.DatabasePath);
Assert.False(paths.IsInSyncedFolder);
Assert.Null(paths.PortableSyncRoot);
paths.CreateDirectories();
Assert.True(Directory.Exists(paths.LogsDirectory));
Assert.True(Directory.Exists(paths.CacheDirectory));
Assert.True(Directory.Exists(paths.ThumbnailsDirectory));
Assert.Equal(Path.Combine(app, "data", "logs"), paths.LogsDirectory);
Assert.Equal(Path.Combine(app, "data", "cache"), paths.CacheDirectory);
}
[Test]
@@ -50,22 +47,19 @@ public sealed class AppPathsTests(TestContext context)
Assert.Equal(Path.Combine(local, "Chronos"), paths.DataRoot);
Assert.Equal<string?>(oneDrive, paths.PortableSyncRoot);
Assert.False(paths.IsInSyncedFolder);
paths.CreateDirectories();
Assert.True(Directory.Exists(paths.LogsDirectory));
Assert.False(Directory.Exists(Path.Combine(app, "data")), "nothing is written into the synchronised folder");
Assert.Equal(Path.Combine(local, "Chronos", "logs"), paths.LogsDirectory);
}
[Test]
public void DataInsideOneDriveIsReportedAndRefused()
public void DataInsideOneDriveIsReported()
{
// Local application data inside a sync root: nowhere is safe, so nothing is created.
// Local application data inside a sync root: nowhere is safe, and the app tells the user.
var oneDrive = context.CreateTempDirectory("onedrive");
var local = Directory.CreateDirectory(Path.Combine(oneDrive, "AppData", "Local")).FullName;
var paths = AppPaths.Resolve(context.CreateTempDirectory("app"), local, [oneDrive]);
Assert.True(paths.IsInSyncedFolder);
Assert.Equal<string?>(oneDrive, paths.SyncedFolder);
Assert.Throws<InvalidOperationException>(paths.CreateDirectories);
Assert.False(Directory.Exists(paths.DataRoot));
}
@@ -0,0 +1,180 @@
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Housekeeping;
using Chronos.Data.Jobs;
using Chronos.Data.Tests.Jobs;
using Chronos.Testing;
using static Chronos.Data.Tests.Archiving.ArchiveFixture;
namespace Chronos.Data.Tests.Archiving;
/// <summary>
/// What the archive jobs say they are doing (owner review 5, #65): the step, the item, photo x of y and sequence, folder
/// or step n of m, sent as the job's progress detail; no localized text in it.
/// </summary>
[Category("archive")]
public sealed class ArchiveProgressDetailTests(TestContext context)
{
private static void Populate(ArchiveFixture fx)
{
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "a"), Start, 4);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "b"), Start.AddDays(1), 3, firstSeed: 50);
}
private static async Task<(DetailRecorder Recorder, JobEngine Engine)> StartAsync(ArchiveFixture fx)
{
var recorder = new DetailRecorder();
var engine = recorder.Engine(fx.Db, fx.Service.CreateJobHandlers());
await engine.StartAsync(fx.Ct);
return (recorder, engine);
}
private static async Task<Guid> RunAsync(ArchiveFixture fx, JobEngine engine, ArchiveJobRequest request)
{
var job = await engine.EnqueueAsync(request, cancellationToken: fx.Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
return job.Id;
}
[Test]
public async Task AScanListsThenIndexesEachNewFolderPhotoByPhotoAndChecksThemOnARescan()
{
await using var fx = await CreateAsync(context);
Populate(fx);
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var first = await RunAsync(fx, engine, ArchiveJobs.Scan(fx.Archive));
var details = recorder.Details(first);
Assert.Equal(JobStep.List, details[0].Step);
var index = details.Where(d => d.Step == JobStep.Index).ToList();
Assert.Equal(new JobDetail(JobStep.Index, "a", 0, 0, 1, 2, JobPartUnit.Folder), index[0]);
// Photo after photo inside an adopted folder, then the next folder.
Assert.SequenceEqual([1L, 2L, 3L, 4L], index.Where(d => d.Item == "a" && d.ItemTotal > 0).Select(d => d.ItemDone));
Assert.True(index.Where(d => d.ItemTotal > 0).All(d => d.ItemTotal == (d.Item == "a" ? 4 : 3)));
Assert.SequenceEqual([1, 2], index.Select(d => d.Part).Distinct());
Assert.True(index.All(d => d.Parts == 2 && d.PartUnit == JobPartUnit.Folder));
Assert.Equal(JobStep.Index, recorder.Steps(first)[1]);
// Nothing changed: each folder is checked, folder n of m, and nothing is indexed.
var again = await RunAsync(fx, engine, ArchiveJobs.Scan(fx.Archive));
Assert.SequenceEqual([JobStep.List, JobStep.Check], recorder.Steps(again));
var check = recorder.Details(again).Where(d => d.Step == JobStep.Check).ToList();
Assert.SequenceEqual([("a", 1), ("b", 2)], check.Select(d => (d.Item!, d.Part)));
Assert.True(check.All(d => d.Parts == 2 && d.PartUnit == JobPartUnit.Folder));
}
[Test]
public async Task AVerifyCountsThePhotosOfEachSequence()
{
await using var fx = await CreateAsync(context);
Populate(fx);
await fx.ScanAsync();
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var id = await RunAsync(fx, engine, ArchiveJobs.Verify(fx.Archive));
var details = recorder.Details(id);
Assert.True(details.All(d => d.Step == JobStep.Verify && d.PartUnit == JobPartUnit.Sequence && d.Parts == 2), string.Join("; ", details));
Assert.SequenceEqual([(1, 1L), (1, 2L), (1, 3L), (1, 4L), (2, 1L), (2, 2L), (2, 3L)], details.Select(d => (d.Part, d.ItemDone)));
Assert.SequenceEqual([4L, 3L], details.GroupBy(d => d.Part).Select(g => g.Max(d => d.ItemTotal)));
Assert.True(details.All(d => !string.IsNullOrEmpty(d.Item)));
}
[Test]
public async Task AThumbnailPassReportsEachFrameOfEachSequence()
{
await using var fx = await CreateAsync(context);
Populate(fx);
await fx.ScanAsync();
var ids = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Select(l => l.Id).ToList();
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var id = await RunAsync(fx, engine, ArchiveJobs.Thumbnails(ids));
var details = recorder.Details(id);
Assert.True(details.All(d => d.Step == JobStep.Thumbs && d.PartUnit == JobPartUnit.Sequence && d.Parts == 2), string.Join("; ", details));
Assert.SequenceEqual([1, 2], details.Select(d => d.Part).Distinct());
// Every frame of a sequence goes out, up to its last.
Assert.SequenceEqual([(1, 4L), (2, 3L)], details.GroupBy(d => d.Part).Select(g => (g.Key, g.Max(d => d.ItemDone))));
Assert.True(details.GroupBy(d => d.Part).All(g => g.Count() >= g.Max(d => d.ItemTotal)));
}
[Test]
public async Task MaintenanceNamesItsStepsInOrder()
{
await using var fx = await CreateAsync(context);
Populate(fx);
await fx.ScanAsync();
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var id = await RunAsync(fx, engine, ArchiveJobs.Maintenance(fx.Archive));
var details = recorder.Details(id);
var steps = details.Where(d => d.Step == JobStep.Maintenance).ToList();
Assert.SequenceEqual(["leases", "temp", "packs", "duplicates", "vacuum"], steps.Select(d => d.Item!));
Assert.SequenceEqual([1, 2, 3, 4, 5], steps.Select(d => d.Part));
Assert.True(steps.All(d => d.Parts == 5 && d.PartUnit == JobPartUnit.Step));
Assert.SequenceEqual([JobStep.Maintenance, JobStep.Check], recorder.Steps(id));
}
[Test]
public async Task DuplicatesAndOrphansRunWithoutACount()
{
await using var fx = await CreateAsync(context);
Populate(fx);
await fx.ScanAsync();
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
foreach (var request in new[] { ArchiveJobs.Duplicates(fx.Archive), ArchiveJobs.Orphans(fx.Archive) })
{
var id = await RunAsync(fx, engine, request);
// Every report until the one that completes it.
var reports = recorder.Of(id);
var running = reports.TakeWhile(p => p.Total == 0 || p.Done < p.Total).ToList();
Assert.NotEmpty(running);
Assert.True(running.All(p => p.Detail == new JobDetail(JobStep.Check) && p.Total == 0),
$"{request.Kind}: {string.Join("; ", reports.Select(p => $"{p.Done}/{p.Total} {p.Detail}"))}");
}
}
[Test]
public async Task ABackupRunsWithoutACountAndACleanupNamesItsSteps()
{
await using var fx = await CreateAsync(context);
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var backup = await RunAsync(fx, engine, ArchiveJobs.Backup(keep: 1));
var reports = recorder.Of(backup);
var running = reports.TakeWhile(p => p.Total == 0 || p.Done < p.Total).ToList();
Assert.NotEmpty(running);
Assert.True(running.All(p => p.Detail == new JobDetail(JobStep.Backup) && p.Total == 0), string.Join("; ", reports.Select(p => $"{p.Done}/{p.Total} {p.Detail}")));
var cleanup = await RunAsync(fx, engine, ArchiveJobs.Cleanup(fx.Archive, [CleanupSteps.JobHistory, CleanupSteps.Audit], 0));
var steps = recorder.Details(cleanup);
Assert.SequenceEqual([(CleanupSteps.JobHistory, 1), (CleanupSteps.Audit, 2)], steps.Select(d => (d.Item!, d.Part)));
Assert.True(steps.All(d => d.Step == JobStep.Cleanup && d.Parts == 2 && d.PartUnit == JobPartUnit.Step));
}
[Test]
public async Task EmptyingTheTrashCountsItsEntries()
{
await using var fx = await CreateAsync(context);
Populate(fx);
await fx.ScanAsync();
var ids = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Select(l => l.Id).ToList();
await fx.Service.DeleteAsync(await fx.Service.PlanDeleteAsync(ids, null, fx.Ct), null, null, fx.Ct);
var empty = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var id = await RunAsync(fx, engine, ArchiveJobs.EmptyTrash(fx.Archive, empty));
var details = recorder.Details(id);
Assert.True(details.All(d => d.Step == JobStep.Erase && d.PartUnit == JobPartUnit.Entry && d.Parts == 2), string.Join("; ", details));
Assert.SequenceEqual([1, 2], details.Select(d => d.Part));
Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct));
}
}
@@ -366,7 +366,7 @@ public abstract class PartialRowWriterTests(TestContext context) : DatabaseTest(
// The first verify of photos a scan adopted hashes them all; a thumbnail pass records a preview-only frame meanwhile.
var recorded = false;
var report = await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async (_, _) =>
var report = await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async _ =>
{
if (recorded) return;
recorded = true;
@@ -399,7 +399,7 @@ public abstract class PartialRowWriterTests(TestContext context) : DatabaseTest(
// The verify finds the file missing, and an upload puts it back before the verify writes what it found.
var checkedFrames = 0;
var report = await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async (_, _) =>
var report = await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async _ =>
{
if (++checkedFrames != 2) return;
Assert.True((await fx.Service.Ingest.CommitAsync(Upload(fx.Stage(Start.AddSeconds(10), seed: 2)), fx.Ct)).Repaired, "repaired");
@@ -570,9 +570,9 @@ public abstract class PartialRowWriterTests(TestContext context) : DatabaseTest(
// The server's PATCH takes the row as the last photo is checked, and commits while the verify stamps the sequence.
Task? commit = null;
await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async (done, total) =>
await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async p =>
{
if (done < total || commit is not null) return;
if (p.BytesDone < p.BytesTotal || commit is not null) return;
var tx = await fx.Db.BeginAsync(fx.Ct);
await tx.Sequences.EditAsync(sequence.Id, new SequenceEdit { SettingsJson = """{"heroFrame":1}""" }, sequence.SettingsVersion, fx.Ct);
commit = CommitLaterAsync(tx, fx.Ct);
@@ -0,0 +1,122 @@
using System.Security.Cryptography;
using System.Text;
using Chronos.Core.Archiving;
using Chronos.Core.Project;
using Chronos.Data.Workspaces;
namespace Chronos.Data.Tests.Homes;
/// <summary>Workspaces and caches laid out as 1.0 left them, for the sorting into homes (owner review 5, #66).</summary>
internal static class HomeFixtures
{
public const string Nas = "https://nas.local:8443";
public const string NasByIp = "https://192.168.1.5:8443";
public const string Other = "https://other.example:8443";
/// <summary>A working state of <paramref name="home"/> written into <c>&lt;root&gt;/&lt;id&gt;</c> with some media, versions and a render.</summary>
public static Guid Project(string root, BundleHome home, string name = "Main", DateTimeOffset? saved = null, Guid? id = null, int proxies = 3)
{
var projectId = id ?? Guid.CreateVersion7();
var folder = Path.Combine(root, projectId.ToString("N"));
Directory.CreateDirectory(folder);
var archive = home.IsArchive
? new BundleArchive(home.ArchiveId ?? Guid.CreateVersion7(), "This PC", @"D:\ChronosArchive")
: new BundleArchive(Data.Projects.ServerProjectHome.ArchiveIdOf(home.Server!), "Studio NAS", null);
var bundle = new ProjectBundle(archive, new BundleSequence(home.SequenceId, "2026/2026-11-15 Harbour", "Harbour", proxies), new ProjectSettings(),
saved ?? DateTimeOffset.UtcNow)
{
Workspace = new BundleWorkspace(projectId, name, true, home, null, new BundleMedia(BundleMedia.Proxies, 1)),
};
bundle.Save(Path.Combine(folder, WorkspaceProject.BundleFile));
var media = Path.Combine(folder, WorkspaceProject.MediaFolder, WorkspaceProject.ProxiesFolder);
Directory.CreateDirectory(media);
for (var i = 0; i < proxies; i++) File.WriteAllBytes(Path.Combine(media, Guid.CreateVersion7().ToString("N") + ".jpg"), Bytes(projectId, i, 500 + i));
Directory.CreateDirectory(Path.Combine(folder, WorkspaceProject.VersionsFolder));
File.WriteAllText(Path.Combine(folder, WorkspaceProject.VersionsFolder, "1-" + Guid.CreateVersion7().ToString("N") + ".json"), "{}");
Directory.CreateDirectory(Path.Combine(folder, WorkspaceProject.ExportsFolder));
File.WriteAllBytes(Path.Combine(folder, WorkspaceProject.ExportsFolder, "render.mp4"), Bytes(projectId, 99, 2048));
return projectId;
}
public static BundleHome Local() => new(BundleHome.ArchiveKind, Guid.CreateVersion7(), Guid.CreateVersion7());
public static BundleHome Server(string key) => new(BundleHome.ServerKind, Guid.CreateVersion7(), null, key);
/// <summary>A 1.0 workspace: its manifest (format 1) and the folder.</summary>
public static string LegacyWorkspace(string parent)
{
var root = Path.Combine(parent, "workspace");
_ = new WorkspaceStore(root);
return root;
}
/// <summary>A trash entry of <paramref name="projectId"/> holding a working state, as a removal leaves it.</summary>
public static string TrashEntry(string root, Guid projectId, BundleHome home)
{
var trash = Path.Combine(root, WorkspaceTrash.FolderName);
var staging = Path.Combine(trash, "staging");
Directory.CreateDirectory(staging);
Project(staging, home, id: projectId, proxies: 1);
var entry = Path.Combine(trash, projectId.ToString("N") + "-638000000000000000");
Directory.Move(Path.Combine(staging, projectId.ToString("N")), entry);
Directory.Delete(staging);
return entry;
}
/// <summary>The 1.0 proxy cache of <paramref name="key"/>'s sequence <paramref name="remoteId"/>.</summary>
public static string LegacyProxies(string cache, string key, Guid remoteId, int frames = 2)
{
var folder = Data.Sync.ProxyCache.LegacyFolder(Path.Combine(cache, "proxies"), key, remoteId);
Directory.CreateDirectory(folder);
File.WriteAllText(Path.Combine(folder, "remote.json"), "{}");
for (var i = 0; i < frames; i++) File.WriteAllBytes(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + ".jpg"), Bytes(remoteId, i, 300));
return folder;
}
/// <summary>A live lease on a project folder, as another Chronos working on the same workspace holds it.</summary>
public static LeaseFile Hold(string projectFolder) =>
LeaseFile.TryAcquire(projectFolder, ".lock", "workspace@other", TimeSpan.FromMinutes(5)) ?? throw new InvalidOperationException("The lease is held.");
/// <summary>
/// The SHA-256 of every file under <paramref name="root"/> by its name relative to the project or entry it belongs to,
/// whatever home folder holds it: the same before and after a sorting that only renames (the test-only proof).
/// </summary>
public static SortedDictionary<string, string> Manifest(string root)
{
var manifest = new SortedDictionary<string, string>(StringComparer.Ordinal);
if (!Directory.Exists(root)) return manifest;
foreach (var file in Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories))
{
var relative = Path.GetRelativePath(root, file).Replace('\\', '/');
var name = Path.GetFileName(file);
if (name is WorkspaceStore.ManifestFile or "server.json" && !relative.Contains('/', StringComparison.Ordinal)) continue;
if (name is WorkspaceStore.ManifestFile or "server.json" && IsHomeLevel(relative)) continue;
manifest[Strip(relative)] = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(file))) + "|" + new FileInfo(file).Length;
}
return manifest;
}
/// <summary>A path without the home folders it lies in (<c>local/</c>, <c>servers/&lt;folder&gt;/</c>).</summary>
private static string Strip(string relative)
{
if (relative.StartsWith("local/", StringComparison.Ordinal)) return relative["local/".Length..];
if (relative.StartsWith("servers/", StringComparison.Ordinal))
{
var rest = relative["servers/".Length..];
var slash = rest.IndexOf('/', StringComparison.Ordinal);
return slash < 0 ? rest : rest[(slash + 1)..];
}
return relative;
}
private static bool IsHomeLevel(string relative) =>
relative.Split('/') is { Length: 2 } parts && parts[0] == "local" || relative.Split('/') is { Length: 3 } more && more[0] == "servers";
private static byte[] Bytes(Guid seed, int index, int length)
{
var bytes = new byte[length];
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(seed.ToString("N") + index));
for (var i = 0; i < length; i++) bytes[i] = hash[i % hash.Length];
return bytes;
}
}
@@ -0,0 +1,302 @@
using Chronos.Core.IO;
using Chronos.Core.Project;
using Chronos.Data.Homes;
using Chronos.Data.Sync;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.Data.Tests.Homes;
/// <summary>The one-time sorting of a 1.0 workspace and cache into homes (owner review 5, #66).</summary>
[Category("homes")]
public sealed class HomeLayoutMigrationTests(TestContext context)
{
private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
/// <summary>A 1.0 data folder: a workspace with local, server and damaged projects and a trash, and a cache with proxies, render-node files and a staged import.</summary>
private sealed class Legacy
{
public required string Data { get; init; }
public required string Workspace { get; init; }
public required string Cache { get; init; }
public required Guid Local { get; init; }
public required Guid OnNas { get; init; }
public required Guid OnOther { get; init; }
public required Guid Damaged { get; init; }
public required Guid NasRemote { get; init; }
public HomeLayoutMigration Migration(ServerIdentity? identity = null, Action<string, string>? cut = null) =>
new(new HomeLayoutOptions
{
DataDirectory = Data,
WorkspaceRoot = Workspace,
CacheRoot = Cache,
Identity = identity ?? ServerIdentity.None,
CurrentServer = HomeFixtures.Nas,
})
{ Cut = cut };
}
private Legacy Make()
{
var data = context.CreateTempDirectory("data");
var workspace = HomeFixtures.LegacyWorkspace(data);
var local = HomeFixtures.Project(workspace, HomeFixtures.Local());
var onNas = HomeFixtures.Project(workspace, HomeFixtures.Server(HomeFixtures.Nas));
var onOther = HomeFixtures.Project(workspace, HomeFixtures.Server(HomeFixtures.Other));
var damaged = Guid.CreateVersion7();
Directory.CreateDirectory(Path.Combine(workspace, damaged.ToString("N")));
File.WriteAllText(Path.Combine(workspace, damaged.ToString("N"), WorkspaceProject.BundleFile), "{ not json");
HomeFixtures.TrashEntry(workspace, onNas, HomeFixtures.Server(HomeFixtures.Nas));
File.WriteAllText(Path.Combine(workspace, WorkspaceTrash.FolderName, "loose.txt"), "kept");
var cache = Path.Combine(data, "cache");
var nasRemote = Guid.CreateVersion7();
HomeFixtures.LegacyProxies(cache, HomeFixtures.Nas, nasRemote);
HomeFixtures.LegacyProxies(cache, HomeFixtures.Other, Guid.CreateVersion7());
Directory.CreateDirectory(Path.Combine(cache, "render-node", "job1"));
File.WriteAllText(Path.Combine(cache, "render-node", "job1", "frame.jpg"), "rn");
Directory.CreateDirectory(Path.Combine(cache, "server-import"));
File.WriteAllText(Path.Combine(cache, "server-import", "card.part"), "import");
return new Legacy
{
Data = data,
Workspace = workspace,
Cache = cache,
Local = local,
OnNas = onNas,
OnOther = onOther,
Damaged = damaged,
NasRemote = nasRemote,
};
}
/// <summary>Every file and folder under <paramref name="root"/> with its size and time: what a dry run must leave as it was.</summary>
private static List<string> Snapshot(string root) =>
[.. new DirectoryInfo(root).EnumerateFileSystemInfos("*", SearchOption.AllDirectories)
.Select(e => Path.GetRelativePath(root, e.FullName) + "|" + (e is FileInfo f ? f.Length + "|" + f.LastWriteTimeUtc.Ticks : "dir"))
.Order(StringComparer.Ordinal)];
private static string Home(string workspace, string key) => Path.Combine(workspace, "servers", HomeFolders.ServerFolder(key));
private static void AssertSorted(Legacy legacy, string nasFolder)
{
var ws = legacy.Workspace;
Assert.True(WorkspaceHomes.IsSplitRoot(ws));
Assert.FileExists(Path.Combine(ws, "local", legacy.Local.ToString("N"), WorkspaceProject.BundleFile));
Assert.FileExists(Path.Combine(ws, "local", legacy.Damaged.ToString("N"), WorkspaceProject.BundleFile));
Assert.FileExists(Path.Combine(ws, "servers", nasFolder, legacy.OnNas.ToString("N"), WorkspaceProject.BundleFile));
Assert.FileExists(Path.Combine(Home(ws, HomeFixtures.Other), legacy.OnOther.ToString("N"), WorkspaceProject.BundleFile));
Assert.FileExists(Path.Combine(ws, "local", WorkspaceTrash.FolderName, "loose.txt"));
Assert.Count(1, Directory.EnumerateDirectories(Path.Combine(ws, "servers", nasFolder, WorkspaceTrash.FolderName)));
Assert.False(Directory.EnumerateDirectories(ws).Any(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _)), "no project is left in the parent");
Assert.False(Directory.Exists(Path.Combine(ws, WorkspaceTrash.FolderName)), "the parent's emptied trash went");
Assert.Equal("Studio NAS", Assert.NotNull(ServerHomeRecord.Read(Path.Combine(ws, "servers", nasFolder))).Name);
Assert.FileExists(Path.Combine(legacy.Cache, "servers", nasFolder, "proxies", legacy.NasRemote.ToString("N"), "remote.json"));
Assert.True(Directory.Exists(Path.Combine(legacy.Cache, "servers", HomeFolders.ServerFolder(HomeFixtures.Other), "proxies")));
Assert.FileExists(Path.Combine(legacy.Cache, "servers", nasFolder, "render-node", "job1", "frame.jpg"));
Assert.FileExists(Path.Combine(legacy.Cache, "servers", nasFolder, "import", "card.part"));
Assert.False(Directory.Exists(Path.Combine(legacy.Cache, "render-node")));
Assert.FileMissing(Path.Combine(legacy.Data, HomeLayoutMigration.JournalFile));
var homes = new WorkspaceHomes(ws);
Assert.True(homes.IsSplit);
Assert.Equal(4, homes.List().Count);
}
[Test]
public async Task ThePlanWritesNothing()
{
var legacy = Make();
var before = Snapshot(legacy.Data);
var plan = await legacy.Migration().PlanAsync(context.Cancellation);
Assert.SequenceEqual(before, Snapshot(legacy.Data));
Assert.True(plan.SplitsWorkspace);
Assert.Null(plan.Deferred);
Assert.Equal(4, plan.Projects);
Assert.Equal(2, plan.Entries.Count(e => e.Kind == HomeEntryKind.Trash));
Assert.Equal(2, plan.Entries.Count(e => e.Kind == HomeEntryKind.Proxies));
Assert.Equal(1, plan.Entries.Count(e => e.Kind == HomeEntryKind.RenderNode));
Assert.Equal(1, plan.Entries.Count(e => e.Kind == HomeEntryKind.Import));
var damaged = plan.Entries.Single(e => e.Source.EndsWith(legacy.Damaged.ToString("N"), StringComparison.Ordinal));
Assert.Equal(Path.Combine(legacy.Workspace, "local", legacy.Damaged.ToString("N")), damaged.Target);
Assert.Equal(plan.Fingerprint, (await legacy.Migration().PlanAsync(context.Cancellation)).Fingerprint);
}
[Test]
public async Task SortingMovesEveryHomeAndRenamesOnly()
{
var legacy = Make();
var before = HomeFixtures.Manifest(legacy.Workspace);
var cacheBefore = HomeFixtures.Manifest(legacy.Cache);
var result = await legacy.Migration().ApplyAsync(context.Cancellation);
Assert.Equal((4, 0, false, true), (result.ProjectsMoved, result.InUse, result.Resumed, result.Split));
AssertSorted(legacy, HomeFolders.ServerFolder(HomeFixtures.Nas));
// Every file is there with the same name relative to its project and the same bytes: the sorting only renamed.
Assert.SequenceEqual(before, HomeFixtures.Manifest(legacy.Workspace));
Assert.SequenceEqual(cacheBefore.Values.Order(), HomeFixtures.Manifest(legacy.Cache).Values.Order());
// A second run does nothing.
var again = await legacy.Migration().ApplyAsync(context.Cancellation);
Assert.Equal(HomeLayoutResult.Nothing, again);
Assert.True((await legacy.Migration().PlanAsync(context.Cancellation)).IsEmpty);
}
[Test]
public async Task AServerKnownByIdGetsItsIdHome()
{
var legacy = Make();
await legacy.Migration(new ServerIdentity([new KnownServerKey(Id, [HomeFixtures.Nas])])).ApplyAsync(context.Cancellation);
AssertSorted(legacy, Id.ToString("N"));
Assert.Equal(ServerIdentity.IdKey(Id), Assert.NotNull(ServerHomeRecord.Read(Path.Combine(legacy.Workspace, "servers", Id.ToString("N")))).Key);
}
[Test]
public async Task ACrashAtAnyStepIsTakenUpToTheSameEnd()
{
var entries = (await Make().Migration().PlanAsync(context.Cancellation)).Entries.Count;
var cuts = new List<(string Step, int Occurrence)> { ("journal", 1), ("commit", 1) };
for (var i = 1; i <= entries; i++) cuts.AddRange([("rename", i), ("renamed", i)]);
foreach (var (step, occurrence) in cuts)
{
var legacy = Make();
var before = HomeFixtures.Manifest(legacy.Workspace);
var seen = 0;
var crashing = legacy.Migration(cut: (name, _) =>
{
if (name == step && ++seen == occurrence) throw new IOException("cut at " + step);
});
await Assert.ThrowsAsync<IOException>(() => crashing.ApplyAsync(context.Cancellation));
Assert.FileExists(Path.Combine(legacy.Data, HomeLayoutMigration.JournalFile));
var resumed = await legacy.Migration().ApplyAsync(context.Cancellation);
Assert.True(resumed.Resumed, $"{step} #{occurrence}");
AssertSorted(legacy, HomeFolders.ServerFolder(HomeFixtures.Nas));
Assert.SequenceEqual(before, HomeFixtures.Manifest(legacy.Workspace), $"{step} #{occurrence}");
Assert.Equal(HomeLayoutResult.Nothing, await legacy.Migration().ApplyAsync(context.Cancellation));
}
}
[Test]
public async Task AProjectInUseIsLeftAndMovedAtALaterStart()
{
var legacy = Make();
var held = HomeFixtures.Hold(Path.Combine(legacy.Workspace, legacy.Local.ToString("N")));
HomeLayoutResult result;
using (held)
{
var plan = await legacy.Migration().PlanAsync(context.Cancellation);
Assert.SequenceEqual(new[] { legacy.Local }, plan.InUse);
result = await legacy.Migration().ApplyAsync(context.Cancellation);
Assert.Equal((3, 1, true), (result.ProjectsMoved, result.InUse, result.Split));
Assert.True(WorkspaceHomes.IsSplitRoot(legacy.Workspace));
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));
Assert.FileExists(Path.Combine(legacy.Workspace, "local", legacy.Local.ToString("N"), WorkspaceProject.BundleFile));
Assert.Null(new WorkspaceHomes(legacy.Workspace).Homes().FirstOrDefault(h => h.IsLegacy));
}
[Test]
public async Task AnUnfinishedMoveDefersTheWorkspaceWhileTheCacheIsSorted()
{
var legacy = Make();
File.WriteAllText(Path.Combine(legacy.Workspace, WorkspaceMover.JournalFile), "{}");
var before = Snapshot(legacy.Workspace);
var result = await legacy.Migration().ApplyAsync(context.Cancellation);
Assert.Equal((HomeLayoutDeferral?)HomeLayoutDeferral.Moving, result.Deferred);
Assert.False(result.Split);
Assert.SequenceEqual(before, Snapshot(legacy.Workspace));
Assert.FileExists(Path.Combine(legacy.Cache, "servers", HomeFolders.ServerFolder(HomeFixtures.Nas), "proxies", legacy.NasRemote.ToString("N"), "remote.json"));
File.Delete(Path.Combine(legacy.Workspace, WorkspaceMover.JournalFile));
await legacy.Migration().ApplyAsync(context.Cancellation);
AssertSorted(legacy, HomeFolders.ServerFolder(HomeFixtures.Nas));
}
[Test]
public async Task AWorkspaceThatWentOfflineWaitsWithItsJournal()
{
var legacy = Make();
var before = HomeFixtures.Manifest(legacy.Workspace);
await Assert.ThrowsAsync<IOException>(() => legacy.Migration(cut: (name, _) =>
{
if (name == "journal") throw new IOException("cut");
}).ApplyAsync(context.Cancellation));
// The drive goes before the next start.
var away = legacy.Workspace + "-unplugged";
Directory.Move(legacy.Workspace, away);
var waiting = await legacy.Migration().ApplyAsync(context.Cancellation);
Assert.Equal((HomeLayoutDeferral?)HomeLayoutDeferral.Offline, waiting.Deferred);
Assert.FileExists(Path.Combine(legacy.Data, HomeLayoutMigration.JournalFile));
Assert.FileExists(Path.Combine(legacy.Cache, "servers", HomeFolders.ServerFolder(HomeFixtures.Nas), "import", "card.part"));
// Back: the workspace is sorted, the cache left as it is now.
Directory.Move(away, legacy.Workspace);
await legacy.Migration().ApplyAsync(context.Cancellation);
AssertSorted(legacy, HomeFolders.ServerFolder(HomeFixtures.Nas));
Assert.SequenceEqual(before, HomeFixtures.Manifest(legacy.Workspace));
}
[Test]
public async Task AProjectInBothPlacesKeepsTheCopySavedLastAndTrashesTheOther()
{
var data = context.CreateTempDirectory("data");
var workspace = HomeFixtures.LegacyWorkspace(data);
var id = Guid.CreateVersion7();
var home = HomeFixtures.Local();
HomeFixtures.Project(workspace, home, "newer", DateTimeOffset.UtcNow, id);
HomeFixtures.Project(Path.Combine(workspace, "local"), home, "older", DateTimeOffset.UtcNow.AddDays(-1), id);
var files = Directory.EnumerateFiles(workspace, "*", SearchOption.AllDirectories).Count(f => Path.GetFileName(f) != WorkspaceStore.ManifestFile);
var result = await new HomeLayoutMigration(new HomeLayoutOptions { DataDirectory = data, WorkspaceRoot = workspace }).ApplyAsync(context.Cancellation);
Assert.Equal(1, result.Clashes);
var kept = ProjectBundle.Load(Path.Combine(workspace, "local", id.ToString("N"), WorkspaceProject.BundleFile));
Assert.Equal("newer", kept.Workspace!.Name);
var trashed = Assert.NotNull(Directory.EnumerateDirectories(Path.Combine(workspace, "local", WorkspaceTrash.FolderName)).SingleOrDefault());
Assert.Equal("older", ProjectBundle.Load(Path.Combine(trashed, WorkspaceProject.BundleFile)).Workspace!.Name);
Assert.Equal(files, Directory.EnumerateFiles(workspace, "*", SearchOption.AllDirectories)
.Count(f => Path.GetFileName(f) is not (WorkspaceStore.ManifestFile or "server.json")), "nothing was deleted");
}
[Test]
public async Task ARenameThatDoesNotCheckStopsWithItsJournal()
{
var legacy = Make();
var tampered = false;
var migration = legacy.Migration(cut: (name, path) =>
{
if (name != "renamed" || tampered || !Directory.Exists(path)) return;
tampered = true;
File.WriteAllText(Path.Combine(path, "stray.txt"), "written meanwhile");
});
await Assert.ThrowsAsync<HomeLayoutException>(() => migration.ApplyAsync(context.Cancellation));
Assert.FileExists(Path.Combine(legacy.Data, HomeLayoutMigration.JournalFile));
// The next start takes it up; the entry found renamed is taken as moved.
await legacy.Migration().ApplyAsync(context.Cancellation);
AssertSorted(legacy, HomeFolders.ServerFolder(HomeFixtures.Nas));
}
[Test]
public async Task AWorkspaceNeverMadeOrAlreadySortedHasNothingToDo()
{
var data = context.CreateTempDirectory("data");
var options = new HomeLayoutOptions { DataDirectory = data, WorkspaceRoot = Path.Combine(data, "workspace"), CacheRoot = Path.Combine(data, "cache") };
Assert.True((await new HomeLayoutMigration(options).PlanAsync(context.Cancellation)).IsEmpty);
Assert.Equal(HomeLayoutResult.Nothing, await new HomeLayoutMigration(options).ApplyAsync(context.Cancellation));
Assert.False(Directory.Exists(options.WorkspaceRoot));
_ = new WorkspaceHomes(options.WorkspaceRoot);
Assert.True((await new HomeLayoutMigration(options).PlanAsync(context.Cancellation)).IsEmpty);
// An empty 1.0 workspace is split by its manifest alone.
var empty = HomeFixtures.LegacyWorkspace(context.CreateTempDirectory("empty"));
var split = await new HomeLayoutMigration(options with { WorkspaceRoot = empty }).ApplyAsync(context.Cancellation);
Assert.True(split.Split);
Assert.True(WorkspaceHomes.IsSplitRoot(empty));
Assert.Equal(WorkspaceStore.FormatVersion, new WorkspaceStore(Path.Combine(empty, "local")).Manifest.FormatVersion);
}
}
@@ -0,0 +1,215 @@
using Chronos.Core.IO;
using Chronos.Core.Project;
using Chronos.Data.Homes;
using Chronos.Data.Projects;
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.Homes;
/// <summary>A server's home moves from its address to its id when it first announces one (owner review 5, #66).</summary>
[Category("homes")]
public sealed class HomeRekeyTests(TestContext context)
{
private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
private static string IdFolder => Id.ToString("N");
private (string Data, WorkspaceHomes Homes, string Cache) Make()
{
var data = context.CreateTempDirectory("data");
return (data, new WorkspaceHomes(Path.Combine(data, "workspace")), Path.Combine(data, "cache"));
}
private static HomeLayoutMigration Migration(string data, WorkspaceHomes homes, string cache) =>
new(new HomeLayoutOptions { DataDirectory = data, WorkspaceRoot = homes.Root, CacheRoot = cache });
private static string AddressHome(string root, string key) => Path.Combine(root, "servers", HomeFolders.ServerFolder(key));
private static ProjectBundle Bundle(string home, Guid id) => ProjectBundle.Load(Path.Combine(home, id.ToString("N"), WorkspaceProject.BundleFile));
[Test]
public async Task TheHomeOfTheAddressBecomesTheHomeOfTheId()
{
var (data, homes, cache) = Make();
var home = HomeFixtures.Server(HomeFixtures.Nas);
var store = homes.StoreFor(home);
var (a, b) = (HomeFixtures.Project(store.Root, home), HomeFixtures.Project(store.Root, HomeFixtures.Server(HomeFixtures.Nas)));
HomeFixtures.TrashEntry(store.Root, a, home);
var before = HomeFixtures.Manifest(homes.Root);
var (sorted, old) = (Guid.CreateVersion7(), Guid.CreateVersion7());
var cached = Path.Combine(AddressHome(cache, HomeFixtures.Nas), "proxies", sorted.ToString("N"));
Directory.CreateDirectory(cached);
File.WriteAllText(Path.Combine(cached, "remote.json"), "{}");
HomeFixtures.LegacyProxies(cache, HomeFixtures.Nas, old);
var result = await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas], context.Cancellation);
Assert.Equal(new HomeRekeyResult(2, 0, 0, 2, 0, 0, 0), result);
var idHome = Path.Combine(homes.Root, "servers", IdFolder);
Assert.False(Directory.Exists(AddressHome(homes.Root, HomeFixtures.Nas)));
var idKey = ServerIdentity.IdKey(Id);
foreach (var id in new[] { a, b })
{
var bundle = Bundle(idHome, id);
Assert.Equal(idKey, bundle.Workspace!.Home!.Server);
Assert.Equal(ServerProjectHome.ArchiveIdOf(idKey), bundle.Archive.Id);
}
var record = Assert.NotNull(ServerHomeRecord.Read(idHome));
Assert.Equal((idKey, (Guid?)Id, HomeFixtures.Nas), (record.Key, record.Id, record.Address));
Assert.Count(1, Directory.EnumerateDirectories(Path.Combine(idHome, WorkspaceTrash.FolderName)));
// Only the working states were rewritten: every other file is as it was.
var after = HomeFixtures.Manifest(homes.Root);
Assert.SequenceEqual(before.Keys, after.Keys);
Assert.SequenceEqual(before.Where(f => !f.Key.EndsWith(WorkspaceProject.BundleFile, StringComparison.Ordinal)),
after.Where(f => !f.Key.EndsWith(WorkspaceProject.BundleFile, StringComparison.Ordinal)));
Assert.FileExists(Path.Combine(cache, "servers", IdFolder, "proxies", sorted.ToString("N"), "remote.json"));
Assert.FileExists(Path.Combine(cache, "servers", IdFolder, "proxies", old.ToString("N"), "remote.json"));
Assert.False(Directory.Exists(AddressHome(cache, HomeFixtures.Nas)));
// The store now finds the id home by either key.
var identity = new ServerIdentity([new KnownServerKey(Id, [HomeFixtures.Nas])]);
Assert.Equal(idHome, new WorkspaceHomes(homes.Root, identity).ServerRoot(HomeFixtures.Nas));
// Again: nothing left to do.
Assert.Equal(new HomeRekeyResult(0, 0, 0, 0, 0, 0, 0), await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas], context.Cancellation));
}
[Test]
public async Task TwoAddressesOfOneServerMergeAndTheOlderCopyGoesToTheTrash()
{
var (data, homes, cache) = Make();
var byName = HomeFixtures.Server(HomeFixtures.Nas);
var byIp = HomeFixtures.Server(HomeFixtures.NasByIp);
var first = homes.StoreFor(byName).Root;
var second = homes.StoreFor(byIp).Root;
var both = Guid.CreateVersion7();
HomeFixtures.Project(first, byName, "older", DateTimeOffset.UtcNow.AddDays(-1), both);
HomeFixtures.Project(second, byIp, "newer", DateTimeOffset.UtcNow, both);
var onlyFirst = HomeFixtures.Project(first, byName);
var onlySecond = HomeFixtures.Project(second, byIp);
HomeFixtures.TrashEntry(first, onlyFirst, byName);
HomeFixtures.TrashEntry(second, onlyFirst, byIp);
var files = Directory.EnumerateFiles(homes.Root, "*", SearchOption.AllDirectories).Count(IsProjectFile);
// Each address had a proxy cache too.
Directory.CreateDirectory(Path.Combine(AddressHome(cache, HomeFixtures.Nas), "proxies", "a"));
Directory.CreateDirectory(Path.Combine(AddressHome(cache, HomeFixtures.NasByIp), "proxies", "a"));
Directory.CreateDirectory(Path.Combine(AddressHome(cache, HomeFixtures.NasByIp), "proxies", "b"));
var result = await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas, HomeFixtures.NasByIp], context.Cancellation);
Assert.Equal((2, 2, 1, 3), (result.HomesMoved, result.ProjectsMoved, result.ProjectsTrashed, result.BundlesRewritten));
var idHome = Path.Combine(homes.Root, "servers", IdFolder);
Assert.Equal("newer", Bundle(idHome, both).Workspace!.Name);
foreach (var id in new[] { onlyFirst, onlySecond }) Assert.FileExists(Path.Combine(idHome, id.ToString("N"), WorkspaceProject.BundleFile));
var trash = Directory.EnumerateDirectories(Path.Combine(idHome, WorkspaceTrash.FolderName)).ToList();
Assert.Equal(3, trash.Count);
Assert.Contains(trash, t => ProjectBundle.Load(Path.Combine(t, WorkspaceProject.BundleFile)).Workspace!.Name == "older");
// The second address's home held only its manifest and record afterwards: it went. Nothing else was deleted.
Assert.False(Directory.Exists(second));
Assert.Equal(files, Directory.EnumerateFiles(homes.Root, "*", SearchOption.AllDirectories).Count(IsProjectFile));
Assert.Count(1, Directory.EnumerateDirectories(Path.Combine(homes.Root, "servers")));
Assert.True(Directory.Exists(Path.Combine(cache, "servers", IdFolder, "proxies", "b")));
}
[Test]
public async Task AProjectInUseStaysAndKeepsItsAliasWhichStillMatches()
{
var (data, homes, cache) = Make();
var home = HomeFixtures.Server(HomeFixtures.Nas);
var root = homes.StoreFor(home).Root;
var (held, free) = (HomeFixtures.Project(root, home), HomeFixtures.Project(root, HomeFixtures.Server(HomeFixtures.Nas)));
HomeRekeyResult result;
using (HomeFixtures.Hold(Path.Combine(root, held.ToString("N"))))
{
// A project in use keeps the whole home where it is until a later re-key; the id home is made beside it.
_ = new WorkspaceStore(Path.Combine(homes.Root, "servers", IdFolder));
result = await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas], context.Cancellation);
}
Assert.Equal((0, 1, 1), (result.HomesMoved, result.ProjectsMoved, result.BundlesRewritten));
Assert.FileExists(Path.Combine(root, held.ToString("N"), WorkspaceProject.BundleFile));
Assert.Equal(HomeFixtures.Nas, Bundle(root, held).Workspace!.Home!.Server);
var idHome = Path.Combine(homes.Root, "servers", IdFolder);
Assert.Equal(ServerIdentity.IdKey(Id), Bundle(idHome, free).Workspace!.Home!.Server);
Assert.True(ServerProjectHome.IsArchiveIdOf(Bundle(root, held).Archive.Id, [ServerIdentity.IdKey(Id), HomeFixtures.Nas]));
Assert.NotNull(homes.Find(held));
result = await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas], context.Cancellation);
Assert.Equal((1, 1), (result.ProjectsMoved, result.BundlesRewritten));
Assert.False(Directory.Exists(root));
Assert.Equal(ServerIdentity.IdKey(Id), Bundle(idHome, held).Workspace!.Home!.Server);
}
[Test]
public async Task AWorkingStateInUseInTheIdHomeIsLeftNamingTheAlias()
{
var (data, homes, cache) = Make();
var home = HomeFixtures.Server(HomeFixtures.Nas);
var root = homes.StoreFor(home).Root;
var id = HomeFixtures.Project(root, home);
// Renamed whole first (nothing held), then held while its working state would be rewritten.
var idHome = Path.Combine(homes.Root, "servers", IdFolder);
Directory.Move(root, idHome);
HomeRekeyResult result;
using (HomeFixtures.Hold(Path.Combine(idHome, id.ToString("N"))))
result = await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas], context.Cancellation);
Assert.Equal((0, 1), (result.BundlesRewritten, result.BundlesInUse));
Assert.Equal(HomeFixtures.Nas, Bundle(idHome, id).Workspace!.Home!.Server);
Assert.Equal(ServerIdentity.IdKey(Id), Assert.NotNull(ServerHomeRecord.Read(idHome)).Key);
}
[Test]
public async Task AnIdKeyIsNeverAnAliasAndAnEmptyIdIsRefused()
{
var (data, homes, cache) = Make();
await Assert.ThrowsAsync<ArgumentException>(() => Migration(data, homes, cache).RekeyAsync(Guid.Empty, [HomeFixtures.Nas], context.Cancellation));
var other = ServerIdentity.IdKey(Guid.CreateVersion7());
var otherHome = homes.StoreFor(HomeFixtures.Server(other)).Root;
Assert.Equal(new HomeRekeyResult(0, 0, 0, 0, 0, 0, 0), await Migration(data, homes, cache).RekeyAsync(Id, [other], context.Cancellation));
Assert.True(Directory.Exists(otherHome));
}
private static bool IsProjectFile(string path) => Path.GetFileName(path) is not (WorkspaceStore.ManifestFile or HomeFolders.ServerFile);
}
/// <summary>A re-key moves the server's links in the index too.</summary>
[Category("homes")]
public abstract class HomeRekeyLinkTests(TestContext context) : RepositoryTest(context)
{
private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
[Test]
public async Task TheLinksOfEveryAliasMoveToTheId()
{
var db = await OpenChronosAsync();
var store = new SyncLinkStore(db);
foreach (var key in new[] { HomeFixtures.Nas, HomeFixtures.NasByIp, HomeFixtures.Other })
{
await store.UpsertAsync(new SyncLink
{
Server = key,
RemoteId = Guid.CreateVersion7(),
Title = "Harbour",
RemoteUpdatedAt = TestData.Now,
SyncedAt = TestData.Now,
}, Ct);
}
var data = Context.CreateTempDirectory("data");
var migration = new HomeLayoutMigration(new HomeLayoutOptions { DataDirectory = data, Database = db });
var result = await migration.RekeyAsync(Id, [HomeFixtures.Nas, HomeFixtures.NasByIp], Ct);
Assert.Equal((2, 0), (result.LinksMoved, result.LinksDropped));
Assert.Count(2, await store.ListAsync(ServerIdentity.IdKey(Id), Ct));
Assert.Count(1, await store.ListAsync(HomeFixtures.Other, Ct));
Assert.Empty(await store.ListAsync(HomeFixtures.Nas, Ct));
}
}
public sealed class SqliteHomeRekeyLinkTests(TestContext context) : HomeRekeyLinkTests(context)
{
protected override Backend Backend => Backend.SqliteMemory;
}
public sealed class PostgresHomeRekeyLinkTests(TestContext context) : HomeRekeyLinkTests(context)
{
protected override Backend Backend => Backend.Postgres;
}
@@ -0,0 +1,62 @@
using Chronos.Core.Model;
using Chronos.Data.Jobs;
namespace Chronos.Data.Tests.Jobs;
/// <summary>
/// Every progress report a job engine publishes, kept to tell which details a handler sent and in what order (owner review
/// 5, #65). The engine it records has no publish throttle (<see cref="Options"/>), so each report a handler makes goes out.
/// </summary>
internal sealed class DetailRecorder
{
private readonly List<JobProgressInfo> _published = [];
/// <summary>A started engine's options that publish every report: one worker, fast polls and checkpoints, no progress interval.</summary>
public static JobEngineOptions Options(string worker = "detail") => new()
{
Workers = 1,
WorkerId = worker,
PollInterval = TimeSpan.FromMilliseconds(50),
CheckpointInterval = TimeSpan.FromMilliseconds(50),
ProgressInterval = TimeSpan.Zero,
};
/// <summary>A new engine with <paramref name="handlers"/>, recorded, not started.</summary>
public JobEngine Engine(ChronosDatabase db, IEnumerable<IJobHandler> handlers, string worker = "detail")
{
var engine = new JobEngine(db, [.. handlers], Options(worker));
engine.Progress += p =>
{
lock (_published) _published.Add(p);
};
return engine;
}
/// <summary>The reports of <paramref name="jobId"/> in the order they went out.</summary>
public IReadOnlyList<JobProgressInfo> Of(Guid jobId)
{
lock (_published) return [.. _published.Where(p => p.JobId == jobId)];
}
/// <summary>The details of <paramref name="jobId"/>, without repeats of the one before.</summary>
public IReadOnlyList<JobDetail> Details(Guid jobId)
{
var details = new List<JobDetail>();
foreach (var report in Of(jobId))
{
if (report.Detail is { } detail && (details.Count == 0 || details[^1] != detail)) details.Add(detail);
}
return details;
}
/// <summary>The steps of <paramref name="jobId"/> in order, each once in a row.</summary>
public IReadOnlyList<JobStep> Steps(Guid jobId)
{
var steps = new List<JobStep>();
foreach (var detail in Details(jobId))
{
if (steps.Count == 0 || steps[^1] != detail.Step) steps.Add(detail.Step);
}
return steps;
}
}
@@ -0,0 +1,267 @@
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Testing;
namespace Chronos.Data.Tests.Jobs;
/// <summary>
/// How a running job's progress goes out (owner review 5, #65): at most twice a second, at once for the run's first report,
/// a new step and a completed count, and with the persist that falls due when the last report was dropped; saved at most
/// every checkpoint interval and at each checkpoint, with its detail.
/// </summary>
[Category("jobs")]
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()
{
await using var run = await StartAsync();
for (var i = 1; i <= 100; i++)
{
await run.Context.ReportAsync(i, 1000);
run.Time.Advance(Tick);
}
Assert.True(run.Published.Count <= 3, $"{run.Published.Count} publishes");
// 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]
public async Task ANewStepAndACompletedCountGoOutAtOnce()
{
await using var run = await StartAsync();
var index = new JobDetail(JobStep.Index, "2024/Harbour sunset", 1, 5, 1, 2, JobPartUnit.Folder);
await run.Context.ReportAsync(1, 10, new JobDetail(JobStep.List));
run.Time.Advance(Tick);
await run.Context.ReportAsync(2, 10, new JobDetail(JobStep.List));
// 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);
run.Time.Advance(Tick);
await run.Context.ReportAsync(10, 10);
run.Time.Advance(Tick);
await run.Context.ReportAsync(10, 10);
Assert.SequenceEqual([1L, 3L, 10L], run.Published.Select(p => p.Done));
Assert.Equal(index, run.Published[1].Detail);
// A report without a detail keeps the last one, with the item counts reported since.
Assert.Equal(index with { ItemDone = 2 }, run.Published[2].Detail);
Assert.Equal(index with { ItemDone = 2 }, run.Context.Detail);
}
[Test]
public async Task ADroppedReportGoesOutWithThePersistThatFallsDue()
{
await using var run = await StartAsync();
await run.Context.ReportAsync(1, 100);
run.Time.Advance(TimeSpan.FromSeconds(4.8));
await run.Context.ReportAsync(2, 100);
Assert.Equal(0L, (await run.StoredAsync()).ProgressDone);
run.Time.Advance(TimeSpan.FromSeconds(0.2));
// Too soon for a publish, but the persist falls due: it shows what it saves.
await run.Context.ReportAsync(3, 100);
Assert.SequenceEqual([1L, 2L, 3L], run.Published.Select(p => p.Done));
Assert.Equal(3L, (await run.StoredAsync()).ProgressDone);
}
[Test]
public async Task ProgressIsSavedAtMostEveryCheckpointIntervalAndAtEachCheckpoint()
{
await using var run = await StartAsync();
for (var i = 1; i <= 50; i++)
{
await run.Context.ReportAsync(i, 100);
run.Time.Advance(TimeSpan.FromMilliseconds(99));
}
Assert.Equal(0L, (await run.StoredAsync()).ProgressDone);
run.Time.Advance(TimeSpan.FromMilliseconds(50));
await run.Context.ReportAsync(51, 100);
Assert.Equal(51L, (await run.StoredAsync()).ProgressDone);
var published = run.Published.Count;
// A checkpoint is saved at once; it goes out as any report would.
run.Time.Advance(Tick);
await run.Context.CheckpointAsync("52", 52, 100);
var stored = await run.StoredAsync();
Assert.Equal((52L, "52"), (stored.ProgressDone, stored.Checkpoint));
Assert.Null(stored.Detail);
Assert.Equal(published, run.Published.Count);
var verify = new JobDetail(JobStep.Verify, "Harbour sunset", 1, 9, 1, 3, JobPartUnit.Sequence);
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));
Assert.Equal(verify, run.Published[^1].Detail);
// A checkpoint without a detail keeps it.
run.Time.Advance(Tick);
await run.Context.CheckpointAsync("54", 54, 100);
Assert.Equal(verify, (await run.StoredAsync()).Detail);
}
[Test]
public async Task TheRateIsTheSameUnderThePublishThrottle()
{
await using var run = await StartAsync();
// 100 photos a second for ten seconds, every photo reported.
for (var i = 1; i <= 1000; i++)
{
await run.Context.ReportAsync(i, 2000);
run.Time.Advance(Tick);
}
Assert.True(run.Published.Count <= 22, $"{run.Published.Count} publishes");
var last = run.Published[^1];
Assert.Approximately(100, last.ItemsPerSecond!.Value, 0.5);
Assert.Approximately((2000 - last.Done) / 100.0, last.Eta!.Value.TotalSeconds, 0.1);
}
[Test]
public async Task ItemCountsWithoutADetailAreAPhotoPass()
{
await using var run = await StartAsync();
Assert.Null(run.Context.Detail);
await run.Context.ReportItemAsync(1, 10, 3, 9);
Assert.Equal(new JobDetail(JobStep.Process, null, 3, 9), run.Context.Detail);
Assert.Equal(run.Context.Detail, run.Published.Single().Detail);
// A plain report keeps the detail and drops the old free text.
await run.Context.ReportAsync(2, 10, "IMG_0001.CR3");
await run.Context.ReportAsync(3, 10);
Assert.Null(run.Context.Message);
Assert.Equal(new JobDetail(JobStep.Process, null, 3, 9), run.Context.Detail);
}
[Test]
public async Task ADroppedReportAllocatesNothing()
{
await using var run = await StartAsync();
var thumbs = new JobDetail(JobStep.Thumbs, "Harbour sunset", 0, 3600, 2, 7, JobPartUnit.Sequence);
await run.Context.ReportAsync(1, 1_000_000, thumbs);
var job = run.Context;
var dropped = 0;
for (var i = 0; i < 200; i++) dropped += Drop(job, thumbs, i) ? 1 : 0;
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 20_000; i++) dropped += Drop(job, thumbs, i) ? 1 : 0;
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
Assert.Equal(20_200, dropped);
Assert.Equal(0L, allocated);
Assert.Count(1, run.Published);
}
[Test]
public async Task TheEngineSendsAndSavesTheDetail()
{
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(), "jobs.db")), context.Cancellation);
var verify = new JobDetail(JobStep.Verify, "Harbour sunset", 5, 9, 1, 2, JobPartUnit.Sequence);
var handler = new CallbackHandler(JobKind.Verify, async c =>
{
await c.CheckpointAsync("1", 1, 2, verify);
await c.ReportAsync(2, 2);
});
await using var engine = new JobEngine(db, [handler], new JobEngineOptions { Workers = 1, WorkerId = "t" });
var published = new List<JobProgressInfo>();
engine.Progress += p =>
{
lock (published) published.Add(p);
};
await engine.StartAsync(context.Cancellation);
var job = await engine.EnqueueAsync(JobKind.Verify, [Guid.NewGuid()], cancellationToken: context.Cancellation);
var until = DateTime.UtcNow.AddSeconds(15);
Job? done = null;
while (DateTime.UtcNow < until && (done = await db.Jobs.GetAsync(job.Id, context.Cancellation))?.State != JobState.Done) await Task.Delay(20, context.Cancellation);
Assert.Equal(JobState.Done, done?.State);
Assert.Equal(verify, done!.Detail);
lock (published) Assert.SequenceEqual([verify, verify], published.Select(p => p.Detail));
}
/// <summary>One report dropped by the throttle: no new step, no completed count, no time passed.</summary>
private static bool Drop(JobContext job, JobDetail detail, int i)
{
var item = job.ReportItemAsync(2 + i, 1_000_000, i, 3600);
var full = job.ReportAsync(3 + i, 1_000_000, detail);
return item.IsCompletedSuccessfully && full.IsCompletedSuccessfully;
}
private async Task<Run> StartAsync()
{
var time = new ManualTime();
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(), "jobs.db")), context.Cancellation);
var engine = new JobEngine(db, [], new JobEngineOptions { WorkerId = "t", Time = time });
var run = new Run(db, engine, time);
engine.Progress += run.Published.Add;
await db.Jobs.EnqueueAsync(new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Verify, State = JobState.Queued, Created = DateTimeOffset.UtcNow },
context.Cancellation);
var claimed = Assert.NotNull(await db.Jobs.ClaimNextAsync("t", null, context.Cancellation));
run.Context = new JobContext(engine, claimed, context.Cancellation);
return run;
}
private sealed class Run(ChronosDatabase db, JobEngine engine, ManualTime time) : IAsyncDisposable
{
public ManualTime Time { get; } = time;
public JobContext Context { get; set; } = null!;
public List<JobProgressInfo> Published { get; } = [];
public async Task<Job> StoredAsync() => (await db.Jobs.GetAsync(Context.Job.Id))!;
public async ValueTask DisposeAsync()
{
await engine.DisposeAsync();
await db.DisposeAsync();
}
}
private sealed class CallbackHandler(JobKind kind, Func<JobContext, Task> run) : IJobHandler
{
public JobKind Kind => kind;
public Task RunAsync(JobContext context) => run(context);
}
}
@@ -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,5 +1,6 @@
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Jobs;
@@ -29,4 +30,72 @@ public sealed class JobWireTests
Assert.Equal(names.Count, names.Distinct(StringComparer.Ordinal).Count());
Assert.False(JobWire.TryParseKind("workspace-teleport", out _));
}
/// <summary>Steps and units are stored and sent by name, appended only: these values and names are pinned once shipped.</summary>
[Theory]
[Case(JobStep.None, 0, "none")]
[Case(JobStep.List, 1, "list")]
[Case(JobStep.Verify, 4, "verify")]
[Case(JobStep.CopyPhoto, 11, "copy-photo")]
[Case(JobStep.CopyOriginal, 13, "copy-original")]
[Case(JobStep.FollowUps, 22, "follow-ups")]
[Case(JobStep.Process, 23, "process")]
public void StepsKeepTheirValueAndName(JobStep step, int value, string name)
{
Assert.Equal(value, (int)step);
Assert.Equal(name, JobWire.Step(step));
Assert.True(JobWire.TryParseStep(name, out var parsed), name);
Assert.Equal(step, parsed);
}
[Test]
public void EveryStepAndUnitHasItsOwnName()
{
var steps = Enum.GetValues<JobStep>().Select(JobWire.Step).ToList();
Assert.Equal(steps.Count, steps.Distinct(StringComparer.Ordinal).Count());
Assert.SequenceEqual(["none", "sequence", "folder", "render", "entry", "step"], Enum.GetValues<JobPartUnit>().Select(JobWire.PartUnit));
Assert.False(JobWire.TryParseStep("teleport", out _));
Assert.False(JobWire.TryParsePartUnit(null, out _));
}
[Test]
public void ADetailCrossesTheWireAndBack()
{
var detail = new JobDetail(JobStep.CopyOriginal, "2024/2024-09-27 Harbour sunset", 1240, 3600, 12, 340, JobPartUnit.Folder);
var dto = JobWire.Detail(detail)!;
Assert.Equal(new JobDetailDto("copy-original", "2024/2024-09-27 Harbour sunset", 1240, 3600, 12, 340, "folder"), dto);
Assert.Equal(detail, JobWire.FromDto(dto));
// A unit of none is left out; nothing is none.
Assert.Null(JobWire.Detail(new JobDetail(JobStep.Backup))!.PartUnit);
Assert.Null(JobWire.Detail(null));
Assert.Null(JobWire.FromDto((JobDetailDto?)null));
// A newer peer's step or unit reads as none and its counts stay; nonsense counts read as 0.
Assert.Equal(new JobDetail(JobStep.None, "x", 0, 9, 2, 0), JobWire.FromDto(new JobDetailDto("teleport", "x", -4, 9, 2, -1, "galaxy")));
Assert.Equal(new JobDetail(JobStep.None), JobWire.FromDto(new JobDetailDto(null!)));
}
[Test]
public void AnItemIsCutToItsLongestLengthWithoutSplittingACharacter()
{
var plain = new string('a', JobDetail.MaxItemLength + 40);
Assert.Equal(JobDetail.MaxItemLength, new JobDetail(JobStep.Index, plain).Item!.Length);
// A pair whose high half would be the last kept character goes whole.
var emoji = new string('a', JobDetail.MaxItemLength - 1) + "\U0001F4F7" + "tail";
var cut = new JobDetail(JobStep.Index, emoji).Item!;
Assert.Equal(JobDetail.MaxItemLength - 1, cut.Length);
Assert.False(char.IsHighSurrogate(cut[^1]));
Assert.Equal(JobDetail.MaxItemLength, (new JobDetail(JobStep.Index) with { Item = plain }).Item!.Length);
Assert.Equal(JobDetail.MaxItemLength, JobWire.FromDto(new JobDetailDto("index", plain))!.Item!.Length);
Assert.Equal("short", new JobDetail(JobStep.Index, "short").Item);
}
[Test]
public void AServerJobBringsItsDetail()
{
var dto = new JobDto(Guid.NewGuid(), "verify", [], "Archive", "paused", "normal", 4, 10, null, null, null, null, 1, null, DateTimeOffset.UtcNow, null, null,
Detail: new JobDetailDto("verify", "Harbour sunset", 812, 2400, 3, 41, "sequence"));
Assert.Equal(new JobDetail(JobStep.Verify, "Harbour sunset", 812, 2400, 3, 41, JobPartUnit.Sequence), JobWire.FromDto(dto)!.Detail);
Assert.Null(JobWire.FromDto(dto with { Detail = null })!.Detail);
}
}
@@ -139,6 +139,24 @@ public abstract class MigrationTests(TestContext context) : RepositoryTest(conte
Assert.Equal(0L, await session.ScalarAsync<long>("SELECT bytes FROM render_copies WHERE path = $1", ["C:/Videos/b"], Ct));
}
[Test]
public async Task TheProgressDetailColumnJoinsAnIndexOfTheVideosRelease()
{
var database = await OpenDatabaseAsync();
var all = MigrationRunner.Load(Dialect);
Assert.Equal(10, await MigrationRunner.MigrateAsync(database, [.. all.Where(m => m.Version <= 10)], Ct));
var id = Guid.CreateVersion7();
await using (var session = await database.OpenAsync(Ct))
await session.ExecuteAsync("INSERT INTO jobs (id, kind, state, priority, created) VALUES ($1, $2, $3, $4, $5)",
[id, (int)JobKind.Verify, (int)JobState.Paused, (int)JobPriority.Normal, DateTimeOffset.UtcNow], Ct);
Assert.Equal(11, all.Single(m => m.Name == "job_progress_detail").Version);
Assert.Equal(all[^1].Version, await MigrationRunner.MigrateAsync(database, Ct));
await using var after = await database.OpenAsync(Ct);
// No backfill: a job of 1.0 has no detail.
Assert.Equal(1L, await after.ScalarAsync<long>("SELECT count(*) FROM jobs WHERE id = $1 AND progress_detail IS NULL", [id], Ct));
}
[Test]
public async Task AppliesOnlyPendingMigrations()
{
@@ -0,0 +1,82 @@
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Export;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Tests.Jobs;
using Chronos.Testing;
namespace Chronos.Data.Tests.Processing;
/// <summary>What the analysis and render jobs say they are doing (owner review 5, #65), as the job's progress detail.</summary>
[Category("processing")]
public sealed class ProcessingProgressDetailTests(TestContext context)
{
private const int Frames = 12;
private static SyntheticSequence Scene() => SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = Frames, StartEv = 0.5, EndEv = -0.5 });
private static async Task<(DetailRecorder Recorder, JobEngine Engine)> StartAsync(ProcessingFixture fx)
{
var recorder = new DetailRecorder();
var engine = recorder.Engine(fx.Db, fx.Processing.CreateJobHandlers());
await engine.StartAsync(fx.Ct);
return (recorder, engine);
}
private static async Task<Guid> RunAsync(ProcessingFixture fx, JobEngine engine, ArchiveJobRequest request)
{
var job = await engine.EnqueueAsync(request, cancellationToken: fx.Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
return job.Id;
}
[Test]
public async Task AnAnalysisNamesEachSequenceAndADeepOneCountsItsPhotos()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var first = await fx.AddAsync(Scene(), "First");
var second = await fx.AddAsync(Scene(), "Second");
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var light = await RunAsync(fx, engine, ProcessingJobs.LightAnalysis([first.Id, second.Id], "both"));
var details = recorder.Details(light);
Assert.True(details.All(d => d.Step == JobStep.Analyse && d.PartUnit == JobPartUnit.Sequence && d.Parts == 2 && d.ItemTotal == 0), string.Join("; ", details));
Assert.SequenceEqual([(1, first.DisplayTitle), (2, second.DisplayTitle)], details.Select(d => (d.Part, d.Item!)));
var deep = await RunAsync(fx, engine, ProcessingJobs.DeepAnalysis([first.Id]));
details = recorder.Details(deep);
Assert.True(details.All(d => d.Step == JobStep.Analyse && d.Item == first.DisplayTitle && d.Part == 1 && d.Parts == 1 && d.ItemTotal == Frames),
string.Join("; ", details));
Assert.True(details.Max(d => d.ItemDone) > 0, string.Join("; ", details));
Assert.True(details.All(d => d.ItemDone <= Frames));
}
[Test]
public async Task ARenderPreparesEncodesThenVerifiesWithoutTextInTheDetail()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var mjpeg = new ExportSettings
{
Preset = new Auto<string>().WithManual("mjpeg-avi"),
Overrides = new ExportOverrides { Width = 96, Height = 64 },
NameTemplate = "clip-{codec}",
};
var id = await RunAsync(fx, engine, ProcessingJobs.Render(sequence, mjpeg, 96, 64));
Assert.SequenceEqual([JobStep.Analyse, JobStep.Encode, JobStep.Verify], recorder.Steps(id));
var details = recorder.Details(id);
Assert.Equal(new JobDetail(JobStep.Analyse, sequence.DisplayTitle), details[0]);
var encode = details.Where(d => d.Step == JobStep.Encode).ToList();
Assert.True(encode.All(d => d.Item == sequence.DisplayTitle && d.Parts == 0 && d.ItemDone <= d.ItemTotal), string.Join("; ", encode));
Assert.True(encode.Max(d => d.ItemDone) > 0, string.Join("; ", encode));
Assert.Equal(new JobDetail(JobStep.Verify, "clip-MJPEG.avi"), details[^1]);
}
}
@@ -30,12 +30,52 @@ public abstract class JobRepositoryTests(TestContext context) : RepositoryTest(c
Started = TestData.Now.AddMinutes(1),
Finished = TestData.Now.AddMinutes(2),
ScheduleId = Guid.CreateVersion7(),
Detail = new JobDetail(JobStep.Encode, "Harbour sunset", 5, 10, 1, 2, JobPartUnit.Render),
};
await db.Jobs.EnqueueAsync(job, Ct);
var read = Assert.NotNull(await db.Jobs.GetAsync(job.Id, Ct));
Assert.SequenceEqual(job.TargetIds, read.TargetIds);
Assert.Equal(job with { TargetIds = read.TargetIds }, read);
Assert.Null((await db.Jobs.GetAsync((await EnqueueAsync(db, TestData.Job())).Id, Ct))!.ScheduleId);
var plain = (await db.Jobs.GetAsync((await EnqueueAsync(db, TestData.Job())).Id, Ct))!;
Assert.Null(plain.ScheduleId);
Assert.Null(plain.Detail);
}
[Test]
public async Task TheProgressDetailIsSavedWithTheProgressAndListedWithTheJob()
{
var db = await OpenChronosAsync();
var job = TestData.Job(JobKind.Verify);
await db.Jobs.EnqueueAsync(job, Ct);
await db.Jobs.ClaimNextAsync("w", cancellationToken: Ct);
var detail = new JobDetail(JobStep.Verify, "Harbour sunset · 2024", 812, 2400, 3, 41, JobPartUnit.Sequence);
Assert.True(await db.Jobs.UpdateProgressAsync(job.Id, 4, 10, null, null, "cursor:4", null, detail, Ct));
Assert.Equal(detail, (await db.Jobs.GetAsync(job.Id, Ct))!.Detail);
// Lists read it too: a paused job tells where it stopped.
Assert.SequenceEqual([detail], (await db.Jobs.ListBriefAsync(JobState.Running, null, cancellationToken: Ct)).Items.Select(j => j.Detail));
// Without a detail the column is cleared; a node's progress keeps or replaces it.
Assert.True(await db.Jobs.UpdateProgressAsync(job.Id, 5, 10, null, null, "cursor:5", null, Ct));
Assert.Null((await db.Jobs.GetAsync(job.Id, Ct))!.Detail);
var node = new JobDetail(JobStep.Encode, null, 120, 3600);
Assert.True(await db.Jobs.UpdateNodeProgressAsync(job.Id, "w", 6, 10, null, null, null, node, Ct));
Assert.True(await db.Jobs.UpdateNodeProgressAsync(job.Id, "w", 7, 10, null, null, "line", Ct));
Assert.Equal(node, (await db.Jobs.GetAsync(job.Id, Ct))!.Detail);
Assert.True(await db.Jobs.UpdateNodeProgressAsync(job.Id, "w", 8, 10, null, null, null, null, Ct));
Assert.Null((await db.Jobs.GetAsync(job.Id, Ct))!.Detail);
// A cell this build cannot read is no detail, never an error.
foreach (var unreadable in new[] { "not json", "42", "[]", "{\"step\": 7}" })
{
await using (var session = await db.Database.OpenAsync(Ct))
await session.ExecuteAsync("UPDATE jobs SET progress_detail = $1 WHERE id = $2", [unreadable, job.Id], Ct);
Assert.Null((await db.Jobs.GetAsync(job.Id, Ct))!.Detail);
}
// One of a newer build: its step and unit read as none, the counts stay.
await using (var session = await db.Database.OpenAsync(Ct))
await session.ExecuteAsync("UPDATE jobs SET progress_detail = $1 WHERE id = $2",
["""{"step":"teleport","itemDone":3,"itemTotal":9,"part":2,"parts":4,"partUnit":"galaxy","future":true}""", job.Id], Ct);
Assert.Equal(new JobDetail(JobStep.None, null, 3, 9, 2, 4), (await db.Jobs.GetAsync(job.Id, Ct))!.Detail);
}
[Test]
@@ -0,0 +1,58 @@
using Chronos.Core.IO;
using Chronos.Data.Sync;
using Chronos.Data.Tests.Homes;
using Chronos.Testing;
namespace Chronos.Data.Tests.Sync;
/// <summary>Where the proxies of a server's sequence live (owner review 5, #66): its home in the cache, else where an earlier layout left them.</summary>
[Category("sync")]
public sealed class ProxyCacheTests(TestContext context)
{
private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
[Test]
public void WithoutAServersRootTheLayoutIs10s()
{
var root = context.CreateTempDirectory("proxies");
var remote = Guid.CreateVersion7();
var cache = new ProxyCache(root);
Assert.Equal(Path.Combine(root, HomeFolders.AddressHash(HomeFixtures.Nas), remote.ToString("N")), cache.Folder(HomeFixtures.Nas, remote));
}
[Test]
public void ANewSequenceGoesToItsServersHomeAndAnOldOneIsReadWhereItIs()
{
var cacheRoot = context.CreateTempDirectory("cache");
var (legacyRoot, servers) = (Path.Combine(cacheRoot, "proxies"), Path.Combine(cacheRoot, "servers"));
var identity = new ServerIdentity([new KnownServerKey(Id, [HomeFixtures.Nas])]);
var cache = new ProxyCache(legacyRoot, servers, () => identity);
var idKey = ServerIdentity.IdKey(Id);
var fresh = Guid.CreateVersion7();
Assert.Equal(Path.Combine(servers, Id.ToString("N"), "proxies", fresh.ToString("N")), cache.Folder(idKey, fresh));
Assert.Equal(cache.Folder(idKey, fresh), cache.Folder(HomeFixtures.Nas, fresh), "an alias names the same home");
// A sequence cached by 1.0 under the address is used where it is until it is moved.
var old = Guid.CreateVersion7();
var legacy = HomeFixtures.LegacyProxies(cacheRoot, HomeFixtures.Nas, old);
Assert.Equal(legacy, cache.Folder(idKey, old));
Assert.True(cache.Exists(idKey, old));
// In the home of the address (sorted before the server announced its id): used there too.
var sorted = Guid.CreateVersion7();
var byAddress = Path.Combine(servers, HomeFolders.ServerFolder(HomeFixtures.Nas), "proxies", sorted.ToString("N"));
Directory.CreateDirectory(byAddress);
Assert.Equal(byAddress, cache.Folder(idKey, sorted));
// Once in its home, that is where it is.
var home = Path.Combine(servers, Id.ToString("N"), "proxies", old.ToString("N"));
Directory.CreateDirectory(Path.GetDirectoryName(home)!);
Directory.Move(legacy, home);
Assert.Equal(home, cache.Folder(HomeFixtures.Nas, old));
// A server known by its address only has an address home.
var other = Guid.CreateVersion7();
Assert.Equal(Path.Combine(servers, HomeFolders.ServerFolder(HomeFixtures.Other), "proxies", other.ToString("N")), cache.Folder(HomeFixtures.Other, other));
}
}
@@ -0,0 +1,84 @@
using Chronos.Core.IO;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Sync;
/// <summary>How the desktop names a server (owner review 5, #66): by its announced id, its address keys kept as aliases.</summary>
[Category("sync")]
public sealed class ServerIdentityTests
{
private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
private static ServerInfo Info(Guid? id) => new("Studio NAS", "1.1.0", 1, [], null, [], new ServerLimits(1, 1), null, null, id);
[Test]
public void AServerThatAnnouncesAnIdIsKeyedByIt()
{
var key = ServerIdentity.Key(Info(Id), new Uri("https://NAS.local:8443/"));
Assert.Equal("id:" + Id.ToString("N"), key);
Assert.True(ServerIdentity.IsIdKey(key));
Assert.Equal(Id, ServerIdentity.IdOf(key));
// Another address of the same server: the same key.
Assert.Equal(key, ServerIdentity.Key(Info(Id), new Uri("https://192.168.1.5:8443")));
}
[Test]
public void AnOlderServerKeepsItsAddressKey()
{
var address = new Uri("https://NAS.local:8443/");
Assert.Equal("https://nas.local:8443", ServerIdentity.Key(Info(null), address));
Assert.Equal(SyncService.ServerKey(address), ServerIdentity.Key((ServerInfo?)null, address));
Assert.Equal(SyncService.ServerKey(address), ServerIdentity.Key(Guid.Empty, address));
Assert.False(ServerIdentity.IsIdKey(SyncService.ServerKey(address)));
}
[Test]
public void AliasesNameTheServerOfTheirId()
{
var identity = new ServerIdentity([new KnownServerKey(Id, ["https://nas.local:8443", "https://192.168.1.5:8443"])]);
var key = ServerIdentity.IdKey(Id);
Assert.Equal(key, identity.Canonical("https://NAS.local:8443"));
Assert.Equal(key, identity.Canonical(key.ToUpperInvariant()));
Assert.Equal("https://other:1", identity.Canonical("https://other:1"));
Assert.True(identity.Same("https://nas.local:8443", "https://192.168.1.5:8443"));
Assert.True(identity.Same(key, "https://192.168.1.5:8443"));
Assert.False(identity.Same(key, "https://other:1"));
Assert.True(identity.Same(null, null));
Assert.False(identity.Same(key, null));
Assert.Equal(Id.ToString("N"), identity.FolderName("https://192.168.1.5:8443"));
Assert.Equal(HomeFolders.ServerFolder("https://other:1"), identity.FolderName("https://other:1"));
Assert.SequenceEqual(new[] { key, "https://nas.local:8443", "https://192.168.1.5:8443" }, identity.KeysOf("https://192.168.1.5:8443"));
Assert.SequenceEqual(new[] { "https://other:1" }, identity.KeysOf("https://other:1"));
Assert.Equal(2, identity.AliasesOf(Id).Count);
// Without the table every key is its own.
Assert.False(ServerIdentity.None.Same(key, "https://nas.local:8443"));
}
[Test]
public void AnAddressChangeKeepsTheKeyOnceTheAliasIsKnown()
{
var identity = new ServerIdentity([new KnownServerKey(Id, ["https://nas.local:8443"])]);
var widened = identity.With(Id, "https://nas.local:9443");
Assert.True(widened.Same("https://nas.local:8443", "https://nas.local:9443"));
Assert.Same(widened, widened.With(Id, "HTTPS://nas.local:9443"));
Assert.False(identity.Same("https://nas.local:8443", "https://nas.local:9443"), "the table it came from is unchanged");
var other = Guid.CreateVersion7();
Assert.Equal(ServerIdentity.IdKey(other), widened.With(other, "https://second:1").Canonical("https://second:1"));
// An address two ids claim stays with the first one listed.
var clash = new ServerIdentity([new KnownServerKey(Id, ["https://x"]), new KnownServerKey(other, ["https://x"])]);
Assert.Equal(ServerIdentity.IdKey(Id), clash.Canonical("https://x"));
}
[Test]
public void TheArchiveIdOfAnyAliasIsTheServers()
{
string[] keys = [ServerIdentity.IdKey(Id), "https://nas.local:8443"];
Assert.True(ServerProjectHome.IsArchiveIdOf(ServerProjectHome.ArchiveIdOf("https://nas.local:8443"), keys));
Assert.True(ServerProjectHome.IsArchiveIdOf(ServerProjectHome.ArchiveIdOf(keys[0]), keys));
Assert.False(ServerProjectHome.IsArchiveIdOf(ServerProjectHome.ArchiveIdOf("https://other:1"), keys));
}
}
@@ -0,0 +1,102 @@
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;
/// <summary>A server's links move from its address key to its id key (owner review 5, #66), the newer row winning a clash.</summary>
[Category("sync")]
public abstract class SyncLinkRekeyTests(TestContext context) : RepositoryTest(context)
{
private const string Address = "https://nas.local:8443";
private static readonly string IdKey = ServerIdentity.IdKey(Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01"));
private static SyncLink Link(string server, Guid remoteId, Guid? localId, DateTimeOffset? synced, string title = "Harbour") => new()
{
Server = server,
RemoteId = remoteId,
LocalId = localId,
Title = title,
RemoteUpdatedAt = TestData.Now,
SyncedAt = synced,
};
[Test]
public async Task TheLinksOfAnAddressMoveToTheIdAndTheNewerRowWinsAClash()
{
var db = await OpenChronosAsync();
var archive = TestData.Archive();
await db.Archives.UpsertAsync(archive, Ct);
var (a, b, c) = (TestData.Sequence(archive.Id), TestData.Sequence(archive.Id), TestData.Sequence(archive.Id));
foreach (var sequence in new[] { a, b, c }) await db.Sequences.UpsertAsync(sequence, Ct);
var store = new SyncLinkStore(db);
var (plain, sameRemote, sameLocal, stale) = (Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7());
// Only under the address: it moves.
await store.UpsertAsync(Link(Address, plain, a.Id, TestData.Now), Ct);
// Under both keys for one server sequence: the address's row is newer, so it replaces the id's.
await store.UpsertAsync(Link(Address, sameRemote, null, TestData.Now.AddHours(2), "newer"), Ct);
await store.UpsertAsync(Link(IdKey, sameRemote, null, TestData.Now.AddHours(1), "older"), Ct);
// Both keys link local copy b to different server sequences: the id's row is newer, so the address's goes.
await store.UpsertAsync(Link(Address, sameLocal, b.Id, TestData.Now), Ct);
await store.UpsertAsync(Link(IdKey, Guid.CreateVersion7(), b.Id, TestData.Now.AddDays(1)), Ct);
// Never compared under the address, compared under the id: the id's stays.
await store.UpsertAsync(Link(Address, stale, c.Id, null), Ct);
await store.UpsertAsync(Link(IdKey, stale, null, TestData.Now), Ct);
var (moved, dropped) = await store.RekeyAsync(Address, IdKey, Ct);
Assert.Equal((2, 3), (moved, dropped));
Assert.Empty(await store.ListAsync(Address, Ct));
var links = (await store.ListAsync(IdKey, Ct)).ToDictionary(l => l.RemoteId);
Assert.Equal(4, links.Count);
Assert.Equal(a.Id, links[plain].LocalId);
Assert.Equal("newer", links[sameRemote].Title);
Assert.False(links.ContainsKey(sameLocal));
Assert.Null(links[stale].LocalId);
Assert.Equal(b.Id, Assert.NotNull(await store.FindByLocalAsync(IdKey, b.Id, Ct)).LocalId);
// Again: nothing left to move; and a key onto itself does nothing.
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)
{
protected override Backend Backend => Backend.SqliteMemory;
}
public sealed class PostgresSyncLinkRekeyTests(TestContext context) : SyncLinkRekeyTests(context)
{
protected override Backend Backend => Backend.Postgres;
}
@@ -0,0 +1,172 @@
using Chronos.Core.IO;
using Chronos.Core.Localization;
using Chronos.Core.Project;
using Chronos.Data.Sync;
using Chronos.Data.Tests.Homes;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.Data.Tests.Workspaces;
/// <summary>The workspace split into one store per home (owner review 5, #66).</summary>
[Category("workspace")]
public sealed class WorkspaceHomesTests(TestContext context)
{
private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
[Test]
public void ANewWorkspaceIsSplitAndEachHomeGetsItsStore()
{
var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
var homes = new WorkspaceHomes(root, new ServerIdentity([new KnownServerKey(Id, [HomeFixtures.Nas])]));
Assert.True(homes.IsSplit);
Assert.True(WorkspaceHomes.IsSplitRoot(root));
Assert.Equal((WorkspaceHomes.ParentFormatVersion, WorkspaceHomes.HomesLayout), (homes.Manifest.FormatVersion, homes.Manifest.Layout));
Assert.Empty(homes.Homes());
// A 1.0 Chronos (store format 1) refuses the parent: it never shows the workspace empty.
Assert.Throws<InvalidDataException>(() => new WorkspaceStore(root));
var local = homes.StoreFor(HomeFixtures.Local());
Assert.Equal(Path.Combine(homes.Root, "local"), local.Root);
var server = homes.StoreFor(HomeFixtures.Server(HomeFixtures.Nas));
Assert.Equal(Path.Combine(homes.Root, "servers", Id.ToString("N")), server.Root);
Assert.Same(server, homes.StoreFor(HomeFixtures.Server(ServerIdentity.IdKey(Id))));
var record = Assert.NotNull(ServerHomeRecord.Read(server.Root));
Assert.Equal((ServerIdentity.IdKey(Id), (Guid?)Id), (record.Key, record.Id));
var other = homes.StoreFor(HomeFixtures.Server(HomeFixtures.Other));
Assert.Equal(Path.Combine(homes.Root, "servers", HomeFolders.ServerFolder(HomeFixtures.Other)), other.Root);
Assert.Equal(HomeFixtures.Other, Assert.NotNull(ServerHomeRecord.Read(other.Root)).Address);
Assert.NotEqual(local.Id, server.Id);
var described = Assert.NotNull(homes.Describe(HomeFixtures.Nas, "Studio NAS", HomeFixtures.Nas, "AA:BB", DateTimeOffset.UtcNow));
Assert.Equal(("Studio NAS", HomeFixtures.Nas, "AA:BB"), (described.Name, described.Address, described.TlsFingerprint));
Assert.Equal(record.FirstSeen, described.FirstSeen);
var listed = homes.Homes();
Assert.Equal(3, listed.Count);
Assert.True(listed[0].IsLocal);
Assert.Contains(listed, h => h.ServerKey == ServerIdentity.IdKey(Id) && h.Server?.Name == "Studio NAS");
}
[Test]
public void ProjectsAreFoundInEveryHomeAndTheTrashIsListedPerHome()
{
var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
var homes = new WorkspaceHomes(root);
var a = HomeFixtures.Project(homes.StoreFor(HomeFixtures.Local()).Root, HomeFixtures.Local());
var serverHome = HomeFixtures.Server(HomeFixtures.Nas);
var b = HomeFixtures.Project(homes.StoreFor(serverHome).Root, serverHome);
Assert.Equal(homes.LocalRoot, Path.GetDirectoryName(Assert.NotNull(homes.Find(a)).Folder));
Assert.Equal(homes.ServerRoot(HomeFixtures.Nas), Path.GetDirectoryName(Assert.NotNull(homes.Find(b)).Folder));
Assert.Null(homes.Find(Guid.CreateVersion7()));
Assert.Equal(2, homes.List().Count);
Assert.Equal(2, homes.ListBundles().Count);
HomeFixtures.TrashEntry(homes.ServerRoot(HomeFixtures.Nas), b, serverHome);
var trash = homes.Trash();
Assert.Equal(2, trash.Count);
Assert.Equal(1, trash.Sum(t => t.Entries.Count));
}
[Test]
public void A10WorkspaceStaysOneStoreUntilItIsSorted()
{
var root = HomeFixtures.LegacyWorkspace(context.CreateTempDirectory("ws"));
var a = HomeFixtures.Project(root, HomeFixtures.Local());
var homes = new WorkspaceHomes(root);
Assert.False(homes.IsSplit);
Assert.Equal(1, homes.Manifest.FormatVersion);
Assert.Equal(homes.Root, homes.StoreFor(HomeFixtures.Server(HomeFixtures.Nas)).Root);
Assert.Equal(homes.Root, homes.Local.Root);
Assert.True(Assert.NotNull(homes.Find(a)).Exists);
Assert.True(homes.Homes().Single().IsLegacy);
Assert.False(Directory.Exists(homes.LocalRoot), "nothing is made beside the 1.0 projects");
// A folder with projects and no manifest is a 1.0 workspace too, never a new split one.
var bare = Path.Combine(context.CreateTempDirectory("bare"), "workspace");
HomeFixtures.Project(bare, HomeFixtures.Local());
Assert.False(new WorkspaceHomes(bare).IsSplit);
}
[Test]
public void AProjectNotSortedYetIsListedWhereItIs()
{
var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
_ = new WorkspaceHomes(root);
var left = HomeFixtures.Project(root, HomeFixtures.Local());
var homes = new WorkspaceHomes(root);
Assert.True(homes.IsSplit);
Assert.Equal(homes.Root, Path.GetDirectoryName(Assert.NotNull(homes.Find(left)).Folder));
Assert.True(homes.Homes()[0].IsLegacy);
Assert.Equal(homes.LocalRoot, homes.Local.Root);
}
[Test]
public void AJobQueuedBeforeTheSortingFindsItsProjectInItsHome()
{
var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
var homes = new WorkspaceHomes(root);
var home = HomeFixtures.Server(HomeFixtures.Nas);
var id = HomeFixtures.Project(homes.ServerRoot(HomeFixtures.Nas), home);
_ = homes.StoreFor(home);
// Queued with the 1.0 folder (the parent): found in the server's home.
Assert.Equal(homes.ServerRoot(HomeFixtures.Nas), WorkspaceJobRoots.Resolve(root, id, null, "Errors.Workspace.NotCheckedOut"));
// Queued with the home of the address, which was re-keyed to the id since.
var rekeyed = Path.Combine(root, "servers", Id.ToString("N"));
Directory.Move(homes.ServerRoot(HomeFixtures.Nas), rekeyed);
Assert.Equal(rekeyed, WorkspaceJobRoots.Resolve(Path.Combine(root, "servers", HomeFolders.ServerFolder(HomeFixtures.Nas)), id, null, "Errors.Workspace.NotCheckedOut"));
// With the parent in use now (Settings › Workspace) and an older folder named.
Assert.Equal(rekeyed, WorkspaceJobRoots.Resolve(Path.Combine(context.CreateTempDirectory("gone"), "workspace"), id, () => root, "Errors.Workspace.NotCheckedOut"));
// While the parent is being moved nothing runs.
File.WriteAllText(Path.Combine(root, WorkspaceMover.JournalFile), "{}");
var moving = Assert.Throws<InvalidOperationException>(() => WorkspaceJobRoots.Resolve(rekeyed, id, null, "Errors.Workspace.NotCheckedOut"));
Assert.Equal(Loc.L("Errors.Workspace.Moving"), moving.Message);
File.Delete(Path.Combine(root, WorkspaceMover.JournalFile));
Assert.Throws<InvalidOperationException>(() => WorkspaceJobRoots.Resolve(root, Guid.CreateVersion7(), null, "Errors.Workspace.NotCheckedOut"));
}
[Test]
public void SameServerGoesThroughTheAliases()
{
var identity = new ServerIdentity([new KnownServerKey(Id, [HomeFixtures.Nas])]);
var options = new WorkspaceJobOptions(new Chronos.Data.Processing.ProcessingOptions(), () => false);
Assert.True(options.IsSameServer("https://NAS.local:8443", HomeFixtures.Nas));
Assert.False(options.IsSameServer(ServerIdentity.IdKey(Id), HomeFixtures.Nas));
var aliased = options with { SameServer = identity.Same };
Assert.True(aliased.IsSameServer(ServerIdentity.IdKey(Id), HomeFixtures.Nas));
Assert.False(aliased.IsSameServer(ServerIdentity.IdKey(Id), HomeFixtures.Other));
}
[Test]
public async Task MovingASplitWorkspaceMovesEveryHome()
{
foreach (var sameVolume in new[] { true, false })
{
var parent = context.CreateTempDirectory("move");
var from = Path.Combine(parent, "workspace");
var homes = new WorkspaceHomes(from);
var serverHome = HomeFixtures.Server(HomeFixtures.Nas);
var ids = new[]
{
HomeFixtures.Project(homes.StoreFor(HomeFixtures.Local()).Root, HomeFixtures.Local()),
HomeFixtures.Project(homes.StoreFor(serverHome).Root, serverHome),
HomeFixtures.Project(homes.StoreFor(HomeFixtures.Server(HomeFixtures.Other)).Root, HomeFixtures.Server(HomeFixtures.Other)),
};
var before = HomeFixtures.Manifest(from);
var to = Path.Combine(parent, "moved");
var mover = new WorkspaceMover(from, to) { SameVolume = sameVolume };
var survey = mover.Survey();
Assert.Equal(3, survey.Projects.Count);
Assert.SequenceEqual(new[] { "local", "servers", WorkspaceStore.ManifestFile }, survey.Entries);
var lines = new List<string>();
await mover.MoveAsync(survey.Fingerprint, log: lines.Add, cancellationToken: context.Cancellation);
Assert.False(Directory.Exists(from), "the old folder went");
var moved = new WorkspaceHomes(to);
Assert.True(moved.IsSplit);
Assert.Equal(3, moved.List().Count);
foreach (var id in ids) Assert.NotNull(moved.Find(id));
Assert.SequenceEqual(before, HomeFixtures.Manifest(to));
Assert.Contains(Loc.L("Archive.Log.WorkspaceMoved", mover.To, 3, survey.Files), lines);
}
}
}
@@ -0,0 +1,117 @@
using System.Text.Json;
using Chronos.Data;
using Chronos.Data.Repositories;
using Chronos.Protocol;
using Chronos.Server.Hosting;
using Chronos.Testing;
namespace Chronos.Server.Tests.Api;
/// <summary>The server's stable id announced by <c>/server/info</c> (owner review 5, #66).</summary>
[Category("server")]
public sealed class ServerInfoIdTests(TestContext context)
{
private static async Task<ServerInfo> InfoAsync(TestServer server)
{
using var response = await server.Client.GetAsync("/api/v1/server/info");
return await response.ReadAsync(ProtocolJson.Default.ServerInfo);
}
[Test]
public async Task TheIdIsMadeOnceAndKeptAcrossRestarts()
{
var root = context.CreateTempDirectory("kept");
void Same(Configuration.ServerOptions o)
{
o.DataPath = Path.Combine(root, "data");
o.ArchivePath = Path.Combine(root, "archive");
}
Guid first;
await using (var server = await TestServer.StartAsync(context, Same))
{
first = Assert.NotNull((await InfoAsync(server)).ServerId);
Assert.NotEqual(Guid.Empty, first);
var stored = await server.Database.Settings.GetJsonAsync(SettingScope.App, null, ServerHost.ServerIdKey, context.Cancellation);
Assert.Equal("\"" + first.ToString("D") + "\"", stored);
}
await using (var again = await TestServer.StartAsync(context, Same))
Assert.Equal((Guid?)first, (await InfoAsync(again)).ServerId);
// Another server (another database) has another id.
await using (var other = await TestServer.StartAsync(context))
Assert.NotEqual((Guid?)first, (await InfoAsync(other)).ServerId);
}
[Test]
public async Task TheIdSurvivesARestoreOfTheIndex()
{
var folder = context.CreateTempDirectory("restore");
Guid id;
string backup;
await using (var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(folder, "chronos.db")), context.Cancellation))
{
id = await ServerHost.ServerIdAsync(db, null, context.Cancellation);
backup = await db.BackupAsync(Path.Combine(folder, "backups"), cancellationToken: context.Cancellation);
}
// A new index (the disk replaced), then the backup put back.
await using var restored = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(folder, "new.db")), context.Cancellation);
await restored.RestoreAsync(backup, context.Cancellation);
Assert.Equal(id, await ServerHost.ServerIdAsync(restored, null, context.Cancellation));
}
[Test]
public async Task AStoredIdThatIsNotOneIsMadeAgain()
{
var folder = context.CreateTempDirectory("damaged");
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(folder, "chronos.db")), context.Cancellation);
foreach (var damaged in new[] { "\"not a guid\"", "\"" + Guid.Empty.ToString("D") + "\"", "42" })
{
await db.Settings.SetJsonAsync(SettingScope.App, null, ServerHost.ServerIdKey, damaged, context.Cancellation);
var made = await ServerHost.ServerIdAsync(db, null, context.Cancellation);
Assert.NotEqual(Guid.Empty, made);
Assert.Equal(made, await ServerHost.ServerIdAsync(db, null, context.Cancellation));
}
}
[Test]
[RequiresEnvironment("CHRONOS_TEST_PG")]
public async Task TheIdIsKeptOnPostgres()
{
var baseConnection = Environment.GetEnvironmentVariable("CHRONOS_TEST_PG")!;
var admin = DatabaseFactory.Open(DatabaseOptions.Postgres(baseConnection));
var schema = "chronos_s_" + Guid.NewGuid().ToString("N")[..16];
await using (var session = await admin.OpenAsync(context.Cancellation))
await session.ExecuteScriptAsync($"CREATE SCHEMA {schema}", context.Cancellation);
try
{
var options = DatabaseOptions.Postgres(baseConnection.TrimEnd(';', ' ') + $";Search Path={schema}");
Guid id;
await using (var db = await ChronosDatabase.OpenAsync(options, context.Cancellation))
id = await ServerHost.ServerIdAsync(db, null, context.Cancellation);
await using (var db = await ChronosDatabase.OpenAsync(options, context.Cancellation))
Assert.Equal(id, await ServerHost.ServerIdAsync(db, null, context.Cancellation));
}
finally
{
await using (var session = await admin.OpenAsync(CancellationToken.None))
await session.ExecuteScriptAsync($"DROP SCHEMA IF EXISTS {schema} CASCADE", CancellationToken.None);
await admin.DisposeAsync();
}
}
[Test]
public void AnOlderClientAndAnOlderServerReadEachOther()
{
var id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
var info = new ServerInfo("Studio NAS", "1.1.0", 1, ["sync"], null, ["jpeg"], new ServerLimits(1, 1), null, 3, id);
var json = JsonSerializer.Serialize(info, ProtocolJson.Default.ServerInfo);
Assert.Contains("\"serverId\":\"" + id.ToString("D") + "\"", json);
Assert.Equal(info.ServerId, Assert.NotNull(JsonSerializer.Deserialize(json, ProtocolJson.Default.ServerInfo)).ServerId);
// A 1.0 server sends no id: it reads as null, and a 1.0 client ignores the member it does not know.
const string older = """{"name":"NAS","version":"1.0.0","apiVersion":1,"capabilities":["sync"],"formats":["jpeg"],"limits":{"maxUploadBytes":1,"chunkSizeBytes":1}}""";
Assert.Null(Assert.NotNull(JsonSerializer.Deserialize(older, ProtocolJson.Default.ServerInfo)).ServerId);
Assert.False(JsonSerializer.Serialize(info with { ServerId = null }, ProtocolJson.Default.ServerInfo).Contains("serverId", StringComparison.Ordinal));
using var parsed = JsonDocument.Parse(json);
Assert.Equal("Studio NAS", parsed.RootElement.GetProperty("name").GetString());
}
}
@@ -0,0 +1,223 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Protocol;
using Chronos.Server.Events;
using Chronos.Server.Jobs;
using Chronos.Server.Tests.Jobs;
using Chronos.Testing;
namespace Chronos.Server.Tests.Events;
/// <summary>
/// What a job does now on the wire (owner review 5, #65): the progress event, the job and a render node's report carry an
/// optional detail, older and newer peers read each other, and the event socket gets a job's progress at most twice a second.
/// </summary>
[Category("server")]
public sealed class ProgressEventTests(TestContext context)
{
private static readonly JobDetailDto Verify = new("verify", "Harbour sunset", 812, 2400, 3, 41, "sequence");
[Test]
public void TheProgressEventCarriesItsDetailInCamelCase()
{
var id = Guid.CreateVersion7();
var json = JsonSerializer.Serialize<ServerEvent>(new JobProgressEvent(id, 3, 10, 2.5, 4, Verify), ProtocolJson.Default.ServerEvent);
Assert.Contains("\"type\":\"jobProgress\"", json);
Assert.Contains("\"detail\":{\"step\":\"verify\",\"item\":\"Harbour sunset\",\"itemDone\":812,\"itemTotal\":2400,\"part\":3,\"parts\":41,\"partUnit\":\"sequence\"}", json);
Assert.Equal(new JobProgressEvent(id, 3, 10, 2.5, 4, Verify), JsonSerializer.Deserialize(json, ProtocolJson.Default.ServerEvent));
// None is left out.
var plain = JsonSerializer.Serialize<ServerEvent>(new JobProgressEvent(id, 3, 10, null, null), ProtocolJson.Default.ServerEvent);
Assert.False(plain.Contains("detail", StringComparison.Ordinal), plain);
}
[Test]
public void AnOlderPeersPayloadReadsWithoutADetail()
{
var id = Guid.CreateVersion7();
var progress = JsonSerializer.Deserialize($$"""{"type":"jobProgress","jobId":"{{id}}","done":1,"total":4,"itemsPerSecond":null,"etaSeconds":null}""",
ProtocolJson.Default.ServerEvent);
Assert.Equal(new JobProgressEvent(id, 1, 4, null, null), progress);
Assert.Equal(new NodeProgress(120, 3600, 40, "encoding"),
JsonSerializer.Deserialize("""{"done":120,"total":3600,"itemsPerSecond":40,"logLine":"encoding"}""", ProtocolJson.Default.NodeProgress));
var job = JsonSerializer.Deserialize($$"""
{"id":"{{id}}","kind":"verify","targetIds":[],"state":"running","priority":"normal","progressDone":1,"progressTotal":4,
"attempts":1,"created":"2026-11-15T10:00:00Z"}
""", ProtocolJson.Default.JobDto)!;
Assert.Null(job.Detail);
Assert.Null(JobWire.FromDto(job)!.Detail);
// A detail of fewer fields (a newer peer's that drops some, or a sparse one) reads with zeros.
Assert.Equal(new JobDetailDto("backup"), JsonSerializer.Deserialize("""{"step":"backup"}""", ProtocolJson.Default.JobDetailDto));
}
[Test]
public void ANewerPayloadReadsIntoAnOlderRecord()
{
var id = Guid.CreateVersion7();
var web = new JsonSerializerOptions(JsonSerializerDefaults.Web);
var json = JsonSerializer.Serialize<ServerEvent>(new JobProgressEvent(id, 3, 10, 2.5, 4, Verify), ProtocolJson.Default.ServerEvent);
Assert.Equal(new JobProgressBefore(id, 3, 10, 2.5, 4), JsonSerializer.Deserialize<JobProgressBefore>(json, web));
var node = JsonSerializer.Serialize(new NodeProgress(120, 3600, 40, "encoding", new JobDetailDto("encode", null, 120, 3600)), ProtocolJson.Default.NodeProgress);
Assert.Equal(new NodeProgressBefore(120, 3600, 40, "encoding"), JsonSerializer.Deserialize<NodeProgressBefore>(node, web));
}
[Test]
public void TheGateLetsAJobsProgressOutTwiceASecondButForNewStepsAndCompletedCounts()
{
var clock = new TimestampClock();
var gate = new ProgressGate(clock);
var job = Guid.CreateVersion7();
Assert.True(gate.Passes(job, 1, 100, JobStep.Verify), "the first");
clock.Advance(TimeSpan.FromMilliseconds(100));
Assert.False(gate.Passes(job, 2, 100, JobStep.Verify));
Assert.True(gate.Passes(job, 3, 100, JobStep.Replace), "a new step");
Assert.True(gate.Passes(job, 100, 100, JobStep.Replace), "a completed count");
Assert.True(gate.Passes(Guid.CreateVersion7(), 1, 100, JobStep.Verify), "another job");
clock.Advance(TimeSpan.FromMilliseconds(300));
Assert.False(gate.Passes(job, 4, 100, JobStep.Replace));
// The engine spaces its reports by the same half second, measured a moment before: they are not dropped.
clock.Advance(TimeSpan.FromMilliseconds(160));
Assert.True(gate.Passes(job, 5, 100, JobStep.Replace), "on time");
Assert.False(gate.Passes(job, 6, 100, JobStep.Replace));
// A job that stops running is forgotten; its next run starts afresh.
gate.Forget(job);
Assert.True(gate.Passes(job, 7, 100, JobStep.Replace), "after a pause");
gate.Forget(job);
Assert.Equal(1, gate.Count);
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()
{
var handler = new DetailJobHandler();
await using var server = await TestServer.StartAsync(context, services: s => s.AddSingleton<IJobHandler>(handler));
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var sequence = await JobApiTests.CreateSequenceAsync(editor);
var hub = server.Services.GetRequiredService<EventHub>();
using var subscription = hub.Subscribe();
var job = await JobApiTests.CreateAsync(editor, "deep-analyse", sequence);
await handler.Started.Task.WaitAsync(TimeSpan.FromSeconds(10));
var running = await JobApiTests.GetAsync(editor, job.Id);
Assert.Equal(DetailJobHandler.Expected, running.Detail);
handler.Release();
var done = await JobApiTests.WaitForAsync(editor, job.Id, "done");
// Kept once the job ends, as it was last saved.
Assert.Equal(DetailJobHandler.Expected with { ItemDone = 4 }, done.Detail);
using (var list = await editor.GetAsync("/api/v1/jobs"))
{
var page = await list.ReadAsync(ProtocolJson.Default.PageJobDto);
Assert.Equal(DetailJobHandler.Expected with { ItemDone = 4 }, page.Items.Single(j => j.Id == job.Id).Detail);
}
var progress = new List<JobProgressEvent>();
while (subscription.Reader.TryRead(out var e))
{
if (e is JobProgressEvent p && p.JobId == job.Id) progress.Add(p);
}
Assert.SequenceEqual([1L, 4L], progress.Select(p => p.Done));
Assert.SequenceEqual([DetailJobHandler.Expected, DetailJobHandler.Expected with { ItemDone = 4 }], progress.Select(p => p.Detail));
// The ended job is forgotten once its state goes out.
var gate = server.Services.GetRequiredService<JobEngineHost>().Gate;
for (var i = 0; i < 200 && gate.Count > 0; i++) await Task.Delay(25, context.Cancellation);
Assert.Equal(0, gate.Count);
}
[Test]
public async Task ARenderNodeSendsWhatItDoesAndAnOlderNodeNothing()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, _) = await server.UserAsync("alberto", "editor", renderNode: true);
var sequence = await JobApiTests.CreateSequenceAsync(editor);
var job = await JobApiTests.CreateAsync(editor, "render", sequence, RenderNodeTests.HevcJob);
var node = await RenderNodeTests.RegisterAsync(editor, "studio-pc", "hevc", 8192);
using (var claim = await editor.PostAsync($"/api/v1/nodes/{node.Id}/claim", null)) await claim.ExpectAsync(HttpStatusCode.OK);
using var subscription = server.Services.GetRequiredService<EventHub>().Subscribe();
var encode = new JobDetailDto("encode", "Harbour sunset", 120, 3600, 1, 1, "render");
await ReportAsync(new NodeProgress(120, 3600, 40, "encoding", encode));
Assert.Equal(encode, (await JobApiTests.GetAsync(editor, job.Id)).Detail);
// A step or unit this server does not know is stored as none, with its counts.
await ReportAsync(new NodeProgress(130, 3600, 40, null, new JobDetailDto("teleport", null, 130, 3600, 0, 0, "galaxy")));
Assert.Equal(new JobDetailDto("none", null, 130, 3600), (await JobApiTests.GetAsync(editor, job.Id)).Detail);
// An older node sends none: the counts alone.
await ReportAsync(new NodeProgress(140, 3600, 40, null));
var stored = await JobApiTests.GetAsync(editor, job.Id);
Assert.Equal((140L, (JobDetailDto?)null), (stored.ProgressDone, stored.Detail));
var events = new List<JobProgressEvent>();
while (subscription.Reader.TryRead(out var e))
{
if (e is JobProgressEvent p) events.Add(p);
}
Assert.Equal(encode, events[0].Detail);
Assert.True(events.All(e => e.JobId == job.Id), "only the node's job");
async Task ReportAsync(NodeProgress progress)
{
using var response = await editor.PostAsJsonAsync($"/api/v1/nodes/{node.Id}/jobs/{job.Id}/progress", progress, ProtocolJson.Default.NodeProgress);
await response.ExpectAsync(HttpStatusCode.NoContent);
}
}
/// <summary>A progress event as a 1.0 client reads it.</summary>
private sealed record JobProgressBefore(Guid JobId, long Done, long Total, double? ItemsPerSecond, double? EtaSeconds);
/// <summary>A node's report as a 1.0 server reads it.</summary>
private sealed record NodeProgressBefore(long Done, long Total, double? ItemsPerSecond, string? LogLine);
/// <summary>A monotonic clock the test moves by hand.</summary>
private sealed class TimestampClock : TimeProvider
{
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);
}
/// <summary>A deep analysis that says what it does, waits to be released, then completes.</summary>
private sealed class DetailJobHandler : IJobHandler
{
public static readonly JobDetailDto Expected = new("analyse", "Harbour sunset", 1, 4, 1, 1, "sequence");
private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
public JobKind Kind => JobKind.DeepAnalyse;
public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public void Release() => _release.TrySetResult();
public async Task RunAsync(JobContext context)
{
await context.CheckpointAsync("1", 1, 4, JobWire.FromDto(Expected)!);
Started.TrySetResult();
await _release.Task.WaitAsync(context.Cancellation);
await context.ReportItemAsync(4, 4, 4, 4);
}
}
}
@@ -0,0 +1,60 @@
using System.Net.Http.Json;
using System.Text.RegularExpressions;
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Server.Tests.Hosting;
/// <summary>
/// What a job does now in the admin panel (owner review 5, #65; <c>Admin/web/jobs.js</c>): the Jobs page and the dashboard
/// draw the status line under the target and move it with every progress event, and every step, part and sub-step the
/// server can send is worded in English and Italian.
/// </summary>
[Category("server")]
public sealed class AdminJobDetailTests(TestContext context)
{
private static readonly string[] MaintenanceSteps = ["Leases", "Temp", "Packs", "Duplicates", "Vacuum"];
[Test]
public async Task TheJobsPageAndTheDashboardShowTheStatusLine()
{
await using var server = await TestServer.StartAsync(context);
var jobs = await server.Client.GetStringAsync("/admin/jobs.js");
foreach (var helper in new[] { "statusText(detail)", "rowStatus(job)", "speedText(kind, rate)", "leftText(seconds)", "targetCell(job)", "statusLine(job)", "updateStatus(row, job)" })
Assert.Contains($"export function {helper}", jobs);
// Items are data: they read in their own direction, and the whole line is the tooltip.
Assert.Contains(@"<span class=""progress-detail"" dir=""auto"" title=""${attr(tip)}"">", jobs);
foreach (var page in new[] { "/admin/pages/jobs.js", "/admin/pages/dashboard.js" })
{
var text = await server.Client.GetStringAsync(page);
Assert.Contains(@"<span class=""target-cell"" role=""cell"">${targetCell(j)}</span>", text);
Assert.Contains("if (e.detail) job.detail = e.detail;", text);
Assert.Contains("updateStatus(row, job);", text);
Assert.True(!text.Contains(" style=", StringComparison.Ordinal), "inline style");
}
Assert.Contains(".progress-detail {", await server.Client.GetStringAsync("/admin/admin.css"));
}
[Test]
public async Task EveryStepAndPartIsInEnglishAndItalian()
{
await using var server = await TestServer.StartAsync(context);
var jobs = await server.Client.GetStringAsync("/admin/jobs.js");
var en = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/en", ProtocolJson.Default.DictionaryStringString));
var it = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/it", ProtocolJson.Default.DictionaryStringString));
var keys = Regex.Matches(jobs, @"""(Admin\.[A-Za-z]+(?:\.[A-Za-z]+)*)""").Select(m => m.Groups[1].Value).ToList();
Assert.Contains("Admin.Job.Detail.StoppedAt", keys);
// The keys built from what the server sends.
keys.AddRange(Enum.GetValues<JobStep>().Where(s => s != JobStep.None).Select(s => $"Admin.Job.Step.{s}"));
keys.AddRange(Enum.GetValues<JobPartUnit>().Where(u => u != JobPartUnit.None).Select(u => $"Admin.Job.Part.{u}"));
keys.AddRange(MaintenanceSteps.Select(s => $"Admin.Job.Maintenance.Step.{s}"));
foreach (var key in keys.Distinct())
Assert.True(en.ContainsKey(key) && it.ContainsKey(key), key);
// The step and the unit keys are the wire names in PascalCase, as the panel builds them.
Assert.Equal("copy-photo", JobWire.Step(JobStep.CopyPhoto));
Assert.Equal("Copia foto {0} di {1}", it["Admin.Job.Step.CopyPhoto.Count"]);
Assert.Equal("Verifying photo {0} of {1}", en["Admin.Job.Step.Verify.Count"]);
}
}
@@ -0,0 +1,390 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Diagnostics;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Model;
using Chronos.Core.Video.Managed;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Scheduling;
using Chronos.Protocol;
using Chronos.Server.Api;
using Chronos.Server.Configuration;
using Chronos.Server.Hosting;
using Chronos.Server.Jobs;
using Chronos.Server.Security;
using Chronos.Testing;
namespace Chronos.Server.Tests.Hosting;
/// <summary>
/// The server Chronos Desktop hosts to share this PC's library (owner review 5, #67): built over an index, engines, a job
/// engine and a scheduler the test owns, as the desktop does, which it never creates, starts, stops or disposes.
/// </summary>
[Category("server")]
[Serial] // Log.Sink is process-wide: the standalone server tests running beside these set their own
public sealed class HostedServerTests(TestContext context)
{
[Test]
public async Task ItAnswersWithTheCertificateOfItsDataFolderAndKeepsItsIdAcrossRestarts()
{
await using var desktop = await DesktopFixture.StartAsync(context);
Guid? firstId;
string? fingerprint;
await using (var shared = await desktop.ShareAsync())
{
using var http = desktop.Client(shared);
using var health = await http.GetAsync("/health");
Assert.Equal(HttpStatusCode.OK, health.StatusCode);
var info = Assert.NotNull(await http.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo));
var pfx = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(desktop.ShareData, "tls", "server.pfx"), null);
Assert.Equal(CertificateStore.Fingerprint(pfx), shared.Fingerprint);
Assert.Equal(shared.ServerId, info.ServerId);
Assert.True(shared.HttpsPort > 0, "the HTTPS listener's port");
firstId = shared.ServerId;
fingerprint = shared.Fingerprint;
}
// A second start on the same folder and index: the same certificate, id and administrator.
await using var again = await desktop.ShareAsync();
Assert.Equal(fingerprint, again.Fingerprint);
Assert.Equal(firstId, again.ServerId);
Assert.Count(1, (await desktop.Database.Users.ListAsync()).Where(u => u.Role == UserRole.Admin));
}
[Test]
public async Task JobsQueuedByClientsRunOnTheDesktopsEngineWhichOutlivesTheServer()
{
await using var desktop = await DesktopFixture.StartAsync(context);
var sink = Log.Sink;
await using (var shared = await desktop.ShareAsync())
{
Assert.Same(desktop.Engine, shared.Services.GetRequiredService<JobEngineHost>().Engine);
Assert.True(shared.Services.GetRequiredService<JobEngineHost>().Hosted, "hosted");
using var admin = await desktop.AdminAsync(shared);
using var created = await admin.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("scan", [], null), ProtocolJson.Default.CreateJobRequest);
Assert.Equal(HttpStatusCode.Accepted, created.StatusCode);
var job = Assert.NotNull(await created.Content.ReadFromJsonAsync(ProtocolJson.Default.JobDto));
var done = await desktop.WaitAsync(job.Id);
Assert.Equal(JobState.Done, done.State);
Assert.Equal(DesktopFixture.WorkerId, done.NodeId);
Assert.Same(sink, Log.Sink);
}
// Stopped: the index answers, the engine runs jobs, the scheduler still works, the log sink is the desktop's.
Assert.Same(sink, Log.Sink);
var after = await desktop.Engine.EnqueueAsync(JobKind.Scan, [desktop.Archive.Id], "after");
Assert.Equal(JobState.Done, (await desktop.WaitAsync(after.Id)).State);
Assert.NotNull(await desktop.Scheduler.ListAsync(context.Cancellation));
}
[Test]
public async Task TheServerAddsOnlyItsOwnSystemSchedulesToTheDesktops()
{
await using var desktop = await DesktopFixture.StartAsync(context);
var before = (await desktop.Scheduler.ListAsync(context.Cancellation)).Items.Select(s => s.SystemKey).OfType<string>().ToHashSet();
await using var shared = await desktop.ShareAsync();
var after = (await desktop.Scheduler.ListAsync(context.Cancellation)).Items.Select(s => s.SystemKey).OfType<string>().ToHashSet();
Assert.SequenceEqual([ServerScheduleHost.AuditCleanup, ServerScheduleHost.UploadCleanup], after.Except(before).Order(StringComparer.Ordinal));
Assert.SequenceEqual([DesktopFixture.ScanKey], before);
}
[Test]
public async Task ItServesTheDesktopsArchiveAloneAndHidesItsPrivateJobs()
{
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);
var workspace = await desktop.Engine.EnqueueAsync(JobKind.WorkspaceCopy, [mine.Id], "workspace");
await using var shared = await desktop.ShareAsync();
using var admin = await desktop.AdminAsync(shared);
using (var ok = await admin.GetAsync($"/api/v1/sequences/{mine.Id}")) Assert.Equal(HttpStatusCode.OK, ok.StatusCode);
foreach (var path in new[] { $"/api/v1/sequences/{theirs.Id}", $"/api/v1/sequences/{theirs.Id}/projects", $"/api/v1/sequences/{theirs.Id}/frames" })
{
using var hidden = await admin.GetAsync(path);
Assert.Equal(HttpStatusCode.NotFound, hidden.StatusCode, path);
}
using (var job = await admin.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("thumbs", [theirs.Id], null), ProtocolJson.Default.CreateJobRequest))
Assert.Equal(HttpStatusCode.NotFound, job.StatusCode);
var listed = Assert.NotNull(await admin.GetFromJsonAsync("/api/v1/jobs", ProtocolJson.Default.PageJobDto));
Assert.False(listed.Items.Any(j => j.Id == workspace.Id), "a workspace job is the desktop's own");
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]
public async Task TheDesktopOwnsItsSettingsAndTheFirstAdministratorsPasswordIsInTheShareFolder()
{
await using var desktop = await DesktopFixture.StartAsync(context);
Environment.SetEnvironmentVariable("CHRONOS_SERVER_NAME", "from a variable");
try
{
var options = ServerOptions.ForHosted(desktop.ShareData, desktop.Settings with { ServerName = "Studio PC" });
Assert.Equal("Studio PC", options.ServerName);
Assert.True(options.Hosted, "hosted");
Assert.Contains(nameof(ServerOptions.HttpsPort), options.Locked);
Assert.Equal(ServerOptions.DesktopLock, options.LockedBy[nameof(ServerOptions.Parallelism)]);
Assert.False(options.Locked.Contains(nameof(ServerOptions.TokenLifetimeDays)), "the admin panel owns the token lifetime");
Assert.Equal(Microsoft.Extensions.Logging.LogLevel.None, options.ConsoleLogLevel);
}
finally
{
Environment.SetEnvironmentVariable("CHRONOS_SERVER_NAME", null);
}
await using var shared = await desktop.ShareAsync();
Assert.True(File.Exists(shared.AdminPasswordFile), "the temporary password's file");
Assert.Equal(Path.Combine(desktop.ShareData, AdminBootstrap.PasswordFileName), shared.AdminPasswordFile);
Assert.NotNull(shared.AdminPassword());
using var admin = await desktop.AdminAsync(shared);
Assert.Null(shared.AdminPassword());
var settings = Assert.NotNull(await admin.GetFromJsonAsync("/api/v1/server/settings", ProtocolJson.Default.ServerSettingsDto));
Assert.Equal(ServerOptions.DesktopLock, settings.LockedBy["HttpsPort"]);
}
[Test]
public async Task ClientsAreKeptForFiveMinutes()
{
var time = new ManualTime(DateTimeOffset.Parse("2026-11-15T10:00:00Z", System.Globalization.CultureInfo.InvariantCulture));
var activity = new ClientActivity(time);
var user = new User { Id = Guid.CreateVersion7(), Username = "alberto", PasswordHash = "x", Role = UserRole.Editor, Created = time.GetUtcNow() };
activity.Record(new Caller(user, "hash", CredentialSource.Bearer, "Chronos Uploader (Studio)"), "192.168.1.20");
activity.Record(new Caller(user, "hash", CredentialSource.Cookie, null), "192.168.1.21");
var seen = activity.Recent();
Assert.Count(2, seen);
Assert.Contains("Chronos Uploader (Studio)", seen.Select(s => s.Client));
Assert.Contains(ClientActivity.AdminPanel, seen.Select(s => s.Client));
time.Advance(TimeSpan.FromMinutes(6));
Assert.Count(0, activity.Recent());
}
[Test]
public void ARenderNeverKeepsTheExportFolderAClientChose()
{
var parameters = new RenderJobParameters("1080p", """{"preset":"1080p","Folder":"C:\\Users\\someone","nameTemplate":"{title}"}""", "h264", 1920, 1080, false, null);
var stripped = JobEndpoints.WithoutExportFolder(parameters);
Assert.False(stripped.PresetJson.Contains("Users", StringComparison.Ordinal), stripped.PresetJson);
Assert.True(stripped.PresetJson.Contains("nameTemplate", StringComparison.Ordinal), stripped.PresetJson);
var plain = parameters with { PresetJson = """{"preset":"1080p"}""" };
Assert.Same(plain, JobEndpoints.WithoutExportFolder(plain));
}
[Test]
public void TheServiceSwitchesAreGone()
{
var parsed = ServerCommandLine.Parse(["--service", "--install-service", "--uninstall-service"]);
Assert.Equal(ServerCommand.Run, parsed.Command);
Assert.SequenceEqual(["--service", "--install-service", "--uninstall-service"], parsed.HostArguments);
Assert.False(ServerCommandLine.Usage.Contains("service", StringComparison.OrdinalIgnoreCase), "usage names a service");
}
/// <summary>A clock the test moves.</summary>
private sealed class ManualTime(DateTimeOffset start) : TimeProvider
{
private DateTimeOffset _now = start;
public override DateTimeOffset GetUtcNow() => _now;
public void Advance(TimeSpan by) => _now += by;
}
}
/// <summary>
/// What Chronos Desktop has when it shares its library: a SQLite index, the archive and processing services (managed
/// codecs), a started job engine and a started scheduler with one system schedule of its own.
/// </summary>
internal sealed class DesktopFixture : IAsyncDisposable
{
public const string WorkerId = "STUDIO-PC";
public const string ScanKey = "archive-scan";
private readonly TestContext _context;
private DesktopFixture(TestContext context, string root, ChronosDatabase db, ArchiveService archives, ProcessingService processing, JobEngine engine,
Scheduler scheduler, Archive archive)
{
_context = context;
Root = root;
Database = db;
Archives = archives;
Processing = processing;
Engine = engine;
Scheduler = scheduler;
Archive = archive;
}
public string Root { get; }
public ChronosDatabase Database { get; }
public ArchiveService Archives { get; }
public ProcessingService Processing { get; }
public JobEngine Engine { get; }
public Scheduler Scheduler { get; }
public Archive Archive { get; }
public string ShareData => Path.Combine(Root, "data", "server");
public HostedSettings Settings => new(null, 0, 0, null, null, Discovery: false, Archive.RootPath, null, 2, false, new Dictionary<string, string>(), "en",
LogLevel.Warning, 14, 50, 1024, LogRotation.Daily, 4);
public static async Task<DesktopFixture> StartAsync(TestContext context)
{
var root = context.CreateTempDirectory("desktop");
Directory.CreateDirectory(Path.Combine(root, "data"));
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(root, "data", "chronos.db")), context.Cancellation);
var archiveOptions = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Parallelism = () => 2 };
var archives = new ArchiveService(db, archiveOptions);
var processing = new ProcessingService(db, new ProcessingOptions { Archive = archiveOptions, Encoders = [new ManagedEncoderProvider()] });
var archive = await archives.CreateAsync(Path.Combine(root, "archive"), "Studio", cancellationToken: context.Cancellation);
var handlers = archives.CreateJobHandlers().Concat(processing.CreateJobHandlers()).ToList();
var engine = new JobEngine(db, handlers, new JobEngineOptions
{
WorkerId = WorkerId,
Kinds = [.. handlers.Select(h => h.Kind).Distinct()],
PollInterval = TimeSpan.FromMilliseconds(100),
});
await engine.StartAsync(context.Cancellation);
var scheduler = new Scheduler(db, engine);
await scheduler.StartAsync(new Host(archives, archive), context.Cancellation);
return new DesktopFixture(context, root, db, archives, processing, engine, scheduler, archive);
}
public async Task<HostedServer> ShareAsync()
{
var options = ServerOptions.ForHosted(ShareData, Settings);
options.LoginAttemptsPerMinute = 1000;
var server = ServerHost.BuildHosted(options, new HostedEngine(Database, Archives, Processing, Engine, Scheduler, Archive));
await server.StartAsync(_context.Cancellation);
return server;
}
public HttpClient Client(HostedServer server, string? token = null)
{
var client = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{server.HttpPort}"), Timeout = TimeSpan.FromSeconds(60) };
if (token is not null) client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
return client;
}
/// <summary>The first administrator, signed in with its temporary password, which it then replaces.</summary>
public async Task<HttpClient> AdminAsync(HostedServer server)
{
var temporary = server.AdminPassword() ?? throw new InvalidOperationException("No temporary password");
using var anonymous = Client(server);
using var login = await anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", temporary, "tests"), ProtocolJson.Default.LoginRequest);
login.EnsureSuccessStatusCode();
var token = (await login.Content.ReadFromJsonAsync(ProtocolJson.Default.LoginResponse))!.Token!;
var client = Client(server, token);
using var changed = await client.PostAsJsonAsync("/api/v1/auth/password", new ChangePasswordRequest(temporary, "a-good-password-1"),
ProtocolJson.Default.ChangePasswordRequest);
changed.EnsureSuccessStatusCode();
return client;
}
public async Task<Sequence> SequenceAsync(Archive archive)
{
var sequence = new Sequence
{
Id = Guid.CreateVersion7(),
ArchiveId = archive.Id,
Title = "Roof " + archive.Name,
Folder = string.Empty,
Origin = SequenceOrigin.Server,
UpdatedAt = DateTimeOffset.UtcNow,
};
await Database.Sequences.UpsertAsync(sequence, _context.Cancellation);
return sequence;
}
public async Task<Job> WaitAsync(Guid id)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while (true)
{
if (await Database.Jobs.GetAsync(id, _context.Cancellation) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } job) return job;
Assert.True(DateTime.UtcNow < until, "the job did not finish");
await Task.Delay(50, _context.Cancellation);
}
}
public async ValueTask DisposeAsync()
{
await Scheduler.DisposeAsync();
await Engine.DisposeAsync();
await Database.DisposeAsync();
}
/// <summary>A desktop's schedule host: one archive scan schedule, the archive service's clean-up steps.</summary>
private sealed class Host(ArchiveService archives, Archive archive) : IScheduleHost
{
public TimeZoneInfo TimeZone => TimeZoneInfo.Utc;
public IReadOnlyList<SystemSchedule> SystemSchedules =>
[new(ScanKey, "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(10, RecurrenceUnit.Minutes), CatchUp: false)];
public IReadOnlyList<string> CleanupSteps => [.. archives.CleanupSteps.Select(s => s.Name)];
public bool DeepAnalysisAfterScan => false;
public ValueTask<Archive?> GetArchiveAsync(CancellationToken cancellationToken) => ValueTask.FromResult<Archive?>(archive);
public string? Unavailable(string action) => null;
}
}
@@ -1,152 +0,0 @@
using System.Diagnostics.Eventing.Reader;
using System.Security.AccessControl;
using System.Security.Principal;
using Chronos.Server.Hosting;
using Chronos.Server.Hosting.Windows;
using Chronos.Testing;
namespace Chronos.Server.Tests.Hosting;
public sealed class WindowsServiceTests(TestContext context)
{
[Test]
public void CommandSwitchesAreParsedAndTheRestPassedOn()
{
Assert.Equal(ServerCommand.Run, ServerCommandLine.Parse([]).Command);
var service = ServerCommandLine.Parse(["--service", "--urls", "x"]);
Assert.Equal(ServerCommand.Service, service.Command);
Assert.SequenceEqual(["--urls", "x"], service.HostArguments);
Assert.Equal(ServerCommand.InstallService, ServerCommandLine.Parse(["--install-service"]).Command);
Assert.Equal(ServerCommand.UninstallService, ServerCommandLine.Parse(["--uninstall-service"]).Command);
Assert.Equal(ServerCommand.HealthCheck, ServerCommandLine.Parse(["--healthcheck"]).Command);
Assert.Equal(ServerCommand.Help, ServerCommandLine.Parse(["/?"]).Command);
Assert.NotNull(ServerCommandLine.Parse(["--install-service", "--uninstall-service"]).Error);
Assert.Null(ServerCommandLine.Parse(["--service", "--service"]).Error);
}
[Test]
public void StatusReportsFollowTheServiceControlManagerRules()
{
var tracker = new ServiceStatusTracker();
var start = tracker.StartPending(60_000);
Assert.Equal((ServiceState.StartPending, 0u, 1u, 60_000u), (start.State, start.ControlsAccepted, start.CheckPoint, start.WaitHintMilliseconds));
Assert.Equal(2u, tracker.StartPending(60_000).CheckPoint);
var running = tracker.Running();
Assert.Equal((ServiceState.Running, ServiceStatusTracker.AcceptStop | ServiceStatusTracker.AcceptShutdown, 0u), (running.State, running.ControlsAccepted, running.CheckPoint));
Assert.Throws<InvalidOperationException>(() => tracker.Running());
Assert.Equal(1u, tracker.StopPending(35_000).CheckPoint);
Assert.Equal(2u, tracker.StopPending(35_000).CheckPoint);
var stopped = tracker.Stopped(0);
Assert.Equal((ServiceState.Stopped, 0u, 0u), (stopped.State, stopped.ControlsAccepted, stopped.CheckPoint));
Assert.Throws<InvalidOperationException>(() => tracker.StopPending(1));
Assert.Equal(1064u, new ServiceStatusTracker().Stopped(1064).ExitCode);
}
[Test]
public void AServiceFailureLeadsWithTheReasonTheServerGave()
{
var refused = new InvalidOperationException(@"C:\ProgramData\Chronos Server belongs to PC\ada, not to SYSTEM, Administrators or the account Chronos Server runs as.");
var text = ServiceEventLog.Describe("Chronos Server did not start:", refused);
Assert.True(text.StartsWith(@"Chronos Server did not start: C:\ProgramData\Chronos Server belongs to PC\ada", StringComparison.Ordinal), text);
Assert.Contains("System.InvalidOperationException", text);
// ReportEvent refuses a longer string: the text is cut, never between the halves of a surrogate pair.
var cut = ServiceEventLog.Describe("x", new InvalidOperationException(new string('a', ServiceEventLog.MaxLength)));
Assert.Equal(ServiceEventLog.MaxLength, cut.Length);
Assert.True(cut.EndsWith("a\u2026", StringComparison.Ordinal), cut[^5..]);
var pair = ServiceEventLog.Describe("x", new InvalidOperationException(new string('a', ServiceEventLog.MaxLength - 4) + "\uD83D\uDE00" + new string('b', 99)));
Assert.Equal(ServiceEventLog.MaxLength - 1, pair.Length);
Assert.True(pair.EndsWith("a\u2026", StringComparison.Ordinal), pair[^5..]);
}
[Test]
[WindowsOnly]
public void AServiceFailureReachesTheApplicationEventLog()
{
if (!OperatingSystem.IsWindows()) return;
// Written as a source of its own, so a test run never looks like a failed service in Event Viewer.
const string source = "Chronos.Server.Tests";
var marker = source + " " + Guid.NewGuid().ToString("N");
Assert.True(ServiceEventLog.Error(source, ServiceEventLog.StartFailed, marker), "the Application log takes the event");
var filter = $"*[System[Provider[@Name='{source}'] and EventID={ServiceEventLog.StartFailed}]]";
var query = new EventLogQuery("Application", PathType.LogName, filter) { ReverseDirection = true };
for (var attempt = 0; attempt < 50; attempt++)
{
using (var reader = new EventLogReader(query))
{
for (var read = 0; read < 100 && reader.ReadEvent() is { } record; read++)
{
using (record)
{
// The event's one string, which Event Viewer shows whole.
if (record.Properties.Count != 1 || record.Properties[0].Value as string != marker) continue;
Assert.Equal((byte?)2, record.Level, "an error");
return;
}
}
}
Thread.Sleep(100);
}
Assert.Fail($"No {source} event carries '{marker}'.");
}
[Test]
[WindowsOnly]
public void TheServiceIsRegisteredOnlyFromInsideProgramFiles()
{
if (!OperatingSystem.IsWindows()) return;
var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
Assert.True(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "Chronos", "Chronos.Server.exe")));
Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles));
Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles + " Tools\\Chronos"));
Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Chronos")));
Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "..", "Chronos")));
// The test build is not under Program Files: registering it is refused, naming the folder.
Assert.Contains(Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory), Assert.NotNull(ServiceInstaller.UnsafeLocation()));
}
[Test]
[WindowsOnly]
public void AnyFileOrdinaryUsersCanChangeIsFound()
{
if (!OperatingSystem.IsWindows()) return;
using var identity = WindowsIdentity.GetCurrent();
if (!new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) Assert.Inconclusive("registering a service needs an administrator");
var folder = new DirectoryInfo(context.CreateTempDirectory("program"));
File.WriteAllBytes(Path.Combine(folder.FullName, "Chronos.Server.exe"), [1]);
var satellite = new FileInfo(Path.Combine(folder.CreateSubdirectory("it").FullName, "Chronos.Core.resources.dll"));
File.WriteAllBytes(satellite.FullName, [1]);
// Like Program Files: administrators may change the folder, users only read it.
var locked = new DirectorySecurity();
locked.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
var everything = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
foreach (var account in new[] { new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), identity.User! })
locked.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl, everything, PropagationFlags.None, AccessControlType.Allow));
locked.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.ReadAndExecute, everything,
PropagationFlags.None, AccessControlType.Allow));
folder.SetAccessControl(locked);
Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: true));
// One satellite assembly users may replace is enough: the service would load it as SYSTEM.
var open = satellite.GetAccessControl();
open.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.Modify, AccessControlType.Allow));
satellite.SetAccessControl(open);
Assert.Equal(satellite.FullName, ServiceInstaller.FindChangeable(folder, recursive: true));
Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: false));
}
[Test]
[WindowsOnly]
public void TheDispatcherDeclinesAConsoleProcess()
{
if (!OperatingSystem.IsWindows()) return;
var built = false;
Assert.False(WindowsServiceHost.Run(() =>
{
built = true;
throw new InvalidOperationException("never built outside the SCM");
}));
Assert.False(built);
}
}
@@ -233,6 +233,32 @@ public sealed class ServerWorkspaceTests(TestContext context)
Assert.Null(a.Store.Find(main.Id)!.ReadMedia());
}
[Test]
public async Task ACopyQueuedUnderTheAddressRunsOnAProjectReKeyedToTheServersId()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (_, _, token) = await server.UserAsync("alberto", "editor");
var sid = await SequenceAsync(server, token, 2);
var id = Guid.CreateVersion7();
var idKey = ServerIdentity.IdKey(id);
ServerIdentity? identity = null;
await using var a = await WorkspaceClient.StartAsync(context, server, token, "PC-A", sameServer: (x, y) => identity!.Same(x, y));
identity = ServerIdentity.None.With(id, a.Server);
// The project's home names the server by its id (re-keyed at sign-in, owner review 5); the job still names the address.
var home = new ServerProjectHome(a.Client, sid, "Test server", server: idKey);
var main = (await home.ListAsync(context.Cancellation)).Single();
var project = await a.Sync.CheckoutAsync(home, main.Id, cancellationToken: context.Cancellation);
Assert.Equal(idKey, project.ReadBundle().Workspace!.Home.Server);
var job = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, a.Server, a.Store.Root, main.Id));
await a.WaitAsync(job.Id, JobState.Done);
Assert.Equal(2, Assert.NotNull(project.ReadMedia()).Frames.Count);
// Another server is still another home.
var other = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, "https://elsewhere:8443", a.Store.Root, main.Id));
Assert.Equal(Loc.L("Errors.Workspace.OtherHome"), (await a.WaitAsync(other.Id, JobState.Failed)).Error);
}
[Test]
public async Task TheOriginalsAreDownloadedCheckedAndKeptBesideTheProxies()
{
@@ -560,7 +586,7 @@ public sealed class ServerWorkspaceTests(TestContext context)
public bool Connected { get; set; } = true;
public static async Task<WorkspaceClient> StartAsync(TestContext context, TestServer server, string token, string name, HttpMessageHandler? handler = null,
Func<bool>? hold = null)
Func<bool>? hold = null, Func<string?, string?, bool>? sameServer = null)
{
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(name + "-db"), "chronos.db")), context.Cancellation);
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = name });
@@ -568,7 +594,8 @@ public sealed class ServerWorkspaceTests(TestContext context)
var archive = await archives.CreateAsync(context.CreateTempDirectory(name + "-archive"), "Local", cancellationToken: context.Cancellation);
var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), name, handler) { Token = token };
WorkspaceClient? created = null;
var options = hold is null ? WorkspaceJobOptions.For(archives) : WorkspaceJobOptions.For(archives) with { HoldTransfers = hold };
var options = WorkspaceJobOptions.For(archives) with { SameServer = sameServer };
if (hold is not null) options = options with { HoldTransfers = hold };
var engine = new JobEngine(db, WorkspaceJobs.CreateHandlers(db, archives, new Connector(client, () => created?.Connected ?? true), options),
new JobEngineOptions { Workers = 1, WorkerId = name, PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync(context.Cancellation);
@@ -8,31 +8,83 @@ namespace Chronos.Tools.Tests;
public sealed class PackInstallerCommandTests(TestContext context)
{
[Test]
public async Task TheServerInstallsOnlyForAllUsersAndChronosOwnsTheProjectFileType()
public async Task TheSetupCarriesTheDesktopAppPreselectedAndTheUploaderToChoose()
{
var root = context.CreateTempDirectory("pack");
var stub = await Stub(root);
var app = Program(root, "app", "Chronos.exe");
var uploader = Program(root, "uploader", "Chronos.Uploader.exe");
var output = Path.Combine(root, "out", "Chronos-Setup.exe");
// "Desktop" names the desktop app, as /COMPONENTS=Desktop does.
Assert.Equal(0, await new PackInstallerCommand().RunAsync(
["--setup", stub, "--product", "Chronos", "--version", "1.2.3", "--component", "Desktop=" + app, "--component", "Uploader=" + uploader, "--out", output]));
using var reader = PayloadReader.Open(output);
var manifest = reader.Manifest;
Assert.SequenceEqual(["Chronos", "Uploader"], manifest.Components.Select(c => c.Id));
var desktop = manifest.FindComponent("Chronos")!;
Assert.True(desktop.DefaultSelected);
Assert.Equal("Chronos Desktop", desktop.DisplayName);
Assert.False(desktop.AllUsersOnly);
Assert.False(manifest.FindComponent("Uploader")!.DefaultSelected);
// The shortcut names that links, pins and the installer test follow stay as in 1.0.
Assert.SequenceEqual(["Chronos", "Chronos Uploader"], manifest.Shortcuts.Select(s => s.Name));
var association = Assert.Contains(manifest.Associations, a => a.Extension == ".chronos");
Assert.Equal("Chronos.Project", association.ProgId);
Assert.Equal("Chronos.exe", association.Target);
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()
{
var root = context.CreateTempDirectory("pack");
var stub = await Stub(root);
var app = Program(root, "app", "Chronos.exe");
var server = Program(root, "server", "Chronos.Server.exe");
var output = Path.Combine(root, "out", "Chronos-Setup.exe");
string[] args = ["--setup", stub, "--product", "Chronos", "--version", "1.0.0", "--component", "Chronos=" + app, "--component", "Server=" + server, "--out", output];
var refused = await Assert.ThrowsAsync<ToolException>(() => new PackInstallerCommand().RunAsync(args));
Assert.Contains("Docker", refused.Message);
Assert.FileMissing(output);
Assert.Equal(0, await new PackInstallerCommand().RunAsync([.. args, "--legacy"]));
using var reader = PayloadReader.Open(output);
var serverComponent = reader.Manifest.FindComponent("Server")!;
Assert.False(serverComponent.DefaultSelected);
// Installable for the current user, so that the test needs no administrator rights.
Assert.False(serverComponent.AllUsersOnly);
var shortcut = Assert.Contains(reader.Manifest.Shortcuts, s => s.Component == "Server");
Assert.Equal("Chronos Server", shortcut.Name);
Assert.False(shortcut.Desktop);
}
private static async Task<string> Stub(string root)
{
var stub = Path.Combine(root, "Chronos.Setup.exe");
var bytes = new byte[4096];
new Random(5).NextBytes(bytes);
"MZ"u8.CopyTo(bytes);
await File.WriteAllBytesAsync(stub, bytes);
var app = Program(root, "app", "Chronos.exe");
var server = Program(root, "server", "Chronos.Server.exe");
var output = Path.Combine(root, "out", "Chronos-Setup.exe");
Assert.Equal(0, await new PackInstallerCommand().RunAsync(
["--setup", stub, "--product", "Chronos", "--version", "1.2.3", "--component", "Chronos=" + app, "--component", "Server=" + server, "--out", output]));
using var reader = PayloadReader.Open(output);
var manifest = reader.Manifest;
Assert.False(manifest.FindComponent("Chronos")!.AllUsersOnly);
var serverComponent = manifest.FindComponent("Server")!;
Assert.True(serverComponent.AllUsersOnly);
Assert.False(serverComponent.DefaultSelected);
var association = Assert.Contains(manifest.Associations, a => a.Extension == ".chronos");
Assert.Equal("Chronos.Project", association.ProgId);
Assert.Equal("Chronos.exe", association.Target);
Assert.Equal("Chronos", association.Component);
return stub;
}
private static string Program(string root, string folder, string name)
Binary file not shown.

Before

Width:  |  Height:  |  Size: 88 KiB

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 85 KiB

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 71 KiB

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 80 KiB

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 80 KiB

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 172 KiB

After

Width:  |  Height:  |  Size: 172 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 167 KiB

After

Width:  |  Height:  |  Size: 167 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 258 KiB

After

Width:  |  Height:  |  Size: 259 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 267 KiB

After

Width:  |  Height:  |  Size: 267 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 276 KiB

After

Width:  |  Height:  |  Size: 276 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 270 KiB

After

Width:  |  Height:  |  Size: 270 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 211 KiB

After

Width:  |  Height:  |  Size: 211 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 212 KiB

After

Width:  |  Height:  |  Size: 212 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 108 KiB

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 100 KiB

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 214 KiB

After

Width:  |  Height:  |  Size: 215 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 213 KiB

After

Width:  |  Height:  |  Size: 213 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 212 KiB

After

Width:  |  Height:  |  Size: 213 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 210 KiB

After

Width:  |  Height:  |  Size: 211 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 216 KiB

After

Width:  |  Height:  |  Size: 217 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 214 KiB

After

Width:  |  Height:  |  Size: 214 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 276 KiB

After

Width:  |  Height:  |  Size: 276 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 271 KiB

After

Width:  |  Height:  |  Size: 271 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 271 KiB

After

Width:  |  Height:  |  Size: 271 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 267 KiB

After

Width:  |  Height:  |  Size: 268 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 426 KiB

After

Width:  |  Height:  |  Size: 426 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 404 KiB

After

Width:  |  Height:  |  Size: 404 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 273 KiB

After

Width:  |  Height:  |  Size: 273 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 317 KiB

After

Width:  |  Height:  |  Size: 317 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 310 KiB

After

Width:  |  Height:  |  Size: 310 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 226 KiB

After

Width:  |  Height:  |  Size: 227 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 220 KiB

After

Width:  |  Height:  |  Size: 221 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 250 KiB

After

Width:  |  Height:  |  Size: 250 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 245 KiB

After

Width:  |  Height:  |  Size: 245 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 267 KiB

After

Width:  |  Height:  |  Size: 268 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 262 KiB

After

Width:  |  Height:  |  Size: 262 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 105 KiB

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 98 KiB

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 226 KiB

After

Width:  |  Height:  |  Size: 226 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 223 KiB

After

Width:  |  Height:  |  Size: 223 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 229 KiB

After

Width:  |  Height:  |  Size: 229 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 224 KiB

After

Width:  |  Height:  |  Size: 224 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 241 KiB

After

Width:  |  Height:  |  Size: 242 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 236 KiB

After

Width:  |  Height:  |  Size: 236 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 80 KiB

After

Width:  |  Height:  |  Size: 81 KiB

Loaded 100 of 793 files, more files were not shown because too many files have changed in this diff. Show more