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,149 +0,0 @@
using System.Net;
using System.Net.Http;
using System.Text;
using Chronos.App.About;
using Chronos.App.Infrastructure;
using Chronos.Testing;
namespace Chronos.App.Tests.About;
public sealed class UpdateCheckTests
{
[Theory]
[Case("v1.2.3", "1.2.3")]
[Case("1.2", "1.2.0")]
[Case("V0.10.0-beta.2", "0.10.0")]
[Case("v2.0.1+abc", "2.0.1")]
public void TagsParseToVersions(string tag, string expected) =>
Assert.Equal(Version.Parse(expected), UpdateCheck.ParseVersion(tag));
[Theory]
[Case(new object?[] { null })]
[Case("")]
[Case("latest")]
[Case("v-one")]
public void OtherTagsAreIgnored(string? tag) => Assert.Null(UpdateCheck.ParseVersion(tag));
[Test]
public void TheLatestReleaseIsComparedWithTheRunningVersion()
{
var release = UpdateCheck.Parse("""{ "tag_name": "v0.2.0", "html_url": "https://gitea.example/o/r/releases/tag/v0.2.0", "draft": false, "prerelease": false }""");
Assert.NotNull(release);
Assert.Equal(new Version(0, 2, 0), release!.Version);
Assert.True(UpdateCheck.IsNewer(release, UpdateCheck.RunningVersion("0.1.0")));
Assert.False(UpdateCheck.IsNewer(release, UpdateCheck.RunningVersion("0.2.0+local")));
Assert.False(UpdateCheck.IsNewer(release, new Version(0, 2, 0, 0)));
Assert.False(UpdateCheck.IsNewer(release, UpdateCheck.RunningVersion("1.0.0")));
Assert.Equal("0.2.0", UpdateCheck.Display(release.Version));
}
[Test]
public void APreReleaseBuildIsOfferedTheFinalReleaseOfItsVersion()
{
var final = UpdateCheck.Parse("""{ "tag_name": "v0.1.0", "html_url": "https://gitea.example/o/r/releases/tag/v0.1.0" }""")!;
Assert.True(UpdateCheck.IsPrerelease("0.1.0-rc.1"));
Assert.True(UpdateCheck.IsPrerelease("v0.1.0-beta+abc"));
Assert.False(UpdateCheck.IsPrerelease("0.1.0+abc-def"));
Assert.False(UpdateCheck.IsPrerelease("0.1.0"));
Assert.True(UpdateCheck.IsNewer(final, UpdateCheck.RunningVersion("0.1.0-rc.1"), UpdateCheck.IsPrerelease("0.1.0-rc.1")));
Assert.False(UpdateCheck.IsNewer(final, UpdateCheck.RunningVersion("0.1.0"), UpdateCheck.IsPrerelease("0.1.0")));
Assert.False(UpdateCheck.IsNewer(final, UpdateCheck.RunningVersion("0.2.0-rc.1"), UpdateCheck.IsPrerelease("0.2.0-rc.1")));
}
[Test]
public void DraftsPrereleasesAndOddLinksAreIgnored()
{
Assert.Null(UpdateCheck.Parse("""{ "tag_name": "v9.0.0", "html_url": "https://x", "prerelease": true }"""));
Assert.Null(UpdateCheck.Parse("""{ "tag_name": "v9.0.0", "html_url": "https://x", "draft": true }"""));
Assert.Null(UpdateCheck.Parse("""{ "tag_name": "v9.0.0", "html_url": "javascript:alert(1)" }"""));
Assert.Null(UpdateCheck.Parse("""{ "html_url": "https://x" }"""));
Assert.Null(UpdateCheck.Parse("[]"));
}
[Test]
public async Task FetchReadsTheApiAndToleratesMissingReleases()
{
// Gitea lists the most recently created first: a re-published 0.9.0 must not hide 1.0.0.
using var ok = new HttpClient(new Reply(HttpStatusCode.OK, """
[ { "tag_name": "v0.9.0", "html_url": "https://gitea.example/o/r/releases/tag/v0.9.0" },
{ "tag_name": "v1.0.0", "html_url": "https://gitea.example/o/r/releases/tag/v1.0.0" },
{ "tag_name": "v2.0.0", "html_url": "https://gitea.example/o/r/releases/tag/v2.0.0", "prerelease": true } ]
"""));
var release = await UpdateCheck.FetchAsync(ok, Api, "0.1.0", CancellationToken.None);
Assert.Equal(new Version(1, 0, 0), release!.Version);
using var none = new HttpClient(new Reply(HttpStatusCode.OK, "[]"));
Assert.Null(await UpdateCheck.FetchAsync(none, Api, "0.1.0", CancellationToken.None));
using var garbage = new HttpClient(new Reply(HttpStatusCode.OK, "<html>"));
Assert.Null(await UpdateCheck.FetchAsync(garbage, Api, "0.1.0", CancellationToken.None));
using var broken = new HttpClient(new Reply(HttpStatusCode.InternalServerError, "{}"));
await Assert.ThrowsAsync<HttpRequestException>(() => UpdateCheck.FetchAsync(broken, Api, "0.1.0", CancellationToken.None));
}
[Test]
public async Task LinksComeFromTheRepositoryAddressNotFromGiteasRootUrl()
{
// The owner's Gitea writes its links with its ROOT_URL, a plain-http LAN address clients cannot use.
const string json = """
[ { "tag_name": "v1.0.0", "html_url": "http://192.168.30.23:3000/BalboSoft/Chronos/releases/tag/v1.0.0",
"assets": [ { "name": "Chronos-Setup-1.0.0.exe", "size": 5, "browser_download_url": "http://192.168.30.23:3000/BalboSoft/Chronos/releases/download/v1.0.0/Chronos-Setup-1.0.0.exe" },
{ "name": "Read me.txt", "size": 2, "browser_download_url": "http://192.168.30.23:3000/x" } ] } ]
""";
Assert.Null(UpdateCheck.Parse(json));
var release = UpdateCheck.Parse(json, "https://gitea.example/BalboSoft/Chronos/")!;
Assert.Equal("https://gitea.example/BalboSoft/Chronos/releases/tag/v1.0.0", release.PageUrl);
Assert.SequenceEqual(
["https://gitea.example/BalboSoft/Chronos/releases/download/v1.0.0/Chronos-Setup-1.0.0.exe",
"https://gitea.example/BalboSoft/Chronos/releases/download/v1.0.0/Read%20me.txt"],
release.Assets.Select(a => a.DownloadUrl));
Assert.Equal(5L, release.Assets[0].Size);
Assert.Null(UpdateCheck.Parse(json, "http://gitea.example/BalboSoft/Chronos"));
using var ok = new HttpClient(new Reply(HttpStatusCode.OK, json));
var fetched = await UpdateCheck.FetchAsync(ok, Api, "https://gitea.example/BalboSoft/Chronos", "0.1.0", CancellationToken.None);
Assert.Equal("https://gitea.example/BalboSoft/Chronos/releases/tag/v1.0.0", fetched!.PageUrl);
}
[Test]
public async Task ARepositoryThatCannotBeSeenIsAFailedCheckNotUpToDate()
{
using var hidden = new HttpClient(new Reply(HttpStatusCode.NotFound, """{ "message": "not found" }"""));
var error = await Assert.ThrowsAsync<HttpRequestException>(() => UpdateCheck.FetchAsync(hidden, Api, "0.1.0", CancellationToken.None));
Assert.Equal(HttpStatusCode.NotFound, error.StatusCode);
}
private const string Api = "https://gitea.example/api/v1/repos/o/r/releases?draft=false&pre-release=false&limit=50";
[Theory]
[Case("https://gitea.example/BalboSoft/Chronos", "https://gitea.example/api/v1/repos/BalboSoft/Chronos/releases?draft=false&pre-release=false&limit=50")]
[Case("https://example.org:8443/git/BalboSoft/Chronos", "https://example.org:8443/git/api/v1/repos/BalboSoft/Chronos/releases?draft=false&pre-release=false&limit=50")]
public void TheReleasesAreAskedOfTheGiteaApiOfTheRepository(string repository, string expected) =>
Assert.Equal(expected, ProductLinks.StableReleasesApiOf(repository));
[Theory]
[Case(" https://gitea.example/o/r/ ", "https://gitea.example/o/r")]
[Case("https://gitea.example/o/r.git", "https://gitea.example/o/r")]
[Case("", null)]
public void TheReleasesRepositoryAddressIsNormalised(string address, string? expected) =>
Assert.Equal(expected, ProductLinks.Normalise(address));
[Test]
public void LocalBuildsLinkTheRepositoryTheBuildPropertiesName()
{
Assert.Equal(ProductLinks.DefaultRepository, ProductLinks.Repository);
Assert.Equal(ProductLinks.DefaultRepository + "/src/branch/main/EULA.md", ProductLinks.Licence);
Assert.Throws<ArgumentException>(() => ProductLinks.StableReleasesApiOf("https://gitea.example/only-owner"));
}
private sealed class Reply(HttpStatusCode status, string body) : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Assert.True(request.Headers.UserAgent.ToString().StartsWith("Chronos/", StringComparison.Ordinal), "the update requests identify the program");
return Task.FromResult(new HttpResponseMessage(status) { Content = new StringContent(body, Encoding.UTF8, "application/json") });
}
}
}
@@ -1,328 +0,0 @@
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using Chronos.App.About;
using Chronos.Testing;
namespace Chronos.App.Tests.About;
public sealed class UpdateDownloadTests(TestContext context)
{
private const string Base = "https://gitea.example/o/r/releases/download/v1.0.0/";
private const string SetupName = "Chronos-Setup-1.0.0.exe";
private const string PortableName = "Chronos-win-x64-portable-1.0.0.zip";
private static readonly TimeSpan Idle = TimeSpan.FromSeconds(30);
private static readonly byte[] Setup = Encoding.ASCII.GetBytes(string.Concat(Enumerable.Repeat("MZ setup payload ", 20_000)));
private static readonly byte[] Portable = Encoding.ASCII.GetBytes(string.Concat(Enumerable.Repeat("PK portable zip ", 9_000)));
[Test]
public void ChecksumLinesOfBothSha256sumModesAreRead()
{
var hash = new string('A', 64);
var sums = UpdateDownload.ParseChecksums(
$"{hash} Chronos-Setup-1.0.0.exe\r\n{new string('b', 64)} *Chronos-Uploader-Setup-1.0.0.exe\nnot a checksum line\n{new string('c', 63)} short.exe\n\n");
Assert.Equal(2, sums.Count);
Assert.Equal(new string('a', 64), sums["Chronos-Setup-1.0.0.exe"]);
Assert.Equal(new string('b', 64), sums["Chronos-Uploader-Setup-1.0.0.exe"]);
}
[Test]
public void ThePackageForEachKindOfCopyAndTheChecksumsAreFoundAmongTheAssets()
{
var release = UpdateCheck.Parse($$"""
{ "tag_name": "v1.0.0", "html_url": "https://gitea.example/o/r/releases/tag/v1.0.0", "assets": [
{ "name": "Chronos-Uploader-Setup-1.0.0.exe", "browser_download_url": "{{Base}}Chronos-Uploader-Setup-1.0.0.exe", "size": 10 },
{ "name": "{{SetupName}}", "browser_download_url": "{{Base}}{{SetupName}}", "size": {{Setup.Length}} },
{ "name": "{{PortableName}}", "browser_download_url": "{{Base}}{{PortableName}}", "size": {{Portable.Length}} },
{ "name": "SHA256SUMS", "browser_download_url": "{{Base}}SHA256SUMS", "size": 300 },
{ "name": "evil.exe", "browser_download_url": "http://example.com/evil.exe", "size": 1 }
] }
""")!;
Assert.Equal(4, release.Assets.Count);
Assert.Equal(SetupName, UpdateDownload.Package(release, portable: false)!.Name);
Assert.Equal(PortableName, UpdateDownload.Package(release, portable: true)!.Name);
Assert.Equal(Base + "SHA256SUMS", UpdateDownload.Checksums(release)!.DownloadUrl);
Assert.True(UpdateDownload.CanDownload(release, portable: false));
Assert.True(UpdateDownload.CanDownload(release, portable: true));
Assert.False(UpdateDownload.CanDownload(release with { Assets = [.. release.Assets.Where(a => a.Name != "SHA256SUMS")] }, portable: false));
Assert.False(UpdateDownload.CanDownload(release with { Assets = [.. release.Assets.Where(a => a.Name != PortableName)] }, portable: true));
var root = UpdateDownload.Root(Path.GetTempPath());
Assert.True(root.EndsWith(Path.Combine("Chronos", "updates"), StringComparison.Ordinal), root);
Assert.Equal(Path.Combine(root, "v1.0.0"), UpdateDownload.Folder(root, release));
}
[Test]
public async Task AVerifiedSetupIsKeptAndReusedWithoutDownloadingAgain()
{
var root = context.CreateTempDirectory();
var server = new FakeReleases(Setup);
using var http = new HttpClient(server);
var reported = new List<double>();
var path = await DownloadAsync(http, root, progress: new SyncProgress(reported.Add));
Assert.Equal(Path.Combine(root, "v1.0.0", SetupName), path);
Assert.SequenceEqual(Setup, await File.ReadAllBytesAsync(path));
Assert.Equal(1.0, reported[^1]);
Assert.Equal(1, server.PackageRequests);
Assert.SequenceEqual(new[] { SetupName }, Directory.GetFiles(Path.GetDirectoryName(path)!).Select(f => Path.GetFileName(f)));
await DownloadAsync(http, root);
Assert.Equal(1, server.PackageRequests);
}
[Test]
public async Task APortableCopyGetsThePortableZipNeverTheSetup()
{
var root = context.CreateTempDirectory();
var server = new FakeReleases(Setup);
using var http = new HttpClient(server);
var path = await DownloadAsync(http, root, portable: true);
Assert.Equal(PortableName, Path.GetFileName(path));
Assert.SequenceEqual(Portable, await File.ReadAllBytesAsync(path));
Assert.SequenceEqual(new[] { Base + PortableName }, server.PackageUrls);
}
[Test]
public async Task ASetupThatDoesNotMatchItsChecksumIsDeleted()
{
var root = context.CreateTempDirectory();
var tampered = Setup.ToArray();
tampered[^1] ^= 1;
using var http = new HttpClient(new FakeReleases(Setup) { Served = tampered });
var error = await Assert.ThrowsAsync<UpdateVerificationException>(() => DownloadAsync(http, root));
Assert.Contains("does not match", error.Message);
Assert.Empty(Directory.GetFiles(root, "*", SearchOption.AllDirectories));
}
[Test]
public async Task ACorruptedSetupLeftFromBeforeIsReplacedByAFreshDownload()
{
var root = context.CreateTempDirectory();
var server = new FakeReleases(Setup);
using var http = new HttpClient(server);
var target = Path.Combine(root, "v1.0.0", SetupName);
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
await File.WriteAllBytesAsync(target, Setup[..1000]);
Assert.Equal(target, await DownloadAsync(http, root));
Assert.SequenceEqual(Setup, await File.ReadAllBytesAsync(target));
Assert.Equal(1, server.PackageRequests);
}
[Test]
public async Task ASetupWithoutAChecksumLineIsNeverDownloaded()
{
var root = context.CreateTempDirectory();
var server = new FakeReleases(Setup) { Sums = $"{new string('0', 64)} Chronos-Uploader-Setup-1.0.0.exe\n" };
using var http = new HttpClient(server);
await Assert.ThrowsAsync<UpdateVerificationException>(() => DownloadAsync(http, root));
Assert.Equal(0, server.PackageRequests);
Assert.Empty(Directory.GetFiles(root, "*", SearchOption.AllDirectories));
}
[Test]
public async Task MoreBytesThanTheReleaseAnnouncedAreRefused()
{
var root = context.CreateTempDirectory();
var longer = Setup.Concat(new byte[100]).ToArray();
using var http = new HttpClient(new FakeReleases(Setup) { Served = longer, Sums = Sums(longer, Portable) });
await Assert.ThrowsAsync<UpdateVerificationException>(() => DownloadAsync(http, root));
Assert.Empty(Directory.GetFiles(root, "*", SearchOption.AllDirectories));
}
[Test]
public async Task AFailedRequestLeavesNoFile()
{
var root = context.CreateTempDirectory();
using var http = new HttpClient(new FakeReleases(Setup) { Fail = true });
await Assert.ThrowsAsync<HttpRequestException>(() => DownloadAsync(http, root));
Assert.Empty(Directory.GetFiles(root, "*", SearchOption.AllDirectories));
}
[Test]
public async Task ATransferCutShortIsResumedWhereItStopped()
{
var root = context.CreateTempDirectory();
var server = new FakeReleases(Setup) { CutAfter = 100_000 };
using var http = new HttpClient(server);
await Assert.ThrowsAsync<IOException>(() => DownloadAsync(http, root));
var part = Path.Combine(root, "v1.0.0", SetupName + ".part");
Assert.Equal(100_000L, new FileInfo(part).Length);
server.CutAfter = null;
var path = await DownloadAsync(http, root);
Assert.SequenceEqual(Setup, await File.ReadAllBytesAsync(path));
Assert.SequenceEqual(new long?[] { null, 100_000 }, server.Ranges);
Assert.FileMissing(part);
}
[Test]
public async Task AServerThatIgnoresTheRangeStartsTheFileAgain()
{
var root = context.CreateTempDirectory();
var server = new FakeReleases(Setup) { CutAfter = 50_000 };
using var http = new HttpClient(server);
await Assert.ThrowsAsync<IOException>(() => DownloadAsync(http, root));
server.CutAfter = null;
server.HonourRange = false;
var path = await DownloadAsync(http, root);
Assert.SequenceEqual(Setup, await File.ReadAllBytesAsync(path));
}
[Test]
public async Task ACancelledDownloadKeepsItsPartialFileForTheNextAttempt()
{
var root = context.CreateTempDirectory();
var server = new FakeReleases(Setup) { StallAfter = 64 * 1024 };
using var http = new HttpClient(server);
using var cts = new CancellationTokenSource();
var reported = new List<double>();
var download = DownloadAsync(http, root, progress: new SyncProgress(f =>
{
reported.Add(f);
cts.Cancel();
}), ct: cts.Token);
await Assert.ThrowsAsync<OperationCanceledException>(() => download);
var part = Path.Combine(root, "v1.0.0", SetupName + ".part");
Assert.Equal(64L * 1024, new FileInfo(part).Length);
server.StallAfter = null;
Assert.SequenceEqual(Setup, await File.ReadAllBytesAsync(await DownloadAsync(http, root)));
Assert.Equal(64L * 1024, server.Ranges[^1]);
}
[Test]
public async Task ATransferThatStallsFailsAfterTheIdleTimeout()
{
var root = context.CreateTempDirectory();
using var http = new HttpClient(new FakeReleases(Setup) { StallAfter = 10_000 });
var started = DateTime.UtcNow;
var error = await Assert.ThrowsAsync<TimeoutException>(() => DownloadAsync(http, root, idle: TimeSpan.FromMilliseconds(300)));
Assert.Contains("No data received", error.Message);
Assert.Less((DateTime.UtcNow - started).TotalSeconds, 20);
Assert.FileExists(Path.Combine(root, "v1.0.0", SetupName + ".part"));
}
[Test]
public async Task AnAssetOfUnknownSizeIsStillVerified()
{
var root = context.CreateTempDirectory();
using var http = new HttpClient(new FakeReleases(Setup));
var release = Release() with { Assets = [new ReleaseAsset(SetupName, Base + SetupName, -1), new ReleaseAsset("SHA256SUMS", Base + "SHA256SUMS", -1)] };
var reported = new List<double>();
var path = await UpdateDownload.DownloadAsync(http, release, false, root, "0.1.0", new SyncProgress(reported.Add), Idle, CancellationToken.None);
Assert.SequenceEqual(Setup, await File.ReadAllBytesAsync(path));
Assert.Empty(reported);
}
[Test]
public async Task AVerifiedDownloadRemovesTheFoldersOfOtherReleases()
{
var root = context.CreateTempDirectory();
var old = Directory.CreateDirectory(Path.Combine(root, "v0.9.0")).FullName;
await File.WriteAllTextAsync(Path.Combine(old, "Chronos-Setup-0.9.0.exe"), "old setup");
using var http = new HttpClient(new FakeReleases(Setup));
await DownloadAsync(http, root);
Assert.SequenceEqual(new[] { "v1.0.0" }, Directory.GetDirectories(root).Select(d => Path.GetFileName(d)));
}
private static Task<string> DownloadAsync(HttpClient http, string root, bool portable = false, IProgress<double>? progress = null, TimeSpan? idle = null,
CancellationToken ct = default) =>
UpdateDownload.DownloadAsync(http, Release(), portable, root, "0.1.0", progress, idle ?? Idle, ct);
private static ReleaseInfo Release() => new(new Version(1, 0, 0), "v1.0.0", "https://gitea.example/o/r/releases/tag/v1.0.0")
{
Assets =
[
new ReleaseAsset(SetupName, Base + SetupName, Setup.Length),
new ReleaseAsset(PortableName, Base + PortableName, Portable.Length),
new ReleaseAsset("SHA256SUMS", Base + "SHA256SUMS", 300),
],
};
private static string Sums(byte[] setup, byte[] portable) =>
$"{new string('1', 64)} Chronos-Uploader-Setup-1.0.0.exe\n{Hash(setup)} {SetupName}\n{Hash(portable)} *{PortableName}\n";
private static string Hash(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
/// <summary>
/// Serves SHA256SUMS, the setup and the portable zip like Gitea's release downloads: honours single open-ended
/// ranges, and can fail, end a transfer early or stall in the middle of it.
/// </summary>
private sealed class FakeReleases(byte[] setup) : HttpMessageHandler
{
public string Sums { get; set; } = UpdateDownloadTests.Sums(setup, Portable);
/// <summary>The setup bytes actually served (tampered or longer ones); the real setup by default.</summary>
public byte[] Served { get; set; } = setup;
public bool Fail { get; set; }
public bool HonourRange { get; set; } = true;
public int? CutAfter { get; set; }
public int? StallAfter { get; set; }
public int PackageRequests => PackageUrls.Count;
public List<string> PackageUrls { get; } = [];
public List<long?> Ranges { get; } = [];
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Assert.True(request.Headers.UserAgent.ToString().StartsWith("Chronos/", StringComparison.Ordinal), "the update requests identify the program");
var url = request.RequestUri!.AbsoluteUri;
if (url == Base + "SHA256SUMS") return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(Sums) });
var bytes = url == Base + SetupName ? Served : url == Base + PortableName ? Portable : throw new AssertionException("Unexpected request " + url);
PackageUrls.Add(url);
var from = request.Headers.Range?.Ranges.Single().From;
Ranges.Add(from);
if (Fail) return Task.FromResult(new HttpResponseMessage(HttpStatusCode.InternalServerError));
var offset = HonourRange && from is { } start ? (int)start : 0;
var end = CutAfter is { } cut ? System.Math.Min(bytes.Length, offset + cut) : bytes.Length;
var body = new StreamContent(new Body(bytes[offset..end], StallAfter));
var response = new HttpResponseMessage(offset > 0 ? HttpStatusCode.PartialContent : HttpStatusCode.OK) { Content = body };
if (offset > 0) body.Headers.ContentRange = new ContentRangeHeaderValue(offset, bytes.Length - 1, bytes.Length);
return Task.FromResult(response);
}
}
/// <summary>A non-seekable body (no Content-Length) that waits for cancellation once <paramref name="stallAfter"/> bytes are read.</summary>
private sealed class Body(byte[] bytes, int? stallAfter) : Stream
{
private int _position;
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => throw new NotSupportedException();
public override long Position { get => _position; set => throw new NotSupportedException(); }
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
if (_position == stallAfter) await Task.Delay(Timeout.Infinite, cancellationToken);
var limit = stallAfter is { } stall && _position < stall ? stall : bytes.Length;
var count = System.Math.Min(buffer.Length, limit - _position);
bytes.AsMemory(_position, count).CopyTo(buffer);
_position += count;
return count;
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
public override void Flush() => throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
}
/// <summary>Reports synchronously (<see cref="Progress{T}"/> would post to the thread pool).</summary>
private sealed class SyncProgress(Action<double> report) : IProgress<double>
{
public void Report(double value) => report(value);
}
}
@@ -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)));
}