feat: owner review 2 phase 4a: Reorganize sequences after import (#12)
CI / Build and test (push) Successful in 9m15s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 15m35s
CI / PostgreSQL 16 integration (push) Successful in 7m26s
CI / PostgreSQL 17 integration (push) Successful in 6m47s
CI / Docker image (push) Successful in 59s
Release / Server image (push) Successful in 1m24s

- Reorganize… on the web panel and the desktop: folder, file and title templates applied to existing sequences, with a dry run and an explicit Apply that runs as a job.
- One naming rule (FrameNaming) for import, upload and Reorganize.
- Crash-safe plan and file journals, held plans, stale-plan refusal; exports move with their folder.
- Writers refuse a folder another program moved or gave to another sequence.
- Server: POST /api/v1/archive/reorganize with a bounded plan cache; template rules.
- Phase 3 docs and translations merged; strings in all 38 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #12.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-27 21:58:39 +01:00
1 parent 9aa818ed47
commit 7e4a3b481d
416 files changed
+15304 -1572

No files matched your search

+82 -14
View File
@@ -177,12 +177,16 @@ public sealed class SyncService
/// <summary>
/// Settles a conflict as the user chose (BRIEF §12.7), against the versions the user was shown: when either side
/// changed again since, nothing is written, the sequence is compared again and <see cref="SyncConflictChangedException"/>
/// is thrown. Returns the file this PC's settings were saved to for <see cref="SyncResolution.SaveBoth"/>, else null.
/// is thrown, as it is when <see cref="SyncResolution.SaveBoth"/> cannot keep this PC's version first or the server's
/// version cannot be written because the folder is not where the index has it (another index moved it; its message then
/// says to try again after the next scan). Returns the file this PC's settings were saved to for
/// <see cref="SyncResolution.SaveBoth"/>, else null.
/// </summary>
public async Task<string?> ResolveAsync(ISyncRemote remote, Guid remoteId, SyncResolution resolution, CancellationToken cancellationToken)
{
string? saved = null;
var changed = false;
var moved = false;
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
@@ -222,9 +226,15 @@ public sealed class SyncService
{
changed = true;
}
else if (resolution == SyncResolution.SaveBoth && (saved = await SaveCopyAsync(local, cancellationToken).ConfigureAwait(false)) is null)
{
// This PC's version could not be kept (another index moved the folder): the server's does not replace it,
// even where this index's scan finds the folder before the server's version would be written.
changed = true;
moved = true;
}
else
{
if (resolution == SyncResolution.SaveBoth) saved = await SaveCopyAsync(local, cancellationToken).ConfigureAwait(false);
var theirs = SyncPayload.Of(dto, manifest!.SettingsJson);
if (await ApplyLocallyAsync(local, theirs, Positions(remote, local, manifest), cancellationToken).ConfigureAwait(false) is { } applied)
{
@@ -232,9 +242,11 @@ public sealed class SyncService
}
else
{
// Edited on this PC since it was read: the copy of a version the user did not choose to keep goes.
// Edited on this PC since it was read, or the folder moved by another index: the copy of a version the
// user did not choose to keep goes.
changed = true;
if (saved is not null) File.Delete(saved);
moved = await FolderMovedAsync(local, cancellationToken).ConfigureAwait(false);
if (saved is not null) await DeleteCopyAsync(local, saved, cancellationToken).ConfigureAwait(false);
saved = null;
}
}
@@ -252,7 +264,8 @@ public sealed class SyncService
if (changed)
{
await RefreshSequencesAsync(remote, [remoteId], CompareOnly, cancellationToken).ConfigureAwait(false);
throw new SyncConflictChangedException(Loc.L("Errors.Sync.ChangedAgain"));
// Choosing again changes nothing while the folder is not where the index has it: the next scan finds it.
throw new SyncConflictChangedException(Loc.L(moved ? "Errors.Archive.FolderMoved" : "Errors.Sync.ChangedAgain"));
}
await StoreStatesAsync(remote.Server, null, cancellationToken).ConfigureAwait(false);
Changed?.Invoke(remote.Server);
@@ -721,8 +734,9 @@ public sealed class SyncService
/// sequence's lease, which the editor's saves and the archive's frame commits take too, and only while the local copy
/// is still at the settings version <paramref name="local"/> was read at. The settings' frame positions are moved to
/// this copy's frames as they are under the lease (<paramref name="positions"/>). Null when an edit was saved on this
/// PC since, or the frames of either copy could not be read as one state: nothing is written then. A payload the local
/// copy already holds writes nothing, so it needs neither a writable archive nor the lease.
/// PC since, the frames of either copy could not be read as one state, or the copy is not in the folder this index has
/// (another index moved it): nothing is written then. A payload the local copy already holds writes nothing, so it
/// needs neither a writable archive nor the lease.
/// </summary>
private async Task<Sequence?> ApplyLocallyAsync(Sequence local, SyncPayload payload, SyncPositions positions, CancellationToken cancellationToken)
{
@@ -734,12 +748,16 @@ public sealed class SyncService
?? throw new InvalidDataException($"Archive {local.ArchiveId} is not indexed.");
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var folder = paths.Sequence(local.Folder);
await using (await _writer.LockAsync(paths, local.Id, cancellationToken).ConfigureAwait(false))
{
// The frames cannot change under the lease: the positions are moved to them as they are now.
if (await positions.ToLocalAsync(payload.SettingsJson, local.SettingsVersion, cancellationToken).ConfigureAwait(false) is not { } current) return null;
var row = current.Local;
// The folder too: a Reorganize moves it and its row under this lease. One another index moved is found by the next
// scan; nothing is written until then, so the folder it left is not created again, nor written in when it holds
// another sequence now.
var folder = paths.Sequence(row.Folder);
if (!SequenceFolders.Holds(folder, row.Id)) return null;
payload = payload with { SettingsJson = current.SettingsJson };
var metadata = !payload.SameMetadata(SyncPayload.Of(row));
var settings = !SyncRules.SameSettings(payload.SettingsJson, row.SettingsJson);
@@ -789,20 +807,70 @@ public sealed class SyncService
/// <summary>
/// "Save both": this PC's project is kept next to <c>project.json</c> as <c>project.this-pc-&lt;local time&gt;.json</c>
/// before the server's replaces it; returns that file.
/// before the server's replaces it; returns that file. Written under the sequence's lease into its folder as the index
/// has it then: a Reorganize may have moved it while the server was asked, and the folder it left is never created again.
/// Null, with nothing written, when the sequence is not in that folder (another index moved it, and maybe another
/// sequence into it; the next scan finds them, <see cref="SequenceFolders.Holds"/>).
/// </summary>
private async Task<string> SaveCopyAsync(Sequence local, CancellationToken cancellationToken)
private async Task<string?> SaveCopyAsync(Sequence local, CancellationToken cancellationToken)
{
var archive = await _db.Archives.GetAsync(local.ArchiveId, cancellationToken).ConfigureAwait(false)
?? throw new InvalidDataException($"Archive {local.ArchiveId} is not indexed.");
var folder = new ArchivePaths(archive.RootPath).Sequence(local.Folder);
Directory.CreateDirectory(folder.MetaDirectory);
var path = Path.Combine(folder.MetaDirectory, SavedCopyName(DateTime.Now));
AtomicFile.WriteAllText(path, SyncRules.NormalizeSettings(local.SettingsJson));
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
string path;
await using (await _writer.LockAsync(paths, local.Id, cancellationToken).ConfigureAwait(false))
{
var folder = await SequenceWriter.FolderAsync(_db, paths, local, cancellationToken).ConfigureAwait(false);
if (!SequenceFolders.Holds(folder, local.Id)) return null;
Directory.CreateDirectory(folder.MetaDirectory);
path = Path.Combine(folder.MetaDirectory, SavedCopyName(DateTime.Now));
AtomicFile.WriteAllText(path, SyncRules.NormalizeSettings(local.SettingsJson));
}
Log.Info(LogCategory, $"Settings of {local.DisplayTitle} kept as {path}");
return path;
}
/// <summary>
/// Whether the sequence is not in the folder the index has for it now, on an archive that is there: another index moved
/// it (and maybe another sequence into that folder), and this index's next scan finds it. Read without the lease, to
/// tell why a resolution wrote nothing.
/// </summary>
private async Task<bool> FolderMovedAsync(Sequence local, CancellationToken cancellationToken)
{
if (await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false) is not { } row
|| await _db.Archives.GetAsync(row.ArchiveId, cancellationToken).ConfigureAwait(false) is not { } archive)
return false;
var paths = new ArchivePaths(archive.RootPath);
return Directory.Exists(paths.Root) && !SequenceFolders.Holds(paths.Sequence(row.Folder), row.Id);
}
/// <summary>
/// Deletes a "Save both" copy of a version the user did not keep from the sequence's folder as the index has it now: a
/// Reorganize may have moved the folder, the copy with it, since the copy was written. Best effort: a copy that cannot
/// be reached (the folder gone or another sequence's now, the sequence busy, the archive offline) stays, as one more
/// copy of this PC's version.
/// </summary>
private async Task DeleteCopyAsync(Sequence local, string saved, CancellationToken cancellationToken)
{
try
{
var archive = await _db.Archives.GetAsync(local.ArchiveId, cancellationToken).ConfigureAwait(false)
?? throw new InvalidDataException($"Archive {local.ArchiveId} is not indexed.");
var paths = new ArchivePaths(archive.RootPath);
await using (await _writer.LockAsync(paths, local.Id, cancellationToken).ConfigureAwait(false))
{
var folder = await SequenceWriter.FolderAsync(_db, paths, local, cancellationToken).ConfigureAwait(false);
if (SequenceFolders.Holds(folder, local.Id) && Directory.Exists(folder.MetaDirectory))
File.Delete(Path.Combine(folder.MetaDirectory, Path.GetFileName(saved)));
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
{
Log.Warning(LogCategory, $"The copy {saved} of {local.DisplayTitle}'s settings could not be deleted", ex);
}
}
/// <summary>The file name of a "Save both" copy kept at <paramref name="localTime"/>.</summary>
public static string SavedCopyName(DateTime localTime) =>
string.Create(CultureInfo.InvariantCulture, $"{SavedCopyPrefix}{localTime.ToString(SavedCopyTimeFormat, CultureInfo.InvariantCulture)}.json");
+77 -31
View File
@@ -25,7 +25,8 @@ namespace Chronos.Data.Sync;
/// original the server has not hashed yet, its size, and hash it here) and commit them through the archive ingest,
/// which names them and writes the sidecar; the first original creates the local
/// sequence, which then takes the server's settings. Frames of the local copy not hashed yet are hashed first (so the
/// server's copies of them are recognised), and originals flagged missing here are restored to their recorded place.
/// server's copies of them are recognised), and originals flagged missing here are restored to their recorded place in
/// the folder the sequence is in (never one it left).
/// Proxy downloads fill the proxy cache. Renders travel on request: this PC's to the server (hash-verified chunked
/// upload) and the server's into the local copy's exports. A resumed job skips what is already on the other side, so
/// pausing or a crash loses at most the files in flight.
@@ -244,14 +245,14 @@ internal sealed class SyncTransfers(SyncService sync)
await progress.StepAsync().ConfigureAwait(false);
}
var sequenceId = local?.Id;
int restored = 0, refused = 0;
var refused = 0;
var restores = new ConcurrentBag<(string Staged, Guid FrameId)>();
await Parallel.ForEachAsync(rest, Workers(sync.Options.Downloads, ct), async (frame, token) =>
{
var (staged, sha) = await FetchOriginalAsync(remote, frame, staging, token).ConfigureAwait(false);
if (restore.TryGetValue(sha, out var place))
if (restore.TryGetValue(sha, out var frameId))
{
Restore(staged, place);
Interlocked.Increment(ref restored);
restores.Add((staged, frameId));
}
else if (frame.Sha256.Length == 0 && (tombstones.DeletedLocally(sha) || have.Contains(tombstones.Canonical(sha)!)))
{
@@ -267,26 +268,30 @@ internal sealed class SyncTransfers(SyncService sync)
}
await progress.StepAsync().ConfigureAwait(false);
}).ConfigureAwait(false);
TryDeleteDirectory(staging);
// Null when the sequence is not in the folder the index has: the copies stay staged for the next attempt.
var restored = restores.IsEmpty ? 0 : await RestoreAsync(local!, paths, restores, ct).ConfigureAwait(false);
if (restored is not null) TryDeleteDirectory(staging);
// Restored originals are checked against their records, which clears their missing flag.
if (restored > 0) await VerifyAsync(archive, local!.Id, ct).ConfigureAwait(false);
if (created) await sync.TakeAllAsync(remote, remoteId, ct).ConfigureAwait(false);
await sync.RecompareAsync(remote, remoteId, ct).ConfigureAwait(false);
if (sequenceId is { } downloaded && wanted.Count > restored + refused)
if (sequenceId is { } downloaded && wanted.Count > restores.Count + refused)
{
var label = local!.DisplayTitle;
await EnqueueFollowUpAsync(context, ArchiveJobs.Thumbnails([downloaded], label)).ConfigureAwait(false);
await EnqueueFollowUpAsync(context, ProcessingJobs.LightAnalysis([downloaded], label)).ConfigureAwait(false);
}
if (restored is null) throw new InvalidOperationException(Loc.L("Errors.Archive.FolderMoved"));
}
/// <summary>
/// The originals a local copy holds (lower-case SHA-256, and their photos for server frames not hashed yet) and where
/// each original flagged missing belongs. Frames not hashed yet (an adopted folder never verified) are hashed first
/// through the archive's verify, so the server's copies of them are recognised instead of committed again as duplicates.
/// The originals a local copy holds (lower-case SHA-256, and their photos for server frames not hashed yet) and the
/// frame each original flagged missing restores. Frames not hashed yet (an adopted folder never verified) are hashed
/// first through the archive's verify, so the server's copies of them are recognised instead of committed again as
/// duplicates.
/// </summary>
private async Task<(HashSet<string> Have, Dictionary<string, string> Restore, FramePhotos Photos)> LocalContentAsync(Archive archive, Sequence local,
private async Task<(HashSet<string> Have, Dictionary<string, Guid> Restore, FramePhotos Photos)> LocalContentAsync(Archive archive, Sequence local,
CancellationToken ct)
{
var frames = await SequenceFrames.ListAsync(sync.Database, local.Id, ct).ConfigureAwait(false);
@@ -297,12 +302,11 @@ internal sealed class SyncTransfers(SyncService sync)
}
var have = frames.Where(f => (f.Flags & FrameFlags.Missing) == 0 && f.Sha256 is not null).Select(f => f.Sha256!.ToLowerInvariant())
.ToHashSet(StringComparer.Ordinal);
var paths = new ArchivePaths(archive.RootPath);
var restore = new Dictionary<string, string>(StringComparer.Ordinal);
var restore = new Dictionary<string, Guid>(StringComparer.Ordinal);
foreach (var frame in frames.Where(f => (f.Flags & FrameFlags.Missing) != 0 && f.Sha256 is not null))
{
var sha = frame.Sha256!.ToLowerInvariant();
if (!have.Contains(sha)) restore.TryAdd(sha, paths.FromRelative(frame.RelativePath));
if (!have.Contains(sha)) restore.TryAdd(sha, frame.Id);
}
var photos = SyncRules.Photos([.. frames.Where(f => (f.Flags & FrameFlags.Missing) == 0)]);
return (have, restore, photos);
@@ -311,6 +315,35 @@ internal sealed class SyncTransfers(SyncService sync)
private Task VerifyAsync(Archive archive, Guid sequenceId, CancellationToken ct) =>
sync.Archives.Verifier.VerifyAsync(archive, [sequenceId], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: ct);
/// <summary>
/// Puts the verified copies of originals flagged missing (<paramref name="staged"/>, each with the frame it restores)
/// back where their records say, under the sequence's lease in its folder as the index has it then: a Reorganize moves
/// the folder and the frames' paths under that lease. Returns how many went back; a file that reappeared meanwhile is
/// kept, and the copy of a frame that left the index is dropped. Null, with nothing restored and every copy kept in
/// staging for the next attempt, when the sequence is not in that folder (another index moved it, and maybe another
/// sequence into it; this index's next scan finds them): the folder it left is not created again, nor given an
/// original of this sequence when it holds another one now.
/// </summary>
private Task<int?> RestoreAsync(Sequence local, ArchivePaths paths, IReadOnlyCollection<(string Staged, Guid FrameId)> staged, CancellationToken ct) =>
sync.Archives.UnderLeaseAsync(local, async row =>
{
if (row is null) throw new InvalidOperationException(Loc.L("Errors.Sync.LocalMissing"));
if (!SequenceFolders.Holds(paths.Sequence(row.Folder), row.Id)) return (int?)null;
var restored = 0;
foreach (var (copy, frameId) in staged)
{
// Read under the lease, as the folder: where the photo belongs in the folder the sequence is in now.
if (await sync.Database.Frames.GetAsync(frameId, ct).ConfigureAwait(false) is not { } frame || frame.SequenceId != row.Id)
{
File.Delete(copy);
continue;
}
Restore(copy, paths.FromRelative(frame.RelativePath));
restored++;
}
return restored;
}, ct);
/// <summary>Puts a verified copy of an original flagged missing back where its record says; a file that reappeared meanwhile is kept.</summary>
private static void Restore(string staged, string place)
{
@@ -370,31 +403,44 @@ internal sealed class SyncTransfers(SyncService sync)
EnsureSpace(paths.Root, wanted.Sum(r => r.Bytes));
var staging = Path.Combine(paths.StagingDirectory, "exports-" + remoteId.ToString("N"));
var exports = paths.Sequence(local.Folder).Exports;
Directory.CreateDirectory(staging);
Directory.CreateDirectory(exports);
var progress = new TransferProgress(context, wanted.Count, 0);
await progress.ReportAsync().ConfigureAwait(false);
foreach (var render in wanted)
{
var (part, name) = await FetchRenderAsync(remote, render, staging, ct).ConfigureAwait(false);
var target = Unique(exports, name);
File.Move(part, target);
await db.Renders.InsertAsync(new Render
// Filed under the sequence's lease into its folder as the index has it then, as a server files a render: a
// Reorganize may have moved it since the sequence was read, and moves the row's path along when it moves it later.
// One another index moved is found by this index's next scan; until then nothing is filed (the download stays
// staged for the next attempt), so the folder it left is not created again, nor filed into when it holds another
// sequence now.
var filed = await sync.Archives.UnderLeaseAsync(local, async row =>
{
Id = render.Id,
SequenceId = local.Id,
PresetName = render.PresetName,
OutputPath = paths.ToRelative(target),
Codec = render.Codec,
Width = render.Width,
Height = render.Height,
Fps = render.Fps,
DurationSeconds = render.DurationSeconds,
Bytes = new FileInfo(target).Length,
Created = render.Created,
ProducedBy = render.ProducedBy,
if (row is null) throw new InvalidOperationException(Loc.L("Errors.Sync.LocalMissing"));
var folder = paths.Sequence(row.Folder);
if (!SequenceFolders.Holds(folder, row.Id)) return false;
Directory.CreateDirectory(folder.Exports);
var target = Unique(folder.Exports, name);
File.Move(part, target);
// Recorded even if the job is being cancelled: a filed export is never left without its row.
await db.Renders.InsertAsync(new Render
{
Id = render.Id,
SequenceId = row.Id,
PresetName = render.PresetName,
OutputPath = paths.ToRelative(target),
Codec = render.Codec,
Width = render.Width,
Height = render.Height,
Fps = render.Fps,
DurationSeconds = render.DurationSeconds,
Bytes = new FileInfo(target).Length,
Created = render.Created,
ProducedBy = render.ProducedBy,
}, CancellationToken.None).ConfigureAwait(false);
return true;
}, ct).ConfigureAwait(false);
if (!filed) throw new InvalidOperationException(Loc.L("Errors.Archive.FolderMoved"));
await progress.StepAsync().ConfigureAwait(false);
}
TryDeleteDirectory(staging);