feat(copies): matches between this PC and the server, Integrate and merge (owner review 6, v1.2.0) (#74)
CI / Build and test (push) Successful in 13m44s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 16s
Release / Build, test and publish (push) Successful in 26m34s
CI / PostgreSQL 16 integration (push) Failing after 17m36s
CI / PostgreSQL 17 integration (push) Failing after 15m36s
CI / Docker image (push) Successful in 1m12s
Release / Server image (push) Failing after 15s

The same time-lapse on a server and on this PC under different ids, or twice on this PC, is recognised,
compared and settled as the owner asked in owner review 6.

Matches are found after each sync refresh, through the server's new photo lookup, and after the jobs that
change photos. The default is to ask every time. Server › Matches offers:
- Keep apart, which is remembered;
- Link only and Unlink;
- the Compare dialog: photos, details line by line, projects and the plan.

Integrate completes both sides. Photos default to Union, projects are copied across, and a losing version
goes to the trash only after a hash check. Afterwards new photos move by themselves, and deletions wait for
the user.

A merge of two local sequences verifies every photo before the other sequence goes to its archive's trash.
Upload all local skips suspected matches and flags them.

Migration 0012 adds the found_copies and copy_probes tables. Jobs 25 (Integrate) and 26 (MergeSequences) are
new, and so are the server capabilities photo-lookup and upload-into.

Refs #73

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 #74.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-18 15:20:29 +01:00
1 parent 43719bb5c5
commit f33bcac32e
586 files changed
+41546 -280

No files matched your search

@@ -0,0 +1,81 @@
using System.Reflection;
using Chronos.App.Infrastructure;
using Chronos.App.Library;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Copies;
using Chronos.Testing;
namespace Chronos.App.Tests.Library;
/// <summary>Two versions… (owner Q3, #73): a drop whose dry run cannot go says why and asks nothing.</summary>
[Serial]
public sealed class VersionsDialogTests
{
private static readonly Sequence Comet = new()
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.CreateVersion7(),
Title = "Comet",
Folder = "2026/comet",
};
[Test]
public async Task ABlockedDropSaysWhyAndNeverAsksOrDrops()
{
foreach (var (block, expected) in new[]
{
(FrameDeleteBlock.Offline, Loc.L("Errors.Copies.TrashBlocked", "IMG_0002.JPG", Loc.L("Archive.Delete.Reason.Offline"))),
(FrameDeleteBlock.Busy, Loc.L("Errors.Copies.TrashBlocked", "IMG_0002.JPG", Loc.L("Archive.Delete.Reason.Busy"))),
(FrameDeleteBlock.FramesChanged, Loc.L("Archive.Convert.Blocked.FramesChanged")),
})
{
var engine = FakeEngine.Create(new OwnVersionDropPlan(new FrameDeletePlan(Comet, [], 0, [block]), Guid.NewGuid(), "IMG_0003.JPG", "b", []));
var asked = 0;
var dialog = new VersionsDialogViewModel((ICopyEngine)engine, Comet.Id, Comet.DisplayTitle, _ =>
{
asked++;
return true;
}, _ => { });
var row = new VersionRow(dialog, new PhotoVersions(Guid.NewGuid(), "IMG_0002.JPG", "a", Guid.NewGuid(), "IMG_0003.JPG", "b"), Guid.NewGuid(), "IMG_0002.JPG", 10, "IMG_0003.JPG", inMain: true);
await dialog.DropAsync(row);
Assert.Equal(0, asked);
Assert.Equal(0, ((FakeEngine)engine).Dropped);
Assert.Equal(expected, dialog.ErrorText);
Assert.True(row.InMain);
}
}
/// <summary>An <see cref="ICopyEngine"/> that plans <see cref="Plan"/> for every drop and counts the drops applied.</summary>
public class FakeEngine : DispatchProxy
{
internal OwnVersionDropPlan? Plan { get; set; }
internal int Dropped { get; private set; }
internal static object Create(OwnVersionDropPlan plan)
{
var proxy = Create<ICopyEngine, FakeEngine>();
((FakeEngine)(object)proxy).Plan = plan;
return proxy;
}
protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) => targetMethod?.Name switch
{
nameof(ICopyEngine.PlanDropOwnVersionAsync) => Task.FromResult(Plan!),
nameof(ICopyEngine.DropOwnVersionAsync) => Drop(),
nameof(ICopyEngine.VersionsAsync) => Task.FromResult<IReadOnlyList<PhotoVersions>>([]),
nameof(IDisposable.Dispose) => null,
_ => throw new NotSupportedException(targetMethod?.Name),
};
private Task<int> Drop()
{
Dropped++;
return Task.FromResult(1);
}
}
}
@@ -0,0 +1,619 @@
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Media;
using Chronos.App.DesignTime;
using Chronos.App.Infrastructure;
using Chronos.App.Library;
using Chronos.App.Sections;
using Chronos.App.Server;
using Chronos.App.Server.Copies;
using Chronos.App.Settings;
using Chronos.App.Shell;
using Chronos.App.Tests.Windows;
using Chronos.Core.Localization;
using Chronos.Data.Copies;
using Chronos.Data.Sync;
using Chronos.Testing;
using Chronos.Ui.Controls;
namespace Chronos.App.Tests.Server;
/// <summary>
/// Server › Matches on the capture sample pairs (owner review 6, #73): the list and its chip, the Compare dialog in the
/// window, its plan and blocks, the confirmations, the Library's match cards and the Settings rows.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class CopyScreenSmokeTests
{
[Test]
public Task TheMatchesListOrdersThePairsAndEveryActionSaysWhatItDoes() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var table = shell.Server.Sync;
var list = table.Copies;
await CopyScenes.ShowAsync(shell, "server-copies");
Assert.True(table.IsMatches);
Assert.True(table.ShowCopyList, "the Matches list replaces the sync table");
Assert.GreaterOrEqual(list.Count, 5);
Assert.Equal(list.Count, table.Chips.Single(c => c.Filter == SyncFilter.FoundCopies).Count);
Assert.True(list.AttentionCount > 0);
// Pairs that ask for a choice come first.
Assert.True(list.Rows[0].IsConflict);
Assert.True(list.Rows.SkipWhile(r => r.IsConflict).All(r => !r.IsConflict), "attention first, then the rest");
foreach (var row in list.Rows)
{
Assert.False(string.IsNullOrWhiteSpace(row.StateToolTip), $"{row.Title}: the state has a tooltip");
foreach (var action in row.Actions)
{
Assert.False(string.IsNullOrWhiteSpace(action.ToolTip), $"{row.Title}: {action.Text} has a tooltip");
Assert.LessOrEqual(action.Text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length, 3, $"\"{action.Text}\" is at most three words");
}
}
var lighthouse = list.Rows.Single(r => r.Title == CopyScenes.Lighthouse);
Assert.SequenceEqual([CopyAction.Compare, CopyAction.Integrate, CopyAction.KeepApart], lighthouse.Actions.Select(a => a.Action));
Assert.SequenceEqual([CopyAction.Compare, CopyAction.Merge, CopyAction.KeepApart],
list.Rows.Single(r => r.Title == CopyScenes.Alps).Actions.Select(a => a.Action));
await app.ExpectAsync<ServerView>("server-copies");
// The search narrows the pairs, by either title.
table.SearchText = "Alps";
Assert.Count(1, list.Rows);
table.SearchText = string.Empty;
// The sync table marks the sequence of an unanswered pair and offers Compare… first.
table.ShowFilter(SyncFilter.All);
var marked = table.Rows.First(r => r.Title == CopyScenes.Lighthouse);
Assert.Equal(Loc.L("Server.Sync.State.CopyFound"), marked.StateText);
Assert.Equal(SyncAction.Compare, marked.Actions[0].Action);
// A match the server deleted: the local row offers what the Matches row does (design §6.3), each with a tooltip.
await CopyScenes.ShowAsync(shell, "server-copies-gone");
var gone = table.Rows.Single(r => r.Title == "Garden 2026");
Assert.SequenceEqual([SyncAction.KeepHere, SyncAction.UploadAgain, SyncAction.ToTrash], gone.Actions.Select(a => a.Action));
foreach (var action in gone.Actions)
{
Assert.False(string.IsNullOrWhiteSpace(action.ToolTip), $"{action.Text} has a tooltip");
Assert.Equal(Loc.L("Server.Copies.Action." + action.Action), action.Text);
}
CopyScenes.Reset(shell);
});
[Test]
public Task TheCompareDialogWaitsForTheDetailsAndConfirmsWhatItReplaces() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var server = shell.Server;
var list = server.Sync.Copies;
await CopyScenes.ShowAsync(shell, "server-copies");
// Integrate… opens on the details while one waits for a choice.
var pair = list.Pairs.Single(p => p.Here.Title == CopyScenes.Lighthouse);
var dialog = Assert.NotNull(list.Open(pair, CopyDialogPart.Plan, integrate: true));
await dialog.LoadAsync();
Assert.True(server.IsDialogOpen);
Assert.False(server.IsContentEnabled, "the screen behind the dialog takes no input");
Assert.Equal(CopyDialogPart.Details, dialog.Part);
Assert.Equal(3, dialog.Unchosen);
await app.ExpectAsync<ServerView>("server-copies-details");
// The footer: one primary action, Cancel answers Esc; both say what they do.
var cancel = app.FindAll<Button>().Single(b => b.IsVisible && b.IsCancel);
Assert.Equal(Loc.L("Tooltips.Server.Copies.Cancel"), cancel.ToolTip);
Assert.Contains(app.FindAll<Button>(), b => b.IsVisible && b.Content as string == dialog.ApplyText && b.ToolTip is not null);
// The plan is blocked until every detail is chosen; the block line offers Choose.
dialog.Part = CopyDialogPart.Plan;
await dialog.PlanNowAsync();
var block = Assert.Contains(dialog.Blocks, b => b.Block == CopyBlock.DetailsUnchosen);
Assert.True(block.HasChoose);
Assert.False(dialog.ApplyCommand.CanExecute(null));
Assert.Equal(block.Text, dialog.ApplyToolTip);
dialog.AllHereCommand.Execute(null);
Assert.Equal(0, dialog.Unchosen);
await dialog.PlanNowAsync();
Assert.False(dialog.Blocks.Any(b => b.Block == CopyBlock.DetailsUnchosen), "every detail chosen");
Assert.True(dialog.ApplyCommand.CanExecute(null));
Assert.NotEmpty(dialog.HereLines);
await app.ExpectAsync<ServerView>("server-copies-plan");
// This PC's version wins: the server's versions go to its trash, so the confirmation is destructive.
dialog.Policy = dialog.Policies.First(o => o.Value == CopyPhotoPolicy.ThisPcWins);
await dialog.PlanNowAsync();
var replace = dialog.ReplaceRequest(Assert.NotNull(dialog.Plan));
Assert.True(replace.IsDestructive);
Assert.Equal(Loc.L("Server.Copies.Confirm.Replace.Title"), replace.Heading);
// Cancel closes the dialog and gives the screen back.
dialog.CloseCommand.Execute(null);
Assert.False(server.IsDialogOpen);
Assert.True(server.IsContentEnabled);
// A local pair merges into the kept copy, preselected; the confirmation asks for the dropped photo count.
var merge = Assert.NotNull(await CopyScenes.ShowAsync(shell, "server-copies-merge"));
Assert.True(merge.IsMerge);
Assert.Count(2, merge.KeepOptions);
Assert.Count(1, merge.KeepOptions.Where(o => o.IsChecked));
merge.AllHereCommand.Execute(null);
await merge.PlanNowAsync();
var plan = Assert.NotNull(merge.MergePlan);
var request = merge.MergeRequest(plan);
Assert.True(request.IsDestructive);
var dropped = list.Pairs.Single(p => p.Here.Title == CopyScenes.Alps) is var alps && plan.KeepId == alps.Copy.LocalId ? alps.There : alps.Here;
Assert.Equal(dropped.Photos.ToString(System.Globalization.CultureInfo.InvariantCulture), request.TypedConfirmation);
Assert.Contains(request.TypedConfirmation!, request.TypedPrompt!);
// Its first line is the dropped sequence's fact, not a photo held elsewhere.
Assert.False(request.Detail!.StartsWith(Loc.L("Server.Copies.Confirm.Elsewhere", string.Empty).Trim(), StringComparison.Ordinal),
"a merge's facts carry no Held elsewhere prefix");
await app.ExpectAsync<ServerView>("server-copies-merge");
// Choose on "choose the sequence to keep" takes the keyboard to the first Kept radio of the Plan part.
merge.Part = CopyDialogPart.Plan;
var view = app.FindAll<ServerView>().First(v => v.IsVisible);
for (var i = 0; i < 80 && ServerView.FirstKeepOption(view) is null; i++)
{
view.UpdateLayout();
await Task.Delay(25);
}
Assert.NotNull(ServerView.FirstKeepOption(view), "the Kept sequence radios are on the Plan part");
CopyScenes.Reset(shell);
Assert.False(server.IsDialogOpen);
});
[Test]
public Task AMergeKeepingThePairsOtherCopyShowsItFirstAndKeepsItsValues() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var merge = Assert.NotNull(await CopyScenes.ShowAsync(shell, "server-copies-merge"));
Assert.Equal(Loc.L("Server.Copies.Detail.AllKept"), merge.AllHereText);
Assert.Equal(Loc.L("Server.Copies.Detail.AllOther"), merge.AllThereText);
Assert.True(merge.Details.Count > 0, "the Alps pair has details that differ");
// Kept: the pair's other sequence. Its values move to the first column, and "kept" stays the kept one's.
merge.KeepOptions.Single(o => o.SequenceId == merge.Copy.OtherId).IsChecked = true;
var detail = merge.Details[0];
Assert.Equal(detail.Line.There ?? Loc.L("Server.Sync.None"), detail.HereToolTip);
Assert.Equal(detail.Line.Here ?? Loc.L("Server.Sync.None"), detail.ThereToolTip);
// The segments say what choosing them does, with the worded value each takes, not the raw value.
Assert.Equal(Loc.L("Tooltips.Server.Copies.Detail.UseKept", detail.HereText), detail.HereChoiceToolTip);
Assert.Equal(Loc.L("Tooltips.Server.Copies.Detail.UseOther", detail.ThereText), detail.ThereChoiceToolTip);
detail.ChoiceIndex = 0;
await merge.PlanNowAsync();
var plan = Assert.NotNull(merge.MergePlan);
Assert.Equal(CopySide.ThisPc, plan.Choices.Details[detail.Path]);
CopyScenes.Reset(shell);
});
[Test]
public Task EditsPickerMarksAProjectWhoseTimeLapseHasATwin() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
// A workspace project of this PC: the sample reads it as a linked pair's, with a project on the server.
var id = await app.Sample.FillEditorAsync();
shell.OpenSequence(id);
await shell.Sequence.OpenAsync(id);
Assert.Contains(CopyScenes.Views, v => v == "edit-picker-twins");
await CopyScenes.ShowAsync(shell, "edit-picker-twins");
var twin = Assert.Contains(shell.Sequence.Picker.WorkspaceItems, i => i.HasTwin);
Assert.False(string.IsNullOrWhiteSpace(twin.TwinToolTip), "the Twin chip says where the other project is");
await app.ExpectAsync<SequenceView>("edit-picker-twins", waitForThumbnails: true);
CopyScenes.Reset(shell);
});
[Test]
public Task ManyProjectsScrollInsideTheDialog() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var dialog = Assert.NotNull(await CopyScenes.ShowAsync(shell, "server-copies-projects-many"));
Assert.True(dialog.IsProjects);
Assert.Equal((CopyScenes.ManyProjects, CopyScenes.ManyProjects), (dialog.HereProjects.Count, dialog.ThereProjects.Count));
await app.ExpectAsync<ServerView>("server-copies-projects-many");
// Both lists sit in one scroll viewer that holds more than it shows: the dialog's footer stays in view.
var scroll = Assert.Contains(app.FindAll<ScrollViewer>(), s => s.IsVisible && s.ScrollableHeight > 0
&& s.Content is Grid grid && grid.Children.OfType<ItemsControl>().Count() == 2);
Assert.True(scroll.ViewportHeight > 0);
// Each heading shares its list's column, so the scroll bar never moves a list off its heading.
var lists = ((Grid)scroll.Content).Children.OfType<ItemsControl>().ToList();
var headings = ((Grid)scroll.Content).Children.OfType<TextBlock>().ToList();
Assert.Count(2, headings);
for (var i = 0; i < 2; i++)
{
var window = Window.GetWindow(scroll);
Assert.Approximately(lists[i].TranslatePoint(new Point(0, 0), window).X, headings[i].TranslatePoint(new Point(0, 0), window).X, 0.5,
$"heading {i} starts where its list does");
}
// The sample pair has its own projects back for the other scenes.
var lighthouse = shell.Server.Sync.Copies.Pairs.Single(p => p.Here.Title == CopyScenes.Lighthouse);
Assert.Equal(2, (await shell.Services.Sync.Copies!.CompareAsync(lighthouse.Copy.Id, null, CancellationToken.None)).Projects.Here.Count);
CopyScenes.Reset(shell);
});
[Test]
public Task TheLibraryAndSettingsShowTheMatches() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
// A card in a pair that asks for a choice carries the match status and offers Compare….
await LibraryScenes.ShowCopiesAsync(shell, CopyScenes.Alps);
var item = Assert.Contains(shell.Library.Items, i => i.HasMatch && i.Title == CopyScenes.Alps);
Assert.NotNull(item.MatchStatus);
// Second, right after the analysis status, so a narrow card cuts the others first.
Assert.Equal(item.MatchStatus, item.Statuses[1]);
Assert.True(shell.Library.CompareItemCommand.CanExecute(item));
// A refresh builds new cards: the match status stays on them.
await shell.Library.RefreshAsync();
item = Assert.Contains(shell.Library.Items, i => i.HasMatch && i.Title == CopyScenes.Alps);
Assert.NotNull(item.MatchStatus);
await app.ExpectAsync<LibraryView>("library-copies", waitForThumbnails: true);
// Two versions… lists the photos the sequence keeps in two versions (a Union merge's), here none, and says so.
Assert.True(shell.Library.VersionsItemCommand.CanExecute(item));
await shell.Library.ShowVersionsAsync(item.Id);
var versions = Assert.NotNull(shell.Library.Dialog as VersionsDialogViewModel);
Assert.True(versions.IsEmpty && !versions.HasRows);
Assert.Contains(CopyScenes.Alps, versions.Heading);
versions.CloseCommand.Execute(null);
Assert.Null(shell.Library.Dialog);
shell.Library.CompareItemCommand.Execute(item);
Assert.Equal(SectionKey.Server, shell.Current.Key);
Assert.True(shell.Server.Sync.IsMatches);
Assert.Equal(CopyScenes.Alps, shell.Server.Sync.SearchText);
CopyScenes.Reset(shell);
// Settings › Server: three rows, every option with its tooltip, each choice saved at once.
var rows = shell.Settings.CopyRows;
foreach (var option in rows.LinkingOptions.Cast<object>().Concat(rows.PhotoOptions).Concat(rows.ProjectOptions))
{
var (label, tip) = option switch
{
SettingsOption<CopyLinking> o => (o.Label, o.ToolTip),
SettingsOption<CopyPhotoPolicy> o => (o.Label, o.ToolTip),
SettingsOption<CopyProjects> o => (o.Label, o.ToolTip),
_ => (string.Empty, null),
};
Assert.False(string.IsNullOrWhiteSpace(tip), $"{label} has a tooltip");
Assert.LessOrEqual(label.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length, 3, $"\"{label}\" is at most three words");
}
rows.Linking = rows.LinkingOptions.First(o => o.Value == CopyLinking.WhenIdentical);
Assert.Equal(CopyLinking.WhenIdentical, shell.Services.Settings.CopyLinking);
shell.Navigate(SectionKey.Settings);
shell.Settings.Page = SettingsPage.Server;
await app.ExpectAsync<SettingsView>("settings-server");
Assert.Contains(app.FindAll<ComboBox>(), c => c.IsVisible && Equals(c.SelectedItem, rows.Linking) && c.ToolTip is not null);
});
[Test]
public Task TheDialogStartsFromTheSettingsAndChooseEachPreselectsNothing() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var settings = shell.Services.Settings;
var list = shell.Server.Sync.Copies;
var pair = list.Pairs.Single(p => p.Here.Title == CopyScenes.Lighthouse);
var (photos, projects) = (settings.CopyPhotos, settings.CopyProjects);
try
{
// Owner review 6 (#73): the dialog opens on Settings › Server's choices, whatever they are.
settings.CopyPhotos = CopyPhotoPolicy.ThisPcWins;
settings.CopyProjects = CopyProjects.Leave;
var dialog = Assert.NotNull(list.Open(pair, CopyDialogPart.Photos));
await dialog.LoadAsync();
Assert.Equal((CopyPhotoPolicy.ThisPcWins, 1), (dialog.Policy.Value, dialog.ProjectsIndex));
dialog.CloseCommand.Execute(null);
settings.CopyPhotos = CopyPhotoPolicy.Union;
settings.CopyProjects = CopyProjects.CopyAcross;
dialog = Assert.NotNull(list.Open(pair, CopyDialogPart.Photos));
await dialog.LoadAsync();
Assert.Equal((CopyPhotoPolicy.Union, 0), (dialog.Policy.Value, dialog.ProjectsIndex));
// Choose each: every photo row of every class starts unticked and without a version chosen.
dialog.Policy = dialog.Policies.First(o => o.Value == CopyPhotoPolicy.ChoosePerPhoto);
Assert.True(dialog.IsChoosing);
var offered = 0;
foreach (var cls in dialog.Classes)
{
dialog.SelectedClass = cls;
foreach (var row in dialog.Photos)
{
if (row.CanBring || row.CanChoose) offered++;
Assert.Null(row.Chosen);
Assert.False(row.Bring, $"{row.Name} is not ticked");
Assert.Null(row.Choice);
}
}
Assert.True(offered > 0, "the Lighthouse pair has photos to choose");
dialog.CloseCommand.Execute(null);
}
finally
{
(settings.CopyPhotos, settings.CopyProjects) = (photos, projects);
CopyScenes.Reset(shell);
}
});
[Test]
public Task MatchesFoundInTheBackgroundAndPhotosNotSentAreTold() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var table = shell.Server.Sync;
var raised = new List<Toast>();
shell.PendingToasts.CollectionChanged += (_, e) => raised.AddRange(e.NewItems?.OfType<Toast>() ?? []);
var pair = table.Copies.Pairs.Single(p => p.Here.Title == CopyScenes.Lighthouse);
shell.Navigate(SectionKey.Library);
// A detection that ran by itself (after a refresh, a scan, an import): "1 match found" · Review (design §8.4).
var engine = Assert.NotNull(shell.Services.Sync.Copies as Chronos.App.DesignTime.SampleCopyEngine);
engine.RaiseFound(new CopyFindResult([pair.Copy], [], []));
var found = await ToastAsync(raised, Loc.Plural("Server.Copies.Found", 1));
Assert.Equal(Loc.L("Server.Copies.Action.Review"), found.ActionText);
Assert.False(string.IsNullOrWhiteSpace(found.ActionToolTip));
Assert.True(found.RunsFromNotification, "a click on the Windows notification opens the matches");
found.ActionCommand!.Execute(null);
Assert.Equal(SectionKey.Server, shell.Current.Key);
Assert.True(table.IsMatches);
// A detection that found nothing tells nothing.
shell.Navigate(SectionKey.Library);
raised.Clear();
engine.RaiseFound(CopyFindResult.Empty);
await Task.Delay(200);
Assert.Empty(raised.Where(t => t.Title == Loc.Plural("Server.Copies.Found", 1)));
// Automatic photos of an integrated pair failed three times: "{title}: photos not sent" · Show, an error (design §6.1).
shell.Services.Sync.TellPhotosNotSent("server", pair.Copy.LocalId, new AutoPhotoFailure(SyncAgent.NotSentAfter, "Quota reached"));
var notSent = await ToastAsync(raised, Loc.L("Server.Sync.NotSentToast", CopyScenes.Lighthouse));
Assert.True(notSent.IsError);
Assert.Equal((Loc.L("Server.Sync.Show"), Loc.L("Tooltips.Server.Sync.ShowNotSent")), (notSent.ActionText, notSent.ActionToolTip));
Assert.True(notSent.RunsFromNotification);
notSent.ActionCommand!.Execute(null);
Assert.Equal(SectionKey.Server, shell.Current.Key);
Assert.False(table.IsMatches);
Assert.Equal(CopyScenes.Lighthouse, table.SearchText);
Assert.Contains(table.Rows, r => r.Title == CopyScenes.Lighthouse);
CopyScenes.Reset(shell);
});
[Test]
public Task ASwappedMergeOffersToTrashOnDeletedInOtherFromTheKeptSequenceOnly() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var engine = (SampleCopyEngine)shell.Services.Sync.Copies!;
var list = shell.Server.Sync.Copies;
await CopyScenes.ShowAsync(shell, "server-copies");
var alps = list.Pairs.Single(p => p.Here.Title == CopyScenes.Alps);
var start = new DateTime(2025, 7, 14, 5, 30, 0);
// The pair's first deleted 3 photos its other still holds (Deleted here), and the other deleted 2 the first holds.
var restore = engine.With(alps.Copy.Id, p => p with
{
Photos = [.. p.Photos, .. SampleCopies.Photos(PhotoClass.DeletedHere, 3, start, 950, here: false, there: true),
.. SampleCopies.Photos(PhotoClass.DeletedThere, 2, start, 960, here: true, there: false)],
});
try
{
var dialog = Assert.NotNull(list.Open(alps, CopyDialogPart.Photos, PhotoClass.DeletedHere));
await dialog.LoadAsync();
Assert.Equal(alps.Copy.OtherId, dialog.KeepOptions.Single(o => o.IsChecked).SequenceId);
// Kept: the pair's other. Its "Deleted in other" (the first deleted them) offers To trash…, from the kept one.
var deletedInOther = dialog.Classes.Single(c => c.Class == PhotoClass.DeletedHere);
Assert.Equal(CopyText.Class(PhotoClass.DeletedThere, merge: true), deletedInOther.Text);
dialog.SelectedClass = deletedInOther;
Assert.True(dialog.CanTrashHere);
var plan = await dialog.PlanTrashHereAsync([dialog.Photos[0].Key]);
Assert.Equal(alps.Copy.OtherId, plan.Plan.Sequence.Id);
// "Deleted in kept": its frames are the dropped sequence's, which go with the merge; no To trash….
var deletedInKept = dialog.Classes.Single(c => c.Class == PhotoClass.DeletedThere);
Assert.Equal(CopyText.Class(PhotoClass.DeletedHere, merge: true), deletedInKept.Text);
dialog.SelectedClass = deletedInKept;
Assert.False(dialog.CanTrashHere);
// Kept: the pair's first. Now Deleted there reads "Deleted in other" and trashes from the first.
dialog.KeepOptions.Single(o => o.SequenceId == alps.Copy.LocalId).IsChecked = true;
dialog.SelectedClass = dialog.Classes.Single(c => c.Class == PhotoClass.DeletedThere);
Assert.True(dialog.CanTrashHere);
Assert.Equal(alps.Copy.LocalId, (await dialog.PlanTrashHereAsync([dialog.Photos[0].Key])).Plan.Sequence.Id);
dialog.SelectedClass = dialog.Classes.Single(c => c.Class == PhotoClass.DeletedHere);
Assert.False(dialog.CanTrashHere);
}
finally
{
restore();
CopyScenes.Reset(shell);
}
});
[Test]
public Task InMainMarksTheVersionTheKeptSequencesMainUses() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var dialog = Assert.NotNull(await CopyScenes.ShowAsync(shell, "server-copies-versions"));
var alps = shell.Server.Sync.Copies.Pairs.Single(p => p.Here.Title == CopyScenes.Alps);
var review = await shell.Services.Sync.Copies!.CompareAsync(alps.Copy.Id, null, CancellationToken.None);
Assert.Equal(alps.Copy.OtherId, dialog.KeepOptions.Single(o => o.IsChecked).SequenceId);
// The two Mains use different versions: the kept sequence's (the pair's other) is marked.
Assert.Count(1, dialog.Photos.Where(p => p.InMain));
foreach (var marked in dialog.Photos.Where(x => x.InMain)) Assert.DoesNotContain(marked.Key, review.ExcludedThere);
await app.ExpectAsync<ServerView>("server-copies-versions");
// Both sides hold both versions: the side reads whole beside "In Main", and Drop… keeps its gap.
var view = app.FindAll<ServerView>().First(v => v.IsVisible);
foreach (var row in app.FindAll<ListBoxItem>().Where(i => i is { DataContext: CopyPhotoRow, IsVisible: true }))
{
var photo = (CopyPhotoRow)row.DataContext;
var side = Descendants<TextBlock>(row).Single(t => t.Text == photo.SideText);
// Layout rounding may take under a pixel; a trimmed text loses a whole character to the ellipsis.
Assert.True(Needed(side, side.Text) <= side.ActualWidth + 1.0, $"'{side.Text}' needs {Needed(side, side.Text):0.0} px, has {side.ActualWidth:0.0}");
var drop = Descendants<Button>(row).Single(b => b.IsVisible);
Assert.True(drop.Margin.Left >= 10, "Drop… keeps a gap from the side cell");
}
Assert.NotNull(view);
// Kept: the pair's first. The marker follows its Main.
dialog.KeepOptions.Single(o => o.SequenceId == alps.Copy.LocalId).IsChecked = true;
Assert.Count(1, dialog.Photos.Where(p => p.InMain));
foreach (var marked in dialog.Photos.Where(x => x.InMain)) Assert.DoesNotContain(marked.Key, review.ExcludedHere);
CopyScenes.Reset(shell);
});
[Test]
public Task ATwinNeedsItsSiblingAtTheOtherHome() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var engine = (SampleCopyEngine)shell.Services.Sync.Copies!;
// The integrated pair: Main and Vertical on this PC, only Main on the server.
var bridge = engine.Pairs.Single(p => p.Copy is { Kind: CopyKind.LocalServer, State: CopyState.Integrated });
Assert.SequenceEqual(["Main", "Vertical"], bridge.Projects.Here.Select(p => p.Name));
Assert.SequenceEqual(["Main"], bridge.Projects.There.Select(p => p.Name));
await CopyScenes.ShowAsync(shell, "edit-picker-twins");
var picker = shell.Sequence.Picker;
var home = Chronos.App.Workspace.WorkspaceHost.ArchiveHome(bridge.Copy.LocalId);
IReadOnlyList<Chronos.App.Workspace.WorkspaceEntry> entries =
[
new(Guid.CreateVersion7(), bridge.Copy.LocalId, "Main", true, home, bridge.Here.Title, HasMedia: true, SampleData.Now),
new(Guid.CreateVersion7(), bridge.Copy.LocalId, "Vertical", false, home, bridge.Here.Title, HasMedia: true, SampleData.Now),
];
await picker.ShowSampleWorkspaceAsync(entries, new Chronos.Data.Workspaces.WorkspaceStatus(Chronos.Data.Workspaces.WorkspaceState.InSync, false, 0, 0,
false, false, false, null, null, null));
var main = picker.WorkspaceItems.Single(i => i.Entry.Name == "Main");
var vertical = picker.WorkspaceItems.Single(i => i.Entry.Name == "Vertical");
Assert.True(main.HasTwin, "Main has its sibling on the server");
Assert.Contains(main.Name, main.TwinToolTip!);
Assert.False(vertical.HasTwin, "Vertical is only on this PC");
CopyScenes.Reset(shell);
});
[Test]
public Task TheDialogsPolicyAndVersionChoicesFitTheirBoxesInEveryLanguage() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var dialog = Assert.NotNull(await CopyScenes.ShowAsync(shell, "server-copies-choose"));
await app.ExpectAsync<ServerView>("server-copies-choose");
var policy = app.FindAll<ComboBox>().Single(c => c.IsVisible && AutomationProperties.GetName(c) == Loc.L("Server.Copies.Policy.Label"));
var version = app.FindAll<ComboBox>().First(c => c.IsVisible && c.DataContext is CopyPhotoRow);
List<string> misses = [];
try
{
foreach (var language in Languages.Shipped)
{
UiLanguage.Apply(language);
app.Window.UpdateLayout();
await app.Window.Dispatcher.InvokeAsync(() => { }, System.Windows.Threading.DispatcherPriority.ApplicationIdle);
foreach (var merge in new[] { false, true })
{
Fits(misses, language, policy, CopyDialogViewModel.PolicyOptions(merge).Select(o => o.Label));
Fits(misses, language, version, CopyDialogViewModel.VersionChoices(merge).Select(o => o.Label));
}
}
}
finally
{
UiLanguage.Apply("en");
}
Assert.True(misses.Count == 0, string.Join(Environment.NewLine, misses));
Assert.NotNull(dialog);
CopyScenes.Reset(shell);
});
[Test]
public Task TheMatchesSettingsFitTheirBoxesInEveryLanguage() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var settings = shell.Settings;
shell.Navigate(SectionKey.Settings);
settings.Page = SettingsPage.Server;
await app.ExpectAsync<Chronos.App.Sections.SettingsView>("settings-server");
string[] names = ["Settings.Server.CopyLinking", "Settings.Server.CopyPhotos", "Settings.Server.CopyProjects"];
List<string> misses = [];
try
{
foreach (var language in Languages.Shipped)
{
UiLanguage.Apply(language);
settings.CopyRows.Refresh();
app.Window.UpdateLayout();
await app.Window.Dispatcher.InvokeAsync(() => { }, System.Windows.Threading.DispatcherPriority.ApplicationIdle);
foreach (var name in names)
{
var box = app.FindAll<ComboBox>().Single(c => c.IsVisible && AutomationProperties.GetName(c) == Loc.L(name));
var labels = box.ItemsSource.Cast<object>().Select(o => (string)o.GetType().GetProperty("Label")!.GetValue(o)!);
Fits(misses, language, box, labels);
}
}
}
finally
{
UiLanguage.Apply("en");
settings.CopyRows.Refresh();
}
Assert.True(misses.Count == 0, string.Join(Environment.NewLine, misses));
});
/// <summary>
/// Adds to <paramref name="misses"/> each label that does not show whole in <paramref name="box"/>'s selection box (its
/// content site, inside the margins).
/// </summary>
private static void Fits(List<string> misses, string language, ComboBox box, IEnumerable<string> labels)
{
box.ApplyTemplate();
var site = (FrameworkElement)box.Template.FindName("ContentSite", box);
var room = box.ActualWidth - site.Margin.Left - site.Margin.Right - box.BorderThickness.Left - box.BorderThickness.Right;
var probe = new TextBlock { FontFamily = box.FontFamily, FontSize = box.FontSize, FontWeight = box.FontWeight, FlowDirection = box.FlowDirection };
foreach (var label in labels.Where(l => Needed(probe, l) > room + 0.5))
misses.Add($"{language}: '{label}' needs {Needed(probe, label):0.0} px, its box has {room:0.0}");
}
/// <summary>The width <paramref name="text"/> takes in <paramref name="cell"/>'s font.</summary>
private static double Needed(TextBlock cell, string text) => new FormattedText(text, System.Globalization.CultureInfo.CurrentUICulture, cell.FlowDirection,
new Typeface(cell.FontFamily, cell.FontStyle, cell.FontWeight, cell.FontStretch), cell.FontSize, Brushes.Black, 1.0).WidthIncludingTrailingWhitespace;
private static IEnumerable<T> Descendants<T>(DependencyObject node)
where T : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++)
{
var child = VisualTreeHelper.GetChild(node, i);
if (child is T match) yield return match;
foreach (var inner in Descendants<T>(child)) yield return inner;
}
}
private static async Task<Toast> ToastAsync(List<Toast> raised, string title)
{
for (var i = 0; i < 250 && !raised.Any(t => t.Title == title); i++) await Task.Delay(20);
return Assert.Contains(raised, t => t.Title == title);
}
private static async Task<ScreenSmokeTests.SampleApp> StartAsync()
{
var app = await ScreenSmokeTests.SampleApp.StartAsync();
var shell = app.Shell;
await app.Sample.FillAsync();
await shell.Services.Server.RestoreAsync();
Assert.NotNull(await shell.Services.Sync.RefreshAsync());
await app.Sample.FillCopiesAsync();
await shell.Library.RefreshAsync();
await shell.Server.Sync.ReloadAsync();
return app;
}
}
@@ -0,0 +1,545 @@
using System.Globalization;
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Server;
using Chronos.App.Server.Copies;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Copies;
using Chronos.Data.Sync;
using Chronos.Testing;
using Chronos.Ui.Controls;
namespace Chronos.App.Tests.Server;
/// <summary>Words, glyphs and actions of a match (owner review 6, #73, design §8.1), and the sync rows a match marks.</summary>
[Serial]
public sealed class CopyTextTests
{
private const string Nas = "https://nas.local:8443";
private static readonly CopyRights SignedIn = new(Nas, "Studio NAS", CanIntegrate: true, CanUpload: true);
private static readonly Sequence Local = new()
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.CreateVersion7(),
Title = "Lighthouse 2026-08-13",
Folder = "2026/lighthouse",
FrameCount = 1_204,
TotalBytes = 18_200_000_000,
Status = SequenceStatus.ProxiesBuilt,
};
private static readonly SyncLink Link = new()
{
Server = Nas,
RemoteId = Guid.CreateVersion7(),
Title = "Lighthouse 2026-08-13",
TotalBytes = 18_200_000_000,
RemoteStatus = SequenceStatus.ProxiesBuilt,
};
[Test]
public void EachStateOffersTheActionsOfTheTable()
{
Assert.SequenceEqual([CopyAction.Compare, CopyAction.Integrate, CopyAction.KeepApart], CopyText.Actions(Copy(CopyState.Candidate)));
Assert.SequenceEqual([CopyAction.Compare, CopyAction.Merge, CopyAction.KeepApart], CopyText.Actions(Copy(CopyState.Candidate, CopyKind.LocalLocal)));
Assert.SequenceEqual([CopyAction.Compare, CopyAction.AskAgain], CopyText.Actions(Copy(CopyState.KeptApart)));
Assert.SequenceEqual([CopyAction.Compare, CopyAction.Integrate, CopyAction.Unlink], CopyText.Actions(Copy(CopyState.Linked)));
// Three buttons at most: a linked pair with photos deleted there reaches Integrate through Compare… or Review.
Assert.SequenceEqual([CopyAction.Compare, CopyAction.Unlink, CopyAction.Review], CopyText.Actions(Copy(CopyState.Linked, deletedThere: 3)));
foreach (var state in Enum.GetValues<CopyState>())
{
foreach (var copy in new[] { Copy(state), Copy(state, deletedThere: 3), Copy(state, gone: true), Copy(state, CopyKind.LocalLocal, deletedThere: 3) })
Assert.LessOrEqual(CopyText.Actions(copy).Count, 3, $"{state}: at most three row buttons");
}
Assert.SequenceEqual([CopyAction.Compare, CopyAction.Unlink], CopyText.Actions(Copy(CopyState.Integrated)));
Assert.SequenceEqual([CopyAction.Compare, CopyAction.Unlink, CopyAction.Review], CopyText.Actions(Copy(CopyState.Integrated, deletedThere: 3)));
Assert.SequenceEqual([CopyAction.Pause], CopyText.Actions(Copy(CopyState.Integrating), JobState.Running));
Assert.SequenceEqual([CopyAction.Resume], CopyText.Actions(Copy(CopyState.Integrating), JobState.Paused));
// The server deleted its copy: keep it here, send it again or move it to the trash; once kept, only send again.
Assert.SequenceEqual([CopyAction.KeepHere, CopyAction.UploadAgain, CopyAction.ToTrash], CopyText.Actions(Copy(CopyState.Linked, gone: true)));
Assert.SequenceEqual([CopyAction.UploadAgain], CopyText.Actions(Copy(CopyState.KeptApart, gone: true)));
}
[Test]
public void TheStateGlyphFollowsWhatThePairAsksFor()
{
Assert.Equal(StatusKind.Warning, CopyText.State(Copy(CopyState.Candidate)).Kind);
Assert.Equal(StatusKind.Offline, CopyText.State(Copy(CopyState.KeptApart)).Kind);
Assert.Equal(StatusKind.Synced, CopyText.State(Copy(CopyState.Linked)).Kind);
Assert.Equal(StatusKind.Running, CopyText.State(Copy(CopyState.Integrating), progress: (3, 10)).Kind);
Assert.Equal(StatusKind.Done, CopyText.State(Copy(CopyState.Integrated)).Kind);
Assert.Equal((StatusKind.Warning, Loc.L("Server.Copies.State.DeletedThere", "3")),
Head(CopyText.State(Copy(CopyState.Integrated, deletedThere: 3))));
Assert.Equal((StatusKind.Warning, Loc.L("Server.Copies.State.DeletedOther", "3")),
Head(CopyText.State(Copy(CopyState.Integrated, CopyKind.LocalLocal, deletedThere: 3))));
Assert.Equal((StatusKind.Warning, Loc.L("Server.Copies.State.RemoteGone")), Head(CopyText.State(Copy(CopyState.Linked, gone: true))));
Assert.Equal((StatusKind.Offline, Loc.L("Server.Copies.State.KeptHere")), Head(CopyText.State(Copy(CopyState.KeptApart, gone: true))));
// The candidate's tooltip says how much the two share.
Assert.Contains("98", CopyText.State(Copy(CopyState.Candidate)).ToolTip);
}
[Test]
public void AnActionThatCannotRunSaysWhy()
{
var candidate = Copy(CopyState.Candidate);
Assert.Null(CopyText.Blocked(candidate, CopyAction.Integrate, SignedIn));
// A pair of another server needs that server signed in; the answers that move nothing never do.
var signedOut = new CopyRights(null, null, false, false);
Assert.Equal(Loc.L("Tooltips.Server.Copies.SignIn", Nas), CopyText.Blocked(candidate, CopyAction.Compare, signedOut));
Assert.Null(CopyText.Blocked(candidate, CopyAction.KeepApart, signedOut));
Assert.Equal(Loc.L("Tooltips.Server.Copies.NeedsNewerServer"), CopyText.Blocked(candidate, CopyAction.Integrate, SignedIn with { CanIntegrate = false }));
Assert.Equal(Loc.L("Errors.Copies.Busy"), CopyText.Blocked(candidate, CopyAction.Integrate, SignedIn with { Busy = true }));
Assert.Null(CopyText.Blocked(candidate, CopyAction.Compare, SignedIn with { Busy = true }));
var gone = Copy(CopyState.Linked, gone: true);
Assert.Equal(Loc.L("Tooltips.Server.Sync.UploadAll.NoRight"), CopyText.Blocked(gone, CopyAction.UploadAgain, SignedIn with { CanUpload = false }));
// A local pair needs no server.
Assert.Null(CopyText.Blocked(Copy(CopyState.Candidate, CopyKind.LocalLocal), CopyAction.Merge, signedOut));
// The tooltip of a disabled button is its reason.
Assert.Equal(Loc.L("Errors.Copies.Busy"), CopyText.ToolTip(candidate, CopyAction.Integrate, SignedIn with { Busy = true }));
}
[Test]
public void AttentionComesFirstThenTheStrongerHints()
{
var kept = View(Copy(CopyState.KeptApart) with { Score = Score(hints: 900) }, "Aurora");
var weak = View(Copy(CopyState.Candidate) with { Score = Score(hints: 100) }, "Bridge");
var strong = View(Copy(CopyState.Candidate) with { Score = Score(hints: 800) }, "Comet");
Assert.SequenceEqual(["Comet", "Bridge", "Aurora"], CopyText.Sorted([kept, weak, strong]).Select(p => p.Here.Title));
Assert.True(CopyText.Matches(strong, "com"));
Assert.True(CopyText.Matches(strong, "Comet (nas)"));
Assert.False(CopyText.Matches(strong, "Aurora"));
}
[Test]
public void EveryWordResolvesInEnglishAndItalianAndLabelsStayShort()
{
var missing = new List<string>();
void OnMissing(string key) => missing.Add(key);
Loc.MissingKey += OnMissing;
try
{
foreach (var culture in new[] { "en", "it" })
{
Loc.SetCulture(CultureInfo.GetCultureInfo(culture));
var gone = Copy(CopyState.Linked, gone: true);
foreach (var action in Enum.GetValues<CopyAction>())
{
var label = CopyText.Label(action);
Assert.LessOrEqual(label.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length, 3, $"{culture}: \"{label}\" is at most three words");
Assert.False(string.IsNullOrWhiteSpace(CopyText.ToolTip(gone, action, SignedIn)), $"{culture}: {action} has a tooltip");
}
foreach (var c in Enum.GetValues<PhotoClass>())
{
Assert.False(string.IsNullOrWhiteSpace(CopyText.Class(c)), $"{culture}: {c}");
foreach (var policy in Enum.GetValues<CopyPhotoPolicy>())
{
foreach (var merge in new[] { false, true })
Assert.False(string.IsNullOrWhiteSpace(CopyText.ClassToolTip(c, policy, merge)), $"{culture}: {c} has a tooltip under {policy}");
}
}
foreach (var block in Enum.GetValues<CopyBlock>())
Assert.False(string.IsNullOrWhiteSpace(CopyText.Block(block, "Lighthouse", "Studio NAS", "2 GB", 2)), $"{culture}: {block}");
foreach (var state in Enum.GetValues<CopyState>())
{
foreach (var copy in new[] { Copy(state), Copy(state, deletedThere: 2), Copy(state, gone: true), Copy(state, CopyKind.LocalLocal, deletedThere: 2) })
{
var (_, text, tip) = CopyText.State(copy, "Studio NAS", (1, 4));
Assert.False(string.IsNullOrWhiteSpace(text) || string.IsNullOrWhiteSpace(tip), $"{culture}: {state}");
}
}
foreach (var why in Enum.GetValues<UploadSkip>())
Assert.False(string.IsNullOrWhiteSpace(SyncText.State(Entry(SyncStatus.LocalOnly, link: null), new SyncMark(null, why)).ToolTip), $"{culture}: {why}");
Assert.False(string.IsNullOrWhiteSpace(SyncText.ToolTip(Entry(SyncStatus.InSync), SyncAction.Compare)), $"{culture}: Compare has a tooltip");
Assert.Equal(Loc.L("Server.Copies.Detail.OtherSetting"), SyncText.DetailLabel("nothing.known"));
}
}
finally
{
Loc.MissingKey -= OnMissing;
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
Assert.Empty(missing);
}
[Test]
public void ASyncRowInAMatchSaysSoAndOffersCompare()
{
var entry = Entry(SyncStatus.LocalOnly, link: null);
// The Matches chip lists pairs, never sync rows.
Assert.False(SyncText.Matches(entry, SyncFilter.FoundCopies, string.Empty));
var editor = SyncRights.Of((long)RolePermissions.Default(UserRole.Editor));
var candidate = new SyncMark(Copy(CopyState.Candidate), null, "Studio NAS");
var (kind, text, tip) = SyncText.State(entry, candidate);
Assert.Equal((StatusKind.Warning, Loc.L("Server.Sync.State.CopyFound")), (kind, text));
Assert.Equal(Loc.L("Tooltips.Server.Sync.State.CopyFound", "Studio NAS"), tip);
Assert.SequenceEqual([SyncAction.Compare, SyncAction.Upload], SyncText.Actions(entry, editor, candidate));
// A linked row offers Compare last; one without a pair, nothing more.
var linked = Entry(SyncStatus.InSync);
Assert.SequenceEqual([SyncAction.Compare], SyncText.Actions(linked, editor, new SyncMark(Copy(CopyState.Linked), null)));
Assert.Empty(SyncText.Actions(linked, editor, default));
// Deleted on the server, or kept here after that.
Assert.Equal(Loc.L("Server.Sync.State.RemoteGone"), SyncText.State(linked, new SyncMark(Copy(CopyState.Linked, gone: true), null)).Text);
Assert.Equal(Loc.L("Server.Sync.State.KeptHere"), SyncText.State(linked, new SyncMark(Copy(CopyState.KeptApart, gone: true), null)).Text);
// Upload all local left it out: "skipped", with the reason, under the Warning glyph (design §6.4).
var skipped = SyncText.State(entry, new SyncMark(null, UploadSkip.KeptApart));
Assert.Equal((StatusKind.Warning, Loc.L("Server.Sync.State.Skipped")), (skipped.Kind, skipped.Text));
Assert.Equal(Loc.L("Tooltips.Server.Sync.State.Skipped", Loc.L("Tooltips.Server.Sync.Skip.KeptApart")), skipped.ToolTip);
// A transfer still shows first.
var upload = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.UploadCommit, State = JobState.Running };
Assert.Equal(SyncText.State(entry with { Transfer = upload }), SyncText.State(entry with { Transfer = upload }, candidate));
}
[Test]
public void ASkipForASuspectedMatchNamesWhereTheMatchLies()
{
var mark = new SyncMark(null, UploadSkip.SuspectedCopy, "Studio NAS");
// A match on another server than the signed-in one is named by that server.
Assert.Equal(Loc.L("Tooltips.Server.Sync.Skip.SuspectedCopy", "Lab NAS"),
SyncText.SkipReason(UploadSkip.SuspectedCopy, mark with { SkippedMatch = new SkippedMatch("Lab NAS", false) }));
// One in another archive of this PC says "in", not "on".
Assert.Equal(Loc.L("Tooltips.Server.Sync.Skip.SuspectedCopyLocal", "Old archive"),
SyncText.SkipReason(UploadSkip.SuspectedCopy, mark with { SkippedMatch = new SkippedMatch("Old archive", true) }));
// Unknown: the signed-in server.
Assert.Equal(Loc.L("Tooltips.Server.Sync.Skip.SuspectedCopy", "Studio NAS"), SyncText.SkipReason(UploadSkip.SuspectedCopy, mark));
// A job on it may integrate or merge it: the words say neither alone.
Assert.Equal(Loc.L("Tooltips.Server.Sync.Skip.Busy"), SyncText.SkipReason(UploadSkip.Busy, mark));
}
[Test]
public void ARowWhoseMatchTheServerDeletedOffersWhatTheMatchesRowDoes()
{
var entry = Entry(SyncStatus.LocalOnly, link: null);
var editor = SyncRights.Of((long)RolePermissions.Default(UserRole.Editor));
var gone = new SyncMark(Copy(CopyState.Linked, gone: true), null, "Studio NAS");
Assert.SequenceEqual([SyncAction.KeepHere, SyncAction.UploadAgain, SyncAction.ToTrash], SyncText.Actions(entry, editor, gone));
// Kept here: only Upload again.
Assert.SequenceEqual([SyncAction.UploadAgain], SyncText.Actions(entry, editor, new SyncMark(Copy(CopyState.KeptApart, gone: true), null)));
foreach (var action in new[] { SyncAction.KeepHere, SyncAction.UploadAgain, SyncAction.ToTrash })
{
var row = new SyncRowAction(action, () => Task.CompletedTask);
Assert.Equal(Loc.L("Server.Copies.Action." + action), row.Text);
Assert.False(string.IsNullOrWhiteSpace(SyncText.ToolTip(entry, action, editor, gone)), $"{action} has a tooltip");
}
Assert.Equal(Loc.L("Tooltips.Server.Copies.UploadAgain", "Studio NAS"), SyncText.ToolTip(entry, SyncAction.UploadAgain, editor, gone));
// Without the upload right, Upload again is offered disabled with the reason.
var reader = SyncRights.Of((long)RolePermissions.Default(UserRole.Viewer));
Assert.False(SyncText.IsEnabled(SyncAction.UploadAgain, reader));
Assert.Equal(Loc.L("Tooltips.Server.Sync.UploadAll.NoRight"), SyncText.ToolTip(entry, SyncAction.UploadAgain, reader, gone));
}
[Test]
public void TheOwnerReview6TextsFitTheirPlaces()
{
// Integrating: the share in the cell, "x of y" in the tooltip.
var (_, text, tip) = CopyText.State(Copy(CopyState.Integrating), progress: (1_234, 2_400));
Assert.Equal(Loc.L("Server.Copies.State.Integrating", "51"), text);
Assert.Contains(Loc.L("Server.Copies.State.Progress", "1,234", "2,400"), tip);
Assert.Equal(Loc.L("Server.Copies.State.Integrating", "0"), CopyText.State(Copy(CopyState.Integrating)).Text);
// The count comes first, so a trimmed cell keeps what tells two pairs apart.
Assert.True(CopyText.Where(Facts("Lighthouse", "Main archive", 1_204), isServer: false).StartsWith("1,204", StringComparison.Ordinal));
// A server that deleted its sequence is named alone, never "0 photos".
Assert.Equal("Studio NAS", CopyText.Where(Facts(string.Empty, "Studio NAS", 0), isServer: true, gone: true));
// The frame positions read as the setting they are, with the count of photos they place.
Assert.Equal(Loc.L("Server.Copies.Detail.Positions"), SyncText.DetailLabel(CopyPayload.PendingFramesPath));
Assert.Equal(Loc.Plural("Shell.Status.Photos", 2), SyncText.DetailValue(CopyPayload.PendingFramesPath, "{\"a\":{},\"b\":{}}"));
Assert.Equal("Lighthouse", SyncText.DetailValue("sequence.title", "Lighthouse"));
Assert.Equal("41", SyncText.DetailValue("exposure.deflickerWindow.manual", "41"));
Assert.Equal(Loc.L("Server.Copies.Detail.Changed"), SyncText.DetailValue("exposure.curve", "{\"points\":[[0,0],[1,1]]}"));
// The members of one setting are one row and one choice.
Assert.Equal(SyncText.DetailSetting("exposure.deflickerWindow.isAuto"), SyncText.DetailSetting("exposure.deflickerWindow.manual"));
var row = new CopyDetailRow([new DetailLine("exposure.deflickerWindow.isAuto", "true", "false"), new DetailLine("exposure.deflickerWindow.manual", "41", "33")],
isMerge: false, () => { });
Assert.SequenceEqual(["exposure.deflickerWindow.isAuto", "exposure.deflickerWindow.manual"], row.Paths);
Assert.Equal(string.Join(Loc.Separator, Loc.L("Server.Setting.Auto"), "41"), row.HereText);
// A match between this PC's archives names the other archive, not the server.
var local = new SyncMark(Copy(CopyState.Candidate, CopyKind.LocalLocal), null, "Studio NAS", OtherWhere: "Old archive");
Assert.Equal(Loc.L("Tooltips.Library.Status.CopyFoundLocal", "Old archive"), SyncText.State(Entry(SyncStatus.LocalOnly, link: null), local).ToolTip);
// The Library card of a sequence whose server copy was deleted says so.
var gone = View(Copy(CopyState.Linked, gone: true), "Lighthouse");
var status = CopyListViewModel.LibraryStatus(gone, Local.Id);
Assert.Equal(Loc.L("Library.Status.RemoteGone"), status.Text);
// A plan line is what will happen (queued), a warning leads.
Assert.Equal(StatusKind.Queued, new CopyPlanLine("Receives 2 photos").Kind);
Assert.Equal(StatusKind.Warning, new CopyPlanLine("Only copy", IsWarning: true).Kind);
}
[Test]
public void TheReplaceConfirmationListsEachSidesLosersUnderItsHeading()
{
var trashed = new List<PhotoStep>
{
new("a", PhotoAction.TrashHere, Guid.NewGuid(), "IMG_0001.JPG", 10, "a"),
new("b", PhotoAction.TrashHere, Guid.NewGuid(), "IMG_0002.JPG", 10, "b"),
new("c", PhotoAction.TrashThere, Guid.NewGuid(), "IMG_0003.JPG", 10, "c"),
};
var lasts = new List<LastCopy> { new("b", CopySide.ThisPc, "IMG_0002.JPG", 10) };
var lines = CopyDialogViewModel.ReplaceLines(lasts, trashed, "Studio NAS").Split(Environment.NewLine);
Assert.SequenceEqual(
[
Loc.L("Server.Copies.Plan.OnThisPc"),
" " + Loc.L("Server.Copies.Confirm.LastCopy", "IMG_0002.JPG"),
// A replaced version under an "Only copy:" line carries its own prefix (owner review 6, verification round 5).
" " + Loc.L("Server.Copies.Confirm.Replaced", "IMG_0001.JPG"),
Loc.L("Server.Copies.Plan.OnServer", "Studio NAS"),
" " + Loc.L("Server.Copies.Confirm.Replaced", "IMG_0003.JPG"),
], lines);
// To trash… and Delete on server…: the only copies first, the photos held elsewhere each with their prefix, once.
var trash = CopyDialogViewModel.Lines(lasts, ["IMG_0002.JPG", "IMG_0001.JPG", "IMG_0001.JPG"]).Split(Environment.NewLine);
Assert.SequenceEqual(
[
Loc.L("Server.Copies.Confirm.LastCopy", "IMG_0002.JPG"),
Loc.L("Server.Copies.Confirm.Elsewhere", "IMG_0001.JPG"),
], trash);
// A merge's facts are not photos held elsewhere: they carry no prefix, after the only copies.
var facts = CopyDialogViewModel.Lines(lasts, ["1 render moved"], elsewhere: false).Split(Environment.NewLine);
Assert.SequenceEqual(
[
Loc.L("Server.Copies.Confirm.LastCopy", "IMG_0002.JPG"),
"1 render moved",
], facts);
}
[Test]
public void AMergeNamesItsSidesByRoleAndAsksForAVersionOfEachDifferentPhoto()
{
// Class words: by role once a sequence is kept, oriented from the kept one; by place before.
var onlyHere = new CopyClassRow(new PhotoClassTotal(PhotoClass.OnlyHere, 38, 570_000_000, 0), CopyPhotoPolicy.Union, isMerge: true);
Assert.Equal(Loc.L("Server.Copies.Class.OnlyKept"), onlyHere.Text);
var raised = new List<string?>();
onlyHere.PropertyChanged += (_, e) => raised.Add(e.PropertyName);
onlyHere.Swapped = true;
Assert.Equal(Loc.L("Server.Copies.Class.OnlyOther"), onlyHere.Text);
Assert.Contains(nameof(CopyClassRow.Text), raised);
raised.Clear();
onlyHere.Places = ("Main archive", "Studio archive");
Assert.Equal(Loc.L("Server.Copies.Class.OnlyHere"), onlyHere.Text);
Assert.Contains(nameof(CopyClassRow.Text), raised);
Assert.Equal(Loc.L("Server.Copies.Class.DeletedOther"), CopyText.Class(PhotoClass.DeletedThere, merge: true));
Assert.Equal(Loc.L("Server.Copies.Class.Differs"), CopyText.Class(PhotoClass.Differs, merge: true));
Assert.Equal(Loc.L("Server.Copies.Class.OnlyHere"), new CopyClassRow(new PhotoClassTotal(PhotoClass.OnlyHere, 1, 1, 0)).Text);
// Choose each in a merge: its own tooltip, no Leave, and the unchosen block leads to the photos.
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.Differs.ChooseMerge"),
CopyText.ClassToolTip(PhotoClass.Differs, CopyPhotoPolicy.ChoosePerPhoto, isMerge: true));
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.Differs.Choose"), CopyText.ClassToolTip(PhotoClass.Differs, CopyPhotoPolicy.ChoosePerPhoto));
Assert.SequenceEqual([PhotoChoice.KeepBoth, PhotoChoice.TakeHere, PhotoChoice.TakeThere],
CopyDialogViewModel.VersionChoices(merge: true).Select(o => o.Value));
Assert.Contains(PhotoChoice.Leave, CopyDialogViewModel.VersionChoices(merge: false).Select(o => o.Value));
Assert.True(CopyText.HasChoose(CopyBlock.PhotosUnchosen));
// A version choice not made yet is read out as such, not as Leave.
var photo = new ComparedPhoto(PhotoClass.Differs, "k",
new CopyPhotoInput(Guid.NewGuid(), 0, "IMG_0004.JPG", "a", 10, null, false), new CopyPhotoInput(Guid.NewGuid(), 0, "IMG_0004.JPG", "b", 12, null, false),
1, 1, 10);
var row = new CopyPhotoRow(photo, isMerge: true, canBring: false, canChoose: true, CopyDialogViewModel.VersionChoices(true), null, () => { }, null);
Assert.Equal(Loc.L("Server.Copies.ControlFor", "IMG_0004.JPG", Loc.L("Server.Copies.Version.None")), row.ChoiceAccessibleName);
Assert.False(row.InMain);
}
[Test]
public void ThePairWordsFollowWhatTheRunReallyDoes()
{
// An Integrate that left photos out moves new photos only by hand; one that left nothing out, by itself.
Assert.Equal(Loc.L("Tooltips.Server.Copies.State.IntegratedByHand"), CopyText.State(Copy(CopyState.Integrated)).ToolTip);
Assert.Equal(Loc.L("Tooltips.Server.Copies.State.Integrated"), CopyText.State(Copy(CopyState.Integrated) with { AutoPhotos = true }).ToolTip);
// A pair of this PC's archives is merged, with the same "x of y".
var (_, text, tip) = CopyText.State(Copy(CopyState.Integrating, CopyKind.LocalLocal), progress: (1, 4));
Assert.Equal(Loc.L("Server.Copies.State.Merging", "25"), text);
Assert.Equal(string.Join(Environment.NewLine, Loc.L("Tooltips.Server.Copies.State.Merging"), Loc.L("Server.Copies.State.Progress", "1", "4")), tip);
// The row follows a merge's progress as it follows an Integrate's.
Assert.True(CopyListViewModel.Follows(JobKind.MergeSequences));
Assert.True(CopyListViewModel.Follows(JobKind.Integrate));
Assert.False(CopyListViewModel.Follows(JobKind.UploadCommit));
// A class says what the chosen policy does with it, and a merge says it its own way.
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.Differs"), CopyText.ClassToolTip(PhotoClass.Differs));
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.Differs.ThisPcWins"), CopyText.ClassToolTip(PhotoClass.Differs, CopyPhotoPolicy.ThisPcWins));
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.Differs.KeptWins"), CopyText.ClassToolTip(PhotoClass.Differs, CopyPhotoPolicy.ThisPcWins, isMerge: true));
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.OnlyHere.Choose"), CopyText.ClassToolTip(PhotoClass.OnlyHere, CopyPhotoPolicy.ChoosePerPhoto));
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.OnlyThere.Merge"), CopyText.ClassToolTip(PhotoClass.OnlyThere, CopyPhotoPolicy.ChoosePerPhoto, isMerge: true));
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.SameUnhashed.Integrate"), CopyText.ClassToolTip(PhotoClass.SameUnhashed));
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.SameUnhashed"), CopyText.ClassToolTip(PhotoClass.SameUnhashed, isMerge: true));
// The class row follows the dialog's policy, and a merge keeping the other sequence reads its classes from the kept side.
var differs = new CopyClassRow(new PhotoClassTotal(PhotoClass.Differs, 2, 51_400_000, 51_800_000));
differs.Policy = CopyPhotoPolicy.OtherWins;
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.Differs.OtherWins"), differs.ToolTip);
var onlyHere = new CopyClassRow(new PhotoClassTotal(PhotoClass.OnlyHere, 38, 570_000_000, 0), CopyPhotoPolicy.Union, isMerge: true) { Swapped = true };
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.OnlyThere.Merge"), onlyHere.ToolTip);
// The size cell shows the bytes of the side that holds them; both sides in the tooltip when both do.
var onlyThere = new CopyClassRow(new PhotoClassTotal(PhotoClass.OnlyThere, 3, 0, 45_000_000));
Assert.Equal(Formatting.Bytes(45_000_000), onlyThere.BytesText);
Assert.Equal(Loc.L("Server.Copies.Detail.Server") + " " + Formatting.Bytes(45_000_000), onlyThere.BytesToolTip);
Assert.Equal(Formatting.Bytes(51_400_000), differs.BytesText);
Assert.Equal(string.Join(Loc.Separator, Loc.L("Server.Copies.Detail.ThisPc") + " " + Formatting.Bytes(51_400_000),
Loc.L("Server.Copies.Detail.Server") + " " + Formatting.Bytes(51_800_000)), differs.BytesToolTip);
}
[Test]
public void ASyncRowOfAPairWhoseMatchDeletedPhotosSaysSoAndOffersReview()
{
var entry = Entry(SyncStatus.InSync);
var editor = SyncRights.Of((long)RolePermissions.Default(UserRole.Editor));
foreach (var state in new[] { CopyState.Linked, CopyState.Integrated })
{
var mark = new SyncMark(Copy(state, deletedThere: 3), null);
Assert.Equal((StatusKind.Warning, Loc.L("Server.Copies.State.DeletedThere", "3"), Loc.Plural("Tooltips.Server.Copies.State.DeletedThere", 3)),
SyncText.State(entry, mark));
Assert.SequenceEqual([SyncAction.Compare, SyncAction.Review], SyncText.Actions(entry, editor, mark).TakeLast(2));
Assert.False(string.IsNullOrWhiteSpace(SyncText.ToolTip(entry, SyncAction.Review)));
}
// Nothing deleted: the ordinary sync state, Compare last.
Assert.Equal(SyncText.State(entry), SyncText.State(entry, new SyncMark(Copy(CopyState.Linked), null)));
Assert.Equal(SyncAction.Compare, SyncText.Actions(entry, editor, new SyncMark(Copy(CopyState.Linked), null))[^1]);
}
[Test]
public void TheMatchStatusComesRightAfterTheAnalysisStatus()
{
var analysed = new Chronos.Ui.Visuals.CardStatus(StatusKind.Analysed, "Analysed");
var proxies = new Chronos.Ui.Visuals.CardStatus(StatusKind.Done, "Proxies");
var synced = new Chronos.Ui.Visuals.CardStatus(StatusKind.Synced, "Synced");
var match = new Chronos.Ui.Visuals.CardStatus(StatusKind.Warning, "Also elsewhere");
Assert.SequenceEqual([analysed, match, proxies, synced], Chronos.App.Library.SequenceItem.WithMatch([analysed, proxies, synced], match));
Assert.SequenceEqual([analysed, proxies], Chronos.App.Library.SequenceItem.WithMatch([analysed, proxies], null));
}
[Test]
public void TheMatchWordsNeverUseTheNounCopy()
{
// Design §1.1: the duplicates report owns "copy/copie"; a match is a sequence twice. The photo-level "last copy"
// and the verb "copy" stay.
string[] areas = ["Server.Copies.", "Server.Sync.Skip.", "Server.Sync.State.", "Library.Status.", "Settings.Copy", "Errors.Copies."];
string[] allowed =
[
"Server.Copies.Projects.CopyAcross", "Server.Copies.Plan.LastCopies.one", "Server.Copies.Plan.LastCopies.other",
"Server.Copies.Confirm.LastCopy", "Tooltips.Server.Copies.ToTrashSequence", "Tooltips.Server.Copies.Bring",
];
var noun = new System.Text.RegularExpressions.Regex(@"\b(copy|copie)\b", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
var found = new List<string>();
foreach (var culture in new[] { "en", "it" })
{
foreach (var file in Directory.EnumerateFiles(Path.Combine(TestContext.RepositoryRoot, "i18n", culture), "*.resx"))
{
foreach (var data in System.Xml.Linq.XDocument.Load(file).Root!.Elements("data"))
{
var name = (string)data.Attribute("name")!;
var bare = name.StartsWith("Tooltips.", StringComparison.Ordinal) ? name["Tooltips.".Length..] : name;
if (!areas.Any(a => bare.StartsWith(a, StringComparison.Ordinal)) || allowed.Contains(name)) continue;
if (noun.IsMatch((string?)data.Element("value") ?? string.Empty)) found.Add($"{culture}: {name}");
}
}
}
Assert.Empty(found);
}
[Test]
public void APlanCountsAsSecondVersionsOnlyThoseKeptBesideTheirPair()
{
// Union keeps "a" beside its pair; This PC wins replaces "b" (its loser goes to the trash on the same side).
var steps = new List<PhotoStep>
{
new("a", PhotoAction.SendVersion, Guid.NewGuid(), "IMG_0001.JPG", 10, "a"),
new("b", PhotoAction.SendVersion, Guid.NewGuid(), "IMG_0002.JPG", 10, "b"),
new("b", PhotoAction.TrashThere, Guid.NewGuid(), "IMG_0002.JPG", 10, "b2"),
new("c", PhotoAction.FetchVersion, Guid.NewGuid(), "IMG_0003.JPG", 10, "c"),
new("c", PhotoAction.TrashHere, Guid.NewGuid(), "IMG_0003.JPG", 10, "c2"),
};
Assert.Equal(1, CopyDialogViewModel.KeptVersions(steps, PhotoAction.SendVersion, PhotoAction.TrashThere));
Assert.Equal(0, CopyDialogViewModel.KeptVersions(steps, PhotoAction.FetchVersion, PhotoAction.TrashHere));
}
[Test]
public void TheMergesTypedConfirmationIsTheCountWithoutSeparatorsAndThePromptNamesIt()
{
// 1,204 photos: what to type has no group separator in any language ("1.204" in Italian), and the prompt says it.
foreach (var culture in new[] { "en", "it", "de", "hu" })
{
Loc.SetCulture(CultureInfo.GetCultureInfo(culture));
try
{
Assert.Equal("1204", CopyDialogViewModel.MergeTyped(1_204));
var prompt = CopyDialogViewModel.MergeTypedPrompt(1_204, "Alps 2026");
Assert.Contains("1204", prompt);
Assert.Contains("Alps 2026", prompt);
}
finally
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
}
}
[Test]
public void TheSessionKeysTooltipNamesTheKeysThatStayOnlyWhenThereAreAny()
{
Assert.Equal(Loc.L("Tooltips.Server.Copies.Plan.SessionKeys"), CopyDialogViewModel.SessionKeysToolTip([]));
var kept = CopyDialogViewModel.SessionKeysToolTip(["card:A1", "folder:B2"]);
Assert.False(kept.Contains("{0}", StringComparison.Ordinal), "no placeholder is left in the text");
Assert.Contains("card:A1", kept);
Assert.Contains("folder:B2", kept);
}
[Test]
public void AMatchRowTrimsALongArchiveNameInItsMiddleAndItsTooltipSaysItWhole()
{
Assert.Equal("Main archive", CopyText.MiddleTrim("Main archive", CopyText.RowNameLength));
var name = "ChronosArchive-Photos-2026-Studio NAS backup";
var trimmed = CopyText.MiddleTrim(name, CopyText.RowNameLength);
Assert.LessOrEqual(trimmed.Length, CopyText.RowNameLength);
Assert.True(trimmed.StartsWith("ChronosArch", StringComparison.Ordinal) && trimmed.EndsWith("NAS backup", StringComparison.Ordinal), trimmed);
Assert.Contains("…", trimmed);
var facts = Facts("Lighthouse", name, 1_204);
Assert.Contains(trimmed, CopyText.Where(facts, isServer: false, maxName: CopyText.RowNameLength));
Assert.Contains(name, CopyText.Where(facts, isServer: false));
}
private static (StatusKind, string) Head((StatusKind Kind, string Text, string ToolTip) state) => (state.Kind, state.Text);
private static FoundCopy Copy(CopyState state, CopyKind kind = CopyKind.LocalServer, int deletedThere = 0, bool gone = false) => new()
{
Id = Guid.CreateVersion7(),
Kind = kind,
LocalId = Local.Id,
Server = kind == CopyKind.LocalServer ? Nas : null,
RemoteId = kind == CopyKind.LocalServer ? Link.RemoteId : null,
OtherId = kind == CopyKind.LocalLocal ? Guid.CreateVersion7() : null,
Evidence = CopyEvidence.Hashes,
State = state,
Score = Score(deletedThere: deletedThere),
Fingerprint = "f",
RemoteGoneHits = gone ? 2 : 0,
UpdatedAt = new DateTimeOffset(2026, 11, 16, 9, 0, 0, TimeSpan.Zero),
};
private static CopyScore Score(int deletedThere = 0, int hints = 500) =>
new(1_178, 0, 0, 24, 0, 2, 0, deletedThere, 0, 1_204, 1_180, 980, 960, hints);
private static FoundCopyView View(FoundCopy copy, string title) =>
new(copy, Facts(title, "Main archive", 1_204), Facts(title + " (nas)", "Studio NAS", 1_180));
private static CopyFacts Facts(string title, string where, int photos) =>
new(title, where, null, photos, photos * 15_000_000L, null, null, null, photos, null, [], false);
private static SyncEntry Entry(SyncStatus status, SyncLink? link = null) =>
new(Local, status == SyncStatus.LocalOnly ? link : link ?? Link, status, null);
}
@@ -0,0 +1,100 @@
using Chronos.App.Server;
using Chronos.Core.Model;
using Chronos.Testing;
namespace Chronos.App.Tests.Server;
/// <summary>
/// The local detection that runs by itself (owner review 6, #73; design §3.4): once after the index opened, after a job that
/// changes photos ended, one at a time, and the requests that arrive meanwhile coalesce into one more.
/// </summary>
public sealed class CopyWatchTests
{
private static readonly TimeSpan Deadline = TimeSpan.FromSeconds(30);
private static readonly CopyWatchOptions Quick = new() { StartDelay = TimeSpan.FromMilliseconds(20), AfterJobDelay = TimeSpan.FromMilliseconds(50) };
private static Job Ended(JobKind kind, JobState state = JobState.Done) => new()
{
Id = Guid.CreateVersion7(),
Kind = kind,
State = state,
Created = DateTimeOffset.UtcNow,
};
private static async Task WaitAsync(Func<bool> condition, string what)
{
var until = DateTime.UtcNow + Deadline;
while (!condition())
{
if (DateTime.UtcNow > until) Assert.Fail($"timed out waiting for {what}");
await Task.Delay(10);
}
}
[Test]
public async Task ItLooksOnceAfterStartAndAfterAJobThatChangesPhotos()
{
var runs = 0;
await using var watch = new CopyWatch(_ =>
{
Interlocked.Increment(ref runs);
return Task.CompletedTask;
}, Quick);
watch.Start(null);
await WaitAsync(() => watch.Runs == 1, "the first detection");
watch.OnJobChanged(Ended(JobKind.Render));
watch.OnJobChanged(Ended(JobKind.Scan, JobState.Running));
await Task.Delay(200);
Assert.Equal(1, watch.Runs, "a render, or a scan still running, asks for none");
watch.OnJobChanged(Ended(JobKind.Scan));
watch.OnJobChanged(Ended(JobKind.Import, JobState.Failed));
watch.OnJobChanged(Ended(JobKind.MergeSequences, JobState.Cancelled));
await WaitAsync(() => watch.Runs == 2, "the detection after the jobs");
await Task.Delay(200);
Assert.Equal(2, Volatile.Read(ref runs), "jobs that end close together ask for one detection");
}
[Test]
public async Task RequestsWhileOneRunsGiveExactlyOneMore()
{
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var running = 0;
var overlapped = false;
await using var watch = new CopyWatch(async _ =>
{
if (Interlocked.Increment(ref running) > 1) overlapped = true;
await release.Task;
Interlocked.Decrement(ref running);
}, Quick with { StartDelay = TimeSpan.Zero, AfterJobDelay = TimeSpan.Zero });
watch.Start(null);
await WaitAsync(() => Volatile.Read(ref running) == 1, "the first detection to start");
foreach (var kind in CopyWatch.Triggers) watch.OnJobChanged(Ended(kind));
await Task.Delay(100);
release.TrySetResult();
await WaitAsync(() => watch.Runs == 2, "the one more detection");
await Task.Delay(200);
Assert.Equal(2, watch.Runs);
Assert.False(overlapped, "never two at once");
}
[Test]
public async Task AFailedDetectionDoesNotStopTheWatch()
{
var calls = 0;
await using var watch = new CopyWatch(_ => Interlocked.Increment(ref calls) == 1 ? throw new InvalidOperationException("index busy") : Task.CompletedTask,
Quick);
watch.Start(null);
await WaitAsync(() => watch.Runs == 1, "the failed detection");
watch.OnJobChanged(Ended(JobKind.Download));
await WaitAsync(() => watch.Runs == 2, "the next detection");
Assert.Equal(2, Volatile.Read(ref calls));
}
}
@@ -169,6 +169,21 @@ public sealed class SyncTextTests
Assert.Contains("403 forbidden", tip);
}
[Test]
public void PhotosThatFailedToMoveThreeTimesReadNotSentWithTheReason()
{
// Owner review 6 (#73), design §7.3: automatic photos of an integrated pair failed NotSentAfter times in a row.
var entry = Entry(SyncStatus.InSync);
var told = SyncText.State(entry, new SyncMark(null, null, NotSent: new AutoPhotoFailure(SyncAgent.NotSentAfter, "Quota reached")));
Assert.Equal((StatusKind.Warning, Loc.L("Server.Sync.State.NotSent")), (told.Kind, told.Text));
Assert.Equal(Loc.L("Tooltips.Server.Sync.State.NotSent", "Quota reached"), told.ToolTip);
// Fewer failures are still retried quietly; a transfer running now wins.
Assert.Equal(SyncText.State(entry), SyncText.State(entry, new SyncMark(null, null, NotSent: new AutoPhotoFailure(SyncAgent.NotSentAfter - 1, "Quota reached"))));
var moving = Entry(SyncStatus.Transferring, transfer: Upload(JobState.Running));
Assert.Equal(SyncText.State(moving), SyncText.State(moving, new SyncMark(null, null, NotSent: new AutoPhotoFailure(SyncAgent.NotSentAfter, "x"))));
}
[Test]
public void FiltersAndSearchSelectRows()
{
@@ -1,3 +1,4 @@
using System.IO;
using Chronos.App.Server;
using Chronos.Core.Model;
using Chronos.Data.Archiving.Jobs;
@@ -8,7 +9,7 @@ namespace Chronos.App.Tests.Server;
/// <summary>
/// Which jobs "Pause metered transfers" holds (Server.html, phase 5c): uploads, the sync's downloads, and the workspace's copies from and renders
/// sent to a server; never a copy from or a send to this PC's archive.
/// sent to a server, and the integrations of pairs with a server sequence; never a copy from or a send to this PC's archive, nor a merge.
/// </summary>
public sealed class UploadHoldTests
{
@@ -46,9 +47,104 @@ public sealed class UploadHoldTests
Assert.True(UploadHold.Holds(Of(JobKind.Download)));
Assert.True(UploadHold.Holds(Of(WorkspaceJobs.CopyFromServer(SequenceId, "Harbour", Server, Root, ProjectId))));
Assert.True(UploadHold.Holds(Of(WorkspaceJobs.Send(SequenceId, "Harbour", Root, ProjectId, [], Server))));
Assert.SequenceEqual([JobKind.UploadCommit, JobKind.Download, JobKind.WorkspaceCopy, JobKind.WorkspaceSend], UploadHold.Kinds);
Assert.SequenceEqual([JobKind.UploadCommit, JobKind.Download, JobKind.WorkspaceCopy, JobKind.WorkspaceSend, JobKind.Integrate], UploadHold.Kinds);
}
[Test]
public void AnIntegrationIsHeldAMergeIsNot()
{
// An integration always moves photos with a server (owner review 6, #73); a merge of two local sequences never does.
Assert.True(UploadHold.Holds(Of(JobKind.Integrate)));
Assert.False(UploadHold.Holds(Of(JobKind.MergeSequences)));
}
[Test]
public void AnAutomaticTransferIsHeldOnAMeteredConnectionWithTheOptionOff()
{
// Owner review 6, Q6: new photos of an integrated pair move by themselves, "paused on metered connections".
var automatic = Of(JobKind.Download, $$"""{"server":"{{Server}}","mode":"Originals","automatic":true}""");
var manual = Of(JobKind.Download, $$"""{"server":"{{Server}}","mode":"Originals"}""");
Assert.True(Chronos.Data.Sync.SyncService.IsAutomaticTransfer(automatic));
Assert.False(Chronos.Data.Sync.SyncService.IsAutomaticTransfer(manual));
Assert.True(UploadHold.HeldNow(automatic, metered: true, optionOn: false));
Assert.False(UploadHold.HeldNow(manual, metered: true, optionOn: false));
Assert.True(UploadHold.HeldNow(manual, metered: true, optionOn: true));
Assert.False(UploadHold.HeldNow(automatic, metered: false, optionOn: true));
// An automatic upload too.
Assert.True(UploadHold.HeldNow(Of(JobKind.UploadCommit, $$"""{"server":"{{Server}}","automatic":true}"""), metered: true, optionOn: false));
}
/// <summary>A fresh index in a temporary folder and its job engine (not started).</summary>
private static async Task HoldScenarioAsync(Func<Chronos.Data.ChronosDatabase, Chronos.Data.Jobs.JobEngine, Task> body)
{
var folder = Path.Combine(Path.GetTempPath(), "chronos-hold-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(folder);
try
{
await using var db = await Chronos.Data.ChronosDatabase.OpenAsync(Chronos.Data.DatabaseOptions.Sqlite(Path.Combine(folder, "index.db")));
await using var engine = new Chronos.Data.Jobs.JobEngine(db, [], new Chronos.Data.Jobs.JobEngineOptions { Workers = 1, WorkerId = "test" });
await body(db, engine);
}
finally
{
try
{
Directory.Delete(folder, recursive: true);
}
catch (IOException)
{
}
}
}
[Test]
public Task ATransferTheHoldPausedBeforeARestartResumesOnceTheConnectionIsNotMetered() => HoldScenarioAsync(async (db, engine) =>
{
var automatic = Of(JobKind.Download, $$"""{"server":"{{Server}}","mode":"Originals","automatic":true}""");
var userPaused = Of(JobKind.Download, $$"""{"server":"{{Server}}","mode":"Originals","automatic":true}""");
await db.Jobs.EnqueueAsync(automatic);
await db.Jobs.EnqueueAsync(userPaused);
// The user paused this one before the connection became metered: the hold never paused it.
await db.Jobs.SetStateAsync(userPaused.Id, JobState.Paused, null);
using (var before = new UploadHold(() => db, () => false, () => true))
{
before.Attach(engine);
await before.ApplyAsync();
Assert.Equal(JobState.Paused, (await db.Jobs.GetAsync(automatic.Id))!.State);
}
// A new hold after a restart reads the record the first one kept in the index.
using var hold = new UploadHold(() => db, () => false, () => false);
hold.Attach(engine);
await hold.ApplyAsync();
Assert.Equal(JobState.Queued, (await db.Jobs.GetAsync(automatic.Id))!.State);
// An automatic transfer the user paused stays paused: the hold resumes only what it paused.
Assert.Equal(JobState.Paused, (await db.Jobs.GetAsync(userPaused.Id))!.State);
Assert.Equal("[]", await db.Settings.GetJsonAsync(Chronos.Data.Repositories.SettingScope.App, null, UploadHold.RecordKey));
});
[Test]
public Task AJobTheUserPausesWhileHeldIsNeverResumedByTheHold() => HoldScenarioAsync(async (db, engine) =>
{
var automatic = Of(JobKind.UploadCommit, $$"""{"server":"{{Server}}","automatic":true}""");
await db.Jobs.EnqueueAsync(automatic);
var metered = true;
using var hold = new UploadHold(() => db, () => false, () => metered);
hold.Attach(engine);
await hold.ApplyAsync();
Assert.Equal(JobState.Paused, (await db.Jobs.GetAsync(automatic.Id))!.State);
// The user pauses it from Jobs (the queue tells the hold), then the connection is no longer metered.
using var queue = new Chronos.App.Jobs.EngineJobQueue(db, engine, started: false, acted: id => hold.ForgetAsync(id).GetAwaiter().GetResult());
await queue.PauseAsync(automatic.Id);
metered = false;
await hold.ApplyAsync();
Assert.Equal(JobState.Paused, (await db.Jobs.GetAsync(automatic.Id))!.State);
});
[Test]
public void TransfersWithThisPcsLibraryAndOtherJobsAreNot()
{
@@ -327,6 +327,36 @@ public sealed class SettingsLogicTests
Assert.Equal(ThreadPriority.Normal, InterfacePriority.For(enabled: false, active: true));
}
[Test]
public void ThePriorityQueueListsTheMatchesJobsUnderTheirOwnNames()
{
// Owner review 6 (#73): integrating with the server and merging two local copies are jobs the user may rank too.
var kinds = Chronos.App.Sections.SettingsViewModel.PriorityKinds;
Assert.Contains(Chronos.Core.Model.JobKind.Integrate, kinds);
Assert.Contains(Chronos.Core.Model.JobKind.MergeSequences, kinds);
Assert.Equal(kinds.Length, kinds.Distinct().Count());
foreach (var row in kinds.Select(k => new JobPriorityRow(k, _ => default, (_, _) => { }))
.Where(r => r.Kind is Chronos.Core.Model.JobKind.Integrate or Chronos.Core.Model.JobKind.MergeSequences))
{
Assert.False(string.IsNullOrWhiteSpace(row.Label) || row.Label.StartsWith("Jobs.Kind.", StringComparison.Ordinal), row.Label);
Assert.True(row.ToolTip.Contains(row.Label, StringComparison.Ordinal), row.ToolTip);
Assert.True(Loc.GetArea("Jobs", CultureInfo.GetCultureInfo("it")).ContainsKey("Jobs.Kind." + row.Kind), $"Italian name of {row.Kind}");
}
}
[Test]
public void TheMatchesStartFromTheOwnersDefaults()
{
// Owner review 6 (#73): ask before linking, keep every photo of both sides, copy the projects across.
var settings = new AppSettings();
Assert.Equal((Chronos.Data.Copies.CopyLinking.AskAlways, Chronos.Data.Copies.CopyPhotoPolicy.Union, Chronos.Data.Copies.CopyProjects.CopyAcross),
(settings.CopyLinking, settings.CopyPhotos, settings.CopyProjects));
var loaded = AppSettings.Parse("{}")!;
Assert.Equal((Chronos.Data.Copies.CopyLinking.AskAlways, Chronos.Data.Copies.CopyPhotoPolicy.Union, Chronos.Data.Copies.CopyProjects.CopyAcross),
(loaded.CopyLinking, loaded.CopyPhotos, loaded.CopyProjects));
Assert.Equal(Chronos.Data.Copies.CopyLinking.AskAlways, new Chronos.Data.Sync.SyncPolicy().Linking);
}
[Test]
public void FormatsShowTheirTierAndWhatToInstall()
{
@@ -0,0 +1,35 @@
using Microsoft.Win32;
namespace Chronos.App.Tests.Setup;
/// <summary>
/// Scratch keys under HKCU\Software\Chronos.Tests for the setup tests, which run in parallel: a key is created, and the
/// shared parent removed once empty, under one lock, so one test's cleanup never deletes the parent while another test
/// is creating its key under it.
/// </summary>
internal static class ScratchRegistry
{
private const string Root = @"Software\Chronos.Tests";
private static readonly Lock Gate = new();
/// <summary>Creates a new empty scratch key and returns its path under HKCU.</summary>
public static string Create()
{
var keyPath = Root + @"\" + Guid.NewGuid().ToString("N");
lock (Gate) Registry.CurrentUser.CreateSubKey(keyPath, writable: true).Dispose();
return keyPath;
}
/// <summary>Deletes a scratch key made by <see cref="Create"/>, and the shared parent too once it is empty.</summary>
public static void Delete(string keyPath)
{
lock (Gate)
{
Registry.CurrentUser.DeleteSubKeyTree(keyPath, throwOnMissingSubKey: false);
bool empty;
using (var tests = Registry.CurrentUser.OpenSubKey(Root)) empty = tests is { SubKeyCount: 0, ValueCount: 0 };
if (empty) Registry.CurrentUser.DeleteSubKey(Root, throwOnMissingSubKey: false);
}
}
}
@@ -16,8 +16,6 @@ namespace Chronos.App.Tests.Setup;
/// </summary>
public sealed class SetupEngineTests(TestContext context)
{
private const string TestsKey = @"Software\Chronos.Tests";
/// <summary>The StartupApproved state Task Manager writes for an entry it turned off.</summary>
private static readonly byte[] TurnedOff = [0x03, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
@@ -64,7 +62,7 @@ public sealed class SetupEngineTests(TestContext context)
{
var folder = Path.Combine(context.CreateTempDirectory("services"), "Apps");
var owned = CommandProgram.FullPaths(folder, ["Chronos.Server.exe", "Chronos.exe", "lib/Chronos.Core.dll"]);
var keyPath = TestsKey + @"\" + Guid.NewGuid().ToString("N");
var keyPath = ScratchRegistry.Create();
try
{
using var services = Registry.CurrentUser.CreateSubKey(keyPath, writable: true);
@@ -88,7 +86,7 @@ public sealed class SetupEngineTests(TestContext context)
}
finally
{
DeleteTestKey(keyPath);
ScratchRegistry.Delete(keyPath);
}
static void Service(RegistryKey services, string name, int type, string imagePath)
@@ -158,7 +156,7 @@ public sealed class SetupEngineTests(TestContext context)
public void UninstallRemovesOnlyTheSignInEntriesOfTheProgramsItRemoves()
{
var folder = Path.Combine(context.CreateTempDirectory("startup"), "Apps");
var keyPath = TestsKey + @"\" + Guid.NewGuid().ToString("N");
var keyPath = ScratchRegistry.Create();
try
{
using (var run = Registry.CurrentUser.CreateSubKey(keyPath + @"\Run", writable: true))
@@ -182,7 +180,7 @@ public sealed class SetupEngineTests(TestContext context)
}
finally
{
DeleteTestKey(keyPath);
ScratchRegistry.Delete(keyPath);
}
}
@@ -191,7 +189,6 @@ public sealed class SetupEngineTests(TestContext context)
public void AnUpgradeMovesTheSignInEntryOfARenamedProgramAndRemovesThatOfADroppedOne()
{
var folder = Path.Combine(context.CreateTempDirectory("upgrade"), "Apps");
var keyPath = TestsKey + @"\" + Guid.NewGuid().ToString("N");
// This version ships the client as Chronos.exe (the previous one as Chronos.old.exe), and the user left out the Uploader.
var manifest = Manifest();
manifest.Components.Add(new PayloadComponent { Id = "Uploader", DisplayName = "Chronos Uploader", DefaultSelected = true });
@@ -200,6 +197,7 @@ public sealed class SetupEngineTests(TestContext context)
var programs = InstallEngine.StartupPrograms(manifest, folder, ["Chronos", "Server"]);
Assert.SequenceEqual(["Chronos"], programs.Keys);
Assert.Equal(Path.Combine(folder, "Chronos.exe"), programs["Chronos"]);
var keyPath = ScratchRegistry.Create();
try
{
using (var run = Registry.CurrentUser.CreateSubKey(keyPath + @"\Run", writable: true))
@@ -226,7 +224,7 @@ public sealed class SetupEngineTests(TestContext context)
}
finally
{
DeleteTestKey(keyPath);
ScratchRegistry.Delete(keyPath);
}
}
@@ -344,15 +342,6 @@ public sealed class SetupEngineTests(TestContext context)
Assert.Equal("Something else", InstallEngine.FileTypeName(unknown, CultureInfo.GetCultureInfo("it")));
}
/// <summary>Deletes a scratch key under <see cref="TestsKey"/>, and that key too once it is empty.</summary>
private static void DeleteTestKey(string keyPath)
{
Registry.CurrentUser.DeleteSubKeyTree(keyPath, throwOnMissingSubKey: false);
bool empty;
using (var tests = Registry.CurrentUser.OpenSubKey(TestsKey)) empty = tests is { SubKeyCount: 0, ValueCount: 0 };
if (empty) Registry.CurrentUser.DeleteSubKey(TestsKey, throwOnMissingSubKey: false);
}
/// <summary>A manifest under a product name no machine has installed, so the registry holds no installation of it.</summary>
private static PayloadManifest Manifest() => new()
{
@@ -19,8 +19,6 @@ namespace Chronos.App.Tests.Setup;
/// </summary>
public sealed class SingleSetupTests(TestContext context)
{
private const string TestsKey = @"Software\Chronos.Tests";
/// <summary>The StartupApproved state Task Manager writes for an entry it turned off.</summary>
private static readonly byte[] TurnedOff = [0x03, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
@@ -223,7 +221,7 @@ public sealed class SingleSetupTests(TestContext context)
var programs = LegacyProducts.StartupPrograms(Manifest(), directory);
Assert.SequenceEqual(["Chronos Uploader"], programs.Keys);
var keyPath = TestsKey + @"\" + Guid.NewGuid().ToString("N");
var keyPath = ScratchRegistry.Create();
try
{
using var run = Registry.CurrentUser.CreateSubKey(keyPath + @"\Run", writable: true);
@@ -238,10 +236,7 @@ public sealed class SingleSetupTests(TestContext context)
}
finally
{
Registry.CurrentUser.DeleteSubKeyTree(keyPath, throwOnMissingSubKey: false);
bool empty;
using (var tests = Registry.CurrentUser.OpenSubKey(TestsKey)) empty = tests is { SubKeyCount: 0, ValueCount: 0 };
if (empty) Registry.CurrentUser.DeleteSubKey(TestsKey, throwOnMissingSubKey: false);
ScratchRegistry.Delete(keyPath);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,126 @@
using Chronos.Core.Import;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Testing;
using static Chronos.Data.Tests.Archiving.ArchiveFixture;
namespace Chronos.Data.Tests.Archiving;
/// <summary>
/// Trash steps run inside the job that holds the sequence (an Integrate or a merge, owner review 6, #73): the job's own hold
/// does not make the sequence busy, another job's still does, and a frames version that moved refuses the step.
/// </summary>
[Category("archive")]
public abstract class TrashExceptJobTests(TestContext context) : DatabaseTest(context)
{
private async Task<ArchiveFixture> FixtureAsync() => Own(await CreateAsync(Context, database: await NewOptionsAsync(multiConnection: true)));
private static async Task<Sequence> UploadedAsync(ArchiveFixture fx, int count, string session, int seed)
{
Guid? id = null;
for (var i = 0; i < count; i++)
{
var (path, size, sha) = fx.Stage(Start.AddSeconds(10 * i), seed + i);
var result = await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, id, null, id is null ? session : null, path, $"IMG_{i + 1:0000}.JPG",
size, sha, null, null), fx.Ct);
id = result.SequenceId;
}
return (await fx.Db.Sequences.GetAsync(id!.Value))!;
}
private static async Task<Job> RunningAsync(ArchiveFixture fx, JobKind kind, params Guid[] targets)
{
var job = new Job
{
Id = Guid.CreateVersion7(),
Kind = kind,
TargetIds = targets,
State = JobState.Running,
NodeId = "test#0",
Created = DateTimeOffset.UtcNow,
Started = DateTimeOffset.UtcNow,
};
await fx.Db.Jobs.EnqueueAsync(job);
return job;
}
[Test]
public async Task APhotoTrashStepInsideItsOwnJobIsNotBusyAnotherJobsTargetIs()
{
var fx = await FixtureAsync();
var sequence = await UploadedAsync(fx, 3, "upload-1", 100);
var frames = await fx.Db.Frames.ListBySequenceAsync(sequence.Id);
var trash = fx.Service.FrameTrash;
var integrate = await RunningAsync(fx, JobKind.Integrate, sequence.Id);
Assert.SequenceEqual([FrameDeleteBlock.Busy], (await trash.PlanDeleteAsync(sequence.Id, [frames[0].Id], sequence.FramesVersion, fx.Ct)).Blocked);
var plan = await trash.PlanDeleteAsync(sequence.Id, [frames[0].Id], sequence.FramesVersion, fx.Ct, exceptJob: integrate.Id);
Assert.True(plan.CanDelete, string.Join(", ", plan.Blocked));
// The re-plan of the deletion itself must not count the job either.
await Assert.ThrowsAsync<StaleDeletePlanException>(() => trash.DeleteAsync(plan, "alberto", null, fx.Ct));
var result = await trash.DeleteAsync(plan, "alberto", null, fx.Ct, exceptJob: integrate.Id);
Assert.Equal(sequence.Id, result.Sequence.Id);
Assert.Count(2, await fx.Db.Frames.ListBySequenceAsync(sequence.Id));
await RunningAsync(fx, JobKind.Render, sequence.Id);
var now = (await fx.Db.Sequences.GetAsync(sequence.Id))!;
var held = await trash.PlanDeleteAsync(sequence.Id, [frames[1].Id], now.FramesVersion, fx.Ct, exceptJob: integrate.Id);
Assert.SequenceEqual([FrameDeleteBlock.Busy], held.Blocked);
}
[Test]
public async Task ASequenceTrashStepInsideItsOwnJobIsNotBusyAnotherJobsTargetIs()
{
var fx = await FixtureAsync();
var keep = await UploadedAsync(fx, 2, "upload-1", 100);
var drop = await UploadedAsync(fx, 2, "upload-2", 200);
var merge = await RunningAsync(fx, JobKind.MergeSequences, keep.Id, drop.Id);
Assert.Equal(DeleteBlock.Busy, (await fx.Service.Trash.PlanAsync([drop.Id], null, fx.Ct)).Blocked.Single().Reason);
var plan = await fx.Service.Trash.PlanAsync([drop.Id], null, fx.Ct, exceptJob: merge.Id);
Assert.Empty(plan.Blocked);
// Revalidated without the job's own hold too.
await Assert.ThrowsAsync<StaleDeletePlanException>(() => fx.Service.Trash.DeleteAsync(plan, null, null, fx.Ct));
Assert.NotNull(await fx.Db.Sequences.GetAsync(drop.Id));
var entries = await fx.Service.Trash.DeleteAsync(plan, "alberto", null, fx.Ct, exceptJob: merge.Id,
expectedFramesVersions: new Dictionary<Guid, int> { [drop.Id] = drop.FramesVersion });
Assert.Count(1, entries);
Assert.Null(await fx.Db.Sequences.GetAsync(drop.Id));
await RunningAsync(fx, JobKind.Render, keep.Id);
Assert.Equal(DeleteBlock.Busy, (await fx.Service.Trash.PlanAsync([keep.Id], null, fx.Ct, exceptJob: merge.Id)).Blocked.Single().Reason);
}
[Test]
public async Task AFramesVersionThatMovedRefusesTheStepUnderItsLeaseAndNothingMoves()
{
var fx = await FixtureAsync();
var drop = await UploadedAsync(fx, 2, "upload-1", 100);
var plan = await fx.Service.Trash.PlanAsync([drop.Id], null, fx.Ct);
var folder = fx.Paths.Sequence(drop.Folder).Folder;
// A photo added since the version the caller verified.
await Assert.ThrowsAsync<StaleDeletePlanException>(() => fx.Service.Trash.DeleteAsync(plan, null, null, fx.Ct,
expectedFramesVersions: new Dictionary<Guid, int> { [drop.Id] = drop.FramesVersion - 1 }));
Assert.NotNull(await fx.Db.Sequences.GetAsync(drop.Id));
Assert.True(Directory.Exists(folder));
// A sequence the map does not name is not checked; the one it names at its version goes.
var entries = await fx.Service.Trash.DeleteAsync(plan, null, null, fx.Ct,
expectedFramesVersions: new Dictionary<Guid, int> { [Guid.CreateVersion7()] = 99, [drop.Id] = drop.FramesVersion });
Assert.Count(1, entries);
Assert.False(Directory.Exists(folder));
}
}
public sealed class SqliteTrashExceptJobTests(TestContext context) : TrashExceptJobTests(context)
{
protected override Backend Backend => Backend.SqliteFile;
}
[RequiresEnvironment(PgTestServer.Variable)]
public sealed class PostgresTrashExceptJobTests(TestContext context) : TrashExceptJobTests(context)
{
protected override Backend Backend => Backend.Postgres;
}
@@ -0,0 +1,592 @@
using System.Security.Cryptography;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Copies;
using Chronos.Data.Sync;
using Chronos.Data.Tests.Archiving;
using Chronos.Data.Tests.Sync;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Copies;
/// <summary>
/// The matches engine of a PC (owner review 6, #73; design §5, §6): what Find matches finds and tells, the facts listed,
/// Link, Unlink, Keep apart and Ask again, and the trash steps of photos one side deleted, re-checked when applied.
/// </summary>
[Category("sync")]
public sealed class CopyEngineTests(TestContext context)
{
private static readonly CopyPlanContext Context =
new("STUDIO-PC", "NAS", true, true, true, true, true, false, null, new HashSet<Guid>(), new HashSet<Guid>());
private static async Task<SyncFixture> FixtureAsync(TestContext context)
{
var f = await SyncFixture.CreateAsync(context);
f.Remote.Capabilities.Add(ServerCapabilities.UploadInto);
f.Remote.Capabilities.Add(ServerCapabilities.PhotoLookup);
return f;
}
private static CopyEngine Engine(SyncFixture f)
{
var sides = new CopySides(f.Db);
return new CopyEngine(f.Sync, f.Archive.Service, new IntegratePlanner(f.Sync, sides, f.Archive.Service.Projects),
new SequenceMerger(f.Db, f.Archive.Service, sides), new CopyReviewBuilder(f.Db, f.Archive.Service.Projects, sides), _ => Context,
serverNames: key => key == f.Server ? "NAS" : null);
}
private static string Sha(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
private static Task<FoundCopy> PairAsync(SyncFixture f, Guid localId, Guid remoteId) =>
f.Sync.Copies.UpsertFoundAsync(new FoundCopy
{
Id = Guid.NewGuid(),
Kind = CopyKind.LocalServer,
LocalId = localId,
Server = f.Server,
RemoteId = remoteId,
Evidence = CopyEvidence.Hashes,
Fingerprint = "f",
}, f.Ct);
/// <summary>A paused Integrate job of <paramref name="localId"/>: a pair naming it reads Integrating.</summary>
private static async Task<Guid> PausedIntegrateAsync(SyncFixture f, Guid localId)
{
var id = Guid.CreateVersion7();
await f.Db.Jobs.EnqueueAsync(new Job
{
Id = id,
Kind = JobKind.Integrate,
TargetIds = [localId],
State = JobState.Paused,
Created = DateTimeOffset.UtcNow,
}, f.Ct);
return id;
}
private static async Task<CopyState> StateAsync(SyncFixture f, Guid copyId) => (await f.Sync.Copies.GetAsync(copyId, f.Ct))!.State;
[Test]
public async Task FindMatchesTellsAndListsTheServerPairWithTheFactsOfBothSides()
{
await using var f = await FixtureAsync(context);
var photos = f.NewPhotos(4);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet (selection)", photos.Take(2));
using var engine = Engine(f);
var told = new List<CopyFindResult>();
engine.Found += told.Add;
var result = await engine.FindAsync(f.Remote, f.Ct);
var pair = result.New.Single();
Assert.Equal((local.Id, remote.Id), (pair.LocalId, pair.RemoteId!.Value));
Assert.True(told.Any(t => t.New.Any(n => n.Id == pair.Id)));
var view = (await engine.ListAsync(f.Ct)).Single();
Assert.Equal(("Comet", 4, 4), (view.Here.Title, view.Here.Photos, view.Here.Hashed));
Assert.Equal(("Comet (selection)", "NAS", 2), (view.There.Title, view.There.Where, view.There.Photos));
}
[Test]
public async Task FindMatchesWithoutAServerLooksAmongThisPcsArchives()
{
await using var f = await FixtureAsync(context);
var photos = f.NewPhotos(3);
var first = await f.LocalAsync("Comet", photos);
var second = await f.LocalAsync("Comet copy", photos);
using var engine = Engine(f);
var result = await engine.FindAsync(null, f.Ct);
var pair = result.New.Single();
Assert.Equal(CopyKind.LocalLocal, pair.Kind);
Assert.SequenceEqual(new[] { first.Id, second.Id }.Order(), new[] { pair.LocalId, pair.OtherId!.Value }.Order());
// Asked again later, the pair already known is not new.
Assert.True((await engine.FindLocalAsync(f.Ct)).New.Count == 0);
}
[Test]
public async Task LinkUnlinkKeepApartAndAskAgainMoveThePair()
{
await using var f = await FixtureAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet NAS", photos.Take(2));
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.AskAlways });
var pair = (await f.Sync.Copies.ListAsync(f.Ct)).Single();
using var engine = Engine(f);
await engine.LinkAsync(pair.Id, f.Remote, f.Ct);
Assert.Equal(CopyState.Linked, await StateAsync(f, pair.Id));
Assert.Equal(remote.Id, (await f.Sync.LinkOfAsync(f.Server, local.Id, f.Ct))!.RemoteId);
await engine.UnlinkAsync(pair.Id, f.Remote, f.Ct);
Assert.Equal(CopyState.KeptApart, await StateAsync(f, pair.Id));
Assert.Null(await f.Sync.LinkOfAsync(f.Server, local.Id, f.Ct));
await engine.AskAgainAsync(pair.Id, f.Ct);
Assert.Equal(CopyState.Candidate, await StateAsync(f, pair.Id));
await engine.KeepApartAsync(pair.Id, f.Ct);
var kept = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
Assert.Equal(CopyState.KeptApart, kept.State);
Assert.False(kept.IsListed && kept.State == CopyState.Candidate);
}
[Test]
public async Task UnlinkOfAPairThatNoLongerHoldsTheLinkLeavesTheOtherPairsLinkAndIntegration()
{
await using var f = await FixtureAsync(context);
var photos = f.NewPhotos(2);
var first = await f.LocalAsync("Comet", photos);
var second = await f.LocalAsync("Comet copy", photos);
var remote = f.Remote.Add("Comet NAS", photos);
// (second, R) was unlinked earlier; then (first, R) was linked and its Integrate began.
var old = await PairAsync(f, second.Id, remote.Id);
await f.Sync.Copies.SetStateAsync(old.Id, null, CopyState.KeptApart, null, f.Ct);
await f.Sync.LinkAsync(f.Server, remote.Id, first.Id, f.Ct);
var linked = await f.Sync.Copies.EnsureLinkedAsync(f.Server, remote.Id, first.Id, f.Ct);
var job = await PausedIntegrateAsync(f, first.Id);
Assert.True(await f.Sync.Copies.SetStateAsync(linked.Id, null, CopyState.Integrating, new CopyAnswer(null, null, job, null, DateTimeOffset.UtcNow), f.Ct));
using var engine = Engine(f);
// The stale row still offers Unlink.
await engine.UnlinkAsync(old.Id, f.Remote, f.Ct);
Assert.Equal(CopyState.KeptApart, await StateAsync(f, old.Id));
Assert.Equal(first.Id, (await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct))!.LocalId);
var integrating = (await f.Sync.Copies.GetAsync(linked.Id, f.Ct))!;
Assert.Equal((CopyState.Integrating, (Guid?)job), (integrating.State, integrating.JobId));
// The pair being integrated refuses an Unlink of its own.
await Assert.ThrowsAsync<InvalidOperationException>(() => engine.UnlinkAsync(linked.Id, f.Remote, f.Ct));
await Assert.ThrowsAsync<InvalidOperationException>(() => f.Sync.UnlinkAsync(f.Server, remote.Id, first.Id, f.Ct));
Assert.Equal(first.Id, (await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct))!.LocalId);
}
[Test]
public async Task KeepApartOfALinkedPairUnlinksIt()
{
await using var f = await FixtureAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet NAS", photos);
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.AskAlways });
var pair = (await f.Sync.Copies.ListAsync(f.Ct)).Single();
using var engine = Engine(f);
await engine.LinkAsync(pair.Id, f.Remote, f.Ct);
await engine.KeepApartAsync(pair.Id, f.Ct);
Assert.Equal(CopyState.KeptApart, await StateAsync(f, pair.Id));
Assert.Null(await f.Sync.LinkOfAsync(f.Server, local.Id, f.Ct));
Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct));
}
[Test]
public async Task KeepHereOfASequenceDeletedOnTheServerIsLeftOutOfUploadAllLocal()
{
await using var f = await FixtureAsync(context);
var local = await f.LocalAsync("Comet", f.NewPhotos(2));
var gone = Guid.CreateVersion7();
var pair = await f.Sync.Copies.EnsureLinkedAsync(f.Server, gone, local.Id, f.Ct);
// Deleted on the server: two 404s the re-check apart, read as deleted on server.
var at = DateTimeOffset.UtcNow.AddHours(-2);
await f.Sync.Copies.MarkRemoteGoneAsync(f.Server, gone, local.Id, Guid.NewGuid(), at, f.Ct);
await f.Sync.Copies.MarkRemoteGoneAsync(f.Server, gone, local.Id, Guid.NewGuid(), at.AddHours(1), f.Ct);
using var engine = Engine(f);
await engine.KeepHereAsync(pair.Id, f.Ct);
// Kept here: Upload all local leaves it out, and the answer stays.
var row = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
Assert.Equal((CopyState.KeptApart, true), (row.State, row.RemoteGone));
var entry = new SyncEntry(local, null, SyncStatus.LocalOnly);
var (upload, skipped) = UploadAllRule.Select([entry], await f.Sync.Copies.ListAsync(f.Ct), new HashSet<Guid>(), new HashSet<Guid>());
Assert.Empty(upload);
Assert.Equal(local.Id, skipped.Single().Entry.Local!.Id);
}
[Test]
public async Task LinkIsRefusedWhenTheLocalCopyIsLinkedToAnotherServerSequence()
{
await using var f = await FixtureAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos);
var linked = f.Remote.Add("Comet", photos);
var other = f.Remote.Add("Comet selection", photos.Take(2));
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.AskAlways });
await f.Sync.LinkAsync(f.Server, linked.Id, local.Id, f.Ct);
var pair = await PairAsync(f, local.Id, other.Id);
using var engine = Engine(f);
await Assert.ThrowsAsync<CopyLinkTakenException>(() => engine.LinkAsync(pair.Id, f.Remote, f.Ct));
Assert.Equal(linked.Id, (await f.Sync.LinkOfAsync(f.Server, local.Id, f.Ct))!.RemoteId);
Assert.Equal(CopyState.Candidate, await StateAsync(f, pair.Id));
}
[Test]
public async Task TrashHereMovesWhatTheServerDeletedAndRefusesAPhotoRestoredThere()
{
await using var f = await FixtureAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet NAS", photos);
var pair = await PairAsync(f, local.Id, remote.Id);
using var engine = Engine(f);
var (gone, restored) = (remote.Frames[1], remote.Frames[2]);
await f.Remote.DeleteFramesAsync(remote.Id, new FrameDeleteRequest([gone.Id, restored.Id], null, false), f.Ct);
var trash = await engine.PlanTrashHereAsync(pair.Id, local.Id, [Sha(photos[1]), Sha(photos[2])], f.Ct);
var (plan, lasts) = trash;
Assert.Equal(2, plan.Frames.Count);
// No other sequence of this PC holds them: the trash takes their last copies, and the confirmation says so.
Assert.SequenceEqual(new[] { Sha(photos[1]), Sha(photos[2]) }.Order(StringComparer.Ordinal), lasts.Select(l => l.Key).Order(StringComparer.Ordinal));
// Restored on the server after the dry run: nothing moves, all or nothing.
remote.AddFrame(photos[2], restored.FileName);
await Assert.ThrowsAsync<StaleCopyPlanException>(() => engine.TrashHereAsync(pair.Id, trash, f.Remote, f.Ct));
Assert.Count(3, await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct));
var again = await engine.PlanTrashHereAsync(pair.Id, local.Id, [Sha(photos[1])], f.Ct);
Assert.Equal(1, await engine.TrashHereAsync(pair.Id, again, f.Remote, f.Ct));
var left = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
Assert.SequenceEqual(new[] { Sha(photos[0]), Sha(photos[2]) }.Order(StringComparer.Ordinal), left.Select(fr => fr.Sha256!).Order(StringComparer.Ordinal));
}
[Test]
public async Task TrashThereSendsThePlansVersionAndAStalePlanMovesNothing()
{
await using var f = await FixtureAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet NAS", photos);
var pair = await PairAsync(f, local.Id, remote.Id);
using var engine = Engine(f);
var frames = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
var deleted = frames.Single(fr => fr.Sha256 == Sha(photos[2]));
var sequence = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
var local3 = await f.Archive.Service.FrameTrash.PlanDeleteAsync(local.Id, [deleted.Id], sequence.FramesVersion, f.Ct);
await f.Archive.Service.FrameTrash.DeleteAsync(local3, "test", null, f.Ct);
var plan = await engine.PlanTrashThereAsync(pair.Id, f.Remote, [Sha(photos[2])], f.Ct);
Assert.Equal((1, remote.FramesVersion), (plan.Photos, plan.FramesVersion));
// The photo is in this PC's trash only: the server's is its last copy.
Assert.Count(1, plan.LastCopies);
remote.AddFrame(f.NewPhotos(1)[0], "IMG_0009.JPG");
await Assert.ThrowsAsync<StaleCopyPlanException>(() => engine.TrashThereAsync(plan, f.Remote, f.Ct));
Assert.Count(0, f.Remote.Trashed);
var fresh = await engine.PlanTrashThereAsync(pair.Id, f.Remote, [Sha(photos[2])], f.Ct);
Assert.Equal(1, await engine.TrashThereAsync(fresh, f.Remote, f.Ct));
Assert.Equal(Sha(photos[2]), f.Remote.Trashed.Single().Frame.Sha256);
}
[Test]
public async Task TrashHereNamesNoLastCopyForAPhotoAnotherSequenceHolds()
{
await using var f = await FixtureAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos[..2]);
// The backup holds photo 1 and one of its own (a sequence keeps at least one frame).
var backup = await f.LocalAsync("Comet backup", [photos[1], photos[2]]);
var remote = f.Remote.Add("Comet NAS", photos[..2]);
var pair = await PairAsync(f, local.Id, remote.Id);
using var engine = Engine(f);
await f.Remote.DeleteFramesAsync(remote.Id, new FrameDeleteRequest([remote.Frames[1].Id], null, false), f.Ct);
var plan = await engine.PlanTrashHereAsync(pair.Id, local.Id, [Sha(photos[1])], f.Ct);
Assert.Equal((1, 0), (plan.Plan.Frames.Count, plan.LastCopies.Count));
// The other sequence goes to the trash while the confirmation is open: the photo is a last copy now, never moved unnamed.
var held = (await f.Db.Frames.ListBySequenceAsync(backup.Id, cancellationToken: f.Ct)).Single(r => r.Sha256 == Sha(photos[1]));
var other = await f.Archive.Service.FrameTrash.PlanDeleteAsync(backup.Id, [held.Id], (await f.Db.Sequences.GetAsync(backup.Id, f.Ct))!.FramesVersion, f.Ct);
await f.Archive.Service.FrameTrash.DeleteAsync(other, "test", null, f.Ct);
await Assert.ThrowsAsync<StaleCopyPlanException>(() => engine.TrashHereAsync(pair.Id, plan, f.Remote, f.Ct));
Assert.Count(2, await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct));
Assert.Count(1, (await engine.PlanTrashHereAsync(pair.Id, local.Id, [Sha(photos[1])], f.Ct)).LastCopies);
}
[Test]
public async Task TrashHereOfTwoLocalCopiesTrashesFromTheSequenceAsked()
{
await using var f = await FixtureAsync(context);
var photos = f.NewPhotos(3);
var first = await f.LocalAsync("Comet", photos);
var second = await f.LocalAsync("Comet copy", photos);
using var engine = Engine(f);
var pair = (await engine.FindAsync(null, f.Ct)).New.Single();
// The pair's first deletes a photo the second still holds (a merge keeping the second reads it "Deleted in other").
var (deleter, keeper) = pair.LocalId == first.Id ? (first, second) : (second, first);
var gone = (await f.Db.Frames.ListBySequenceAsync(deleter.Id, cancellationToken: f.Ct)).Single(fr => fr.Sha256 == Sha(photos[1]));
var deletion = await f.Archive.Service.FrameTrash.PlanDeleteAsync(deleter.Id, [gone.Id], (await f.Db.Sequences.GetAsync(deleter.Id, f.Ct))!.FramesVersion, f.Ct);
await f.Archive.Service.FrameTrash.DeleteAsync(deletion, "test", null, f.Ct);
var plan = await engine.PlanTrashHereAsync(pair.Id, keeper.Id, [Sha(photos[1])], f.Ct);
Assert.Equal(keeper.Id, plan.Plan.Sequence.Id);
Assert.Equal(1, await engine.TrashHereAsync(pair.Id, plan, null, f.Ct));
Assert.DoesNotContain(Sha(photos[1]), (await f.Db.Frames.ListBySequenceAsync(keeper.Id, cancellationToken: f.Ct)).Select(fr => fr.Sha256));
Assert.Count(2, await f.Db.Frames.ListBySequenceAsync(deleter.Id, cancellationToken: f.Ct));
// The sequence that deleted it holds nothing to trash: its own photos are refused.
await Assert.ThrowsAsync<InvalidOperationException>(() => engine.PlanTrashHereAsync(pair.Id, deleter.Id, [Sha(photos[1])], f.Ct));
await Assert.ThrowsAsync<ArgumentException>(() => engine.PlanTrashHereAsync(pair.Id, Guid.NewGuid(), [Sha(photos[1])], f.Ct));
}
[Test]
public async Task UnlinkKeepsApartAgainstWhatTheTwoHoldNowNotAtTheLastComparison()
{
await using var f = await FixtureAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet NAS", [photos[0]]);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.Sync.Copies.EnsureLinkedAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.AskAlways });
// The server copy grows to hold every photo: the pair's score follows at the next comparison.
remote.AddFrame(photos[1], "IMG_0002.JPG");
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.AskAlways });
var pair = (await f.Sync.Copies.FindRemoteAsync(local.Id, f.Server, remote.Id, f.Ct))!;
Assert.Equal((2, 0, 0), (pair.Score.Shared, pair.Score.OnlyHere, pair.Score.OnlyThere));
using var engine = Engine(f);
await engine.UnlinkAsync(pair.Id, f.Remote, f.Ct);
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.AskAlways });
// Answered against two identical copies: nothing grew since, so the pair is not asked about again.
var kept = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
Assert.Equal((CopyState.KeptApart, 2), (kept.State, kept.AnsweredShared ?? -1));
}
[Test]
public async Task DropVersionTrashesOneVersionOnBothSidesAndIsRefusedOnceTheOtherIsGone()
{
await using var f = await FixtureAsync(context);
var (local, remote, a, b) = await VersionsAsync(f);
var pair = await PairAsync(f, local.Id, remote.Id);
using var engine = Engine(f);
var review = await engine.CompareAsync(pair.Id, f.Remote, f.Ct);
Assert.Count(2, review.Photos.Of(PhotoClass.Versions));
var plan = await engine.PlanDropVersionAsync(pair.Id, Sha(a), f.Remote, f.Ct);
Assert.Equal((Sha(b), 2), (plan.PartnerKey, plan.Photos));
Assert.Equal(2, await engine.DropVersionAsync(plan, f.Remote, f.Ct));
var left = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
Assert.SequenceEqual(new[] { Sha(b) }, left.Select(fr => fr.Sha256!).Where(s => s == Sha(a) || s == Sha(b)));
Assert.False(remote.Frames.Any(fr => fr.Sha256 == Sha(a)));
Assert.True(remote.Frames.Any(fr => fr.Sha256 == Sha(b)));
Assert.Equal(Sha(a), f.Remote.Trashed.Single().Frame.Sha256);
}
[Test]
public async Task DropVersionIsRefusedWhenTheOtherVersionLeftOneSide()
{
await using var f = await FixtureAsync(context);
var (local, remote, a, b) = await VersionsAsync(f);
var pair = await PairAsync(f, local.Id, remote.Id);
using var engine = Engine(f);
var plan = await engine.PlanDropVersionAsync(pair.Id, Sha(a), f.Remote, f.Ct);
// The other version leaves the server after the dry run: dropping this one would leave the server without the photo.
await f.Remote.DeleteFramesAsync(remote.Id, new FrameDeleteRequest([remote.Frames.Single(fr => fr.Sha256 == Sha(b)).Id], null, false), f.Ct);
await Assert.ThrowsAsync<StaleCopyPlanException>(() => engine.DropVersionAsync(plan, f.Remote, f.Ct));
Assert.True(remote.Frames.Any(fr => fr.Sha256 == Sha(a)));
Assert.Count(1, f.Remote.Trashed);
Assert.True((await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).Any(fr => fr.Sha256 == Sha(a)));
}
[Test]
public async Task DropOwnVersionTrashesOneVersionOfALocalSequenceAndIsRefusedOnceTheOtherIsGone()
{
// Two versions a Union merge left in one sequence, its pair gone (owner Q3): listed, and each can be dropped.
await using var f = await FixtureAsync(context);
var (local, _, a, b) = await VersionsAsync(f);
using var engine = Engine(f);
var photo = (await engine.VersionsAsync(local.Id, f.Ct)).Single();
var (frameA, frameB) = photo.FirstSha256 == Sha(a) ? (photo.FirstFrameId, photo.SecondFrameId) : (photo.SecondFrameId, photo.FirstFrameId);
Assert.True(photo.CapturedAt is not null && photo.FirstSize > 0 && photo.SecondSize > 0);
var dropA = await engine.PlanDropOwnVersionAsync(local.Id, frameA, f.Ct);
Assert.Equal((1, frameB, Sha(b)), (dropA.Plan.Frames.Count, dropA.PartnerFrameId, dropA.PartnerSha256));
Assert.Equal(Sha(a), dropA.LastCopies.Single().Key);
var dropB = await engine.PlanDropOwnVersionAsync(local.Id, frameB, f.Ct);
Assert.Equal(1, await engine.DropOwnVersionAsync(dropB, f.Ct));
var left = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
Assert.True(left.Any(fr => fr.Sha256 == Sha(a)) && !left.Any(fr => fr.Sha256 == Sha(b)));
Assert.Empty(await engine.VersionsAsync(local.Id, f.Ct));
// The other version is gone now: dropping this one too would lose the photo, so nothing moves.
await Assert.ThrowsAsync<StaleCopyPlanException>(() => engine.DropOwnVersionAsync(dropA, f.Ct));
Assert.True((await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).Any(fr => fr.Sha256 == Sha(a)));
}
/// <summary>The photos Main leaves out of <paramref name="sequenceId"/>, by content.</summary>
private static async Task<IReadOnlySet<string>> ExcludedAsync(SyncFixture f, Guid sequenceId)
{
var row = (await f.Db.Sequences.GetAsync(sequenceId))!;
return CopyPayload.ExcludedKeys(CopyPayload.Portable(SyncPayload.Of(row), await SequencePayloadWriter.PhotosAsync(f.Db, sequenceId, null, f.Ct)));
}
/// <summary>Main of <paramref name="sequenceId"/> leaves out <paramref name="key"/>, as a Union keep-both leaves the incoming version.</summary>
private static async Task ExcludeAsync(SyncFixture f, Guid sequenceId, string key)
{
var row = (await f.Db.Sequences.GetAsync(sequenceId))!;
var portable = CopyPayload.Portable(SyncPayload.Of(row), await SequencePayloadWriter.PhotosAsync(f.Db, sequenceId, null, f.Ct));
await new SequencePayloadWriter(f.Db, f.Archive.Service).ApplyAsync(sequenceId, CopyPayload.ExcludeVersions(portable, [key]), row.SettingsVersion, f.Ct);
}
[Test]
public async Task DroppingTheVersionMainUsesLetsMainUseTheOneThatStays()
{
// A Union keep-both excluded version B in Main; the user drops A, the one Main used: Main must not be left without
// the photo (owner review 6, verification round 5).
await using var f = await FixtureAsync(context);
var (local, _, a, b) = await VersionsAsync(f);
await ExcludeAsync(f, local.Id, Sha(b));
Assert.SequenceEqual([Sha(b)], await ExcludedAsync(f, local.Id));
using var engine = Engine(f);
var photo = (await engine.VersionsAsync(local.Id, f.Ct)).Single();
var (frameA, aExcluded, bExcluded) = photo.FirstSha256 == Sha(a)
? (photo.FirstFrameId, photo.FirstExcluded, photo.SecondExcluded)
: (photo.SecondFrameId, photo.SecondExcluded, photo.FirstExcluded);
Assert.Equal((false, true), (aExcluded, bExcluded));
var plan = await engine.PlanDropOwnVersionAsync(local.Id, frameA, f.Ct);
Assert.Equal(1, await engine.DropOwnVersionAsync(plan, f.Ct));
Assert.Empty(await ExcludedAsync(f, local.Id));
Assert.True((await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).Any(fr => fr.Sha256 == Sha(b)));
}
[Test]
public async Task KeepVersionMovesTheExclusionHeroAndKeyframesToTheVersionThatStays()
{
await using var f = await FixtureAsync(context);
var (local, _, a, b) = await VersionsAsync(f);
await ExcludeAsync(f, local.Id, Sha(b));
var row = (await f.Db.Sequences.GetAsync(local.Id))!;
var portable = CopyPayload.Portable(SyncPayload.Of(row), await SequencePayloadWriter.PhotosAsync(f.Db, local.Id, null, f.Ct));
// Main used A and left B out: once A goes, B is used.
var kept = CopyPayload.KeepVersion(portable, Sha(b), Sha(a));
Assert.NotNull(kept);
Assert.Empty(CopyPayload.ExcludedKeys(kept!));
// Dropping the excluded one changes nothing in Main.
Assert.Null(CopyPayload.KeepVersion(portable, Sha(a), Sha(b)));
}
[Test]
public async Task DropVersionOfTwoLocalSequencesCountsAPhotoOnEachSide()
{
// Finding 9 said a pair of this PC's sequences listed "0 photos": the plan counts each local side's version.
await using var f = await FixtureAsync(context);
var (local, _, a, b) = await VersionsAsync(f);
var at = ArchiveFixture.Start.AddSeconds(5).AddMilliseconds(250);
var plainAt = ArchiveFixture.Start;
var other = await f.LocalAsync("Comet copy", [Photos.Jpeg(plainAt, 7001), a, b], capturedAt: [plainAt, at, at]);
var pair = await f.Sync.Copies.UpsertFoundAsync(new FoundCopy
{
Id = Guid.NewGuid(),
Kind = CopyKind.LocalLocal,
LocalId = local.Id,
OtherId = other.Id,
Evidence = CopyEvidence.Hashes,
Fingerprint = "f",
}, f.Ct);
await ExcludeAsync(f, local.Id, Sha(b));
await ExcludeAsync(f, other.Id, Sha(b));
using var engine = Engine(f);
var plan = await engine.PlanDropVersionAsync(pair.Id, Sha(a), null, f.Ct);
Assert.Equal((Sha(b), 2), (plan.PartnerKey, plan.Photos));
Assert.Equal(2, await engine.DropVersionAsync(plan, null, f.Ct));
// Both sides' Main now use the version that stays.
Assert.Empty(await ExcludedAsync(f, local.Id));
Assert.Empty(await ExcludedAsync(f, other.Id));
}
/// <summary>
/// A pair holding one photo in two versions (a Union keep-both): two files of one sub-second capture time, on both sides,
/// besides one plain photo.
/// </summary>
private static async Task<(Sequence Local, FakeSequence Remote, byte[] A, byte[] B)> VersionsAsync(SyncFixture f)
{
var plainAt = ArchiveFixture.Start;
var at = ArchiveFixture.Start.AddSeconds(5).AddMilliseconds(250);
var (plain, a, b) = (Photos.Jpeg(plainAt, 7001), Photos.Jpeg(at, 7002), Photos.Jpeg(at, 7003));
var local = await f.LocalAsync("Comet", [plain, a, b], capturedAt: [plainAt, at, at]);
var remote = f.Remote.Add("Comet NAS", []);
remote.AddFrame(plain, "IMG_0001.JPG", plainAt);
remote.AddFrame(a, "IMG_0002.JPG", at);
remote.AddFrame(b, "IMG_0003.JPG", at);
return (local, remote, a, b);
}
[Test]
public async Task TrashThereIsRefusedForAPhotoThisPcStillHolds()
{
await using var f = await FixtureAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet NAS", photos);
var pair = await PairAsync(f, local.Id, remote.Id);
using var engine = Engine(f);
var plan = await engine.PlanTrashThereAsync(pair.Id, f.Remote, [Sha(photos[1])], f.Ct);
await Assert.ThrowsAsync<StaleCopyPlanException>(() => engine.TrashThereAsync(plan, f.Remote, f.Ct));
Assert.Count(0, f.Remote.Trashed);
}
[Test]
public async Task TwinsNameTheProjectsOfBothHomesOfALinkedPairEvenUnderTheServersIdKey()
{
// Owner Q5's alternative: projects left where they are; Edit's picker marks the two homes' projects as twins. The
// server home is keyed by the server's id while the pair still carries the address key it was found under.
var serverId = Guid.NewGuid();
var address = string.Empty;
await using var f = await SyncFixture.CreateAsync(context, () => new ServerIdentity([new KnownServerKey(serverId, [address])]));
address = f.Server;
var photos = f.NewPhotos(2);
var linked = await f.LocalAsync("Comet", photos);
var apart = await f.LocalAsync("Lighthouse", f.NewPhotos(2));
var linkedRemote = f.Remote.Add("Comet NAS", photos);
var apartRemote = f.Remote.Add("Lighthouse NAS", photos);
var pair = await PairAsync(f, linked.Id, linkedRemote.Id);
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.Candidate, CopyState.Linked, null, f.Ct));
await PairAsync(f, apart.Id, apartRemote.Id);
var sides = new CopySides(f.Db);
IReadOnlyList<(Chronos.Core.Project.BundleHome Home, string Name)> projects =
[
(new(Chronos.Core.Project.BundleHome.ArchiveKind, linked.Id), "Grade"),
(new(Chronos.Core.Project.BundleHome.ArchiveKind, linked.Id), "Vertical"),
(new(Chronos.Core.Project.BundleHome.ArchiveKind, linked.Id), "Slow pan"),
(new(Chronos.Core.Project.BundleHome.ServerKind, linkedRemote.Id, Server: ServerIdentity.IdKey(serverId)), "Grade"),
(new(Chronos.Core.Project.BundleHome.ServerKind, linkedRemote.Id, Server: ServerIdentity.IdKey(serverId)), "Slow pan (STUDIO-PC)"),
(new(Chronos.Core.Project.BundleHome.ArchiveKind, apart.Id), "Unpaired"),
];
using var engine = new CopyEngine(f.Sync, f.Archive.Service, new IntegratePlanner(f.Sync, sides, f.Archive.Service.Projects),
new SequenceMerger(f.Db, f.Archive.Service, sides), new CopyReviewBuilder(f.Db, f.Archive.Service.Projects, sides), _ => Context,
serverNames: key => key == f.Server ? "Studio NAS" : null, workspaceProjects: _ => Task.FromResult(projects));
var twin = (await engine.TwinsAsync(f.Ct)).Single();
Assert.Equal((pair.Id, linked.Id, linkedRemote.Id), (twin.CopyId, twin.LocalId, twin.RemoteId));
Assert.SequenceEqual(["Grade", "Vertical", "Slow pan"], twin.LocalProjects);
Assert.SequenceEqual(["Grade", "Slow pan (STUDIO-PC)"], twin.ServerProjects);
// A project is a twin only with its sibling: the same name, or the name Copy across gave it at the other home.
Assert.Equal("Grade", twin.CounterpartOf("Grade", atServerHome: false));
Assert.Null(twin.CounterpartOf("Vertical", atServerHome: false));
Assert.Equal("Slow pan (STUDIO-PC)", twin.CounterpartOf("Slow pan", atServerHome: false));
Assert.Equal("Slow pan", twin.CounterpartOf("Slow pan (STUDIO-PC)", atServerHome: true));
Assert.Equal(f.Server, twin.Server);
// The Edit picker shows the server by its name, never by its key.
Assert.Equal("Studio NAS", twin.ServerName);
}
}
@@ -0,0 +1,96 @@
using Chronos.Core.Model;
using Chronos.Data.Copies;
using Chronos.Data.Tests.Sync;
using Chronos.Testing;
namespace Chronos.Data.Tests.Copies;
/// <summary>Detection on this PC (owner review 6, #73; design §3.4): two local copies are asked about, never linked.</summary>
[Category("sync")]
public sealed class CopyFinderLocalTests(TestContext context)
{
[Test]
public async Task TwoLocalCopiesAreAskedAndNeverLinked()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(4);
var first = await f.LocalAsync("Comet", photos);
var second = await f.LocalAsync("Comet (card)", photos.Take(3).ToList());
await f.LocalAsync("Harbour", f.NewPhotos(2));
var result = await f.Sync.Finder.FindLocalAsync(f.Ct);
var pair = result.New.Single();
Assert.Equal((CopyKind.LocalLocal, CopyState.Candidate, CopyEvidence.Hashes), (pair.Kind, pair.State, pair.Evidence));
Assert.Equal(FoundCopyStore.Order(first.Id, second.Id), (pair.LocalId, pair.OtherId!.Value));
Assert.Equal(3, pair.Score.Shared);
Assert.Empty(result.AutoLinked);
Assert.Count(1, await f.Sync.Copies.ListAsync(f.Ct));
// Nothing moved: nothing is compared or announced again.
Assert.True((await f.Sync.Finder.FindLocalAsync(f.Ct)).IsEmpty);
}
[Test]
public async Task AnUnhashedCopyIsFoundBySizeAndCaptureTime()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
await f.LocalAsync("Comet", photos);
var adopted = await f.LocalAsync("Comet (adopted)", photos);
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
await session.ExecuteAsync("UPDATE frames SET sha256 = NULL WHERE sequence_id = $1", [adopted.Id], f.Ct);
var pair = (await f.Sync.Finder.FindLocalAsync(f.Ct)).New.Single();
Assert.Equal(CopyEvidence.SizeAndTime, pair.Evidence);
Assert.Equal(3, pair.Score.SharedUnhashed);
Assert.Equal(CopyState.Candidate, pair.State);
}
[Test]
public async Task AKeptApartPairStaysApartAndAMergeTargetIsLeftAlone()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
var first = await f.LocalAsync("Comet", photos);
await f.LocalAsync("Comet (card)", photos);
var pair = (await f.Sync.Finder.FindLocalAsync(f.Ct)).New.Single();
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.Candidate, CopyState.KeptApart,
new CopyAnswer(pair.Fingerprint, pair.Score.Shared, null, false, DateTimeOffset.UtcNow), f.Ct));
await f.Sync.Finder.ResetProbesAsync(CopyFinder.LocalScope, f.Ct);
Assert.True((await f.Sync.Finder.FindLocalAsync(f.Ct)).IsEmpty);
Assert.Equal(CopyState.KeptApart, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
// A third copy while a merge waits on the first: the first is left out until the merge ends.
var third = await f.LocalAsync("Comet (again)", photos);
await f.Db.Jobs.EnqueueAsync(new Job
{
Id = Guid.CreateVersion7(),
Kind = JobKind.MergeSequences,
TargetIds = [first.Id],
State = JobState.Queued,
Created = DateTimeOffset.UtcNow,
}, f.Ct);
var result = await f.Sync.Finder.FindLocalAsync(f.Ct);
Assert.False(result.New.Any(p => p.Names(first.Id)));
Assert.True(result.New.Single().Names(third.Id));
}
[Test]
public async Task APairThatSharesNothingAnyMoreIsNoLongerAsked()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(2);
await f.LocalAsync("Comet", photos);
var second = await f.LocalAsync("Comet (card)", photos);
var pair = (await f.Sync.Finder.FindLocalAsync(f.Ct)).New.Single();
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
await session.ExecuteAsync("UPDATE frames SET sha256 = NULL, captured_at = NULL WHERE sequence_id = $1", [second.Id], f.Ct);
await f.Sync.Finder.FindLocalAsync(f.Ct);
Assert.Null(await f.Sync.Copies.GetAsync(pair.Id, f.Ct));
}
}
@@ -0,0 +1,283 @@
using Chronos.Core.Model;
using Chronos.Data.Copies;
using Chronos.Data.Archiving;
using Chronos.Data.Sync;
using Chronos.Data.Tests.Sync;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Copies;
/// <summary>
/// Detection against a server (owner review 6, #73; design §3.3): the photo lookup and its follow-ups, the exact comparison,
/// what is left alone, the probes kept across refreshes and restarts, and the limits of one refresh.
/// </summary>
[Category("sync")]
public sealed class CopyFinderServerTests(TestContext context)
{
private static async Task<SyncFixture> LookupAsync(TestContext context)
{
var f = await SyncFixture.CreateAsync(context);
f.Remote.Capabilities.Add(ServerCapabilities.PhotoLookup);
return f;
}
private static Task<IReadOnlyList<FoundCopy>> PairsAsync(SyncFixture f) => f.Sync.Copies.ListAsync(f.Ct);
[Test]
public async Task AServerSequenceHoldingSomeOfThePhotosIsAsked()
{
await using var f = await LookupAsync(context);
var photos = f.NewPhotos(4);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet (selection)", photos.Take(2));
f.Remote.Add("Other card", f.NewPhotos(2));
await f.RefreshAsync();
var pair = (await PairsAsync(f)).Single();
Assert.Equal((CopyKind.LocalServer, local.Id, remote.Id), (pair.Kind, pair.LocalId, pair.RemoteId!.Value));
Assert.Equal((CopyState.Candidate, CopyEvidence.Hashes), (pair.State, pair.Evidence));
Assert.Equal((2, 2, 0), (pair.Score.Shared, pair.Score.OnlyHere, pair.Score.OnlyThere));
Assert.Count(1, f.Remote.Lookups);
Assert.Equal(1, f.Remote.ManifestCalls);
Assert.Equal("chronos-sync:" + local.Id.ToString("N"), f.Remote.Lookups[0].Probes.Single().SessionKey);
}
[Test]
public async Task AnUploadFiledUnderThisCopysKeyIsFoundByIt()
{
await using var f = await LookupAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("2026-09-28 Canon", photos);
f.Remote.FileUnder("chronos-sync:" + local.Id.ToString("N"), remote);
await f.RefreshAsync();
var pair = (await PairsAsync(f)).Single();
Assert.Equal((CopyEvidence.SessionKey, remote.Id), (pair.Evidence, pair.RemoteId!.Value));
Assert.Equal(CopyState.Candidate, pair.State);
}
[Test]
public async Task ADownloadWhoseLinkWasLostIsFoundByItsKey()
{
await using var f = await LookupAsync(context);
var photos = f.NewPhotos(2);
var remote = f.Remote.Add("Comet", photos);
var local = await LocalUnderAsync(f, photos, SyncService.SessionKey(remote.Id));
await f.RefreshAsync();
var pair = (await PairsAsync(f)).Single();
Assert.Equal((CopyEvidence.SessionKey, local.Id, remote.Id), (pair.Evidence, pair.LocalId, pair.RemoteId!.Value));
}
[Test]
public async Task ASecondLocalCopyOfALinkedServerSequenceMakesALocalPair()
{
await using var f = await LookupAsync(context);
var photos = f.NewPhotos(3);
var first = await f.LocalAsync("Comet", photos);
var second = await f.LocalAsync("Comet copy", photos);
var remote = f.Remote.Add("Comet", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, first.Id, f.Ct);
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.WhenHalfShared });
Assert.Null(await f.Sync.LinkOfAsync(f.Server, second.Id, f.Ct));
var local = (await PairsAsync(f)).Single(p => p.Kind == CopyKind.LocalLocal);
Assert.Equal(FoundCopyStore.Order(first.Id, second.Id), (local.LocalId, local.OtherId!.Value));
Assert.Equal(CopyState.Candidate, local.State);
}
[Test]
public async Task SequencesAnIntegrateWaitsForAreLeftAlone()
{
await using var f = await LookupAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
f.Remote.Add("Comet", photos);
await f.Db.Jobs.EnqueueAsync(new Job
{
Id = Guid.CreateVersion7(),
Kind = JobKind.Integrate,
TargetIds = [local.Id],
State = JobState.Queued,
Created = DateTimeOffset.UtcNow,
}, f.Ct);
await f.RefreshAsync();
Assert.Empty(await PairsAsync(f));
Assert.Empty(f.Remote.Lookups);
}
[Test]
public async Task AKeptApartPairIsNotAskedAgainForTheSamePhotos()
{
await using var f = await LookupAsync(context);
var photos = f.NewPhotos(3);
await f.LocalAsync("Comet", photos);
f.Remote.Add("Comet", photos);
await f.RefreshAsync();
var pair = (await PairsAsync(f)).Single();
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.Candidate, CopyState.KeptApart,
new CopyAnswer(pair.Fingerprint, pair.Score.Shared, null, false, DateTimeOffset.UtcNow), f.Ct));
var raised = new List<CopyFindResult>();
f.Sync.CopiesFound += (_, result) => raised.Add(result);
await f.Sync.Finder.ResetProbesAsync(f.Server, f.Ct);
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.WhenIdentical });
Assert.Count(2, f.Remote.Lookups);
Assert.Equal(CopyState.KeptApart, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
Assert.Empty(raised);
}
[Test]
public async Task NothingIsLookedUpAgainUntilTheCopyChanges()
{
await using var f = await LookupAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos);
f.Remote.Add("Harbour", f.NewPhotos(2));
await f.RefreshAsync();
await f.RefreshAsync();
Assert.Count(1, f.Remote.Lookups);
// A restart keeps what was probed.
var restarted = new SyncService(f.Db, f.Archive.Service, new SyncOptions
{
Archive = new ArchiveServiceOptions { Owner = "test" },
ProxyCacheDirectory = context.CreateTempDirectory("proxies-again"),
});
await restarted.RefreshAsync(f.Remote, new SyncPolicy(), f.Ct);
Assert.Count(1, f.Remote.Lookups);
// Hashes lost and given back by Verify change what the copy can be found by.
await SetHashesAsync(f, local.Id, null);
await f.RefreshAsync();
Assert.Count(2, f.Remote.Lookups);
Assert.Empty(f.Remote.Lookups[1].Probes.Single().Sha256);
Assert.Equal(3, f.Remote.Lookups[1].Probes.Single().Unhashed!.Count);
// A sequence uploaded to the server later is looked for too.
f.Remote.Add("Comet", photos);
await f.RefreshAsync();
Assert.Count(3, f.Remote.Lookups);
Assert.Equal(CopyEvidence.SizeAndTime, (await PairsAsync(f)).Single().Evidence);
}
[Test]
public async Task AServerCopyNotHashedYetIsFoundByTheSizeAndTimeOfHashedPhotos()
{
await using var f = await LookupAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos);
// Adopted on the server and not verified there: it lists no hash, so only size and capture time can find it.
var remote = f.Remote.Add("Comet", photos);
remote.Unhashed = true;
await f.RefreshAsync();
var pair = (await PairsAsync(f)).Single();
Assert.Equal((local.Id, remote.Id), (pair.LocalId, pair.RemoteId!.Value));
Assert.Equal(CopyState.Candidate, pair.State);
}
[Test]
public async Task ASequenceAddedOnAServerWhoseClockIsBehindIsStillLookedFor()
{
await using var f = await LookupAsync(context);
var photos = f.NewPhotos(3);
await f.LocalAsync("Comet", photos);
var other = f.Remote.Add("Harbour", f.NewPhotos(2));
other.UpdatedAt = DateTimeOffset.UtcNow.AddHours(-3);
await f.RefreshAsync();
Assert.Count(1, f.Remote.Lookups);
// Added after the probe by a server whose clock is three hours behind this PC's: later than the newest it showed.
var remote = f.Remote.Add("Comet", photos);
remote.UpdatedAt = other.UpdatedAt.AddMinutes(1);
await f.RefreshAsync();
Assert.Count(2, f.Remote.Lookups);
Assert.Equal(remote.Id, (await PairsAsync(f)).Single().RemoteId!.Value);
}
[Test]
public async Task OneRefreshComparesAtMostFiftyPairs()
{
await using var f = await LookupAsync(context);
for (var i = 0; i < CopyFinder.MaxExact + 1; i++)
{
var photos = f.NewPhotos(1);
await f.LocalAsync($"Card {i}", photos);
f.Remote.Add($"Card {i}", photos);
}
await f.RefreshAsync();
Assert.Equal(CopyFinder.MaxExact, f.Remote.ManifestCalls);
Assert.Count(CopyFinder.MaxExact, await PairsAsync(f));
await f.RefreshAsync();
Assert.Equal(CopyFinder.MaxExact + 1, f.Remote.ManifestCalls);
Assert.Count(CopyFinder.MaxExact + 1, await PairsAsync(f));
Assert.True(f.Remote.Lookups.All(l => l.Probes.Count <= PhotoLookupRequest.MaxProbes && l.CountItems() <= PhotoLookupRequest.MaxItems));
}
[Test]
public async Task AnOlderServerIsComparedByTheGateTwentyManifestsAtATime()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
FakeSequence? copy = null;
for (var i = 0; i <= CopyFinder.MaxExactOlderServer; i++)
{
// The same first second and camera: each one passes 1.1's gate; only the last holds the photos.
var remote = f.Remote.Add($"Card {i}", i == CopyFinder.MaxExactOlderServer ? photos : f.NewPhotos(1));
remote.FirstCapture = local.FirstCapture;
remote.CameraModel = local.CameraModel;
copy = remote;
}
await f.RefreshAsync();
Assert.Equal(CopyFinder.MaxExactOlderServer, f.Remote.ManifestCalls);
await f.RefreshAsync();
Assert.Equal(CopyFinder.MaxExactOlderServer + 1, f.Remote.ManifestCalls);
var pair = (await PairsAsync(f)).Single();
Assert.Equal((copy!.Id, CopyState.Candidate), (pair.RemoteId!.Value, pair.State));
Assert.Empty(f.Remote.Lookups);
await f.RefreshAsync();
Assert.Equal(CopyFinder.MaxExactOlderServer + 1, f.Remote.ManifestCalls);
}
private static async Task SetHashesAsync(SyncFixture f, Guid sequenceId, string? sha256)
{
await using var session = await f.Db.Database.OpenAsync(f.Ct);
await session.ExecuteAsync("UPDATE frames SET sha256 = $1 WHERE sequence_id = $2", [sha256, sequenceId], f.Ct);
}
/// <summary>A local sequence filed under <paramref name="sessionKey"/> (a download of a server sequence keeps its back-reference).</summary>
private static async Task<Sequence> LocalUnderAsync(SyncFixture f, IReadOnlyList<byte[]> originals, string sessionKey)
{
Guid? id = null;
var staging = Path.Combine(f.Archive.Paths.StagingDirectory, "session");
Directory.CreateDirectory(staging);
for (var i = 0; i < originals.Count; i++)
{
var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part");
await File.WriteAllBytesAsync(path, originals[i], f.Ct);
var sha = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(originals[i]));
var result = await f.Archive.Service.Ingest.CommitAsync(new IngestRequest(f.Archive.Archive.Id, id, null, id is null ? sessionKey : null, path,
$"IMG_{i + 1:0000}.JPG", originals[i].Length, sha, null, null), f.Ct);
id = result.SequenceId;
}
return (await f.Db.Sequences.GetAsync(id!.Value, f.Ct))!;
}
}
@@ -0,0 +1,41 @@
using Chronos.Data.Copies;
using Chronos.Testing;
namespace Chronos.Data.Tests.Copies;
/// <summary>The parameters of the Integrate and MergeSequences jobs (owner review 6, #73) survive the job row, and junk reads as none.</summary>
[Category("jobs")]
public sealed class CopyJobParametersTests
{
[Test]
public void IntegrateParametersRoundTrip()
{
var choices = new IntegrateChoices(CopyPhotoPolicy.ChoosePerPhoto, new Dictionary<string, PhotoChoice> { ["h:ab"] = PhotoChoice.KeepBoth },
new Dictionary<string, CopySide> { ["title"] = CopySide.Other }, CopyProjects.Leave);
var parameters = new IntegrateJobParameters(Guid.NewGuid(), "https://nas.test:8443", Guid.CreateVersion7(), Guid.CreateVersion7(), choices, "fp", true);
var json = parameters.ToJson();
// Enums are written by name: a value appended later never shifts what a queued job meant.
Assert.Contains("\"ChoosePerPhoto\"", json);
Assert.Contains("\"autoPhotos\":true", json);
var back = IntegrateJobParameters.Read(json)!;
Assert.Equal((parameters.CopyId, parameters.Server, parameters.LocalId, parameters.RemoteId, "fp", true),
(back.CopyId, back.Server, back.LocalId, back.RemoteId, back.Fingerprint, back.AutoPhotos));
Assert.Equal((CopyPhotoPolicy.ChoosePerPhoto, PhotoChoice.KeepBoth, CopySide.Other, CopyProjects.Leave),
(back.Choices.Photos, back.Choices.PerPhoto["h:ab"], back.Choices.Details["title"], back.Choices.Projects));
Assert.Null(IntegrateJobParameters.Read(null));
Assert.Null(IntegrateJobParameters.Read("{not json"));
Assert.Null(IntegrateJobParameters.Read("{}"));
}
[Test]
public void MergeParametersRoundTrip()
{
var choices = new MergeChoices(CopyPhotoPolicy.Union, new Dictionary<string, PhotoChoice>(), new Dictionary<string, CopySide>());
var parameters = new MergeJobParameters(Guid.NewGuid(), Guid.CreateVersion7(), Guid.CreateVersion7(), choices, "fp");
var back = MergeJobParameters.Read(parameters.ToJson())!;
Assert.Equal((parameters.CopyId, parameters.KeepId, parameters.DropId, "fp", CopyPhotoPolicy.Union),
(back.CopyId, back.KeepId, back.DropId, back.Fingerprint, back.Choices.Photos));
Assert.Null(MergeJobParameters.Read(" "));
Assert.Null(MergeJobParameters.Read("[1]"));
}
}
@@ -0,0 +1,76 @@
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Copies;
using Chronos.Data.Tests.Archiving;
using Chronos.Testing;
namespace Chronos.Data.Tests.Copies;
/// <summary>
/// What a merge or an integration leaves in the archive's journal folder (owner review 6, #73): the maintenance pass keeps
/// the journal a retry can use and clears the one no job will read again, as it does for conversions.
/// </summary>
[Category("archive")]
public sealed class CopyJournalMaintenanceTests(TestContext context)
{
[Test]
public async Task MaintenanceClearsTheJournalOfAMergeOrIntegrateNoJobWillReadAgain()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
var failed = Guid.CreateVersion7();
var done = Guid.CreateVersion7();
var cancelled = Guid.CreateVersion7();
var paused = Guid.CreateVersion7();
foreach (var (id, kind, state) in new[]
{
(failed, JobKind.MergeSequences, JobState.Failed), (done, JobKind.Integrate, JobState.Done),
(cancelled, JobKind.MergeSequences, JobState.Cancelled), (paused, JobKind.Integrate, JobState.Paused),
})
await fx.Db.Jobs.EnqueueAsync(new Job { Id = id, Kind = kind, State = state, Created = DateTimeOffset.UtcNow }, fx.Ct);
// Deleted without a cancel: the index no longer knows the job.
var deleted = Guid.CreateVersion7();
var recent = Guid.CreateVersion7();
const int Old = Housekeeping.CleanupSteps.DefaultHistoryDays + 1;
string Write(string path, int daysOld)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, "{}");
File.SetLastWriteTimeUtc(path, DateTime.UtcNow.AddDays(-daysOld));
return path;
}
var failedJournal = Write(MergeJournal.PathFor(fx.Paths, failed), Old);
var doneJournal = Write(IntegrateJournal.PathFor(fx.Paths, done), 0);
var cancelledJournal = Write(MergeJournal.PathFor(fx.Paths, cancelled), 0);
var pausedJournal = Write(IntegrateJournal.PathFor(fx.Paths, paused), Old);
var deletedJournal = Write(MergeJournal.PathFor(fx.Paths, deleted), Old);
var recentJournal = Write(IntegrateJournal.PathFor(fx.Paths, recent), 1);
var other = Write(Path.Combine(fx.Paths.JournalDirectory, "merge-notes.json"), Old);
var dry = await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: true, 0, _ => ValueTask.CompletedTask, fx.Ct);
Assert.SequenceEqual(new[] { doneJournal, cancelledJournal, deletedJournal }.Select(fx.Paths.ToRelative).Order(), dry.TemporaryFiles.Order());
Assert.FileExists(deletedJournal);
await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: false, 0, _ => ValueTask.CompletedTask, fx.Ct);
Assert.FileMissing(doneJournal);
Assert.FileMissing(cancelledJournal);
Assert.FileMissing(deletedJournal);
// A retry still reads these: the failed and the paused job's, and one another host may still be writing.
Assert.FileExists(failedJournal);
Assert.FileExists(pausedJournal);
Assert.FileExists(recentJournal);
Assert.FileExists(other);
}
[Test]
public void OnlyTheJournalsOfMergesAndIntegrationsAreRecognised()
{
var job = Guid.CreateVersion7();
Assert.Equal(job, ArchiveMaintenance.CopyJournalJob($"merge-{job:N}.json"));
Assert.Equal(job, ArchiveMaintenance.CopyJournalJob($"integrate-{job:N}.json"));
Assert.Null(ArchiveMaintenance.CopyJournalJob($"convert-{job:N}.json"));
Assert.Null(ArchiveMaintenance.CopyJournalJob($"merge-{job:N}.json.tmp"));
Assert.Null(ArchiveMaintenance.CopyJournalJob($"merge-{job:D}.json"));
}
}
@@ -0,0 +1,139 @@
using System.Globalization;
using Chronos.Core.Project;
using Chronos.Data.Copies;
using Chronos.Data.Sync;
using Chronos.Testing;
namespace Chronos.Data.Tests.Copies;
/// <summary>The details of two copies line by line and the one payload both get (owner review 6, Q4; design §4.3, §5e).</summary>
[Category("sync")]
public sealed class CopyPayloadTests
{
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0, 250);
private static string Sha(int n) => Convert.ToHexStringLower(BitConverter.GetBytes((long)n)).PadLeft(64, 'b');
private static FramePhoto Photo(int n) => new(Sha(n), 1000 + n, Start.AddSeconds(5 * n));
/// <summary>Photos 0–19 at indices 0–19.</summary>
private static readonly FramePhotos Here = new(Enumerable.Range(0, 20).Select(i => (i, Photo(i))));
/// <summary>Two photos more before them (100, 101): photo n at index n + 2.</summary>
private static readonly FramePhotos There = new(new[] { (0, Photo(100)), (1, Photo(101)) }.Concat(Enumerable.Range(0, 20).Select(i => (i + 2, Photo(i)))));
private static SyncPayload Payload(ProjectSettings settings, string? title = "Harbour", params string[] tags) =>
new(title, tags, 3, null, settings.ToJson());
private static IReadOnlyDictionary<string, CopySide> Choose(IEnumerable<DetailLine> lines, CopySide side, params (string Path, CopySide Side)[] except)
{
var choices = lines.ToDictionary(l => l.Path, _ => side, StringComparer.Ordinal);
foreach (var (path, chosen) in except) choices[path] = chosen;
return choices;
}
[Test]
public void TheSameExclusionAtAnotherIndexIsNoLine()
{
var here = Payload(new ProjectSettings { ExcludedFrames = [10], HeroFrame = 3 });
var there = Payload(new ProjectSettings { ExcludedFrames = [12], HeroFrame = 5 });
Assert.Empty(CopyPayload.Lines(here, Here, there, There));
// Another photo excluded there: one line, the frame positions.
var other = Payload(new ProjectSettings { ExcludedFrames = [11], HeroFrame = 5 });
var lines = CopyPayload.Lines(here, Here, other, There);
var line = Assert.Contains(lines, l => l.Path == CopyPayload.PendingFramesPath);
Assert.Count(1, lines);
Assert.Contains(Sha(10), line.Here);
Assert.Contains(Sha(9), line.There);
}
[Test]
public void FramePositionsCollapseIntoOneLine()
{
var here = Payload(new ProjectSettings { ExcludedFrames = [1, 2], HeroFrame = 3 }, "Harbour", "dusk");
var there = Payload(new ProjectSettings { ExcludedFrames = [9], HeroFrame = 7, Stack = new StackSettings { Length = 15 } }, "Harbour at dusk", "dusk", "sea");
var lines = CopyPayload.Lines(here, Here, there, There);
Assert.Count(4, lines);
Assert.True(lines.Select(l => l.Path).ToHashSet().SetEquals(["sequence.title", "sequence.tags", CopyPayload.PendingFramesPath, "stack.length"]));
var stack = lines.Single(l => l.Path == "stack.length");
Assert.Equal(("9", "15"), (stack.Here, stack.There));
}
[Test]
public void MergeTakesTheChosenSideOfEachLine()
{
var here = Payload(new ProjectSettings { ExcludedFrames = [1], Stack = new StackSettings { Length = 9 }, Export = new ExportSettings { NameTemplate = "{title}" } },
"Harbour", "dusk");
var there = Payload(new ProjectSettings { ExcludedFrames = [9], Stack = new StackSettings { Length = 15 }, Export = new ExportSettings { NameTemplate = "{date}" } },
"Harbour at dusk", "dusk", "sea");
var lines = CopyPayload.Lines(here, Here, there, There);
var choices = Choose(lines, CopySide.ThisPc, ("sequence.title", CopySide.Other), ("stack.length", CopySide.Other), (CopyPayload.PendingFramesPath, CopySide.Other));
var merged = CopyPayload.Merge(CopyPayload.Portable(here, Here), CopyPayload.Portable(there, There), choices, lines);
Assert.Equal("Harbour at dusk", merged.Title);
Assert.SequenceEqual(["dusk"], merged.Tags);
var settings = ProjectSettings.FromJson(merged.SettingsJson!);
Assert.Equal((15, "{title}"), (settings.Stack.Length, settings.Export.NameTemplate));
// Portable: placed on this PC's frames, the exclusion is there's photo 7 (index 9 there).
Assert.SequenceEqual([7], ProjectSettings.FromJson(ProjectContent.Place(merged.SettingsJson!, Here)).ExcludedFrames);
Assert.SequenceEqual([9], ProjectSettings.FromJson(ProjectContent.Place(merged.SettingsJson!, There)).ExcludedFrames);
// Every line this PC's: the merged payload is this PC's.
var mine = CopyPayload.Merge(CopyPayload.Portable(here, Here), CopyPayload.Portable(there, There), Choose(lines, CopySide.ThisPc), lines);
Assert.Empty(CopyPayload.Lines(mine, new FramePhotos([]), CopyPayload.Portable(here, Here), new FramePhotos([])));
}
[Test]
public void AnUnchosenLineThrows()
{
var here = Payload(new ProjectSettings(), "Harbour");
var there = Payload(new ProjectSettings { Stack = new StackSettings { Length = 15 } }, "Harbour at dusk");
var lines = CopyPayload.Lines(here, Here, there, There);
var choices = new Dictionary<string, CopySide> { ["sequence.title"] = CopySide.Other };
Assert.Throws<ArgumentException>(() => CopyPayload.Merge(here, there, choices, lines));
}
[Test]
public void AMergeThatIsNoProjectIsRefused()
{
var here = Payload(new ProjectSettings());
var there = new SyncPayload("Harbour", [], 3, null, "not a project");
var lines = CopyPayload.Lines(here, Here, there, There);
Assert.Equal("settings", Assert.Contains(lines, l => l.Path == "settings").Path);
Assert.Throws<InvalidDataException>(() => CopyPayload.Merge(here, there, Choose(lines, CopySide.Other), lines));
var kept = CopyPayload.Merge(here, there, Choose(lines, CopySide.ThisPc), lines);
Assert.Equal(9, ProjectSettings.FromJson(kept.SettingsJson!).Stack.Length);
}
[Test]
public void ExcludeVersionsExcludesByPhoto()
{
var portable = CopyPayload.Portable(Payload(new ProjectSettings { HeroFrame = 4 }), Here);
var unhashed = string.Create(CultureInfo.InvariantCulture, $"u:777:{Start.AddSeconds(500).Ticks / TimeSpan.TicksPerMillisecond}");
var excluded = CopyPayload.ExcludeVersions(portable, [Sha(99), Sha(4), unhashed]);
var pending = ProjectSettings.FromJson(excluded.SettingsJson!).PendingFrames!;
Assert.True(pending.Single(p => p.Sha256 == Sha(99)).Excluded);
// The hero's photo keeps its hero flag and is excluded too.
var hero = pending.Single(p => p.Sha256 == Sha(4));
Assert.True(hero.Excluded && hero.Hero);
var byTime = pending.Single(p => string.IsNullOrEmpty(p.Sha256));
Assert.Equal((777L, Start.AddSeconds(500)), (byTime.Size, byTime.CapturedAt!.Value));
// Placed on frames holding the version, it is excluded there.
var frames = new FramePhotos([(0, Photo(1)), (1, new FramePhoto(Sha(99), 5, Start)), (2, Photo(4))]);
var placed = ProjectSettings.FromJson(ProjectContent.Place(excluded.SettingsJson!, frames));
Assert.SequenceEqual([1, 2], placed.ExcludedFrames.Order());
Assert.Equal(2, placed.HeroFrame);
Assert.Same(portable, CopyPayload.ExcludeVersions(portable, []));
}
[Test]
public void MovedNamesThePathsThatChanged()
{
var before = CopyPayload.Portable(Payload(new ProjectSettings { ExcludedFrames = [1] }), Here);
var after = CopyPayload.Portable(Payload(new ProjectSettings { ExcludedFrames = [2], Stack = new StackSettings { Length = 3 } }, "Pier"), Here);
Assert.True(CopyPayload.Moved(before, after).SetEquals(["sequence.title", CopyPayload.PendingFramesPath, "stack.length"]));
Assert.Empty(CopyPayload.Moved(before, before));
}
}
@@ -0,0 +1,111 @@
using Chronos.Data.Copies;
using Chronos.Data.Sync;
using Chronos.Data.Tests.Sync;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Copies;
/// <summary>What the Compare dialog shows of a pair (owner review 6, #73; design §4.4): facts, photos, details and what can be done.</summary>
[Category("sync")]
public sealed class CopyReviewBuilderTests(TestContext context)
{
private static CopyPlanContext Context(bool canUpload = true, bool canDelete = false) =>
new("PC", "NAS", canUpload, true, true, canDelete, canDelete, false, null, new HashSet<Guid>(), new HashSet<Guid>());
private static CopyReviewBuilder Builder(SyncFixture f) => new(f.Db, f.Archive.Service.Projects, new CopySides(f.Db));
/// <summary>A local copy and a server copy sharing two photos, each holding one more, with different settings; asked about.</summary>
private static async Task<(FoundCopy Pair, Guid LocalId, FakeSequence Remote)> AskedAsync(SyncFixture f)
{
var photos = f.NewPhotos(4);
var local = await f.LocalAsync("Comet", photos.Take(3).ToList(), SyncFixture.Window33);
var remote = f.Remote.Add("Comet", [photos[0], photos[1], photos[3]], SyncFixture.Window41);
await f.RefreshAsync();
return ((await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(), local.Id, remote);
}
[Test]
public async Task AServerPairShowsBothSidesAndCanBeIntegrated()
{
await using var f = await SyncFixture.CreateAsync(context);
f.Remote.Capabilities.Add(ServerCapabilities.PhotoLookup);
f.Remote.Capabilities.Add(ServerCapabilities.UploadInto);
var (pair, localId, remote) = await AskedAsync(f);
var review = await Builder(f).BuildAsync(pair, f.Remote, Context(), f.Ct);
Assert.Equal(("Comet", f.Archive.Archive.Id, 3, 3), (review.Here.Title, review.Here.ArchiveId, review.Here.Photos, review.Here.Hashed));
Assert.Equal((3, (Guid?)null), (review.There.Photos, review.There.ArchiveId));
Assert.Equal((2, 1, 1), (review.Photos.Score.Shared, review.Photos.Score.OnlyHere, review.Photos.Score.OnlyThere));
Assert.True(review.Details.Any(d => d.Path.StartsWith("exposure", StringComparison.Ordinal)));
Assert.Empty(review.Can.Blocks);
Assert.True(review.Can.Integrate);
Assert.True(review.Can.LinkOnly);
Assert.False(review.Can.DeleteThere);
Assert.Equal(pair.Id, review.Copy.Id);
Assert.Equal(localId, review.Copy.LocalId);
Assert.Equal(remote.Id, review.Copy.RemoteId);
}
[Test]
public async Task AnOlderServerOrMissingRightsBlockIntegrateButNotLinkOnly()
{
await using var f = await SyncFixture.CreateAsync(context);
var (pair, _, _) = await AskedAsync(f);
var review = await Builder(f).BuildAsync(pair, f.Remote, Context(canUpload: false, canDelete: true), f.Ct);
Assert.SequenceEqual([CopyBlock.NeedsNewerServer, CopyBlock.NoUploadRight], review.Can.Blocks);
Assert.False(review.Can.Integrate);
Assert.True(review.Can.LinkOnly);
Assert.True(review.Can.DeleteThere);
}
[Test]
public async Task ALinkToAnotherCopyIsTaken()
{
await using var f = await SyncFixture.CreateAsync(context);
f.Remote.Capabilities.Add(ServerCapabilities.PhotoLookup);
f.Remote.Capabilities.Add(ServerCapabilities.UploadInto);
var (pair, localId, _) = await AskedAsync(f);
var other = f.Remote.Add("Harbour", f.NewPhotos(1));
await f.Sync.LinkAsync(f.Server, other.Id, localId, f.Ct);
var review = await Builder(f).BuildAsync(pair, f.Remote, Context(), f.Ct);
Assert.Contains(CopyBlock.LinkTaken, review.Can.Blocks);
Assert.False(review.Can.Integrate);
Assert.False(review.Can.LinkOnly);
}
[Test]
public async Task TwoLocalCopiesCanBeMergedNeverLinked()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
await f.LocalAsync("Comet", photos);
await f.LocalAsync("Comet (card)", photos.Take(2).ToList(), SyncFixture.Window41);
var pair = (await f.Sync.Finder.FindLocalAsync(f.Ct)).New.Single();
var review = await Builder(f).BuildAsync(pair, null, Context(), f.Ct);
Assert.Equal((2, 1, 0), (review.Photos.Score.Shared, review.Photos.Score.OnlyHere + review.Photos.Score.OnlyThere, review.Photos.Score.Differs));
Assert.Equal(f.Archive.Archive.Id, review.There.ArchiveId);
Assert.NotEmpty(review.Details);
Assert.True(review.Can.Integrate);
Assert.False(review.Can.LinkOnly);
Assert.False(review.Can.DeleteThere);
}
[Test]
public async Task AServerPairNeedsItsServer()
{
await using var f = await SyncFixture.CreateAsync(context);
var (pair, _, _) = await AskedAsync(f);
await Assert.ThrowsAsync<ArgumentException>(() => Builder(f).BuildAsync(pair, null, Context(), f.Ct));
await Assert.ThrowsAsync<ArgumentException>(() =>
Builder(f).BuildAsync(pair, new FakeSyncRemote { Server = "https://other.test:8443" }, Context(), f.Ct));
}
}
@@ -0,0 +1,180 @@
using Chronos.Core.Project;
using Chronos.Data.Copies;
using Chronos.Testing;
namespace Chronos.Data.Tests.Copies;
/// <summary>The detection rules (owner review 6, Q1; design §3.1, §3.2, §3.6): pairs, the Link matches setting, 1.1's gate, asking again.</summary>
[Category("sync")]
public sealed class CopyRulesTests
{
private static readonly DateTime First = new(2026, 9, 28, 18, 0, 0, 400);
private static CopyScore Identical(int shared = 10, int unhashed = 0) =>
CopyScore.None with { Shared = shared, SharedUnhashed = unhashed, LocalPhotos = shared + unhashed, OtherPhotos = shared + unhashed, Containment = 1000, Overlap = 1000 };
private static CopyScore Partial(int shared, int onlyHere) =>
CopyScore.None with { Shared = shared, OnlyHere = onlyHere, LocalPhotos = shared + onlyHere, OtherPhotos = shared, Containment = 1000 };
/// <summary>1.1's gate passing: both unlinked, same second, same camera, half of 10 shared.</summary>
private static SameOriginalsInput Gate(int shared = 5) => new(true, First, First.AddMilliseconds(300), "EOS R5", "eos r5", 10, 10, shared);
private static readonly SameOriginalsInput Closed = new(false, null, null, null, null, 0, 0, 0);
private static FoundCopy KeptApart(int answeredShared, string? fingerprint = null) => new()
{
Id = Guid.NewGuid(),
Kind = CopyKind.LocalServer,
LocalId = Guid.NewGuid(),
Server = "https://nas.test:8443",
RemoteId = Guid.NewGuid(),
Evidence = CopyEvidence.Hashes,
State = CopyState.KeptApart,
Score = Partial(answeredShared, 5),
Fingerprint = "f",
AnsweredShared = answeredShared,
AnsweredFingerprint = fingerprint,
};
[Test]
public void APairNeedsALinkASessionKeyOrEnoughShared()
{
Assert.True(CopyRules.IsCopy(CopyEvidence.Link, CopyScore.None));
Assert.True(CopyRules.IsCopy(CopyEvidence.SessionKey, CopyScore.None));
Assert.False(CopyRules.IsCopy(CopyEvidence.Hashes, CopyScore.None));
Assert.True(CopyRules.IsCopy(CopyEvidence.Hashes, CopyScore.None with { Shared = 1, Containment = 100 }));
Assert.False(CopyRules.IsCopy(CopyEvidence.Hashes, CopyScore.None with { Shared = 1, Containment = 99 }));
// Tombstoned content is evidence too.
Assert.True(CopyRules.IsCopy(CopyEvidence.Hashes, CopyScore.None with { SharedRemoved = 3, Containment = 300 }));
Assert.True(CopyRules.IsCopy(CopyEvidence.SizeAndTime, CopyScore.None with { SharedUnhashed = 2, Containment = 1000 }));
}
[Test]
public void AskAlwaysNeverLinks()
{
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.AskAlways, CopyKind.LocalServer, Identical(), Gate()));
Assert.Equal(CopyDecision.None, CopyRules.Decide(CopyLinking.AskAlways, CopyKind.LocalServer, CopyScore.None, Gate()));
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.AskAlways, CopyKind.LocalServer, CopyScore.None, Closed, CopyEvidence.SessionKey));
}
[Test]
public void WhenIdenticalLinksOnlyTheSamePhotosKnownByHash()
{
Assert.Equal(CopyDecision.Link, CopyRules.Decide(CopyLinking.WhenIdentical, CopyKind.LocalServer, Identical(), Closed));
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenIdentical, CopyKind.LocalServer, Partial(10, 1), Gate()));
// A size and time identity always asks.
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenIdentical, CopyKind.LocalServer, Identical(8, 2), Closed));
// Photos deleted on one side only are no identity.
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenIdentical, CopyKind.LocalServer, Identical() with { DeletedThere = 1, SharedRemoved = 1 }, Closed));
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenIdentical, CopyKind.LocalServer, Identical() with { DeletedHere = 1, SharedRemoved = 1 }, Closed));
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenIdentical, CopyKind.LocalServer, Identical() with { Differs = 1 }, Closed));
}
[Test]
public void IdenticalNeedsNothingDeletedOnOneSide()
{
Assert.True(Identical().Identical);
Assert.False((Identical() with { DeletedHere = 1 }).Identical);
Assert.False((Identical() with { DeletedThere = 1 }).Identical);
Assert.False(CopyScore.None.Identical);
}
[Test]
public void WhenHalfSharedKeeps11sGates()
{
Assert.Equal(CopyDecision.Link, CopyRules.Decide(CopyLinking.WhenHalfShared, CopyKind.LocalServer, Partial(5, 5), Gate()));
// A different first-capture second, or another camera: asked.
var otherSecond = Gate() with { RemoteFirst = First.AddSeconds(1) };
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenHalfShared, CopyKind.LocalServer, Partial(5, 5), otherSecond));
var otherCamera = Gate() with { RemoteCamera = "EOS R6" };
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenHalfShared, CopyKind.LocalServer, Partial(5, 5), otherCamera));
// Fewer than half of the smaller side, nothing hashed here, or a side linked already: asked.
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenHalfShared, CopyKind.LocalServer, Partial(4, 6), Gate(4)));
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenHalfShared, CopyKind.LocalServer, Partial(5, 5), Gate() with { LocalHashed = 0 }));
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenHalfShared, CopyKind.LocalServer, Partial(5, 5), Gate() with { BothUnlinked = false }));
}
[Test]
public void SameOriginalsIsThe11Rule()
{
Assert.True(CopyRules.SameOriginals(Gate()));
// Half of the smaller side: 3 of a 6-frame server sequence is enough against 10 local hashes.
Assert.True(CopyRules.SameOriginals(Gate(3) with { RemoteFrames = 6 }));
Assert.False(CopyRules.SameOriginals(Gate(0) with { RemoteFrames = 0 }));
Assert.False(CopyRules.SameOriginals(Gate() with { LocalFirst = null }));
// Both without a camera model count as equal, as in 1.1.
Assert.True(CopyRules.SameOriginals(Gate() with { LocalCamera = null, RemoteCamera = null }));
}
[Test]
public void ALocalPairIsNeverLinkedByItself()
{
foreach (var linking in Enum.GetValues<CopyLinking>())
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(linking, CopyKind.LocalLocal, Identical(), Gate()));
}
[Test]
public void AKeptApartPairAsksAgainOnlyWhenItGrewALotOrBecameIdentical()
{
// Ten more shared photos at least, and a quarter of the answered count.
Assert.False(CopyRules.AsksAgain(KeptApart(20), Partial(29, 5)));
Assert.True(CopyRules.AsksAgain(KeptApart(20), Partial(30, 5)));
Assert.False(CopyRules.AsksAgain(KeptApart(100), Partial(124, 5)));
Assert.True(CopyRules.AsksAgain(KeptApart(100), Partial(125, 5)));
// Identical now, and not when answered.
Assert.True(CopyRules.AsksAgain(KeptApart(20, CopyRules.Fingerprint(Partial(20, 5), 1, 1)), Identical(20)));
// Kept apart while identical: an identity is no news.
Assert.False(CopyRules.AsksAgain(KeptApart(20, CopyRules.Fingerprint(Identical(20), 1, 1)), Identical(20)));
// Only kept-apart pairs ask again.
Assert.False(CopyRules.AsksAgain(KeptApart(20) with { State = CopyState.Linked }, Partial(90, 5)));
}
[Test]
public void FingerprintsFollowTheScoreAndTheVersions()
{
var a = CopyRules.Fingerprint(Partial(5, 5), 3, 4);
Assert.Equal(a, CopyRules.Fingerprint(Partial(5, 5), 3, 4));
Assert.NotEqual(a, CopyRules.Fingerprint(Partial(5, 5), 3, 5));
Assert.NotEqual(a, CopyRules.Fingerprint(Partial(6, 5), 3, 4));
var plan = CopyRules.PlanFingerprint(["send a", "fetch b"]);
Assert.Equal(64, plan.Length);
Assert.Equal(plan, CopyRules.PlanFingerprint(["send a", "fetch b"]));
Assert.NotEqual(plan, CopyRules.PlanFingerprint(["fetch b", "send a"]));
Assert.Equal("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", CopyRules.PlanFingerprint([]));
}
[Test]
public void AProbeIsEvenlySpacedWithTheFirstAndTheLast()
{
var photos = Enumerable.Range(0, 1000).Select(i => new FramePhoto(i.ToString("x64"), i, null)).ToList();
var probe = CopyRules.Probe(photos);
Assert.Count(64, probe);
Assert.Same(photos[0], probe[0]);
Assert.Same(photos[^1], probe[^1]);
Assert.Count(64, probe.Distinct());
var gaps = probe.Zip(probe.Skip(1), (a, b) => b.Size - a.Size).ToList();
Assert.InRange(gaps.Min(), 15, 16);
Assert.InRange(gaps.Max(), 15, 16);
Assert.Count(10, CopyRules.Probe(photos.Take(10).ToList()));
Assert.SequenceEqual([photos[0], photos[999]], CopyRules.Probe(photos, 2));
Assert.Empty(CopyRules.Probe([]));
}
[Test]
public void HintsScoreRangeCameraIntervalAndTitle()
{
var start = new DateTime(2026, 9, 28, 18, 0, 0);
var a = new CopyHintsInput(start, start.AddHours(2), "EOS R5", 5, "Harbour sunset");
Assert.Equal(100, CopyRules.Hints(a, a with { Camera = "eos r5", Title = "harbour" }));
// Half of the shorter range shared: 20.
Assert.Equal(20, CopyRules.Hints(a, new CopyHintsInput(start.AddHours(1), start.AddHours(3), null, null, null)));
Assert.Equal(25, CopyRules.Hints(a, new CopyHintsInput(null, null, "EOS R5", null, null)));
Assert.Equal(20, CopyRules.Hints(a, new CopyHintsInput(null, null, null, 5.4, null)));
Assert.Equal(0, CopyRules.Hints(a, new CopyHintsInput(null, null, null, 6, "Sun")));
// A null Last reads as First: a sequence with its first capture inside the other's range overlaps fully.
Assert.Equal(40, CopyRules.Hints(a, new CopyHintsInput(start.AddMinutes(30), null, null, null, null)));
Assert.Equal(0, CopyRules.Hints(a, new CopyHintsInput(start.AddHours(3), null, null, null, null)));
Assert.Equal(40, CopyRules.Hints(new CopyHintsInput(start, null, null, null, null), new CopyHintsInput(start, null, null, null, null)));
}
}
@@ -0,0 +1,130 @@
using Chronos.Core.Model;
using Chronos.Data.Copies;
using Chronos.Data.Sync;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Data.Tests.Sync;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Copies;
/// <summary>The two sides of a comparison read from the index and from a server, and the last-copy check (owner review 6, #73; design §4.2).</summary>
[Category("sync")]
public abstract class CopySidesTests(TestContext context) : RepositoryTest(context)
{
private static string Sha(int n) => Convert.ToHexStringLower(BitConverter.GetBytes((long)n)).PadLeft(64, 'c');
private async Task<(Archive Archive, Sequence Sequence)> SequenceAsync(ChronosDatabase db, Archive? archive = null)
{
if (archive is null)
{
archive = TestData.Archive("A" + Guid.NewGuid().ToString("N")[..6]);
await db.Archives.UpsertAsync(archive, Ct);
}
var sequence = TestData.Sequence(archive.Id);
await db.Sequences.UpsertAsync(sequence, Ct);
return (archive, sequence);
}
private async Task<Frame> FrameAsync(ChronosDatabase db, Guid sequenceId, int index, string? sha, FrameFlags flags = FrameFlags.None)
{
var frame = TestData.Frame(sequenceId, index) with { Sha256 = sha, Flags = flags };
await db.Frames.InsertAsync(frame, Ct);
return frame;
}
[Test]
public async Task ALocalSideHoldsItsFramesTombstonesAndUnusableFlags()
{
var db = await OpenChronosAsync();
var (_, sequence) = await SequenceAsync(db);
var frames = new[]
{
await FrameAsync(db, sequence.Id, 0, Sha(0)),
await FrameAsync(db, sequence.Id, 1, Sha(1), FrameFlags.Missing),
await FrameAsync(db, sequence.Id, 2, Sha(2), FrameFlags.Corrupt | FrameFlags.Excluded),
await FrameAsync(db, sequence.Id, 3, null),
await FrameAsync(db, sequence.Id, 4, Sha(4), FrameFlags.Excluded),
};
await db.FrameRemovals.SyncSequenceAsync(sequence.Id,
[
new FrameRemoval(sequence.Id, Sha(8), null, RemovalReason.Deleted, TestData.Now),
new FrameRemoval(sequence.Id, Sha(9), Sha(4), RemovalReason.Replaced, TestData.Now.AddMinutes(1)),
], Ct);
var side = await new CopySides(db).LocalAsync(sequence.Id, Ct);
Assert.SequenceEqual(frames.Select(f => f.Id), side.Photos.Select(p => p.FrameId));
Assert.SequenceEqual([false, true, true, false, false], side.Photos.Select(p => p.Unusable));
Assert.Null(side.Photos[3].Sha256);
Assert.Equal((frames[0].FileName, frames[0].Size, frames[0].CapturedAt), (side.Photos[0].FileName, side.Photos[0].Size, side.Photos[0].CapturedAt));
Assert.SequenceEqual([(Sha(8), (string?)null, "deleted"), (Sha(9), Sha(4), "replaced")], side.Removed.Select(r => (r.Sha256, r.Replacement, r.Reason)));
// Compared with a copy holding every photo, the unusable frames are repaired and the converted one is the same photo.
var there = new CopySideInput([.. Enumerable.Range(0, 5).Select(i => new CopyPhotoInput(Guid.NewGuid(), i, frames[i].FileName,
i == 4 ? Sha(9) : Sha(i), frames[i].Size, frames[i].CapturedAt, false))], []);
var result = CopyComparer.Compare(side, there);
Assert.Equal((2, 1, 2), (result.Score.Shared, result.Score.SharedUnhashed, result.Score.OnlyThere));
Assert.True(result.Of(PhotoClass.OnlyThere).All(p => p.RepairsHere));
Assert.Equal(Sha(9), Assert.Contains(result.Photos, p => p.Class == PhotoClass.Converted).There!.Sha256);
}
[Test]
public async Task ARemoteSideTakesCaptureTimesFromTheFrameRows()
{
var db = await OpenChronosAsync();
using var remote = new FakeSyncRemote();
var at = new DateTime(2026, 9, 28, 18, 0, 0, 120);
var sequence = remote.Add("Harbour", []);
sequence.AddFrame([1, 2, 3], "IMG_0001.JPG", at);
sequence.AddFrame([4, 5, 6], "IMG_0002.JPG", at.AddSeconds(5));
sequence.Removed.Add(new RemovedPhotoDto(Sha(7), null, "deleted", TestData.Now));
var side = await new CopySides(db).RemoteAsync(remote, sequence.Id, Ct);
Assert.SequenceEqual(sequence.Frames.Select(f => (f.Id, f.FileName, f.Sha256, (long)f.Bytes.Length, f.CapturedAt)),
side.Photos.Select(p => (p.FrameId, p.FileName, p.Sha256!, p.Size, p.CapturedAt)));
Assert.True(side.Photos.All(p => !p.Unusable));
Assert.SequenceEqual([Sha(7)], side.Removed.Select(r => r.Sha256));
// A server that never hashed its originals lists none: they compare by size and time.
sequence.Unhashed = true;
Assert.True((await new CopySides(db).RemoteAsync(remote, sequence.Id, Ct)).Photos.All(p => p.Sha256 is null));
}
[Test]
public async Task HeldElsewhereLooksAcrossEveryArchiveOfTheIndex()
{
var db = await OpenChronosAsync();
var (_, mine) = await SequenceAsync(db);
var (other, inOther) = await SequenceAsync(db);
var (_, alsoInOther) = await SequenceAsync(db, other);
await FrameAsync(db, mine.Id, 0, Sha(1));
await FrameAsync(db, mine.Id, 1, Sha(2));
await FrameAsync(db, mine.Id, 2, Sha(3));
await FrameAsync(db, inOther.Id, 0, Sha(1));
await FrameAsync(db, alsoInOther.Id, 0, Sha(2), FrameFlags.Missing);
await FrameAsync(db, alsoInOther.Id, 1, Sha(4));
var sides = new CopySides(db);
var held = await sides.HeldElsewhereAsync([Sha(1).ToUpperInvariant(), Sha(2), Sha(3), Sha(4), string.Empty], [mine.Id], Ct);
// Photo 2's other frame is missing: it holds nothing. Photo 3 is only in the compared sequence.
Assert.True(held.SetEquals([Sha(1), Sha(4)]));
Assert.True((await sides.HeldElsewhereAsync([Sha(1), Sha(4)], [mine.Id, inOther.Id, alsoInOther.Id], Ct)).Count == 0);
Assert.True((await sides.HeldElsewhereAsync([Sha(1)], [], Ct)).SetEquals([Sha(1)]));
Assert.Empty(await sides.HeldElsewhereAsync([], [mine.Id], Ct));
// Batched: more hashes than one statement takes.
var many = Enumerable.Range(100, 1200).Select(Sha).Append(Sha(4)).ToList();
Assert.True((await sides.HeldElsewhereAsync(many, [mine.Id], Ct)).SetEquals([Sha(4)]));
}
}
public sealed class SqliteCopySidesTests(TestContext context) : CopySidesTests(context)
{
protected override Backend Backend => Backend.SqliteMemory;
}
[RequiresEnvironment(PgTestServer.Variable)]
public sealed class PostgresCopySidesTests(TestContext context) : CopySidesTests(context)
{
protected override Backend Backend => Backend.Postgres;
}
@@ -0,0 +1,446 @@
using Chronos.Core.Model;
using Chronos.Data.Copies;
using Chronos.Data.Sync;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Testing;
namespace Chronos.Data.Tests.Copies;
/// <summary>The found copies store (owner review 6, #73, migration 0012): pairs, answers, the Integrating backstop, merges and 404s.</summary>
[Category("sync")]
public abstract class FoundCopyStoreTests(TestContext context) : RepositoryTest(context)
{
private const string Nas = "https://nas.test:8443";
private const string Other = "id:server-b";
private async Task<(ChronosDatabase Db, Archive Archive, Sequence[] Sequences)> SetupAsync(int count)
{
var db = await OpenChronosAsync();
var archive = TestData.Archive();
await db.Archives.UpsertAsync(archive, Ct);
var sequences = new Sequence[count];
for (var i = 0; i < count; i++)
{
sequences[i] = TestData.Sequence(archive.Id);
await db.Sequences.UpsertAsync(sequences[i], Ct);
}
return (db, archive, sequences);
}
private static FoundCopy Remote(Guid localId, Guid remoteId, string server = Nas, CopyEvidence evidence = CopyEvidence.Hashes) => new()
{
Id = Guid.NewGuid(),
Kind = CopyKind.LocalServer,
LocalId = localId,
Server = server,
RemoteId = remoteId,
Evidence = evidence,
Fingerprint = "f1",
};
private static FoundCopy Local(Guid a, Guid b) => new()
{
Id = Guid.NewGuid(),
Kind = CopyKind.LocalLocal,
LocalId = a,
OtherId = b,
Evidence = CopyEvidence.Hashes,
Fingerprint = "f1",
};
private static SyncLink Link(string server, Guid remoteId, Guid localId) => new()
{
Server = server,
RemoteId = remoteId,
LocalId = localId,
Title = "Harbour",
RemoteUpdatedAt = TestData.Now,
DiffLocalFrames = 3,
BaseLocalSettings = 2,
MissingRemote = 4,
};
private static CopyAnswer Answer(Guid? job = null, bool? auto = null, string? fingerprint = null, int? shared = null) =>
new(fingerprint, shared, job, auto, TestData.Now);
private async Task<Job> JobAsync(ChronosDatabase db, JobKind kind = JobKind.Integrate)
{
var job = TestData.Job(kind);
await db.Jobs.EnqueueAsync(job, Ct);
return job;
}
[Test]
public async Task ThePruneOfAStaleCandidateLeavesARowAnsweredMeanwhile()
{
var (db, _, s) = await SetupAsync(2);
var store = new FoundCopyStore(db);
var stale = await store.UpsertFoundAsync(Remote(s[0].Id, Guid.CreateVersion7()), Ct);
var answered = await store.UpsertFoundAsync(Remote(s[1].Id, Guid.CreateVersion7()), Ct);
// Detection read both as candidates; the user keeps one apart before the prune runs.
Assert.True(await store.SetStateAsync(answered.Id, CopyState.Candidate, CopyState.KeptApart, Answer(), Ct));
Assert.True(await store.DeleteCandidateAsync(stale.Id, Ct));
Assert.False(await store.DeleteCandidateAsync(answered.Id, Ct));
Assert.Null(await store.GetAsync(stale.Id, Ct));
Assert.Equal(CopyState.KeptApart, (await store.GetAsync(answered.Id, Ct))!.State);
}
[Test]
public async Task AnUpsertUpdatesScoresAndKeepsTheStateAndTheStrongerEvidence()
{
var (db, _, s) = await SetupAsync(1);
var store = new FoundCopyStore(db);
var remote = Guid.CreateVersion7();
var found = await store.UpsertFoundAsync(Remote(s[0].Id, remote) with { Score = CopyScore.None with { Shared = 3 } }, Ct);
Assert.Equal((CopyState.Candidate, CopyEvidence.Hashes, 3), (found.State, found.Evidence, found.Score.Shared));
Assert.True(await store.SetStateAsync(found.Id, CopyState.Candidate, CopyState.KeptApart, Answer(fingerprint: "f1", shared: 3), Ct));
var again = await store.UpsertFoundAsync(Remote(s[0].Id, remote, evidence: CopyEvidence.SizeAndTime) with
{
Score = CopyScore.None with { Shared = 5 },
Fingerprint = "f2",
LocalFramesVersion = 7,
}, Ct);
Assert.Equal(found.Id, again.Id);
Assert.Equal((CopyState.KeptApart, CopyEvidence.Hashes, 5, "f2", 7), (again.State, again.Evidence, again.Score.Shared, again.Fingerprint, again.LocalFramesVersion));
Assert.Equal(("f1", (int?)3), (again.AnsweredFingerprint, again.AnsweredShared));
Assert.Count(1, await store.ListAsync(Ct));
}
[Test]
public async Task ALocalPairIsStoredOnceInOrder()
{
var (db, _, s) = await SetupAsync(2);
var store = new FoundCopyStore(db);
var (low, high) = FoundCopyStore.Order(s[0].Id, s[1].Id);
var stored = await store.UpsertFoundAsync(Local(high, low) with { LocalFramesVersion = 1, OtherFramesVersion = 2 }, Ct);
Assert.Equal((low, (Guid?)high), (stored.LocalId, stored.OtherId));
// The sides swap with the ids.
Assert.Equal((2, 1), (stored.LocalFramesVersion, stored.OtherFramesVersion));
var same = await store.UpsertFoundAsync(Local(low, high), Ct);
Assert.Equal(stored.Id, same.Id);
Assert.Equal(stored.Id, (await store.FindLocalAsync(high, low, Ct))!.Id);
Assert.Count(1, await store.ListByLocalAsync(high, Ct));
}
[Test]
public async Task SetStateIsACompareAndSetAndIntegratingKeepsWhereItCameFrom()
{
var (db, _, s) = await SetupAsync(1);
var store = new FoundCopyStore(db);
var row = await store.UpsertFoundAsync(Remote(s[0].Id, Guid.CreateVersion7()), Ct);
Assert.False(await store.SetStateAsync(row.Id, CopyState.Linked, CopyState.KeptApart, null, Ct));
await Assert.ThrowsAsync<ArgumentException>(() => store.SetStateAsync(row.Id, null, CopyState.Integrating, Answer(), Ct));
Assert.False(await store.SetStateAsync(Guid.NewGuid(), null, CopyState.KeptApart, null, Ct));
var job = await JobAsync(db);
Assert.True(await store.SetStateAsync(row.Id, CopyState.Candidate, CopyState.Integrating, Answer(job.Id), Ct));
var integrating = (await store.GetAsync(row.Id, Ct))!;
Assert.Equal((CopyState.Integrating, (CopyState?)CopyState.Candidate, (Guid?)job.Id), (integrating.State, integrating.PreviousState, integrating.JobId));
Assert.True(await store.SetStateAsync(row.Id, CopyState.Integrating, CopyState.Integrated, Answer(auto: true), Ct));
var done = (await store.GetAsync(row.Id, Ct))!;
Assert.Equal((CopyState.Integrated, (CopyState?)null, (Guid?)null, true), (done.State, done.PreviousState, done.JobId, done.AutoPhotos));
// Auto photos hold only while Integrated.
Assert.True(await store.SetStateAsync(row.Id, null, CopyState.Linked, null, Ct));
Assert.False((await store.GetAsync(row.Id, Ct))!.AutoPhotos);
}
[Test]
public async Task AnIntegratingRowWhoseJobFailedOrWasCancelledReadsAsItsPreviousState()
{
var (db, _, s) = await SetupAsync(2);
var store = new FoundCopyStore(db);
foreach (var (sequence, end) in new[] { (s[0], JobState.Failed), (s[1], JobState.Cancelled) })
{
var row = await store.UpsertFoundAsync(Remote(sequence.Id, Guid.CreateVersion7()), Ct);
Assert.True(await store.SetStateAsync(row.Id, null, CopyState.KeptApart, Answer(fingerprint: "f1"), Ct));
var job = await JobAsync(db);
Assert.True(await store.SetStateAsync(row.Id, CopyState.KeptApart, CopyState.Integrating, Answer(job.Id), Ct));
Assert.Equal(CopyState.Integrating, (await store.GetAsync(row.Id, Ct))!.State);
await db.Jobs.SetStateAsync(job.Id, end, null, Ct);
var read = (await store.GetAsync(row.Id, Ct))!;
Assert.Equal((CopyState.KeptApart, (Guid?)null, (CopyState?)null), (read.State, read.JobId, read.PreviousState));
// The compare-and-set sees the state it reads as.
Assert.False(await store.SetStateAsync(row.Id, CopyState.Integrating, CopyState.Integrated, null, Ct));
Assert.True(await store.SetStateAsync(row.Id, CopyState.KeptApart, CopyState.Candidate, null, Ct));
}
}
[Test]
public async Task PairsGoWithTheirSequenceAndSurviveItsUpsert()
{
var (db, _, s) = await SetupAsync(3);
var store = new FoundCopyStore(db);
await store.UpsertFoundAsync(Remote(s[0].Id, Guid.CreateVersion7()), Ct);
await store.UpsertFoundAsync(Local(s[0].Id, s[1].Id), Ct);
await store.UpsertFoundAsync(Local(s[1].Id, s[2].Id), Ct);
await store.SetProbeAsync(new CopyProbe(s[0].Id, Nas, 1, 1, TestData.Now), Ct);
// A Rebuild writes the sequence row again: its pairs stay.
await db.Sequences.UpsertAsync(s[0] with { Title = "Harbour" }, Ct);
Assert.Count(3, await store.ListAsync(Ct));
Assert.True(await db.Sequences.DeleteAsync(s[0].Id, Ct));
var left = await store.ListAsync(Ct);
Assert.Count(1, left);
Assert.True(left[0].Names(s[1].Id) && left[0].Names(s[2].Id));
Assert.Null(await store.GetProbeAsync(s[0].Id, Nas, Ct));
}
[Test]
public async Task EnsureLinkedPromotesACandidateAndDemotesTheRowsTheLinkNoLongerBacks()
{
var (db, _, s) = await SetupAsync(2);
var store = new FoundCopyStore(db);
var (r1, r2) = (Guid.CreateVersion7(), Guid.CreateVersion7());
var candidate = await store.UpsertFoundAsync(Remote(s[0].Id, r1), Ct);
var linked = await store.EnsureLinkedAsync(Nas, r1, s[0].Id, Ct);
Assert.Equal(candidate.Id, linked.Id);
Assert.Equal((CopyState.Linked, CopyEvidence.Hashes), (linked.State, linked.Evidence));
var other = await store.EnsureLinkedAsync(Other, r1, s[0].Id, Ct);
Assert.Equal((CopyState.Linked, CopyEvidence.Link, "link"), (other.State, other.Evidence, other.Fingerprint));
// The link is pointed at another local copy: the old pair is a candidate again; the other server's stays.
var moved = await store.EnsureLinkedAsync(Nas, r1, s[1].Id, Ct);
Assert.Equal(CopyState.Linked, moved.State);
Assert.Equal(CopyState.Candidate, (await store.GetAsync(linked.Id, Ct))!.State);
Assert.Equal(CopyState.Linked, (await store.GetAsync(other.Id, Ct))!.State);
// The local copy is linked to another server sequence: the same.
await store.EnsureLinkedAsync(Nas, r2, s[1].Id, Ct);
Assert.Equal(CopyState.Candidate, (await store.GetAsync(moved.Id, Ct))!.State);
Assert.Count(4, await store.ListAsync(Ct));
}
[Test]
public async Task UploadAgainDeletesTheGoneRowLinkedOrKeptHere()
{
var (db, _, s) = await SetupAsync(2);
var store = new FoundCopyStore(db);
foreach (var (sequence, keptHere) in new[] { (s[0], false), (s[1], true) })
{
var (gone, fresh) = (Guid.CreateVersion7(), Guid.CreateVersion7());
var linked = await store.EnsureLinkedAsync(Nas, gone, sequence.Id, Ct);
// A refresh's 404 forgets the link (hit 1); the recheck counts the second.
await store.MarkRemoteGoneAsync(Nas, gone, sequence.Id, Guid.NewGuid(), TestData.Now, Ct);
await store.MarkRemoteGoneAsync(Nas, gone, sequence.Id, Guid.NewGuid(), TestData.Now.AddHours(1), Ct);
if (keptHere) Assert.True(await store.SetStateAsync(linked.Id, null, CopyState.KeptApart, Answer(), Ct));
Assert.True((await store.GetAsync(linked.Id, Ct))!.RemoteGone);
// Upload again: the first original creates a new server sequence and the link points at it.
var uploaded = await store.EnsureLinkedAsync(Nas, fresh, sequence.Id, Ct);
Assert.Null(await store.GetAsync(linked.Id, Ct));
var left = await store.ListByLocalAsync(sequence.Id, Ct);
Assert.Equal((uploaded.Id, CopyState.Linked, (Guid?)fresh, 0), (left.Single().Id, left.Single().State, left.Single().RemoteId, left.Single().RemoteGoneHits));
// Upload all local no longer reads it as deleted on the server.
var entry = new SyncEntry(sequence, null, SyncStatus.LocalOnly);
var (upload, skipped) = UploadAllRule.Select([entry], left, new HashSet<Guid>(), new HashSet<Guid>());
Assert.Empty(skipped);
Assert.Count(1, upload);
}
}
[Test]
public async Task A404CountsOncePerRefreshAndDeletesTheCandidatesOfThatRemote()
{
var (db, _, s) = await SetupAsync(2);
var store = new FoundCopyStore(db);
var remote = Guid.CreateVersion7();
// An observation-only link has no pair: nothing happens.
await store.MarkRemoteGoneAsync(Nas, remote, null, Guid.NewGuid(), TestData.Now, Ct);
Assert.Empty(await store.ListAsync(Ct));
var candidate = await store.UpsertFoundAsync(Remote(s[1].Id, remote), Ct);
var (first, second) = (Guid.NewGuid(), Guid.NewGuid());
await store.MarkRemoteGoneAsync(Nas, remote, s[0].Id, first, TestData.Now, Ct);
await store.MarkRemoteGoneAsync(Nas, remote, s[0].Id, first, TestData.Now.AddMinutes(1), Ct);
var row = (await store.FindRemoteAsync(s[0].Id, Nas, remote, Ct))!;
Assert.Equal((1, (DateTimeOffset?)TestData.Now, CopyEvidence.Link, false), (row.RemoteGoneHits, row.RemoteGoneAt, row.Evidence, row.RemoteGone));
Assert.Null(await store.GetAsync(candidate.Id, Ct));
await store.MarkRemoteGoneAsync(Nas, remote, s[0].Id, second, TestData.Now.AddHours(1), Ct);
row = (await store.GetAsync(row.Id, Ct))!;
Assert.Equal((2, (DateTimeOffset?)TestData.Now, true), (row.RemoteGoneHits, row.RemoteGoneAt, row.RemoteGone));
await store.ClearRemoteGoneAsync(Nas, remote, Ct);
row = (await store.GetAsync(row.Id, Ct))!;
Assert.Equal((0, (DateTimeOffset?)null), (row.RemoteGoneHits, row.RemoteGoneAt));
// After a clear the same refresh counts again.
await store.MarkRemoteGoneAsync(Nas, remote, s[0].Id, second, TestData.Now, Ct);
Assert.Equal(1, (await store.GetAsync(row.Id, Ct))!.RemoteGoneHits);
}
[Test]
public async Task A404OfAServerSequenceNoLocalCopyIsLinkedToDeletesItsCandidatesAndCountsOnItsKeptApartAnswers()
{
var (db, _, s) = await SetupAsync(4);
var store = new FoundCopyStore(db);
var remote = Guid.CreateVersion7();
var candidate = await store.UpsertFoundAsync(Remote(s[0].Id, remote), Ct);
var apart = await store.UpsertFoundAsync(Remote(s[1].Id, remote), Ct);
Assert.True(await store.SetStateAsync(apart.Id, CopyState.Candidate, CopyState.KeptApart, Answer(), Ct));
var linked = await store.UpsertFoundAsync(Remote(s[2].Id, remote), Ct);
Assert.True(await store.SetStateAsync(linked.Id, CopyState.Candidate, CopyState.Linked, Answer(), Ct));
var elsewhere = await store.UpsertFoundAsync(Remote(s[3].Id, Guid.CreateVersion7()), Ct);
// After the answers, an observation-only link answers 404: no local copy is linked to it.
var first = Guid.NewGuid();
await store.MarkRemoteGoneAsync(Nas, remote, null, first, TestData.Now.AddMinutes(1), Ct);
await store.MarkRemoteGoneAsync(Nas, remote, null, first, TestData.Now.AddMinutes(2), Ct);
// The unanswered match is gone; the Keep apart answer stays and counts the 404 once, not read as deleted yet.
Assert.Null(await store.GetAsync(candidate.Id, Ct));
var row = (await store.GetAsync(apart.Id, Ct))!;
Assert.Equal((CopyState.KeptApart, 1, false), (row.State, row.RemoteGoneHits, row.RemoteGone));
Assert.Equal(CopyState.Linked, (await store.GetAsync(linked.Id, Ct))!.State);
Assert.Equal(CopyState.Candidate, (await store.GetAsync(elsewhere.Id, Ct))!.State);
var entries = s[..2].Select(q => new SyncEntry(q, null, SyncStatus.LocalOnly)).ToList();
var (upload, skipped) = UploadAllRule.Select(entries, await store.ListAsync(Ct), new HashSet<Guid>(), new HashSet<Guid>());
Assert.Equal(s[0].Id, upload.Single().Local!.Id);
Assert.Equal((s[1].Id, UploadSkip.DeletedOnServer), (skipped.Single().Entry.Local!.Id, skipped.Single().Why));
// A second 404 within the re-check is the same moment; one after it confirms the deletion.
await store.MarkRemoteGoneAsync(Nas, remote, null, Guid.NewGuid(), TestData.Now.AddMinutes(5), Ct);
Assert.Equal(1, (await store.GetAsync(apart.Id, Ct))!.RemoteGoneHits);
await store.MarkRemoteGoneAsync(Nas, remote, null, Guid.NewGuid(), TestData.Now.AddHours(1), Ct);
row = (await store.GetAsync(apart.Id, Ct))!;
Assert.Equal((CopyState.KeptApart, true), (row.State, row.RemoteGone));
(upload, skipped) = UploadAllRule.Select(entries, await store.ListAsync(Ct), new HashSet<Guid>(), new HashSet<Guid>());
Assert.Empty(skipped);
Assert.Count(2, upload);
// Listed again: the count clears and the answer is the user's as before.
await store.ClearRemoteGoneAsync(Nas, remote, Ct);
row = (await store.GetAsync(apart.Id, Ct))!;
Assert.Equal((CopyState.KeptApart, 0), (row.State, row.RemoteGoneHits));
}
[Test]
public async Task MoveToKeptMovesKeysLinksAndPairsAndIsIdempotent()
{
var (db, archive, s) = await SetupAsync(4);
var (keep, drop, third, fourth) = (s[0], s[1], s[2], s[3]);
var store = new FoundCopyStore(db);
var links = new SyncLinkStore(db);
var (r1, r2, r3) = (Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7());
await db.Sequences.MapSessionKeyAsync(archive.Id, "upload-a", drop.Id, Ct);
await db.Sequences.MapSessionKeyAsync(archive.Id, "upload-c", third.Id, Ct);
await links.UpsertAsync(Link(Nas, r1, drop.Id), Ct);
var dropLink = await store.EnsureLinkedAsync(Nas, r1, drop.Id, Ct);
Assert.True(await store.SetStateAsync(dropLink.Id, CopyState.Linked, CopyState.Integrated, Answer(auto: true), Ct));
// keep already pairs with r2: drop's pair of r2 is the clash, deleted.
await store.UpsertFoundAsync(Remote(keep.Id, r2), Ct);
var clash = await store.UpsertFoundAsync(Remote(drop.Id, r2), Ct);
var self = await store.UpsertFoundAsync(Local(keep.Id, drop.Id), Ct);
var withThird = await store.UpsertFoundAsync(Local(drop.Id, third.Id), Ct);
await store.UpsertFoundAsync(Local(keep.Id, fourth.Id), Ct);
var withFourth = await store.UpsertFoundAsync(Local(drop.Id, fourth.Id), Ct);
var own = await store.UpsertFoundAsync(Remote(drop.Id, r3, Other), Ct);
var result = await store.MoveToKeptAsync(drop.Id, keep.Id, archive.Id, ["upload-a", "upload-b", "upload-c"], own.Id, Ct);
Assert.Equal((2, 1, 2), (result.SessionKeys, result.Links, result.Pairs));
Assert.SequenceEqual(["upload-c"], result.SkippedKeys);
Assert.Equal(keep.Id, await db.Sequences.FindBySessionKeyAsync(archive.Id, "upload-a", Ct));
Assert.Equal(keep.Id, await db.Sequences.FindBySessionKeyAsync(archive.Id, "upload-b", Ct));
Assert.Equal(third.Id, await db.Sequences.FindBySessionKeyAsync(archive.Id, "upload-c", Ct));
var link = (await links.GetAsync(Nas, r1, Ct))!;
Assert.Equal((keep.Id, (int?)null, (int?)null, 0), (link.LocalId!.Value, link.DiffLocalFrames, link.BaseLocalSettings, link.MissingRemote));
var moved = (await store.GetAsync(dropLink.Id, Ct))!;
Assert.Equal((keep.Id, CopyState.Linked, false, -1), (moved.LocalId, moved.State, moved.AutoPhotos, moved.LocalFramesVersion));
Assert.Null(await store.GetAsync(clash.Id, Ct));
Assert.Null(await store.GetAsync(self.Id, Ct));
Assert.Null(await store.GetAsync(withFourth.Id, Ct));
var third2 = (await store.GetAsync(withThird.Id, Ct))!;
Assert.True(third2.Names(keep.Id) && third2.Names(third.Id));
Assert.Equal((-1, -1), (third2.LocalFramesVersion, third2.OtherFramesVersion));
Assert.Equal(drop.Id, (await store.GetAsync(own.Id, Ct))!.LocalId);
var again = await store.MoveToKeptAsync(drop.Id, keep.Id, archive.Id, ["upload-a", "upload-b", "upload-c"], own.Id, Ct);
Assert.Equal((0, 0), (again.Links, again.Pairs));
Assert.SequenceEqual(["upload-c"], again.SkippedKeys);
Assert.Equal(keep.Id, await db.Sequences.FindBySessionKeyAsync(archive.Id, "upload-a", Ct));
}
[Test]
public async Task MoveToKeptIsRefusedBeforeAnyChangeWhenBothAreLinkedOnOneServer()
{
var (db, archive, s) = await SetupAsync(2);
var (keep, drop) = (s[0], s[1]);
var store = new FoundCopyStore(db);
var links = new SyncLinkStore(db);
await db.Sequences.MapSessionKeyAsync(archive.Id, "upload-a", drop.Id, Ct);
await links.UpsertAsync(Link(Nas, Guid.CreateVersion7(), keep.Id), Ct);
var dropRemote = Guid.CreateVersion7();
await links.UpsertAsync(Link(Nas, dropRemote, drop.Id), Ct);
var pair = await store.UpsertFoundAsync(Local(keep.Id, drop.Id), Ct);
await Assert.ThrowsAsync<CopyLinkTakenException>(() => store.MoveToKeptAsync(drop.Id, keep.Id, archive.Id, ["upload-a"], null, Ct));
Assert.Equal(drop.Id, await db.Sequences.FindBySessionKeyAsync(archive.Id, "upload-a", Ct));
Assert.Equal(drop.Id, (await links.GetAsync(Nas, dropRemote, Ct))!.LocalId);
Assert.NotNull(await store.GetAsync(pair.Id, Ct));
await Assert.ThrowsAsync<ArgumentException>(() => store.MoveToKeptAsync(keep.Id, keep.Id, archive.Id, [], null, Ct));
}
[Test]
public async Task LocalOverlapsCountHashesTombstonesAndSizeAndTime()
{
var (db, _, s) = await SetupAsync(4);
var store = new FoundCopyStore(db);
// s0 and s1 share frames 1 and 2 by hash (TestData.Frame's hash is its index's).
foreach (var i in new[] { 1, 2, 3 }) await db.Frames.InsertAsync(TestData.Frame(s[0].Id, i), Ct);
foreach (var i in new[] { 1, 2, 4 }) await db.Frames.InsertAsync(TestData.Frame(s[1].Id, i), Ct);
// s2 tombstoned frame 3 of s0.
await db.FrameRemovals.SyncSequenceAsync(s[2].Id, [new FrameRemoval(s[2].Id, TestData.Frame(s[0].Id, 3).Sha256!, null, RemovalReason.Deleted, TestData.Now)], Ct);
Assert.Empty((await store.LocalOverlapsAsync(Ct)).Where(o => o.SharedUnhashed > 0));
// s3 holds an unhashed frame of s1's size and capture time.
var unhashed = TestData.Frame(s[3].Id, 4) with { Sha256 = null };
await db.Frames.InsertAsync(unhashed, Ct);
var overlaps = (await store.LocalOverlapsAsync(Ct)).ToDictionary(o => (o.Low, o.High));
Assert.Equal(3, overlaps.Count);
Assert.Equal((2, 0, 0), Counts(overlaps[FoundCopyStore.Order(s[0].Id, s[1].Id)]));
Assert.Equal((0, 1, 0), Counts(overlaps[FoundCopyStore.Order(s[0].Id, s[2].Id)]));
Assert.Equal((0, 0, 1), Counts(overlaps[FoundCopyStore.Order(s[1].Id, s[3].Id)]));
foreach (var o in overlaps.Values) Assert.True(string.CompareOrdinal(o.Low.ToString("D"), o.High.ToString("D")) < 0);
static (int, int, int) Counts(LocalOverlap o) => (o.SharedHashes, o.SharedRemoved, o.SharedUnhashed);
}
[Test]
public async Task ProbesAndSyncSessionKeysRoundTrip()
{
var (db, archive, s) = await SetupAsync(2);
var store = new FoundCopyStore(db);
await store.SetProbeAsync(new CopyProbe(s[0].Id, Nas, 1, 1, TestData.Now), Ct);
await store.SetProbeAsync(new CopyProbe(s[0].Id, Nas, 2, 5, TestData.Now.AddMinutes(1)), Ct);
await store.SetProbeAsync(new CopyProbe(s[0].Id, string.Empty, 9, 9, TestData.Now), Ct);
Assert.Equal(new CopyProbe(s[0].Id, Nas, 2, 5, TestData.Now.AddMinutes(1)), await store.GetProbeAsync(s[0].Id, Nas, Ct));
await store.ResetProbesAsync(Nas, Ct);
Assert.Null(await store.GetProbeAsync(s[0].Id, Nas, Ct));
Assert.NotNull(await store.GetProbeAsync(s[0].Id, string.Empty, Ct));
var remote = Guid.CreateVersion7();
await db.Sequences.MapSessionKeyAsync(archive.Id, $"chronos-sync:{remote:N}", s[1].Id, Ct);
await db.Sequences.MapSessionKeyAsync(archive.Id, "chronos-sync:not-a-guid", s[1].Id, Ct);
await db.Sequences.MapSessionKeyAsync(archive.Id, "upload-1", s[0].Id, Ct);
Assert.SequenceEqual([(s[1].Id, remote)], await store.SyncSessionKeysAsync(Ct));
}
}
public sealed class SqliteFoundCopyStoreTests(TestContext context) : FoundCopyStoreTests(context)
{
protected override Backend Backend => Backend.SqliteMemory;
}
[RequiresEnvironment(PgTestServer.Variable)]
public sealed class PostgresFoundCopyStoreTests(TestContext context) : FoundCopyStoreTests(context)
{
protected override Backend Backend => Backend.Postgres;
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,91 @@
using Chronos.Core.Model;
using Chronos.Data.Copies;
using Chronos.Data.Sync;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Testing;
namespace Chronos.Data.Tests.Copies;
/// <summary>Upload all local (owner review 6, Q8): suspected, kept-apart, deleted, busy and server-born sequences stay here.</summary>
[Category("sync")]
public sealed class UploadAllRuleTests
{
private const string Nas = "https://nas.test:8443";
private static readonly Guid Archive = Guid.CreateVersion7();
private static SyncEntry Entry(Guid? archiveId = null) =>
new(TestData.Sequence(archiveId ?? Archive) with { FrameCount = 3 }, null, SyncStatus.LocalOnly);
private static FoundCopy Remote(Guid localId, CopyState state, int goneHits = 0) => new()
{
Id = Guid.NewGuid(),
Kind = CopyKind.LocalServer,
LocalId = localId,
Server = Nas,
RemoteId = Guid.CreateVersion7(),
Evidence = CopyEvidence.Hashes,
State = state,
Fingerprint = "f",
RemoteGoneHits = goneHits,
};
private static FoundCopy Local(Guid a, Guid b, CopyState state) => new()
{
Id = Guid.NewGuid(),
Kind = CopyKind.LocalLocal,
LocalId = a,
OtherId = b,
Evidence = CopyEvidence.Hashes,
State = state,
Fingerprint = "f",
};
[Test]
public void APlainLocalSequenceUploads()
{
var plain = Entry();
var linked = Entry();
var (upload, skipped) = UploadAllRule.Select([plain, linked], [Remote(linked.Local!.Id, CopyState.Linked)], new HashSet<Guid>(), new HashSet<Guid>());
Assert.SequenceEqual([plain.Local!.Id, linked.Local!.Id], upload.Select(e => e.Local!.Id));
Assert.Empty(skipped);
}
[Test]
public void EachReasonKeepsTheSequenceHereWithItsReason()
{
var (suspected, keptApart, other, gone, busy, integrating, born) = (Entry(), Entry(), Entry(), Entry(), Entry(), Entry(), Entry(Guid.CreateVersion7()));
FoundCopy[] copies =
[
Remote(suspected.Local!.Id, CopyState.Candidate),
// A local pair names its second sequence too.
Local(other.Local!.Id, keptApart.Local!.Id, CopyState.KeptApart),
// One 404 is enough to stay here: it is not uploaded as a new server sequence.
Remote(gone.Local!.Id, CopyState.Linked, goneHits: 1),
Remote(integrating.Local!.Id, CopyState.Integrating),
];
var (upload, skipped) = UploadAllRule.Select([suspected, keptApart, other, gone, busy, integrating, born], copies,
new HashSet<Guid> { born.Local!.ArchiveId }, new HashSet<Guid> { busy.Local!.Id });
Assert.Empty(upload);
var why = skipped.ToDictionary(s => s.Entry.Local!.Id, s => s.Why);
Assert.Equal(UploadSkip.SuspectedCopy, why[suspected.Local.Id]);
Assert.Equal(UploadSkip.KeptApart, why[keptApart.Local.Id]);
Assert.Equal(UploadSkip.KeptApart, why[other.Local.Id]);
Assert.Equal(UploadSkip.DeletedOnServer, why[gone.Local.Id]);
Assert.Equal(UploadSkip.Busy, why[busy.Local.Id]);
Assert.Equal(UploadSkip.Busy, why[integrating.Local.Id]);
Assert.Equal(UploadSkip.ServerOriginals, why[born.Local.Id]);
}
[Test]
public void BusyComesFirstAndAnEntryWithoutALocalSequenceIsNeither()
{
var entry = Entry();
var serverOnly = new SyncEntry(null, new SyncLink { Server = Nas, RemoteId = Guid.CreateVersion7(), Title = "Harbour" }, SyncStatus.RemoteOnly);
var (upload, skipped) = UploadAllRule.Select([entry, serverOnly], [Remote(entry.Local!.Id, CopyState.Candidate, goneHits: 2)],
new HashSet<Guid> { Archive }, new HashSet<Guid> { entry.Local.Id });
Assert.Empty(upload);
Assert.Equal((entry.Local.Id, UploadSkip.Busy), (skipped.Single().Entry.Local!.Id, skipped.Single().Why));
}
}
@@ -1,5 +1,6 @@
using Chronos.Core.IO;
using Chronos.Core.Project;
using Chronos.Data.Copies;
using Chronos.Data.Homes;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
@@ -202,6 +203,105 @@ public abstract class HomeRekeyLinkTests(TestContext context) : RepositoryTest(c
Assert.Count(1, await store.ListAsync(HomeFixtures.Other, Ct));
Assert.Empty(await store.ListAsync(HomeFixtures.Nas, Ct));
}
[Test]
public async Task TheMatchesAndProbesOfAnAliasMoveWithItsLinks()
{
var db = await OpenChronosAsync();
var (linked, found) = await TwoSequencesAsync(db);
var store = new SyncLinkStore(db);
var copies = new FoundCopyStore(db);
var (r1, r2) = (Guid.CreateVersion7(), Guid.CreateVersion7());
await store.UpsertAsync(Link(HomeFixtures.Nas, r1, linked, TestData.Now), Ct);
await copies.EnsureLinkedAsync(HomeFixtures.Nas, r1, linked, Ct);
await copies.UpsertFoundAsync(Candidate(HomeFixtures.Nas, r2, found), Ct);
await copies.SetProbeAsync(new CopyProbe(found, HomeFixtures.Nas, 3, 3, TestData.Now), Ct);
var migration = new HomeLayoutMigration(new HomeLayoutOptions { DataDirectory = Context.CreateTempDirectory("data"), Database = db });
var result = await migration.RekeyAsync(Id, [HomeFixtures.Nas, HomeFixtures.NasByIp], Ct);
Assert.Equal((1, 0), (result.LinksMoved, result.LinksDropped));
var key = ServerIdentity.IdKey(Id);
Assert.Empty(await copies.ListByServerAsync(HomeFixtures.Nas, Ct));
var moved = await copies.ListByServerAsync(key, Ct);
Assert.Count(2, moved);
Assert.Equal(CopyState.Linked, moved.Single(c => c.RemoteId == r1).State);
Assert.Equal(CopyState.Candidate, moved.Single(c => c.RemoteId == r2).State);
Assert.Null(await copies.GetProbeAsync(found, HomeFixtures.Nas, Ct));
Assert.Equal(3, (await copies.GetProbeAsync(found, key, Ct))!.FramesVersion);
}
[Test]
public async Task OnAClashThePairOfTheSurvivingLinkWinsElseTheHigherState()
{
var db = await OpenChronosAsync();
var (linked, found) = await TwoSequencesAsync(db);
var key = ServerIdentity.IdKey(Id);
var store = new SyncLinkStore(db);
var copies = new FoundCopyStore(db);
var (r1, r2) = (Guid.CreateVersion7(), Guid.CreateVersion7());
// The same link under both keys: the one compared last (the alias's) survives, and so does its pair, though the pair
// under the id is further on.
await store.UpsertAsync(Link(HomeFixtures.Nas, r1, linked, TestData.Now), Ct);
await store.UpsertAsync(Link(key, r1, linked, TestData.Now.AddHours(-1)), Ct);
var aliasPair = await copies.EnsureLinkedAsync(HomeFixtures.Nas, r1, linked, Ct);
var idPair = await copies.EnsureLinkedAsync(key, r1, linked, Ct);
Assert.True(await copies.SetStateAsync(idPair.Id, CopyState.Linked, CopyState.Integrated, new CopyAnswer(null, null, null, true, TestData.Now), Ct));
// A match without a link under both keys: the answered one wins over the newer candidate.
var keptApart = await copies.UpsertFoundAsync(Candidate(HomeFixtures.Nas, r2, found), Ct);
Assert.True(await copies.SetStateAsync(keptApart.Id, CopyState.Candidate, CopyState.KeptApart, new CopyAnswer("f", 4, null, null, TestData.Now), Ct));
var candidate = await copies.UpsertFoundAsync(Candidate(key, r2, found), Ct);
await copies.SetProbeAsync(new CopyProbe(found, HomeFixtures.Nas, 1, 1, TestData.Now), Ct);
await copies.SetProbeAsync(new CopyProbe(found, key, 2, 2, TestData.Now), Ct);
var (moved, dropped) = await store.RekeyAsync(HomeFixtures.Nas, key, Ct);
Assert.Equal((1, 1), (moved, dropped));
var rows = await copies.ListByServerAsync(key, Ct);
Assert.Count(2, rows);
var pair = rows.Single(c => c.RemoteId == r1);
Assert.Equal(aliasPair.Id, pair.Id);
Assert.Equal(CopyState.Linked, pair.State);
var match = rows.Single(c => c.RemoteId == r2);
Assert.Equal(keptApart.Id, match.Id);
Assert.NotEqual(candidate.Id, match.Id);
Assert.Equal(CopyState.KeptApart, match.State);
Assert.Empty(await copies.ListByServerAsync(HomeFixtures.Nas, Ct));
Assert.Equal(2, (await copies.GetProbeAsync(found, key, Ct))!.FramesVersion);
Assert.Null(await copies.GetProbeAsync(found, HomeFixtures.Nas, Ct));
}
private async Task<(Guid Linked, Guid Found)> TwoSequencesAsync(ChronosDatabase db)
{
var archive = TestData.Archive();
await db.Archives.UpsertAsync(archive, Ct);
var linked = TestData.Sequence(archive.Id);
var found = TestData.Sequence(archive.Id);
await db.Sequences.UpsertAsync(linked, Ct);
await db.Sequences.UpsertAsync(found, Ct);
return (linked.Id, found.Id);
}
private static SyncLink Link(string server, Guid remoteId, Guid localId, DateTimeOffset synced) => new()
{
Server = server,
RemoteId = remoteId,
LocalId = localId,
Title = "Harbour",
RemoteUpdatedAt = TestData.Now,
SyncedAt = synced,
};
private static FoundCopy Candidate(string server, Guid remoteId, Guid localId) => new()
{
Id = Guid.NewGuid(),
Kind = CopyKind.LocalServer,
LocalId = localId,
Server = server,
RemoteId = remoteId,
Evidence = CopyEvidence.Hashes,
Fingerprint = "f",
};
}
public sealed class SqliteHomeRekeyLinkTests(TestContext context) : HomeRekeyLinkTests(context)
@@ -462,6 +462,34 @@ public sealed class JobEngineTests(TestContext context)
foreach (var id in new[] { analysing.Id, followUp.Id, drawing.Id, other.Id }) await WaitForStateAsync(db, id, JobState.Done, TimeSpan.FromSeconds(10));
}
[Test]
public async Task ABackgroundJobNeverInterruptsEvenAtAHigherLevel()
{
// Owner review 6 (#73): an Integrate queued by itself at the end of a sync is High but Background; it waits for the
// running job instead of pausing it.
await using var db = await OpenAsync();
var release = new SemaphoreSlim(0);
var scan = new GatedHandler(JobKind.Scan, release);
var download = new GatedHandler(JobKind.Download, release);
var queue = new JobPriorityQueue { Enabled = true };
Assert.True(queue.Interrupts(JobKind.Download, JobKind.Scan));
await using var engine = new JobEngine(db, [scan, download],
new JobEngineOptions { WorkerId = "pc", PollInterval = TimeSpan.FromMilliseconds(50), PriorityQueue = () => queue });
await engine.StartAsync();
var scanning = await engine.EnqueueAsync(JobKind.Scan, []);
await UntilAsync(() => Volatile.Read(ref scan.Running) == 1, "the scan runs");
var downloading = await engine.EnqueueAsync(JobKind.Download, [], priority: JobPriority.Background);
await Task.Delay(400);
Assert.Equal((1, 0), (Volatile.Read(ref scan.Running), Volatile.Read(ref download.Started)));
Assert.Equal(JobState.Running, (await db.Jobs.GetAsync(scanning.Id))!.State);
Assert.False(await engine.ReviewAsync(context.Cancellation));
release.Release(10);
await WaitForStateAsync(db, scanning.Id, JobState.Done, TimeSpan.FromSeconds(10));
await WaitForStateAsync(db, downloading.Id, JobState.Done, TimeSpan.FromSeconds(10));
Assert.Equal(1, Volatile.Read(ref scan.Started));
}
[Test]
public async Task RequeueingAYieldedJobLeavesPausesAndOtherNodesAlone()
{
@@ -15,6 +15,8 @@ public sealed class JobWireTests
[Case(JobKind.WorkspaceSend, 22, "workspace-send")]
[Case(JobKind.WorkspaceMove, 23, "workspace-move")]
[Case(JobKind.VideoCopy, 24, "video-copy")]
[Case(JobKind.Integrate, 25, "integrate")]
[Case(JobKind.MergeSequences, 26, "merge-sequences")]
public void TheWorkspaceJobsKeepTheirValueAndName(JobKind kind, int value, string name)
{
Assert.Equal(value, (int)kind);
@@ -40,6 +42,9 @@ public sealed class JobWireTests
[Case(JobStep.CopyOriginal, 13, "copy-original")]
[Case(JobStep.FollowUps, 22, "follow-ups")]
[Case(JobStep.Process, 23, "process")]
[Case(JobStep.Details, 24, "details")]
[Case(JobStep.Projects, 25, "projects")]
[Case(JobStep.Trash, 26, "trash")]
public void StepsKeepTheirValueAndName(JobStep step, int value, string name)
{
Assert.Equal(value, (int)step);
@@ -0,0 +1,103 @@
using Chronos.Data.Migrations;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Testing;
namespace Chronos.Data.Tests.Migrations;
/// <summary>Migration 0012 (owner review 6, #73): found copies beside the links, every existing link a linked pair.</summary>
public abstract class FoundCopiesMigrationTests(TestContext context) : RepositoryTest(context)
{
[Test]
public async Task EveryLinkWithALocalSequenceBecomesOneLinkedPair()
{
var chronos = await OpenChronosAsync();
var database = chronos.Database;
var all = MigrationRunner.Load(Dialect);
Assert.Equal(12, all.Single(m => m.Name == "found_copies").Version);
var archive = TestData.Archive();
await chronos.Archives.UpsertAsync(archive, Ct);
var first = TestData.Sequence(archive.Id);
var second = TestData.Sequence(archive.Id);
await chronos.Sequences.UpsertAsync(first, Ct);
await chronos.Sequences.UpsertAsync(second, Ct);
var (r1, r2, r3) = (Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7());
await using (var session = await database.OpenAsync(Ct))
{
// Back to an index of 1.1 (schema 11) holding these links, then migrated again.
await session.ExecuteAsync("DROP TABLE copy_probes", [], Ct);
await session.ExecuteAsync("DROP TABLE found_copies", [], Ct);
await session.ExecuteAsync("DELETE FROM schema_migrations WHERE version = 12", [], Ct);
await Link(session, "https://nas.test:8443", r1, first.Id);
await Link(session, "id:server-b", r2, second.Id);
// An observation-only link (a server sequence this PC does not hold) is no pair.
await Link(session, "https://nas.test:8443", r3, null);
}
Assert.Equal(all[^1].Version, await MigrationRunner.MigrateAsync(database, Ct));
await using var after = await database.OpenAsync(Ct);
var rows = await after.QueryListAsync(
"SELECT id, kind, local_id, server, remote_id, other_id, evidence, state, fingerprint, auto_photos, remote_gone_hits, found_at FROM found_copies ORDER BY server",
[], r => r, Ct);
Assert.Equal(2, rows.Count);
Assert.Equal(2, rows.Select(r => r.GetGuid(0)).Distinct().Count());
foreach (var row in rows)
{
Assert.NotEqual(Guid.Empty, row.GetGuid(0));
Assert.Equal(0, row.GetInt32(1));
Assert.True(row.IsNull(5));
Assert.Equal(0, row.GetInt32(6));
Assert.Equal(2, row.GetInt32(7));
Assert.Equal("link", row.GetString(8));
Assert.False(row.GetBool(9));
Assert.Equal(0, row.GetInt32(10));
Assert.True(row.GetDateTimeOffset(11) > DateTimeOffset.UtcNow.AddMinutes(-5));
}
var pairs = rows.Select(r => (r.GetString(3), r.GetGuid(4), r.GetGuid(2))).ToHashSet();
Assert.Contains(("https://nas.test:8443", r1, first.Id), pairs);
Assert.Contains(("id:server-b", r2, second.Id), pairs);
// The ids are random version 4 UUIDs, in the form the binding writes.
foreach (var row in rows) Assert.Equal(4, row.GetGuid(0).Version);
// No change to the links.
Assert.Equal(3L, await after.ScalarAsync<long>("SELECT count(*) FROM sync_links", [], Ct));
}
[Test]
public async Task TheCheckRefusesAServerPairWithoutServerAndALocalPairOfOneSequence()
{
var chronos = await OpenChronosAsync();
var archive = TestData.Archive();
await chronos.Archives.UpsertAsync(archive, Ct);
var sequence = TestData.Sequence(archive.Id);
await chronos.Sequences.UpsertAsync(sequence, Ct);
await using var session = await chronos.Database.OpenAsync(Ct);
const string insert = "INSERT INTO found_copies (id, kind, local_id, server, remote_id, other_id, evidence, fingerprint, found_at, updated_at) " +
"VALUES ($1, $2, $3, $4, $5, $6, 2, 'f', $7, $7)";
await Assert.ThrowsAsync<DatabaseException>(() => session.ExecuteAsync(insert,
[Guid.NewGuid(), 0, sequence.Id, DbParam.Text(null), Guid.CreateVersion7(), (Guid?)null, TestData.Now], Ct));
await Assert.ThrowsAsync<DatabaseException>(() => session.ExecuteAsync(insert,
[Guid.NewGuid(), 1, sequence.Id, DbParam.Text(null), (Guid?)null, sequence.Id, TestData.Now], Ct));
await Assert.ThrowsAsync<DatabaseException>(() => session.ExecuteAsync(insert,
[Guid.NewGuid(), 1, sequence.Id, "https://nas.test:8443", (Guid?)null, Guid.CreateVersion7(), TestData.Now], Ct));
// A pair names existing sequences: a found copy goes with its sequence.
await Assert.ThrowsAsync<DatabaseException>(() => session.ExecuteAsync(insert,
[Guid.NewGuid(), 0, Guid.CreateVersion7(), "https://nas.test:8443", Guid.CreateVersion7(), (Guid?)null, TestData.Now], Ct));
await session.ExecuteAsync(insert, [Guid.NewGuid(), 0, sequence.Id, "https://nas.test:8443", Guid.CreateVersion7(), (Guid?)null, TestData.Now], Ct);
Assert.Equal(1L, await session.ScalarAsync<long>("SELECT count(*) FROM found_copies", [], Ct));
}
private static Task<int> Link(IDbSession session, string server, Guid remoteId, Guid? localId) =>
session.ExecuteAsync("INSERT INTO sync_links (server, remote_id, local_id, title, remote_updated_at) VALUES ($1, $2, $3, $4, $5)",
[server, remoteId, localId, "Remote", TestData.Now], CancellationToken.None);
}
public sealed class SqliteFoundCopiesMigrationTests(TestContext context) : FoundCopiesMigrationTests(context)
{
protected override Backend Backend => Backend.SqliteMemory;
}
[RequiresEnvironment(PgTestServer.Variable)]
public sealed class PostgresFoundCopiesMigrationTests(TestContext context) : FoundCopiesMigrationTests(context)
{
protected override Backend Backend => Backend.Postgres;
}
@@ -11,7 +11,7 @@ public abstract class MigrationTests(TestContext context) : RepositoryTest(conte
[
"archives", "sequences", "frames", "renders", "jobs", "media_cards", "import_history", "users", "tokens",
"render_nodes", "settings", "tags", "sequence_tags", "audit_log", "uploads", "schedules", "frame_removals", "projects", "project_versions",
"render_copies",
"render_copies", "found_copies", "copy_probes",
];
[Test]
@@ -0,0 +1,46 @@
using Chronos.Data.Copies;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Testing;
namespace Chronos.Data.Tests.Perf;
/// <summary>
/// Owner review 6 (#73), design §3.4: local detection's SHA-256 join over the 500,000-photo library answers in under 2 s
/// (every photo unique: the join finds no pair, which is the whole index read). Opt-in: <c>CHRONOS_PERF=1</c>.
/// </summary>
[Category("perf")]
[RequiresEnvironment(PerfGate.Variable)]
[Serial]
[Timeout(3_600_000)]
public abstract class CopyOverlapPerfTests(TestContext context) : RepositoryTest(context)
{
public const double BudgetMs = 2_000;
[Test]
public async Task LocalOverlapsAreFoundWithinTheGate()
{
var options = await NewOptionsAsync(multiConnection: true);
await using (var build = await ChronosDatabase.OpenAsync(options, Ct)) await SyntheticLibrary.BuildAsync(build, Context);
var db = Own(await ChronosDatabase.OpenAsync(options, Ct));
var store = new FoundCopyStore(db);
IReadOnlyList<LocalOverlap> overlaps = [];
var first = await PerfGate.TimeAsync(async () => overlaps = await store.LocalOverlapsAsync(Ct));
var again = await PerfGate.MedianAsync(() => store.LocalOverlapsAsync(Ct));
Context.Log($"perf: {Dialect} local overlaps {first:F0} ms first, {again:F0} ms again (budget {BudgetMs:F0} ms), {overlaps.Count} pairs");
Assert.Empty(overlaps);
Assert.LessOrEqual(first, BudgetMs);
}
}
public sealed class SqliteCopyOverlapPerfTests(TestContext context) : CopyOverlapPerfTests(context)
{
protected override Backend Backend => Backend.SqliteFile;
}
[RequiresEnvironment(PgTestServer.Variable)]
public sealed class PostgresCopyOverlapPerfTests(TestContext context) : CopyOverlapPerfTests(context)
{
protected override Backend Backend => Backend.Postgres;
}
@@ -0,0 +1,192 @@
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Copies;
using Chronos.Data.Projects;
using Chronos.Data.Tests.Archiving;
using Chronos.Testing;
namespace Chronos.Data.Tests.Projects;
/// <summary>
/// A project copied with its whole history from one home to another (owner review 6, #73; design §5c): content hashes
/// kept, a free name, a cut finished from its journal, a copy somebody took left alone, a newer format refused.
/// </summary>
[Category("projects")]
public sealed class ProjectTransplantTests(TestContext context)
{
private sealed record Homes(ArchiveFixture Fx, ArchiveProjectHome From, ArchiveProjectHome To, SequenceProject Source, List<Frame> FromFrames,
List<Frame> ToFrames);
/// <summary>Two sequences; the first has "Vertical" with two versions after its first.</summary>
private async Task<Homes> HomesAsync()
{
var fx = await ArchiveFixture.CreateAsync(context);
var (a, aFrames) = await ProjectServiceTests.UploadedAsync(fx, 3, 100);
var (b, bFrames) = await ProjectServiceTests.UploadedAsync(fx, 3, 200);
var projects = fx.Service.Projects;
var vertical = await projects.CreateAsync(a.Id, "Vertical", cancellationToken: fx.Ct);
var head = await projects.HeadAsync(vertical.Id, fx.Ct);
head = (await projects.PushAsync(vertical.Id, ProjectServiceTests.Draft(head, new ProjectSettings { ExcludedFrames = [1] }, aFrames, "one"), fx.Ct)).Version!;
await projects.PushAsync(vertical.Id, ProjectServiceTests.Draft(head, new ProjectSettings { HeroFrame = 2 }, aFrames, "two"), fx.Ct);
var source = (await projects.ListAsync(a.Id, fx.Ct)).Single(p => p.Id == vertical.Id);
return new Homes(fx, new ArchiveProjectHome(fx.Db, projects, a.Id), new ArchiveProjectHome(fx.Db, projects, b.Id), source, aFrames, bFrames);
}
private static async Task<List<string>> HashesAsync(IProjectHome home, Guid projectId, CancellationToken ct) =>
[.. (await home.VersionsAfterAsync(projectId, 0, 100, ct)).Select(v => v.ContentHash)];
[Test]
public async Task TheWholeHistoryIsCopiedWithItsContentHashes()
{
var h = await HomesAsync();
await using var _ = h.Fx;
var saved = new List<TransplantStep>();
var copy = await new ProjectTransplant().CopyAsync(h.From, h.Source, h.To, "Vertical", null, s => { saved.Add(s); return ValueTask.CompletedTask; }, h.Fx.Ct);
Assert.Equal("Vertical", copy.Name);
var source = await HashesAsync(h.From, h.Source.Id, h.Fx.Ct);
var copied = await HashesAsync(h.To, copy.Id, h.Fx.Ct);
// The copy's first version is the one it was made from, then the source's history in order.
Assert.SequenceEqual(source, copied.Skip(1));
Assert.Equal(source.Count + 1, copy.HeadNumber);
Assert.Equal(copy.Id, saved[^1].TargetId);
Assert.Equal(source.Count, saved[^1].Moves.Count);
// The source is untouched.
Assert.Equal(source.Count, (await h.From.HeadAsync(h.Source.Id, h.Fx.Ct)).Number);
}
[Test]
public async Task ANameTakenGetsTheNextFreeOne()
{
var h = await HomesAsync();
await using var _ = h.Fx;
await h.To.CreateAsync("Vertical", null, null, h.Fx.Ct);
var copy = await new ProjectTransplant().CopyAsync(h.From, h.Source, h.To, "Vertical", null, _ => ValueTask.CompletedTask, h.Fx.Ct);
Assert.Equal("Vertical (2)", copy.Name);
Assert.Equal("Vertical", ProjectTransplant.FreeName("Vertical", "STUDIO-PC", new HashSet<string> { "Main" }));
Assert.Equal("Vertical (STUDIO-PC)", ProjectTransplant.FreeName("Vertical", "STUDIO-PC", new HashSet<string> { "vertical" }));
Assert.Equal("Vertical (STUDIO-PC) (2)", ProjectTransplant.FreeName("Vertical", "STUDIO-PC", new HashSet<string> { "Vertical", "Vertical (studio-pc)" }));
var longName = new string('x', ProjectService.MaxNameLength);
Assert.True(ProjectTransplant.FreeName(longName, "STUDIO-PC", new HashSet<string> { longName }).Length <= ProjectService.MaxNameLength);
}
[Test]
public async Task ACutAfterTheCopyWasAskedForIsFinishedOnTheCopyFoundByItsName()
{
var h = await HomesAsync();
await using var _ = h.Fx;
TransplantStep? journal = null;
ValueTask Save(TransplantStep s)
{
journal = s;
return ValueTask.CompletedTask;
}
var cut = new ProjectTransplant { Step = s => { if (s == "created") throw new IOException("cut"); } };
await Assert.ThrowsAsync<IOException>(() => cut.CopyAsync(h.From, h.Source, h.To, "Vertical", null, Save, h.Fx.Ct));
Assert.Null(journal!.TargetId);
var copy = await new ProjectTransplant().CopyAsync(h.From, h.Source, h.To, "Vertical", journal, Save, h.Fx.Ct);
Assert.Count(1, (await h.To.ListAsync(h.Fx.Ct)).Where(p => !p.IsMain));
Assert.Equal("Vertical", copy.Name);
Assert.SequenceEqual(await HashesAsync(h.From, h.Source.Id, h.Fx.Ct), (await HashesAsync(h.To, copy.Id, h.Fx.Ct)).Skip(1));
}
[Test]
public async Task ACutResumedSendsNoVersionTwice()
{
var h = await HomesAsync();
await using var _ = h.Fx;
TransplantStep? journal = null;
ValueTask Save(TransplantStep s)
{
journal = s;
return ValueTask.CompletedTask;
}
var pushes = 0;
var cut = new ProjectTransplant { Step = s => { if (s == "pushed" && ++pushes == 2) throw new IOException("cut"); } };
await Assert.ThrowsAsync<IOException>(() => cut.CopyAsync(h.From, h.Source, h.To, "Vertical", null, Save, h.Fx.Ct));
var copy = await new ProjectTransplant().CopyAsync(h.From, h.Source, h.To, "Vertical", journal, Save, h.Fx.Ct);
Assert.Equal(journal!.TargetId, copy.Id);
var copied = await HashesAsync(h.To, copy.Id, h.Fx.Ct);
Assert.SequenceEqual(await HashesAsync(h.From, h.Source.Id, h.Fx.Ct), copied.Skip(1));
}
[Test]
public async Task ACopySomebodyTookIsLeftAloneAndANewNameIsTaken()
{
var h = await HomesAsync();
await using var _ = h.Fx;
TransplantStep? journal = null;
ValueTask Save(TransplantStep s)
{
journal = s;
return ValueTask.CompletedTask;
}
var cut = new ProjectTransplant { Step = s => { if (s == "pushed") throw new IOException("cut"); } };
await Assert.ThrowsAsync<IOException>(() => cut.CopyAsync(h.From, h.Source, h.To, "Vertical", null, Save, h.Fx.Ct));
var taken = journal!.TargetId!.Value;
// Somebody works on the copy meanwhile.
var theirs = ProjectServiceTests.Draft(await h.To.HeadAsync(taken, h.Fx.Ct), new ProjectSettings { HeroFrame = 0 }, h.ToFrames, "mine");
Assert.Equal(PushOutcome.Stored, (await h.To.PushAsync(taken, theirs, h.Fx.Ct)).Outcome);
var copy = await new ProjectTransplant().CopyAsync(h.From, h.Source, h.To, "Vertical", journal, Save, h.Fx.Ct);
Assert.NotEqual(taken, copy.Id);
Assert.Equal("Vertical (2)", copy.Name);
Assert.Equal(theirs.Id, (await h.To.HeadAsync(taken, h.Fx.Ct)).Id);
Assert.SequenceEqual(await HashesAsync(h.From, h.Source.Id, h.Fx.Ct), (await HashesAsync(h.To, copy.Id, h.Fx.Ct)).Skip(1));
}
[Test]
public async Task AHomeThatReadsAnOlderFormatGetsNothing()
{
var h = await HomesAsync();
await using var _ = h.Fx;
var needed = (await h.From.VersionsAfterAsync(h.Source.Id, 0, 100, h.Fx.Ct)).Max(v => int.Max(v.SettingsFormat, ProjectContent.FormatOf(v.SettingsJson)));
Assert.True(needed > 0);
var older = new OlderHome(h.To, needed - 1);
var before = (await h.To.ListAsync(h.Fx.Ct)).Count;
var refused = await Assert.ThrowsAsync<TransplantFormatException>(() =>
new ProjectTransplant().CopyAsync(h.From, h.Source, older, "Vertical", null, _ => ValueTask.CompletedTask, h.Fx.Ct));
Assert.Equal((needed, needed - 1), (refused.Needed, refused.Reads));
Assert.Equal(before, (await h.To.ListAsync(h.Fx.Ct)).Count);
}
/// <summary>A home that stores an older settings format than this Chronos writes (an older server).</summary>
private sealed class OlderHome(IProjectHome inner, int format) : IProjectHome
{
public int SettingsFormat => format;
public Task<HomeSequence> SequenceAsync(CancellationToken cancellationToken) => inner.SequenceAsync(cancellationToken);
public Task<IReadOnlyList<SequenceProject>> ListAsync(CancellationToken cancellationToken) => inner.ListAsync(cancellationToken);
public Task<SequenceProject> CreateAsync(string name, Guid? fromVersionId, string? author, CancellationToken cancellationToken) =>
inner.CreateAsync(name, fromVersionId, author, cancellationToken);
public Task<ProjectVersion> HeadAsync(Guid projectId, CancellationToken cancellationToken) => inner.HeadAsync(projectId, cancellationToken);
public Task<ProjectVersion?> GetVersionAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken) =>
inner.GetVersionAsync(projectId, versionId, cancellationToken);
public Task<IReadOnlyList<ProjectVersion>> VersionsAfterAsync(Guid projectId, int afterNumber, int limit, CancellationToken cancellationToken) =>
inner.VersionsAfterAsync(projectId, afterNumber, limit, cancellationToken);
public Task<IReadOnlyList<ProjectVersion>> HistoryAsync(Guid projectId, int? beforeNumber, int limit, CancellationToken cancellationToken) =>
inner.HistoryAsync(projectId, beforeNumber, limit, cancellationToken);
public Task<PushResult> PushAsync(Guid projectId, ProjectVersion version, CancellationToken cancellationToken) =>
inner.PushAsync(projectId, version, cancellationToken);
public Task<HomeFrames> FramesAsync(CancellationToken cancellationToken) => inner.FramesAsync(cancellationToken);
}
}
@@ -0,0 +1,228 @@
using Chronos.Core.Project;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Sync;
/// <summary>The photo-by-photo comparison of two copies (owner review 6, #73; design §4.1).</summary>
[Category("sync")]
public sealed class CopyComparisonTests
{
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0, 250);
private static string Sha(int n) => Convert.ToHexStringLower(BitConverter.GetBytes((long)n)).PadLeft(64, 'a');
/// <summary>Photo n: its own SHA-256, size and a sub-second capture time 5 s after the one before.</summary>
private static CopyPhotoInput Photo(int n, int index = -1, bool hashed = true, bool unusable = false, string? name = null, DateTime? at = null, long? size = null) =>
new(Guid.NewGuid(), index < 0 ? n : index, name ?? $"IMG_{n:0000}.JPG", hashed ? Sha(n) : null, size ?? 1000 + n, at ?? Start.AddSeconds(5 * n), unusable);
private static CopySideInput Side(params CopyPhotoInput[] photos) => new(photos, []);
private static CopySideInput Side(IEnumerable<CopyPhotoInput> photos, params RemovedPhotoDto[] removed) => new([.. photos], removed);
private static RemovedPhotoDto Deleted(int n) => new(Sha(n), null, "deleted", DateTimeOffset.UnixEpoch);
private static RemovedPhotoDto Replaced(int n, int by) => new(Sha(n), Sha(by), "replaced", DateTimeOffset.UnixEpoch);
private static int Count(CopyComparisonResult result, PhotoClass c) => result.Of(c).Count();
[Test]
public void IdenticalCopiesAreAllSame()
{
var result = CopyComparer.Compare(Side(Photo(1), Photo(2), Photo(3)), Side(Photo(1), Photo(2), Photo(3)));
Assert.Equal(3, Count(result, PhotoClass.Same));
Assert.Equal((3, 0, 0, 1000, 1000), (result.Score.Shared, result.Score.OnlyHere, result.Score.OnlyThere, result.Score.Containment, result.Score.Overlap));
Assert.True(result.Score.Identical);
Assert.True(result.Score.ByHash);
Assert.Count(9, result.Totals);
}
[Test]
public void ASubsetReadsFullyContainedAndASupersetToo()
{
// The Uploader sent part of the card: the server holds a subset.
var all = Enumerable.Range(1, 10).Select(n => Photo(n)).ToArray();
var part = Enumerable.Range(1, 4).Select(n => Photo(n)).ToArray();
var subset = CopyComparer.Compare(Side(all), Side(part));
Assert.Equal((4, 6, 0, 1000, 400), (subset.Score.Shared, subset.Score.OnlyHere, subset.Score.OnlyThere, subset.Score.Containment, subset.Score.Overlap));
Assert.False(subset.Score.Identical);
var superset = CopyComparer.Compare(Side(part), Side(all));
Assert.Equal((4, 0, 6, 1000), (superset.Score.Shared, superset.Score.OnlyHere, superset.Score.OnlyThere, superset.Score.Containment));
}
[Test]
public void AConvertedPhotoIsConvertedNotOnlyOnOneSide()
{
// This PC replaced photo 2 by a converted file (photo 50's content); the server still holds the original.
var here = Side([Photo(1), Photo(50, index: 1, at: Start.AddSeconds(10))], Replaced(2, 50));
var result = CopyComparer.Compare(here, Side(Photo(1), Photo(2)));
var converted = Assert.Contains(result.Photos, p => p.Class == PhotoClass.Converted);
Assert.Equal((Sha(50), Sha(2)), (converted.Here!.Sha256, converted.There!.Sha256));
Assert.Equal((2, 0, 0), (result.Score.Shared, result.Score.OnlyHere, result.Score.OnlyThere));
Assert.True(result.Score.Identical);
}
[Test]
public void ATombstonedPhotoIsDeletedOnThatSideNotOnlyOnTheOther()
{
var result = CopyComparer.Compare(Side([Photo(1), Photo(2)], Deleted(3)), Side([Photo(1), Photo(3)], Deleted(2)));
Assert.Equal(Sha(2), Assert.Contains(result.Photos, p => p.Class == PhotoClass.DeletedThere).Key);
Assert.Equal(Sha(3), Assert.Contains(result.Photos, p => p.Class == PhotoClass.DeletedHere).Key);
Assert.Equal((0, 0, 1, 1, 2), (result.Score.OnlyHere, result.Score.OnlyThere, result.Score.DeletedHere, result.Score.DeletedThere, result.Score.SharedRemoved));
Assert.False(result.Score.Identical);
Assert.Equal(1000, result.Score.Containment);
}
[Test]
public void CopiesOfOnePhotoInsideASideCountOnce()
{
var copy = Photo(2) with { FrameId = Guid.NewGuid(), Index = 5, FileName = "IMG_0002 (1).JPG" };
var result = CopyComparer.Compare(Side(Photo(1), Photo(2), copy), Side(Photo(1), Photo(2)));
Assert.Equal((2, 2, 2), (result.Score.Shared, result.Score.LocalPhotos, result.Score.OtherPhotos));
var same = Assert.Contains(result.Photos, p => p.Key == Sha(2));
Assert.Equal((2, 1), (same.HereOccurrences, same.ThereOccurrences));
Assert.True(result.Score.Identical);
}
[Test]
public void AnUnhashedPhotoMatchesBySizeAndMillisecond()
{
var result = CopyComparer.Compare(Side(Photo(1), Photo(2, hashed: false)), Side(Photo(1), Photo(2)));
var unhashed = Assert.Contains(result.Photos, p => p.Class == PhotoClass.SameUnhashed);
Assert.Equal(Sha(2), unhashed.Key);
Assert.Equal((1, 1), (result.Score.Shared, result.Score.SharedUnhashed));
Assert.True(result.Score.Identical);
Assert.False(result.Score.ByHash);
}
[Test]
public void UnhashedLeftoversStayOnTheirSide()
{
// Another size at the same time is another photo: unlike CompareOriginals, nothing is assumed to match.
var result = CopyComparer.Compare(Side(Photo(1), Photo(2, hashed: false, size: 7)), Side(Photo(1), Photo(3, hashed: false)));
Assert.Equal((1, 0, 1, 1), (result.Score.Shared, result.Score.SharedUnhashed, result.Score.OnlyHere, result.Score.OnlyThere));
Assert.True(Assert.Contains(result.Photos, p => p.Class == PhotoClass.OnlyHere).Key.StartsWith("u:7:", StringComparison.Ordinal));
}
[Test]
public void DiffersPairsOnePhotoPerSideWithTheSameNameAndSubSecondInstant()
{
// Photo 2 edited on one side: another SHA-256, same name, same sub-second capture time.
var edited = Photo(2) with { Sha256 = Sha(99), Size = 4242 };
var result = CopyComparer.Compare(Side(Photo(1), Photo(2)), Side(Photo(1), edited));
var differs = Assert.Contains(result.Photos, p => p.Class == PhotoClass.Differs);
Assert.Equal((Sha(2), Sha(99), 1002L), (differs.Here!.Sha256, differs.There!.Sha256, differs.Bytes));
Assert.Equal((1, 0, 0), (result.Score.Differs, result.Score.OnlyHere, result.Score.OnlyThere));
Assert.False(result.Score.Identical);
var total = Assert.Contains(result.Totals, t => t.Class == PhotoClass.Differs);
Assert.Equal((1002L, 4242L), (total.HereBytes, total.ThereBytes));
// Another name, or another millisecond, is no pair.
Assert.Equal(0, CopyComparer.Compare(Side(Photo(2)), Side(edited with { FileName = "DSC_0002.JPG" })).Score.Differs);
Assert.Equal(0, CopyComparer.Compare(Side(Photo(2)), Side(edited with { CapturedAt = edited.CapturedAt!.Value.AddMilliseconds(1) })).Score.Differs);
}
[Test]
public void WholeSecondCaptureTimesNeverPairAsDiffers()
{
// A camera that records whole seconds: two different photos at one second with one name are not one photo edited.
var at = new DateTime(2026, 9, 28, 18, 0, 0);
var result = CopyComparer.Compare(Side(Photo(1, at: at, name: "IMG_0001.JPG")), Side(Photo(2, at: at, name: "IMG_0001.JPG")));
Assert.Equal((0, 1, 1), (result.Score.Differs, result.Score.OnlyHere, result.Score.OnlyThere));
}
[Test]
public void BurstsNeverPairAsDiffers()
{
// Two photos of a burst at one instant on each side: which is which cannot be told, so nothing pairs.
var at = Start.AddMilliseconds(130);
var result = CopyComparer.Compare(
Side(Photo(1, at: at, name: "IMG_0001.JPG"), Photo(2, at: at, name: "IMG_0001.JPG")),
Side(Photo(3, at: at, name: "IMG_0001.JPG"), Photo(4, at: at, name: "IMG_0001.JPG")));
Assert.Equal((0, 2, 2), (result.Score.Differs, result.Score.OnlyHere, result.Score.OnlyThere));
}
[Test]
public void TwoVersionsAfterAKeepBothAreVersions()
{
// A Union keep-both left both versions of photo 2 on both sides, at its one capture instant.
var version = Photo(2) with { FrameId = Guid.NewGuid(), Index = 3, Sha256 = Sha(99), Size = 4242 };
var result = CopyComparer.Compare(Side(Photo(1), Photo(2), version), Side(Photo(1), Photo(2), version with { FrameId = Guid.NewGuid() }));
Assert.Equal(2, Count(result, PhotoClass.Versions));
Assert.Equal((3, 2), (result.Score.Shared, result.Score.Versions));
Assert.True(result.Score.Identical);
// At a whole second they stay Same.
var at = new DateTime(2026, 9, 28, 18, 0, 10);
var whole = CopyComparer.Compare(Side(Photo(2, at: at), version with { CapturedAt = at }), Side(Photo(2, at: at), version with { CapturedAt = at }));
Assert.Equal((2, 0), (Count(whole, PhotoClass.Same), whole.Score.Versions));
}
[Test]
public void AnUnusableFrameHoldsNothingAndMarksTheRepair()
{
var result = CopyComparer.Compare(Side(Photo(1), Photo(2, unusable: true)), Side(Photo(1), Photo(2), Photo(3, unusable: true)));
var brought = Assert.Contains(result.Photos, p => p.Key == Sha(2));
Assert.Equal((PhotoClass.OnlyThere, true, false), (brought.Class, brought.RepairsHere, brought.RepairsThere));
Assert.DoesNotContain(Sha(3), result.Photos.Select(p => p.Key));
Assert.Equal((1, 2), (result.Score.LocalPhotos, result.Score.OtherPhotos));
// A Missing or Corrupt frame there is repaired by this PC's copy.
var other = CopyComparer.Compare(Side(Photo(1), Photo(2)), Side(Photo(1), Photo(2, unusable: true)));
var sent = Assert.Contains(other.Photos, p => p.Key == Sha(2));
Assert.Equal((PhotoClass.OnlyHere, true), (sent.Class, sent.RepairsThere));
}
[Test]
public void BytesArePerClassAndSide()
{
var result = CopyComparer.Compare(Side(Photo(1), Photo(2)), Side(Photo(1), Photo(3)));
Assert.Equal((1001L, 1001L), Totals(PhotoClass.Same));
Assert.Equal((1002L, 0L), Totals(PhotoClass.OnlyHere));
Assert.Equal((0L, 1003L), Totals(PhotoClass.OnlyThere));
Assert.Equal(1003L, Assert.Contains(result.Photos, p => p.Class == PhotoClass.OnlyThere).Bytes);
(long, long) Totals(PhotoClass c)
{
var total = result.Totals.Single(t => t.Class == c);
return (total.HereBytes, total.ThereBytes);
}
}
[Test]
public void TheResultDoesNotDependOnTheOrderOfTheInputs()
{
var edited = Photo(7) with { Sha256 = Sha(97) };
CopyPhotoInput[] here = [Photo(1), Photo(2), Photo(3, hashed: false), Photo(4), Photo(5), Photo(6), Photo(7), Photo(8, unusable: true)];
CopyPhotoInput[] there = [Photo(1), Photo(3), Photo(4, hashed: false), Photo(6), edited, Photo(8), Photo(9)];
var removedHere = new[] { Deleted(9) };
var removedThere = new[] { Deleted(5) };
var a = CopyComparer.Compare(Side(here, removedHere), Side(there, removedThere));
var b = CopyComparer.Compare(Side(Enumerable.Reverse(here), removedHere), Side(Enumerable.Reverse(there), removedThere));
Assert.Equal(a.Score, b.Score);
Assert.SequenceEqual(a.Photos.Select(p => (p.Class, p.Key, p.Here?.FrameId, p.There?.FrameId)), b.Photos.Select(p => (p.Class, p.Key, p.Here?.FrameId, p.There?.FrameId)));
Assert.Equal((2, 2, 1, 1, 1, 1, 1), (a.Score.Shared, a.Score.SharedUnhashed, a.Score.Differs, a.Score.DeletedHere, a.Score.DeletedThere, a.Score.OnlyHere, a.Score.OnlyThere));
}
[Test]
public void DeletionsCountWhatTheOtherSideTombstonedAndNoLongerHolds()
{
var tombstones = SyncTombstones.FromDtos([Deleted(3)], [Deleted(2), Deleted(1)]);
FramePhoto[] here = [new(Sha(1), 1, null), new(Sha(2), 2, null), new(Sha(2), 2, null)];
FramePhoto[] there = [new(Sha(1), 1, null), new(Sha(3), 3, null)];
Assert.Equal((1, 1), CopyComparer.Deletions(here, there, tombstones));
Assert.Equal((0, 0), CopyComparer.Deletions(here, there, SyncTombstones.None));
}
[Test]
public void TombstonesFromDtosReadBothSides()
{
var tombstones = SyncTombstones.FromDtos([Replaced(2, 50), Deleted(4)], [Deleted(5)]);
Assert.Equal(tombstones.Canonical(Sha(50)), tombstones.Canonical(Sha(2)));
Assert.True(tombstones.DeletedLocally(Sha(4)));
Assert.False(tombstones.DeletedLocally(Sha(2)));
Assert.True(tombstones.DeletedRemotely(Sha(5)));
Assert.True(SyncTombstones.FromDtos([], null).IsEmpty);
}
}
+161 -2
View File
@@ -17,7 +17,8 @@ internal sealed class FakeSyncRemote : ISyncRemote
private readonly Channel<ServerEvent> _events = Channel.CreateUnbounded<ServerEvent>();
private readonly Dictionary<string, FakeSequence> _sessions = [];
public string Server => "https://nas.test:8443";
/// <summary>The server's key: an address key unless a test names one by id (<c>id:&lt;N&gt;</c>).</summary>
public string Server { get; init; } = "https://nas.test:8443";
public Dictionary<Guid, FakeSequence> Sequences { get; } = [];
@@ -59,6 +60,155 @@ internal sealed class FakeSyncRemote : ISyncRemote
public Task<int> SettingsFormatAsync(CancellationToken cancellationToken) => Task.FromResult(SettingsFormat);
/// <summary>
/// The capabilities the server announces (<see cref="ServerCapabilities"/>): none by default, an older server's path
/// (owner review 6, #73); tests of the lookup and of uploads into a target opt in.
/// </summary>
public HashSet<string> Capabilities { get; } = new(StringComparer.Ordinal);
public Task<IReadOnlySet<string>> CapabilitiesAsync(CancellationToken cancellationToken)
{
lock (_gate) return Task.FromResult<IReadOnlySet<string>>(new HashSet<string>(Capabilities, StringComparer.Ordinal));
}
/// <summary>Lookup requests so far, as received.</summary>
public List<PhotoLookupRequest> Lookups { get; } = [];
/// <summary>Uploads into a target so far (<see cref="UploadFileIntoAsync"/>), and how many the server filed from a copy it held elsewhere.</summary>
public int IntoUploads { get; private set; }
public int CopiedInto { get; private set; }
/// <summary>
/// Uploads into a target refused with 403, as for an account with Read and Upload but not Edit that does not own the
/// target; <see cref="RefusedInto"/> counts them.
/// </summary>
public bool ForbidInto { get; set; }
public int RefusedInto { get; private set; }
/// <summary>Runs once, before the next frame deletion is answered (the server sequence changing meanwhile).</summary>
public Action? OnceBeforeDelete { get; set; }
/// <summary>Frame deletions refused with 403, as for an account that is neither the owner nor an admin.</summary>
public bool ForbidFrameDeletes { get; set; }
/// <summary>Frames moved to the server's trash so far, by sequence.</summary>
public List<(Guid SequenceId, FakeFrame Frame)> Trashed { get; } = [];
/// <summary>Files <paramref name="sequence"/> under <paramref name="sessionKey"/>, as an upload with that key would.</summary>
public void FileUnder(string sessionKey, FakeSequence sequence)
{
lock (_gate) _sessions[sessionKey] = sequence;
}
/// <summary>
/// Like the server (owner review 6, #73): per probe, the sequences holding its hashes in a frame (a sequence it never
/// hashed lists none), tombstoning them (by the photo's or its replacement's SHA-256), holding a frame of its unhashed keys
/// by size and capture millisecond, or filed under its session key. 404 without <see cref="ServerCapabilities.PhotoLookup"/>,
/// 413 beyond the limits.
/// </summary>
public Task<PhotoLookupResponse> LookupPhotosAsync(PhotoLookupRequest request, CancellationToken cancellationToken)
{
lock (_gate)
{
if (!Capabilities.Contains(ServerCapabilities.PhotoLookup)) throw new ChronosApiException(HttpStatusCode.NotFound, new ApiError("not_found", "route"));
if (request.Probes.Count > PhotoLookupRequest.MaxProbes || request.CountItems() > PhotoLookupRequest.MaxItems)
throw new ChronosApiException(HttpStatusCode.RequestEntityTooLarge, new ApiError("too_many", "probes"));
Lookups.Add(request);
var results = new List<ProbeResult>();
foreach (var probe in request.Probes)
{
var hashes = probe.Sha256.Select(h => h.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
var keys = (probe.Unhashed ?? []).Select(k => (k.Size, Ms(k.CapturedAt))).ToHashSet();
var filed = probe.SessionKey is { } key && _sessions.TryGetValue(key, out var held) ? held : null;
var hits = new List<PhotoLookupHit>();
foreach (var sequence in Sequences.Values)
{
var inFrames = sequence.Unhashed ? 0 : sequence.Frames.Select(f => f.Sha256).Where(hashes.Contains).Distinct(StringComparer.Ordinal).Count();
var removed = hashes.Count(h => sequence.Removed.Any(r => r.Sha256 == h || r.Replacement == h));
var unhashed = keys.Count(k => sequence.Frames.Any(f => f.CapturedAt is { } at && f.Bytes.Length == k.Size && Ms(at) == k.Item2));
var session = ReferenceEquals(filed, sequence);
if (inFrames + removed + unhashed > 0 || session) hits.Add(new PhotoLookupHit(sequence.Id, inFrames, removed, unhashed, session));
}
results.Add(new ProbeResult(probe.Key, hits));
}
return Task.FromResult(new PhotoLookupResponse(results));
}
static long Ms(DateTime at) => at.Ticks / TimeSpan.TicksPerMillisecond;
}
/// <summary>
/// Like the server with <see cref="ServerCapabilities.UploadInto"/>: the photo is filed into the target even when another
/// sequence holds it (a server-side copy, counted in <see cref="CopiedInto"/>); one the target holds answers its frame, one
/// it tombstoned answers none. Without the capability the server ignores the flag: an upload as before.
/// </summary>
public async Task<CompleteUploadResponse?> UploadFileIntoAsync(string path, Guid sequenceId, string sha256, DateTime? capturedAt,
CancellationToken cancellationToken)
{
bool capable;
lock (_gate) capable = Capabilities.Contains(ServerCapabilities.UploadInto);
if (!capable) return await UploadFileAsync(path, sequenceId, null, sha256, capturedAt, cancellationToken);
if (ForbidInto)
{
lock (_gate) RefusedInto++;
throw new ChronosApiException(HttpStatusCode.Forbidden, new ApiError("forbidden", "into"));
}
var bytes = await File.ReadAllBytesAsync(path, cancellationToken);
if (Convert.ToHexStringLower(SHA256.HashData(bytes)) != sha256)
throw new ChronosApiException(HttpStatusCode.BadRequest, new ApiError("hash_mismatch", "hash"));
lock (_gate)
{
IntoUploads++;
var target = Find(sequenceId);
if (target.Removed.Any(r => r.Sha256 == sha256)) return null;
var index = target.Frames.FindIndex(f => f.Sha256 == sha256);
if (index >= 0) return new CompleteUploadResponse(target.Frames[index].Id, target.Id, index);
if (Sequences.Values.Where(s => !s.Unhashed && s != target).SelectMany(s => s.Frames).Any(f => f.Sha256 == sha256)) CopiedInto++;
var frame = target.AddFrame(bytes, Path.GetFileName(path), capturedAt);
return new CompleteUploadResponse(frame.Id, target.Id, target.Frames.IndexOf(frame));
}
}
/// <summary>
/// Like the server's <c>frames/delete</c>: 404 for an unknown sequence, 403 with <see cref="ForbidFrameDeletes"/>, 409
/// <c>frames_conflict</c> when a frame is not there or the frames version moved, 409 <c>would_empty</c>; a dry run answers
/// the plan; else the frames go to the trash, each leaving a tombstone, and the frames version moves.
/// </summary>
public Task<FrameDeleteResultDto> DeleteFramesAsync(Guid sequenceId, FrameDeleteRequest request, CancellationToken cancellationToken)
{
if (OnceBeforeDelete is { } before)
{
OnceBeforeDelete = null;
before();
}
lock (_gate)
{
var sequence = Find(sequenceId);
if (ForbidFrameDeletes) throw new ChronosApiException(HttpStatusCode.Forbidden, new ApiError("forbidden", "delete"));
var wanted = request.FrameIds.ToHashSet();
var frames = sequence.Frames.Where(f => wanted.Contains(f.Id)).ToList();
if (frames.Count != wanted.Count || (request.ExpectedFramesVersion is { } expected && expected != sequence.FramesVersion))
throw new ChronosApiException(HttpStatusCode.Conflict, new ApiError("frames_conflict", "changed"));
if (frames.Count == sequence.Frames.Count) throw new ChronosApiException(HttpStatusCode.Conflict, new ApiError("would_empty", "empty"));
var bytes = frames.Sum(f => (long)f.Bytes.Length);
if (request.DryRun)
return Task.FromResult(new FrameDeleteResultDto(sequenceId, frames.Count, bytes, sequence.FramesVersion, sequence.Frames.Count, null, true));
var at = DateTimeOffset.UtcNow;
foreach (var frame in frames)
{
sequence.Frames.Remove(frame);
Trashed.Add((sequenceId, frame));
if (!sequence.Removed.Any(r => r.Sha256 == frame.Sha256)) sequence.Removed.Add(new RemovedPhotoDto(frame.Sha256, null, "deleted", at));
}
sequence.FramesVersion++;
sequence.UpdatedAt = at;
return Task.FromResult(new FrameDeleteResultDto(sequenceId, frames.Count, bytes, sequence.FramesVersion, sequence.Frames.Count,
$"trash/photos-{Guid.NewGuid():N}", false));
}
}
public FakeSequence Add(string? title, IEnumerable<byte[]> originals, string? settingsJson = null,
SequenceStatus status = SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt)
{
@@ -68,6 +218,12 @@ internal sealed class FakeSyncRemote : ISyncRemote
return sequence;
}
/// <summary>Someone deletes the sequence on the server: every later call for it answers 404.</summary>
public void Drop(Guid id)
{
lock (_gate) Sequences.Remove(id);
}
/// <summary>Someone else edits the settings on the server.</summary>
public void EditSettings(Guid id, string settingsJson)
{
@@ -357,7 +513,10 @@ internal sealed class FakeSequence
}
public SequenceDto Dto() => new(Id, Title, Title ?? "Untitled", "2026/" + Id.ToString("N"), "Canon", CameraModel, null, FirstCapture, null, Frames.Count, 10,
Frames.Sum(f => (long)f.Bytes.Length), (long)Status, Renders.Count, null, Tags, Rating, Notes, SettingsVersion, FramesVersion, 0, null, UpdatedAt);
Frames.Sum(f => (long)f.Bytes.Length), (long)Status, Renders.Count, null, Tags, Rating, Notes, SettingsVersion, FramesVersion, 0, OwnerUserId, UpdatedAt);
/// <summary>The server account that owns the sequence (none by default).</summary>
public Guid? OwnerUserId { get; set; }
public SequenceManifest Manifest(Func<Guid, bool> proxySent) => new(Id, FramesVersion, SettingsVersion, SettingsJson, Tags,
[.. Frames.Select((f, i) => new ManifestFrame(f.Id, i, f.FileName, f.Bytes.Length, Unhashed ? string.Empty : f.Sha256,
@@ -0,0 +1,146 @@
using Chronos.Core.IO;
using Chronos.Core.Model;
using Chronos.Data.Copies;
using Chronos.Data.Jobs;
using Chronos.Data.Sync;
using Chronos.Testing;
namespace Chronos.Data.Tests.Sync;
/// <summary>
/// The new photos of a pair integrated with automatic photos (owner review 6, #73; design §7.3): after a comparison the
/// agent queues them both ways in the background; never for a pair only linked or integrated without automatic photos; a
/// failed transfer counts, waits for its backoff, and three in a row are told.
/// </summary>
[Category("sync")]
public sealed class SyncAgentCopyTests(TestContext context)
{
private static readonly SyncAgentOptions Quick = new()
{
RefreshInterval = TimeSpan.FromHours(1),
EventDelay = TimeSpan.FromMilliseconds(20),
MinBackoff = TimeSpan.FromMilliseconds(20),
MaxBackoff = TimeSpan.FromMilliseconds(200),
};
/// <summary>An engine that queues but never runs, so the queued jobs can be read and settled by the test.</summary>
private static JobEngine Queue(SyncFixture f) => new(f.Db, [.. f.Sync.CreateJobHandlers(new SyncFixture.Connector(f.Remote))],
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50) });
/// <summary>A local sequence and a server sequence sharing two photos, each with one the other lacks, linked, in <paramref name="state"/>.</summary>
private static async Task<(Sequence Local, FakeSequence Remote)> PairAsync(SyncFixture f, string title, CopyState state, bool autoPhotos)
{
var photos = f.NewPhotos(4);
var local = await f.LocalAsync(title, photos.Take(3).ToList());
var remote = f.Remote.Add(title + " NAS", [photos[0], photos[1], photos[3]]);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
var row = await f.Sync.Copies.EnsureLinkedAsync(f.Server, remote.Id, local.Id, f.Ct);
if (state != CopyState.Linked)
Assert.True(await f.Sync.Copies.SetStateAsync(row.Id, null, state, new CopyAnswer(null, null, null, autoPhotos, DateTimeOffset.UtcNow), f.Ct));
return (local, remote);
}
private static async Task<List<Job>> QueuedAsync(SyncFixture f, JobKind kind) =>
[.. (await f.Db.Jobs.ListAsync(JobState.Queued, kind, 50, cancellationToken: f.Ct)).Items];
[Test]
public async Task AnIntegratedPairWithAutomaticPhotosQueuesBothWaysInTheBackground()
{
await using var f = await SyncFixture.CreateAsync(context);
var (local, remote) = await PairAsync(f, "Comet", CopyState.Integrated, autoPhotos: true);
await using var engine = Queue(f);
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(), engine, Quick);
await agent.RefreshAsync(f.Ct);
await agent.RefreshAsync(f.Ct);
var upload = (await QueuedAsync(f, JobKind.UploadCommit)).Single();
var download = (await QueuedAsync(f, JobKind.Download)).Single();
Assert.Equal((local.Id, JobPriority.Background), (upload.TargetIds.Single(), upload.Priority));
Assert.Equal((remote.Id, JobPriority.Background), (download.TargetIds.Single(), download.Priority));
Assert.Contains(local.ArchiveId.ToString(), download.ParametersJson ?? string.Empty);
Assert.Count(0, agent.PhotoFailures);
}
[Test]
public async Task APairOnlyLinkedOrWithoutAutomaticPhotosQueuesNothing()
{
await using var f = await SyncFixture.CreateAsync(context);
await PairAsync(f, "Linked", CopyState.Linked, autoPhotos: false);
await PairAsync(f, "Manual", CopyState.Integrated, autoPhotos: false);
await using var engine = Queue(f);
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(), engine, Quick);
await agent.RefreshAsync(f.Ct);
Assert.Count(0, await QueuedAsync(f, JobKind.UploadCommit));
Assert.Count(0, await QueuedAsync(f, JobKind.Download));
}
[Test]
public async Task APairWhoseServerCopyIsGoneQueuesNoAutomaticPhotos()
{
await using var f = await SyncFixture.CreateAsync(context);
// A server keyed by its id, so a 404 counts against the pair (design §7.5).
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos);
var remote = nas.Add("Comet NAS", photos.Take(2));
await f.Sync.LinkAsync(nas.Server, remote.Id, local.Id, f.Ct);
var row = await f.Sync.Copies.EnsureLinkedAsync(nas.Server, remote.Id, local.Id, f.Ct);
Assert.True(await f.Sync.Copies.SetStateAsync(row.Id, null, CopyState.Integrated,
new CopyAnswer(null, null, null, true, DateTimeOffset.UtcNow), f.Ct));
nas.Drop(remote.Id);
await using var engine = new JobEngine(f.Db, [.. f.Sync.CreateJobHandlers(new SyncFixture.Connector(nas))],
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50) });
await using var agent = new SyncAgent(f.Sync, nas, () => new SyncPolicy(), engine, Quick);
await agent.RefreshAsync(f.Ct);
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
await session.ExecuteAsync("UPDATE found_copies SET remote_gone_at = $1 WHERE id = $2", [DateTimeOffset.UtcNow.AddMinutes(-11), row.Id], f.Ct);
await agent.RefreshAsync(f.Ct);
var pair = (await f.Sync.Copies.GetAsync(row.Id, f.Ct))!;
Assert.True(pair.RemoteGoneHits > 0);
Assert.Equal((CopyState.Integrated, true), (pair.State, pair.AutoPhotos));
Assert.Count(0, await QueuedAsync(f, JobKind.UploadCommit));
Assert.Count(0, await QueuedAsync(f, JobKind.Download));
Assert.Count(0, agent.PhotoFailures);
}
[Test]
public async Task FailedTransfersCountWaitForTheirBackoffAndThreeInARowAreTold()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet NAS", photos.Take(2));
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
var row = await f.Sync.Copies.EnsureLinkedAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.Sync.Copies.SetStateAsync(row.Id, null, CopyState.Integrated, new CopyAnswer(null, null, null, true, DateTimeOffset.UtcNow), f.Ct);
await using var engine = Queue(f);
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(), engine, Quick);
var told = new List<(Guid, AutoPhotoFailure)>();
agent.PhotosNotSent += (id, failure) => told.Add((id, failure));
for (var attempt = 1; attempt <= SyncAgent.NotSentAfter; attempt++)
{
await agent.RefreshAsync(f.Ct);
var upload = (await QueuedAsync(f, JobKind.UploadCommit)).Single();
await f.Db.Jobs.SetStateAsync(upload.Id, JobState.Failed, "Quota reached", f.Ct);
await agent.RefreshAsync(f.Ct);
Assert.Equal(new AutoPhotoFailure(attempt, "Quota reached"), agent.PhotoFailures[local.Id]);
// Within its backoff nothing new is queued.
Assert.Count(0, await QueuedAsync(f, JobKind.UploadCommit));
await Task.Delay(Quick.MaxBackoff + TimeSpan.FromMilliseconds(50), f.Ct);
}
Assert.Equal((local.Id, SyncAgent.NotSentAfter), (told.Single().Item1, told.Single().Item2.Count));
await agent.RefreshAsync(f.Ct);
var last = (await QueuedAsync(f, JobKind.UploadCommit)).Single();
await f.Db.Jobs.SetStateAsync(last.Id, JobState.Done, null, f.Ct);
await agent.RefreshAsync(f.Ct);
Assert.Count(0, agent.PhotoFailures);
}
}
+9 -4
View File
@@ -30,13 +30,15 @@ internal sealed class SyncFixture : IAsyncDisposable
public string Server => Remote.Server;
public CancellationToken Ct => Archive.Ct;
public static async Task<SyncFixture> CreateAsync(TestContext context)
/// <param name="identity">The servers known by id and the address keys they were reached under (default: none).</param>
public static async Task<SyncFixture> CreateAsync(TestContext context, Func<ServerIdentity>? identity = null)
{
var archive = await ArchiveFixture.CreateAsync(context);
var sync = new SyncService(archive.Db, archive.Service, new SyncOptions
{
Archive = new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) },
ProxyCacheDirectory = context.CreateTempDirectory("proxies"),
Identity = identity,
});
return new SyncFixture(archive, sync);
}
@@ -54,8 +56,11 @@ internal sealed class SyncFixture : IAsyncDisposable
return photos;
}
/// <summary>A local sequence made through the archive ingest (hashed frames, a real sidecar).</summary>
public async Task<Sequence> LocalAsync(string title, IReadOnlyList<byte[]> originals, string? settingsJson = null)
/// <summary>
/// A local sequence made through the archive ingest (hashed frames, a real sidecar), each frame captured 10 s after the
/// one before from <see cref="ArchiveFixture.Start"/>, or at <paramref name="capturedAt"/>.
/// </summary>
public async Task<Sequence> LocalAsync(string title, IReadOnlyList<byte[]> originals, string? settingsJson = null, IReadOnlyList<DateTime>? capturedAt = null)
{
Guid? id = null;
var staging = Path.Combine(Archive.Paths.StagingDirectory, "test");
@@ -66,7 +71,7 @@ internal sealed class SyncFixture : IAsyncDisposable
await File.WriteAllBytesAsync(path, originals[i], Ct);
var sha = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(originals[i]));
var result = await Archive.Service.Ingest.CommitAsync(new IngestRequest(Archive.Archive.Id, id, id is null ? title : null, null, path,
$"IMG_{i + 1:0000}.JPG", originals[i].Length, sha, ArchiveFixture.Start.AddSeconds(10 * i), null), Ct);
$"IMG_{i + 1:0000}.JPG", originals[i].Length, sha, capturedAt?[i] ?? ArchiveFixture.Start.AddSeconds(10 * i), null), Ct);
id = result.SequenceId;
}
var sequence = (await Db.Sequences.GetAsync(id!.Value, Ct))!;
@@ -0,0 +1,535 @@
using Chronos.Core.IO;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Copies;
using Chronos.Data.Jobs;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Sync;
/// <summary>
/// Sync with found copies (owner review 6, #73): no silent link, links by setting outside the gate, unlink, 404 marks,
/// deletion counts and the agreed details of an Integrate.
/// </summary>
[Category("sync")]
public sealed class SyncServiceCopyTests(TestContext context)
{
[Test]
public async Task ARefreshLinksNothingByDefaultAndAsks()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("2026-09-28 Canon", photos);
remote.FirstCapture = local.FirstCapture;
remote.CameraModel = local.CameraModel;
var raised = new List<CopyFindResult>();
f.Sync.CopiesFound += (_, result) => raised.Add(result);
await f.RefreshAsync();
Assert.Null((await f.EntryAsync("Comet")).Link);
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single();
Assert.Equal(CopyState.Candidate, pair.State);
Assert.Equal((local.Id, remote.Id), (pair.LocalId, pair.RemoteId!.Value));
Assert.Equal(CopyEvidence.Hashes, pair.Evidence);
Assert.Equal(3, pair.Score.Shared);
Assert.Equal(pair.Id, raised.Single().New.Single().Id);
Assert.Empty(raised.Single().AutoLinked);
// Nothing moved: nothing is compared or announced again.
var manifests = f.Remote.ManifestCalls;
await f.RefreshAsync();
Assert.Equal(manifests, f.Remote.ManifestCalls);
Assert.Count(1, raised);
}
[Test]
public async Task IdenticalCopiesAreLinkedByThemselvesWhenTheSettingSaysSo()
{
await using var f = await SyncFixture.CreateAsync(context);
f.Remote.Capabilities.Add(ServerCapabilities.PhotoLookup);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet", photos);
var raised = new List<CopyFindResult>();
f.Sync.CopiesFound += (_, result) => raised.Add(result);
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.WhenIdentical });
var entry = await f.EntryAsync("Comet");
Assert.Equal(remote.Id, entry.Link?.RemoteId);
Assert.Equal(SyncStatus.InSync, entry.Status);
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single();
Assert.Equal(CopyState.Linked, pair.State);
Assert.Equal(pair.Id, raised.Single().AutoLinked.Single().Id);
Assert.Equal(local.Id, pair.LocalId);
}
[Test]
public async Task AKeepApartAnsweredMeanwhileWinsOverTheLink()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet", photos);
remote.FirstCapture = local.FirstCapture;
remote.CameraModel = local.CameraModel;
await f.RefreshAsync();
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single();
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.Candidate, CopyState.KeptApart,
new CopyAnswer(pair.Fingerprint, pair.Score.Shared, null, false, DateTimeOffset.UtcNow), f.Ct));
var linked = await f.Sync.AutoLinkAsync(f.Remote, new SyncPolicy { Linking = CopyLinking.WhenIdentical }, pair, remote.Dto(), local, null, f.Ct);
Assert.False(linked);
Assert.Null(await f.Sync.LinkOfAsync(f.Server, local.Id, f.Ct));
Assert.Equal(CopyState.KeptApart, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
}
[Test]
public async Task EveryLinkHasItsPair()
{
await using var f = await SyncFixture.CreateAsync(context);
var local = await f.LocalAsync("Comet", f.NewPhotos(2));
var remote = f.Remote.Add("Harbour", f.NewPhotos(1));
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single();
Assert.Equal((CopyEvidence.Link, CopyState.Linked), (pair.Evidence, pair.State));
Assert.Equal((local.Id, remote.Id), (pair.LocalId, pair.RemoteId!.Value));
Assert.False(pair.IsListed);
}
[Test]
public async Task AnUploadForAnIntegratedPairCanWaitInTheBackground()
{
await using var f = await SyncFixture.CreateAsync(context);
var local = await f.LocalAsync("Comet", f.NewPhotos(1));
await using var engine = new JobEngine(f.Db, f.Sync.CreateJobHandlers(new SyncFixture.Connector(f.Remote)));
var background = await f.Sync.EnqueueUploadAsync(engine, f.Server, local, JobPriority.Background, f.Ct);
Assert.Equal(JobPriority.Background, background.Priority);
Assert.Equal(SyncTransferKind.Upload, SyncService.TransferKind(background));
}
[Test]
public async Task UnlinkKeepsTheServerSequenceAndKeepsThePairApart()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Comet")).Status);
await f.Sync.UnlinkAsync(f.Server, remote.Id, local.Id, f.Ct);
var link = await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct);
Assert.NotNull(link);
Assert.Null(link.LocalId);
Assert.Null(await f.Sync.LinkOfAsync(f.Server, local.Id, f.Ct));
Assert.Equal(SyncState.LocalOnly, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SyncState);
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single();
Assert.Equal(CopyState.KeptApart, pair.State);
Assert.Equal(2, pair.AnsweredShared);
// Asked again only by a large later change: the next refresh leaves the two apart.
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.WhenHalfShared });
Assert.Null((await f.Sync.ListAsync(f.Server, f.Ct)).Single(e => e.Local?.Id == local.Id).Link);
Assert.Equal(CopyState.KeptApart, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
}
[Test]
public async Task A404IsCountedOncePerRefreshAndTwiceReadsDeleted()
{
await using var f = await SyncFixture.CreateAsync(context);
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
var remote = nas.Add("Comet", photos);
await f.Sync.LinkAsync(nas.Server, remote.Id, local.Id, f.Ct);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
nas.Sequences.Remove(remote.Id);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
Assert.Null(await f.Sync.LinkOfAsync(nas.Server, local.Id, f.Ct));
var pair = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
Assert.Equal(1, pair.RemoteGoneHits);
Assert.False(pair.RemoteGone);
// Asked again no sooner than ten minutes after the first 404.
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
Assert.Equal(1, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.RemoteGoneHits);
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
await session.ExecuteAsync("UPDATE found_copies SET remote_gone_at = $1 WHERE id = $2", [DateTimeOffset.UtcNow.AddMinutes(-11), pair.Id], f.Ct);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
pair = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
Assert.Equal(2, pair.RemoteGoneHits);
Assert.True(pair.RemoteGone);
Assert.True(pair.NeedsAttention);
}
[Test]
public async Task AMatchWhoseServerSequenceIsDeletedIsGoneAfterTheRefreshAndUploadAllSendsTheLocalOne()
{
await using var f = await SyncFixture.CreateAsync(context);
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos);
var remote = nas.Add("2026-09-28 Canon", photos);
remote.FirstCapture = local.FirstCapture;
remote.CameraModel = local.CameraModel;
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
var pair = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
Assert.Equal((CopyState.Candidate, local.Id), (pair.State, pair.LocalId));
Assert.Null((await f.Sync.Links.GetAsync(nas.Server, remote.Id, f.Ct))!.LocalId);
// Deleted on the server: no longer listed, and a 404 when asked for.
nas.Sequences.Remove(remote.Id);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
Assert.Null(await f.Sync.Copies.GetAsync(pair.Id, f.Ct));
var entries = (await f.Sync.ListAsync(nas.Server, f.Ct)).Where(e => e.Local?.Id == local.Id).ToList();
var (upload, skipped) = UploadAllRule.Select(entries, await f.Sync.Copies.ListAsync(f.Ct), new HashSet<Guid>(), new HashSet<Guid>());
Assert.Empty(skipped);
Assert.Equal(local.Id, upload.Single().Local!.Id);
}
[Test]
public async Task AKeptApartServerSequenceAnswering404OnceKeepsTheAnswerAndIsNeverLinkedByItself()
{
await using var f = await SyncFixture.CreateAsync(context);
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos);
var remote = nas.Add("2026-09-28 Canon", photos);
remote.FirstCapture = local.FirstCapture;
remote.CameraModel = local.CameraModel;
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
var pair = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.Candidate, CopyState.KeptApart,
new CopyAnswer(pair.Fingerprint, pair.Score.Shared, null, false, DateTimeOffset.UtcNow), f.Ct));
// Moved to the server's trash and restored: one refresh gets a 404, the next lists it again.
nas.Sequences.Remove(remote.Id);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
Assert.Equal((CopyState.KeptApart, 1), ((await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.RemoteGoneHits));
nas.Sequences[remote.Id] = remote;
await f.Sync.RefreshAsync(nas, new SyncPolicy { Linking = CopyLinking.WhenIdentical }, f.Ct);
// Keep separate is remembered (owner Q1): not asked again, and not linked although the photos are identical.
var after = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
Assert.Equal((pair.Id, CopyState.KeptApart, 0), (after.Id, after.State, after.RemoteGoneHits));
Assert.Null(await f.Sync.LinkOfAsync(nas.Server, local.Id, f.Ct));
}
[Test]
public async Task ASequenceReadAsDeletedOnTheServerIsClearedWhenItIsListedAgainOrLinkedAgain()
{
await using var f = await SyncFixture.CreateAsync(context);
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
var remote = nas.Add("Comet", photos);
await f.Sync.LinkAsync(nas.Server, remote.Id, local.Id, f.Ct);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
nas.Sequences.Remove(remote.Id);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
var pair = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
await session.ExecuteAsync("UPDATE found_copies SET remote_gone_at = $1 WHERE id = $2", [DateTimeOffset.UtcNow.AddMinutes(-11), pair.Id], f.Ct);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
Assert.True((await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.RemoteGone);
// Restored from the server's trash: listed again, it no longer reads "deleted on server".
nas.Sequences[remote.Id] = remote;
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
pair = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
Assert.Equal((0, (DateTimeOffset?)null, false), (pair.RemoteGoneHits, pair.RemoteGoneAt, pair.RemoteGone));
Assert.Equal(CopyState.Candidate, pair.State);
// A pair still marked (the listing missed it) is cleared by a link to that very sequence: automatic photos may move again.
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
await session.ExecuteAsync("UPDATE found_copies SET remote_gone_hits = 2, remote_gone_at = $1 WHERE id = $2", [DateTimeOffset.UtcNow, pair.Id], f.Ct);
await f.Sync.LinkAsync(nas.Server, remote.Id, local.Id, f.Ct);
pair = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
Assert.Equal((0, false, CopyState.Linked), (pair.RemoteGoneHits, pair.RemoteGone, pair.State));
}
[Test]
public async Task ASequenceBackOnTheServerIsAskedAboutAgain()
{
await using var f = await SyncFixture.CreateAsync(context);
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
var remote = nas.Add("Comet", photos);
await f.Sync.LinkAsync(nas.Server, remote.Id, local.Id, f.Ct);
nas.Unlisted.Add(remote.Id);
nas.Sequences.Remove(remote.Id);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
Assert.Equal(1, (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single().RemoteGoneHits);
nas.Sequences[remote.Id] = remote;
nas.Unlisted.Remove(remote.Id);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
var pair = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
Assert.Equal(0, pair.RemoteGoneHits);
Assert.Null(pair.RemoteGoneAt);
Assert.Equal(CopyState.Candidate, pair.State);
}
[Test]
public async Task ASequenceBackAfterAJobs404StaysLinked()
{
await using var f = await SyncFixture.CreateAsync(context);
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
var remote = nas.Add("Comet", photos);
await f.Sync.LinkAsync(nas.Server, remote.Id, local.Id, f.Ct);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
// A transfer's 404: the pair is marked once, the link stays.
await f.Sync.Copies.MarkRemoteGoneAsync(nas.Server, remote.Id, local.Id, Guid.NewGuid(), DateTimeOffset.UtcNow, f.Ct);
Assert.Equal(1, (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single().RemoteGoneHits);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
var pair = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
Assert.Equal((0, CopyState.Linked), (pair.RemoteGoneHits, pair.State));
Assert.Equal(local.Id, (await f.Sync.LinkOfAsync(nas.Server, local.Id, f.Ct))?.LocalId);
}
[Test]
public async Task EveryLinkAnswering404AtOnceMarksNothing()
{
await using var f = await SyncFixture.CreateAsync(context);
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
var remotes = new List<FakeSequence>();
for (var i = 0; i < 5; i++)
{
var photos = f.NewPhotos(1);
var local = await f.LocalAsync($"Card {i}", photos);
var remote = nas.Add($"Card {i}", photos);
await f.Sync.LinkAsync(nas.Server, remote.Id, local.Id, f.Ct);
remotes.Add(remote);
}
foreach (var remote in remotes) nas.Sequences.Remove(remote.Id);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
Assert.Empty(await f.Sync.Links.ListAsync(nas.Server, f.Ct));
Assert.True((await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).All(p => p.RemoteGoneHits == 0));
}
[Test]
public async Task ASweepOf404sConfirmsNoEarlierHitEither()
{
await using var f = await SyncFixture.CreateAsync(context);
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
// One pair with a 404 counted more than ten minutes ago (its link already forgotten).
var first = f.NewPhotos(2);
var gone = await f.LocalAsync("Comet", first);
var goneRemote = nas.Add("Comet", first);
await f.Sync.LinkAsync(nas.Server, goneRemote.Id, gone.Id, f.Ct);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
nas.Sequences.Remove(goneRemote.Id);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
var pair = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single(p => p.LocalId == gone.Id);
Assert.Equal(1, pair.RemoteGoneHits);
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
await session.ExecuteAsync("UPDATE found_copies SET remote_gone_at = $1 WHERE id = $2", [DateTimeOffset.UtcNow.AddMinutes(-11), pair.Id], f.Ct);
// Then the server serves something else: every linked sequence answers 404 at once.
var remotes = new List<FakeSequence>();
for (var i = 0; i < 5; i++)
{
var photos = f.NewPhotos(1);
var local = await f.LocalAsync($"Card {i}", photos);
var remote = nas.Add($"Card {i}", photos);
await f.Sync.LinkAsync(nas.Server, remote.Id, local.Id, f.Ct);
remotes.Add(remote);
}
foreach (var remote in remotes) nas.Sequences.Remove(remote.Id);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
pair = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
Assert.Equal(1, pair.RemoteGoneHits);
Assert.False(pair.RemoteGone);
}
[Test]
public async Task AServerKnownOnlyByItsAddressMarksNothing()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
f.Remote.Sequences.Remove(remote.Id);
await f.RefreshAsync();
Assert.Null(await f.Sync.LinkOfAsync(f.Server, local.Id, f.Ct));
Assert.True((await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).All(p => p.RemoteGoneHits == 0));
}
[Test]
public async Task ASequenceForgottenOnAServerKnownByItsAddressIsFoundAgainWhenItIsBack()
{
await using var f = await SyncFixture.CreateAsync(context);
f.Remote.Capabilities.Add(ServerCapabilities.PhotoLookup);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
f.Remote.Sequences.Remove(remote.Id);
await f.RefreshAsync();
Assert.Null(await f.Sync.LinkOfAsync(f.Server, local.Id, f.Ct));
// Back on the server: nothing remembers the forgotten link, so the two are found and asked about again.
f.Remote.Sequences[remote.Id] = remote;
await f.RefreshAsync();
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single();
Assert.Equal((local.Id, remote.Id, CopyState.Candidate), (pair.LocalId, pair.RemoteId!.Value, pair.State));
Assert.Null(await f.Sync.LinkOfAsync(f.Server, local.Id, f.Ct));
}
[Test]
public async Task ALinkedPairWhoseLinkIsGoneIsAskedAboutAgain()
{
await using var f = await SyncFixture.CreateAsync(context);
f.Remote.Capabilities.Add(ServerCapabilities.PhotoLookup);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
// The link removed by another hand, the pair's row left as it was.
await f.Sync.Links.DeleteAsync(f.Server, remote.Id, f.Ct);
var raised = new List<CopyFindResult>();
f.Sync.CopiesFound += (_, result) => raised.Add(result);
await f.RefreshAsync();
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single();
Assert.Equal((CopyState.Candidate, false), (pair.State, pair.AutoPhotos));
Assert.Contains(pair.Id, raised.SelectMany(r => r.New).Select(p => p.Id));
}
[Test]
public async Task DeletionCountsFollowEachComparison()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single();
Assert.Equal((3, 0, 0), (pair.Score.Shared, pair.Score.DeletedHere, pair.Score.DeletedThere));
// The server deletes a photo this PC still holds.
var gone = remote.Frames[1];
remote.Frames.Remove(gone);
remote.FramesVersion++;
remote.Removed.Add(new RemovedPhotoDto(gone.Sha256, null, "deleted", DateTimeOffset.UtcNow));
await f.RefreshAsync();
pair = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
Assert.Equal((0, 1), (pair.Score.DeletedHere, pair.Score.DeletedThere));
Assert.True(pair.IsListed);
Assert.True(pair.NeedsAttention);
// A photo deleted on this PC only: counted, never a warning (the user's own cull).
var culled = pair with { Score = pair.Score with { DeletedHere = 2, DeletedThere = 0 } };
Assert.False(culled.NeedsAttention);
}
[Test]
public async Task AgreedDetailsTakeTheServersOwnChangeSinceThePlan()
{
await using var f = await SyncFixture.CreateAsync(context);
var (local, remote, planLocal, planRemote) = await PlannedAsync(f);
var final = planLocal with { Title = "Comet agreed" };
// The server's light analysis of the photos just filed changes its settings after the plan.
f.Remote.EditSettings(remote.Id, SyncFixture.Window41);
var (applied, updated) = await f.Sync.ApplyAgreedAsync(f.Remote, remote.Id, final, planLocal, planRemote, local.SettingsVersion, f.Ct);
Assert.Equal("Comet agreed", remote.Title);
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, remote.SettingsJson));
var stored = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
Assert.Equal("Comet agreed", stored.Title);
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, stored.SettingsJson));
Assert.Equal((stored.SettingsVersion, remote.SettingsVersion), (applied.SettingsVersion, updated.SettingsVersion));
var link = (await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct))!;
Assert.Equal((stored.SettingsVersion, remote.SettingsVersion), (link.BaseLocalSettings, link.BaseRemoteSettings));
Assert.Count(1, f.Remote.Updates);
}
[Test]
public async Task AgreedDetailsAreSentAgainAfterARefusedEdit()
{
await using var f = await SyncFixture.CreateAsync(context);
var (local, remote, planLocal, planRemote) = await PlannedAsync(f);
var final = planLocal with { Title = "Comet agreed" };
// Unhashed on the server: its frames are read after the manifest, and the server changes right then.
remote.Unhashed = true;
f.Remote.OnceBeforeFrames = () =>
{
f.Remote.EditSettings(remote.Id, SyncFixture.Window41);
return Task.CompletedTask;
};
await f.Sync.ApplyAgreedAsync(f.Remote, remote.Id, final, planLocal, planRemote, local.SettingsVersion, f.Ct);
Assert.Equal("Comet agreed", remote.Title);
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, remote.SettingsJson));
Assert.Equal("Comet agreed", (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Title);
Assert.Count(1, f.Remote.Updates);
}
[Test]
public async Task AgreedDetailsAreRefusedAfterAnEditOnThisPc()
{
await using var f = await SyncFixture.CreateAsync(context);
var (local, remote, planLocal, planRemote) = await PlannedAsync(f);
var final = planLocal with { Title = "Comet agreed" };
var edited = await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41);
await Assert.ThrowsAsync<SyncConflictChangedException>(() =>
f.Sync.ApplyAgreedAsync(f.Remote, remote.Id, final, planLocal, planRemote, local.SettingsVersion, f.Ct));
// Shown at the new version, the content still moved since the plan.
await Assert.ThrowsAsync<SyncConflictChangedException>(() =>
f.Sync.ApplyAgreedAsync(f.Remote, remote.Id, final, planLocal, planRemote, edited.SettingsVersion, f.Ct));
Assert.Empty(f.Remote.Updates);
Assert.Equal("Comet", remote.Title);
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson));
}
/// <summary>A linked pair with the same settings on both sides, and each side's portable payload as an Integrate's plan reads it.</summary>
private static async Task<(Sequence Local, FakeSequence Remote, SyncPayload PlanLocal, SyncPayload PlanRemote)> PlannedAsync(SyncFixture f)
{
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos, SyncFixture.Window33);
var remote = f.Remote.Add("Comet", photos, SyncFixture.Window33);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
local = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
var none = new FramePhotos([]);
return (local, remote, CopyPayload.Portable(SyncPayload.Of(local), none), CopyPayload.Portable(SyncPayload.Of(remote.Dto(), remote.SettingsJson), none));
}
}
@@ -2,6 +2,7 @@ using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Copies;
using Chronos.Data.Sync;
using Chronos.Data.Tests.Archiving;
using Chronos.Protocol;
@@ -763,14 +764,14 @@ public sealed class SyncServiceTests(TestContext context)
other.FirstCapture = local.FirstCapture;
other.CameraModel = local.CameraModel;
await f.RefreshAsync();
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.WhenHalfShared });
var entry = await f.EntryAsync("Comet");
Assert.Equal(remote.Id, entry.Link?.RemoteId);
Assert.Equal((0, 0), (entry.Link!.MissingRemote, entry.Link.MissingLocal));
Assert.Null((await f.EntryAsync("Other card")).Local);
var manifests = f.Remote.ManifestCalls;
await f.RefreshAsync();
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.WhenHalfShared });
Assert.Equal(manifests, f.Remote.ManifestCalls);
}
@@ -0,0 +1,555 @@
using System.Security.Cryptography;
using Chronos.Core.Model;
using Chronos.Data.Copies;
using Chronos.Data.Jobs;
using Chronos.Data.Repositories;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Sync;
/// <summary>
/// The filtered transfers an Integrate runs (owner review 6, #73; design §5c): only the photos asked for, each once even
/// when resumed, a server sequence gone marks the pair, and a linked upload files into its target when the server can.
/// </summary>
[Category("sync")]
public sealed class SyncTransferCopyTests(TestContext context)
{
private static string Sha(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
private static async Task<JobContext> ContextAsync(SyncFixture f)
{
var engine = new JobEngine(f.Db, [], new JobEngineOptions { WorkerId = "t" });
await f.Db.Jobs.EnqueueAsync(new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Verify, State = JobState.Queued, Created = DateTimeOffset.UtcNow }, f.Ct);
var claimed = Assert.NotNull(await f.Db.Jobs.ClaimNextAsync("t", [JobKind.Verify], f.Ct));
return new JobContext(engine, claimed, f.Ct);
}
private static async Task<HashSet<string>> LocalHashesAsync(SyncFixture f, Guid id) =>
(await f.Db.Frames.ListBySequenceAsync(id, cancellationToken: f.Ct)).Select(fr => fr.Sha256!).ToHashSet(StringComparer.Ordinal);
private static SyncFixture Capable(SyncFixture f)
{
f.Remote.Capabilities.Add(ServerCapabilities.UploadInto);
f.Remote.Capabilities.Add(ServerCapabilities.PhotoLookup);
return f;
}
/// <summary>Waits until no pass a download queued works on <paramref name="sequenceId"/>.</summary>
private static async Task WaitIdleAsync(SyncFixture f, Guid sequenceId)
{
var until = DateTime.UtcNow.AddSeconds(30);
while (DateTime.UtcNow < until)
{
var held = await f.Db.Jobs.ListPendingTargetsAsync(JobKind.Thumbs, f.Ct);
held.UnionWith(await f.Db.Jobs.ListPendingTargetsAsync(JobKind.LightAnalyse, f.Ct));
if (!held.Contains(sequenceId)) return;
await Task.Delay(20, f.Ct);
}
}
[Test]
public async Task OnlyThePhotosAskedForGoEachWay()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
var photos = f.NewPhotos(5);
var local = await f.LocalAsync("Comet", [photos[0], photos[1], photos[2]]);
var remote = f.Remote.Add("Comet", [photos[0], photos[3], photos[4]]);
var job = await ContextAsync(f);
var transfers = new SyncTransfers(f.Sync);
Assert.Equal(1, await transfers.SendPhotosAsync(job, f.Remote, local.Id, remote.Id, [Sha(photos[1])]));
Assert.Equal(1, await transfers.FetchPhotosAsync(job, f.Remote, remote.Id, local.Id, [Sha(photos[3])]));
Assert.True(remote.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals([Sha(photos[0]), Sha(photos[1]), Sha(photos[3]), Sha(photos[4])]));
Assert.True((await LocalHashesAsync(f, local.Id)).SetEquals([Sha(photos[0]), Sha(photos[1]), Sha(photos[2]), Sha(photos[3])]));
Assert.Equal(1, f.Remote.IntoUploads);
}
[Test]
public async Task ARunAgainSendsAndFetchesNothingTwice()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
var photos = f.NewPhotos(4);
var local = await f.LocalAsync("Comet", [photos[0], photos[1]]);
var remote = f.Remote.Add("Comet", [photos[2], photos[3]]);
var job = await ContextAsync(f);
var transfers = new SyncTransfers(f.Sync);
var sent = new List<string>();
var fetched = new List<string>();
string[] send = [Sha(photos[0]), Sha(photos[1])], fetch = [Sha(photos[2]), Sha(photos[3])];
Assert.Equal(2, await transfers.SendPhotosAsync(job, f.Remote, local.Id, remote.Id, send, k => { sent.Add(k); return ValueTask.CompletedTask; }));
Assert.Equal(2, await transfers.FetchPhotosAsync(job, f.Remote, remote.Id, local.Id, fetch, k => { fetched.Add(k); return ValueTask.CompletedTask; }));
var uploads = f.Remote.IntoUploads;
Assert.Equal(0, await transfers.SendPhotosAsync(job, f.Remote, local.Id, remote.Id, send, k => { sent.Add(k); return ValueTask.CompletedTask; }));
Assert.Equal(0, await transfers.FetchPhotosAsync(job, f.Remote, remote.Id, local.Id, fetch, k => { fetched.Add(k); return ValueTask.CompletedTask; }));
Assert.Equal(uploads, f.Remote.IntoUploads);
Assert.Count(4, remote.Frames);
Assert.Count(4, await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct));
// Every key is reported done, the second time without moving a file.
Assert.SequenceEqual([.. send, .. send], sent);
Assert.SequenceEqual([.. fetch, .. fetch], fetched);
}
[Test]
public async Task AServerSequenceGoneMarksThePairAndSendsNowhereElse()
{
await using var f = await SyncFixture.CreateAsync(context);
// A server known by its id: a 404 there is that server's word (an address may name another server tomorrow).
var nas = new FakeSyncRemote { Server = ServerIdentity.IdKey(Guid.NewGuid()) };
nas.Capabilities.Add(ServerCapabilities.UploadInto);
nas.Capabilities.Add(ServerCapabilities.PhotoLookup);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
var remote = nas.Add("Comet", [photos[0]]);
var pair = await PairAsync(f, nas.Server, local.Id, remote.Id);
nas.Sequences.Remove(remote.Id);
var job = await ContextAsync(f);
var transfers = new SyncTransfers(f.Sync);
await Assert.ThrowsAsync<RemoteGoneException>(() => transfers.SendPhotosAsync(job, nas, local.Id, remote.Id, [Sha(photos[1])]));
await Assert.ThrowsAsync<RemoteGoneException>(() => transfers.FetchPhotosAsync(job, nas, remote.Id, local.Id, [Sha(photos[0])]));
Assert.Empty(nas.Sequences);
Assert.Equal(0, nas.IntoUploads);
Assert.Equal(1, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.RemoteGoneHits);
// A refresh right after asks again but does not count a second 404 within the recheck interval.
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
Assert.Equal(1, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.RemoteGoneHits);
}
[Test]
public async Task AGoneAnswerFromAServerKnownByItsAddressMarksNothing()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet", [photos[0]]);
var pair = await PairAsync(f, f.Server, local.Id, remote.Id);
f.Remote.Sequences.Remove(remote.Id);
var job = await ContextAsync(f);
await Assert.ThrowsAsync<RemoteGoneException>(() => new SyncTransfers(f.Sync).SendPhotosAsync(job, f.Remote, local.Id, remote.Id, [Sha(photos[1])]));
Assert.Equal(0, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.RemoteGoneHits);
}
[Test]
public async Task AFirstUploadWhoseFirstPhotoTheServerHoldsElsewhereEndsWithEveryPhotoInTheNewSequence()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos);
// The first photo is already on the server, in another sequence.
f.Remote.Add("Elsewhere", [photos[0]]);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var link = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct));
var target = f.Remote.Sequences[link.RemoteId];
Assert.True(target.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
}
[Test]
public async Task AnUploadOfASequenceKeptApartMakesANewServerSequenceAndLeavesTheOtherAlone()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", [photos[0], photos[1]]);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var first = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId;
// Unlinked ("Stop syncing these sequences"): the pair is kept apart.
await f.Sync.UnlinkAsync(f.Server, first, local.Id, f.Ct);
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(c => c.RemoteId == first);
Assert.Equal(CopyState.KeptApart, pair.State);
// A new photo, then a plain Upload.
await f.AddLocalAsync(local.Id, photos[2]);
job = await f.Sync.EnqueueUploadAsync(engine, f.Server, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
// The sequence kept apart gets nothing, and stays apart and unlinked; a new one holds every photo.
Assert.True(f.Remote.Sequences[first].Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals([Sha(photos[0]), Sha(photos[1])]));
Assert.Equal(CopyState.KeptApart, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
Assert.Null((await f.Sync.Links.GetAsync(f.Server, first, f.Ct))!.LocalId);
var link = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct));
Assert.NotEqual(first, link.RemoteId);
Assert.True(f.Remote.Sequences[link.RemoteId].Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
}
[Test]
public async Task ARetriedUploadNeverLinksAgainTheServerSequenceItsFirstAttemptMadeAndTheUserKeptApart()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", [photos[0], photos[1]]);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var started = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId;
// The user keeps the pair apart while a run of the upload that made it is still to be retried.
await f.Sync.UnlinkAsync(f.Server, started, local.Id, f.Ct);
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(c => c.RemoteId == started);
await f.AddLocalAsync(local.Id, photos[2]);
// The retry resumes from the checkpoint naming the sequence that run made.
var row = new Job
{
Id = Guid.CreateVersion7(),
Kind = JobKind.UploadCommit,
TargetIds = [local.Id],
State = JobState.Running,
NodeId = "t#0",
Created = DateTimeOffset.UtcNow,
Started = DateTimeOffset.UtcNow,
Checkpoint = started.ToString(),
};
await f.Db.Jobs.EnqueueAsync(row, f.Ct);
var retry = new JobContext(new JobEngine(f.Db, [], new JobEngineOptions { WorkerId = "t" }), row, f.Ct);
await new SyncTransfers(f.Sync).UploadAsync(retry, f.Remote, local.Id);
// The sequence kept apart stays apart, unlinked and as it was; a new one holds every photo.
Assert.Equal(CopyState.KeptApart, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
Assert.Null((await f.Sync.Links.GetAsync(f.Server, started, f.Ct))!.LocalId);
Assert.True(f.Remote.Sequences[started].Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals([Sha(photos[0]), Sha(photos[1])]));
var link = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct));
Assert.NotEqual(started, link.RemoteId);
Assert.True(f.Remote.Sequences[link.RemoteId].Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
}
[Test]
public async Task DownloadingAgainAServerSequenceUnlinkedFromItsDownloadMakesANewLocalSequence()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
var photos = f.NewPhotos(3);
var remote = f.Remote.Add("Comet", photos);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, f.Archive.Archive.Id);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var local = Assert.NotNull(Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
await WaitIdleAsync(f, local);
// Here: one photo deleted, the title edited; then the pair is unlinked (kept apart).
var sequence = (await f.Db.Sequences.GetAsync(local, f.Ct))!;
var gone = (await f.Db.Frames.ListBySequenceAsync(local, cancellationToken: f.Ct))[0];
var delete = await f.Archive.Service.FrameTrash.PlanDeleteAsync(local, [gone.Id], sequence.FramesVersion, f.Ct);
await f.Archive.Service.FrameTrash.DeleteAsync(delete, cancellationToken: f.Ct);
await f.Db.Sequences.EditAsync(local, new SequenceEdit { Title = "Mine" }, null, f.Ct);
await f.Sync.UnlinkAsync(f.Server, remote.Id, local, f.Ct);
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(c => c.RemoteId == remote.Id && c.LocalId == local);
Assert.Equal(CopyState.KeptApart, pair.State);
// Download originals again: a separate local copy.
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, f.Archive.Archive.Id);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
// The sequence kept apart is as the user left it: its photos, its deletion, its title, its pair.
var after = (await f.Db.Sequences.GetAsync(local, f.Ct))!;
Assert.Equal("Mine", after.Title);
Assert.Count(2, await f.Db.Frames.ListBySequenceAsync(local, cancellationToken: f.Ct));
Assert.Contains(gone.Sha256, (await f.Db.FrameRemovals.ListBySequenceAsync(local, f.Ct)).Select(r => r.Sha256));
Assert.Equal(CopyState.KeptApart, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
var copy = Assert.NotNull(Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
Assert.NotEqual(local, copy);
Assert.True((await LocalHashesAsync(f, copy)).SetEquals(photos.Select(Sha)));
}
[Test]
public async Task DownloadingAgainAServerSequenceWhoseLinkA404ForgotRefillsAndLinksItsOwnLocalCopy()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
var photos = f.NewPhotos(3);
var remote = f.Remote.Add("Comet", photos);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, f.Archive.Archive.Id);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var local = Assert.NotNull(Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
await WaitIdleAsync(f, local);
// A refresh's 404 forgot the link (the archive was briefly offline); listed again, the pair is asked about again.
await f.Sync.Links.DeleteAsync(f.Server, remote.Id, f.Ct);
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(c => c.RemoteId == remote.Id && c.LocalId == local);
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, pair.State, CopyState.Candidate, null, f.Ct));
// Download originals of the server-only sequence: it goes back into its own local copy, linked again.
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, f.Archive.Archive.Id);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.Equal(local, Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
Assert.Count(3, await f.Db.Frames.ListBySequenceAsync(local, cancellationToken: f.Ct));
Assert.True((await LocalHashesAsync(f, local)).SetEquals(photos.Select(Sha)));
var keys = await f.Db.Sequences.ListSessionKeysAsync(f.Archive.Archive.Id, SyncService.SessionKey(remote.Id) + "%", f.Ct);
Assert.True(keys.All(k => k.SequenceId == local), "no second local sequence holds a key of the server sequence");
Assert.Equal(1, (await f.Db.Sequences.ListAsync(new SequenceQuery(), f.Ct)).Items.Count);
}
[Test]
public async Task DownloadingAgainIntoTheOwnLocalCopyOfAPairAskedAgainKeepsItsDeletionsAndDetails()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
var photos = f.NewPhotos(3);
var remote = f.Remote.Add("Comet", photos);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, f.Archive.Archive.Id);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var local = Assert.NotNull(Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
await WaitIdleAsync(f, local);
// While linked: one photo deleted here (the server keeps it, owner Q6) and the title edited; then unlinked and
// asked about again (Ask again, or a Keep apart undone).
var sequence = (await f.Db.Sequences.GetAsync(local, f.Ct))!;
var gone = (await f.Db.Frames.ListBySequenceAsync(local, cancellationToken: f.Ct))[0];
var delete = await f.Archive.Service.FrameTrash.PlanDeleteAsync(local, [gone.Id], sequence.FramesVersion, f.Ct);
await f.Archive.Service.FrameTrash.DeleteAsync(delete, cancellationToken: f.Ct);
await f.Db.Sequences.EditAsync(local, new SequenceEdit { Title = "Mine" }, null, f.Ct);
await f.Sync.UnlinkAsync(f.Server, remote.Id, local, f.Ct);
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(c => c.RemoteId == remote.Id && c.LocalId == local);
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.KeptApart, CopyState.Candidate, null, f.Ct));
// Download originals of the server sequence: it refills its own local copy, as a linked copy.
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, f.Archive.Archive.Id);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
// The photo deleted here stays deleted, and the title is not overwritten by the server's.
Assert.Equal(local, Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
Assert.Count(2, await f.Db.Frames.ListBySequenceAsync(local, cancellationToken: f.Ct));
Assert.Contains(gone.Sha256, (await f.Db.FrameRemovals.ListBySequenceAsync(local, f.Ct)).Select(r => r.Sha256));
Assert.Equal("Mine", (await f.Db.Sequences.GetAsync(local, f.Ct))!.Title);
Assert.Equal("Comet", remote.Title);
Assert.Equal(1, (await f.Db.Sequences.ListAsync(new SequenceQuery(), f.Ct)).Items.Count);
}
[Test]
public async Task AnUploadOfASequenceAskedAboutAgainMakesANewServerSequenceAndLeavesTheOtherAlone()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", [photos[0], photos[1]]);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var first = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId;
// Unlinked, then asked about again: the pair is a Candidate and nothing links the two.
await f.Sync.UnlinkAsync(f.Server, first, local.Id, f.Ct);
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(c => c.RemoteId == first);
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.KeptApart, CopyState.Candidate, null, f.Ct));
// Renamed on the server (the web, another desktop); a new photo here.
var server = f.Remote.Sequences[first];
server.Title = "Comet NAS";
server.SettingsVersion++;
server.UpdatedAt = DateTimeOffset.UtcNow;
await f.AddLocalAsync(local.Id, photos[2]);
job = await f.Sync.EnqueueUploadAsync(engine, f.Server, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
// The other is not joined through the key, linked unasked or overwritten: a new server sequence holds every photo.
Assert.Equal("Comet NAS", server.Title);
Assert.True(server.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals([Sha(photos[0]), Sha(photos[1])]));
Assert.Equal(CopyState.Candidate, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
Assert.Null((await f.Sync.Links.GetAsync(f.Server, first, f.Ct))!.LocalId);
var link = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct));
Assert.NotEqual(first, link.RemoteId);
Assert.True(f.Remote.Sequences[link.RemoteId].Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
}
[Test]
public async Task AnUploadThatJoinsAServerSequenceItKnowsAlreadyComparesItsDetailsInsteadOfOverwritingThem()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", [photos[0], photos[1]]);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var first = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId;
// The link and its pair were forgotten (a sweep of 404s: the server served another archive for a while); the
// server sequence is listed again, as an observation.
var observed = Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, first, f.Ct)) with { LocalId = null };
await f.Sync.Links.UpsertAsync(observed, f.Ct);
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
await session.ExecuteAsync("DELETE FROM found_copies WHERE remote_id = $1", [first], f.Ct);
var server = f.Remote.Sequences[first];
server.Title = "Comet NAS";
server.SettingsVersion++;
server.UpdatedAt = DateTimeOffset.UtcNow;
await f.AddLocalAsync(local.Id, photos[2]);
job = await f.Sync.EnqueueUploadAsync(engine, f.Server, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
// Joined through this sequence's key, not made by this upload: the server's title is not overwritten unseen.
Assert.Equal(first, Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId);
Assert.True(server.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
Assert.Equal("Comet NAS", server.Title);
Assert.Equal("Comet", (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Title);
}
[Test]
public async Task ARetriedUploadThatJoinedAServerSequenceItKnewStillComparesItsDetails()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
var photos = f.NewPhotos(4);
var local = await f.LocalAsync("Comet", [photos[0], photos[1]]);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var first = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId;
// The link and its pair were forgotten; the server sequence is listed again and renamed there.
var observed = Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, first, f.Ct)) with { LocalId = null };
await f.Sync.Links.UpsertAsync(observed, f.Ct);
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
await session.ExecuteAsync("DELETE FROM found_copies WHERE remote_id = $1", [first], f.Ct);
var server = f.Remote.Sequences[first];
server.Title = "Comet NAS";
server.SettingsVersion++;
server.UpdatedAt = DateTimeOffset.UtcNow;
await f.AddLocalAsync(local.Id, photos[2]);
await f.AddLocalAsync(local.Id, photos[3]);
// One original unreadable for the first attempt: it fails after joining the known sequence.
var damaged = (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).Single(fr => fr.Sha256 == Sha(photos[3]));
var path = f.Archive.Paths.FromRelative(damaged.RelativePath);
var bytes = await File.ReadAllBytesAsync(path, f.Ct);
var broken = bytes.ToArray();
broken[^3] ^= 0xFF;
await File.WriteAllBytesAsync(path, broken, f.Ct);
var row = new Job
{
Id = Guid.CreateVersion7(),
Kind = JobKind.UploadCommit,
TargetIds = [local.Id],
State = JobState.Running,
NodeId = "t#0",
Created = DateTimeOffset.UtcNow,
Started = DateTimeOffset.UtcNow,
};
await f.Db.Jobs.EnqueueAsync(row, f.Ct);
var jobs = new JobEngine(f.Db, [], new JobEngineOptions { WorkerId = "t" });
var attempt = new JobContext(jobs, row, f.Ct);
await Assert.ThrowsAsync<InvalidDataException>(() => new SyncTransfers(f.Sync).UploadAsync(attempt, f.Remote, local.Id));
Assert.Equal(first, Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId);
// Retried from that attempt's checkpoint, the original readable again.
await File.WriteAllBytesAsync(path, bytes, f.Ct);
var retry = new JobContext(jobs, row with { Checkpoint = attempt.Checkpoint }, f.Ct);
await new SyncTransfers(f.Sync).UploadAsync(retry, f.Remote, local.Id);
// Still joined, not made by this upload: the server's title is not overwritten unseen.
Assert.True(server.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
Assert.Equal("Comet NAS", server.Title);
Assert.Equal("Comet", (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Title);
}
[Test]
public async Task AnAutomaticUploadAfterTheServerCopyIsGoneFailsAndCreatesNothing()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet", [photos[0]]);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
var pair = await PairAsync(f, f.Server, local.Id, remote.Id);
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, null, CopyState.Integrated, new CopyAnswer(null, null, null, true, DateTimeOffset.UtcNow), f.Ct));
f.Remote.Sequences.Remove(remote.Id);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueAutomaticUploadAsync(engine, f.Server, local, f.Ct);
await f.Archive.WaitForAsync(job.Id, JobState.Failed);
// Never a new server sequence: the automatic photos move only between the two the pair joins.
Assert.Empty(f.Remote.Sequences);
}
[Test]
public async Task AnAutomaticUploadOfAPairNoLongerIntegratedSendsNothing()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet", [photos[0]]);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await PairAsync(f, f.Server, local.Id, remote.Id, CopyState.Linked);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueAutomaticUploadAsync(engine, f.Server, local, f.Ct);
await f.Archive.WaitForAsync(job.Id, JobState.Failed);
Assert.Count(1, remote.Frames);
}
[Test]
public async Task AnAutomaticDownloadWithoutTheLocalCopyFailsAndCreatesNoSequence()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
var remote = f.Remote.Add("Comet", f.NewPhotos(2));
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueAutomaticDownloadAsync(engine, f.Server, remote.Id, "Comet", f.Archive.Archive.Id, f.Ct);
await f.Archive.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(0, await f.Db.Sequences.CountAsync(new() { ArchiveId = f.Archive.Archive.Id }, f.Ct));
}
private static Task<FoundCopy> PairAsync(SyncFixture f, string server, Guid localId, Guid remoteId, CopyState state = CopyState.Candidate) =>
f.Sync.Copies.UpsertFoundAsync(new FoundCopy
{
Id = Guid.NewGuid(),
Kind = CopyKind.LocalServer,
LocalId = localId,
Server = server,
RemoteId = remoteId,
Evidence = CopyEvidence.Hashes,
Fingerprint = "f",
State = state,
}, f.Ct);
[Test]
public async Task ALinkedUploadFilesIntoItsTargetWhenTheServerCan()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet", [photos[0]]);
// The server holds the second photo in another sequence: filed into the target all the same.
f.Remote.Add("Elsewhere", [photos[1]]);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.True(remote.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
Assert.Equal((1, 1), (f.Remote.IntoUploads, f.Remote.CopiedInto));
}
[Test]
public async Task ALinkedUploadTheServerRefusesIntoItsTargetStillFilesEveryOriginal()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
// An account with Read and Upload but not Edit, whose local sequence is linked to another account's: 403 for "into".
f.Remote.ForbidInto = true;
var photos = f.NewPhotos(4);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet", [photos[0]]);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
// The refusal falls back to the upload as before the server could file into a target: every original is there.
Assert.True(remote.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
Assert.True(f.Remote.RefusedInto >= 1);
Assert.Equal(0, f.Remote.IntoUploads);
}
}
@@ -6,6 +6,7 @@ using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Data.Archiving;
using Chronos.Data.Copies;
using Chronos.Data.Sync;
using Chronos.Data.Tests.Archiving;
using Chronos.Protocol;
@@ -879,7 +880,7 @@ public sealed class SyncTransferTests(TestContext context)
theirs.FirstCapture = mine.FirstCapture;
theirs.CameraModel = mine.CameraModel;
await f.RefreshAsync();
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.WhenHalfShared });
var comet = await f.EntryAsync("Comet");
Assert.Equal(remote.Id, comet.Link?.RemoteId);
@@ -0,0 +1,72 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Server.Tests.Api;
/// <summary>
/// The wire shapes of found copies (owner review 6, #73): the photo lookup in camelCase with nulls left out, and the upload
/// members added trailing and optional, so a client or server of before reads and writes them as it did.
/// </summary>
public sealed class CopyContractTests
{
private static readonly Guid SequenceId = Guid.Parse("01890000-0000-7000-8000-000000000002");
private static readonly DateTime Captured = new(2026, 10, 1, 18, 0, 0, 123, DateTimeKind.Unspecified);
[Test]
public void ALookupTravelsAsProbesAndHits()
{
var hash = new string('a', 64);
var request = new PhotoLookupRequest(
[
new PhotoProbe("p1", [hash], [new PhotoKeyDto(25_000_001, Captured)], "upload-1"),
new PhotoProbe("p2", [hash]),
]);
var json = JsonNode.Parse(JsonSerializer.Serialize(request, ProtocolJson.Default.PhotoLookupRequest))!.AsObject();
Assert.SequenceEqual(["probes"], json.Select(p => p.Key));
Assert.SequenceEqual(["key", "sha256", "unhashed", "sessionKey"], json["probes"]![0]!.AsObject().Select(p => p.Key));
Assert.SequenceEqual(["key", "sha256"], json["probes"]![1]!.AsObject().Select(p => p.Key));
Assert.SequenceEqual(["size", "capturedAt"], json["probes"]![0]!["unhashed"]![0]!.AsObject().Select(p => p.Key));
var back = JsonSerializer.Deserialize(json.ToJsonString(), ProtocolJson.Default.PhotoLookupRequest)!;
Assert.Equal(2, back.Probes.Count);
Assert.Equal(("p1", "upload-1", Captured), (back.Probes[0].Key, back.Probes[0].SessionKey, back.Probes[0].Unhashed![0].CapturedAt));
Assert.Null(back.Probes[1].Unhashed);
// The limit counts hashes, unhashed keys and session keys; the count is never sent.
Assert.Equal(4, request.CountItems());
Assert.Equal((200, 20_000), (PhotoLookupRequest.MaxProbes, PhotoLookupRequest.MaxItems));
var response = new PhotoLookupResponse([new ProbeResult("p1", [new PhotoLookupHit(SequenceId, 1, 0, 1, true)]), new ProbeResult("p2", [])]);
var answer = JsonNode.Parse(JsonSerializer.Serialize(response, ProtocolJson.Default.PhotoLookupResponse))!.AsObject();
Assert.SequenceEqual(["sequenceId", "hashes", "removed", "unhashed", "sessionKey"], answer["results"]![0]!["hits"]![0]!.AsObject().Select(p => p.Key));
var read = JsonSerializer.Deserialize(answer.ToJsonString(), ProtocolJson.Default.PhotoLookupResponse)!;
Assert.Equal(response.Results[0].Hits[0], read.Results[0].Hits[0]);
Assert.Empty(read.Results[1].Hits);
Assert.Equal(("photo-lookup", "upload-into"), (ServerCapabilities.PhotoLookup, ServerCapabilities.UploadInto));
}
[Test]
public void AnUploadIntoATargetIsAnOptionalTrailingFlag()
{
// A client of before sends no flag: an upload as before.
var old = JsonSerializer.Deserialize(
"""{ "sequenceId": null, "fileName": "IMG_0001.JPG", "size": 10, "sha256": "ab", "capturedAt": null, "sessionKey": "upload-1" }""",
ProtocolJson.Default.StartUploadRequest)!;
Assert.Equal((false, false), (old.Restore, old.IntoTarget));
var into = new StartUploadRequest(SequenceId, "IMG_0001.JPG", 10, "ab", null, null, IntoTarget: true);
var json = JsonNode.Parse(JsonSerializer.Serialize(into, ProtocolJson.Default.StartUploadRequest))!.AsObject();
Assert.Equal("intoTarget", json.Last().Key);
Assert.True(json["intoTarget"]!.GetValue<bool>());
Assert.True(JsonSerializer.Deserialize(json.ToJsonString(), ProtocolJson.Default.StartUploadRequest)!.IntoTarget);
// A server of before answers without Copied.
var answer = JsonSerializer.Deserialize("""{ "uploadId": null, "chunkSize": 0, "received": [], "alreadyExists": true, "frameId": null }""",
ProtocolJson.Default.StartUploadResponse)!;
Assert.False(answer.Copied);
var copied = new StartUploadResponse(null, 0, [], true, SequenceId, Copied: true);
var copiedJson = JsonNode.Parse(JsonSerializer.Serialize(copied, ProtocolJson.Default.StartUploadResponse))!.AsObject();
Assert.Equal("copied", copiedJson.Last().Key);
var back = JsonSerializer.Deserialize(copiedJson.ToJsonString(), ProtocolJson.Default.StartUploadResponse)!;
Assert.Equal(((Guid?)SequenceId, true, true), (back.FrameId, back.AlreadyExists, back.Copied));
}
}
@@ -0,0 +1,239 @@
using System.Net;
using System.Net.Http.Json;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Protocol;
using Chronos.Server.Configuration;
using Chronos.Testing;
namespace Chronos.Server.Tests.Api;
/// <summary><c>POST /api/v1/photos/lookup</c> (owner review 6, #73): counts per probe, scoped to the served archive.</summary>
[Category("server")]
public sealed class PhotoLookupTests(TestContext context)
{
private static readonly DateTime Shot = new DateTime(2026, 9, 28, 18, 2, 11, 123, DateTimeKind.Unspecified).AddTicks(4560);
[Test]
public async Task EachProbeCountsTheSequencesThatHoldItsPhotos()
{
await using var server = await TestServer.StartAsync(context);
await CountsAsync(server, context);
}
[Test]
[RequiresEnvironment("CHRONOS_TEST_PG")]
public async Task EachProbeCountsTheSequencesThatHoldItsPhotosOnPostgres()
{
await using var schema = await PgSchema.CreateAsync(context);
await using var server = await schema.StartAsync(context);
Assert.Equal(Dialect.Postgres, server.Database.Dialect);
await CountsAsync(server, context);
}
[Test]
public async Task OnlyTheServedArchiveIsLookedAt()
{
await using var server = await TestServer.StartAsync(context);
await ScopedAsync(server, context);
}
[Test]
[RequiresEnvironment("CHRONOS_TEST_PG")]
public async Task OnlyTheServedArchiveIsLookedAtOnPostgres()
{
await using var schema = await PgSchema.CreateAsync(context);
await using var server = await schema.StartAsync(context);
await ScopedAsync(server, context);
}
[Test]
public async Task TheLookupNeedsTheReadRight()
{
await using var server = await TestServer.StartAsync(context);
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
using (var refused = await LookupAsync(uploader, new PhotoLookupRequest([new PhotoProbe("a", [Hash('a')])])))
await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var anonymous = await LookupAsync(server.Client, new PhotoLookupRequest([new PhotoProbe("a", [Hash('a')])])))
Assert.Equal(HttpStatusCode.Unauthorized, anonymous.StatusCode);
var (viewer, _, _) = await server.UserAsync("guest", "viewer");
using var allowed = await LookupAsync(viewer, new PhotoLookupRequest([new PhotoProbe("a", [Hash('a')])]));
Assert.Empty(Assert.NotNull(await allowed.ReadAsync(ProtocolJson.Default.PhotoLookupResponse)).Results.Single().Hits);
}
[Test]
public async Task MoreThan200ProbesOr20000ItemsAreRefused()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var most = Enumerable.Range(0, PhotoLookupRequest.MaxProbes).Select(i => new PhotoProbe("p" + i, [Hash('b')])).ToList();
using (var ok = await LookupAsync(editor, new PhotoLookupRequest(most)))
Assert.Equal(PhotoLookupRequest.MaxProbes, (await ok.ReadAsync(ProtocolJson.Default.PhotoLookupResponse)).Results.Count);
using (var probes = await LookupAsync(editor, new PhotoLookupRequest([.. most, new PhotoProbe("one more", [Hash('b')])])))
await probes.ExpectErrorAsync(HttpStatusCode.RequestEntityTooLarge, "too_many");
// 20,000 items fit in one request (a body larger than the other JSON calls take); one more does not.
var hashes = Enumerable.Range(0, PhotoLookupRequest.MaxItems - 100).Select(i => i.ToString("x64", System.Globalization.CultureInfo.InvariantCulture)).ToList();
var unhashed = Enumerable.Range(0, 99).Select(i => new PhotoKeyDto(1000 + i, Shot.AddSeconds(i))).ToList();
var full = new PhotoProbe("full", hashes, unhashed, "chronos-sync:" + Guid.NewGuid().ToString("N"));
Assert.Equal(PhotoLookupRequest.MaxItems, new PhotoLookupRequest([full]).CountItems());
using (var ok = await LookupAsync(editor, new PhotoLookupRequest([full])))
Assert.Empty((await ok.ReadAsync(ProtocolJson.Default.PhotoLookupResponse)).Results.Single().Hits);
var over = full with { Unhashed = [.. unhashed, new PhotoKeyDto(5, Shot)] };
using (var items = await LookupAsync(editor, new PhotoLookupRequest([over])))
await items.ExpectErrorAsync(HttpStatusCode.RequestEntityTooLarge, "too_many");
}
[Test]
public async Task TheServerAnnouncesTheLookupAndUploadsIntoATarget()
{
await using var server = await TestServer.StartAsync(context);
using var response = await server.Client.GetAsync("/api/v1/server/info");
var info = await response.ReadAsync(ProtocolJson.Default.ServerInfo);
Assert.Contains(ServerCapabilities.PhotoLookup, info.Capabilities);
Assert.Contains(ServerCapabilities.UploadInto, info.Capabilities);
}
/// <summary>
/// Sequence A holds p1, p2 and p3 (p3 captured at <see cref="Shot"/>); B holds p4, tombstoned p5, replaced p6 by p7 and
/// is filed under a session key. One probe counts both, another hits nothing.
/// </summary>
internal static async Task CountsAsync(TestServer server, TestContext context)
{
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var photos = Enumerable.Range(1, 7).Select(i => Uploads.Photo(3000 + i, 700 + i)).ToArray();
var a = (await Uploads.UploadAsync(editor, photos[0], "IMG_0001.JPG", sessionKey: "a")).SequenceId;
await Uploads.UploadAsync(editor, photos[1], "IMG_0002.JPG", sessionKey: "a");
await Uploads.UploadAsync(editor, photos[2], "IMG_0003.JPG", sessionKey: "a", capturedAt: Shot);
var b = (await Uploads.UploadAsync(editor, photos[3], "IMG_0004.JPG", sessionKey: "b")).SequenceId;
var now = DateTimeOffset.UtcNow;
await server.Database.FrameRemovals.SyncSequenceAsync(b,
[
new FrameRemoval(b, Uploads.Sha(photos[4]), null, RemovalReason.Deleted, now),
new FrameRemoval(b, Uploads.Sha(photos[5]), Uploads.Sha(photos[6]), RemovalReason.Replaced, now),
// A stale tombstone: B still holds p4, which counts once, as held.
new FrameRemoval(b, Uploads.Sha(photos[3]), null, RemovalReason.Deleted, now),
], context.Cancellation);
var archive = (await server.Database.Sequences.GetAsync(b, context.Cancellation))!.ArchiveId;
var key = "chronos-sync:" + Guid.NewGuid().ToString("N");
await server.Database.Sequences.MapSessionKeyAsync(archive, key, b, context.Cancellation);
var probe = new PhotoProbe("local-1",
[Uploads.Sha(photos[0]).ToUpperInvariant(), Uploads.Sha(photos[1]), Uploads.Sha(photos[1]), Uploads.Sha(photos[3]), Uploads.Sha(photos[4]),
Uploads.Sha(photos[6]), Hash('c')],
[
// The same millisecond as p3 (the index keeps microseconds); the next millisecond, another size: no match.
new PhotoKeyDto(photos[2].Length, new DateTime(2026, 9, 28, 18, 2, 11, 123).AddTicks(9999)),
new PhotoKeyDto(photos[2].Length, new DateTime(2026, 9, 28, 18, 2, 11, 124)),
new PhotoKeyDto(photos[2].Length + 1, Shot),
],
key);
var nothing = new PhotoProbe("local-2", [Hash('d')], [new PhotoKeyDto(photos[2].Length, Shot.AddDays(1))], "chronos-sync:" + Guid.NewGuid().ToString("N"));
using var response = await LookupAsync(editor, new PhotoLookupRequest([probe, nothing]));
var results = (await response.ReadAsync(ProtocolJson.Default.PhotoLookupResponse)).Results;
Assert.SequenceEqual(["local-1", "local-2"], results.Select(r => r.Key));
var hits = results[0].Hits.ToDictionary(h => h.SequenceId);
Assert.Equal(2, hits.Count);
Assert.Equal(new PhotoLookupHit(a, Hashes: 2, Removed: 0, Unhashed: 1, SessionKey: false), hits[a]);
Assert.Equal(new PhotoLookupHit(b, Hashes: 1, Removed: 2, Unhashed: 0, SessionKey: true), hits[b]);
Assert.Empty(results[1].Hits);
}
/// <summary>A sequence of another archive of the index holding the same photo and session key is never answered.</summary>
internal static async Task ScopedAsync(TestServer server, TestContext context)
{
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var photo = Uploads.Photo(4000, 801);
var mine = (await Uploads.UploadAsync(editor, photo, sessionKey: "mine", capturedAt: Shot)).SequenceId;
var key = "chronos-sync:" + Guid.NewGuid().ToString("N");
var foreign = await ForeignFrameAsync(server, context, photo, Shot, key);
using var response = await LookupAsync(editor, new PhotoLookupRequest([new PhotoProbe("x", [Uploads.Sha(photo)], [new PhotoKeyDto(photo.Length, Shot)], key)]));
var hit = (await response.ReadAsync(ProtocolJson.Default.PhotoLookupResponse)).Results.Single().Hits.Single();
Assert.Equal(new PhotoLookupHit(mine, 1, 0, 1, false), hit);
Assert.NotEqual(foreign.SequenceId, hit.SequenceId);
}
/// <summary>
/// A frame of <paramref name="data"/> in a sequence of a second archive of the index (as a desktop sharing its library
/// keeps other archives' sequences), its file under that archive's root; optionally filed under <paramref name="sessionKey"/>.
/// </summary>
internal static async Task<Frame> ForeignFrameAsync(TestServer server, TestContext context, byte[] data, DateTime? capturedAt = null, string? sessionKey = null)
{
var db = server.Database;
var other = new Archive { Id = Guid.CreateVersion7(), Name = "Another archive", RootPath = context.CreateTempDirectory("other-archive"), Created = DateTimeOffset.UtcNow };
await db.Archives.UpsertAsync(other, context.Cancellation);
var sequence = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = other.Id, Folder = "2026/other", UpdatedAt = DateTimeOffset.UtcNow };
await db.Sequences.UpsertAsync(sequence, context.Cancellation);
const string relative = "2026/other/originals/0000_IMG_0001.CR3";
var path = Path.Combine(other.RootPath, relative);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
await File.WriteAllBytesAsync(path, data, context.Cancellation);
var frame = new Frame
{
Id = Guid.CreateVersion7(),
SequenceId = sequence.Id,
Index = 0,
RelativePath = relative,
FileName = Path.GetFileName(relative),
OriginalFileName = "IMG_0001.CR3",
Size = data.Length,
Sha256 = Uploads.Sha(data),
CapturedAt = capturedAt,
};
await db.Frames.InsertAsync(frame, context.Cancellation);
await db.Sequences.RefreshStatsAsync(sequence.Id, context.Cancellation);
if (sessionKey is not null) await db.Sequences.MapSessionKeyAsync(other.Id, sessionKey, sequence.Id, context.Cancellation);
return frame;
}
internal static Task<HttpResponseMessage> LookupAsync(HttpClient client, PhotoLookupRequest request) =>
client.PostAsJsonAsync("/api/v1/photos/lookup", request, ProtocolJson.Default.PhotoLookupRequest);
private static string Hash(char c) => new(c, 64);
}
/// <summary>A throw-away schema on the PostgreSQL test server (<c>CHRONOS_TEST_PG</c>), selected through <c>Search Path</c>.</summary>
internal sealed class PgSchema : IAsyncDisposable
{
private readonly IDatabase _admin;
private readonly string _name;
private PgSchema(IDatabase admin, string name, string connectionString)
{
_admin = admin;
_name = name;
ConnectionString = connectionString;
}
public string ConnectionString { get; }
public static async Task<PgSchema> CreateAsync(TestContext context)
{
var baseConnection = Environment.GetEnvironmentVariable("CHRONOS_TEST_PG")!;
var admin = DatabaseFactory.Open(DatabaseOptions.Postgres(baseConnection));
var name = "chronos_l_" + Guid.NewGuid().ToString("N")[..16];
await using (var session = await admin.OpenAsync(context.Cancellation))
await session.ExecuteScriptAsync($"CREATE SCHEMA {name}", context.Cancellation);
return new PgSchema(admin, name, baseConnection.TrimEnd(';', ' ') + $";Search Path={name}");
}
/// <summary>A test server on this schema.</summary>
public Task<TestServer> StartAsync(TestContext context, Action<ServerOptions>? configure = null,
Action<Microsoft.Extensions.DependencyInjection.IServiceCollection>? services = null) =>
TestServer.StartAsync(context, o =>
{
o.Database = DatabaseKind.Postgres;
o.DbConnectionString = ConnectionString;
configure?.Invoke(o);
}, services);
public async ValueTask DisposeAsync()
{
await using (var session = await _admin.OpenAsync(CancellationToken.None))
await session.ExecuteScriptAsync($"DROP SCHEMA IF EXISTS {_name} CASCADE", CancellationToken.None);
await _admin.DisposeAsync();
}
}
@@ -0,0 +1,298 @@
using System.Net;
using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Protocol;
using Chronos.Server.Events;
using Chronos.Server.Tests.Api;
using Chronos.Testing;
namespace Chronos.Server.Tests.Storage;
/// <summary>
/// <see cref="StartUploadRequest.IntoTarget"/> (owner review 6, #73): a photo another sequence of the served archive holds is
/// copied into the target by the server itself, authorised and scoped on the server.
/// </summary>
[Category("server")]
public sealed class UploadIntoTests(TestContext context)
{
private static readonly DateTime Shot = new(2026, 9, 28, 18, 2, 11, 250, DateTimeKind.Unspecified);
[Test]
public async Task APhotoHeldElsewhereIsCopiedIntoTheTargetAndChargedOnce()
{
await using var server = await TestServer.StartAsync(context);
await CopiedAsync(server, context);
}
[Test]
[RequiresEnvironment("CHRONOS_TEST_PG")]
public async Task APhotoHeldElsewhereIsCopiedIntoTheTargetAndChargedOnceOnPostgres()
{
await using var schema = await PgSchema.CreateAsync(context);
await using var server = await schema.StartAsync(context);
Assert.Equal(Dialect.Postgres, server.Database.Dialect);
await CopiedAsync(server, context);
}
[Test]
public async Task ACommitThatFindsThePhotoFiledMeanwhileChargesNothing()
{
await using var server = await TestServer.StartAsync(context, services: s =>
{
s.AddSingleton<RacingIngest>();
s.AddSingleton<IArchiveIngest>(sp => sp.GetRequiredService<RacingIngest>());
});
var scene = await SceneAsync(server);
var racing = server.Services.GetRequiredService<RacingIngest>();
Guid? raced = null;
// Another writer files the same photo into the target just before this commit: the ingest answers a duplicate.
racing.Before = async request =>
{
var copy = request.StagedPath + ".race";
File.Copy(request.StagedPath, copy);
raced = (await racing.Inner.CommitAsync(request with { StagedPath = copy }, context.Cancellation)).FrameId;
};
var used = await UsedAsync(scene.Editor);
using var response = await StartIntoAsync(scene.Editor, scene.Photo, scene.Target);
var answer = await response.ReadAsync(ProtocolJson.Default.StartUploadResponse);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(answer.AlreadyExists && answer.Copied);
Assert.Equal(Assert.NotNull(raced), answer.FrameId);
Assert.Equal(used, await UsedAsync(scene.Editor));
Assert.Empty(Directory.EnumerateFiles(server.Options.StagingPath));
}
[Test]
public async Task TheCopyIsRefusedBeyondTheQuota()
{
await using var server = await TestServer.StartAsync(context);
// The two uploads of the scene take 9,000 bytes; copying the 5,000-byte photo would take the account beyond 10,000.
var scene = await SceneAsync(server, quota: 10_000);
using var response = await StartIntoAsync(scene.Editor, scene.Photo, scene.Target);
await response.ExpectErrorAsync(HttpStatusCode.Forbidden, "quota_exceeded");
Assert.Empty(await FramesOfAsync(server, scene.Target, scene.Photo));
}
[Test]
public async Task OnlyTheOwnerAnAdminOrAnEditorMayUploadIntoATarget()
{
await using var server = await TestServer.StartAsync(context);
var scene = await SceneAsync(server);
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
// An upload-only account may not file into another account's sequence.
using (var refused = await StartIntoAsync(uploader, scene.Photo, scene.Target))
await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
Assert.Empty(await FramesOfAsync(server, scene.Target, scene.Photo));
// Into its own sequence it may: the server copies the photo the editor's sequence holds.
var own = (await Uploads.UploadAsync(uploader, Uploads.Photo(3000, 903), "IMG_0200.CR3", sessionKey: "roof")).SequenceId;
using (var allowed = await StartIntoAsync(uploader, scene.Photo, own))
Assert.True((await allowed.ReadAsync(ProtocolJson.Default.StartUploadResponse)).Copied);
Assert.Count(1, await FramesOfAsync(server, own, scene.Photo));
// An administrator may.
var admin = await server.AdminAsync();
using (var byAdmin = await StartIntoAsync(admin, scene.Photo, scene.Target))
Assert.True((await byAdmin.ReadAsync(ProtocolJson.Default.StartUploadResponse)).Copied);
}
[Test]
public async Task ATargetOfAnotherArchiveIsUnknown()
{
await using var server = await TestServer.StartAsync(context);
var scene = await SceneAsync(server);
var foreign = await PhotoLookupTests.ForeignFrameAsync(server, context, Uploads.Photo(2000, 904));
using (var other = await StartIntoAsync(scene.Editor, scene.Photo, foreign.SequenceId))
Assert.Equal("sequence", (await other.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found")).Details);
using (var unknown = await StartIntoAsync(scene.Editor, scene.Photo, Guid.CreateVersion7()))
await unknown.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
Assert.Empty(await FramesOfAsync(server, foreign.SequenceId, scene.Photo));
}
[Test]
public async Task AnUploadIntoATargetNamesItAndNeverRestores()
{
await using var server = await TestServer.StartAsync(context);
var scene = await SceneAsync(server);
using (var restore = await StartIntoAsync(scene.Editor, scene.Photo, scene.Target, restore: true))
Assert.Equal("restore", (await restore.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request")).Details);
using (var none = await StartIntoAsync(scene.Editor, scene.Photo, null))
Assert.Equal("sequenceId", (await none.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request")).Details);
}
[Test]
public async Task ATargetThatHoldsThePhotoAnswersItsFrame()
{
await using var server = await TestServer.StartAsync(context);
var scene = await SceneAsync(server);
using var response = await StartIntoAsync(scene.Editor, scene.Photo, scene.Held.SequenceId);
var answer = await response.ReadAsync(ProtocolJson.Default.StartUploadResponse);
Assert.True(answer.AlreadyExists);
Assert.False(answer.Copied);
Assert.Equal(scene.Held.FrameId, answer.FrameId);
}
[Test]
public async Task APhotoTheTargetDeletedStaysDeleted()
{
await using var server = await TestServer.StartAsync(context);
var scene = await SceneAsync(server);
await server.Database.FrameRemovals.SyncSequenceAsync(scene.Target,
[new FrameRemoval(scene.Target, Uploads.Sha(scene.Photo), null, RemovalReason.Deleted, DateTimeOffset.UtcNow)], context.Cancellation);
var requests = server.Services.GetRequiredService<FakeArchiveIngest>().Requests.Count;
using var response = await StartIntoAsync(scene.Editor, scene.Photo, scene.Target);
var answer = await response.ReadAsync(ProtocolJson.Default.StartUploadResponse);
Assert.True(answer.AlreadyExists);
Assert.Null(answer.FrameId);
Assert.False(answer.Copied);
Assert.Empty(await FramesOfAsync(server, scene.Target, scene.Photo));
Assert.Equal(requests, server.Services.GetRequiredService<FakeArchiveIngest>().Requests.Count);
}
[Test]
public async Task APhotoOnlyAnotherArchiveHoldsIsUploaded()
{
await using var server = await TestServer.StartAsync(context);
var scene = await SceneAsync(server);
var elsewhere = Uploads.Photo(2500, 905);
await PhotoLookupTests.ForeignFrameAsync(server, context, elsewhere);
using var response = await StartIntoAsync(scene.Editor, elsewhere, scene.Target);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
var answer = await response.ReadAsync(ProtocolJson.Default.StartUploadResponse);
Assert.NotNull(answer.UploadId);
Assert.False(answer.AlreadyExists || answer.Copied);
}
[Test]
public async Task ADamagedSourceLeavesTheClientToSendThePhoto()
{
await using var server = await TestServer.StartAsync(context);
var scene = await SceneAsync(server);
// The file keeps its size, so the frame reads as intact; its bytes are no longer the photo.
var source = Assert.NotNull(await server.Database.Frames.GetAsync(scene.Held.FrameId));
await File.WriteAllBytesAsync(Path.Combine(server.Options.ArchivePath, source.RelativePath), Uploads.Photo(scene.Photo.Length, 906), context.Cancellation);
using (var response = await StartIntoAsync(scene.Editor, scene.Photo, scene.Target))
{
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
var answer = await response.ReadAsync(ProtocolJson.Default.StartUploadResponse);
Assert.NotNull(answer.UploadId);
Assert.False(answer.Copied);
}
Assert.Empty(Directory.EnumerateFiles(server.Options.StagingPath));
Assert.Empty(await FramesOfAsync(server, scene.Target, scene.Photo));
}
[Test]
public async Task WithoutIntoTargetACopyElsewhereStillStandsIn()
{
await using var server = await TestServer.StartAsync(context);
var scene = await SceneAsync(server);
var used = await UsedAsync(scene.Editor);
var answer = await Uploads.StartAsync(scene.Editor, scene.Photo, sequenceId: scene.Target, expected: HttpStatusCode.OK);
Assert.True(answer.AlreadyExists);
Assert.False(answer.Copied);
Assert.Equal(scene.Held.FrameId, answer.FrameId);
Assert.Empty(await FramesOfAsync(server, scene.Target, scene.Photo));
Assert.Equal(used, await UsedAsync(scene.Editor));
}
/// <summary>The copy lands in the target with the photo's bytes, charged once, announced, and answered from the target after.</summary>
internal static async Task CopiedAsync(TestServer server, TestContext context)
{
var scene = await SceneAsync(server);
var used = await UsedAsync(scene.Editor);
using var events = server.Services.GetRequiredService<EventHub>().Subscribe();
StartUploadResponse answer;
using (var response = await StartIntoAsync(scene.Editor, scene.Photo, scene.Target))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
answer = await response.ReadAsync(ProtocolJson.Default.StartUploadResponse);
}
Assert.True(answer.AlreadyExists && answer.Copied);
Assert.Null(answer.UploadId);
var frame = Assert.NotNull(await server.Database.Frames.GetAsync(Assert.NotNull(answer.FrameId), context.Cancellation));
Assert.Equal(scene.Target, frame.SequenceId);
Assert.Equal(Uploads.Sha(scene.Photo), frame.Sha256);
await Http.BytesEqualAsync(scene.Photo, File.ReadAllBytesAsync(Path.Combine(server.Options.ArchivePath, frame.RelativePath)));
Assert.NotNull(await server.Database.Frames.GetAsync(scene.Held.FrameId, context.Cancellation));
var request = Assert.NotNull(server.Services.GetRequiredService<FakeArchiveIngest>().Requests.LastOrDefault());
Assert.Equal(scene.Target, request.SequenceId);
Assert.True(request.RefuseRemoved, "the copy refuses a photo the target deleted");
Assert.Equal(scene.Photo.Length, request.Size);
Assert.True(request.StagedPath.StartsWith(server.Options.StagingPath, StringComparison.Ordinal), request.StagedPath);
Assert.Empty(Directory.EnumerateFiles(server.Options.StagingPath));
Assert.Equal(used + scene.Photo.Length, await UsedAsync(scene.Editor));
using (var wait = CancellationTokenSource.CreateLinkedTokenSource(context.Cancellation))
{
wait.CancelAfter(TimeSpan.FromSeconds(10));
while (await events.Reader.ReadAsync(wait.Token) is var e)
{
if (e is SequenceChangedEvent { Change: "frames" } changed && changed.SequenceId == scene.Target) break;
}
}
// Asked again, the target answers with its own copy, charged nothing more.
using (var again = await StartIntoAsync(scene.Editor, scene.Photo, scene.Target))
{
var repeated = await again.ReadAsync(ProtocolJson.Default.StartUploadResponse);
Assert.True(repeated.AlreadyExists);
Assert.False(repeated.Copied);
Assert.Equal(frame.Id, repeated.FrameId);
}
Assert.Equal(used + scene.Photo.Length, await UsedAsync(scene.Editor));
Assert.Count(1, await FramesOfAsync(server, scene.Target, scene.Photo));
}
/// <summary>An editor's sequence A holding a 5,000-byte photo, and the editor's sequence B (the target) holding another photo.</summary>
private static async Task<Scene> SceneAsync(TestServer server, long quota = 0)
{
var (editor, _, _) = await server.UserAsync("alberto", "editor", quotaBytes: quota);
var photo = Uploads.Photo(5000, 901);
var held = await Uploads.UploadAsync(editor, photo, "IMG_0001.CR3", sessionKey: "a", capturedAt: Shot);
var target = (await Uploads.UploadAsync(editor, Uploads.Photo(4000, 902), "IMG_0100.CR3", sessionKey: "b")).SequenceId;
return new Scene(editor, photo, held, target);
}
private static Task<HttpResponseMessage> StartIntoAsync(HttpClient client, byte[] data, Guid? target, bool restore = false) =>
client.PostAsJsonAsync("/api/v1/uploads", new StartUploadRequest(target, "IMG_0001.CR3", data.Length, Uploads.Sha(data), Shot, null, restore, IntoTarget: true),
ProtocolJson.Default.StartUploadRequest);
private static async Task<long> UsedAsync(HttpClient client)
{
using var me = await client.GetAsync("/api/v1/auth/me");
return (await me.ReadAsync(ProtocolJson.Default.UserDto)).UsedBytes;
}
private static async Task<IReadOnlyList<Frame>> FramesOfAsync(TestServer server, Guid sequenceId, byte[] photo) =>
[.. (await server.Database.Frames.FindBySha256Async(Uploads.Sha(photo))).Where(f => f.SequenceId == sequenceId)];
private sealed record Scene(HttpClient Editor, byte[] Photo, CompleteUploadResponse Held, Guid Target);
/// <summary>The fake ingest, with a step that runs once just before the next commit (another writer filing the same photo).</summary>
private sealed class RacingIngest(FakeArchiveIngest inner) : IArchiveIngest
{
public FakeArchiveIngest Inner => inner;
public Func<IngestRequest, Task>? Before { get; set; }
public async Task<IngestResult> CommitAsync(IngestRequest request, CancellationToken cancellationToken = default)
{
if (Before is { } before)
{
Before = null;
await before(request);
}
return await inner.CommitAsync(request, cancellationToken);
}
}
}
@@ -0,0 +1,393 @@
using System.Security.Cryptography;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Imaging;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Copies;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Repositories;
using Chronos.Data.Sync;
using Chronos.Protocol.Client;
using Chronos.Server.Storage;
using Chronos.Testing;
namespace Chronos.Server.Tests.Sync;
/// <summary>
/// The owner's scenario of review 6 (#73) end to end, against a real in-process server: a time-lapse uploaded from this PC,
/// an old copy of it found again on a disk adopted as an archive, compared, kept apart, integrated (Union) both ways with
/// the details settled line by line and the projects copied across, its new photos moving by themselves unless the
/// connection is metered, Upload all local leaving a suspected copy out, and two copies on this PC merged into one.
/// </summary>
[Category("server")]
[Timeout(300_000)]
public sealed class CopyScenarioTests(TestContext context)
{
private const string PcName = "STUDIO";
private const string ServerName = "Test server";
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0);
private static readonly TimeSpan Deadline = TimeSpan.FromSeconds(60);
private CancellationToken Ct => context.Cancellation;
[Test]
public async Task AnOldCopyFoundOnAnAdoptedDiskIsIntegratedWithTheServerAndMergedOnThisPc()
{
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = 64 * 1024, ArchiveModule.Register);
var (_, _, token) = await server.UserAsync("alberto", "editor");
await using var pc = await Pc.StartAsync(context, server, token);
// 1. A time-lapse of eight photos, rated 4, uploaded from this PC.
// Photo 3 carries the camera's sub-second time: two versions of it at that instant under one name are one photo that differs.
static DateTime Captured(int i) => Start.AddSeconds(10 * i).AddMilliseconds(i == 3 ? 250 : 0);
var photos = Enumerable.Range(1, 8).Select(i => Jpeg(Captured(i), i)).ToList();
var original = await pc.LocalAsync(pc.Main, "Comet over the ridge", photos.Select((p, i) => (p, Captured(i + 1))).ToList());
original = (await pc.Db.Sequences.EditAsync(original.Id, new SequenceEdit { Rating = 4 }, null, Ct)).Sequence!;
await pc.WaitAsync((await pc.Sync.EnqueueUploadAsync(pc.Jobs, pc.Server, original, Ct)).Id);
var remoteId = (await pc.Sync.LinkOfAsync(pc.Server, original.Id, Ct))!.RemoteId;
var onServer = Assert.NotNull(await server.Database.Sequences.GetAsync(remoteId));
Assert.True((await server.Database.Frames.ListBySequenceAsync(remoteId)).Select(f => f.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
await ServerIdleAsync(server);
// Freed on this PC since: the server holds it.
await pc.Archives.DeleteAsync(await pc.Archives.PlanDeleteAsync([original.Id], cancellationToken: Ct), "alberto", cancellationToken: Ct);
await pc.Sync.RefreshAsync(pc.Remote, Policy, Ct);
Assert.Null(await pc.Sync.LinkOfAsync(pc.Server, original.Id, Ct));
// 2. An old disk adopted as an archive: photos 1-6 (photo 3 in another version), two more of its own, another title and rating.
var manifest = await pc.Remote.GetManifestAsync(remoteId, Ct);
var names = manifest.Frames.OrderBy(f => f.Index).Select(f => f.FileName).ToList();
var diskRoot = context.CreateTempDirectory("old-disk");
var folder = Path.Combine(diskRoot, "2026-09-28 comet");
Directory.CreateDirectory(folder);
var differing = Jpeg(Captured(3), 103);
var extras = new[] { Jpeg(Start.AddSeconds(5), 201), Jpeg(Start.AddSeconds(75), 202) };
for (var i = 0; i < 6; i++) await File.WriteAllBytesAsync(Path.Combine(folder, names[i]), i == 2 ? differing : photos[i], Ct);
await File.WriteAllBytesAsync(Path.Combine(folder, "IMG_9001.JPG"), extras[0], Ct);
await File.WriteAllBytesAsync(Path.Combine(folder, "IMG_9002.JPG"), extras[1], Ct);
var disk = await pc.Archives.AdoptAsync(diskRoot, "Old disk", Ct);
await pc.Archives.Indexer.ScanAsync(disk, ScanMode.Full, null, _ => ValueTask.CompletedTask, Ct);
var old = Assert.NotNull((await pc.Db.Sequences.ListAsync(new SequenceQuery { ArchiveId = disk.Id }, Ct)).Items.SingleOrDefault());
old = (await pc.Db.Sequences.EditAsync(old.Id, new SequenceEdit { Title = "Old disk comet", Rating = 2 }, null, Ct)).Sequence!;
Assert.Equal(8, old.FrameCount);
// 3. Detection with Ask always (a refresh in the background): the match is listed, told, and not linked.
var told = new List<CopyFindResult>();
pc.Copies.Found += told.Add;
await pc.Sync.RefreshAsync(pc.Remote, Policy, Ct);
var pair = Assert.Contains(await pc.Copies.ListAsync(Ct), v => v.Copy.LocalId == old.Id).Copy;
Assert.Equal((CopyKind.LocalServer, CopyState.Candidate, (Guid?)remoteId), (pair.Kind, pair.State, pair.RemoteId));
Assert.Contains(told.SelectMany(r => r.New), c => c.Id == pair.Id);
Assert.Empty(told.SelectMany(r => r.AutoLinked));
Assert.Null(await pc.Sync.LinkOfAsync(pc.Server, old.Id, Ct));
// 4. Verified (an adopted folder holds no hashes until then), the comparison shows each class of photo.
await pc.Archives.Verifier.VerifyAsync(disk, [old.Id], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: Ct);
var review = await pc.Copies.CompareAsync(pair.Id, pc.Remote, Ct);
int Count(PhotoClass c) => review.Photos.Photos.Count(p => p.Class == c);
Assert.Equal((5, 2, 2, 1), (Count(PhotoClass.Same), Count(PhotoClass.OnlyHere), Count(PhotoClass.OnlyThere), Count(PhotoClass.Differs)));
Assert.True(review.Photos.Photos.Where(p => p.Class == PhotoClass.OnlyThere).Select(p => p.There!.Sha256).ToHashSet().SetEquals([Sha(photos[6]), Sha(photos[7])]));
Assert.True(review.Photos.Photos.Where(p => p.Class == PhotoClass.OnlyHere).Select(p => p.Here!.Sha256).ToHashSet().SetEquals(extras.Select(Sha)));
var differs = review.Photos.Photos.Single(p => p.Class == PhotoClass.Differs);
Assert.Equal((Sha(differing), Sha(photos[2])), (differs.Here!.Sha256, differs.There!.Sha256));
Assert.Contains(review.Details, d => d.Path == "sequence.title" && d.Here == "Old disk comet" && d.There == onServer.Title);
Assert.Contains(review.Details, d => d.Path == "sequence.rating" && d.Here == "2" && d.There == onServer.Rating.ToString(System.Globalization.CultureInfo.InvariantCulture));
// 5. Keep apart is remembered across refreshes; Ask again brings it back.
await pc.Copies.KeepApartAsync(pair.Id, Ct);
for (var i = 0; i < 2; i++)
{
await pc.Sync.Finder.ResetProbesAsync(pc.Server, Ct);
await pc.Sync.RefreshAsync(pc.Remote, Policy, Ct);
}
Assert.Equal(CopyState.KeptApart, (await pc.Sync.Copies.GetAsync(pair.Id, Ct))!.State);
Assert.Null(await pc.Sync.LinkOfAsync(pc.Server, old.Id, Ct));
await pc.Copies.AskAgainAsync(pair.Id, Ct);
// 6. A project other than Main on each side, under one name, each edited its own way.
await ProjectAsync(new ArchiveProjectHome(pc.Db, pc.Archives.Projects, old.Id), "Vertical", 41);
await ProjectAsync(pc.ServerHome(remoteId), "Vertical", 33);
// 7. Integrate with Union: the server's title, this PC's rating, the rest the server's; the projects copied across.
review = await pc.Copies.CompareAsync(pair.Id, pc.Remote, Ct);
var details = review.Details.Select(d => d.Path).Distinct()
.ToDictionary(p => p, p => p == "sequence.rating" ? CopySide.ThisPc : CopySide.Other);
var plan = await pc.Copies.PlanIntegrateAsync(pair.Id, pc.Remote,
new IntegrateChoices(CopyPhotoPolicy.Union, new Dictionary<string, PhotoChoice>(), details, CopyProjects.CopyAcross), Ct);
Assert.True(plan.CanApply, string.Join(", ", plan.Blocks));
Assert.Equal((0, true, false), (plan.LeftOut, plan.AutoPhotos, plan.Destructive));
Assert.SequenceEqual(["Other:Vertical (Test server)", "ThisPc:Vertical (STUDIO)"],
plan.Projects.Select(p => $"{p.From}:{p.TargetName}").Order(StringComparer.Ordinal));
await pc.WaitAsync((await pc.Copies.EnqueueIntegrateAsync(pc.Jobs, plan, Ct)).Id);
var union = photos.Select(Sha).Concat(extras.Select(Sha)).Append(Sha(differing)).ToHashSet(StringComparer.Ordinal);
Assert.True((await LocalHashesAsync(pc, old.Id)).SetEquals(union), "this PC holds every photo of both, both versions of photo 3");
Assert.True((await server.Database.Frames.ListBySequenceAsync(remoteId)).Select(f => f.Sha256!).ToHashSet().SetEquals(union), "and so does the server");
var here = (await pc.Db.Sequences.GetAsync(old.Id, Ct))!;
var there = (await server.Database.Sequences.GetAsync(remoteId))!;
Assert.Equal((onServer.Title, 2), (here.Title, here.Rating));
Assert.Equal((onServer.Title, 2), (there.Title, there.Rating));
static List<string> Names(IEnumerable<SequenceProject> list) => [.. list.Where(p => !p.IsMain).Select(p => p.Name).Order(StringComparer.Ordinal)];
Assert.SequenceEqual(["Vertical", "Vertical (Test server)"], Names(await pc.Archives.Projects.ListAsync(old.Id, Ct)));
Assert.SequenceEqual(["Vertical", "Vertical (STUDIO)"], Names(await pc.ServerHome(remoteId).ListAsync(Ct)));
var integrated = (await pc.Sync.Copies.GetAsync(pair.Id, Ct))!;
Assert.Equal((CopyState.Integrated, true), (integrated.State, integrated.AutoPhotos));
Assert.Equal(remoteId, (await pc.Sync.LinkOfAsync(pc.Server, old.Id, Ct))?.RemoteId);
await ServerIdleAsync(server);
// 8. A new photo on this PC moves to the server by itself, but not while the connection is metered.
var later = Jpeg(Start.AddSeconds(200), 301);
await pc.AddPhotoAsync(disk, old.Id, later, Start.AddSeconds(200));
var held = await pc.StopJobsAsync();
await using (var agent = new SyncAgent(pc.Sync, pc.Remote, () => Policy, held, new SyncAgentOptions
{
RefreshInterval = TimeSpan.FromHours(1),
EventDelay = TimeSpan.FromMilliseconds(20),
MinBackoff = TimeSpan.FromMilliseconds(20),
MaxBackoff = TimeSpan.FromMilliseconds(200),
}))
{
await agent.RefreshAsync(Ct);
var automatic = (await pc.Db.Jobs.ListAsync(JobState.Queued, JobKind.UploadCommit, 10, cancellationToken: Ct)).Items.Single();
Assert.Equal((old.Id, JobPriority.Background), (automatic.TargetIds.Single(), automatic.Priority));
// Metered: the hold pauses the transfers with the server (UploadHold, the desktop's, does this on Windows).
await held.PauseAsync(automatic.Id, Ct);
await held.StartAsync(Ct);
await Task.Delay(TimeSpan.FromSeconds(1), Ct);
Assert.Equal(JobState.Paused, (await pc.Db.Jobs.GetAsync(automatic.Id, Ct))!.State);
Assert.DoesNotContain(Sha(later), (await server.Database.Frames.ListBySequenceAsync(remoteId)).Select(f => f.Sha256));
// No longer metered: it goes on.
await held.ResumeAsync(automatic.Id, Ct);
await pc.WaitAsync(automatic.Id);
Assert.Contains(Sha(later), (await server.Database.Frames.ListBySequenceAsync(remoteId)).Select(f => f.Sha256));
}
// 9. Upload all local: a copy filed again from the card is a suspected duplicate, skipped and flagged; the rest goes.
var card = await pc.LocalAsync(pc.Main, "Comet from the card", [(photos[0], Start.AddSeconds(10)), (photos[1], Start.AddSeconds(20)),
(Jpeg(Start.AddSeconds(210), 401), Start.AddSeconds(210))]);
var other = await pc.LocalAsync(pc.Main, "Harbour", [(Jpeg(Start.AddDays(1), 501), Start.AddDays(1)), (Jpeg(Start.AddDays(1).AddSeconds(10), 502), Start.AddDays(1).AddSeconds(10))]);
await pc.Copies.FindAsync(pc.Remote, Ct);
var local = Assert.Contains(await pc.Copies.ListAsync(Ct), v => v.Copy.Kind == CopyKind.LocalLocal).Copy;
Assert.True(new[] { local.LocalId, local.OtherId!.Value }.ToHashSet().SetEquals([old.Id, card.Id]));
Assert.Equal(CopyState.Candidate, local.State);
var entries = (await pc.Sync.ListAsync(pc.Server, Ct)).Where(e => e.Status == SyncStatus.LocalOnly);
var (upload, skipped) = UploadAllRule.Select(entries, await pc.Copies.ListAllPairsAsync(Ct), new HashSet<Guid>(), new HashSet<Guid>());
Assert.Equal((card.Id, UploadSkip.SuspectedCopy), (skipped.Single().Entry.Local!.Id, skipped.Single().Why));
Assert.Equal(other.Id, upload.Single().Local!.Id);
await pc.WaitAsync((await pc.Sync.EnqueueUploadAsync(held, pc.Server, upload.Single().Local!, Ct)).Id);
Assert.NotNull(await pc.Sync.LinkOfAsync(pc.Server, other.Id, Ct));
Assert.Null(await pc.Sync.LinkOfAsync(pc.Server, card.Id, Ct));
// 10. The two copies on this PC merge into the linked one; the other goes to the archive trash once every photo is verified there.
review = await pc.Copies.CompareAsync(local.Id, null, Ct);
var merge = await pc.Copies.PlanMergeAsync(local.Id, old.Id,
new MergeChoices(CopyPhotoPolicy.Union, new Dictionary<string, PhotoChoice>(), review.Details.Select(d => d.Path).Distinct().ToDictionary(p => p, _ => CopySide.ThisPc)), Ct);
Assert.True(merge.CanApply, string.Join(", ", merge.Blocks));
Assert.Equal((old.Id, card.Id), (merge.KeepId, merge.DropId));
await pc.WaitAsync((await pc.Copies.EnqueueMergeAsync(held, merge, Ct)).Id);
Assert.Null(await pc.Db.Sequences.GetAsync(card.Id, Ct));
var kept = await pc.Db.Frames.ListBySequenceAsync(old.Id, cancellationToken: Ct);
Assert.Contains(Sha(Jpeg(Start.AddSeconds(210), 401)), kept.Select(f => f.Sha256));
foreach (var frame in kept) Assert.Equal(frame.Sha256, Sha(await File.ReadAllBytesAsync(Path.Combine(disk.RootPath, frame.RelativePath), Ct)));
Assert.Contains(await pc.Archives.ListTrashAsync(pc.Main.Id, Ct), t => t.SequenceId == card.Id);
Assert.Equal(remoteId, (await pc.Sync.LinkOfAsync(pc.Server, old.Id, Ct))?.RemoteId);
}
private static readonly SyncPolicy Policy = new(Linking: CopyLinking.AskAlways);
private static string Sha(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
/// <summary>A project named <paramref name="name"/> at <paramref name="home"/> with one version of its own (a deflicker window).</summary>
private async Task ProjectAsync(IProjectHome home, string name, int window)
{
var project = await home.CreateAsync(name, null, "alberto", Ct);
var head = await home.HeadAsync(project.Id, Ct);
var portable = ProjectContent.ToPortable(ProjectSettings.FromJson("""{"exposure":{"deflickerWindow":{"isAuto":false,"manual":""" + window + "}}}"), new FramePhotos([]));
var pushed = await home.PushAsync(project.Id, new ProjectVersion
{
Id = Guid.CreateVersion7(),
ProjectId = project.Id,
ParentId = head.Id,
Number = head.Number + 1,
Kind = ProjectVersionKind.Commit,
Author = "alberto",
ClientName = PcName,
SettingsJson = portable,
ContentHash = ProjectContent.Hash(portable),
FramesVersion = head.FramesVersion,
CreatedAt = DateTimeOffset.UtcNow,
}, Ct);
Assert.NotNull(pushed.Version);
}
/// <summary>A small real JPEG with Exif (camera and capture time); each seed gives distinct bytes.</summary>
private static byte[] Jpeg(DateTime captured, int seed)
{
using var image = new ImageBuffer(48, 32);
var random = new Random(seed);
for (var c = 0; c < 3; c++)
{
var plane = image.Plane(c);
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 = "Canon", Model = "Canon EOS R5", BodySerial = "0431", CapturedAt = captured, Iso = 100 });
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [exif[4..]] });
}
private static async Task<HashSet<string>> LocalHashesAsync(Pc pc, Guid id) =>
(await pc.Db.Frames.ListBySequenceAsync(id, cancellationToken: pc.Ct)).Select(f => f.Sha256!).ToHashSet(StringComparer.Ordinal);
private Task ServerIdleAsync(TestServer server) =>
UntilAsync(async () => await server.Database.Jobs.CountAsync(DateTimeOffset.UtcNow) is { Queued: 0, Running: 0 }, "the server's jobs");
private async Task UntilAsync(Func<Task<bool>> condition, string what)
{
var until = DateTime.UtcNow + Deadline;
while (!await condition())
{
if (DateTime.UtcNow > until) Assert.Fail("Timed out waiting for " + what);
await Task.Delay(50, Ct);
}
}
/// <summary>
/// This PC as the desktop composes it (AppServices): its index and archive, the sync engine, the matches engine with its
/// planners and the server's project homes, and a job engine with the archive, sync, Integrate and Merge handlers.
/// </summary>
private sealed class Pc : IAsyncDisposable
{
private readonly TestContext _context;
private readonly ChronosClient _client;
private readonly Connector _connector;
private Pc(TestContext context, ChronosDatabase db, ArchiveService archives, Archive main, SyncService sync, ChronosClient client)
{
_context = context;
Db = db;
Archives = archives;
Main = main;
Sync = sync;
_client = client;
Remote = new ChronosSyncRemote(client, ownsClient: false);
_connector = new Connector(client);
var sides = new CopySides(db);
var homes = CopyJobs.ServerHomes(_connector);
Copies = new CopyEngine(sync, archives, new IntegratePlanner(sync, sides, archives.Projects, homes), new SequenceMerger(db, archives, sides),
new CopyReviewBuilder(db, archives.Projects, sides, homes), remote => new CopyPlanContext(PcName, remote is null ? null : ServerName,
true, true, true, false, false, remote is not null, null, new HashSet<Guid>(), new HashSet<Guid>()),
serverNames: _ => ServerName);
Jobs = NewJobs();
}
public ChronosDatabase Db { get; }
public ArchiveService Archives { get; }
public Archive Main { get; }
public SyncService Sync { get; }
public ChronosSyncRemote Remote { get; }
public CopyEngine Copies { get; }
public JobEngine Jobs { get; private set; }
public string Server => Remote.Server;
public CancellationToken Ct => _context.Cancellation;
public static async Task<Pc> StartAsync(TestContext context, TestServer server, string token)
{
var ct = context.Cancellation;
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("studio-db"), "chronos.db")), ct);
var options = new ArchiveServiceOptions { Owner = PcName, LeaseWait = TimeSpan.FromSeconds(20) };
var archives = new ArchiveService(db, options);
var main = await archives.CreateAsync(context.CreateTempDirectory("studio-archive"), "Main", cancellationToken: ct);
var sync = new SyncService(db, archives, new SyncOptions { Archive = options, ProxyCacheDirectory = context.CreateTempDirectory("studio-proxies") });
var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), PcName) { Token = token };
var pc = new Pc(context, db, archives, main, sync, client);
await pc.Jobs.StartAsync(ct);
return pc;
}
/// <summary>A job engine over this index with every handler the desktop registers for these jobs (not started).</summary>
public JobEngine NewJobs() => new(Db,
[
.. Archives.CreateJobHandlers(), .. Sync.CreateJobHandlers(_connector),
CopyJobs.CreateIntegrateHandler(Sync, Archives, _connector, Sync.Copies),
SequenceMerger.CreateHandler(Db, new SequenceMerger(Db, Archives, new CopySides(Db)), Archives, new ProjectTransplant(), new NoWorkspace()),
],
new JobEngineOptions { Workers = 2, WorkerId = PcName, PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
/// <summary>Stops the engine that runs jobs as they come and puts one not started in its place: the next jobs wait for it.</summary>
public async Task<JobEngine> StopJobsAsync()
{
await Jobs.DisposeAsync();
return Jobs = NewJobs();
}
public IProjectHome ServerHome(Guid remoteId) => new ServerProjectHome(_client, remoteId, ServerName, null, Server);
/// <summary>A local sequence filed photo by photo through the archive ingest.</summary>
public async Task<Sequence> LocalAsync(Archive archive, string title, IReadOnlyList<(byte[] Bytes, DateTime Captured)> photos)
{
Guid? id = null;
for (var i = 0; i < photos.Count; i++)
{
var result = await IngestAsync(archive, id, id is null ? title : null, photos[i].Bytes, $"IMG_{photos[i].Captured:HHmmss}.JPG", photos[i].Captured);
id = result.SequenceId;
}
return (await Db.Sequences.GetAsync(id!.Value, Ct))!;
}
public Task<IngestResult> AddPhotoAsync(Archive archive, Guid sequenceId, byte[] photo, DateTime captured) =>
IngestAsync(archive, sequenceId, null, photo, $"IMG_{captured:HHmmss}.JPG", captured);
private async Task<IngestResult> IngestAsync(Archive archive, Guid? sequenceId, string? title, byte[] photo, string name, DateTime captured)
{
var staging = Path.Combine(archive.RootPath, ".chronos", "staging", "test");
Directory.CreateDirectory(staging);
var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part");
await File.WriteAllBytesAsync(path, photo, Ct);
return await Archives.Ingest.CommitAsync(new IngestRequest(archive.Id, sequenceId, title, null, path, name, photo.Length, Sha(photo), captured, null), Ct);
}
public async Task<Job> WaitAsync(Guid jobId)
{
var until = DateTime.UtcNow.AddSeconds(TestTiming.Budget(60));
while (true)
{
var job = await Db.Jobs.GetAsync(jobId, Ct);
if (job?.State == JobState.Done) return job;
if (job?.State is JobState.Failed or JobState.Cancelled) Assert.Fail($"Job {job.Kind} {job.State}: {job.Error}\n{job.LogTail}");
if (DateTime.UtcNow > until) Assert.Fail($"Job {jobId} did not finish (now {job?.State})");
await Task.Delay(25, Ct);
}
}
public async ValueTask DisposeAsync()
{
await Jobs.DisposeAsync();
Copies.Dispose();
Remote.Dispose();
_client.Dispose();
await Db.DisposeAsync();
}
/// <summary>No workspace here: no sequence has workspace work not sent home.</summary>
private sealed class NoWorkspace : IWorkspaceGuard
{
public Task<bool> HasUnsentAsync(Guid sequenceId, CancellationToken ct) => Task.FromResult(false);
}
/// <summary>The signed-in session: a remote per job and the server's project homes (Settings › Server's server keeps projects).</summary>
private sealed class Connector(ChronosClient client) : ISyncConnector
{
public ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken)
{
ISyncRemote remote = new ChronosSyncRemote(client, ownsClient: false);
return ValueTask.FromResult<ISyncRemote?>(remote.Server == server ? remote : null);
}
public IProjectHome? ProjectHome(BundleHome home) =>
home.IsArchive ? null : new ServerProjectHome(client, home.SequenceId, ServerName, null, home.Server);
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 KiB

After

Width:  |  Height:  |  Size: 67 KiB

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