feat: owner review 2 phase 4b: mass conversion after import #13

Merged
Alby96 merged 82 commits from claude/owner-review-2-p4b-rc7 into main 2026-11-03 10:41:59 +01:00
6 changed files with 144 additions and 28 deletions
Showing only changes of commit e3cbe30b29 - Show all commits

No files matched your search

+3
View File
@@ -59,10 +59,13 @@
<data name="Archive.Convert.HeadingAll" xml:space="preserve"><value>Convert {0}</value><comment>long: dialog heading; {0} archive name</comment></data>
<data name="Archive.Convert.Mode" xml:space="preserve"><value>Mode</value></data>
<data name="Archive.Convert.NewSequence" xml:space="preserve"><value>New sequence</value></data>
<data name="Archive.Convert.NotCopied.ColorProfile" xml:space="preserve"><value>Photos whose colour profile this format can neither keep nor convert are not copied into the new sequence.</value><comment>long: why photos are not in the new sequence a conversion makes, in its dry run</comment></data>
<data name="Archive.Convert.NotCopied.EightBit" xml:space="preserve"><value>RAW photos this computer develops at 8 bits only are not copied into the new sequence; JPEG converts them.</value><comment>long: why photos are not in the new sequence a conversion makes, in its dry run</comment></data>
<data name="Archive.Convert.NotCopied.Missing" xml:space="preserve"><value>Missing photos are not copied into the new sequence.</value><comment>long: why photos are not in the new sequence a conversion makes, in its dry run</comment></data>
<data name="Archive.Convert.NotCopied.NoNativeDecoder" xml:space="preserve"><value>Photos of a format this computer cannot read at full resolution are not copied into the new sequence.</value><comment>long: why photos are not in the new sequence a conversion makes, in its dry run</comment></data>
<data name="Archive.Convert.NotCopied.PreviewOnly" xml:space="preserve"><value>Photos read only from their embedded preview here are not copied into the new sequence.</value><comment>long: why photos are not in the new sequence a conversion makes, in its dry run</comment></data>
<data name="Archive.Convert.NotCopied.SameFormat" xml:space="preserve"><value>Photos already in this format are not copied into the new sequence.</value><comment>long: why photos are not in the new sequence a conversion makes, in its dry run</comment></data>
<data name="Archive.Convert.NotCopied.TooLarge" xml:space="preserve"><value>Photos larger than this format can hold are not copied into the new sequence.</value><comment>long: why photos are not in the new sequence a conversion makes, in its dry run</comment></data>
<data name="Archive.Convert.NotCopied.Undecodable" xml:space="preserve"><value>Unreadable photos are not copied into the new sequence.</value><comment>long: why photos are not in the new sequence a conversion makes, in its dry run</comment></data>
<data name="Archive.Convert.NotCopied.Unhashed" xml:space="preserve"><value>Photos never verified are not copied into the new sequence; verify the sequence first.</value><comment>long: why photos are not in the new sequence a conversion makes, in its dry run</comment></data>
<data name="Archive.Convert.NotCopiedPhotos.one" xml:space="preserve"><value>{0:N0} not copied</value><comment>photos a conversion into a new sequence leaves out of it</comment></data>
+3
View File
@@ -56,10 +56,13 @@
<data name="Archive.Convert.HeadingAll" xml:space="preserve"><value>Converti {0}</value></data>
<data name="Archive.Convert.Mode" xml:space="preserve"><value>Modalità</value></data>
<data name="Archive.Convert.NewSequence" xml:space="preserve"><value>Nuova sequenza</value></data>
<data name="Archive.Convert.NotCopied.ColorProfile" xml:space="preserve"><value>Le foto il cui profilo colore questo formato non può né conservare né convertire non vengono copiate nella nuova sequenza.</value></data>
<data name="Archive.Convert.NotCopied.EightBit" xml:space="preserve"><value>Le foto RAW che questo computer sviluppa solo a 8 bit non vengono copiate nella nuova sequenza; JPEG le converte.</value></data>
<data name="Archive.Convert.NotCopied.Missing" xml:space="preserve"><value>Le foto mancanti non vengono copiate nella nuova sequenza.</value></data>
<data name="Archive.Convert.NotCopied.NoNativeDecoder" xml:space="preserve"><value>Le foto di un formato che questo computer non legge a piena risoluzione non vengono copiate nella nuova sequenza.</value></data>
<data name="Archive.Convert.NotCopied.PreviewOnly" xml:space="preserve"><value>Le foto lette qui solo dalla loro anteprima incorporata non vengono copiate nella nuova sequenza.</value></data>
<data name="Archive.Convert.NotCopied.SameFormat" xml:space="preserve"><value>Le foto già in questo formato non vengono copiate nella nuova sequenza.</value></data>
<data name="Archive.Convert.NotCopied.TooLarge" xml:space="preserve"><value>Le foto più grandi di quanto questo formato possa contenere non vengono copiate nella nuova sequenza.</value></data>
<data name="Archive.Convert.NotCopied.Undecodable" xml:space="preserve"><value>Le foto illeggibili non vengono copiate nella nuova sequenza.</value></data>
<data name="Archive.Convert.NotCopied.Unhashed" xml:space="preserve"><value>Le foto mai verificate non vengono copiate nella nuova sequenza; verifica prima la sequenza.</value></data>
<data name="Archive.Convert.NotCopiedPhotos.one" xml:space="preserve"><value>{0:N0} non copiata</value></data>
+39 -24
View File
@@ -306,6 +306,9 @@ public sealed class MassConverter
return new StepDone(Result(row, ConvertOutcome.Changed));
row = now;
folder = paths.Sequence(row.Folder);
// Moved away by another index of the archive, maybe with another sequence in the folder it left (this index's next
// scan finds both): nothing of it is settled, staged or replaced there; the retry after that scan converts it.
if (!SequenceFolders.Holds(folder, row.Id)) return new StepDone(Result(row, ConvertOutcome.Blocked, error: Loc.L("Errors.Archive.FolderMoved")));
manifest = SequenceWriter.ReadLocked(folder, row.Id);
FrameTrash.EnsureReplaced(folder);
var pin = pins.Of(step.Id);
@@ -596,13 +599,18 @@ public sealed class MassConverter
Dictionary<Guid, StagedConversion> ready, string staging, ConvertOptions options, string key, Guid? requestedBy, CancellationToken cancellationToken)
{
SequenceManifest manifest;
string? project;
await using (await _writer.LockAsync(paths, row.Id, cancellationToken).ConfigureAwait(false))
{
if (await _db.Sequences.GetAsync(row.Id, cancellationToken).ConfigureAwait(false) is not { } now || now.ArchiveId != archive.Id)
return new StepDone(Result(row, ConvertOutcome.Changed));
row = now;
manifest = SequenceWriter.ReadLocked(paths.Sequence(row.Folder), row.Id);
var folder = paths.Sequence(row.Folder);
manifest = SequenceWriter.ReadLocked(folder, row.Id);
if (!Holds(manifest, planned)) return new StepDone(Result(row, ConvertOutcome.Changed));
// The source's project, read where its sidecar was just read as its own: another index may move the sequence away
// later, and maybe another one into this folder, whose project the new sequence must not take.
project = row.SettingsJson ?? (File.Exists(folder.ProjectPath) ? AtomicFile.ReadAllText(folder.ProjectPath) : null);
}
var frames = manifest.Frames.ToDictionary(f => f.Id);
var filed = await FiledAsync(archive, key, cancellationToken).ConfigureAwait(false);
@@ -627,7 +635,7 @@ public sealed class MassConverter
await _ingest.CommitSessionAsync(archive, new SequenceTarget(key, title, null, owner), pending, CancellationToken.None).ConfigureAwait(false);
var id = await _db.Sequences.FindBySessionKeyAsync(archive.Id, key, CancellationToken.None).ConfigureAwait(false)
?? throw new IOException($"No converted photo of {row.DisplayTitle} could be filed into a new sequence.");
await CopyAsync(paths, row, manifest, ready, id, cancellationToken).ConfigureAwait(false);
await CopyAsync(paths, row, manifest, project, ready, id, cancellationToken).ConfigureAwait(false);
var made = await _db.Sequences.GetAsync(id, CancellationToken.None).ConfigureAwait(false)
?? throw new InvalidOperationException($"The new sequence {id} is not indexed.");
var leftOut = manifest.Frames.Count - planned.Frames.Count;
@@ -651,35 +659,42 @@ public sealed class MassConverter
}
/// <summary>
/// Gives the new sequence the source's tags, rating and notes, and its project with the frame positions (exclusions,
/// hero, keyframes) moved from the source's frames to the copies of them; a project that cannot be read is left out
/// (logged).
/// Gives the new sequence the source's tags, rating and notes, and its project (<paramref name="json"/>, read under the
/// source's lease) with the frame positions (exclusions, hero, keyframes) moved from the source's frames to the copies of
/// them; a project that cannot be read is left out (logged). The project is written under the new sequence's lease into
/// its folder as the index has it then, which must hold it (<see cref="SequenceFolders.Holds"/>).
/// </summary>
private async Task CopyAsync(ArchivePaths paths, Sequence source, SequenceManifest manifest, Dictionary<Guid, StagedConversion> ready, Guid id,
/// <exception cref="InvalidOperationException">Another index moved the new sequence away meanwhile; its project is not written.</exception>
private async Task CopyAsync(ArchivePaths paths, Sequence source, SequenceManifest manifest, string? json, Dictionary<Guid, StagedConversion> ready, Guid id,
CancellationToken cancellationToken)
{
await _service.EditSequenceInfoAsync(id, info => info with { Tags = source.Tags, Rating = source.Rating, Notes = source.Notes }, cancellationToken)
.ConfigureAwait(false);
var folder = paths.Sequence(source.Folder);
var json = source.SettingsJson ?? (File.Exists(folder.ProjectPath) ? AtomicFile.ReadAllText(folder.ProjectPath) : null);
if (string.IsNullOrWhiteSpace(json)) return;
var made = await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException($"The new sequence {id} is not indexed.");
var copy = Read(paths.Sequence(made.Folder), id) ?? throw new InvalidDataException($"The sidecar of the new sequence {made.DisplayTitle} cannot be read.");
// The source's frames as the copies the conversion made of them; a frame not converted keeps its own photo, which the
// new sequence lacks (its positions wait as pending frames).
var from = new FramePhotos(manifest.Frames.Select(f => (f.I, ready.TryGetValue(f.Id, out var c)
? new FramePhoto(c.Sha256.ToLowerInvariant(), c.Size, f.CapturedAt)
: new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
var to = new FramePhotos(copy.Frames.Select(f => (f.I, new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
try
await using (await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false))
{
var translated = ProjectSettings.TranslateFramePositions(json, from, to) ?? json;
var project = ProjectStore.Parse(translated);
await new ProjectStore(_db, _writer).UpdateAsync(paths, made, _ => project, cancellationToken).ConfigureAwait(false);
}
catch (InvalidDataException ex)
{
Core.Diagnostics.Log.Warning("archive", $"{source.DisplayTitle}: its project cannot be read; the new sequence {made.DisplayTitle} starts without it", ex);
var made = await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException($"The new sequence {id} is not indexed.");
var folder = paths.Sequence(made.Folder);
// Another index of the archive moved it away, and maybe another sequence into its folder (this index's next scan finds
// both): its project goes nowhere, as every writer into a sequence's folder decides.
if (!SequenceFolders.Holds(folder, id)) throw new InvalidOperationException(Loc.L("Errors.Archive.FolderMoved"));
var copy = Read(folder, id) ?? throw new InvalidDataException($"The sidecar of the new sequence {made.DisplayTitle} cannot be read.");
// The source's frames as the copies the conversion made of them; a frame not converted keeps its own photo, which the
// new sequence lacks (its positions wait as pending frames).
var from = new FramePhotos(manifest.Frames.Select(f => (f.I, ready.TryGetValue(f.Id, out var c)
? new FramePhoto(c.Sha256.ToLowerInvariant(), c.Size, f.CapturedAt)
: new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
var to = new FramePhotos(copy.Frames.Select(f => (f.I, new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
try
{
var translated = ProjectSettings.TranslateFramePositions(json, from, to) ?? json;
var project = ProjectStore.Parse(translated);
await new ProjectStore(_db, _writer).UpdateLockedAsync(paths, made, _ => project, cancellationToken).ConfigureAwait(false);
}
catch (InvalidDataException ex)
{
Core.Diagnostics.Log.Warning("archive", $"{source.DisplayTitle}: its project cannot be read; the new sequence {made.DisplayTitle} starts without it", ex);
}
}
}
@@ -725,6 +725,43 @@ public sealed class ConvertTests(TestContext context)
Assert.Equal("moved/Roof", (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single().Folder);
}
[Test]
public async Task ASequenceAnotherIndexMovedIsLeftAsItIsUntilThisIndexFindsIt()
{
// The folder the sequence left holds another sequence now, or nothing.
foreach (var taken in new[] { true, false })
{
await using var fx = await FixtureAsync();
var id = await UploadedAsync(fx, 2);
Guid? stranger = taken ? await UploadedAsync(fx, 2, "upload-2", seed: 200) : null;
var plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, id);
var row = (await fx.Db.Sequences.GetAsync(id))!;
var folder = fx.Paths.Sequence(row.Folder).Folder;
// Another index moves the folder away, then the other sequence into the folder it left; this index has scanned neither.
var (other, archive) = await fx.OtherWriterAsync();
var moves = stranger is not { } s ? [(id, "moved/{date}")] : new[] { (id, "moved/{date}"), (s, "parked/{date}"), (s, row.Folder) };
foreach (var (sequence, template) in moves)
await other.ApplyRenameAsync(await other.PlanRenameAsync(archive.Id, [sequence], template, null, fx.Ct), null, fx.Ct);
var before = taken ? ArchiveFixture.FilesOf(folder) : null;
var job = Guid.NewGuid();
var left = (await RunHereAsync(fx, plan, job)).Sequences.Single();
Assert.Equal((ConvertOutcome.Blocked, Loc.L("Errors.Archive.FolderMoved")), (left.Outcome, left.Error), taken.ToString());
if (taken) Assert.SequenceEqual(before!, ArchiveFixture.FilesOf(folder), "the other sequence's files are untouched");
else Assert.False(Directory.Exists(folder), "the folder it left is not created again");
// Once this index's scan found it there, the retry converts it where it is now.
await fx.ScanAsync();
Assert.Equal(ConvertOutcome.Converted, (await RunHereAsync(fx, plan, job)).Sequences.Single().Outcome, taken.ToString());
var moved = (await fx.Db.Sequences.GetAsync(id))!.Folder;
Assert.True(moved.StartsWith("moved/", StringComparison.Ordinal), moved);
Assert.True((await FramesAsync(fx, id)).All(f => f.Format == ImageFileFormat.Tiff && f.RelativePath.StartsWith(moved + "/", StringComparison.Ordinal)));
if (taken) Assert.SequenceEqual(before!, ArchiveFixture.FilesOf(folder), "the other sequence's files are still untouched");
else Assert.False(Directory.Exists(folder));
}
}
[Test]
public async Task AReorganizeTheArchiveWaitsForKeepsTheConversionOffItsSequences()
{
@@ -881,6 +881,57 @@ public sealed class SyncTransferTests(TestContext context)
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
}
[Test]
public async Task AFrameTakesBackItsPhotoInAnotherEncodingOnlyWhereTheSequenceIsNow()
{
// The folder the sequence left holds another sequence now, or nothing.
foreach (var taken in new[] { true, false })
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Harbour", photos);
var stranger = taken ? await f.LocalAsync("Stranger", f.NewPhotos(2)) : null;
var lost = (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct))[1];
File.Delete(f.Archive.Paths.FromRelative(lost.RelativePath));
await f.Archive.Service.Verifier.VerifyAsync(f.Archive.Archive, [local.Id], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: f.Ct);
// The server converted that photo.
var converted = f.NewPhotos(1)[0];
var remote = f.Remote.Add("Harbour", [photos[0], converted, photos[2]]);
remote.Removed.Add(new RemovedPhotoDto(Sha(photos[1]), Sha(converted), "replaced", DateTimeOffset.UtcNow));
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
var engine = await f.StartEngineAsync();
// Another index moves the folder away, then the other sequence into the folder it left; this index has scanned neither.
var folder = f.Archive.Paths.Sequence(local.Folder).Folder;
var (other, archive) = await f.Archive.OtherWriterAsync();
var moves = stranger is null ? [(local.Id, "moved/{title}")] : new[] { (local.Id, "moved/{title}"), (stranger.Id, "parked/{title}"), (stranger.Id, local.Folder) };
foreach (var (id, template) in moves)
await other.ApplyRenameAsync(await other.PlanRenameAsync(archive.Id, [id], template, null, f.Ct), null, f.Ct);
var before = taken ? ArchiveFixture.FilesOf(folder) : null;
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Originals, null);
var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), failed.Error, taken.ToString());
if (taken) Assert.SequenceEqual(before!, ArchiveFixture.FilesOf(folder), "the other sequence's files are untouched");
else Assert.False(Directory.Exists(folder), "the folder it left is not created again");
Assert.Equal(lost.Sha256, (await f.Db.Frames.GetAsync(lost.Id, f.Ct))!.Sha256);
// Once this index's scan found it there, the converted photo takes the frame's place in the folder the sequence is in now.
await f.Archive.ScanAsync();
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Originals, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var frames = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
Assert.Equal(3, frames.Count);
Assert.Equal((lost.Id, Sha(converted)), (frames[1].Id, frames[1].Sha256));
Assert.True(frames[1].RelativePath.StartsWith("moved/Harbour/", StringComparison.Ordinal), frames[1].RelativePath);
Assert.Equal(Sha(converted), Sha(await File.ReadAllBytesAsync(f.Archive.Paths.FromRelative(frames[1].RelativePath), f.Ct)));
Assert.True(frames.All(fr => (fr.Flags & FrameFlags.Missing) == 0), "nothing missing");
if (taken) Assert.SequenceEqual(before!, ArchiveFixture.FilesOf(folder), "the other sequence's files are still untouched");
else Assert.False(Directory.Exists(folder));
}
}
[Test]
public async Task AConversionMissingHereTakesBackTheOriginalTheServerHolds()
{
+11 -4
View File
@@ -2,6 +2,7 @@ using System.Globalization;
using System.Net;
using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Imaging;
using Chronos.Core.Localization;
@@ -273,22 +274,28 @@ public sealed class ConvertTests(TestContext context)
await UntilIdleAsync(server);
var request = new ConvertRequest([id], false, "linear-dng", null, "replace", DryRun: true);
const long Full = 1_000_000, Free = 100_000_000_000;
// A conversion counts the tighter of the archive root's volume and its staging folder's: one volume here.
void Set(long free)
{
foreach (var folder in (string[])[server.Options.ArchivePath, new ArchivePaths(server.Options.ArchivePath).StagingDirectory])
volumes.Set(folder, new VolumeFigures(free, 4 * Free));
}
volumes.Set(server.Options.ArchivePath, new VolumeFigures(Full, 4 * Free));
Set(Full);
var tight = await DryRunAsync(admin, request);
Assert.Equal((false, (long?)Full), (tight.Space.Enough, tight.Space.Free));
using (var refused = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = tight.Fingerprint }, ProtocolJson.Default.ConvertRequest))
Assert.Equal(tight.Space.Required.ToString(CultureInfo.InvariantCulture), (await refused.ExpectErrorAsync(HttpStatusCode.Conflict, "not_enough_space")).Details);
// Space freed since: the plan kept, with the free space now; and the confirmation measures it again too.
volumes.Set(server.Options.ArchivePath, new VolumeFigures(Free, 4 * Free));
Set(Free);
var freed = await DryRunAsync(admin, request);
Assert.Equal((true, (long?)Free, tight.Fingerprint, tight.Space.Required), (freed.Space.Enough, freed.Space.Free, freed.Fingerprint, freed.Space.Required));
Assert.Equal(1, server.Services.GetRequiredService<PlanCache>().Count);
volumes.Set(server.Options.ArchivePath, new VolumeFigures(Full, 4 * Free));
Set(Full);
using (var filled = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = freed.Fingerprint }, ProtocolJson.Default.ConvertRequest))
await filled.ExpectErrorAsync(HttpStatusCode.Conflict, "not_enough_space");
volumes.Set(server.Options.ArchivePath, new VolumeFigures(Free, 4 * Free));
Set(Free);
using (var applied = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = freed.Fingerprint }, ProtocolJson.Default.ConvertRequest))
await UntilJobAsync(admin, (await applied.ReadAsync(ProtocolJson.Default.JobDto)).Id, "done");
Assert.True((await server.Database.Frames.ListBySequenceAsync(id)).All(f => f.Format == ImageFileFormat.Dng), "converted");