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
@@ -1,6 +1,8 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.IO;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Metadata;
|
||||
using Titano.Core.Model;
|
||||
@@ -22,7 +24,9 @@ internal sealed record SequenceTarget(string Key, string? Title, string? Preferr
|
||||
/// under the naming template, the sidecar is rewritten atomically in capture order and the index follows. Commits
|
||||
/// to one sequence are serialised and batched (concurrent uploads share one sidecar write); a lease file keeps
|
||||
/// other processes out meanwhile, and a write-ahead journal repairs a batch interrupted by a crash. A file whose
|
||||
/// SHA-256 the sequence already holds is reported as a duplicate and left in staging.
|
||||
/// SHA-256 an intact frame of the sequence already holds is reported as a duplicate and left in staging; a frame with
|
||||
/// that SHA-256 that is flagged missing or corrupt, or whose file is gone or has another size, is repaired with it
|
||||
/// instead (its damaged file kept beside it). A sequence created without photos gets its folder with its first frame.
|
||||
/// </summary>
|
||||
public sealed class ArchiveIngest : IArchiveIngest
|
||||
{
|
||||
@@ -57,6 +61,7 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
{
|
||||
var sequence = await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
if (sequence?.ArchiveId != archive.Id) throw new ArgumentException($"Sequence {id} is not in archive {archive.Id}.", nameof(request));
|
||||
if (AwaitsFolder(sequence, new ArchivePaths(archive.RootPath))) await PlaceAsync(archive, id, frame, cancellationToken).ConfigureAwait(false);
|
||||
sequenceId = id;
|
||||
}
|
||||
else
|
||||
@@ -110,12 +115,7 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
Created = now,
|
||||
UpdatedAt = now,
|
||||
};
|
||||
var captured = CaptureTime(first);
|
||||
var wanted = target.PreferredFolder ?? PathTemplate.Parse(archive.FolderTemplate).ExpandFolder(Naming(first, captured, captured, 1, target.Title));
|
||||
if (wanted.Length == 0) wanted = "Sequence";
|
||||
var taken = (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false))
|
||||
.Select(l => l.Folder).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var sequence = ClaimFolder(paths, wanted, taken, manifest);
|
||||
var sequence = await ClaimNewFolderAsync(archive, paths, target.PreferredFolder, first, manifest, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
@@ -134,6 +134,98 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
return manifest.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A sequence created without photos (<c>POST /api/v1/sequences</c>, BRIEF §14.3) has no folder until its first frame.
|
||||
/// An empty folder otherwise means the archive root itself, adopted in place, whose sidecar names the sequence.
|
||||
/// </summary>
|
||||
internal static bool AwaitsFolder(Sequence sequence, ArchivePaths paths)
|
||||
{
|
||||
if (sequence.Folder.Length > 0) return false;
|
||||
var root = paths.Sequence(string.Empty);
|
||||
if (!File.Exists(root.ManifestPath)) return true;
|
||||
try
|
||||
{
|
||||
return ManifestStore.ReadSequence(root.ManifestPath).Id != sequence.Id;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException)
|
||||
{
|
||||
// An unreadable root sidecar: the commit reports it rather than placing the sequence elsewhere.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gives a sequence created without photos its folder, named from its first frame and title by the same rules as a
|
||||
/// sequence created by an upload, with a sidecar carrying the row's id, title, tags, rating and notes (and its project
|
||||
/// when one was saved); the index row takes the folder in one transaction. Serialised with the creation of sequences.
|
||||
/// </summary>
|
||||
private async Task PlaceAsync(Archive archive, Guid sequenceId, StagedFrame first, CancellationToken cancellationToken)
|
||||
{
|
||||
await _creation.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var row = await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException($"Sequence {sequenceId} is not indexed.");
|
||||
// A concurrent first frame placed it meanwhile.
|
||||
if (!AwaitsFolder(row, paths)) return;
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var m = first.Metadata;
|
||||
var manifest = new SequenceManifest
|
||||
{
|
||||
Id = row.Id,
|
||||
Title = row.Title,
|
||||
// The photo names its camera; the creator's hint stands in when it does not.
|
||||
Camera = m.Make is null && m.Model is null && row.CameraModel is not null
|
||||
? new SidecarCamera { Model = row.CameraModel }
|
||||
: new SidecarCamera { Make = m.Make, Model = m.Model, Serial = m.BodySerial },
|
||||
Lens = m.LensModel,
|
||||
Tags = row.Tags,
|
||||
Rating = row.Rating,
|
||||
Notes = row.Notes,
|
||||
Versions = new ManifestVersions { Settings = row.SettingsVersion, Frames = row.FramesVersion },
|
||||
CreatedBy = row.OwnerUserId?.ToString(),
|
||||
Created = now,
|
||||
UpdatedAt = now,
|
||||
};
|
||||
var sequence = await ClaimNewFolderAsync(archive, paths, null, first, manifest, cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (row.SettingsJson is { } settings) AtomicFile.WriteAllText(sequence.ProjectPath, settings);
|
||||
await using var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var current = await tx.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException($"Sequence {sequenceId} was deleted before its first frame.");
|
||||
await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, current), cancellationToken).ConfigureAwait(false);
|
||||
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Nothing was filed into the folder yet: it goes, and the next first frame claims one again.
|
||||
if (File.Exists(sequence.ProjectPath)) File.Delete(sequence.ProjectPath);
|
||||
ReleaseFolder(sequence);
|
||||
throw;
|
||||
}
|
||||
await _indexer.RecordStampsAsync(archive, sequence, manifest.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_creation.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A new folder for <paramref name="manifest"/>: the plan's folder or the archive's folder template, made unique.</summary>
|
||||
private async Task<SequencePaths> ClaimNewFolderAsync(Archive archive, ArchivePaths paths, string? preferredFolder, StagedFrame first,
|
||||
SequenceManifest manifest, CancellationToken cancellationToken)
|
||||
{
|
||||
var captured = CaptureTime(first);
|
||||
var wanted = preferredFolder ?? PathTemplate.Parse(archive.FolderTemplate).ExpandFolder(Naming(first, captured, captured, 1, manifest.Title));
|
||||
if (wanted.Length == 0) wanted = "Sequence";
|
||||
var taken = (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false))
|
||||
.Select(l => l.Folder).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
return ClaimFolder(paths, wanted, taken, manifest);
|
||||
}
|
||||
|
||||
/// <summary>The first free variant of <paramref name="wanted"/>, claimed by creating its sidecar (first writer wins).</summary>
|
||||
private static SequencePaths ClaimFolder(ArchivePaths paths, string wanted, HashSet<string> taken, SequenceManifest manifest)
|
||||
{
|
||||
@@ -197,24 +289,36 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
{
|
||||
var manifest = SequenceWriter.ReadLocked(sequence, sequenceId);
|
||||
var before = manifest.Frames.Count;
|
||||
var known = new Dictionary<string, SidecarFrame>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var f in manifest.Frames)
|
||||
{
|
||||
if (f.Sha256 is not null) known.TryAdd(f.Sha256, f);
|
||||
}
|
||||
var held = manifest.Frames.Where(f => f.Sha256 is not null).ToLookup(f => f.Sha256!, StringComparer.OrdinalIgnoreCase);
|
||||
// Content this batch files (new frames and repairs): another copy of it in the batch is a duplicate of that frame.
|
||||
var filed = new Dictionary<string, Guid>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
var accepted = new List<(Pending Pending, SidecarFrame Frame)>();
|
||||
var repairs = new List<(Pending Pending, SidecarFrame Frame)>();
|
||||
var duplicates = new List<(Pending Pending, Guid FrameId)>();
|
||||
foreach (var p in batch)
|
||||
{
|
||||
if (known.TryGetValue(p.Frame.Sha256, out var existing))
|
||||
if (filed.TryGetValue(p.Frame.Sha256, out var same))
|
||||
{
|
||||
duplicates.Add((p, existing.Id));
|
||||
duplicates.Add((p, same));
|
||||
continue;
|
||||
}
|
||||
// Only a frame that still holds the content makes this copy a duplicate; a missing or damaged one is repaired with it.
|
||||
var holders = held[p.Frame.Sha256];
|
||||
if (holders.FirstOrDefault(f => IsIntact(sequence, f)) is { } intact)
|
||||
{
|
||||
duplicates.Add((p, intact.Id));
|
||||
continue;
|
||||
}
|
||||
if (holders.FirstOrDefault() is { } damaged)
|
||||
{
|
||||
filed[p.Frame.Sha256] = damaged.Id;
|
||||
repairs.Add((p, damaged));
|
||||
continue;
|
||||
}
|
||||
var frame = SequenceFrames.FromMetadata(Guid.CreateVersion7(), p.Frame.OriginalFileName, p.Frame.OriginalFileName, p.Frame.Size,
|
||||
p.Frame.Sha256, p.Frame.Metadata, p.Frame.ClientCapturedAt);
|
||||
known[p.Frame.Sha256] = frame;
|
||||
filed[p.Frame.Sha256] = frame.Id;
|
||||
accepted.Add((p, frame));
|
||||
}
|
||||
|
||||
@@ -235,17 +339,37 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
p.Completion.TrySetException(ex);
|
||||
}
|
||||
}
|
||||
var repaired = new HashSet<Guid>();
|
||||
foreach (var (p, frame) in repairs)
|
||||
{
|
||||
if (Repair(sequence, frame, p.Frame.StagedPath) is { } error) p.Completion.TrySetException(error);
|
||||
else repaired.Add(frame.Id);
|
||||
}
|
||||
var updated = SequenceFrames.Insert(manifest, moved);
|
||||
if (moved.Count > 0) ManifestStore.WriteSequence(sequence.ManifestPath, updated);
|
||||
if (repaired.Count > 0)
|
||||
{
|
||||
updated = SequenceFrames.Update(updated, repaired.ToDictionary(id => id,
|
||||
_ => (Func<SidecarFrame, SidecarFrame>)(f => f with { Flags = f.Flags & ~(FrameFlags.Missing | FrameFlags.Corrupt) })));
|
||||
}
|
||||
if (moved.Count > 0 || repaired.Count > 0) ManifestStore.WriteSequence(sequence.ManifestPath, updated);
|
||||
IngestJournal.Delete(sequence);
|
||||
|
||||
var byId = updated.Frames.ToDictionary(f => f.Id);
|
||||
if (moved.Count > 0) await IndexAsync(archive, sequence, updated, before, moved.ConvertAll(m => byId[m.Id]), cancellationToken).ConfigureAwait(false);
|
||||
if (moved.Count > 0 || repaired.Count > 0)
|
||||
{
|
||||
await IndexAsync(archive, sequence, updated, before, moved.ConvertAll(m => byId[m.Id]), repaired.Count > 0, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
foreach (var (p, frame) in accepted.Where(a => byId.ContainsKey(a.Frame.Id)))
|
||||
p.Completion.TrySetResult(Result(sequenceId, sequence, byId[frame.Id], false));
|
||||
foreach (var (p, frame) in repairs.Where(r => repaired.Contains(r.Frame.Id)))
|
||||
p.Completion.TrySetResult(Result(sequenceId, sequence, byId[frame.Id], false));
|
||||
var unrepaired = repairs.Select(r => r.Frame.Id).Where(id => !repaired.Contains(id)).ToHashSet();
|
||||
foreach (var (p, frameId) in duplicates)
|
||||
{
|
||||
if (byId.TryGetValue(frameId, out var original)) p.Completion.TrySetResult(Result(sequenceId, sequence, original, true));
|
||||
// A copy of content this batch failed to file has nothing intact to stand for it.
|
||||
if (byId.TryGetValue(frameId, out var original) && !unrepaired.Contains(frameId))
|
||||
p.Completion.TrySetResult(Result(sequenceId, sequence, original, true));
|
||||
else p.Completion.TrySetException(new IOException(Loc.L("Archive.Error.DuplicateLost", p.Frame.OriginalFileName)));
|
||||
}
|
||||
}
|
||||
@@ -284,11 +408,60 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
return named;
|
||||
}
|
||||
|
||||
/// <summary>Appends the new rows when the index was in step with the sidecar; otherwise resyncs the whole sequence.</summary>
|
||||
private async Task IndexAsync(Archive archive, SequencePaths sequence, SequenceManifest manifest, int before, List<SidecarFrame> appended,
|
||||
CancellationToken cancellationToken)
|
||||
/// <summary>The frame still holds its content: not flagged missing or corrupt, and its file is there with its size.</summary>
|
||||
private static bool IsIntact(SequencePaths sequence, SidecarFrame frame)
|
||||
{
|
||||
var inStep = appended.All(f => f.I >= before)
|
||||
if ((frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0) return false;
|
||||
var file = new FileInfo(sequence.File(frame.File));
|
||||
return file.Exists && file.Length == frame.Size;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts a verified copy where a damaged frame's file belongs. A file still there (corrupt, or another size) moves aside
|
||||
/// as <c>name.damaged-<time></c>, which no scan takes for a photo, and is never deleted (BRIEF §0.2 rule 8); it comes
|
||||
/// back when the copy cannot be moved in. Returns the failure, or null.
|
||||
/// </summary>
|
||||
private static Exception? Repair(SequencePaths sequence, SidecarFrame frame, string stagedPath)
|
||||
{
|
||||
var target = sequence.File(frame.File);
|
||||
string? aside = null;
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
||||
if (File.Exists(target))
|
||||
{
|
||||
aside = string.Create(CultureInfo.InvariantCulture, $"{target}.damaged-{DateTime.UtcNow:yyyyMMddHHmmss}");
|
||||
File.Move(target, aside, overwrite: false);
|
||||
}
|
||||
File.Move(stagedPath, target, overwrite: false);
|
||||
Log.Info("archive", $"Repaired {sequence.ArchiveRelative(frame.File)} with a verified copy");
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
if (aside is not null && !File.Exists(target) && File.Exists(aside))
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Move(aside, target);
|
||||
}
|
||||
catch (Exception again) when (again is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"{aside} stays beside {target}", again);
|
||||
}
|
||||
}
|
||||
return ex;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends the new rows when the index was in step with the sidecar; otherwise (or when frames were repaired, whose
|
||||
/// flags change) resyncs the whole sequence.
|
||||
/// </summary>
|
||||
private async Task IndexAsync(Archive archive, SequencePaths sequence, SequenceManifest manifest, int before, List<SidecarFrame> appended,
|
||||
bool repaired, CancellationToken cancellationToken)
|
||||
{
|
||||
var inStep = !repaired && appended.All(f => f.I >= before)
|
||||
&& await _db.Frames.CountBySequenceAsync(manifest.Id, cancellationToken).ConfigureAwait(false) == before;
|
||||
if (!inStep)
|
||||
{
|
||||
|
||||
@@ -17,7 +17,10 @@ public sealed record IngestRequest(
|
||||
DateTime? ClientCapturedAt,
|
||||
Guid? UserId);
|
||||
|
||||
/// <summary>The committed frame; <see cref="Duplicate"/> when the sequence already held a frame with that SHA-256.</summary>
|
||||
/// <summary>
|
||||
/// The committed frame; <see cref="Duplicate"/> when an intact frame of the sequence already held that SHA-256 (the file
|
||||
/// stays in staging). A frame with that SHA-256 that was missing or damaged is repaired with the file instead (not a duplicate).
|
||||
/// </summary>
|
||||
public sealed record IngestResult(Guid SequenceId, Guid FrameId, int Index, string RelativePath, bool Duplicate);
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -62,10 +62,18 @@ public sealed class FrameRepository
|
||||
_db.ListAsync($"SELECT {Columns} FROM frames WHERE sequence_id = $1 AND idx > $2 ORDER BY idx LIMIT $3",
|
||||
[sequenceId, afterIndex, Cursor.ClampLimit(limit)], Map, cancellationToken);
|
||||
|
||||
/// <summary>Every frame with this content hash (duplicate detection, upload short-circuit).</summary>
|
||||
/// <summary>Every frame with this content hash (duplicate detection).</summary>
|
||||
public Task<IReadOnlyList<Frame>> FindBySha256Async(string sha256, CancellationToken cancellationToken = default) =>
|
||||
_db.ListAsync($"SELECT {Columns} FROM frames WHERE sha256 = $1 ORDER BY sequence_id, idx", [sha256.ToLowerInvariant()], Map, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Frames with this content hash that are not flagged missing or corrupt: only such a copy may stand for an upload
|
||||
/// (the upload short-circuit, a commit settled after a crash), so an upload of the same content repairs a damaged one.
|
||||
/// </summary>
|
||||
public Task<IReadOnlyList<Frame>> FindIntactBySha256Async(string sha256, CancellationToken cancellationToken = default) =>
|
||||
_db.ListAsync($"SELECT {Columns} FROM frames WHERE sha256 = $1 AND (flags & $2) = 0 ORDER BY sequence_id, idx",
|
||||
[sha256.ToLowerInvariant(), (int)(FrameFlags.Missing | FrameFlags.Corrupt)], Map, cancellationToken);
|
||||
|
||||
/// <summary>Writes analysis results for many frames in one transaction; returns the number of frames updated.</summary>
|
||||
public Task<int> UpdateLightStatsAsync(IReadOnlyList<FrameLightStats> stats, CancellationToken cancellationToken = default) =>
|
||||
_db.InTransactionAsync(async session =>
|
||||
|
||||
Reference in new issue
Block a user