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

@@ -0,0 +1,180 @@
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Housekeeping;
using Chronos.Data.Jobs;
using Chronos.Data.Tests.Jobs;
using Chronos.Testing;
using static Chronos.Data.Tests.Archiving.ArchiveFixture;
namespace Chronos.Data.Tests.Archiving;
/// <summary>
/// What the archive jobs say they are doing (owner review 5, #65): the step, the item, photo x of y and sequence, folder
/// or step n of m, sent as the job's progress detail; no localized text in it.
/// </summary>
[Category("archive")]
public sealed class ArchiveProgressDetailTests(TestContext context)
{
private static void Populate(ArchiveFixture fx)
{
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "a"), Start, 4);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "b"), Start.AddDays(1), 3, firstSeed: 50);
}
private static async Task<(DetailRecorder Recorder, JobEngine Engine)> StartAsync(ArchiveFixture fx)
{
var recorder = new DetailRecorder();
var engine = recorder.Engine(fx.Db, fx.Service.CreateJobHandlers());
await engine.StartAsync(fx.Ct);
return (recorder, engine);
}
private static async Task<Guid> RunAsync(ArchiveFixture fx, JobEngine engine, ArchiveJobRequest request)
{
var job = await engine.EnqueueAsync(request, cancellationToken: fx.Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
return job.Id;
}
[Test]
public async Task AScanListsThenIndexesEachNewFolderPhotoByPhotoAndChecksThemOnARescan()
{
await using var fx = await CreateAsync(context);
Populate(fx);
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var first = await RunAsync(fx, engine, ArchiveJobs.Scan(fx.Archive));
var details = recorder.Details(first);
Assert.Equal(JobStep.List, details[0].Step);
var index = details.Where(d => d.Step == JobStep.Index).ToList();
Assert.Equal(new JobDetail(JobStep.Index, "a", 0, 0, 1, 2, JobPartUnit.Folder), index[0]);
// Photo after photo inside an adopted folder, then the next folder.
Assert.SequenceEqual([1L, 2L, 3L, 4L], index.Where(d => d.Item == "a" && d.ItemTotal > 0).Select(d => d.ItemDone));
Assert.True(index.Where(d => d.ItemTotal > 0).All(d => d.ItemTotal == (d.Item == "a" ? 4 : 3)));
Assert.SequenceEqual([1, 2], index.Select(d => d.Part).Distinct());
Assert.True(index.All(d => d.Parts == 2 && d.PartUnit == JobPartUnit.Folder));
Assert.Equal(JobStep.Index, recorder.Steps(first)[1]);
// Nothing changed: each folder is checked, folder n of m, and nothing is indexed.
var again = await RunAsync(fx, engine, ArchiveJobs.Scan(fx.Archive));
Assert.SequenceEqual([JobStep.List, JobStep.Check], recorder.Steps(again));
var check = recorder.Details(again).Where(d => d.Step == JobStep.Check).ToList();
Assert.SequenceEqual([("a", 1), ("b", 2)], check.Select(d => (d.Item!, d.Part)));
Assert.True(check.All(d => d.Parts == 2 && d.PartUnit == JobPartUnit.Folder));
}
[Test]
public async Task AVerifyCountsThePhotosOfEachSequence()
{
await using var fx = await CreateAsync(context);
Populate(fx);
await fx.ScanAsync();
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var id = await RunAsync(fx, engine, ArchiveJobs.Verify(fx.Archive));
var details = recorder.Details(id);
Assert.True(details.All(d => d.Step == JobStep.Verify && d.PartUnit == JobPartUnit.Sequence && d.Parts == 2), string.Join("; ", details));
Assert.SequenceEqual([(1, 1L), (1, 2L), (1, 3L), (1, 4L), (2, 1L), (2, 2L), (2, 3L)], details.Select(d => (d.Part, d.ItemDone)));
Assert.SequenceEqual([4L, 3L], details.GroupBy(d => d.Part).Select(g => g.Max(d => d.ItemTotal)));
Assert.True(details.All(d => !string.IsNullOrEmpty(d.Item)));
}
[Test]
public async Task AThumbnailPassReportsEachFrameOfEachSequence()
{
await using var fx = await CreateAsync(context);
Populate(fx);
await fx.ScanAsync();
var ids = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Select(l => l.Id).ToList();
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var id = await RunAsync(fx, engine, ArchiveJobs.Thumbnails(ids));
var details = recorder.Details(id);
Assert.True(details.All(d => d.Step == JobStep.Thumbs && d.PartUnit == JobPartUnit.Sequence && d.Parts == 2), string.Join("; ", details));
Assert.SequenceEqual([1, 2], details.Select(d => d.Part).Distinct());
// Every frame of a sequence goes out, up to its last.
Assert.SequenceEqual([(1, 4L), (2, 3L)], details.GroupBy(d => d.Part).Select(g => (g.Key, g.Max(d => d.ItemDone))));
Assert.True(details.GroupBy(d => d.Part).All(g => g.Count() >= g.Max(d => d.ItemTotal)));
}
[Test]
public async Task MaintenanceNamesItsStepsInOrder()
{
await using var fx = await CreateAsync(context);
Populate(fx);
await fx.ScanAsync();
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var id = await RunAsync(fx, engine, ArchiveJobs.Maintenance(fx.Archive));
var details = recorder.Details(id);
var steps = details.Where(d => d.Step == JobStep.Maintenance).ToList();
Assert.SequenceEqual(["leases", "temp", "packs", "duplicates", "vacuum"], steps.Select(d => d.Item!));
Assert.SequenceEqual([1, 2, 3, 4, 5], steps.Select(d => d.Part));
Assert.True(steps.All(d => d.Parts == 5 && d.PartUnit == JobPartUnit.Step));
Assert.SequenceEqual([JobStep.Maintenance, JobStep.Check], recorder.Steps(id));
}
[Test]
public async Task DuplicatesAndOrphansRunWithoutACount()
{
await using var fx = await CreateAsync(context);
Populate(fx);
await fx.ScanAsync();
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
foreach (var request in new[] { ArchiveJobs.Duplicates(fx.Archive), ArchiveJobs.Orphans(fx.Archive) })
{
var id = await RunAsync(fx, engine, request);
// Every report until the one that completes it.
var reports = recorder.Of(id);
var running = reports.TakeWhile(p => p.Total == 0 || p.Done < p.Total).ToList();
Assert.NotEmpty(running);
Assert.True(running.All(p => p.Detail == new JobDetail(JobStep.Check) && p.Total == 0),
$"{request.Kind}: {string.Join("; ", reports.Select(p => $"{p.Done}/{p.Total} {p.Detail}"))}");
}
}
[Test]
public async Task ABackupRunsWithoutACountAndACleanupNamesItsSteps()
{
await using var fx = await CreateAsync(context);
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var backup = await RunAsync(fx, engine, ArchiveJobs.Backup(keep: 1));
var reports = recorder.Of(backup);
var running = reports.TakeWhile(p => p.Total == 0 || p.Done < p.Total).ToList();
Assert.NotEmpty(running);
Assert.True(running.All(p => p.Detail == new JobDetail(JobStep.Backup) && p.Total == 0), string.Join("; ", reports.Select(p => $"{p.Done}/{p.Total} {p.Detail}")));
var cleanup = await RunAsync(fx, engine, ArchiveJobs.Cleanup(fx.Archive, [CleanupSteps.JobHistory, CleanupSteps.Audit], 0));
var steps = recorder.Details(cleanup);
Assert.SequenceEqual([(CleanupSteps.JobHistory, 1), (CleanupSteps.Audit, 2)], steps.Select(d => (d.Item!, d.Part)));
Assert.True(steps.All(d => d.Step == JobStep.Cleanup && d.Parts == 2 && d.PartUnit == JobPartUnit.Step));
}
[Test]
public async Task EmptyingTheTrashCountsItsEntries()
{
await using var fx = await CreateAsync(context);
Populate(fx);
await fx.ScanAsync();
var ids = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Select(l => l.Id).ToList();
await fx.Service.DeleteAsync(await fx.Service.PlanDeleteAsync(ids, null, fx.Ct), null, null, fx.Ct);
var empty = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var id = await RunAsync(fx, engine, ArchiveJobs.EmptyTrash(fx.Archive, empty));
var details = recorder.Details(id);
Assert.True(details.All(d => d.Step == JobStep.Erase && d.PartUnit == JobPartUnit.Entry && d.Parts == 2), string.Join("; ", details));
Assert.SequenceEqual([1, 2], details.Select(d => d.Part));
Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct));
}
}
@@ -366,7 +366,7 @@ public abstract class PartialRowWriterTests(TestContext context) : DatabaseTest(
// The first verify of photos a scan adopted hashes them all; a thumbnail pass records a preview-only frame meanwhile.
var recorded = false;
var report = await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async (_, _) =>
var report = await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async _ =>
{
if (recorded) return;
recorded = true;
@@ -399,7 +399,7 @@ public abstract class PartialRowWriterTests(TestContext context) : DatabaseTest(
// The verify finds the file missing, and an upload puts it back before the verify writes what it found.
var checkedFrames = 0;
var report = await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async (_, _) =>
var report = await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async _ =>
{
if (++checkedFrames != 2) return;
Assert.True((await fx.Service.Ingest.CommitAsync(Upload(fx.Stage(Start.AddSeconds(10), seed: 2)), fx.Ct)).Repaired, "repaired");
@@ -570,9 +570,9 @@ public abstract class PartialRowWriterTests(TestContext context) : DatabaseTest(
// The server's PATCH takes the row as the last photo is checked, and commits while the verify stamps the sequence.
Task? commit = null;
await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async (done, total) =>
await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async p =>
{
if (done < total || commit is not null) return;
if (p.BytesDone < p.BytesTotal || commit is not null) return;
var tx = await fx.Db.BeginAsync(fx.Ct);
await tx.Sequences.EditAsync(sequence.Id, new SequenceEdit { SettingsJson = """{"heroFrame":1}""" }, sequence.SettingsVersion, fx.Ct);
commit = CommitLaterAsync(tx, fx.Ct);
@@ -0,0 +1,122 @@
using System.Security.Cryptography;
using System.Text;
using Chronos.Core.Archiving;
using Chronos.Core.Project;
using Chronos.Data.Workspaces;
namespace Chronos.Data.Tests.Homes;
/// <summary>Workspaces and caches laid out as 1.0 left them, for the sorting into homes (owner review 5, #66).</summary>
internal static class HomeFixtures
{
public const string Nas = "https://nas.local:8443";
public const string NasByIp = "https://192.168.1.5:8443";
public const string Other = "https://other.example:8443";
/// <summary>A working state of <paramref name="home"/> written into <c>&lt;root&gt;/&lt;id&gt;</c> with some media, versions and a render.</summary>
public static Guid Project(string root, BundleHome home, string name = "Main", DateTimeOffset? saved = null, Guid? id = null, int proxies = 3)
{
var projectId = id ?? Guid.CreateVersion7();
var folder = Path.Combine(root, projectId.ToString("N"));
Directory.CreateDirectory(folder);
var archive = home.IsArchive
? new BundleArchive(home.ArchiveId ?? Guid.CreateVersion7(), "This PC", @"D:\ChronosArchive")
: new BundleArchive(Data.Projects.ServerProjectHome.ArchiveIdOf(home.Server!), "Studio NAS", null);
var bundle = new ProjectBundle(archive, new BundleSequence(home.SequenceId, "2026/2026-11-15 Harbour", "Harbour", proxies), new ProjectSettings(),
saved ?? DateTimeOffset.UtcNow)
{
Workspace = new BundleWorkspace(projectId, name, true, home, null, new BundleMedia(BundleMedia.Proxies, 1)),
};
bundle.Save(Path.Combine(folder, WorkspaceProject.BundleFile));
var media = Path.Combine(folder, WorkspaceProject.MediaFolder, WorkspaceProject.ProxiesFolder);
Directory.CreateDirectory(media);
for (var i = 0; i < proxies; i++) File.WriteAllBytes(Path.Combine(media, Guid.CreateVersion7().ToString("N") + ".jpg"), Bytes(projectId, i, 500 + i));
Directory.CreateDirectory(Path.Combine(folder, WorkspaceProject.VersionsFolder));
File.WriteAllText(Path.Combine(folder, WorkspaceProject.VersionsFolder, "1-" + Guid.CreateVersion7().ToString("N") + ".json"), "{}");
Directory.CreateDirectory(Path.Combine(folder, WorkspaceProject.ExportsFolder));
File.WriteAllBytes(Path.Combine(folder, WorkspaceProject.ExportsFolder, "render.mp4"), Bytes(projectId, 99, 2048));
return projectId;
}
public static BundleHome Local() => new(BundleHome.ArchiveKind, Guid.CreateVersion7(), Guid.CreateVersion7());
public static BundleHome Server(string key) => new(BundleHome.ServerKind, Guid.CreateVersion7(), null, key);
/// <summary>A 1.0 workspace: its manifest (format 1) and the folder.</summary>
public static string LegacyWorkspace(string parent)
{
var root = Path.Combine(parent, "workspace");
_ = new WorkspaceStore(root);
return root;
}
/// <summary>A trash entry of <paramref name="projectId"/> holding a working state, as a removal leaves it.</summary>
public static string TrashEntry(string root, Guid projectId, BundleHome home)
{
var trash = Path.Combine(root, WorkspaceTrash.FolderName);
var staging = Path.Combine(trash, "staging");
Directory.CreateDirectory(staging);
Project(staging, home, id: projectId, proxies: 1);
var entry = Path.Combine(trash, projectId.ToString("N") + "-638000000000000000");
Directory.Move(Path.Combine(staging, projectId.ToString("N")), entry);
Directory.Delete(staging);
return entry;
}
/// <summary>The 1.0 proxy cache of <paramref name="key"/>'s sequence <paramref name="remoteId"/>.</summary>
public static string LegacyProxies(string cache, string key, Guid remoteId, int frames = 2)
{
var folder = Data.Sync.ProxyCache.LegacyFolder(Path.Combine(cache, "proxies"), key, remoteId);
Directory.CreateDirectory(folder);
File.WriteAllText(Path.Combine(folder, "remote.json"), "{}");
for (var i = 0; i < frames; i++) File.WriteAllBytes(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + ".jpg"), Bytes(remoteId, i, 300));
return folder;
}
/// <summary>A live lease on a project folder, as another Chronos working on the same workspace holds it.</summary>
public static LeaseFile Hold(string projectFolder) =>
LeaseFile.TryAcquire(projectFolder, ".lock", "workspace@other", TimeSpan.FromMinutes(5)) ?? throw new InvalidOperationException("The lease is held.");
/// <summary>
/// The SHA-256 of every file under <paramref name="root"/> by its name relative to the project or entry it belongs to,
/// whatever home folder holds it: the same before and after a sorting that only renames (the test-only proof).
/// </summary>
public static SortedDictionary<string, string> Manifest(string root)
{
var manifest = new SortedDictionary<string, string>(StringComparer.Ordinal);
if (!Directory.Exists(root)) return manifest;
foreach (var file in Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories))
{
var relative = Path.GetRelativePath(root, file).Replace('\\', '/');
var name = Path.GetFileName(file);
if (name is WorkspaceStore.ManifestFile or "server.json" && !relative.Contains('/', StringComparison.Ordinal)) continue;
if (name is WorkspaceStore.ManifestFile or "server.json" && IsHomeLevel(relative)) continue;
manifest[Strip(relative)] = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(file))) + "|" + new FileInfo(file).Length;
}
return manifest;
}
/// <summary>A path without the home folders it lies in (<c>local/</c>, <c>servers/&lt;folder&gt;/</c>).</summary>
private static string Strip(string relative)
{
if (relative.StartsWith("local/", StringComparison.Ordinal)) return relative["local/".Length..];
if (relative.StartsWith("servers/", StringComparison.Ordinal))
{
var rest = relative["servers/".Length..];
var slash = rest.IndexOf('/', StringComparison.Ordinal);
return slash < 0 ? rest : rest[(slash + 1)..];
}
return relative;
}
private static bool IsHomeLevel(string relative) =>
relative.Split('/') is { Length: 2 } parts && parts[0] == "local" || relative.Split('/') is { Length: 3 } more && more[0] == "servers";
private static byte[] Bytes(Guid seed, int index, int length)
{
var bytes = new byte[length];
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(seed.ToString("N") + index));
for (var i = 0; i < length; i++) bytes[i] = hash[i % hash.Length];
return bytes;
}
}
@@ -0,0 +1,302 @@
using Chronos.Core.IO;
using Chronos.Core.Project;
using Chronos.Data.Homes;
using Chronos.Data.Sync;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.Data.Tests.Homes;
/// <summary>The one-time sorting of a 1.0 workspace and cache into homes (owner review 5, #66).</summary>
[Category("homes")]
public sealed class HomeLayoutMigrationTests(TestContext context)
{
private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
/// <summary>A 1.0 data folder: a workspace with local, server and damaged projects and a trash, and a cache with proxies, render-node files and a staged import.</summary>
private sealed class Legacy
{
public required string Data { get; init; }
public required string Workspace { get; init; }
public required string Cache { get; init; }
public required Guid Local { get; init; }
public required Guid OnNas { get; init; }
public required Guid OnOther { get; init; }
public required Guid Damaged { get; init; }
public required Guid NasRemote { get; init; }
public HomeLayoutMigration Migration(ServerIdentity? identity = null, Action<string, string>? cut = null) =>
new(new HomeLayoutOptions
{
DataDirectory = Data,
WorkspaceRoot = Workspace,
CacheRoot = Cache,
Identity = identity ?? ServerIdentity.None,
CurrentServer = HomeFixtures.Nas,
})
{ Cut = cut };
}
private Legacy Make()
{
var data = context.CreateTempDirectory("data");
var workspace = HomeFixtures.LegacyWorkspace(data);
var local = HomeFixtures.Project(workspace, HomeFixtures.Local());
var onNas = HomeFixtures.Project(workspace, HomeFixtures.Server(HomeFixtures.Nas));
var onOther = HomeFixtures.Project(workspace, HomeFixtures.Server(HomeFixtures.Other));
var damaged = Guid.CreateVersion7();
Directory.CreateDirectory(Path.Combine(workspace, damaged.ToString("N")));
File.WriteAllText(Path.Combine(workspace, damaged.ToString("N"), WorkspaceProject.BundleFile), "{ not json");
HomeFixtures.TrashEntry(workspace, onNas, HomeFixtures.Server(HomeFixtures.Nas));
File.WriteAllText(Path.Combine(workspace, WorkspaceTrash.FolderName, "loose.txt"), "kept");
var cache = Path.Combine(data, "cache");
var nasRemote = Guid.CreateVersion7();
HomeFixtures.LegacyProxies(cache, HomeFixtures.Nas, nasRemote);
HomeFixtures.LegacyProxies(cache, HomeFixtures.Other, Guid.CreateVersion7());
Directory.CreateDirectory(Path.Combine(cache, "render-node", "job1"));
File.WriteAllText(Path.Combine(cache, "render-node", "job1", "frame.jpg"), "rn");
Directory.CreateDirectory(Path.Combine(cache, "server-import"));
File.WriteAllText(Path.Combine(cache, "server-import", "card.part"), "import");
return new Legacy
{
Data = data,
Workspace = workspace,
Cache = cache,
Local = local,
OnNas = onNas,
OnOther = onOther,
Damaged = damaged,
NasRemote = nasRemote,
};
}
/// <summary>Every file and folder under <paramref name="root"/> with its size and time: what a dry run must leave as it was.</summary>
private static List<string> Snapshot(string root) =>
[.. new DirectoryInfo(root).EnumerateFileSystemInfos("*", SearchOption.AllDirectories)
.Select(e => Path.GetRelativePath(root, e.FullName) + "|" + (e is FileInfo f ? f.Length + "|" + f.LastWriteTimeUtc.Ticks : "dir"))
.Order(StringComparer.Ordinal)];
private static string Home(string workspace, string key) => Path.Combine(workspace, "servers", HomeFolders.ServerFolder(key));
private static void AssertSorted(Legacy legacy, string nasFolder)
{
var ws = legacy.Workspace;
Assert.True(WorkspaceHomes.IsSplitRoot(ws));
Assert.FileExists(Path.Combine(ws, "local", legacy.Local.ToString("N"), WorkspaceProject.BundleFile));
Assert.FileExists(Path.Combine(ws, "local", legacy.Damaged.ToString("N"), WorkspaceProject.BundleFile));
Assert.FileExists(Path.Combine(ws, "servers", nasFolder, legacy.OnNas.ToString("N"), WorkspaceProject.BundleFile));
Assert.FileExists(Path.Combine(Home(ws, HomeFixtures.Other), legacy.OnOther.ToString("N"), WorkspaceProject.BundleFile));
Assert.FileExists(Path.Combine(ws, "local", WorkspaceTrash.FolderName, "loose.txt"));
Assert.Count(1, Directory.EnumerateDirectories(Path.Combine(ws, "servers", nasFolder, WorkspaceTrash.FolderName)));
Assert.False(Directory.EnumerateDirectories(ws).Any(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _)), "no project is left in the parent");
Assert.False(Directory.Exists(Path.Combine(ws, WorkspaceTrash.FolderName)), "the parent's emptied trash went");
Assert.Equal("Studio NAS", Assert.NotNull(ServerHomeRecord.Read(Path.Combine(ws, "servers", nasFolder))).Name);
Assert.FileExists(Path.Combine(legacy.Cache, "servers", nasFolder, "proxies", legacy.NasRemote.ToString("N"), "remote.json"));
Assert.True(Directory.Exists(Path.Combine(legacy.Cache, "servers", HomeFolders.ServerFolder(HomeFixtures.Other), "proxies")));
Assert.FileExists(Path.Combine(legacy.Cache, "servers", nasFolder, "render-node", "job1", "frame.jpg"));
Assert.FileExists(Path.Combine(legacy.Cache, "servers", nasFolder, "import", "card.part"));
Assert.False(Directory.Exists(Path.Combine(legacy.Cache, "render-node")));
Assert.FileMissing(Path.Combine(legacy.Data, HomeLayoutMigration.JournalFile));
var homes = new WorkspaceHomes(ws);
Assert.True(homes.IsSplit);
Assert.Equal(4, homes.List().Count);
}
[Test]
public async Task ThePlanWritesNothing()
{
var legacy = Make();
var before = Snapshot(legacy.Data);
var plan = await legacy.Migration().PlanAsync(context.Cancellation);
Assert.SequenceEqual(before, Snapshot(legacy.Data));
Assert.True(plan.SplitsWorkspace);
Assert.Null(plan.Deferred);
Assert.Equal(4, plan.Projects);
Assert.Equal(2, plan.Entries.Count(e => e.Kind == HomeEntryKind.Trash));
Assert.Equal(2, plan.Entries.Count(e => e.Kind == HomeEntryKind.Proxies));
Assert.Equal(1, plan.Entries.Count(e => e.Kind == HomeEntryKind.RenderNode));
Assert.Equal(1, plan.Entries.Count(e => e.Kind == HomeEntryKind.Import));
var damaged = plan.Entries.Single(e => e.Source.EndsWith(legacy.Damaged.ToString("N"), StringComparison.Ordinal));
Assert.Equal(Path.Combine(legacy.Workspace, "local", legacy.Damaged.ToString("N")), damaged.Target);
Assert.Equal(plan.Fingerprint, (await legacy.Migration().PlanAsync(context.Cancellation)).Fingerprint);
}
[Test]
public async Task SortingMovesEveryHomeAndRenamesOnly()
{
var legacy = Make();
var before = HomeFixtures.Manifest(legacy.Workspace);
var cacheBefore = HomeFixtures.Manifest(legacy.Cache);
var result = await legacy.Migration().ApplyAsync(context.Cancellation);
Assert.Equal((4, 0, false, true), (result.ProjectsMoved, result.InUse, result.Resumed, result.Split));
AssertSorted(legacy, HomeFolders.ServerFolder(HomeFixtures.Nas));
// Every file is there with the same name relative to its project and the same bytes: the sorting only renamed.
Assert.SequenceEqual(before, HomeFixtures.Manifest(legacy.Workspace));
Assert.SequenceEqual(cacheBefore.Values.Order(), HomeFixtures.Manifest(legacy.Cache).Values.Order());
// A second run does nothing.
var again = await legacy.Migration().ApplyAsync(context.Cancellation);
Assert.Equal(HomeLayoutResult.Nothing, again);
Assert.True((await legacy.Migration().PlanAsync(context.Cancellation)).IsEmpty);
}
[Test]
public async Task AServerKnownByIdGetsItsIdHome()
{
var legacy = Make();
await legacy.Migration(new ServerIdentity([new KnownServerKey(Id, [HomeFixtures.Nas])])).ApplyAsync(context.Cancellation);
AssertSorted(legacy, Id.ToString("N"));
Assert.Equal(ServerIdentity.IdKey(Id), Assert.NotNull(ServerHomeRecord.Read(Path.Combine(legacy.Workspace, "servers", Id.ToString("N")))).Key);
}
[Test]
public async Task ACrashAtAnyStepIsTakenUpToTheSameEnd()
{
var entries = (await Make().Migration().PlanAsync(context.Cancellation)).Entries.Count;
var cuts = new List<(string Step, int Occurrence)> { ("journal", 1), ("commit", 1) };
for (var i = 1; i <= entries; i++) cuts.AddRange([("rename", i), ("renamed", i)]);
foreach (var (step, occurrence) in cuts)
{
var legacy = Make();
var before = HomeFixtures.Manifest(legacy.Workspace);
var seen = 0;
var crashing = legacy.Migration(cut: (name, _) =>
{
if (name == step && ++seen == occurrence) throw new IOException("cut at " + step);
});
await Assert.ThrowsAsync<IOException>(() => crashing.ApplyAsync(context.Cancellation));
Assert.FileExists(Path.Combine(legacy.Data, HomeLayoutMigration.JournalFile));
var resumed = await legacy.Migration().ApplyAsync(context.Cancellation);
Assert.True(resumed.Resumed, $"{step} #{occurrence}");
AssertSorted(legacy, HomeFolders.ServerFolder(HomeFixtures.Nas));
Assert.SequenceEqual(before, HomeFixtures.Manifest(legacy.Workspace), $"{step} #{occurrence}");
Assert.Equal(HomeLayoutResult.Nothing, await legacy.Migration().ApplyAsync(context.Cancellation));
}
}
[Test]
public async Task AProjectInUseIsLeftAndMovedAtALaterStart()
{
var legacy = Make();
var held = HomeFixtures.Hold(Path.Combine(legacy.Workspace, legacy.Local.ToString("N")));
HomeLayoutResult result;
using (held)
{
var plan = await legacy.Migration().PlanAsync(context.Cancellation);
Assert.SequenceEqual(new[] { legacy.Local }, plan.InUse);
result = await legacy.Migration().ApplyAsync(context.Cancellation);
Assert.Equal((3, 1, true), (result.ProjectsMoved, result.InUse, result.Split));
Assert.True(WorkspaceHomes.IsSplitRoot(legacy.Workspace));
var homes = new WorkspaceHomes(legacy.Workspace);
Assert.Equal(homes.Root, Path.GetDirectoryName(Assert.NotNull(homes.Find(legacy.Local)).Folder));
Assert.Equal(4, homes.List().Count);
// A copy, render or send job of the project left in place still finds it: the parent opens as the view of what it holds.
var root = WorkspaceJobRoots.Resolve(legacy.Workspace, legacy.Local, null, "Errors.Workspace.NotCheckedOut");
Assert.Equal(WorkspaceStore.FullRoot(legacy.Workspace), root);
Assert.Throws<InvalidDataException>(() => new WorkspaceStore(root));
Assert.NotNull(WorkspaceStore.ForJob(root).Find(legacy.Local));
}
result = await legacy.Migration().ApplyAsync(context.Cancellation);
Assert.Equal((1, 0), (result.ProjectsMoved, result.InUse));
Assert.FileExists(Path.Combine(legacy.Workspace, "local", legacy.Local.ToString("N"), WorkspaceProject.BundleFile));
Assert.Null(new WorkspaceHomes(legacy.Workspace).Homes().FirstOrDefault(h => h.IsLegacy));
}
[Test]
public async Task AnUnfinishedMoveDefersTheWorkspaceWhileTheCacheIsSorted()
{
var legacy = Make();
File.WriteAllText(Path.Combine(legacy.Workspace, WorkspaceMover.JournalFile), "{}");
var before = Snapshot(legacy.Workspace);
var result = await legacy.Migration().ApplyAsync(context.Cancellation);
Assert.Equal((HomeLayoutDeferral?)HomeLayoutDeferral.Moving, result.Deferred);
Assert.False(result.Split);
Assert.SequenceEqual(before, Snapshot(legacy.Workspace));
Assert.FileExists(Path.Combine(legacy.Cache, "servers", HomeFolders.ServerFolder(HomeFixtures.Nas), "proxies", legacy.NasRemote.ToString("N"), "remote.json"));
File.Delete(Path.Combine(legacy.Workspace, WorkspaceMover.JournalFile));
await legacy.Migration().ApplyAsync(context.Cancellation);
AssertSorted(legacy, HomeFolders.ServerFolder(HomeFixtures.Nas));
}
[Test]
public async Task AWorkspaceThatWentOfflineWaitsWithItsJournal()
{
var legacy = Make();
var before = HomeFixtures.Manifest(legacy.Workspace);
await Assert.ThrowsAsync<IOException>(() => legacy.Migration(cut: (name, _) =>
{
if (name == "journal") throw new IOException("cut");
}).ApplyAsync(context.Cancellation));
// The drive goes before the next start.
var away = legacy.Workspace + "-unplugged";
Directory.Move(legacy.Workspace, away);
var waiting = await legacy.Migration().ApplyAsync(context.Cancellation);
Assert.Equal((HomeLayoutDeferral?)HomeLayoutDeferral.Offline, waiting.Deferred);
Assert.FileExists(Path.Combine(legacy.Data, HomeLayoutMigration.JournalFile));
Assert.FileExists(Path.Combine(legacy.Cache, "servers", HomeFolders.ServerFolder(HomeFixtures.Nas), "import", "card.part"));
// Back: the workspace is sorted, the cache left as it is now.
Directory.Move(away, legacy.Workspace);
await legacy.Migration().ApplyAsync(context.Cancellation);
AssertSorted(legacy, HomeFolders.ServerFolder(HomeFixtures.Nas));
Assert.SequenceEqual(before, HomeFixtures.Manifest(legacy.Workspace));
}
[Test]
public async Task AProjectInBothPlacesKeepsTheCopySavedLastAndTrashesTheOther()
{
var data = context.CreateTempDirectory("data");
var workspace = HomeFixtures.LegacyWorkspace(data);
var id = Guid.CreateVersion7();
var home = HomeFixtures.Local();
HomeFixtures.Project(workspace, home, "newer", DateTimeOffset.UtcNow, id);
HomeFixtures.Project(Path.Combine(workspace, "local"), home, "older", DateTimeOffset.UtcNow.AddDays(-1), id);
var files = Directory.EnumerateFiles(workspace, "*", SearchOption.AllDirectories).Count(f => Path.GetFileName(f) != WorkspaceStore.ManifestFile);
var result = await new HomeLayoutMigration(new HomeLayoutOptions { DataDirectory = data, WorkspaceRoot = workspace }).ApplyAsync(context.Cancellation);
Assert.Equal(1, result.Clashes);
var kept = ProjectBundle.Load(Path.Combine(workspace, "local", id.ToString("N"), WorkspaceProject.BundleFile));
Assert.Equal("newer", kept.Workspace!.Name);
var trashed = Assert.NotNull(Directory.EnumerateDirectories(Path.Combine(workspace, "local", WorkspaceTrash.FolderName)).SingleOrDefault());
Assert.Equal("older", ProjectBundle.Load(Path.Combine(trashed, WorkspaceProject.BundleFile)).Workspace!.Name);
Assert.Equal(files, Directory.EnumerateFiles(workspace, "*", SearchOption.AllDirectories)
.Count(f => Path.GetFileName(f) is not (WorkspaceStore.ManifestFile or "server.json")), "nothing was deleted");
}
[Test]
public async Task ARenameThatDoesNotCheckStopsWithItsJournal()
{
var legacy = Make();
var tampered = false;
var migration = legacy.Migration(cut: (name, path) =>
{
if (name != "renamed" || tampered || !Directory.Exists(path)) return;
tampered = true;
File.WriteAllText(Path.Combine(path, "stray.txt"), "written meanwhile");
});
await Assert.ThrowsAsync<HomeLayoutException>(() => migration.ApplyAsync(context.Cancellation));
Assert.FileExists(Path.Combine(legacy.Data, HomeLayoutMigration.JournalFile));
// The next start takes it up; the entry found renamed is taken as moved.
await legacy.Migration().ApplyAsync(context.Cancellation);
AssertSorted(legacy, HomeFolders.ServerFolder(HomeFixtures.Nas));
}
[Test]
public async Task AWorkspaceNeverMadeOrAlreadySortedHasNothingToDo()
{
var data = context.CreateTempDirectory("data");
var options = new HomeLayoutOptions { DataDirectory = data, WorkspaceRoot = Path.Combine(data, "workspace"), CacheRoot = Path.Combine(data, "cache") };
Assert.True((await new HomeLayoutMigration(options).PlanAsync(context.Cancellation)).IsEmpty);
Assert.Equal(HomeLayoutResult.Nothing, await new HomeLayoutMigration(options).ApplyAsync(context.Cancellation));
Assert.False(Directory.Exists(options.WorkspaceRoot));
_ = new WorkspaceHomes(options.WorkspaceRoot);
Assert.True((await new HomeLayoutMigration(options).PlanAsync(context.Cancellation)).IsEmpty);
// An empty 1.0 workspace is split by its manifest alone.
var empty = HomeFixtures.LegacyWorkspace(context.CreateTempDirectory("empty"));
var split = await new HomeLayoutMigration(options with { WorkspaceRoot = empty }).ApplyAsync(context.Cancellation);
Assert.True(split.Split);
Assert.True(WorkspaceHomes.IsSplitRoot(empty));
Assert.Equal(WorkspaceStore.FormatVersion, new WorkspaceStore(Path.Combine(empty, "local")).Manifest.FormatVersion);
}
}
@@ -0,0 +1,215 @@
using Chronos.Core.IO;
using Chronos.Core.Project;
using Chronos.Data.Homes;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Data.Tests.Repositories;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.Data.Tests.Homes;
/// <summary>A server's home moves from its address to its id when it first announces one (owner review 5, #66).</summary>
[Category("homes")]
public sealed class HomeRekeyTests(TestContext context)
{
private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
private static string IdFolder => Id.ToString("N");
private (string Data, WorkspaceHomes Homes, string Cache) Make()
{
var data = context.CreateTempDirectory("data");
return (data, new WorkspaceHomes(Path.Combine(data, "workspace")), Path.Combine(data, "cache"));
}
private static HomeLayoutMigration Migration(string data, WorkspaceHomes homes, string cache) =>
new(new HomeLayoutOptions { DataDirectory = data, WorkspaceRoot = homes.Root, CacheRoot = cache });
private static string AddressHome(string root, string key) => Path.Combine(root, "servers", HomeFolders.ServerFolder(key));
private static ProjectBundle Bundle(string home, Guid id) => ProjectBundle.Load(Path.Combine(home, id.ToString("N"), WorkspaceProject.BundleFile));
[Test]
public async Task TheHomeOfTheAddressBecomesTheHomeOfTheId()
{
var (data, homes, cache) = Make();
var home = HomeFixtures.Server(HomeFixtures.Nas);
var store = homes.StoreFor(home);
var (a, b) = (HomeFixtures.Project(store.Root, home), HomeFixtures.Project(store.Root, HomeFixtures.Server(HomeFixtures.Nas)));
HomeFixtures.TrashEntry(store.Root, a, home);
var before = HomeFixtures.Manifest(homes.Root);
var (sorted, old) = (Guid.CreateVersion7(), Guid.CreateVersion7());
var cached = Path.Combine(AddressHome(cache, HomeFixtures.Nas), "proxies", sorted.ToString("N"));
Directory.CreateDirectory(cached);
File.WriteAllText(Path.Combine(cached, "remote.json"), "{}");
HomeFixtures.LegacyProxies(cache, HomeFixtures.Nas, old);
var result = await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas], context.Cancellation);
Assert.Equal(new HomeRekeyResult(2, 0, 0, 2, 0, 0, 0), result);
var idHome = Path.Combine(homes.Root, "servers", IdFolder);
Assert.False(Directory.Exists(AddressHome(homes.Root, HomeFixtures.Nas)));
var idKey = ServerIdentity.IdKey(Id);
foreach (var id in new[] { a, b })
{
var bundle = Bundle(idHome, id);
Assert.Equal(idKey, bundle.Workspace!.Home!.Server);
Assert.Equal(ServerProjectHome.ArchiveIdOf(idKey), bundle.Archive.Id);
}
var record = Assert.NotNull(ServerHomeRecord.Read(idHome));
Assert.Equal((idKey, (Guid?)Id, HomeFixtures.Nas), (record.Key, record.Id, record.Address));
Assert.Count(1, Directory.EnumerateDirectories(Path.Combine(idHome, WorkspaceTrash.FolderName)));
// Only the working states were rewritten: every other file is as it was.
var after = HomeFixtures.Manifest(homes.Root);
Assert.SequenceEqual(before.Keys, after.Keys);
Assert.SequenceEqual(before.Where(f => !f.Key.EndsWith(WorkspaceProject.BundleFile, StringComparison.Ordinal)),
after.Where(f => !f.Key.EndsWith(WorkspaceProject.BundleFile, StringComparison.Ordinal)));
Assert.FileExists(Path.Combine(cache, "servers", IdFolder, "proxies", sorted.ToString("N"), "remote.json"));
Assert.FileExists(Path.Combine(cache, "servers", IdFolder, "proxies", old.ToString("N"), "remote.json"));
Assert.False(Directory.Exists(AddressHome(cache, HomeFixtures.Nas)));
// The store now finds the id home by either key.
var identity = new ServerIdentity([new KnownServerKey(Id, [HomeFixtures.Nas])]);
Assert.Equal(idHome, new WorkspaceHomes(homes.Root, identity).ServerRoot(HomeFixtures.Nas));
// Again: nothing left to do.
Assert.Equal(new HomeRekeyResult(0, 0, 0, 0, 0, 0, 0), await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas], context.Cancellation));
}
[Test]
public async Task TwoAddressesOfOneServerMergeAndTheOlderCopyGoesToTheTrash()
{
var (data, homes, cache) = Make();
var byName = HomeFixtures.Server(HomeFixtures.Nas);
var byIp = HomeFixtures.Server(HomeFixtures.NasByIp);
var first = homes.StoreFor(byName).Root;
var second = homes.StoreFor(byIp).Root;
var both = Guid.CreateVersion7();
HomeFixtures.Project(first, byName, "older", DateTimeOffset.UtcNow.AddDays(-1), both);
HomeFixtures.Project(second, byIp, "newer", DateTimeOffset.UtcNow, both);
var onlyFirst = HomeFixtures.Project(first, byName);
var onlySecond = HomeFixtures.Project(second, byIp);
HomeFixtures.TrashEntry(first, onlyFirst, byName);
HomeFixtures.TrashEntry(second, onlyFirst, byIp);
var files = Directory.EnumerateFiles(homes.Root, "*", SearchOption.AllDirectories).Count(IsProjectFile);
// Each address had a proxy cache too.
Directory.CreateDirectory(Path.Combine(AddressHome(cache, HomeFixtures.Nas), "proxies", "a"));
Directory.CreateDirectory(Path.Combine(AddressHome(cache, HomeFixtures.NasByIp), "proxies", "a"));
Directory.CreateDirectory(Path.Combine(AddressHome(cache, HomeFixtures.NasByIp), "proxies", "b"));
var result = await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas, HomeFixtures.NasByIp], context.Cancellation);
Assert.Equal((2, 2, 1, 3), (result.HomesMoved, result.ProjectsMoved, result.ProjectsTrashed, result.BundlesRewritten));
var idHome = Path.Combine(homes.Root, "servers", IdFolder);
Assert.Equal("newer", Bundle(idHome, both).Workspace!.Name);
foreach (var id in new[] { onlyFirst, onlySecond }) Assert.FileExists(Path.Combine(idHome, id.ToString("N"), WorkspaceProject.BundleFile));
var trash = Directory.EnumerateDirectories(Path.Combine(idHome, WorkspaceTrash.FolderName)).ToList();
Assert.Equal(3, trash.Count);
Assert.Contains(trash, t => ProjectBundle.Load(Path.Combine(t, WorkspaceProject.BundleFile)).Workspace!.Name == "older");
// The second address's home held only its manifest and record afterwards: it went. Nothing else was deleted.
Assert.False(Directory.Exists(second));
Assert.Equal(files, Directory.EnumerateFiles(homes.Root, "*", SearchOption.AllDirectories).Count(IsProjectFile));
Assert.Count(1, Directory.EnumerateDirectories(Path.Combine(homes.Root, "servers")));
Assert.True(Directory.Exists(Path.Combine(cache, "servers", IdFolder, "proxies", "b")));
}
[Test]
public async Task AProjectInUseStaysAndKeepsItsAliasWhichStillMatches()
{
var (data, homes, cache) = Make();
var home = HomeFixtures.Server(HomeFixtures.Nas);
var root = homes.StoreFor(home).Root;
var (held, free) = (HomeFixtures.Project(root, home), HomeFixtures.Project(root, HomeFixtures.Server(HomeFixtures.Nas)));
HomeRekeyResult result;
using (HomeFixtures.Hold(Path.Combine(root, held.ToString("N"))))
{
// A project in use keeps the whole home where it is until a later re-key; the id home is made beside it.
_ = new WorkspaceStore(Path.Combine(homes.Root, "servers", IdFolder));
result = await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas], context.Cancellation);
}
Assert.Equal((0, 1, 1), (result.HomesMoved, result.ProjectsMoved, result.BundlesRewritten));
Assert.FileExists(Path.Combine(root, held.ToString("N"), WorkspaceProject.BundleFile));
Assert.Equal(HomeFixtures.Nas, Bundle(root, held).Workspace!.Home!.Server);
var idHome = Path.Combine(homes.Root, "servers", IdFolder);
Assert.Equal(ServerIdentity.IdKey(Id), Bundle(idHome, free).Workspace!.Home!.Server);
Assert.True(ServerProjectHome.IsArchiveIdOf(Bundle(root, held).Archive.Id, [ServerIdentity.IdKey(Id), HomeFixtures.Nas]));
Assert.NotNull(homes.Find(held));
result = await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas], context.Cancellation);
Assert.Equal((1, 1), (result.ProjectsMoved, result.BundlesRewritten));
Assert.False(Directory.Exists(root));
Assert.Equal(ServerIdentity.IdKey(Id), Bundle(idHome, held).Workspace!.Home!.Server);
}
[Test]
public async Task AWorkingStateInUseInTheIdHomeIsLeftNamingTheAlias()
{
var (data, homes, cache) = Make();
var home = HomeFixtures.Server(HomeFixtures.Nas);
var root = homes.StoreFor(home).Root;
var id = HomeFixtures.Project(root, home);
// Renamed whole first (nothing held), then held while its working state would be rewritten.
var idHome = Path.Combine(homes.Root, "servers", IdFolder);
Directory.Move(root, idHome);
HomeRekeyResult result;
using (HomeFixtures.Hold(Path.Combine(idHome, id.ToString("N"))))
result = await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas], context.Cancellation);
Assert.Equal((0, 1), (result.BundlesRewritten, result.BundlesInUse));
Assert.Equal(HomeFixtures.Nas, Bundle(idHome, id).Workspace!.Home!.Server);
Assert.Equal(ServerIdentity.IdKey(Id), Assert.NotNull(ServerHomeRecord.Read(idHome)).Key);
}
[Test]
public async Task AnIdKeyIsNeverAnAliasAndAnEmptyIdIsRefused()
{
var (data, homes, cache) = Make();
await Assert.ThrowsAsync<ArgumentException>(() => Migration(data, homes, cache).RekeyAsync(Guid.Empty, [HomeFixtures.Nas], context.Cancellation));
var other = ServerIdentity.IdKey(Guid.CreateVersion7());
var otherHome = homes.StoreFor(HomeFixtures.Server(other)).Root;
Assert.Equal(new HomeRekeyResult(0, 0, 0, 0, 0, 0, 0), await Migration(data, homes, cache).RekeyAsync(Id, [other], context.Cancellation));
Assert.True(Directory.Exists(otherHome));
}
private static bool IsProjectFile(string path) => Path.GetFileName(path) is not (WorkspaceStore.ManifestFile or HomeFolders.ServerFile);
}
/// <summary>A re-key moves the server's links in the index too.</summary>
[Category("homes")]
public abstract class HomeRekeyLinkTests(TestContext context) : RepositoryTest(context)
{
private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
[Test]
public async Task TheLinksOfEveryAliasMoveToTheId()
{
var db = await OpenChronosAsync();
var store = new SyncLinkStore(db);
foreach (var key in new[] { HomeFixtures.Nas, HomeFixtures.NasByIp, HomeFixtures.Other })
{
await store.UpsertAsync(new SyncLink
{
Server = key,
RemoteId = Guid.CreateVersion7(),
Title = "Harbour",
RemoteUpdatedAt = TestData.Now,
SyncedAt = TestData.Now,
}, Ct);
}
var data = Context.CreateTempDirectory("data");
var migration = new HomeLayoutMigration(new HomeLayoutOptions { DataDirectory = data, Database = db });
var result = await migration.RekeyAsync(Id, [HomeFixtures.Nas, HomeFixtures.NasByIp], Ct);
Assert.Equal((2, 0), (result.LinksMoved, result.LinksDropped));
Assert.Count(2, await store.ListAsync(ServerIdentity.IdKey(Id), Ct));
Assert.Count(1, await store.ListAsync(HomeFixtures.Other, Ct));
Assert.Empty(await store.ListAsync(HomeFixtures.Nas, Ct));
}
}
public sealed class SqliteHomeRekeyLinkTests(TestContext context) : HomeRekeyLinkTests(context)
{
protected override Backend Backend => Backend.SqliteMemory;
}
public sealed class PostgresHomeRekeyLinkTests(TestContext context) : HomeRekeyLinkTests(context)
{
protected override Backend Backend => Backend.Postgres;
}
@@ -0,0 +1,62 @@
using Chronos.Core.Model;
using Chronos.Data.Jobs;
namespace Chronos.Data.Tests.Jobs;
/// <summary>
/// Every progress report a job engine publishes, kept to tell which details a handler sent and in what order (owner review
/// 5, #65). The engine it records has no publish throttle (<see cref="Options"/>), so each report a handler makes goes out.
/// </summary>
internal sealed class DetailRecorder
{
private readonly List<JobProgressInfo> _published = [];
/// <summary>A started engine's options that publish every report: one worker, fast polls and checkpoints, no progress interval.</summary>
public static JobEngineOptions Options(string worker = "detail") => new()
{
Workers = 1,
WorkerId = worker,
PollInterval = TimeSpan.FromMilliseconds(50),
CheckpointInterval = TimeSpan.FromMilliseconds(50),
ProgressInterval = TimeSpan.Zero,
};
/// <summary>A new engine with <paramref name="handlers"/>, recorded, not started.</summary>
public JobEngine Engine(ChronosDatabase db, IEnumerable<IJobHandler> handlers, string worker = "detail")
{
var engine = new JobEngine(db, [.. handlers], Options(worker));
engine.Progress += p =>
{
lock (_published) _published.Add(p);
};
return engine;
}
/// <summary>The reports of <paramref name="jobId"/> in the order they went out.</summary>
public IReadOnlyList<JobProgressInfo> Of(Guid jobId)
{
lock (_published) return [.. _published.Where(p => p.JobId == jobId)];
}
/// <summary>The details of <paramref name="jobId"/>, without repeats of the one before.</summary>
public IReadOnlyList<JobDetail> Details(Guid jobId)
{
var details = new List<JobDetail>();
foreach (var report in Of(jobId))
{
if (report.Detail is { } detail && (details.Count == 0 || details[^1] != detail)) details.Add(detail);
}
return details;
}
/// <summary>The steps of <paramref name="jobId"/> in order, each once in a row.</summary>
public IReadOnlyList<JobStep> Steps(Guid jobId)
{
var steps = new List<JobStep>();
foreach (var detail in Details(jobId))
{
if (steps.Count == 0 || steps[^1] != detail.Step) steps.Add(detail.Step);
}
return steps;
}
}
@@ -0,0 +1,267 @@
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Testing;
namespace Chronos.Data.Tests.Jobs;
/// <summary>
/// How a running job's progress goes out (owner review 5, #65): at most twice a second, at once for the run's first report,
/// a new step and a completed count, and with the persist that falls due when the last report was dropped; saved at most
/// every checkpoint interval and at each checkpoint, with its detail.
/// </summary>
[Category("jobs")]
public sealed class JobContextProgressTests(TestContext context)
{
private static readonly TimeSpan Tick = TimeSpan.FromMilliseconds(10);
/// <summary>A quarter of the default publish interval: what a new step waits since the last publish.</summary>
private static readonly TimeSpan StepWait = TimeSpan.FromMilliseconds(125);
[Test]
public async Task AHundredReportsInASecondGoOutAtMostThreeTimes()
{
await using var run = await StartAsync();
for (var i = 1; i <= 100; i++)
{
await run.Context.ReportAsync(i, 1000);
run.Time.Advance(Tick);
}
Assert.True(run.Published.Count <= 3, $"{run.Published.Count} publishes");
// The first at once, then one per half second: the latest state when its time comes.
Assert.SequenceEqual([1L, 50L, 100L], run.Published.Select(p => p.Done));
}
[Test]
public async Task AJobGoneQuietInALongStepShowsItsLatestStateOnTime()
{
await using var run = await StartAsync();
// Maintenance: its first sub-steps take milliseconds, the third runs for minutes without a report.
await run.Context.ReportAsync(0, 5, new JobDetail(JobStep.Maintenance, "leases", 0, 0, 1, 5, JobPartUnit.Step));
run.Time.Advance(TimeSpan.FromMilliseconds(30));
await run.Context.CheckpointAsync("leases", 1, 5, new JobDetail(JobStep.Maintenance, "temp", 0, 0, 2, 5, JobPartUnit.Step));
run.Time.Advance(TimeSpan.FromMilliseconds(30));
var packs = new JobDetail(JobStep.Maintenance, "packs", 0, 0, 3, 5, JobPartUnit.Step);
await run.Context.CheckpointAsync("temp", 2, 5, packs);
Assert.Count(1, run.Published);
run.Time.Advance(TimeSpan.FromMilliseconds(500));
Assert.Count(2, run.Published);
Assert.Equal((2L, packs), (run.Published[^1].Done, run.Published[^1].Detail));
// Nothing new: nothing more goes out.
run.Time.Advance(TimeSpan.FromSeconds(10));
Assert.Count(2, run.Published);
}
[Test]
public async Task AJobThatAlternatesStepsGoesOutAFewTimesASecond()
{
await using var run = await StartAsync();
// An incremental scan: every other folder changed, checked and indexed in turn, 200 reports in a second.
for (var i = 0; i < 200; i++)
{
var step = i % 2 == 0 ? JobStep.Check : JobStep.Index;
await run.Context.ReportAsync(i, 10_000, new JobDetail(step, "folder " + i, 0, 0, i + 1, 10_000, JobPartUnit.Folder));
run.Time.Advance(TimeSpan.FromMilliseconds(5));
}
Assert.True(run.Published.Count <= 10, $"{run.Published.Count} publishes");
// The last report still goes out once its time comes.
run.Time.Advance(TimeSpan.FromSeconds(1));
Assert.Equal(199L, run.Published[^1].Done);
}
[Test]
public async Task ANewStepAndACompletedCountGoOutAtOnce()
{
await using var run = await StartAsync();
var index = new JobDetail(JobStep.Index, "2024/Harbour sunset", 1, 5, 1, 2, JobPartUnit.Folder);
await run.Context.ReportAsync(1, 10, new JobDetail(JobStep.List));
run.Time.Advance(Tick);
await run.Context.ReportAsync(2, 10, new JobDetail(JobStep.List));
// A new step goes out once a quarter of the interval has passed, not at every switch.
run.Time.Advance(StepWait);
await run.Context.ReportAsync(3, 10, index);
run.Time.Advance(Tick);
await run.Context.ReportItemAsync(4, 10, 2, 5);
run.Time.Advance(Tick);
await run.Context.ReportAsync(10, 10);
run.Time.Advance(Tick);
await run.Context.ReportAsync(10, 10);
Assert.SequenceEqual([1L, 3L, 10L], run.Published.Select(p => p.Done));
Assert.Equal(index, run.Published[1].Detail);
// A report without a detail keeps the last one, with the item counts reported since.
Assert.Equal(index with { ItemDone = 2 }, run.Published[2].Detail);
Assert.Equal(index with { ItemDone = 2 }, run.Context.Detail);
}
[Test]
public async Task ADroppedReportGoesOutWithThePersistThatFallsDue()
{
await using var run = await StartAsync();
await run.Context.ReportAsync(1, 100);
run.Time.Advance(TimeSpan.FromSeconds(4.8));
await run.Context.ReportAsync(2, 100);
Assert.Equal(0L, (await run.StoredAsync()).ProgressDone);
run.Time.Advance(TimeSpan.FromSeconds(0.2));
// Too soon for a publish, but the persist falls due: it shows what it saves.
await run.Context.ReportAsync(3, 100);
Assert.SequenceEqual([1L, 2L, 3L], run.Published.Select(p => p.Done));
Assert.Equal(3L, (await run.StoredAsync()).ProgressDone);
}
[Test]
public async Task ProgressIsSavedAtMostEveryCheckpointIntervalAndAtEachCheckpoint()
{
await using var run = await StartAsync();
for (var i = 1; i <= 50; i++)
{
await run.Context.ReportAsync(i, 100);
run.Time.Advance(TimeSpan.FromMilliseconds(99));
}
Assert.Equal(0L, (await run.StoredAsync()).ProgressDone);
run.Time.Advance(TimeSpan.FromMilliseconds(50));
await run.Context.ReportAsync(51, 100);
Assert.Equal(51L, (await run.StoredAsync()).ProgressDone);
var published = run.Published.Count;
// A checkpoint is saved at once; it goes out as any report would.
run.Time.Advance(Tick);
await run.Context.CheckpointAsync("52", 52, 100);
var stored = await run.StoredAsync();
Assert.Equal((52L, "52"), (stored.ProgressDone, stored.Checkpoint));
Assert.Null(stored.Detail);
Assert.Equal(published, run.Published.Count);
var verify = new JobDetail(JobStep.Verify, "Harbour sunset", 1, 9, 1, 3, JobPartUnit.Sequence);
run.Time.Advance(StepWait);
await run.Context.CheckpointAsync("53", 53, 100, verify);
stored = await run.StoredAsync();
Assert.Equal((53L, "53", verify), (stored.ProgressDone, stored.Checkpoint, stored.Detail));
Assert.Equal(verify, run.Published[^1].Detail);
// A checkpoint without a detail keeps it.
run.Time.Advance(Tick);
await run.Context.CheckpointAsync("54", 54, 100);
Assert.Equal(verify, (await run.StoredAsync()).Detail);
}
[Test]
public async Task TheRateIsTheSameUnderThePublishThrottle()
{
await using var run = await StartAsync();
// 100 photos a second for ten seconds, every photo reported.
for (var i = 1; i <= 1000; i++)
{
await run.Context.ReportAsync(i, 2000);
run.Time.Advance(Tick);
}
Assert.True(run.Published.Count <= 22, $"{run.Published.Count} publishes");
var last = run.Published[^1];
Assert.Approximately(100, last.ItemsPerSecond!.Value, 0.5);
Assert.Approximately((2000 - last.Done) / 100.0, last.Eta!.Value.TotalSeconds, 0.1);
}
[Test]
public async Task ItemCountsWithoutADetailAreAPhotoPass()
{
await using var run = await StartAsync();
Assert.Null(run.Context.Detail);
await run.Context.ReportItemAsync(1, 10, 3, 9);
Assert.Equal(new JobDetail(JobStep.Process, null, 3, 9), run.Context.Detail);
Assert.Equal(run.Context.Detail, run.Published.Single().Detail);
// A plain report keeps the detail and drops the old free text.
await run.Context.ReportAsync(2, 10, "IMG_0001.CR3");
await run.Context.ReportAsync(3, 10);
Assert.Null(run.Context.Message);
Assert.Equal(new JobDetail(JobStep.Process, null, 3, 9), run.Context.Detail);
}
[Test]
public async Task ADroppedReportAllocatesNothing()
{
await using var run = await StartAsync();
var thumbs = new JobDetail(JobStep.Thumbs, "Harbour sunset", 0, 3600, 2, 7, JobPartUnit.Sequence);
await run.Context.ReportAsync(1, 1_000_000, thumbs);
var job = run.Context;
var dropped = 0;
for (var i = 0; i < 200; i++) dropped += Drop(job, thumbs, i) ? 1 : 0;
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 20_000; i++) dropped += Drop(job, thumbs, i) ? 1 : 0;
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
Assert.Equal(20_200, dropped);
Assert.Equal(0L, allocated);
Assert.Count(1, run.Published);
}
[Test]
public async Task TheEngineSendsAndSavesTheDetail()
{
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(), "jobs.db")), context.Cancellation);
var verify = new JobDetail(JobStep.Verify, "Harbour sunset", 5, 9, 1, 2, JobPartUnit.Sequence);
var handler = new CallbackHandler(JobKind.Verify, async c =>
{
await c.CheckpointAsync("1", 1, 2, verify);
await c.ReportAsync(2, 2);
});
await using var engine = new JobEngine(db, [handler], new JobEngineOptions { Workers = 1, WorkerId = "t" });
var published = new List<JobProgressInfo>();
engine.Progress += p =>
{
lock (published) published.Add(p);
};
await engine.StartAsync(context.Cancellation);
var job = await engine.EnqueueAsync(JobKind.Verify, [Guid.NewGuid()], cancellationToken: context.Cancellation);
var until = DateTime.UtcNow.AddSeconds(15);
Job? done = null;
while (DateTime.UtcNow < until && (done = await db.Jobs.GetAsync(job.Id, context.Cancellation))?.State != JobState.Done) await Task.Delay(20, context.Cancellation);
Assert.Equal(JobState.Done, done?.State);
Assert.Equal(verify, done!.Detail);
lock (published) Assert.SequenceEqual([verify, verify], published.Select(p => p.Detail));
}
/// <summary>One report dropped by the throttle: no new step, no completed count, no time passed.</summary>
private static bool Drop(JobContext job, JobDetail detail, int i)
{
var item = job.ReportItemAsync(2 + i, 1_000_000, i, 3600);
var full = job.ReportAsync(3 + i, 1_000_000, detail);
return item.IsCompletedSuccessfully && full.IsCompletedSuccessfully;
}
private async Task<Run> StartAsync()
{
var time = new ManualTime();
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(), "jobs.db")), context.Cancellation);
var engine = new JobEngine(db, [], new JobEngineOptions { WorkerId = "t", Time = time });
var run = new Run(db, engine, time);
engine.Progress += run.Published.Add;
await db.Jobs.EnqueueAsync(new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Verify, State = JobState.Queued, Created = DateTimeOffset.UtcNow },
context.Cancellation);
var claimed = Assert.NotNull(await db.Jobs.ClaimNextAsync("t", null, context.Cancellation));
run.Context = new JobContext(engine, claimed, context.Cancellation);
return run;
}
private sealed class Run(ChronosDatabase db, JobEngine engine, ManualTime time) : IAsyncDisposable
{
public ManualTime Time { get; } = time;
public JobContext Context { get; set; } = null!;
public List<JobProgressInfo> Published { get; } = [];
public async Task<Job> StoredAsync() => (await db.Jobs.GetAsync(Context.Job.Id))!;
public async ValueTask DisposeAsync()
{
await engine.DisposeAsync();
await db.DisposeAsync();
}
}
private sealed class CallbackHandler(JobKind kind, Func<JobContext, Task> run) : IJobHandler
{
public JobKind Kind => kind;
public Task RunAsync(JobContext context) => run(context);
}
}
@@ -5,16 +5,71 @@ using Chronos.Testing;
namespace Chronos.Data.Tests.Jobs;
/// <summary>A clock the test moves by hand (BCL <see cref="TimeProvider"/>, no package).</summary>
/// <summary>
/// A clock the test moves by hand (BCL <see cref="TimeProvider"/>, no package), whose timers fire only when
/// <see cref="Advance"/> reaches them, on the test's thread.
/// </summary>
internal sealed class ManualTime : TimeProvider
{
private readonly Lock _gate = new();
private readonly List<Timer> _timers = [];
private long _ticks;
public override long TimestampFrequency => TimeSpan.TicksPerSecond;
public override long GetTimestamp() => Interlocked.Read(ref _ticks);
public void Advance(TimeSpan by) => Interlocked.Add(ref _ticks, by.Ticks);
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
{
var timer = new Timer(this, callback, state);
timer.Change(dueTime, period);
return timer;
}
/// <summary>Moves the clock on, then fires each one-shot timer due by then.</summary>
public void Advance(TimeSpan by)
{
List<Timer> due;
lock (_gate)
{
var now = Interlocked.Add(ref _ticks, by.Ticks);
due = [.. _timers.Where(t => t.Due <= now)];
foreach (var timer in due) _timers.Remove(timer);
}
foreach (var timer in due) timer.Fire();
}
private void Schedule(Timer timer, TimeSpan dueTime)
{
lock (_gate)
{
_timers.Remove(timer);
if (dueTime == Timeout.InfiniteTimeSpan) return;
timer.Due = Interlocked.Read(ref _ticks) + dueTime.Ticks;
_timers.Add(timer);
}
}
private sealed class Timer(ManualTime clock, TimerCallback callback, object? state) : ITimer
{
public long Due { get; set; }
public bool Change(TimeSpan dueTime, TimeSpan period)
{
clock.Schedule(this, dueTime);
return true;
}
public void Fire() => callback(state);
public void Dispose() => clock.Schedule(this, Timeout.InfiniteTimeSpan);
public ValueTask DisposeAsync()
{
Dispose();
return ValueTask.CompletedTask;
}
}
}
[Category("jobs")]
@@ -1,5 +1,6 @@
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Jobs;
@@ -29,4 +30,72 @@ public sealed class JobWireTests
Assert.Equal(names.Count, names.Distinct(StringComparer.Ordinal).Count());
Assert.False(JobWire.TryParseKind("workspace-teleport", out _));
}
/// <summary>Steps and units are stored and sent by name, appended only: these values and names are pinned once shipped.</summary>
[Theory]
[Case(JobStep.None, 0, "none")]
[Case(JobStep.List, 1, "list")]
[Case(JobStep.Verify, 4, "verify")]
[Case(JobStep.CopyPhoto, 11, "copy-photo")]
[Case(JobStep.CopyOriginal, 13, "copy-original")]
[Case(JobStep.FollowUps, 22, "follow-ups")]
[Case(JobStep.Process, 23, "process")]
public void StepsKeepTheirValueAndName(JobStep step, int value, string name)
{
Assert.Equal(value, (int)step);
Assert.Equal(name, JobWire.Step(step));
Assert.True(JobWire.TryParseStep(name, out var parsed), name);
Assert.Equal(step, parsed);
}
[Test]
public void EveryStepAndUnitHasItsOwnName()
{
var steps = Enum.GetValues<JobStep>().Select(JobWire.Step).ToList();
Assert.Equal(steps.Count, steps.Distinct(StringComparer.Ordinal).Count());
Assert.SequenceEqual(["none", "sequence", "folder", "render", "entry", "step"], Enum.GetValues<JobPartUnit>().Select(JobWire.PartUnit));
Assert.False(JobWire.TryParseStep("teleport", out _));
Assert.False(JobWire.TryParsePartUnit(null, out _));
}
[Test]
public void ADetailCrossesTheWireAndBack()
{
var detail = new JobDetail(JobStep.CopyOriginal, "2024/2024-09-27 Harbour sunset", 1240, 3600, 12, 340, JobPartUnit.Folder);
var dto = JobWire.Detail(detail)!;
Assert.Equal(new JobDetailDto("copy-original", "2024/2024-09-27 Harbour sunset", 1240, 3600, 12, 340, "folder"), dto);
Assert.Equal(detail, JobWire.FromDto(dto));
// A unit of none is left out; nothing is none.
Assert.Null(JobWire.Detail(new JobDetail(JobStep.Backup))!.PartUnit);
Assert.Null(JobWire.Detail(null));
Assert.Null(JobWire.FromDto((JobDetailDto?)null));
// A newer peer's step or unit reads as none and its counts stay; nonsense counts read as 0.
Assert.Equal(new JobDetail(JobStep.None, "x", 0, 9, 2, 0), JobWire.FromDto(new JobDetailDto("teleport", "x", -4, 9, 2, -1, "galaxy")));
Assert.Equal(new JobDetail(JobStep.None), JobWire.FromDto(new JobDetailDto(null!)));
}
[Test]
public void AnItemIsCutToItsLongestLengthWithoutSplittingACharacter()
{
var plain = new string('a', JobDetail.MaxItemLength + 40);
Assert.Equal(JobDetail.MaxItemLength, new JobDetail(JobStep.Index, plain).Item!.Length);
// A pair whose high half would be the last kept character goes whole.
var emoji = new string('a', JobDetail.MaxItemLength - 1) + "\U0001F4F7" + "tail";
var cut = new JobDetail(JobStep.Index, emoji).Item!;
Assert.Equal(JobDetail.MaxItemLength - 1, cut.Length);
Assert.False(char.IsHighSurrogate(cut[^1]));
Assert.Equal(JobDetail.MaxItemLength, (new JobDetail(JobStep.Index) with { Item = plain }).Item!.Length);
Assert.Equal(JobDetail.MaxItemLength, JobWire.FromDto(new JobDetailDto("index", plain))!.Item!.Length);
Assert.Equal("short", new JobDetail(JobStep.Index, "short").Item);
}
[Test]
public void AServerJobBringsItsDetail()
{
var dto = new JobDto(Guid.NewGuid(), "verify", [], "Archive", "paused", "normal", 4, 10, null, null, null, null, 1, null, DateTimeOffset.UtcNow, null, null,
Detail: new JobDetailDto("verify", "Harbour sunset", 812, 2400, 3, 41, "sequence"));
Assert.Equal(new JobDetail(JobStep.Verify, "Harbour sunset", 812, 2400, 3, 41, JobPartUnit.Sequence), JobWire.FromDto(dto)!.Detail);
Assert.Null(JobWire.FromDto(dto with { Detail = null })!.Detail);
}
}
@@ -139,6 +139,24 @@ public abstract class MigrationTests(TestContext context) : RepositoryTest(conte
Assert.Equal(0L, await session.ScalarAsync<long>("SELECT bytes FROM render_copies WHERE path = $1", ["C:/Videos/b"], Ct));
}
[Test]
public async Task TheProgressDetailColumnJoinsAnIndexOfTheVideosRelease()
{
var database = await OpenDatabaseAsync();
var all = MigrationRunner.Load(Dialect);
Assert.Equal(10, await MigrationRunner.MigrateAsync(database, [.. all.Where(m => m.Version <= 10)], Ct));
var id = Guid.CreateVersion7();
await using (var session = await database.OpenAsync(Ct))
await session.ExecuteAsync("INSERT INTO jobs (id, kind, state, priority, created) VALUES ($1, $2, $3, $4, $5)",
[id, (int)JobKind.Verify, (int)JobState.Paused, (int)JobPriority.Normal, DateTimeOffset.UtcNow], Ct);
Assert.Equal(11, all.Single(m => m.Name == "job_progress_detail").Version);
Assert.Equal(all[^1].Version, await MigrationRunner.MigrateAsync(database, Ct));
await using var after = await database.OpenAsync(Ct);
// No backfill: a job of 1.0 has no detail.
Assert.Equal(1L, await after.ScalarAsync<long>("SELECT count(*) FROM jobs WHERE id = $1 AND progress_detail IS NULL", [id], Ct));
}
[Test]
public async Task AppliesOnlyPendingMigrations()
{
@@ -0,0 +1,82 @@
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Export;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Tests.Jobs;
using Chronos.Testing;
namespace Chronos.Data.Tests.Processing;
/// <summary>What the analysis and render jobs say they are doing (owner review 5, #65), as the job's progress detail.</summary>
[Category("processing")]
public sealed class ProcessingProgressDetailTests(TestContext context)
{
private const int Frames = 12;
private static SyntheticSequence Scene() => SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = Frames, StartEv = 0.5, EndEv = -0.5 });
private static async Task<(DetailRecorder Recorder, JobEngine Engine)> StartAsync(ProcessingFixture fx)
{
var recorder = new DetailRecorder();
var engine = recorder.Engine(fx.Db, fx.Processing.CreateJobHandlers());
await engine.StartAsync(fx.Ct);
return (recorder, engine);
}
private static async Task<Guid> RunAsync(ProcessingFixture fx, JobEngine engine, ArchiveJobRequest request)
{
var job = await engine.EnqueueAsync(request, cancellationToken: fx.Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
return job.Id;
}
[Test]
public async Task AnAnalysisNamesEachSequenceAndADeepOneCountsItsPhotos()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var first = await fx.AddAsync(Scene(), "First");
var second = await fx.AddAsync(Scene(), "Second");
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var light = await RunAsync(fx, engine, ProcessingJobs.LightAnalysis([first.Id, second.Id], "both"));
var details = recorder.Details(light);
Assert.True(details.All(d => d.Step == JobStep.Analyse && d.PartUnit == JobPartUnit.Sequence && d.Parts == 2 && d.ItemTotal == 0), string.Join("; ", details));
Assert.SequenceEqual([(1, first.DisplayTitle), (2, second.DisplayTitle)], details.Select(d => (d.Part, d.Item!)));
var deep = await RunAsync(fx, engine, ProcessingJobs.DeepAnalysis([first.Id]));
details = recorder.Details(deep);
Assert.True(details.All(d => d.Step == JobStep.Analyse && d.Item == first.DisplayTitle && d.Part == 1 && d.Parts == 1 && d.ItemTotal == Frames),
string.Join("; ", details));
Assert.True(details.Max(d => d.ItemDone) > 0, string.Join("; ", details));
Assert.True(details.All(d => d.ItemDone <= Frames));
}
[Test]
public async Task ARenderPreparesEncodesThenVerifiesWithoutTextInTheDetail()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var mjpeg = new ExportSettings
{
Preset = new Auto<string>().WithManual("mjpeg-avi"),
Overrides = new ExportOverrides { Width = 96, Height = 64 },
NameTemplate = "clip-{codec}",
};
var id = await RunAsync(fx, engine, ProcessingJobs.Render(sequence, mjpeg, 96, 64));
Assert.SequenceEqual([JobStep.Analyse, JobStep.Encode, JobStep.Verify], recorder.Steps(id));
var details = recorder.Details(id);
Assert.Equal(new JobDetail(JobStep.Analyse, sequence.DisplayTitle), details[0]);
var encode = details.Where(d => d.Step == JobStep.Encode).ToList();
Assert.True(encode.All(d => d.Item == sequence.DisplayTitle && d.Parts == 0 && d.ItemDone <= d.ItemTotal), string.Join("; ", encode));
Assert.True(encode.Max(d => d.ItemDone) > 0, string.Join("; ", encode));
Assert.Equal(new JobDetail(JobStep.Verify, "clip-MJPEG.avi"), details[^1]);
}
}
@@ -30,12 +30,52 @@ public abstract class JobRepositoryTests(TestContext context) : RepositoryTest(c
Started = TestData.Now.AddMinutes(1),
Finished = TestData.Now.AddMinutes(2),
ScheduleId = Guid.CreateVersion7(),
Detail = new JobDetail(JobStep.Encode, "Harbour sunset", 5, 10, 1, 2, JobPartUnit.Render),
};
await db.Jobs.EnqueueAsync(job, Ct);
var read = Assert.NotNull(await db.Jobs.GetAsync(job.Id, Ct));
Assert.SequenceEqual(job.TargetIds, read.TargetIds);
Assert.Equal(job with { TargetIds = read.TargetIds }, read);
Assert.Null((await db.Jobs.GetAsync((await EnqueueAsync(db, TestData.Job())).Id, Ct))!.ScheduleId);
var plain = (await db.Jobs.GetAsync((await EnqueueAsync(db, TestData.Job())).Id, Ct))!;
Assert.Null(plain.ScheduleId);
Assert.Null(plain.Detail);
}
[Test]
public async Task TheProgressDetailIsSavedWithTheProgressAndListedWithTheJob()
{
var db = await OpenChronosAsync();
var job = TestData.Job(JobKind.Verify);
await db.Jobs.EnqueueAsync(job, Ct);
await db.Jobs.ClaimNextAsync("w", cancellationToken: Ct);
var detail = new JobDetail(JobStep.Verify, "Harbour sunset · 2024", 812, 2400, 3, 41, JobPartUnit.Sequence);
Assert.True(await db.Jobs.UpdateProgressAsync(job.Id, 4, 10, null, null, "cursor:4", null, detail, Ct));
Assert.Equal(detail, (await db.Jobs.GetAsync(job.Id, Ct))!.Detail);
// Lists read it too: a paused job tells where it stopped.
Assert.SequenceEqual([detail], (await db.Jobs.ListBriefAsync(JobState.Running, null, cancellationToken: Ct)).Items.Select(j => j.Detail));
// Without a detail the column is cleared; a node's progress keeps or replaces it.
Assert.True(await db.Jobs.UpdateProgressAsync(job.Id, 5, 10, null, null, "cursor:5", null, Ct));
Assert.Null((await db.Jobs.GetAsync(job.Id, Ct))!.Detail);
var node = new JobDetail(JobStep.Encode, null, 120, 3600);
Assert.True(await db.Jobs.UpdateNodeProgressAsync(job.Id, "w", 6, 10, null, null, null, node, Ct));
Assert.True(await db.Jobs.UpdateNodeProgressAsync(job.Id, "w", 7, 10, null, null, "line", Ct));
Assert.Equal(node, (await db.Jobs.GetAsync(job.Id, Ct))!.Detail);
Assert.True(await db.Jobs.UpdateNodeProgressAsync(job.Id, "w", 8, 10, null, null, null, null, Ct));
Assert.Null((await db.Jobs.GetAsync(job.Id, Ct))!.Detail);
// A cell this build cannot read is no detail, never an error.
foreach (var unreadable in new[] { "not json", "42", "[]", "{\"step\": 7}" })
{
await using (var session = await db.Database.OpenAsync(Ct))
await session.ExecuteAsync("UPDATE jobs SET progress_detail = $1 WHERE id = $2", [unreadable, job.Id], Ct);
Assert.Null((await db.Jobs.GetAsync(job.Id, Ct))!.Detail);
}
// One of a newer build: its step and unit read as none, the counts stay.
await using (var session = await db.Database.OpenAsync(Ct))
await session.ExecuteAsync("UPDATE jobs SET progress_detail = $1 WHERE id = $2",
["""{"step":"teleport","itemDone":3,"itemTotal":9,"part":2,"parts":4,"partUnit":"galaxy","future":true}""", job.Id], Ct);
Assert.Equal(new JobDetail(JobStep.None, null, 3, 9, 2, 4), (await db.Jobs.GetAsync(job.Id, Ct))!.Detail);
}
[Test]
@@ -0,0 +1,58 @@
using Chronos.Core.IO;
using Chronos.Data.Sync;
using Chronos.Data.Tests.Homes;
using Chronos.Testing;
namespace Chronos.Data.Tests.Sync;
/// <summary>Where the proxies of a server's sequence live (owner review 5, #66): its home in the cache, else where an earlier layout left them.</summary>
[Category("sync")]
public sealed class ProxyCacheTests(TestContext context)
{
private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
[Test]
public void WithoutAServersRootTheLayoutIs10s()
{
var root = context.CreateTempDirectory("proxies");
var remote = Guid.CreateVersion7();
var cache = new ProxyCache(root);
Assert.Equal(Path.Combine(root, HomeFolders.AddressHash(HomeFixtures.Nas), remote.ToString("N")), cache.Folder(HomeFixtures.Nas, remote));
}
[Test]
public void ANewSequenceGoesToItsServersHomeAndAnOldOneIsReadWhereItIs()
{
var cacheRoot = context.CreateTempDirectory("cache");
var (legacyRoot, servers) = (Path.Combine(cacheRoot, "proxies"), Path.Combine(cacheRoot, "servers"));
var identity = new ServerIdentity([new KnownServerKey(Id, [HomeFixtures.Nas])]);
var cache = new ProxyCache(legacyRoot, servers, () => identity);
var idKey = ServerIdentity.IdKey(Id);
var fresh = Guid.CreateVersion7();
Assert.Equal(Path.Combine(servers, Id.ToString("N"), "proxies", fresh.ToString("N")), cache.Folder(idKey, fresh));
Assert.Equal(cache.Folder(idKey, fresh), cache.Folder(HomeFixtures.Nas, fresh), "an alias names the same home");
// A sequence cached by 1.0 under the address is used where it is until it is moved.
var old = Guid.CreateVersion7();
var legacy = HomeFixtures.LegacyProxies(cacheRoot, HomeFixtures.Nas, old);
Assert.Equal(legacy, cache.Folder(idKey, old));
Assert.True(cache.Exists(idKey, old));
// In the home of the address (sorted before the server announced its id): used there too.
var sorted = Guid.CreateVersion7();
var byAddress = Path.Combine(servers, HomeFolders.ServerFolder(HomeFixtures.Nas), "proxies", sorted.ToString("N"));
Directory.CreateDirectory(byAddress);
Assert.Equal(byAddress, cache.Folder(idKey, sorted));
// Once in its home, that is where it is.
var home = Path.Combine(servers, Id.ToString("N"), "proxies", old.ToString("N"));
Directory.CreateDirectory(Path.GetDirectoryName(home)!);
Directory.Move(legacy, home);
Assert.Equal(home, cache.Folder(HomeFixtures.Nas, old));
// A server known by its address only has an address home.
var other = Guid.CreateVersion7();
Assert.Equal(Path.Combine(servers, HomeFolders.ServerFolder(HomeFixtures.Other), "proxies", other.ToString("N")), cache.Folder(HomeFixtures.Other, other));
}
}
@@ -0,0 +1,84 @@
using Chronos.Core.IO;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Sync;
/// <summary>How the desktop names a server (owner review 5, #66): by its announced id, its address keys kept as aliases.</summary>
[Category("sync")]
public sealed class ServerIdentityTests
{
private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
private static ServerInfo Info(Guid? id) => new("Studio NAS", "1.1.0", 1, [], null, [], new ServerLimits(1, 1), null, null, id);
[Test]
public void AServerThatAnnouncesAnIdIsKeyedByIt()
{
var key = ServerIdentity.Key(Info(Id), new Uri("https://NAS.local:8443/"));
Assert.Equal("id:" + Id.ToString("N"), key);
Assert.True(ServerIdentity.IsIdKey(key));
Assert.Equal(Id, ServerIdentity.IdOf(key));
// Another address of the same server: the same key.
Assert.Equal(key, ServerIdentity.Key(Info(Id), new Uri("https://192.168.1.5:8443")));
}
[Test]
public void AnOlderServerKeepsItsAddressKey()
{
var address = new Uri("https://NAS.local:8443/");
Assert.Equal("https://nas.local:8443", ServerIdentity.Key(Info(null), address));
Assert.Equal(SyncService.ServerKey(address), ServerIdentity.Key((ServerInfo?)null, address));
Assert.Equal(SyncService.ServerKey(address), ServerIdentity.Key(Guid.Empty, address));
Assert.False(ServerIdentity.IsIdKey(SyncService.ServerKey(address)));
}
[Test]
public void AliasesNameTheServerOfTheirId()
{
var identity = new ServerIdentity([new KnownServerKey(Id, ["https://nas.local:8443", "https://192.168.1.5:8443"])]);
var key = ServerIdentity.IdKey(Id);
Assert.Equal(key, identity.Canonical("https://NAS.local:8443"));
Assert.Equal(key, identity.Canonical(key.ToUpperInvariant()));
Assert.Equal("https://other:1", identity.Canonical("https://other:1"));
Assert.True(identity.Same("https://nas.local:8443", "https://192.168.1.5:8443"));
Assert.True(identity.Same(key, "https://192.168.1.5:8443"));
Assert.False(identity.Same(key, "https://other:1"));
Assert.True(identity.Same(null, null));
Assert.False(identity.Same(key, null));
Assert.Equal(Id.ToString("N"), identity.FolderName("https://192.168.1.5:8443"));
Assert.Equal(HomeFolders.ServerFolder("https://other:1"), identity.FolderName("https://other:1"));
Assert.SequenceEqual(new[] { key, "https://nas.local:8443", "https://192.168.1.5:8443" }, identity.KeysOf("https://192.168.1.5:8443"));
Assert.SequenceEqual(new[] { "https://other:1" }, identity.KeysOf("https://other:1"));
Assert.Equal(2, identity.AliasesOf(Id).Count);
// Without the table every key is its own.
Assert.False(ServerIdentity.None.Same(key, "https://nas.local:8443"));
}
[Test]
public void AnAddressChangeKeepsTheKeyOnceTheAliasIsKnown()
{
var identity = new ServerIdentity([new KnownServerKey(Id, ["https://nas.local:8443"])]);
var widened = identity.With(Id, "https://nas.local:9443");
Assert.True(widened.Same("https://nas.local:8443", "https://nas.local:9443"));
Assert.Same(widened, widened.With(Id, "HTTPS://nas.local:9443"));
Assert.False(identity.Same("https://nas.local:8443", "https://nas.local:9443"), "the table it came from is unchanged");
var other = Guid.CreateVersion7();
Assert.Equal(ServerIdentity.IdKey(other), widened.With(other, "https://second:1").Canonical("https://second:1"));
// An address two ids claim stays with the first one listed.
var clash = new ServerIdentity([new KnownServerKey(Id, ["https://x"]), new KnownServerKey(other, ["https://x"])]);
Assert.Equal(ServerIdentity.IdKey(Id), clash.Canonical("https://x"));
}
[Test]
public void TheArchiveIdOfAnyAliasIsTheServers()
{
string[] keys = [ServerIdentity.IdKey(Id), "https://nas.local:8443"];
Assert.True(ServerProjectHome.IsArchiveIdOf(ServerProjectHome.ArchiveIdOf("https://nas.local:8443"), keys));
Assert.True(ServerProjectHome.IsArchiveIdOf(ServerProjectHome.ArchiveIdOf(keys[0]), keys));
Assert.False(ServerProjectHome.IsArchiveIdOf(ServerProjectHome.ArchiveIdOf("https://other:1"), keys));
}
}
@@ -0,0 +1,102 @@
using Chronos.Core.IO;
using Chronos.Data.Homes;
using Chronos.Data.Sync;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Data.Tests.Repositories;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.Data.Tests.Sync;
/// <summary>A server's links move from its address key to its id key (owner review 5, #66), the newer row winning a clash.</summary>
[Category("sync")]
public abstract class SyncLinkRekeyTests(TestContext context) : RepositoryTest(context)
{
private const string Address = "https://nas.local:8443";
private static readonly string IdKey = ServerIdentity.IdKey(Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01"));
private static SyncLink Link(string server, Guid remoteId, Guid? localId, DateTimeOffset? synced, string title = "Harbour") => new()
{
Server = server,
RemoteId = remoteId,
LocalId = localId,
Title = title,
RemoteUpdatedAt = TestData.Now,
SyncedAt = synced,
};
[Test]
public async Task TheLinksOfAnAddressMoveToTheIdAndTheNewerRowWinsAClash()
{
var db = await OpenChronosAsync();
var archive = TestData.Archive();
await db.Archives.UpsertAsync(archive, Ct);
var (a, b, c) = (TestData.Sequence(archive.Id), TestData.Sequence(archive.Id), TestData.Sequence(archive.Id));
foreach (var sequence in new[] { a, b, c }) await db.Sequences.UpsertAsync(sequence, Ct);
var store = new SyncLinkStore(db);
var (plain, sameRemote, sameLocal, stale) = (Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7());
// Only under the address: it moves.
await store.UpsertAsync(Link(Address, plain, a.Id, TestData.Now), Ct);
// Under both keys for one server sequence: the address's row is newer, so it replaces the id's.
await store.UpsertAsync(Link(Address, sameRemote, null, TestData.Now.AddHours(2), "newer"), Ct);
await store.UpsertAsync(Link(IdKey, sameRemote, null, TestData.Now.AddHours(1), "older"), Ct);
// Both keys link local copy b to different server sequences: the id's row is newer, so the address's goes.
await store.UpsertAsync(Link(Address, sameLocal, b.Id, TestData.Now), Ct);
await store.UpsertAsync(Link(IdKey, Guid.CreateVersion7(), b.Id, TestData.Now.AddDays(1)), Ct);
// Never compared under the address, compared under the id: the id's stays.
await store.UpsertAsync(Link(Address, stale, c.Id, null), Ct);
await store.UpsertAsync(Link(IdKey, stale, null, TestData.Now), Ct);
var (moved, dropped) = await store.RekeyAsync(Address, IdKey, Ct);
Assert.Equal((2, 3), (moved, dropped));
Assert.Empty(await store.ListAsync(Address, Ct));
var links = (await store.ListAsync(IdKey, Ct)).ToDictionary(l => l.RemoteId);
Assert.Equal(4, links.Count);
Assert.Equal(a.Id, links[plain].LocalId);
Assert.Equal("newer", links[sameRemote].Title);
Assert.False(links.ContainsKey(sameLocal));
Assert.Null(links[stale].LocalId);
Assert.Equal(b.Id, Assert.NotNull(await store.FindByLocalAsync(IdKey, b.Id, Ct)).LocalId);
// Again: nothing left to move; and a key onto itself does nothing.
Assert.Equal((0, 0), await store.RekeyAsync(Address, IdKey, Ct));
Assert.Equal((0, 0), await store.RekeyAsync(IdKey, IdKey, Ct));
}
[Test]
public async Task TheLinksMoveToTheIdWhileTheFoldersWait()
{
var db = await OpenChronosAsync();
var archive = TestData.Archive();
await db.Archives.UpsertAsync(archive, Ct);
var sequence = TestData.Sequence(archive.Id);
await db.Sequences.UpsertAsync(sequence, Ct);
var store = new SyncLinkStore(db);
var remote = Guid.CreateVersion7();
await store.UpsertAsync(Link(Address, remote, sequence.Id, TestData.Now), Ct);
var data = Context.CreateTempDirectory("data");
var workspace = new WorkspaceHomes(Path.Combine(data, "workspace"));
var home = Path.Combine(workspace.Root, "servers", HomeFolders.ServerFolder(Address));
Directory.CreateDirectory(home);
var migration = new HomeLayoutMigration(new HomeLayoutOptions { DataDirectory = data, WorkspaceRoot = workspace.Root, Database = db });
// A download or an upload resumed under the id key finds its link before the folders move (a job held them).
var id = ServerIdentity.IdOf(IdKey)!.Value;
Assert.Equal((1, 0), await migration.RekeyLinksAsync(id, [Address, IdKey], Ct));
Assert.Equal(sequence.Id, Assert.NotNull(await store.GetAsync(IdKey, remote, Ct)).LocalId);
Assert.Equal(sequence.Id, Assert.NotNull(await store.FindByLocalAsync(IdKey, sequence.Id, Ct)).LocalId);
Assert.Empty(await store.ListAsync(Address, Ct));
Assert.True(Directory.Exists(home), "the folders wait for the full re-key");
Assert.Equal((0, 0), await migration.RekeyLinksAsync(id, [Address], Ct));
}
}
public sealed class SqliteSyncLinkRekeyTests(TestContext context) : SyncLinkRekeyTests(context)
{
protected override Backend Backend => Backend.SqliteMemory;
}
public sealed class PostgresSyncLinkRekeyTests(TestContext context) : SyncLinkRekeyTests(context)
{
protected override Backend Backend => Backend.Postgres;
}
@@ -0,0 +1,172 @@
using Chronos.Core.IO;
using Chronos.Core.Localization;
using Chronos.Core.Project;
using Chronos.Data.Sync;
using Chronos.Data.Tests.Homes;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.Data.Tests.Workspaces;
/// <summary>The workspace split into one store per home (owner review 5, #66).</summary>
[Category("workspace")]
public sealed class WorkspaceHomesTests(TestContext context)
{
private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
[Test]
public void ANewWorkspaceIsSplitAndEachHomeGetsItsStore()
{
var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
var homes = new WorkspaceHomes(root, new ServerIdentity([new KnownServerKey(Id, [HomeFixtures.Nas])]));
Assert.True(homes.IsSplit);
Assert.True(WorkspaceHomes.IsSplitRoot(root));
Assert.Equal((WorkspaceHomes.ParentFormatVersion, WorkspaceHomes.HomesLayout), (homes.Manifest.FormatVersion, homes.Manifest.Layout));
Assert.Empty(homes.Homes());
// A 1.0 Chronos (store format 1) refuses the parent: it never shows the workspace empty.
Assert.Throws<InvalidDataException>(() => new WorkspaceStore(root));
var local = homes.StoreFor(HomeFixtures.Local());
Assert.Equal(Path.Combine(homes.Root, "local"), local.Root);
var server = homes.StoreFor(HomeFixtures.Server(HomeFixtures.Nas));
Assert.Equal(Path.Combine(homes.Root, "servers", Id.ToString("N")), server.Root);
Assert.Same(server, homes.StoreFor(HomeFixtures.Server(ServerIdentity.IdKey(Id))));
var record = Assert.NotNull(ServerHomeRecord.Read(server.Root));
Assert.Equal((ServerIdentity.IdKey(Id), (Guid?)Id), (record.Key, record.Id));
var other = homes.StoreFor(HomeFixtures.Server(HomeFixtures.Other));
Assert.Equal(Path.Combine(homes.Root, "servers", HomeFolders.ServerFolder(HomeFixtures.Other)), other.Root);
Assert.Equal(HomeFixtures.Other, Assert.NotNull(ServerHomeRecord.Read(other.Root)).Address);
Assert.NotEqual(local.Id, server.Id);
var described = Assert.NotNull(homes.Describe(HomeFixtures.Nas, "Studio NAS", HomeFixtures.Nas, "AA:BB", DateTimeOffset.UtcNow));
Assert.Equal(("Studio NAS", HomeFixtures.Nas, "AA:BB"), (described.Name, described.Address, described.TlsFingerprint));
Assert.Equal(record.FirstSeen, described.FirstSeen);
var listed = homes.Homes();
Assert.Equal(3, listed.Count);
Assert.True(listed[0].IsLocal);
Assert.Contains(listed, h => h.ServerKey == ServerIdentity.IdKey(Id) && h.Server?.Name == "Studio NAS");
}
[Test]
public void ProjectsAreFoundInEveryHomeAndTheTrashIsListedPerHome()
{
var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
var homes = new WorkspaceHomes(root);
var a = HomeFixtures.Project(homes.StoreFor(HomeFixtures.Local()).Root, HomeFixtures.Local());
var serverHome = HomeFixtures.Server(HomeFixtures.Nas);
var b = HomeFixtures.Project(homes.StoreFor(serverHome).Root, serverHome);
Assert.Equal(homes.LocalRoot, Path.GetDirectoryName(Assert.NotNull(homes.Find(a)).Folder));
Assert.Equal(homes.ServerRoot(HomeFixtures.Nas), Path.GetDirectoryName(Assert.NotNull(homes.Find(b)).Folder));
Assert.Null(homes.Find(Guid.CreateVersion7()));
Assert.Equal(2, homes.List().Count);
Assert.Equal(2, homes.ListBundles().Count);
HomeFixtures.TrashEntry(homes.ServerRoot(HomeFixtures.Nas), b, serverHome);
var trash = homes.Trash();
Assert.Equal(2, trash.Count);
Assert.Equal(1, trash.Sum(t => t.Entries.Count));
}
[Test]
public void A10WorkspaceStaysOneStoreUntilItIsSorted()
{
var root = HomeFixtures.LegacyWorkspace(context.CreateTempDirectory("ws"));
var a = HomeFixtures.Project(root, HomeFixtures.Local());
var homes = new WorkspaceHomes(root);
Assert.False(homes.IsSplit);
Assert.Equal(1, homes.Manifest.FormatVersion);
Assert.Equal(homes.Root, homes.StoreFor(HomeFixtures.Server(HomeFixtures.Nas)).Root);
Assert.Equal(homes.Root, homes.Local.Root);
Assert.True(Assert.NotNull(homes.Find(a)).Exists);
Assert.True(homes.Homes().Single().IsLegacy);
Assert.False(Directory.Exists(homes.LocalRoot), "nothing is made beside the 1.0 projects");
// A folder with projects and no manifest is a 1.0 workspace too, never a new split one.
var bare = Path.Combine(context.CreateTempDirectory("bare"), "workspace");
HomeFixtures.Project(bare, HomeFixtures.Local());
Assert.False(new WorkspaceHomes(bare).IsSplit);
}
[Test]
public void AProjectNotSortedYetIsListedWhereItIs()
{
var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
_ = new WorkspaceHomes(root);
var left = HomeFixtures.Project(root, HomeFixtures.Local());
var homes = new WorkspaceHomes(root);
Assert.True(homes.IsSplit);
Assert.Equal(homes.Root, Path.GetDirectoryName(Assert.NotNull(homes.Find(left)).Folder));
Assert.True(homes.Homes()[0].IsLegacy);
Assert.Equal(homes.LocalRoot, homes.Local.Root);
}
[Test]
public void AJobQueuedBeforeTheSortingFindsItsProjectInItsHome()
{
var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
var homes = new WorkspaceHomes(root);
var home = HomeFixtures.Server(HomeFixtures.Nas);
var id = HomeFixtures.Project(homes.ServerRoot(HomeFixtures.Nas), home);
_ = homes.StoreFor(home);
// Queued with the 1.0 folder (the parent): found in the server's home.
Assert.Equal(homes.ServerRoot(HomeFixtures.Nas), WorkspaceJobRoots.Resolve(root, id, null, "Errors.Workspace.NotCheckedOut"));
// Queued with the home of the address, which was re-keyed to the id since.
var rekeyed = Path.Combine(root, "servers", Id.ToString("N"));
Directory.Move(homes.ServerRoot(HomeFixtures.Nas), rekeyed);
Assert.Equal(rekeyed, WorkspaceJobRoots.Resolve(Path.Combine(root, "servers", HomeFolders.ServerFolder(HomeFixtures.Nas)), id, null, "Errors.Workspace.NotCheckedOut"));
// With the parent in use now (Settings › Workspace) and an older folder named.
Assert.Equal(rekeyed, WorkspaceJobRoots.Resolve(Path.Combine(context.CreateTempDirectory("gone"), "workspace"), id, () => root, "Errors.Workspace.NotCheckedOut"));
// While the parent is being moved nothing runs.
File.WriteAllText(Path.Combine(root, WorkspaceMover.JournalFile), "{}");
var moving = Assert.Throws<InvalidOperationException>(() => WorkspaceJobRoots.Resolve(rekeyed, id, null, "Errors.Workspace.NotCheckedOut"));
Assert.Equal(Loc.L("Errors.Workspace.Moving"), moving.Message);
File.Delete(Path.Combine(root, WorkspaceMover.JournalFile));
Assert.Throws<InvalidOperationException>(() => WorkspaceJobRoots.Resolve(root, Guid.CreateVersion7(), null, "Errors.Workspace.NotCheckedOut"));
}
[Test]
public void SameServerGoesThroughTheAliases()
{
var identity = new ServerIdentity([new KnownServerKey(Id, [HomeFixtures.Nas])]);
var options = new WorkspaceJobOptions(new Chronos.Data.Processing.ProcessingOptions(), () => false);
Assert.True(options.IsSameServer("https://NAS.local:8443", HomeFixtures.Nas));
Assert.False(options.IsSameServer(ServerIdentity.IdKey(Id), HomeFixtures.Nas));
var aliased = options with { SameServer = identity.Same };
Assert.True(aliased.IsSameServer(ServerIdentity.IdKey(Id), HomeFixtures.Nas));
Assert.False(aliased.IsSameServer(ServerIdentity.IdKey(Id), HomeFixtures.Other));
}
[Test]
public async Task MovingASplitWorkspaceMovesEveryHome()
{
foreach (var sameVolume in new[] { true, false })
{
var parent = context.CreateTempDirectory("move");
var from = Path.Combine(parent, "workspace");
var homes = new WorkspaceHomes(from);
var serverHome = HomeFixtures.Server(HomeFixtures.Nas);
var ids = new[]
{
HomeFixtures.Project(homes.StoreFor(HomeFixtures.Local()).Root, HomeFixtures.Local()),
HomeFixtures.Project(homes.StoreFor(serverHome).Root, serverHome),
HomeFixtures.Project(homes.StoreFor(HomeFixtures.Server(HomeFixtures.Other)).Root, HomeFixtures.Server(HomeFixtures.Other)),
};
var before = HomeFixtures.Manifest(from);
var to = Path.Combine(parent, "moved");
var mover = new WorkspaceMover(from, to) { SameVolume = sameVolume };
var survey = mover.Survey();
Assert.Equal(3, survey.Projects.Count);
Assert.SequenceEqual(new[] { "local", "servers", WorkspaceStore.ManifestFile }, survey.Entries);
var lines = new List<string>();
await mover.MoveAsync(survey.Fingerprint, log: lines.Add, cancellationToken: context.Cancellation);
Assert.False(Directory.Exists(from), "the old folder went");
var moved = new WorkspaceHomes(to);
Assert.True(moved.IsSplit);
Assert.Equal(3, moved.List().Count);
foreach (var id in ids) Assert.NotNull(moved.Find(id));
Assert.SequenceEqual(before, HomeFixtures.Manifest(to));
Assert.Contains(Loc.L("Archive.Log.WorkspaceMoved", mover.To, 3, survey.Files), lines);
}
}
}