fix(ingest): file uploads into API-made sequences and repair damaged frames
A sequence created with POST /api/v1/sequences had no folder, and the ingest looked for its sidecar at the archive root: every upload into it failed with 503 commit_failed, so the Uploader's "New sequence" target never worked. Its first frame now claims a folder by the rules of a sequence created by an upload (folder template with its title, unique variant, sidecar with the row's id, title, tags, rating, notes and project), and the row takes the folder in one transaction (DOCKER-1). A frame flagged missing or corrupt, or whose file is gone or has another size, no longer stands for an upload: the start short-circuit and crash recovery match only intact frames still on disk, and the ingest repairs such a frame with the verified copy (same id and position, flags cleared, a damaged file kept beside it as name.damaged-<time>) instead of calling it a duplicate. The Uploader deletes a source only after the server received and verified its bytes in that upload, never on "already on the server" (SRV-1). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
12 files changed
+441
-41
No files matched your search
@@ -33,7 +33,7 @@ public sealed class UploadEngineTests(TestContext context)
|
||||
});
|
||||
|
||||
[Test]
|
||||
public void DeleteAfterUploadRemovesOnlyConfirmedUnchangedFiles() => SingleThreadedContext.Run(async () =>
|
||||
public void DeleteAfterUploadRemovesOnlyVerifiedUnchangedFiles() => SingleThreadedContext.Run(async () =>
|
||||
{
|
||||
var queue = Queue(UploadTargetMode.Sessions, 3);
|
||||
var (verified, existing, changed) = (queue.Items[0], queue.Items[1], queue.Items[2]);
|
||||
@@ -54,7 +54,8 @@ public sealed class UploadEngineTests(TestContext context)
|
||||
|
||||
Assert.Equal(UploadItemState.Skipped, existing.State);
|
||||
Assert.False(File.Exists(verified.Path));
|
||||
Assert.False(File.Exists(existing.Path));
|
||||
// The server matched its hash without receiving these bytes: no verified copy, so the source stays.
|
||||
Assert.True(File.Exists(existing.Path), "a file the server already held is kept");
|
||||
Assert.True(File.Exists(changed.Path), "a file changed after verification is kept");
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Archiving;
|
||||
using Titano.Testing;
|
||||
using static Titano.Data.Tests.Archiving.ArchiveFixture;
|
||||
@@ -121,4 +122,97 @@ public sealed class ArchiveIngestTests(TestContext context)
|
||||
Assert.FileMissing(sequence.IngestJournalPath);
|
||||
Assert.Equal(3, (await fx.Db.Frames.ListBySequenceAsync(first.SequenceId)).Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AMissingFrameIsRepairedByTheSameContentInsteadOfCountingAsDuplicate()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var original = await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start, 7)), fx.Ct);
|
||||
var row = (await fx.Db.Sequences.GetAsync(original.SequenceId))!;
|
||||
var file = Path.Combine(fx.Archive.RootPath, original.RelativePath);
|
||||
var bytes = await File.ReadAllBytesAsync(file, fx.Ct);
|
||||
File.Delete(file);
|
||||
await fx.Service.Indexer.ReconcileAsync(fx.Archive, row, fx.Ct);
|
||||
Assert.Equal(FrameFlags.Missing, (await fx.Db.Frames.GetAsync(original.FrameId))!.Flags);
|
||||
|
||||
var again = fx.Stage(Start, 7);
|
||||
var repaired = await fx.Service.Ingest.CommitAsync(Request(fx, again), fx.Ct);
|
||||
|
||||
Assert.False(repaired.Duplicate, "the server holds no intact copy: this one is filed");
|
||||
Assert.Equal((original.FrameId, original.Index, original.RelativePath), (repaired.FrameId, repaired.Index, repaired.RelativePath));
|
||||
Assert.SequenceEqual(bytes, await File.ReadAllBytesAsync(file, fx.Ct));
|
||||
Assert.FileMissing(again.Path);
|
||||
Assert.Equal(FrameFlags.None, (await fx.Db.Frames.GetAsync(original.FrameId))!.Flags);
|
||||
var manifest = ManifestStore.ReadSequence(fx.Paths.Sequence(row.Folder).ManifestPath);
|
||||
Assert.Equal(FrameFlags.None, manifest.Frames.Single().Flags);
|
||||
Assert.False((await fx.Db.Sequences.GetAsync(original.SequenceId))!.Status.HasFlag(SequenceStatus.HasErrors));
|
||||
|
||||
// Intact again: the next copy is a duplicate and stays in staging.
|
||||
var third = fx.Stage(Start, 7);
|
||||
Assert.True((await fx.Service.Ingest.CommitAsync(Request(fx, third), fx.Ct)).Duplicate);
|
||||
Assert.FileExists(third.Path);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACorruptFrameIsRepairedAndItsDamagedFileKeptAside()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var original = await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start, 7)), fx.Ct);
|
||||
var file = Path.Combine(fx.Archive.RootPath, original.RelativePath);
|
||||
var bytes = await File.ReadAllBytesAsync(file, fx.Ct);
|
||||
var damaged = bytes.ToArray();
|
||||
damaged[^10] ^= 0xFF;
|
||||
await File.WriteAllBytesAsync(file, damaged, fx.Ct);
|
||||
await fx.Service.Verifier.VerifyAsync(fx.Archive, null, default, (_, _, _) => ValueTask.CompletedTask, null, fx.Ct);
|
||||
Assert.Equal(FrameFlags.Corrupt, (await fx.Db.Frames.GetAsync(original.FrameId))!.Flags);
|
||||
|
||||
var repaired = await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start, 7)), fx.Ct);
|
||||
|
||||
Assert.False(repaired.Duplicate);
|
||||
Assert.Equal(original.FrameId, repaired.FrameId);
|
||||
Assert.SequenceEqual(bytes, await File.ReadAllBytesAsync(file, fx.Ct));
|
||||
var aside = Directory.GetFiles(Path.GetDirectoryName(file)!, Path.GetFileName(file) + ".damaged-*");
|
||||
Assert.Count(1, aside);
|
||||
Assert.SequenceEqual(damaged, await File.ReadAllBytesAsync(aside[0], fx.Ct));
|
||||
Assert.Equal(FrameFlags.None, (await fx.Db.Frames.GetAsync(original.FrameId))!.Flags);
|
||||
// The kept file is no photo to a scan: the sequence still has one frame.
|
||||
Assert.Equal(0, (await fx.ScanAsync(ScanMode.Full)).Failed.Count);
|
||||
Assert.Equal(1, (await fx.Db.Sequences.GetAsync(original.SequenceId))!.FrameCount);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASequenceCreatedWithoutPhotosGetsItsFolderWithTheFirstFrame()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
// As POST /api/v1/sequences creates it: a row without a folder.
|
||||
var created = new Sequence
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
ArchiveId = fx.Archive.Id,
|
||||
Title = "Harbour sunset",
|
||||
Folder = string.Empty,
|
||||
Tags = ["harbour"],
|
||||
Rating = 4,
|
||||
Origin = SequenceOrigin.Server,
|
||||
OwnerUserId = Guid.CreateVersion7(),
|
||||
UpdatedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
await fx.Db.Sequences.UpsertAsync(created, fx.Ct);
|
||||
|
||||
var first = await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start, 1), sequenceId: created.Id), fx.Ct);
|
||||
var second = await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start.AddSeconds(10), 2), sequenceId: created.Id, name: "IMG_0002.JPG"), fx.Ct);
|
||||
|
||||
Assert.Equal((created.Id, created.Id), (first.SequenceId, second.SequenceId));
|
||||
var row = (await fx.Db.Sequences.GetAsync(created.Id))!;
|
||||
Assert.Equal("2026/2026-09-28 Canon EOS R5", row.Folder);
|
||||
Assert.Equal(("Harbour sunset", 4, SequenceOrigin.Server, created.OwnerUserId, 2), (row.Title, row.Rating, row.Origin, row.OwnerUserId, row.FrameCount));
|
||||
Assert.SequenceEqual(["harbour"], row.Tags);
|
||||
Assert.Equal("2026/2026-09-28 Canon EOS R5/originals/2026-09-28_18-00-00_0001.JPG", first.RelativePath);
|
||||
var manifest = ManifestStore.ReadSequence(fx.Paths.Sequence(row.Folder).ManifestPath);
|
||||
Assert.Equal((created.Id, "Harbour sunset", created.OwnerUserId.ToString()), (manifest.Id, manifest.Title, manifest.CreatedBy));
|
||||
Assert.SequenceEqual([first.FrameId, second.FrameId], manifest.Frames.Select(f => f.Id));
|
||||
Assert.FileMissing(fx.Paths.Sequence(string.Empty).ManifestPath);
|
||||
// The index can be rebuilt from the sidecar it now has.
|
||||
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
using System.Net;
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
using Titano.Server.Storage;
|
||||
using Titano.Testing;
|
||||
|
||||
@@ -42,11 +44,69 @@ public sealed class ArchiveModuleTests(TestContext context)
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] Photo()
|
||||
[Test]
|
||||
public async Task ASequenceCreatedThroughTheApiTakesUploadsIntoAFolderOfItsOwn()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = 64 * 1024, ArchiveModule.Register);
|
||||
var (_, _, token) = await server.UserAsync("alberto", "editor");
|
||||
var source = context.CreateTempDirectory("source");
|
||||
var photos = new List<(string Path, byte[] Bytes)>();
|
||||
for (var i = 0; i < 2; i++)
|
||||
{
|
||||
var path = Path.Combine(source, $"IMG_000{i + 1}.JPG");
|
||||
var bytes = Photo(i + 1);
|
||||
await File.WriteAllBytesAsync(path, bytes);
|
||||
photos.Add((path, bytes));
|
||||
}
|
||||
|
||||
// The Uploader's "New sequence" target: create it, then upload into it (BRIEF §15).
|
||||
using var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), "Titano Uploader (tests)") { Token = token };
|
||||
var created = await client.CreateSequenceAsync(new CreateSequenceRequest("Harbour sunset", null), context.Cancellation);
|
||||
var first = Assert.NotNull(await client.UploadFileAsync(photos[0].Path, created.Id, new DateTime(2026, 9, 28, 18, 2, 11), ct: context.Cancellation));
|
||||
var second = Assert.NotNull(await client.UploadFileAsync(photos[1].Path, created.Id, new DateTime(2026, 9, 28, 18, 2, 21), ct: context.Cancellation));
|
||||
|
||||
Assert.Equal((created.Id, created.Id, 0, 1), (first.SequenceId, second.SequenceId, first.Index, second.Index));
|
||||
var row = Assert.NotNull(await server.Database.Sequences.GetAsync(created.Id));
|
||||
Assert.True(row.Folder.StartsWith("2026/2026-09-28", StringComparison.Ordinal), row.Folder);
|
||||
Assert.Equal(("Harbour sunset", 2), (row.Title, row.FrameCount));
|
||||
var sidecar = ManifestStore.ReadSequence(new ArchivePaths(server.Options.ArchivePath).Sequence(row.Folder).ManifestPath);
|
||||
Assert.Equal((created.Id, "Harbour sunset"), (sidecar.Id, sidecar.Title));
|
||||
Assert.SequenceEqual([first.FrameId, second.FrameId], sidecar.Frames.Select(f => f.Id));
|
||||
Assert.FileMissing(Path.Combine(server.Options.ArchivePath, ".titano", "sequence.json"));
|
||||
for (var i = 0; i < 2; i++)
|
||||
{
|
||||
using var downloaded = new MemoryStream();
|
||||
await client.DownloadFrameAsync(i == 0 ? first.FrameId : second.FrameId, "original", downloaded, ct: context.Cancellation);
|
||||
Assert.BytesEqual(photos[i].Bytes, downloaded.ToArray());
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnOriginalWhoseFileIsGoneIsUploadedAgainIntoItsPlace()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var photo = Photo(3);
|
||||
var frame = await Uploads.UploadAsync(editor, photo, "IMG_0001.JPG", sessionKey: "roof");
|
||||
var row = Assert.NotNull(await server.Database.Frames.GetAsync(frame.FrameId));
|
||||
var path = Path.Combine(server.Options.ArchivePath, row.RelativePath);
|
||||
var known = await Uploads.StartAsync(editor, photo, "IMG_0001.JPG", sessionKey: "roof", expected: HttpStatusCode.OK);
|
||||
Assert.Equal((true, frame.FrameId), (known.AlreadyExists, known.FrameId));
|
||||
|
||||
File.Delete(path);
|
||||
// No "already exists" for a copy that is gone: the bytes come again and the frame gets its file back.
|
||||
var again = await Uploads.UploadAsync(editor, photo, "IMG_0001.JPG", sessionKey: "roof");
|
||||
|
||||
Assert.Equal((frame.FrameId, frame.SequenceId, frame.Index), (again.FrameId, again.SequenceId, again.Index));
|
||||
Assert.SequenceEqual(photo, await File.ReadAllBytesAsync(path));
|
||||
Assert.Equal(1, Assert.NotNull(await server.Database.Sequences.GetAsync(frame.SequenceId)).FrameCount);
|
||||
}
|
||||
|
||||
private static byte[] Photo(int seed = 0)
|
||||
{
|
||||
const int width = 96, height = 64;
|
||||
var pixels = new byte[width * height * 3];
|
||||
for (var i = 0; i < pixels.Length; i++) pixels[i] = (byte)(i * 7 % 251);
|
||||
for (var i = 0; i < pixels.Length; i++) pixels[i] = (byte)((i * 7 + seed * 31) % 251);
|
||||
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 90 });
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
using Titano.Server.Storage;
|
||||
@@ -96,6 +97,49 @@ public sealed class UploadTests(TestContext context)
|
||||
Assert.Equal(frame.FrameId, again.FrameId);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACopyFlaggedOrGoneIsNoShortcut()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk);
|
||||
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
|
||||
// A client may delete its file on "already exists": a damaged copy must ask for the bytes again.
|
||||
var flagged = Uploads.Photo(5000, 11);
|
||||
var first = await Uploads.UploadAsync(uploader, flagged);
|
||||
await server.Database.Frames.UpdateFlagsAsync([first.FrameId], FrameFlags.Corrupt, FrameFlags.None);
|
||||
Assert.False((await Uploads.StartAsync(uploader, flagged)).AlreadyExists);
|
||||
|
||||
var gone = Uploads.Photo(5000, 12);
|
||||
var second = await Uploads.UploadAsync(uploader, gone);
|
||||
File.Delete(Path.Combine(server.Options.ArchivePath, Assert.NotNull(await server.Database.Frames.GetAsync(second.FrameId)).RelativePath));
|
||||
Assert.False((await Uploads.StartAsync(uploader, gone)).AlreadyExists);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACommitLeftByACrashIsSettledOnlyByAnIntactFrame()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk);
|
||||
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
|
||||
var data = Uploads.Photo(Chunk + 100, 13);
|
||||
var missing = await Uploads.UploadAsync(uploader, data);
|
||||
await server.Database.Frames.UpdateFlagsAsync([missing.FrameId], FrameFlags.Missing, FrameFlags.None);
|
||||
var start = await Uploads.StartAsync(uploader, data);
|
||||
var id = Assert.NotNull(start.UploadId);
|
||||
for (var i = 0; i < 2; i++)
|
||||
{
|
||||
using var put = await Uploads.PutChunkAsync(uploader, id, i, Uploads.Chunk(data, Chunk, i));
|
||||
await put.ExpectAsync(HttpStatusCode.OK);
|
||||
}
|
||||
// The server stopped while committing it.
|
||||
Assert.True(await server.Database.Uploads.TryTransitionAsync(id, Titano.Data.Repositories.UploadState.Receiving,
|
||||
Titano.Data.Repositories.UploadState.Committing, cancellationToken: context.Cancellation));
|
||||
|
||||
await server.Services.GetRequiredService<UploadMaintenance>().RecoverAsync(context.Cancellation);
|
||||
|
||||
// The flagged frame does not stand for it: the client completes again with its part file intact.
|
||||
using (var state = await uploader.GetAsync($"/api/v1/uploads/{id}")) Assert.Equal("receiving", (await state.ReadAsync(ProtocolJson.Default.UploadState)).State);
|
||||
Assert.True(server.Services.GetRequiredService<UploadStore>().Exists(id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnUploadKeepsItsChunkSizeWhenTheSettingShrinks()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user