feat: owner review 2 phase 4a: Reorganize sequences after import (#12)
CI / Build and test (push) Successful in 9m15s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 15m35s
CI / PostgreSQL 16 integration (push) Successful in 7m26s
CI / PostgreSQL 17 integration (push) Successful in 6m47s
CI / Docker image (push) Successful in 59s
Release / Server image (push) Successful in 1m24s
CI / Build and test (push) Successful in 9m15s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 15m35s
CI / PostgreSQL 16 integration (push) Successful in 7m26s
CI / PostgreSQL 17 integration (push) Successful in 6m47s
CI / Docker image (push) Successful in 59s
Release / Server image (push) Successful in 1m24s
- Reorganize… on the web panel and the desktop: folder, file and title templates applied to existing sequences, with a dry run and an explicit Apply that runs as a job. - One naming rule (FrameNaming) for import, upload and Reorganize. - Crash-safe plan and file journals, held plans, stale-plan refusal; exports move with their folder. - Writers refuse a folder another program moved or gave to another sequence. - Server: POST /api/v1/archive/reorganize with a bounded plan cache; template rules. - Phase 3 docs and translations merged; strings in all 38 languages. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #12.
This commit is contained in:
1 parent
9aa818ed47
commit
7e4a3b481d
416 files changed
+15304
-1572
No files matched your search
@@ -112,17 +112,24 @@ internal sealed class ArchiveFixture : IAsyncDisposable
|
||||
return job;
|
||||
}
|
||||
|
||||
/// <summary>Stages a verified upload-like file for ingest: returns its path, size and SHA-256.</summary>
|
||||
public (string Path, long Size, string Sha256) Stage(DateTime captured, int seed, string make = "Canon", string model = "Canon EOS R5")
|
||||
/// <summary>Stages a verified upload-like file for ingest (<paramref name="captured"/> null: a photo that records no time): returns its path, size and SHA-256.</summary>
|
||||
public (string Path, long Size, string Sha256) Stage(DateTime? captured, int seed, string? make = "Canon", string? model = "Canon EOS R5", string? lens = null)
|
||||
{
|
||||
var staging = Path.Combine(Paths.StagingDirectory, "uploads");
|
||||
Directory.CreateDirectory(staging);
|
||||
var bytes = Photos.Jpeg(captured, seed, make, model);
|
||||
var bytes = Photos.Jpeg(captured, seed, make, model, lens);
|
||||
var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part");
|
||||
File.WriteAllBytes(path, bytes);
|
||||
return (path, bytes.Length, Convert.ToHexStringLower(SHA256.HashData(bytes)));
|
||||
}
|
||||
|
||||
/// <summary>Every file under <paramref name="folder"/> with the hash of its content, in path order: what a test compares to tell that nothing there changed.</summary>
|
||||
public static List<string> FilesOf(string folder) =>
|
||||
[
|
||||
.. Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal)
|
||||
.Select(p => $"{Path.GetRelativePath(folder, p).Replace('\\', '/')} {Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(p)))}"),
|
||||
];
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
foreach (var owned in _owned) await owned.DisposeAsync();
|
||||
@@ -132,7 +139,7 @@ internal sealed class ArchiveFixture : IAsyncDisposable
|
||||
/// <summary>Small real JPEGs with Exif made by the in-house encoder; each seed gives distinct bytes.</summary>
|
||||
internal static class Photos
|
||||
{
|
||||
public static byte[] Jpeg(DateTime captured, int seed, string make = "Canon", string model = "Canon EOS R5")
|
||||
public static byte[] Jpeg(DateTime? captured, int seed, string? make = "Canon", string? model = "Canon EOS R5", string? lens = null)
|
||||
{
|
||||
using var image = new ImageBuffer(48, 32);
|
||||
var random = new Random(seed);
|
||||
@@ -142,7 +149,7 @@ internal static class Photos
|
||||
var level = (float)random.NextDouble();
|
||||
for (var i = 0; i < plane.Length; i++) plane[i] = level * (0.5f + 0.5f * (i % 48) / 48f);
|
||||
}
|
||||
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata { Make = make, Model = model, BodySerial = "0431", CapturedAt = captured, Iso = 100 });
|
||||
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata { Make = make, Model = model, LensModel = lens, BodySerial = "0431", CapturedAt = captured, Iso = 100 });
|
||||
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [exif[4..]] });
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ using System.Text.Json.Nodes;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Metadata;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving;
|
||||
@@ -90,6 +91,19 @@ public sealed class ArchiveSettingsTests(TestContext context)
|
||||
var template = await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||
fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { Folder = "{year/{date" } }, fx.Ct));
|
||||
Assert.Equal("folderTemplate", template.ParamName);
|
||||
// The rules every template is held to wherever it is typed: a folder scans never enter, a lost extension, names that repeat.
|
||||
foreach (var (folder, file, field) in new[]
|
||||
{
|
||||
("exports/{date}", "{n}", "folderTemplate"), ("{date}", "{n}{ext}", "fileTemplate"), ("{date}", "{title}", "fileTemplate"),
|
||||
})
|
||||
{
|
||||
var rule = await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||
fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { Folder = folder, File = file } }, fx.Ct));
|
||||
Assert.Equal(field, rule.ParamName, $"{folder} · {file}");
|
||||
}
|
||||
var created = await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||
fx.Service.CreateAsync(context.CreateTempDirectory("other"), "Other", new LayoutTemplates { Folder = "{date}", File = "{n}{ext}" }, null, fx.Ct));
|
||||
Assert.Equal("fileTemplate", created.ParamName);
|
||||
var proxies = await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||
fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Proxies = s.Proxies with { LongEdge = 100 } }, fx.Ct));
|
||||
Assert.Equal("proxyLongEdge", proxies.ParamName);
|
||||
@@ -102,6 +116,37 @@ public sealed class ArchiveSettingsTests(TestContext context)
|
||||
Assert.Equal(before, await File.ReadAllTextAsync(fx.Paths.ManifestPath, fx.Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TemplatesSavedBeforeTheRulesNeverFailAnEditOfAnotherSetting()
|
||||
{
|
||||
await using var fx = await ArchiveFixture.CreateAsync(context);
|
||||
// An archive.json of 0.1.0-rc.5 or earlier: both templates break a rule new templates are held to.
|
||||
var manifest = ManifestStore.ReadArchive(fx.Paths.ManifestPath);
|
||||
ManifestStore.WriteArchive(fx.Paths.ManifestPath, manifest with { LayoutTemplates = new LayoutTemplates { Folder = "exports/{date}", File = "{title}" } });
|
||||
|
||||
// The desktop saves one row at a time: each edit keeps the templates it does not change.
|
||||
var proxies = await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Proxies = s.Proxies with { LongEdge = 2560 } }, fx.Ct);
|
||||
Assert.Equal(("exports/{date}", "{title}", 2560), (proxies.FolderTemplate, proxies.FileTemplate, proxies.ProxyLongEdge));
|
||||
await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Name = "Studio" }, fx.Ct);
|
||||
var folder = await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { Folder = "{year}/{date}" } }, fx.Ct);
|
||||
Assert.Equal(("{year}/{date}", "{title}"), (folder.FolderTemplate, folder.FileTemplate));
|
||||
|
||||
// A template given anew is held to every rule, and the refusal says which.
|
||||
var before = await File.ReadAllTextAsync(fx.Paths.ManifestPath, fx.Ct);
|
||||
var refused = await Assert.ThrowsAsync<TemplateRuleException>(() =>
|
||||
fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { File = "{n}{ext}" } }, fx.Ct));
|
||||
Assert.Equal(("fileTemplate", "Extension", Loc.L("Errors.Template.Extension")), (refused.ParamName, refused.Rule, refused.Message));
|
||||
Assert.Equal(before, await File.ReadAllTextAsync(fx.Paths.ManifestPath, fx.Ct));
|
||||
|
||||
var file = await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { File = "{date}_{n:0000}" } }, fx.Ct);
|
||||
Assert.Equal(("Studio", "{year}/{date}", "{date}_{n:0000}", 2560), (file.Name, file.FolderTemplate, file.FileTemplate, file.ProxyLongEdge));
|
||||
|
||||
// A new archive has nothing to keep: its templates meet every rule.
|
||||
var created = await Assert.ThrowsAsync<TemplateRuleException>(() => fx.Service.CreateAsync(context.CreateTempDirectory("other"), "Other",
|
||||
new LayoutTemplates { Folder = "exports/{date}", File = "{date}_{n:0000}" }, null, fx.Ct));
|
||||
Assert.Equal(("folderTemplate", "ReservedFolder"), (created.ParamName, created.Rule));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnOfflineArchiveIsNotChangedAndItsIndexSettingsAreShown()
|
||||
{
|
||||
|
||||
@@ -1127,6 +1127,90 @@ public abstract class FrameTrashTests(TestContext context) : DatabaseTest(contex
|
||||
Assert.SequenceEqual(frames.Select(f => f.Id), (await fx.Db.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
|
||||
}
|
||||
|
||||
/// <summary>The files of a sequence as its sidecar names them, after checking that the index names the same ones and that each holds its photo.</summary>
|
||||
private static async Task<List<string>> FilesAsync(ArchiveFixture fx, Guid id)
|
||||
{
|
||||
var sequence = Assert.NotNull(await fx.Db.Sequences.GetAsync(id));
|
||||
var folder = fx.Paths.Sequence(sequence.Folder);
|
||||
var sidecar = ManifestStore.ReadSequence(folder.ManifestPath);
|
||||
var rows = await fx.Db.Frames.ListBySequenceAsync(id);
|
||||
Assert.SequenceEqual(sidecar.Frames.Select(f => (f.Id, folder.ArchiveRelative(f.File))), rows.Select(r => (r.Id, r.RelativePath)));
|
||||
foreach (var frame in sidecar.Frames) Assert.Equal(frame.Sha256, Sha(folder.File(frame.File)));
|
||||
return [.. sidecar.Frames.Select(f => f.File)];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PhotosDeletedBeforeAReorganizeComeBackBesideTheNamesItGave()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (sequence, frames) = await UploadedAsync(fx, 4);
|
||||
var numbered = new RenameTemplates(File: "{n:000}");
|
||||
await fx.Service.ApplyRenameAsync(await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [sequence.Id], numbered, fx.Ct), null, fx.Ct);
|
||||
var folder = fx.Paths.Sequence(sequence.Folder);
|
||||
File.WriteAllText(folder.File("originals/002.xmp"), "second");
|
||||
await fx.ScanAsync();
|
||||
// The record keeps the names the photo and its companion had: 002.JPG and 002.xmp.
|
||||
var deleted = await DeleteAsync(fx, (await fx.Db.Sequences.GetAsync(sequence.Id))!, frames[1]);
|
||||
Assert.SequenceEqual(["originals/002.JPG", "originals/002.xmp"], FrameTrash.ReadEntry(fx.Paths, deleted.Entry.Name)!.Photos.Single().Files.Select(f => f.From));
|
||||
|
||||
// Moved and renamed since: the photos that stay take 001-003, the deleted photo's name included.
|
||||
var moved = new RenameTemplates(Folder: "moved/{date}", File: "{n:000}");
|
||||
await fx.Service.ApplyRenameAsync(await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [sequence.Id], moved, fx.Ct), null, fx.Ct);
|
||||
Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG", "originals/003.JPG"], await FilesAsync(fx, sequence.Id));
|
||||
|
||||
// Restored into the sequence where it is now, under its own name made free: its companion follows that name.
|
||||
var restored = await fx.Service.RestoreEntryAsync(fx.Archive.Id, deleted.Entry.Name, null, fx.Ct);
|
||||
Assert.Equal(1, restored.Photos);
|
||||
var row = (await fx.Db.Sequences.GetAsync(sequence.Id))!;
|
||||
Assert.Equal("moved/2026-09-28", row.Folder);
|
||||
Assert.SequenceEqual(["originals/001.JPG", "originals/002_2.JPG", "originals/002.JPG", "originals/003.JPG"], await FilesAsync(fx, sequence.Id));
|
||||
var now = fx.Paths.Sequence(row.Folder);
|
||||
Assert.Equal(frames[1].Sha256, Sha(now.File("originals/002_2.JPG")));
|
||||
Assert.Equal("second", File.ReadAllText(now.File("originals/002_2.xmp")));
|
||||
Assert.SequenceEqual(frames.Select(f => f.Id), (await fx.Db.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
|
||||
Assert.DoesNotContain(TrashKind.Photos, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Select(e => e.Kind));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AReorganizeWaitsForARestoreItsEntryHoldsThenSettlesItFirst()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (sequence, frames) = await UploadedAsync(fx, 3);
|
||||
var folder = fx.Paths.Sequence(sequence.Folder);
|
||||
var deleted = await DeleteAsync(fx, sequence, frames[1]);
|
||||
// A restore died after moving the original back, before the sidecar; the entry is being emptied meanwhile.
|
||||
var journal = RestoreJournal(fx, deleted.Entry);
|
||||
journal.Write(folder);
|
||||
var back = journal.Photos[0].Moves[0];
|
||||
File.Move(fx.Paths.FromRelative(back.To), folder.File(back.From));
|
||||
var templates = new RenameTemplates(Folder: "moved/{date}", File: "{n:000}");
|
||||
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [sequence.Id], templates, fx.Ct);
|
||||
Assert.Equal(2, plan.Steps.Single().FileChanges);
|
||||
var before = await FilesAsync(fx, sequence.Id);
|
||||
|
||||
using (Assert.NotNull(LeaseFile.TryAcquire(fx.Paths.LocksDirectory, SequenceTrash.EntryLease(deleted.Entry.Name), "other")))
|
||||
{
|
||||
// Neither the folder nor a file name changes under that restore.
|
||||
await Assert.ThrowsAsync<LeaseUnavailableException>(() => fx.Service.ApplyRenameAsync(plan, null, fx.Ct));
|
||||
Assert.Equal(sequence.Folder, (await fx.Db.Sequences.GetAsync(sequence.Id))!.Folder);
|
||||
Assert.SequenceEqual(before, await FilesAsync(fx, sequence.Id));
|
||||
Assert.FileExists(folder.RestoreJournalPath);
|
||||
Assert.FileExists(folder.File(back.From));
|
||||
}
|
||||
|
||||
// Once the entry is free the rename resumes: the restore is settled first (the original goes back into its entry),
|
||||
// then the folder moves and the files are renamed; the photo then comes back beside them.
|
||||
Assert.Equal(1, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
|
||||
Assert.Equal(frames[1].Sha256, Sha(fx.Paths.FromRelative(back.To)));
|
||||
var row = (await fx.Db.Sequences.GetAsync(sequence.Id))!;
|
||||
Assert.Equal("moved/2026-09-28", row.Folder);
|
||||
Assert.FileMissing(fx.Paths.Sequence(row.Folder).RestoreJournalPath);
|
||||
Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG"], await FilesAsync(fx, sequence.Id));
|
||||
Assert.Equal(1, (await fx.Service.RestoreEntryAsync(fx.Archive.Id, deleted.Entry.Name, null, fx.Ct)).Photos);
|
||||
Assert.SequenceEqual(frames.Select(f => f.Id), (await fx.Db.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
|
||||
Assert.Count(3, await FilesAsync(fx, sequence.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARestoreIntoANewSequenceStoppedBetweenPhotosKeepsItsRecordTrue()
|
||||
{
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Testing;
|
||||
using static Chronos.Data.Tests.Archiving.ArchiveFixture;
|
||||
|
||||
@@ -233,6 +236,331 @@ public sealed class MassRenameTests(TestContext context)
|
||||
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ExportsInsideAMovedFolderAreStillReachable()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var ids = await NestedAsync(fx);
|
||||
// Exports of "trips" and of "trips/day2" in their folders, one of "trips/day2/dawn" saved in the exports of "trips"
|
||||
// (the Export tab's folder picker), one of "trips" outside the archive, a row whose path only starts with the same
|
||||
// letters, and one of "trips/day2" in "trips" whose file is gone.
|
||||
var outside = Path.Combine(context.CreateTempDirectory("exports"), "Trips elsewhere.mp4");
|
||||
List<Guid> renders =
|
||||
[
|
||||
await RenderAsync(fx, ids[0], "trips/exports/Trips.mp4"),
|
||||
await RenderAsync(fx, ids[1], "trips/day2/exports/Day 2.mp4"),
|
||||
await RenderAsync(fx, ids[2], "trips/exports/Dawn.mp4"),
|
||||
await RenderAsync(fx, ids[0], outside),
|
||||
await RenderAsync(fx, ids[0], "trips 2/exports/Other.mp4", write: false),
|
||||
await RenderAsync(fx, ids[1], "trips/exports/Gone.mp4", write: false),
|
||||
];
|
||||
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0]], "moved/{date}", null, fx.Ct);
|
||||
Assert.SequenceEqual([false, true, true], plan.Steps.Select(s => s.Carried));
|
||||
|
||||
await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
string[] expected =
|
||||
[
|
||||
"moved/2026-09-28/exports/Trips.mp4", "moved/2026-09-28/day2/exports/Day 2.mp4", "moved/2026-09-28/exports/Dawn.mp4", outside,
|
||||
"trips 2/exports/Other.mp4", "trips/exports/Gone.mp4",
|
||||
];
|
||||
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders));
|
||||
foreach (var path in expected[..4]) Assert.FileExists(Path.IsPathRooted(path) ? path : fx.Paths.FromRelative(path));
|
||||
|
||||
// A crash after the steps were recorded but before the journal said so: completed again, and again, nothing moves twice.
|
||||
RenameJournal.Write(fx.Paths, new RenameJournal(plan, []));
|
||||
Assert.Equal(1, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
|
||||
Assert.Equal(0, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
|
||||
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnotherIndexFindsTheExportsWhereAReorganizeMovedTheirFolder()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var ids = await PopulateAsync(fx);
|
||||
// This index's exports: of "inbox/a" in its folder, of "inbox/b" saved in the exports of "inbox/a", of "inbox/c" in its own.
|
||||
List<Guid> renders =
|
||||
[
|
||||
await RenderAsync(fx, ids[0], "inbox/a/exports/A.mp4"),
|
||||
await RenderAsync(fx, ids[1], "inbox/a/exports/B.mp4"),
|
||||
await RenderAsync(fx, ids[2], "inbox/c/exports/C.mp4"),
|
||||
];
|
||||
var (server, archive) = await fx.OtherWriterAsync();
|
||||
|
||||
// The other index (a server sharing this desktop's archive) moves "inbox/a", then "inbox/c" into the folder it left.
|
||||
var first = await server.PlanRenameAsync(archive.Id, [ids[0]], "moved/{date}", null, fx.Ct);
|
||||
await server.ApplyRenameAsync(first, null, fx.Ct);
|
||||
var second = await server.PlanRenameAsync(archive.Id, [ids[2]], "inbox/a", null, fx.Ct);
|
||||
Assert.Equal("inbox/a", second.Steps.Single().ToFolder);
|
||||
await server.ApplyRenameAsync(second, null, fx.Ct);
|
||||
|
||||
// A scan here finds both where they are now (the new "inbox/a" first): each export follows the folder its file moved with.
|
||||
await fx.ScanAsync();
|
||||
Assert.Equal("moved/2026-09-28", (await fx.Db.Sequences.GetAsync(ids[0], fx.Ct))!.Folder);
|
||||
Assert.Equal("inbox/a", (await fx.Db.Sequences.GetAsync(ids[2], fx.Ct))!.Folder);
|
||||
string[] expected = ["moved/2026-09-28/exports/A.mp4", "moved/2026-09-28/exports/B.mp4", "inbox/a/exports/C.mp4"];
|
||||
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders));
|
||||
foreach (var path in expected) Assert.FileExists(fx.Paths.FromRelative(path));
|
||||
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
|
||||
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnExportWrittenWhereItsFolderWasStaysWithItsFile()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var ids = await PopulateAsync(fx);
|
||||
List<Guid> renders = [await RenderAsync(fx, ids[0], "inbox/a/exports/A.mp4")];
|
||||
var (server, archive) = await fx.OtherWriterAsync();
|
||||
|
||||
// The other index moves "inbox/a"; a writer here that read the folder before files an export where it was, creating
|
||||
// it again. Another export of the sequence is missing from both places.
|
||||
var plan = await server.PlanRenameAsync(archive.Id, [ids[0]], "moved/{date}", null, fx.Ct);
|
||||
await server.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
renders.Add(await RenderAsync(fx, ids[0], "inbox/a/exports/Late.mp4"));
|
||||
renders.Add(await RenderAsync(fx, ids[0], "inbox/a/exports/Gone.mp4", write: false));
|
||||
|
||||
// The scan here moves the rows whose file went with the folder or is nowhere, and keeps the one whose file stayed.
|
||||
await fx.ScanAsync();
|
||||
Assert.Equal("moved/2026-09-28", (await fx.Db.Sequences.GetAsync(ids[0], fx.Ct))!.Folder);
|
||||
string[] expected = ["moved/2026-09-28/exports/A.mp4", "inbox/a/exports/Late.mp4", "moved/2026-09-28/exports/Gone.mp4"];
|
||||
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders));
|
||||
foreach (var path in expected[..2]) Assert.FileExists(fx.Paths.FromRelative(path));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnImageSequenceExportIsAFolderThatFollowsAsAFileDoes()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var ids = await PopulateAsync(fx);
|
||||
// Image-sequence exports: of "inbox/a" in its folder, and of "inbox/b" saved in the exports of "inbox/a".
|
||||
List<Guid> renders =
|
||||
[
|
||||
await RenderAsync(fx, ids[0], "inbox/a/exports/A frames", frames: true),
|
||||
await RenderAsync(fx, ids[1], "inbox/a/exports/B frames", frames: true),
|
||||
];
|
||||
var (server, archive) = await fx.OtherWriterAsync();
|
||||
|
||||
// The other index moves "inbox/a"; a writer here that read the folder before files one where it was, creating it again.
|
||||
var plan = await server.PlanRenameAsync(archive.Id, [ids[0]], "moved/{date}", null, fx.Ct);
|
||||
await server.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
renders.Add(await RenderAsync(fx, ids[0], "inbox/a/exports/Late frames", frames: true));
|
||||
|
||||
// Each folder follows, or stays, as a file would: both that moved with the folder, not the one written where it was.
|
||||
await fx.ScanAsync();
|
||||
string[] expected = ["moved/2026-09-28/exports/A frames", "moved/2026-09-28/exports/B frames", "inbox/a/exports/Late frames"];
|
||||
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders));
|
||||
foreach (var path in expected) Assert.FileExists(Path.Combine(fx.Paths.FromRelative(path), "000001.png"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnExportNeverNamesTheOneAnotherSequenceBroughtIntoItsOldFolder()
|
||||
{
|
||||
// The new folder is scanned after "inbox/a", then before it. "inbox/a" and "inbox/c" each have an export of the
|
||||
// same name: the one of "inbox/a" gone, both there, or the one of "inbox/c" gone.
|
||||
var cases = from template in new[] { "moved/{date}", "done/{date}" }
|
||||
from files in new[] { (A: false, C: true), (A: true, C: true), (A: true, C: false) }
|
||||
select (template, files.A, files.C);
|
||||
foreach (var (template, a, c) in cases)
|
||||
{
|
||||
var label = $"{template}, a {(a ? "there" : "gone")}, c {(c ? "there" : "gone")}";
|
||||
await using var fx = await CreateAsync(context);
|
||||
var ids = await PopulateAsync(fx);
|
||||
List<Guid> renders =
|
||||
[
|
||||
await RenderAsync(fx, ids[0], "inbox/a/exports/Clip.mp4", write: a),
|
||||
await RenderAsync(fx, ids[2], "inbox/c/exports/Clip.mp4", write: c),
|
||||
];
|
||||
if (a) await File.WriteAllTextAsync(fx.Paths.FromRelative("inbox/a/exports/Clip.mp4"), "a", fx.Ct);
|
||||
if (c) await File.WriteAllTextAsync(fx.Paths.FromRelative("inbox/c/exports/Clip.mp4"), "c", fx.Ct);
|
||||
var (server, archive) = await fx.OtherWriterAsync();
|
||||
|
||||
// The other index moves "inbox/a", then "inbox/c" into the folder it left, their exports along.
|
||||
var first = await server.PlanRenameAsync(archive.Id, [ids[0]], template, null, fx.Ct);
|
||||
await server.ApplyRenameAsync(first, null, fx.Ct);
|
||||
await server.ApplyRenameAsync(await server.PlanRenameAsync(archive.Id, [ids[2]], "inbox/a", null, fx.Ct), null, fx.Ct);
|
||||
|
||||
// Each row follows its own sequence's folder, its file there or missing there too, and never names the other one's.
|
||||
await fx.ScanAsync();
|
||||
string[] expected = [first.Steps.Single().ToFolder + "/exports/Clip.mp4", "inbox/a/exports/Clip.mp4"];
|
||||
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders), label);
|
||||
if (a) Assert.Equal("a", await File.ReadAllTextAsync(fx.Paths.FromRelative(expected[0]), fx.Ct), label);
|
||||
if (c) Assert.Equal("c", await File.ReadAllTextAsync(fx.Paths.FromRelative(expected[1]), fx.Ct), label);
|
||||
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
|
||||
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders), label);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnExportSavedInAnotherSequencesFolderNeverNamesTheOneBroughtIntoIt()
|
||||
{
|
||||
// The new folder is scanned after "inbox/a", then before it.
|
||||
foreach (var template in new[] { "moved/{date}", "done/{date}" })
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var ids = await PopulateAsync(fx);
|
||||
// "inbox/b" saved an export in the exports of "inbox/a" (the Export tab's folder picker); "inbox/c" has one of the same name.
|
||||
List<Guid> renders =
|
||||
[
|
||||
await RenderAsync(fx, ids[1], "inbox/a/exports/Clip.mp4"),
|
||||
await RenderAsync(fx, ids[2], "inbox/c/exports/Clip.mp4"),
|
||||
];
|
||||
await File.WriteAllTextAsync(fx.Paths.FromRelative("inbox/a/exports/Clip.mp4"), "b", fx.Ct);
|
||||
await File.WriteAllTextAsync(fx.Paths.FromRelative("inbox/c/exports/Clip.mp4"), "c", fx.Ct);
|
||||
var (server, archive) = await fx.OtherWriterAsync();
|
||||
|
||||
// The other index moves "inbox/a", the export of "inbox/b" along, then "inbox/c" into the folder it left, its export along.
|
||||
var first = await server.PlanRenameAsync(archive.Id, [ids[0]], template, null, fx.Ct);
|
||||
await server.ApplyRenameAsync(first, null, fx.Ct);
|
||||
await server.ApplyRenameAsync(await server.PlanRenameAsync(archive.Id, [ids[2]], "inbox/a", null, fx.Ct), null, fx.Ct);
|
||||
|
||||
// The export of "inbox/b" follows the folder its file moved with and never names the one of "inbox/c".
|
||||
await fx.ScanAsync();
|
||||
string[] expected = [first.Steps.Single().ToFolder + "/exports/Clip.mp4", "inbox/a/exports/Clip.mp4"];
|
||||
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders), template);
|
||||
Assert.Equal("b", await File.ReadAllTextAsync(fx.Paths.FromRelative(expected[0]), fx.Ct), template);
|
||||
Assert.Equal("c", await File.ReadAllTextAsync(fx.Paths.FromRelative(expected[1]), fx.Ct), template);
|
||||
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
|
||||
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders), template);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APhotoDeletionWhoseFolderMovedWhileItWaitedForTheLeaseIsRefused()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var ids = await PopulateAsync(fx);
|
||||
var frames = await fx.Db.Frames.ListBySequenceAsync(ids[0], cancellationToken: fx.Ct);
|
||||
var deletion = await fx.Service.FrameTrash.PlanDeleteAsync(ids[0], [frames[1].Id], cancellationToken: fx.Ct);
|
||||
Assert.True(deletion.CanDelete);
|
||||
var pause = TimeSpan.FromSeconds(TestTiming.Budget(0.5));
|
||||
|
||||
// Another process holds the sequence and moves its folder (a Reorganize), while the deletion waits for the lease.
|
||||
Task<FrameDeleteResult> delete;
|
||||
using (await LeaseFile.AcquireAsync(fx.Paths.LocksDirectory, $"seq-{ids[0]:N}", "other", TimeSpan.FromSeconds(5), cancellationToken: fx.Ct))
|
||||
{
|
||||
delete = fx.Service.FrameTrash.DeleteAsync(deletion, cancellationToken: fx.Ct);
|
||||
await Task.Delay(pause, fx.Ct);
|
||||
Assert.False(delete.IsCompleted, "the deletion waits for the other process");
|
||||
Directory.CreateDirectory(fx.Paths.FromRelative("moved"));
|
||||
Directory.Move(fx.Paths.FromRelative("inbox/a"), fx.Paths.FromRelative("moved/a"));
|
||||
await using var tx = await fx.Db.BeginAsync(fx.Ct);
|
||||
await tx.Sequences.RelocateAsync(ids[0], "moved/a", null, fx.Ct);
|
||||
await tx.Frames.RebaseFolderAsync(ids[0], "inbox/a", "moved/a", fx.Ct);
|
||||
await tx.CommitAsync(fx.Ct);
|
||||
}
|
||||
|
||||
await Assert.ThrowsAsync<StaleDeletePlanException>(() => delete);
|
||||
Assert.Count(3, await fx.Db.Frames.ListBySequenceAsync(ids[0], cancellationToken: fx.Ct));
|
||||
Assert.Count(3, ManifestStore.ReadSequence(fx.Paths.Sequence("moved/a").ManifestPath).Frames);
|
||||
foreach (var f in frames) Assert.FileExists(fx.Paths.FromRelative(f.RelativePath.Replace("inbox/a/", "moved/a/", StringComparison.Ordinal)));
|
||||
Assert.Empty(await fx.Service.Trash.ListAsync(fx.Archive, fx.Ct));
|
||||
Assert.False(Directory.Exists(fx.Paths.FromRelative("inbox/a")), "the folder it left is not created again");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnInterruptedMoveTakesTheExportsAlongWhenItResumes()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var ids = await PopulateAsync(fx);
|
||||
List<Guid> renders = [];
|
||||
foreach (var (id, folder) in ids.Zip(["inbox/a", "inbox/b", "inbox/c"])) renders.Add(await RenderAsync(fx, id, $"{folder}/exports/Clip.mp4"));
|
||||
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, ids, "renamed/{date}", null, fx.Ct);
|
||||
using var cts = new CancellationTokenSource();
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => fx.Service.ApplyRenameAsync(plan, new SyncProgress(_ => cts.Cancel()), cts.Token));
|
||||
Assert.Count(1, RenameJournal.ListPending(fx.Paths).Single().Completed);
|
||||
|
||||
// Crash in the middle of the next step: its folder moved with its export, the index not yet updated.
|
||||
var next = plan.Steps[1];
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(fx.Paths.FromRelative(next.ToFolder))!);
|
||||
Directory.Move(fx.Paths.FromRelative(next.FromFolder), fx.Paths.FromRelative(next.ToFolder));
|
||||
|
||||
await fx.Service.OpenAsync(fx.Archive.RootPath, fx.Ct); // the next start finds the journal
|
||||
Assert.Empty(RenameJournal.ListPending(fx.Paths));
|
||||
Assert.Equal(0, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
|
||||
var outputs = await OutputsAsync(fx, renders);
|
||||
Assert.SequenceEqual(ids.Select(id => $"{plan.Steps.Single(s => s.SequenceId == id).ToFolder}/exports/Clip.mp4"), outputs);
|
||||
foreach (var path in outputs) Assert.FileExists(fx.Paths.FromRelative(path));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WritersThatReadTheSequenceBeforeItsFolderMovedWriteWhereItIsNow()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var ids = await PopulateAsync(fx);
|
||||
var stale = (await fx.Db.Sequences.GetAsync(ids[0], fx.Ct))!;
|
||||
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0]], "moved/{date}", null, fx.Ct);
|
||||
await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
var now = fx.Paths.Sequence(plan.Steps.Single().ToFolder);
|
||||
var left = fx.Paths.Sequence(stale.Folder).Folder;
|
||||
Assert.False(Directory.Exists(left));
|
||||
|
||||
// A thumbnail pass and an analysis's project update that read the row before the move take their leases after it.
|
||||
await fx.Service.Images.BuildThumbnailsAsync(fx.Archive, stale, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.FileExists(now.ThumbsPackPath);
|
||||
Assert.True(((await fx.Db.Sequences.GetAsync(ids[0], fx.Ct))!.Status & SequenceStatus.ThumbsBuilt) != 0, "the pass is recorded");
|
||||
var projects = new ProjectStore(fx.Db, new SequenceWriter(new ArchiveServiceOptions { Owner = "analysis" }));
|
||||
Assert.True(await projects.UpdateAsync(fx.Paths, stale, p => p with { HeroFrame = 1 }, fx.Ct));
|
||||
Assert.Equal(1, ProjectSettings.FromJson(await File.ReadAllTextAsync(now.ProjectPath, fx.Ct)).HeroFrame);
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APhotoFiledWhileTheFolderMovesGoesWhereTheSequenceIsNow()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var ids = await PopulateAsync(fx);
|
||||
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0]], "moved/{date}", null, fx.Ct);
|
||||
var staged = fx.Stage(Start.AddMinutes(30), 99);
|
||||
var pause = TimeSpan.FromSeconds(TestTiming.Budget(0.5));
|
||||
|
||||
// Another process writes the sequence: the move waits for it, and an upload that read the row meanwhile waits behind the move.
|
||||
Task apply;
|
||||
Task<IngestResult> upload;
|
||||
using (await LeaseFile.AcquireAsync(fx.Paths.LocksDirectory, $"seq-{ids[0]:N}", "other", TimeSpan.FromSeconds(5), cancellationToken: fx.Ct))
|
||||
{
|
||||
apply = fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
await Task.Delay(pause, fx.Ct);
|
||||
upload = fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, ids[0], null, null, staged.Path, "LATE.JPG", staged.Size, staged.Sha256,
|
||||
null, null), fx.Ct);
|
||||
await Task.Delay(pause, fx.Ct);
|
||||
Assert.False(apply.IsCompleted || upload.IsCompleted, "both wait for the other process");
|
||||
}
|
||||
|
||||
await apply;
|
||||
var filed = await upload;
|
||||
var now = plan.Steps.Single().ToFolder;
|
||||
Assert.True(filed.RelativePath.StartsWith(now + "/", StringComparison.Ordinal), filed.RelativePath);
|
||||
Assert.FileExists(fx.Paths.FromRelative(filed.RelativePath));
|
||||
Assert.Count(4, await fx.Db.Frames.ListBySequenceAsync(ids[0], cancellationToken: fx.Ct));
|
||||
Assert.False(Directory.Exists(fx.Paths.FromRelative("inbox/a")), "the folder it left is not created again");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A render row of <paramref name="sequenceId"/> at <paramref name="output"/> (archive-relative or absolute), with its
|
||||
/// file unless told otherwise; with <paramref name="frames"/> an image sequence's export, a folder of frames.
|
||||
/// </summary>
|
||||
private static async Task<Guid> RenderAsync(ArchiveFixture fx, Guid sequenceId, string output, bool write = true, bool frames = false)
|
||||
{
|
||||
if (write)
|
||||
{
|
||||
var file = Path.IsPathRooted(output) ? output : fx.Paths.FromRelative(output);
|
||||
if (frames) file = Path.Combine(file, "000001.png");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(file)!);
|
||||
await File.WriteAllBytesAsync(file, [1, 2, 3], fx.Ct);
|
||||
}
|
||||
var render = new Render { Id = Guid.CreateVersion7(), SequenceId = sequenceId, PresetName = "1080p", OutputPath = output, Bytes = 3, Created = DateTimeOffset.UtcNow };
|
||||
await fx.Db.Renders.InsertAsync(render, fx.Ct);
|
||||
return render.Id;
|
||||
}
|
||||
|
||||
private static async Task<List<string>> OutputsAsync(ArchiveFixture fx, IEnumerable<Guid> renders)
|
||||
{
|
||||
var outputs = new List<string>();
|
||||
foreach (var id in renders) outputs.Add((await fx.Db.Renders.GetAsync(id, fx.Ct))!.OutputPath);
|
||||
return outputs;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFolderInsideASequenceFolderIsRefused()
|
||||
{
|
||||
|
||||
@@ -2,9 +2,11 @@ using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Imaging.Decoders;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Metadata;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Tests.Processing;
|
||||
using Chronos.Testing;
|
||||
using static Chronos.Data.Tests.Archiving.ArchiveFixture;
|
||||
|
||||
@@ -37,11 +39,11 @@ public sealed class ProxyTests(TestContext context)
|
||||
var folder = fx.Paths.Sequence(sequence.Folder);
|
||||
var images = fx.Service.Images;
|
||||
|
||||
Assert.Equal(ProxyStoreResult.Invalid, images.StoreProxy(fx.Archive, sequence, frames[0], "not a photo"u8.ToArray()));
|
||||
Assert.Equal(ProxyStoreResult.WrongFrame, images.StoreProxy(fx.Archive, sequence, frames[0], Proxy(frames[1].CapturedAt!.Value, 1)));
|
||||
Assert.Equal(ProxyStoreResult.Invalid, await images.StoreProxyAsync(fx.Archive, sequence, frames[0], "not a photo"u8.ToArray(), fx.Ct));
|
||||
Assert.Equal(ProxyStoreResult.WrongFrame, await images.StoreProxyAsync(fx.Archive, sequence, frames[0], Proxy(frames[1].CapturedAt!.Value, 1), fx.Ct));
|
||||
Assert.FileMissing(folder.Proxy(0));
|
||||
var proxy = Proxy(frames[0].CapturedAt!.Value, 2);
|
||||
Assert.Equal(ProxyStoreResult.Stored, images.StoreProxy(fx.Archive, sequence, frames[0], proxy));
|
||||
Assert.Equal(ProxyStoreResult.Stored, await images.StoreProxyAsync(fx.Archive, sequence, frames[0], proxy, fx.Ct));
|
||||
Assert.SequenceEqual(proxy, await File.ReadAllBytesAsync(folder.Proxy(0), fx.Ct));
|
||||
|
||||
// The proxy pass keeps what was sent and makes none from the originals here, even when forced.
|
||||
@@ -62,6 +64,148 @@ public sealed class ProxyTests(TestContext context)
|
||||
Assert.Equal((0, 1, 1), (again.Built, again.Reused, again.Undecodable));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ProxiesSentOrMadeAfterTheFolderMovedGoWhereTheSequenceIsNow()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var (stale, frames) = await HeifSequenceAsync(fx);
|
||||
var images = fx.Service.Images;
|
||||
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [stale.Id], "moved/{date}", null, fx.Ct);
|
||||
await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
var now = fx.Paths.Sequence(plan.Steps.Single().ToFolder);
|
||||
var left = fx.Paths.Sequence(stale.Folder).Folder;
|
||||
Assert.False(Directory.Exists(left));
|
||||
|
||||
// A proxy upload and a proxy pass that read the sequence before the move write once they hold its lease.
|
||||
var proxy = Proxy(frames[0].CapturedAt!.Value, 2);
|
||||
Assert.Equal(ProxyStoreResult.Stored, await images.StoreProxyAsync(fx.Archive, stale, frames[0], proxy, fx.Ct));
|
||||
Assert.SequenceEqual(proxy, await File.ReadAllBytesAsync(now.Proxy(0), fx.Ct));
|
||||
var pass = await images.BuildProxiesAsync(fx.Archive, stale, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.Equal((0, 1, 0, 1), (pass.Built, pass.Reused, pass.Undecodable, pass.Waiting));
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
|
||||
// Deleted since: nothing is written.
|
||||
Assert.True(await fx.Db.Sequences.DeleteAsync(stale.Id, fx.Ct));
|
||||
Assert.Equal(ProxyStoreResult.Gone, await images.StoreProxyAsync(fx.Archive, stale, frames[1], Proxy(frames[1].CapturedAt!.Value, 3), fx.Ct));
|
||||
Assert.FileMissing(now.Proxy(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ProxiesOfAFolderAnotherIndexMovedWaitForThisIndexsScan()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var (sequence, frames) = await HeifSequenceAsync(fx);
|
||||
var images = fx.Service.Images;
|
||||
var left = fx.Paths.Sequence(sequence.Folder).Folder;
|
||||
var (server, archive) = await fx.OtherWriterAsync();
|
||||
var plan = await server.PlanRenameAsync(archive.Id, [sequence.Id], "moved/{date}", null, fx.Ct);
|
||||
await server.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
var moved = fx.Paths.Sequence(plan.Steps.Single().ToFolder);
|
||||
|
||||
// This index still has the folder where it was: a proxy sent and a proxy pass write nothing, anywhere.
|
||||
var proxy = Proxy(frames[0].CapturedAt!.Value, 2);
|
||||
Assert.Equal(ProxyStoreResult.Gone, await images.StoreProxyAsync(fx.Archive, sequence, frames[0], proxy, fx.Ct));
|
||||
var refused = await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct));
|
||||
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), refused.Message);
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
Assert.FileMissing(moved.Proxy(0));
|
||||
|
||||
// Once this index's scan found it there, they go where it is.
|
||||
await fx.ScanAsync();
|
||||
Assert.Equal(ProxyStoreResult.Stored, await images.StoreProxyAsync(fx.Archive, sequence, frames[0], proxy, fx.Ct));
|
||||
Assert.SequenceEqual(proxy, await File.ReadAllBytesAsync(moved.Proxy(0), fx.Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ImagesOfAFolderAnotherSequenceTookAreNotWrittenThere()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var (sequence, frames) = await HeifSequenceAsync(fx);
|
||||
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "other"), Start.AddDays(3), 2, firstSeed: 70);
|
||||
await fx.ScanAsync();
|
||||
var stranger = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id, fx.Ct)).Single(l => l.Folder == "inbox/other").Id;
|
||||
var images = fx.Service.Images;
|
||||
var (server, archive) = await fx.OtherWriterAsync();
|
||||
await server.ApplyRenameAsync(await server.PlanRenameAsync(archive.Id, [sequence.Id], "moved/{date}", null, fx.Ct), null, fx.Ct);
|
||||
await server.ApplyRenameAsync(await server.PlanRenameAsync(archive.Id, [stranger], sequence.Folder, null, fx.Ct), null, fx.Ct);
|
||||
var folder = fx.Paths.Sequence(sequence.Folder).Folder;
|
||||
var before = FilesOf(folder);
|
||||
|
||||
// This index still has the sequence in the folder the other sequence holds now: a proxy sent, a proxy pass and a
|
||||
// thumbnail pass write nothing there.
|
||||
Assert.Equal(ProxyStoreResult.Gone, await images.StoreProxyAsync(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 2), fx.Ct));
|
||||
foreach (var pass in new Func<Task<ImagePassResult>>[]
|
||||
{
|
||||
() => images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct),
|
||||
() => images.BuildThumbnailsAsync(fx.Archive, sequence, force: true, 0, (_, _) => ValueTask.CompletedTask, fx.Ct),
|
||||
})
|
||||
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), (await Assert.ThrowsAsync<InvalidOperationException>(pass)).Message);
|
||||
Assert.SequenceEqual(before, FilesOf(folder));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AProxyPassLetsAnotherProcessReorganizeBetweenItsBatches()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
Guid id = default;
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
var staged = fx.Stage(Start.AddSeconds(10 * i), 60 + i);
|
||||
id = (await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, null, null, "batches", staged.Path, $"IMG_{i + 1:0000}.JPG",
|
||||
staged.Size, staged.Sha256, null, null), fx.Ct)).SequenceId;
|
||||
}
|
||||
var sequence = (await fx.Db.Sequences.GetAsync(id, fx.Ct))!;
|
||||
var left = fx.Paths.Sequence(sequence.Folder).Folder;
|
||||
// The second photo is read as a PNG, through the decoders (JPEGs are decoded without them), and slowly.
|
||||
var sidecar = ManifestStore.ReadSequence(fx.Paths.Sequence(sequence.Folder).ManifestPath);
|
||||
ManifestStore.WriteSequence(fx.Paths.Sequence(sequence.Folder).ManifestPath, sidecar with
|
||||
{
|
||||
Frames = [.. sidecar.Frames.Select(f => f.I == 1 ? f with { Format = ImageFileFormat.Png } : f)],
|
||||
});
|
||||
var gate = new GateDecoder { Hold = Path.GetFileName(sidecar.Frames[1].File) };
|
||||
var (server, archive) = await fx.OtherWriterAsync();
|
||||
var plan = await server.PlanRenameAsync(archive.Id, [id], "moved/{date}", null, fx.Ct);
|
||||
var moved = fx.Paths.Sequence(plan.Steps.Single().ToFolder);
|
||||
|
||||
// A proxy pass here, one photo at a time, in batches of a quarter of its lease wait.
|
||||
var batch = TimeSpan.FromSeconds(TestTiming.Budget(2));
|
||||
var here = new ArchiveService(fx.Db, new ArchiveServiceOptions
|
||||
{
|
||||
Owner = "test",
|
||||
LeaseWait = batch * 4,
|
||||
Decoder = new ImageDecoder([gate]),
|
||||
Parallelism = () => 1,
|
||||
});
|
||||
var pass = Task.Run(() => here.Images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct));
|
||||
await Task.WhenAny(gate.Holding.Task, pass).WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
|
||||
if (pass.IsCompleted) Assert.Fail($"The pass ended before the held photo: {await pass}");
|
||||
var held = DateTime.UtcNow;
|
||||
|
||||
// Another process sharing the archive reorganizes the sequence: it holds the sequence, then waits for the thumbnail lease.
|
||||
var move = Task.Run(() => server.ApplyRenameAsync(plan, null, fx.Ct));
|
||||
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(30));
|
||||
while (LeaseFile.Holder(fx.Paths.LocksDirectory, $"seq-{id:N}")?.Owner != "other")
|
||||
{
|
||||
Assert.False(move.IsCompleted, "the Reorganize waits for the pass");
|
||||
Assert.True(DateTime.UtcNow < until, "the Reorganize holds the sequence");
|
||||
await Task.Delay(20, fx.Ct);
|
||||
}
|
||||
var rest = held + batch + TimeSpan.FromSeconds(0.5) - DateTime.UtcNow;
|
||||
if (rest > TimeSpan.Zero) await Task.Delay(rest, fx.Ct);
|
||||
gate.Release();
|
||||
|
||||
// The batch ends with that photo and lets the lease go: the Reorganize moves the folder before the pass ends, and the
|
||||
// pass, finding the folder gone from where this index has it, stops there.
|
||||
await move.WaitAsync(TimeSpan.FromSeconds(TestTiming.Budget(60)), fx.Ct);
|
||||
var stopped = await Assert.ThrowsAsync<InvalidOperationException>(() => pass);
|
||||
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), stopped.Message);
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
Assert.FileExists(moved.Proxy(0));
|
||||
Assert.FileExists(moved.Proxy(1));
|
||||
Assert.FileMissing(moved.Proxy(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AProxyLeftByARenumberedFrameIsAskedForAgain()
|
||||
{
|
||||
@@ -99,8 +243,8 @@ public sealed class ProxyTests(TestContext context)
|
||||
|
||||
// A client or render node sending one that small is refused; one of the policy's size (1920 px) is kept.
|
||||
var frame = frames[0] with { Width = 4032, Height = 3024 };
|
||||
Assert.Equal(ProxyStoreResult.TooSmall, images.StoreProxy(fx.Archive, sequence, frame, Proxy(frame.CapturedAt!.Value, 6, 160, 120)));
|
||||
Assert.Equal(ProxyStoreResult.Stored, images.StoreProxy(fx.Archive, sequence, frame, Proxy(frame.CapturedAt!.Value, 7, 1920, 1440)));
|
||||
Assert.Equal(ProxyStoreResult.TooSmall, await images.StoreProxyAsync(fx.Archive, sequence, frame, Proxy(frame.CapturedAt!.Value, 6, 160, 120), fx.Ct));
|
||||
Assert.Equal(ProxyStoreResult.Stored, await images.StoreProxyAsync(fx.Archive, sequence, frame, Proxy(frame.CapturedAt!.Value, 7, 1920, 1440), fx.Ct));
|
||||
var again = await images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.Equal((0, 1, 0, 1), (again.Built, again.Reused, again.Undecodable, again.Waiting));
|
||||
Assert.FileExists(folder.Proxy(0));
|
||||
@@ -114,7 +258,7 @@ public sealed class ProxyTests(TestContext context)
|
||||
var manifest = ManifestStore.ReadArchive(fx.Paths.ManifestPath);
|
||||
ManifestStore.WriteArchive(fx.Paths.ManifestPath, manifest with { ProxyPolicy = new ProxyPolicy { LongEdge = ProxyPolicy.Disabled } });
|
||||
|
||||
Assert.Equal(ProxyStoreResult.Disabled, fx.Service.Images.StoreProxy(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 4)));
|
||||
Assert.Equal(ProxyStoreResult.Disabled, await fx.Service.Images.StoreProxyAsync(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 4), fx.Ct));
|
||||
Assert.FileMissing(fx.Paths.Sequence(sequence.Folder).Proxy(0));
|
||||
}
|
||||
|
||||
@@ -170,7 +314,7 @@ public sealed class ProxyTests(TestContext context)
|
||||
|
||||
// A client makes one from the index's time: it is kept, and the next pass reuses it rather than making its own.
|
||||
var sent = Proxy(frame.CapturedAt!.Value, 1);
|
||||
Assert.Equal(ProxyStoreResult.Stored, images.StoreProxy(fx.Archive, sequence, frame, sent));
|
||||
Assert.Equal(ProxyStoreResult.Stored, await images.StoreProxyAsync(fx.Archive, sequence, frame, sent, fx.Ct));
|
||||
var again = await images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.Equal((0, 1), (again.Built, again.Reused));
|
||||
Assert.SequenceEqual(sent, await File.ReadAllBytesAsync(folder.Proxy(0), fx.Ct));
|
||||
@@ -264,7 +408,7 @@ public sealed class ProxyTests(TestContext context)
|
||||
await using var fx = await CreateAsync(context);
|
||||
var (sequence, frames) = await HeifSequenceAsync(fx);
|
||||
var images = fx.Service.Images;
|
||||
Assert.Equal(ProxyStoreResult.Stored, images.StoreProxy(fx.Archive, sequence, frames[1], Proxy(frames[1].CapturedAt!.Value, 1)));
|
||||
Assert.Equal(ProxyStoreResult.Stored, await images.StoreProxyAsync(fx.Archive, sequence, frames[1], Proxy(frames[1].CapturedAt!.Value, 1), fx.Ct));
|
||||
|
||||
// A pass resumed at frame 1 (paused, retried or restarted) finds that frame done, but frame 0 still waits: the
|
||||
// status must not tell a server's clients that nothing is wanted.
|
||||
@@ -272,7 +416,7 @@ public sealed class ProxyTests(TestContext context)
|
||||
Assert.Equal((0, 1, 0, 0), (resumed.Built, resumed.Reused, resumed.Undecodable, resumed.Waiting));
|
||||
Assert.False(await ProxiesBuiltAsync(fx, sequence), "frame 0 has no proxy");
|
||||
|
||||
Assert.Equal(ProxyStoreResult.Stored, images.StoreProxy(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 2)));
|
||||
Assert.Equal(ProxyStoreResult.Stored, await images.StoreProxyAsync(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 2), fx.Ct));
|
||||
await images.BuildProxiesAsync(fx.Archive, sequence, force: false, 1, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.True(await ProxiesBuiltAsync(fx, sequence), "every frame has its proxy");
|
||||
}
|
||||
@@ -290,7 +434,7 @@ public sealed class ProxyTests(TestContext context)
|
||||
{
|
||||
Frames = [.. sidecar.Frames.Select(f => f with { Tier = DecodeTier.EmbeddedPreview, Flags = f.Flags | FrameFlags.PreviewOnly, PreviewW = 160, PreviewH = 120 })],
|
||||
});
|
||||
Assert.Equal(ProxyStoreResult.Stored, images.StoreProxy(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 1)));
|
||||
Assert.Equal(ProxyStoreResult.Stored, await images.StoreProxyAsync(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 1), fx.Ct));
|
||||
|
||||
// Frame 0 now renders from its proxy, not from the thumbnail: it caps nothing. Its tier stays the original's.
|
||||
await images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
@@ -315,7 +459,7 @@ public sealed class ProxyTests(TestContext context)
|
||||
var (sequence, frames) = await HeifSequenceAsync(fx);
|
||||
var folder = fx.Paths.Sequence(sequence.Folder);
|
||||
var images = fx.Service.Images;
|
||||
Assert.Equal(ProxyStoreResult.Stored, images.StoreProxy(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 1, 640, 480)));
|
||||
Assert.Equal(ProxyStoreResult.Stored, await images.StoreProxyAsync(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 1, 640, 480), fx.Ct));
|
||||
Task<ImagePassResult> ThumbnailsAsync(bool force = false) =>
|
||||
images.BuildThumbnailsAsync(fx.Archive, sequence, force, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
(int, int) Entry()
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -455,6 +455,33 @@ public sealed class AnalysisJobTests(TestContext context)
|
||||
Assert.Contains("13", ProjectSettings.FromJson(await ProjectJsonAsync(fx, folder)).Timing.FrameRate.ReasonArgs!);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ADeepAnalysisWhoseFolderAnotherChronosMovedRecordsNothingAndCreatesNoFolder()
|
||||
{
|
||||
// One decode at a time, so the held one is the only photo being read while the folder moves.
|
||||
await using var fx = await ProcessingFixture.CreateAsync(context, o => o with { DeepAnalysis = o.DeepAnalysis with { MaxDegreeOfParallelism = 1 } });
|
||||
var sequence = await fx.AddAsync(Flickering(12));
|
||||
var left = fx.Folder(sequence).Folder;
|
||||
var (server, archive) = await fx.Archive.OtherWriterAsync();
|
||||
await fx.StartEngineAsync();
|
||||
|
||||
// A server sharing this desktop's archive reorganizes the sequence while the deep pass reads its photos.
|
||||
fx.Decoder.HoldFrame(5);
|
||||
var deep = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([sequence.Id]));
|
||||
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
|
||||
var plan = await server.PlanRenameAsync(archive.Id, [sequence.Id], "Moved/{date}", null, fx.Ct);
|
||||
await server.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
fx.Decoder.Hold = null;
|
||||
fx.Decoder.Release();
|
||||
var done = await fx.WaitForAsync(deep.Id, JobState.Done);
|
||||
|
||||
Assert.Contains(Loc.L("Advisor.Log.FramesChangedElsewhere", sequence.DisplayTitle), done.LogTail);
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
var moved = fx.Archive.Paths.Sequence(plan.Steps.Single().ToFolder);
|
||||
Assert.FileMissing(moved.AnalysisPath);
|
||||
Assert.False((await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.Status.HasFlag(SequenceStatus.AnalyzedDeep), "nothing is recorded");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ALightAnalysisOvertakenByAScanMarksNothingAnalysedAndRunsAgain()
|
||||
{
|
||||
|
||||
@@ -9,6 +9,7 @@ using Chronos.Core.Project;
|
||||
using Chronos.Core.Video;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Tests.Archiving;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Processing;
|
||||
@@ -126,6 +127,55 @@ public sealed class RenderJobTests(TestContext context)
|
||||
Assert.Empty(await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARenderOfAFolderAnotherIndexMovedWaitsForThisIndexsScan()
|
||||
{
|
||||
await using var fx = await ProcessingFixture.CreateAsync(context);
|
||||
var sequence = await fx.AddAsync(Scene());
|
||||
var left = fx.Folder(sequence).Folder;
|
||||
var (server, archive) = await fx.Archive.OtherWriterAsync();
|
||||
var plan = await server.PlanRenameAsync(archive.Id, [sequence.Id], "Moved/{date}", null, fx.Ct);
|
||||
await server.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
await fx.StartEngineAsync();
|
||||
|
||||
// A server sharing the archive moved the folder; this index has not scanned since. Nothing renders, nothing is flagged.
|
||||
var job = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg, 96, 64));
|
||||
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
|
||||
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), failed.Error);
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
Assert.Empty(await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
|
||||
Assert.True((await fx.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fx.Ct)).All(f => (f.Flags & (FrameFlags.Missing | FrameFlags.Undecodable)) == 0), "no frame flagged");
|
||||
|
||||
// Once this index's scan found it there, the render goes into its exports.
|
||||
await fx.Archive.ScanAsync();
|
||||
var again = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg, 96, 64));
|
||||
await fx.WaitForAsync(again.Id, JobState.Done);
|
||||
var moved = fx.Archive.Paths.Sequence(plan.Steps.Single().ToFolder);
|
||||
Assert.FileExists(Path.Combine(moved.Exports, "clip-MJPEG.avi"));
|
||||
Assert.False(Directory.Exists(left));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARenderNeverWritesIntoAnotherSequenceMovedIntoItsFolder()
|
||||
{
|
||||
await using var fx = await ProcessingFixture.CreateAsync(context);
|
||||
var sequence = await fx.AddAsync(Scene());
|
||||
var stranger = await fx.AddAsync(Scene(), "Other");
|
||||
var (server, archive) = await fx.Archive.OtherWriterAsync();
|
||||
await server.ApplyRenameAsync(await server.PlanRenameAsync(archive.Id, [sequence.Id], "Moved/{date}", null, fx.Ct), null, fx.Ct);
|
||||
await server.ApplyRenameAsync(await server.PlanRenameAsync(archive.Id, [stranger.Id], sequence.Folder, null, fx.Ct), null, fx.Ct);
|
||||
var folder = fx.Folder(sequence).Folder;
|
||||
var before = ArchiveFixture.FilesOf(folder);
|
||||
await fx.StartEngineAsync();
|
||||
|
||||
// A server sharing the archive moved the folder away and the other sequence into it; this index has not scanned since.
|
||||
var job = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg, 96, 64));
|
||||
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
|
||||
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), failed.Error);
|
||||
Assert.SequenceEqual(before, ArchiveFixture.FilesOf(folder), "the other sequence's files are untouched");
|
||||
Assert.Empty(await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFrameThatNoLongerDecodesIsReplacedByItsNeighbourAndLeftOutNextTime()
|
||||
{
|
||||
@@ -325,6 +375,50 @@ public sealed class RenderJobTests(TestContext context)
|
||||
Assert.Count(2, await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARenderResumedAfterItsFolderMovedNeverDeletesWhatAnotherSequenceBroughtIntoIt()
|
||||
{
|
||||
// The crashed attempt's checkpoint names the folder it chose the output in, or (written by an older version) does not.
|
||||
foreach (var named in new[] { true, false })
|
||||
{
|
||||
await using var fx = await ProcessingFixture.CreateAsync(context);
|
||||
var sequence = await fx.AddAsync(Scene());
|
||||
var stranger = await fx.AddAsync(Scene(), "Other");
|
||||
var output = Path.Combine(fx.Folder(sequence).Exports, "clip-MJPEG.avi");
|
||||
// The crashed attempt left its encoder's temporary file and a finished output it never recorded; the other
|
||||
// sequence has an export of that name, and a hidden file that looks like such a leftover.
|
||||
Directory.CreateDirectory(fx.Folder(sequence).Exports);
|
||||
await File.WriteAllBytesAsync(Path.Combine(fx.Folder(sequence).Exports, ".clip-MJPEG.avi.0badf00d.tmp"), new byte[100], fx.Ct);
|
||||
await File.WriteAllBytesAsync(output, new byte[100], fx.Ct);
|
||||
Directory.CreateDirectory(fx.Folder(stranger).Exports);
|
||||
await File.WriteAllBytesAsync(Path.Combine(fx.Folder(stranger).Exports, ".clip-MJPEG.avi.0ddba11.tmp"), new byte[50], fx.Ct);
|
||||
await File.WriteAllBytesAsync(Path.Combine(fx.Folder(stranger).Exports, "clip-MJPEG.avi"), Encoding.ASCII.GetBytes("RIFF theirs"), fx.Ct);
|
||||
|
||||
// Another index moves the folder away, the leftovers along, then the other sequence into the folder it left; this
|
||||
// index's scan finds both before the job resumes.
|
||||
var (server, archive) = await fx.Archive.OtherWriterAsync();
|
||||
var plan = await server.PlanRenameAsync(archive.Id, [sequence.Id], "Moved/{date}", null, fx.Ct);
|
||||
await server.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
await server.ApplyRenameAsync(await server.PlanRenameAsync(archive.Id, [stranger.Id], sequence.Folder, null, fx.Ct), null, fx.Ct);
|
||||
await fx.Archive.ScanAsync();
|
||||
var before = ArchiveFixture.FilesOf(fx.Folder(sequence).Folder);
|
||||
await fx.StartEngineAsync();
|
||||
|
||||
var job = await fx.Archive.EnqueueWithCheckpointAsync(fx.Engine, ProcessingJobs.Render(sequence, Mjpeg, 96, 64),
|
||||
new RenderCheckpoint([], 0, output, named ? sequence.Folder : null).ToJson());
|
||||
await fx.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
Assert.SequenceEqual(before, ArchiveFixture.FilesOf(fx.Folder(sequence).Folder), $"{named}: the other sequence's files are untouched");
|
||||
// Its leftovers are removed where the folder took them when the checkpoint says where it chose the output, and
|
||||
// stay otherwise: the render then takes another name.
|
||||
var moved = fx.Archive.Paths.Sequence(plan.Steps.Single().ToFolder).Exports;
|
||||
Assert.SequenceEqual(named ? ["clip-MJPEG.avi"] : [".clip-MJPEG.avi.0badf00d.tmp", "clip-MJPEG (2).avi", "clip-MJPEG.avi"], Entries(moved), named.ToString());
|
||||
var rendered = (await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct)).Single().OutputPath;
|
||||
Assert.Equal(plan.Steps.Single().ToFolder + (named ? "/exports/clip-MJPEG.avi" : "/exports/clip-MJPEG (2).avi"), rendered);
|
||||
Assert.Equal("RIFF", Encoding.ASCII.GetString((await File.ReadAllBytesAsync(fx.Archive.Paths.FromRelative(rendered), fx.Ct))[..4]));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ConcurrentRendersOfOnePresetKeepBothOutputs()
|
||||
{
|
||||
|
||||
@@ -361,6 +361,43 @@ public abstract class CatalogRepositoryTests(TestContext context) : RepositoryTe
|
||||
Assert.True((await Chronos.Data.Processing.SequenceFrames.ListAsync(db, sequence.Id, Ct)).All(f => (f.Flags, f.PreviewWidth, f.PreviewHeight) == (FrameFlags.None, 4, 3)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task FramesTakeTheNamesAReorganizeGaveTheirFiles()
|
||||
{
|
||||
var db = await OpenChronosAsync();
|
||||
var archive = TestData.Archive();
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
var sequence = TestData.Sequence(archive.Id) with { FramesVersion = 3 };
|
||||
var other = TestData.Sequence(archive.Id);
|
||||
await db.Sequences.UpsertAsync(sequence, Ct);
|
||||
await db.Sequences.UpsertAsync(other, Ct);
|
||||
// More frames than one batched PostgreSQL statement holds, and a frame of another sequence named in the same call.
|
||||
const int count = 1203;
|
||||
var frames = Enumerable.Range(0, count).Select(i => TestData.Frame(sequence.Id, i)).ToList();
|
||||
var foreign = TestData.Frame(other.Id, 0);
|
||||
await db.Frames.BulkInsertAsync([.. frames, foreign], Ct);
|
||||
|
||||
var renamed = frames.Take(count - 1).Select(f => new FrameFileName(f.Id, $"s/originals/{count - f.Index:00000}.cr3", $"{count - f.Index:00000}.cr3")).ToList();
|
||||
Assert.Equal(count - 1, await db.Frames.RenameFilesAsync(sequence.Id, [.. renamed, new FrameFileName(foreign.Id, "x/y.cr3", "y.cr3")], 3, 4, Ct));
|
||||
var read = new List<Frame>();
|
||||
for (var last = -1; ;)
|
||||
{
|
||||
var page = await db.Frames.ListBySequenceAsync(sequence.Id, last, 1000, Ct);
|
||||
read.AddRange(page);
|
||||
if (page.Count < 1000) break;
|
||||
last = page[^1].Index;
|
||||
}
|
||||
Assert.SequenceEqual(frames.Select(f => f.Id), read.Select(f => f.Id));
|
||||
Assert.SequenceEqual([.. renamed.Select(r => (r.RelativePath, r.FileName)), (frames[^1].RelativePath, frames[^1].FileName)],
|
||||
read.Select(f => (f.RelativePath, f.FileName)));
|
||||
Assert.Equal((foreign.RelativePath, foreign.FileName), (await db.Frames.GetAsync(foreign.Id, Ct)) is { } f2 ? (f2.RelativePath, f2.FileName) : default);
|
||||
Assert.Equal(4, (await db.Sequences.GetAsync(sequence.Id, Ct))!.FramesVersion);
|
||||
|
||||
// A row another writer moved past the version the renames started from keeps its own.
|
||||
await db.Frames.RenameFilesAsync(sequence.Id, [], 3, 9, Ct);
|
||||
Assert.Equal(4, (await db.Sequences.GetAsync(sequence.Id, Ct))!.FramesVersion);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RendersKeepTheSequenceCountInStep()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Data.Tests.Infrastructure;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Repositories;
|
||||
|
||||
/// <summary>
|
||||
/// The stamp of what a Reorganize plans from in an archive's index (<see cref="SequenceRepository.GetStampAsync"/>) on both
|
||||
/// dialects: the server makes a kept Reorganize plan again once it is another one, and only then (owner review 2, R7).
|
||||
/// </summary>
|
||||
public abstract class SequenceStampTests(TestContext context) : RepositoryTest(context)
|
||||
{
|
||||
[Test]
|
||||
public async Task TheStampFollowsWhatAReorganizePlansFromAndNothingElse()
|
||||
{
|
||||
var db = await OpenChronosAsync();
|
||||
var archive = TestData.Archive();
|
||||
var other = TestData.Archive("Other");
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
await db.Archives.UpsertAsync(other, Ct);
|
||||
var roof = TestData.Sequence(archive.Id, new DateTime(2026, 9, 28, 18, 0, 0), "Roof");
|
||||
var inner = TestData.Sequence(archive.Id, null, "Inner") with { Folder = roof.Folder + "/inner" };
|
||||
var ridge = TestData.Sequence(archive.Id, new DateTime(2026, 9, 29, 7, 0, 0), "Ridge");
|
||||
IReadOnlyList<Guid> planned = [roof.Id];
|
||||
var empty = await db.Sequences.GetStampAsync(archive.Id, planned, Ct);
|
||||
foreach (var sequence in new[] { roof, inner, ridge }) await db.Sequences.UpsertAsync(sequence, Ct);
|
||||
var stamp = await db.Sequences.GetStampAsync(archive.Id, planned, Ct);
|
||||
Assert.NotEqual(empty, stamp);
|
||||
Assert.Equal(stamp, await db.Sequences.GetStampAsync(archive.Id, planned, Ct));
|
||||
Assert.NotEqual(stamp, await db.Sequences.GetStampAsync(archive.Id, null, Ct));
|
||||
|
||||
// What the plan does not read: another archive, and the writes of every upload, verify, tag or status change elsewhere.
|
||||
await db.Sequences.UpsertAsync(TestData.Sequence(other.Id), Ct);
|
||||
await VerifyAsync(db, await PhotoAsync(db, ridge, 0, hashed: false));
|
||||
await VerifyAsync(db, await PhotoAsync(db, inner, 0, hashed: false));
|
||||
Assert.Equal(SequenceEditOutcome.Updated, (await db.Sequences.EditAsync(ridge.Id, new SequenceEdit { Title = "Ridge at dawn", Notes = "cold" }, null, Ct)).Outcome);
|
||||
foreach (var id in new[] { roof.Id, ridge.Id })
|
||||
{
|
||||
Assert.True(await db.Sequences.SetTagsAsync(id, ["sky"], Ct));
|
||||
Assert.True(await db.Sequences.UpdateStatusAsync(id, SequenceStatus.ProxiesBuilt, SequenceStatus.None, Ct));
|
||||
Assert.True(await db.Sequences.RecordVerifiedAsync(id, SequenceStatus.None, SequenceStatus.None, TestData.Now, Ct));
|
||||
}
|
||||
Assert.Equal(stamp, await db.Sequences.GetStampAsync(archive.Id, planned, Ct));
|
||||
|
||||
// What it reads gives one never seen before: the sequences planned, the titles inside their folders, every folder.
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal) { empty, stamp };
|
||||
async Task ChangedAsync(string what) => Assert.True(seen.Add(await db.Sequences.GetStampAsync(archive.Id, planned, Ct)), what);
|
||||
Assert.Equal(SequenceEditOutcome.Updated, (await db.Sequences.EditAsync(roof.Id, new SequenceEdit { Title = "Roof at noon" }, null, Ct)).Outcome);
|
||||
await ChangedAsync("title");
|
||||
var scanned = await PhotoAsync(db, roof, 0, hashed: false);
|
||||
await ChangedAsync("photos");
|
||||
await VerifyAsync(db, scanned);
|
||||
await ChangedAsync("photos hashed by a verify, which a file template renames");
|
||||
Assert.Equal(SequenceEditOutcome.Updated, (await db.Sequences.EditAsync(inner.Id, new SequenceEdit { Title = "Inner court" }, null, Ct)).Outcome);
|
||||
await ChangedAsync("title of a sequence a moving folder would carry");
|
||||
Assert.True(await db.Sequences.RelocateAsync(ridge.Id, "2026/ridge", null, Ct));
|
||||
await ChangedAsync("folder of a sequence not planned");
|
||||
Assert.True(await db.Sequences.RelocateAsync(roof.Id, "2026/moved", null, Ct));
|
||||
await ChangedAsync("folder");
|
||||
var added = TestData.Sequence(archive.Id);
|
||||
await db.Sequences.UpsertAsync(added, Ct);
|
||||
await ChangedAsync("a sequence added");
|
||||
Assert.True(await db.Sequences.DeleteAsync(added.Id, Ct));
|
||||
Assert.Contains(await db.Sequences.GetStampAsync(archive.Id, planned, Ct), seen);
|
||||
|
||||
// With every sequence planned, a photo anywhere changes the plan read, and so does a verify that hashes one; a verify
|
||||
// that hashes none still does not.
|
||||
var all = await db.Sequences.GetStampAsync(archive.Id, null, Ct);
|
||||
Assert.True(await db.Sequences.RecordVerifiedAsync(ridge.Id, SequenceStatus.None, SequenceStatus.None, TestData.Now.AddDays(1), Ct));
|
||||
Assert.Equal(all, await db.Sequences.GetStampAsync(archive.Id, null, Ct));
|
||||
var photo = await PhotoAsync(db, ridge, 1, hashed: false);
|
||||
var uploaded = await db.Sequences.GetStampAsync(archive.Id, null, Ct);
|
||||
Assert.NotEqual(all, uploaded);
|
||||
await VerifyAsync(db, photo);
|
||||
var verified = await db.Sequences.GetStampAsync(archive.Id, null, Ct);
|
||||
Assert.False(verified == all || verified == uploaded, "a photo hashed");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A photo indexed into a sequence, as an upload does, or without its hash, as a scan does: the frame, then the row's
|
||||
/// counts and frames version.
|
||||
/// </summary>
|
||||
private async Task<Frame> PhotoAsync(ChronosDatabase db, Sequence sequence, int index, bool hashed = true)
|
||||
{
|
||||
var frame = TestData.Frame(sequence.Id, index);
|
||||
frame = frame with { RelativePath = $"{sequence.Folder}/originals/{frame.FileName}", Sha256 = hashed ? frame.Sha256 : null };
|
||||
await db.Frames.BulkInsertAsync([frame], Ct);
|
||||
Assert.NotNull(await db.Sequences.RefreshStatsAsync(sequence.Id, Ct));
|
||||
return frame;
|
||||
}
|
||||
|
||||
/// <summary>What a verify writes once it hashed a photo never hashed: the hash, then the sequence's verify time, and not another frames version.</summary>
|
||||
private async Task VerifyAsync(ChronosDatabase db, Frame frame)
|
||||
{
|
||||
var version = (await db.Sequences.GetAsync(frame.SequenceId, Ct))!.FramesVersion;
|
||||
var sha256 = TestData.Frame(frame.SequenceId, frame.Index).Sha256;
|
||||
Assert.Equal(1, await db.Frames.UpdateIntegrityAsync([new FrameIntegrity(frame.Id, FrameFlags.None, sha256)], Ct));
|
||||
Assert.True(await db.Sequences.RecordVerifiedAsync(frame.SequenceId, SequenceStatus.Verified, SequenceStatus.None, TestData.Now, Ct));
|
||||
Assert.Equal(version, (await db.Sequences.GetAsync(frame.SequenceId, Ct))!.FramesVersion);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SqliteSequenceStampTests(TestContext context) : SequenceStampTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteMemory;
|
||||
}
|
||||
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PostgresSequenceStampTests(TestContext context) : SequenceStampTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
@@ -103,22 +103,38 @@ internal sealed class FakeSyncRemote : ISyncRemote
|
||||
}
|
||||
}
|
||||
|
||||
public Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken)
|
||||
/// <summary>Runs once, before the next manifest is answered: the archive on this PC changing while the sync compares.</summary>
|
||||
public Func<Task>? OnceBeforeManifest { get; set; }
|
||||
|
||||
public async Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
if (OnceBeforeManifest is { } before)
|
||||
{
|
||||
OnceBeforeManifest = null;
|
||||
await before();
|
||||
}
|
||||
lock (_gate)
|
||||
{
|
||||
ManifestCalls++;
|
||||
if (Refused.Contains(id)) throw new ChronosApiException(HttpStatusCode.Forbidden, new ApiError("forbidden", "refused"));
|
||||
return Task.FromResult(Find(id).Manifest(SentProxies.ContainsKey));
|
||||
return Find(id).Manifest(SentProxies.ContainsKey);
|
||||
}
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken)
|
||||
/// <summary>Runs once, before the next frame listing is answered (frame positions translated against the server's frames).</summary>
|
||||
public Func<Task>? OnceBeforeFrames { get; set; }
|
||||
|
||||
public async Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (OnceBeforeFrames is { } before)
|
||||
{
|
||||
OnceBeforeFrames = null;
|
||||
await before();
|
||||
}
|
||||
lock (_gate)
|
||||
{
|
||||
var sequence = Find(sequenceId);
|
||||
return Task.FromResult<IReadOnlyList<FrameDto>>([.. sequence.Frames.Select(sequence.FrameDto)]);
|
||||
return [.. sequence.Frames.Select(sequence.FrameDto)];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Archiving;
|
||||
@@ -97,6 +98,35 @@ public sealed class SyncServiceTests(TestContext context)
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SettingsTakenWhileAReorganizeMovesTheFolderGoWhereTheSequenceIsNow()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Harbour", photos);
|
||||
var remote = f.Remote.Add("Harbour", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
var left = f.Archive.Paths.Sequence((await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Folder).Folder;
|
||||
|
||||
// The server's edit is taken after a Reorganize moved the folder of the copy the comparison had read.
|
||||
f.Remote.EditSettings(remote.Id, SyncFixture.Window33);
|
||||
f.Remote.OnceBeforeManifest = async () =>
|
||||
{
|
||||
var plan = await f.Archive.Service.PlanRenameAsync(f.Archive.Archive.Id, [local.Id], "moved/{title}", null, f.Ct);
|
||||
await f.Archive.Service.ApplyRenameAsync(plan, null, f.Ct);
|
||||
};
|
||||
await f.RefreshAsync();
|
||||
Assert.Null(f.Remote.OnceBeforeManifest, "the folder moved during the comparison");
|
||||
|
||||
var taken = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
|
||||
Assert.Equal("moved/Harbour", taken.Folder);
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, taken.SettingsJson), "the server's edit reached this PC");
|
||||
var project = await File.ReadAllTextAsync(f.Archive.Paths.Sequence(taken.Folder).ProjectPath, f.Ct);
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, project), "project.json in the moved folder follows the index");
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PositionsSentToTheServerNameItsFramesAndWaitForPhotosItLacks()
|
||||
{
|
||||
@@ -403,6 +433,144 @@ public sealed class SyncServiceTests(TestContext context)
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Holy grail")).Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SaveBothWhileAReorganizeMovesTheFolderKeepsTheCopyWhereTheSequenceIsNow()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var (local, remote) = await ConflictAsync(f);
|
||||
var left = f.Archive.Paths.Sequence(local.Folder).Folder;
|
||||
|
||||
// A Reorganize moves the folder while the server's version is read.
|
||||
f.Remote.OnceBeforeManifest = async () =>
|
||||
{
|
||||
var plan = await f.Archive.Service.PlanRenameAsync(f.Archive.Archive.Id, [local.Id], "moved/{title}", null, f.Ct);
|
||||
await f.Archive.Service.ApplyRenameAsync(plan, null, f.Ct);
|
||||
};
|
||||
var copy = await f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.SaveBoth, f.Ct);
|
||||
Assert.Null(f.Remote.OnceBeforeManifest, "the folder moved during the resolution");
|
||||
|
||||
var taken = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
|
||||
Assert.Equal("moved/Holy grail", taken.Folder);
|
||||
Assert.Equal(copy, Assert.Contains(Directory.GetFiles(f.Archive.Paths.Sequence(taken.Folder).MetaDirectory, "project.this-pc-*.json"), _ => true));
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, await File.ReadAllTextAsync(copy!, f.Ct)), "this PC's version is kept");
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, taken.SettingsJson));
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SaveBothThatCannotKeepThisPcsVersionTakesNothing()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
// The server holds a photo this PC does not have yet, and its settings name a frame: taking them reads the server's
|
||||
// frames, after this PC's copy was kept and before the server's version is written.
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Holy grail", photos[..2]);
|
||||
var remote = f.Remote.Add("Holy grail", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
local = await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41);
|
||||
var theirs = """{"heroFrame":1,"exposure":{"deflickerWindow":{"isAuto":false,"manual":33}}}""";
|
||||
f.Remote.EditSettings(remote.Id, theirs);
|
||||
await f.RefreshAsync();
|
||||
Assert.NotNull((await f.EntryAsync("Holy grail")).Link!.ConflictRemote);
|
||||
var left = f.Archive.Paths.Sequence(local.Folder).Folder;
|
||||
|
||||
// Another index moves the folder while the server's version is read, so this PC's version cannot be kept there; this
|
||||
// index's scan finds the folder before the server's version would be written.
|
||||
var (other, archive) = await f.Archive.OtherWriterAsync();
|
||||
string? moved = null;
|
||||
f.Remote.OnceBeforeManifest = async () =>
|
||||
{
|
||||
var plan = await other.PlanRenameAsync(archive.Id, [local.Id], "moved/{title}", null, f.Ct);
|
||||
await other.ApplyRenameAsync(plan, null, f.Ct);
|
||||
moved = plan.Steps.Single().ToFolder;
|
||||
};
|
||||
f.Remote.OnceBeforeFrames = () => f.Archive.ScanAsync();
|
||||
var refused = await Assert.ThrowsAsync<SyncConflictChangedException>(() => f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.SaveBoth, f.Ct));
|
||||
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), refused.Message, "the user hears to try again after the next scan");
|
||||
// The server's frames were not read for a version that is not taken: the scan comes now.
|
||||
f.Remote.OnceBeforeFrames = null;
|
||||
await f.Archive.ScanAsync();
|
||||
|
||||
var kept = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
|
||||
Assert.Equal(moved, kept.Folder, "the scan found the folder");
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, kept.SettingsJson), "this PC's version is not replaced without its copy");
|
||||
var meta = f.Archive.Paths.Sequence(kept.Folder).MetaDirectory;
|
||||
Assert.Empty(Directory.GetFiles(meta, SyncService.SavedCopyPattern));
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
Assert.NotNull((await f.EntryAsync("Holy grail")).Link!.ConflictRemote, "still a conflict");
|
||||
|
||||
// Asked again where the sequence is now, both versions are kept.
|
||||
var copy = await f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.SaveBoth, f.Ct);
|
||||
Assert.Equal(copy, Assert.Contains(Directory.GetFiles(meta, SyncService.SavedCopyPattern), _ => true));
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, await File.ReadAllTextAsync(copy!, f.Ct)), "this PC's version is kept");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TakeServerWhereAnotherIndexMovedTheFolderWritesNothing()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var (local, remote) = await ConflictAsync(f);
|
||||
var left = f.Archive.Paths.Sequence(local.Folder).Folder;
|
||||
|
||||
// Another index moves the folder while the server's version is read; this index has not scanned it since.
|
||||
var (other, archive) = await f.Archive.OtherWriterAsync();
|
||||
f.Remote.OnceBeforeManifest = async () =>
|
||||
{
|
||||
var plan = await other.PlanRenameAsync(archive.Id, [local.Id], "moved/{title}", null, f.Ct);
|
||||
await other.ApplyRenameAsync(plan, null, f.Ct);
|
||||
};
|
||||
var refused = await Assert.ThrowsAsync<SyncConflictChangedException>(() => f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.TakeServer, f.Ct));
|
||||
Assert.Null(f.Remote.OnceBeforeManifest, "the folder moved during the resolution");
|
||||
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), refused.Message, "the user hears to try again after the next scan");
|
||||
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson), "nothing applied");
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, await File.ReadAllTextAsync(f.Archive.Paths.Sequence("moved/Holy grail").ProjectPath, f.Ct)),
|
||||
"the moved project is this PC's version");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TakeServerAndSaveBothWriteNothingIntoAnotherSequenceMovedIntoTheFolder()
|
||||
{
|
||||
const string strangers = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":7}}}""";
|
||||
foreach (var resolution in new[] { SyncResolution.TakeServer, SyncResolution.SaveBoth })
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var (local, remote) = await ConflictAsync(f);
|
||||
var stranger = await f.LocalAsync("Stranger", f.NewPhotos(2), strangers);
|
||||
var folder = f.Archive.Paths.Sequence(local.Folder);
|
||||
|
||||
// Another index moves the folder away while the server's version is read, then another sequence (first parked
|
||||
// elsewhere: its folder is the same name with a number) into the folder it left; this index has scanned neither.
|
||||
var (other, archive) = await f.Archive.OtherWriterAsync();
|
||||
List<string>? before = null;
|
||||
f.Remote.OnceBeforeManifest = async () =>
|
||||
{
|
||||
foreach (var (id, template) in new[] { (local.Id, "moved/{title}"), (stranger.Id, "parked/{title}"), (stranger.Id, local.Folder) })
|
||||
await other.ApplyRenameAsync(await other.PlanRenameAsync(archive.Id, [id], template, null, f.Ct), null, f.Ct);
|
||||
before = ArchiveFixture.FilesOf(folder.Folder);
|
||||
};
|
||||
var refused = await Assert.ThrowsAsync<SyncConflictChangedException>(() => f.Sync.ResolveAsync(f.Remote, remote.Id, resolution, f.Ct));
|
||||
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), refused.Message, $"{resolution}: the user hears to try again after the next scan");
|
||||
|
||||
// Neither version went into the other sequence's folder, nor replaced this PC's where the sequence is.
|
||||
Assert.Equal(stranger.Id, SequenceTrash.SidecarId(folder.ManifestPath), "the other sequence holds the folder");
|
||||
Assert.SequenceEqual(before!, ArchiveFixture.FilesOf(folder.Folder), $"{resolution}: the other sequence's files are untouched");
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson), "nothing applied");
|
||||
var moved = f.Archive.Paths.Sequence("moved/Holy grail");
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, await File.ReadAllTextAsync(moved.ProjectPath, f.Ct)), "the moved project is this PC's version");
|
||||
Assert.Empty(Directory.GetFiles(moved.MetaDirectory, SyncService.SavedCopyPattern));
|
||||
|
||||
// Chosen again once this index's scan found both, it is done where the sequence is now.
|
||||
await f.Archive.ScanAsync();
|
||||
var copy = await f.Sync.ResolveAsync(f.Remote, remote.Id, resolution, f.Ct);
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, await File.ReadAllTextAsync(moved.ProjectPath, f.Ct)), resolution.ToString());
|
||||
Assert.Equal(resolution == SyncResolution.SaveBoth, copy is not null && Path.GetDirectoryName(copy) == moved.MetaDirectory);
|
||||
Assert.True(SyncRules.SameSettings(strangers, await File.ReadAllTextAsync(folder.ProjectPath, f.Ct)), "the other sequence keeps its own");
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task KeepMineRefusesWhenTheServerChangedAfterTheConflictWasShown()
|
||||
{
|
||||
@@ -441,7 +609,8 @@ public sealed class SyncServiceTests(TestContext context)
|
||||
var later = SyncFixture.Window41.Replace("41", "45", StringComparison.Ordinal);
|
||||
await f.EditLocalSettingsAsync(local.Id, later);
|
||||
|
||||
await Assert.ThrowsAsync<SyncConflictChangedException>(() => f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.TakeServer, f.Ct));
|
||||
var refused = await Assert.ThrowsAsync<SyncConflictChangedException>(() => f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.TakeServer, f.Ct));
|
||||
Assert.Equal(Loc.L("Errors.Sync.ChangedAgain"), refused.Message);
|
||||
|
||||
Assert.True(SyncRules.SameSettings(later, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson), "this PC's later edit is kept");
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, remote.SettingsJson));
|
||||
|
||||
@@ -6,6 +6,7 @@ using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Render;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Tests.Archiving;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Testing;
|
||||
|
||||
@@ -384,6 +385,54 @@ public sealed class SyncTransferTests(TestContext context)
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnOriginalIsRestoredOnlyWhereTheSequenceIsNow()
|
||||
{
|
||||
// The folder the sequence left holds another sequence now, or nothing.
|
||||
foreach (var taken in new[] { true, false })
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Harbour", photos);
|
||||
var stranger = taken ? await f.LocalAsync("Stranger", f.NewPhotos(2)) : null;
|
||||
var lost = (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct))[1];
|
||||
File.Delete(f.Archive.Paths.FromRelative(lost.RelativePath));
|
||||
await f.Archive.Service.Verifier.VerifyAsync(f.Archive.Archive, [local.Id], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: f.Ct);
|
||||
var remote = f.Remote.Add("Harbour", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
var engine = await f.StartEngineAsync();
|
||||
|
||||
// Another index moves the folder away, then the other sequence (first parked elsewhere: its folder is the same
|
||||
// name with a number) into the folder it left; this index has scanned neither.
|
||||
var folder = f.Archive.Paths.Sequence(local.Folder).Folder;
|
||||
var (other, archive) = await f.Archive.OtherWriterAsync();
|
||||
var moves = stranger is null ? [(local.Id, "moved/{title}")] : new[] { (local.Id, "moved/{title}"), (stranger.Id, "parked/{title}"), (stranger.Id, local.Folder) };
|
||||
foreach (var (id, template) in moves)
|
||||
await other.ApplyRenameAsync(await other.PlanRenameAsync(archive.Id, [id], template, null, f.Ct), null, f.Ct);
|
||||
var before = taken ? ArchiveFixture.FilesOf(folder) : null;
|
||||
|
||||
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Originals, null);
|
||||
var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed);
|
||||
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), failed.Error, taken.ToString());
|
||||
if (taken) Assert.SequenceEqual(before!, ArchiveFixture.FilesOf(folder), "the other sequence's files are untouched");
|
||||
else Assert.False(Directory.Exists(folder), "the folder it left is not created again");
|
||||
|
||||
// Once this index's scan found it there, the original goes back into the folder the sequence is in now.
|
||||
await f.Archive.ScanAsync();
|
||||
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Originals, null);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
var moved = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Folder;
|
||||
Assert.Equal("moved/Harbour", moved);
|
||||
var restored = (await f.Db.Frames.GetAsync(lost.Id, f.Ct))!;
|
||||
Assert.Equal(moved + lost.RelativePath[local.Folder.Length..], restored.RelativePath);
|
||||
Assert.Equal(lost.Sha256, Sha(await File.ReadAllBytesAsync(f.Archive.Paths.FromRelative(restored.RelativePath), f.Ct)));
|
||||
Assert.True((await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).All(fr => (fr.Flags & FrameFlags.Missing) == 0), "nothing missing");
|
||||
if (taken) Assert.SequenceEqual(before!, ArchiveFixture.FilesOf(folder), "the other sequence's files are still untouched");
|
||||
else Assert.False(Directory.Exists(folder));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OriginalsTheServerHasNotHashedAreDownloadedAndHashedHere()
|
||||
{
|
||||
@@ -600,6 +649,55 @@ public sealed class SyncTransferTests(TestContext context)
|
||||
Assert.Equal(0, (await f.EntryAsync("Star trails")).Link!.ExportsToGet);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheServersRendersGoWhereTheSequenceIsNow()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Star trails", photos);
|
||||
var remote = f.Remote.Add("Star trails", photos);
|
||||
var first = new FakeRender(Guid.CreateVersion7(), "Star trails 4K.mp4", "4K HEVC", [.. Enumerable.Range(0, 3000).Select(i => (byte)i)]);
|
||||
remote.Renders.Add(first);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
var engine = await f.StartEngineAsync();
|
||||
var left = f.Archive.Paths.Sequence(local.Folder).Folder;
|
||||
|
||||
// A Reorganize here moves the folder while the server's renders are listed: the render goes where the sequence is.
|
||||
string? moved = null;
|
||||
f.Remote.OnceBeforeManifest = async () =>
|
||||
{
|
||||
var plan = await f.Archive.Service.PlanRenameAsync(f.Archive.Archive.Id, [local.Id], "moved/{title}", null, f.Ct);
|
||||
await f.Archive.Service.ApplyRenameAsync(plan, null, f.Ct);
|
||||
moved = plan.Steps.Single().ToFolder;
|
||||
};
|
||||
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Star trails", SyncDownloadMode.Exports, null);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
Assert.Equal($"{moved}/exports/Star trails 4K.mp4", (await f.Db.Renders.GetAsync(first.Id, f.Ct))!.OutputPath);
|
||||
Assert.FileExists(f.Archive.Paths.FromRelative($"{moved}/exports/Star trails 4K.mp4"));
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
|
||||
// Another index moves it: nothing is filed until this index's scan finds it there.
|
||||
var second = new FakeRender(Guid.CreateVersion7(), "Star trails 1080p.mp4", "1080p", [.. Enumerable.Range(0, 2000).Select(i => (byte)(i * 3))]);
|
||||
remote.Renders.Add(second);
|
||||
remote.UpdatedAt = DateTimeOffset.UtcNow.AddSeconds(1);
|
||||
var (other, archive) = await f.Archive.OtherWriterAsync();
|
||||
var away = await other.PlanRenameAsync(archive.Id, [local.Id], "elsewhere/{title}", null, f.Ct);
|
||||
await other.ApplyRenameAsync(away, null, f.Ct);
|
||||
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Star trails", SyncDownloadMode.Exports, null);
|
||||
var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed);
|
||||
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), failed.Error);
|
||||
Assert.False(Directory.Exists(f.Archive.Paths.Sequence(moved!).Folder), "the folder it left is not created again");
|
||||
Assert.Null(await f.Db.Renders.GetAsync(second.Id, f.Ct));
|
||||
|
||||
await f.Archive.ScanAsync();
|
||||
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Star trails", SyncDownloadMode.Exports, null);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
var fetched = (await f.Db.Renders.GetAsync(second.Id, f.Ct))!;
|
||||
Assert.Equal("elsewhere/Star trails/exports/Star trails 1080p.mp4", fetched.OutputPath);
|
||||
Assert.SequenceEqual(second.Bytes, await File.ReadAllBytesAsync(f.Archive.Paths.FromRelative(fetched.OutputPath), f.Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RendersMadeHereAreSentOnRequestAndAGoneFileIsReported()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user