Merge branch 'fix/ingest-upload': uploads into API-made sequences, damaged frames repaired, positions follow inserts, cardEvent

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 11:44:09 +00:00
commit 3b1b743fcd
29 files changed
+1546 -80

No files matched your search

+166 -1
View File
@@ -14,7 +14,8 @@ namespace Titano.App.Import;
/// server files them in one sequence — the same one when an interrupted import is started again. A typed session
/// title is set on that sequence once. A file the server refuses (a hash mismatch, a format it rejects) is listed in
/// <see cref="Report"/> and the import goes on (BRIEF §13: errors per file); a failed connection, sign-in or server
/// stops it.
/// stops it. A file the server already held counts as a duplicate: the server answers so only for a copy that is not
/// flagged missing or damaged, and a server import never deletes anything from the card.
/// </summary>
public sealed class ServerImportSink(TitanoClient client, string stagingDirectory) : IImportSink
{
@@ -25,6 +26,27 @@ public sealed class ServerImportSink(TitanoClient client, string stagingDirector
/// <summary>Every file committed or refused so far, by card path; pass it to <see cref="LocalImport.RunAsync"/>.</summary>
public ImportSinkReport Report { get; } = new();
/// <summary>
/// Runs a confirmed plan into the server through this sink (<see cref="LocalImport.RunAsync"/>) and tells the server's
/// other clients about it as <paramref name="card"/> (BRIEF §14.3 <c>cardEvent</c>): started, its progress, and
/// finished, also when it stopped early.
/// </summary>
public async Task<ImportOutcome> RunAsync(ImportPlan plan, string card, bool verify, IProgress<ImportProgress>? progress, CancellationToken cancellationToken)
{
var events = new CardImportReporter(client, plan.Id, card, plan.FileCount);
events.Started();
ImportOutcome? outcome = null;
try
{
outcome = await LocalImport.RunAsync(plan, this, verify, events.Forward(progress), cancellationToken, Report).ConfigureAwait(false);
return outcome;
}
finally
{
await events.FinishedAsync(outcome).ConfigureAwait(false);
}
}
public async Task<IReadOnlyList<SinkCommit>> CommitAsync(PlannedSession session, IReadOnlyList<StagedFile> files, CancellationToken cancellationToken)
{
var results = new List<SinkCommit>(files.Count);
@@ -80,3 +102,146 @@ public sealed class ServerImportSink(TitanoClient client, string stagingDirector
private static bool IsRefusal(TitanoApiException ex) =>
!ex.IsTransient && ex.Status is not (HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) && (int)ex.Status is >= 400 and < 500;
}
/// <summary>
/// The reports of one card import into the server (BRIEF §14.3 <c>cardEvent</c>, §14.4), sent one at a time and in order:
/// progress at most once a second, and a progress report still waiting is replaced by the next report, so a slow or
/// unreachable server never piles them up. A report that fails is logged and the import goes on; a server without the
/// endpoint (404) gets no more reports. Once the import is over its end gets two seconds to reach the server, then
/// whatever is still on its way is given up.
/// </summary>
/// <param name="total">Photos of the plan, skipped ones included (like <see cref="ImportProgress.ItemsTotal"/>).</param>
public sealed class CardImportReporter(TitanoClient client, Guid importId, string card, int total, TimeProvider? time = null)
{
private static readonly TimeSpan ProgressInterval = TimeSpan.FromSeconds(1);
private static readonly TimeSpan SendTimeout = TimeSpan.FromSeconds(10);
private static readonly TimeSpan FinishWait = TimeSpan.FromSeconds(2);
private readonly TimeProvider _time = time ?? TimeProvider.System;
private readonly CancellationTokenSource _stop = new();
private readonly Lock _gate = new();
private readonly List<CardImportReport> _queue = [];
private Task _sending = Task.CompletedTask;
private bool _draining;
private bool _finished;
private bool _unsupported;
private long? _lastProgress;
private ImportProgress? _latest;
public void Started() => Post(CardImportStates.Started, 0, 0);
/// <summary>Progress that reaches <paramref name="inner"/> (the screen's own) and these reports.</summary>
public IProgress<ImportProgress> Forward(IProgress<ImportProgress>? inner) => new Forwarding(this, inner);
public void Report(ImportProgress progress)
{
lock (_gate)
{
_latest = progress;
var now = _time.GetTimestamp();
if (_lastProgress is { } last && _time.GetElapsedTime(last, now) < ProgressInterval) return;
_lastProgress = now;
}
Post(CardImportStates.Progress, progress.ItemsDone, progress.Failed);
}
/// <summary>
/// Reports the end: every photo handled when the import gave an <paramref name="outcome"/>, else as far as its progress
/// got. Waits at most two seconds for the reports still queued, then stops sending: an import that was cancelled or
/// lost its server ends at once instead of waiting for a server that does not answer.
/// </summary>
public async Task FinishedAsync(ImportOutcome? outcome)
{
int done, failed;
Task sending;
lock (_gate)
{
done = outcome is null ? _latest?.ItemsDone ?? 0 : total;
failed = outcome?.Failures.Count ?? _latest?.Failed ?? 0;
}
Post(CardImportStates.Finished, done, failed);
lock (_gate) sending = _sending;
try
{
await sending.WaitAsync(FinishWait, _time).ConfigureAwait(false);
}
catch (TimeoutException)
{
Log.Info("import", $"The last reports of the import from {card} were given up: the server did not take them in time");
}
finally
{
// Nothing is sent once the import is over: its client goes next.
await _stop.CancelAsync().ConfigureAwait(false);
}
}
private void Post(string state, int done, int failed)
{
var report = new CardImportReport(importId, card, state, Math.Clamp(done, 0, total), total, Math.Clamp(failed, 0, total));
lock (_gate)
{
if (_finished || _unsupported) return;
_finished = state == CardImportStates.Finished;
if (_queue.Count > 0 && _queue[^1].State == CardImportStates.Progress) _queue[^1] = report;
else _queue.Add(report);
if (_draining) return;
_draining = true;
_sending = Task.Run(DrainAsync);
}
}
private async Task DrainAsync()
{
while (true)
{
CardImportReport report;
lock (_gate)
{
if (_queue.Count == 0 || _unsupported || _stop.IsCancellationRequested)
{
_queue.Clear();
_draining = false;
return;
}
report = _queue[0];
_queue.RemoveAt(0);
}
await SendAsync(report).ConfigureAwait(false);
}
}
private async Task SendAsync(CardImportReport report)
{
try
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(_stop.Token);
timeout.CancelAfter(SendTimeout);
await client.ReportCardAsync(report, timeout.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (_stop.IsCancellationRequested)
{
// The import is over and did not wait for this one.
}
catch (TitanoApiException ex) when (ex.Status is HttpStatusCode.NotFound or HttpStatusCode.MethodNotAllowed)
{
// A server from before card events.
lock (_gate) _unsupported = true;
Log.Info("import", $"The server takes no card reports ({ex.Error.Code})");
}
catch (Exception ex)
{
// The reports only inform the other clients: nothing about them may stop or fail the import.
Log.Warning("import", $"The {report.State} report of the import from {card} did not reach the server", ex);
}
}
private sealed class Forwarding(CardImportReporter reporter, IProgress<ImportProgress>? inner) : IProgress<ImportProgress>
{
public void Report(ImportProgress value)
{
inner?.Report(value);
reporter.Report(value);
}
}
}
+4 -4
View File
@@ -1168,7 +1168,7 @@ public sealed class ImportViewModel : SectionViewModel
if (choices.Destination == ImportDestinationKind.Folder)
outcome = await Task.Run(() => LocalImport.RunAsync(plan, new FolderImportSink(choices.FolderPath!), choices.VerifyCopies, progress, cts.Token), cts.Token);
else if (Services.Server.Flow is { Address: { } address, Token: { } token })
outcome = await RunServerAsync(plan, choices, address, token, progress, cts.Token);
outcome = await RunServerAsync(plan, choices, source.Title, address, token, progress, cts.Token);
else
{
Fail(Loc.L("Import.Blocked.NoServer"));
@@ -1188,15 +1188,15 @@ public sealed class ImportViewModel : SectionViewModel
}
}
private async Task<ImportOutcome> RunServerAsync(ImportPlan plan, ImportChoices choices, Uri address, string token, IProgress<ImportProgress> progress,
CancellationToken ct)
private async Task<ImportOutcome> RunServerAsync(ImportPlan plan, ImportChoices choices, string card, Uri address, string token,
IProgress<ImportProgress> progress, CancellationToken ct)
{
var staging = Path.Combine(ServerStagingRoot, plan.Id.ToString("N"));
using var client = new TitanoClient(address, new CertificatePinning(Services.Server.Fingerprints), $"Titano ({Environment.MachineName})") { Token = token };
try
{
var sink = new ServerImportSink(client, staging);
return await Task.Run(() => LocalImport.RunAsync(plan, sink, choices.VerifyCopies, progress, ct, sink.Report), ct);
return await Task.Run(() => sink.RunAsync(plan, card, choices.VerifyCopies, progress, ct), ct);
}
finally
{
+50 -1
View File
@@ -174,6 +174,9 @@ public sealed record ProjectSettings
{
public const int CurrentVersion = 1;
/// <summary>Layout of a project edited as JSON (<see cref="MoveFramePositions"/>): indented like <see cref="ToJson"/>.</summary>
private static readonly JsonSerializerOptions IndentedJson = new() { WriteIndented = true };
public int Version { get; init; } = CurrentVersion;
public TimingSettings Timing { get; init; } = new();
public ExposureSettings Exposure { get; init; } = new();
@@ -182,7 +185,7 @@ public sealed record ProjectSettings
public StackSettings Stack { get; init; } = new();
public ExportSettings Export { get; init; } = new();
/// <summary>Frame indices excluded from renders.</summary>
/// <summary>Frame indices excluded from renders (positions in capture order; see <see cref="MoveFramePositions"/>).</summary>
public IReadOnlyList<int> ExcludedFrames { get; init; } = [];
/// <summary>Index of the hero frame (sequence thumbnail).</summary>
@@ -237,6 +240,52 @@ public sealed record ProjectSettings
target[name] = value?.DeepClone();
}
}
/// <summary>
/// Moves the frame positions of a project — <see cref="ExcludedFrames"/>, <see cref="HeroFrame"/> and the
/// virtual-camera <see cref="CameraKey.Frame"/>s — after frames were inserted before them: <paramref name="moves"/> maps
/// an old position to the new one, and a position it does not list stays. The JSON is edited in place, so members
/// this Titano does not know survive. Null when nothing moves or <paramref name="json"/> is not a project object.
/// </summary>
public static string? MoveFramePositions(string json, IReadOnlyDictionary<int, int> moves)
{
ArgumentNullException.ThrowIfNull(moves);
if (moves.Count == 0 || string.IsNullOrWhiteSpace(json)) return null;
try
{
if (JsonNode.Parse(json, new JsonNodeOptions { PropertyNameCaseInsensitive = true }) is not JsonObject project) return null;
var moved = false;
if (project["excludedFrames"] is JsonArray excluded)
{
for (var i = 0; i < excluded.Count; i++)
{
var at = i;
moved |= Move(excluded[at], value => excluded[at] = value, moves);
}
}
if (project["heroFrame"] is { } hero) moved |= Move(hero, value => project["heroFrame"] = value, moves);
if (project["camera"] is JsonObject camera && camera["keyframes"] is JsonArray keyframes)
{
foreach (var key in keyframes.OfType<JsonObject>())
{
if (key["frame"] is { } frame) moved |= Move(frame, value => key["frame"] = value, moves);
}
}
return moved ? project.ToJsonString(IndentedJson) : null;
}
catch (Exception ex) when (ex is JsonException or ArgumentException)
{
// Not JSON, or a member given twice (the case-insensitive member table refuses it): not a project to edit.
return null;
}
}
private static bool Move(JsonNode? position, Action<JsonNode> replace, IReadOnlyDictionary<int, int> moves)
{
if (position is not JsonValue value || !value.TryGetValue<int>(out var old) || !moves.TryGetValue(old, out var now) || now == old) return false;
replace(JsonValue.Create(now));
return true;
}
}
[JsonSourceGenerationOptions(
+52 -9
View File
@@ -91,18 +91,28 @@ public sealed class ArchiveIndexer
return new ScanSummary(folders.Count, indexed, adopted, removed, failed);
}
/// <summary>Writes a sequence's sidecar into the index (row, frames, session keys) and records the folder stamps.</summary>
/// <summary>
/// Writes a sequence's sidecar into the index (row, frames, session keys) and records the folder stamps. Frames
/// inserted before indexed ones take the project's frame positions along (<see cref="ProjectPositions"/>).
/// </summary>
internal async Task SyncAsync(Archive archive, SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken)
{
(string Before, string Moved)? positions = null;
await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false))
{
var existing = await tx.Sequences.GetAsync(manifest.Id, cancellationToken).ConfigureAwait(false);
if (existing is not null)
{
positions = await ProjectPositions.MoveAsync(tx, existing, manifest, cancellationToken).ConfigureAwait(false);
if (positions is { } project) existing = existing with { SettingsJson = project.Moved };
}
await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, existing), cancellationToken).ConfigureAwait(false);
await tx.Frames.SyncSequenceAsync(manifest.Id, SequenceMapping.ToFrames(manifest, sequence), cancellationToken).ConfigureAwait(false);
foreach (var key in manifest.SessionKeys)
await tx.Sequences.MapSessionKeyAsync(archive.Id, key, manifest.Id, cancellationToken).ConfigureAwait(false);
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
}
if (positions is { } moved) ProjectPositions.WriteProject(sequence, moved.Before, moved.Moved);
await RecordStampsAsync(archive, sequence, manifest.Id, cancellationToken).ConfigureAwait(false);
}
@@ -120,10 +130,30 @@ public sealed class ArchiveIndexer
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var folder = paths.Sequence(sequence.Folder);
var manifest = await _writer.UpdateAsync(paths, sequence.Id, sequence.Folder, m => SequenceAdopter.Reconcile(folder, m, cancellationToken),
cancellationToken).ConfigureAwait(false);
await SyncAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false);
return manifest;
return await UpdateAndSyncAsync(archive, paths, folder, sequence.Id, m => SequenceAdopter.Reconcile(folder, m, cancellationToken), cancellationToken)
.ConfigureAwait(false);
}
/// <summary>
/// Applies <paramref name="edit"/> to the sidecar (null writes nothing) and indexes the result, both under the sequence
/// lease. Frames inserted before indexed ones move the project's positions (<see cref="ProjectPositions"/>) without a
/// new settings version; an editor saving its project holds the same lease, so it reads them moved and merges onto
/// them rather than writing its old positions back.
/// </summary>
private async Task<SequenceManifest> UpdateAndSyncAsync(Archive archive, ArchivePaths paths, SequencePaths sequence, Guid sequenceId,
Func<SequenceManifest, SequenceManifest?> edit, CancellationToken cancellationToken)
{
await using (await _writer.LockAsync(paths, sequenceId, cancellationToken).ConfigureAwait(false))
{
var manifest = SequenceWriter.ReadLocked(sequence, sequenceId);
if (edit(manifest) is { } updated)
{
ManifestStore.WriteSequence(sequence.ManifestPath, updated);
manifest = updated;
}
await SyncAsync(archive, sequence, manifest, cancellationToken).ConfigureAwait(false);
return manifest;
}
}
/// <summary>Indexes one folder; returns the sidecar bytes when they were read and not rewritten since (for the snapshot).</summary>
@@ -159,20 +189,33 @@ public sealed class ArchiveIndexer
}
if (reconcile || File.Exists(sequence.IngestJournalPath))
{
var before = manifest;
// Photos added, gone or back: the light analysis no longer describes the frames, so the scan's follow-up runs it again.
manifest = await _writer.UpdateAsync(paths, manifest.Id, folder.RelativeFolder,
manifest = await UpdateAndSyncAsync(archive, paths, sequence, manifest.Id,
m => SequenceAdopter.Reconcile(sequence, m, cancellationToken) is { } reconciled
? reconciled with { Status = reconciled.Status & ~SequenceStatus.AnalyzedLight }
: null,
cancellationToken).ConfigureAwait(false);
if (!ReferenceEquals(before, manifest)) bytes = null;
bytes = null;
}
else if (await MayMovePositionsAsync(manifest, cancellationToken).ConfigureAwait(false))
{
// Another process changed the frames: the sidecar is read again under the lease the project moves under.
manifest = await UpdateAndSyncAsync(archive, paths, sequence, manifest.Id, _ => null, cancellationToken).ConfigureAwait(false);
bytes = null;
}
else
{
await SyncAsync(archive, sequence, manifest, cancellationToken).ConfigureAwait(false);
}
await SyncAsync(archive, sequence, manifest, cancellationToken).ConfigureAwait(false);
locations.Set(manifest.Id, folder.RelativeFolder);
return bytes;
}
/// <summary>The index holds a project for this sequence and other frames than the sidecar: its positions may move.</summary>
private async Task<bool> MayMovePositionsAsync(SequenceManifest manifest, CancellationToken cancellationToken) =>
await _db.Sequences.GetAsync(manifest.Id, cancellationToken).ConfigureAwait(false) is { SettingsJson: not null } indexed
&& indexed.FramesVersion != manifest.Versions.Frames;
/// <summary>A sidecar for a folder that has none; ids of a sequence the index already knew at this folder are kept.</summary>
private async Task<SequenceManifest> AdoptAsync(SequencePaths sequence, Locations locations, CancellationToken cancellationToken)
{
+196 -22
View File
@@ -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,99 @@ 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; one
/// that holds frames is never moved elsewhere, even while its root sidecar is missing.
/// </summary>
internal static bool AwaitsFolder(Sequence sequence, ArchivePaths paths)
{
if (sequence.Folder.Length > 0 || sequence.FrameCount > 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 +290,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 +340,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) with { Repaired = true });
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 +409,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-&lt;time&gt;</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, which also moves the project's frame positions after an insertion.
/// </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)
{
+6 -2
View File
@@ -17,8 +17,12 @@ 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>
public sealed record IngestResult(Guid SequenceId, Guid FrameId, int Index, string RelativePath, bool Duplicate);
/// <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:
/// <see cref="Repaired"/>, not a duplicate, and the archive holds no more bytes than before.
/// </summary>
public sealed record IngestResult(Guid SequenceId, Guid FrameId, int Index, string RelativePath, bool Duplicate, bool Repaired = false);
/// <summary>
/// Commits staged files into the archive layout (originals folder, naming templates, <c>sequence.json</c> written
@@ -0,0 +1,75 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using Titano.Core.Archiving;
using Titano.Core.Diagnostics;
using Titano.Core.IO;
using Titano.Core.Model;
using Titano.Core.Project;
namespace Titano.Data.Archiving;
/// <summary>
/// Keeps a project's frame positions (exclusions, hero, virtual-camera keyframes; BRIEF §5, §7) on their frames when the
/// index takes a sidecar in which frames were inserted before others: an upload or import of earlier photos, photos a
/// scan found, a sync download, a journalled batch completed after a crash. Positions name the frames in the indexed
/// order (what editors, renders and the API read), so the old order comes from the index rows. Only an insertion is
/// followed: when an indexed frame is no longer in the sidecar, positions cannot be mapped and stay as they are. The move
/// is part of the frames change, not a settings edit, so the settings version stays and a synced copy receiving the
/// same frames makes the same move.
/// </summary>
internal static class ProjectPositions
{
/// <summary>
/// The index's copy of the project (the one in force) and the same project with its positions moved to the order of
/// <paramref name="manifest"/>; null when nothing moves. A <c>project.json</c> the index has no copy of was written by
/// another process against its own frames, so it is left to that writer.
/// </summary>
public static async Task<(string Before, string Moved)?> MoveAsync(TitanoRepositories db, Sequence indexed, SequenceManifest manifest,
CancellationToken cancellationToken)
{
// The sidecar's frames are the ones indexed: nothing was inserted.
if (indexed.FramesVersion == manifest.Versions.Frames) return null;
if (indexed.SettingsJson is not { } project) return null;
var rows = await db.Frames.ListPositionsAsync(indexed.Id, cancellationToken).ConfigureAwait(false);
var now = new Dictionary<Guid, int>(manifest.Frames.Count);
foreach (var frame in manifest.Frames) now[frame.Id] = frame.I;
var moves = new Dictionary<int, int>();
foreach (var row in rows)
{
if (!now.TryGetValue(row.FrameId, out var index)) return null;
if (index != row.Index) moves[row.Index] = index;
}
return ProjectSettings.MoveFramePositions(project, moves) is { } moved ? (project, moved) : null;
}
/// <summary>
/// Mirrors moved positions into <c>project.json</c> once the index holds them, unless the file was written since
/// (it then belongs to that writer, whose next save mirrors the index again). A failed write leaves the index right.
/// </summary>
public static void WriteProject(SequencePaths sequence, string before, string moved)
{
try
{
if (File.Exists(sequence.ProjectPath) && !SameJson(File.ReadAllText(sequence.ProjectPath), before)) return;
Directory.CreateDirectory(sequence.MetaDirectory);
AtomicFile.WriteAllText(sequence.ProjectPath, moved);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"Project of {sequence.RelativeFolder} keeps its old frame positions on disk", ex);
}
}
/// <summary>Same JSON content whatever the layout (an index may store it normalised).</summary>
private static bool SameJson(string a, string b)
{
try
{
return JsonNode.DeepEquals(JsonNode.Parse(a), JsonNode.Parse(b));
}
catch (JsonException)
{
return false;
}
}
}
@@ -10,6 +10,9 @@ public readonly record struct FrameIntegrity(Guid FrameId, FrameFlags Flags, str
/// <summary>A frame and the sequence it belongs to.</summary>
public readonly record struct FrameRef(Guid FrameId, Guid SequenceId);
/// <summary>Where a frame stands in its sequence.</summary>
public readonly record struct FramePosition(Guid FrameId, int Index);
/// <summary>A frame whose content (SHA-256) also exists elsewhere in the archive.</summary>
public sealed record DuplicateFrame(string Sha256, Guid FrameId, Guid SequenceId, int Index, string RelativePath);
@@ -66,6 +69,11 @@ public sealed class FrameRepository
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>Id and index of every frame of a sequence, in index order.</summary>
public Task<IReadOnlyList<FramePosition>> ListPositionsAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
_db.ListAsync("SELECT id, idx FROM frames WHERE sequence_id = $1 ORDER BY idx", [sequenceId], r => new FramePosition(r.GetGuid(0), r.GetInt32(1)),
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 =>
@@ -192,6 +192,13 @@ public sealed class TitanoClient : IDisposable
return await RetryAsync(() => SendAsync<CompleteUploadResponse>(HttpMethod.Post, $"api/v1/uploads/{uploadId}/complete", ProtocolJson.Default.CompleteUploadResponse, ct), ct).ConfigureAwait(false);
}
/// <summary>
/// Reports a card import this client streams into the server (started, progress, finished); the server tells every
/// connected client with a <see cref="CardEvent"/> (BRIEF §14.3).
/// </summary>
public Task ReportCardAsync(CardImportReport report, CancellationToken ct = default) =>
SendAsync(HttpMethod.Post, "api/v1/uploads/cards", report, ProtocolJson.Default.CardImportReport, ct);
/// <summary>
/// Render node: uploads the output of a claimed job in resumable chunks, then completes the job; the server verifies
/// the SHA-256 in <paramref name="result"/> and files the render under the sequence's exports (BRIEF §14.7).
+21
View File
@@ -10,6 +10,7 @@ namespace Titano.Protocol;
[JsonDerivedType(typeof(JobProgressEvent), "jobProgress")]
[JsonDerivedType(typeof(JobStateEvent), "jobState")]
[JsonDerivedType(typeof(SequenceChangedEvent), "sequenceChanged")]
[JsonDerivedType(typeof(CardEvent), "cardEvent")]
[JsonDerivedType(typeof(NodeStateEvent), "nodeState")]
public abstract record ServerEvent;
@@ -19,4 +20,24 @@ public sealed record JobStateEvent(Guid JobId, string State, string? Error) : Se
public sealed record SequenceChangedEvent(Guid SequenceId, string Change, int FramesVersion, int SettingsVersion) : ServerEvent;
/// <summary>
/// A card import that a connected client streams into the server (BRIEF §14.4), as that client reported it
/// (<see cref="CardImportReport"/>): <see cref="State"/> is one of <see cref="CardImportStates"/>, <see cref="Done"/>
/// counts the photos of its plan handled so far (failures included), <see cref="User"/> and <see cref="ClientName"/>
/// say who imports it.
/// </summary>
public sealed record CardEvent(Guid ImportId, string Card, string State, int Done, int Total, int Failed, string User, string? ClientName) : ServerEvent;
/// <summary>States of a card import report and of its <see cref="CardEvent"/>.</summary>
public static class CardImportStates
{
public const string Started = "started";
public const string Progress = "progress";
/// <summary>The import ended: every photo handled, or fewer when it stopped early.</summary>
public const string Finished = "finished";
public static bool IsKnown(string? state) => state is Started or Progress or Finished;
}
public sealed record NodeStateEvent(Guid NodeId, string ClientName, string State) : ServerEvent;
+1
View File
@@ -35,6 +35,7 @@ namespace Titano.Protocol;
[JsonSerializable(typeof(ChunkReceived))]
[JsonSerializable(typeof(CompleteUploadResponse))]
[JsonSerializable(typeof(UploadState))]
[JsonSerializable(typeof(CardImportReport))]
[JsonSerializable(typeof(JobDto))]
[JsonSerializable(typeof(Page<JobDto>))]
[JsonSerializable(typeof(CreateJobRequest))]
+7
View File
@@ -17,6 +17,13 @@ public sealed record CompleteUploadResponse(Guid FrameId, Guid SequenceId, int I
/// <summary><c>GET /api/v1/uploads/{id}</c>: resume state.</summary>
public sealed record UploadState(Guid UploadId, string FileName, long Size, string Sha256, int ChunkSize, IReadOnlyList<int> Received, string State);
/// <summary>
/// <c>POST /api/v1/uploads/cards</c>: a client importing a card into the server through these uploads reports its start,
/// progress and end (BRIEF §14.4); the server tells every connected client with a <see cref="CardEvent"/> (BRIEF §14.3).
/// <see cref="ImportId"/> is the client's import plan, <see cref="Card"/> the card's name as the client shows it.
/// </summary>
public sealed record CardImportReport(Guid ImportId, string Card, string State, int Done, int Total, int Failed);
/// <summary>
/// <c>POST /api/v1/sequences/{id}/renders</c>: a client offers one of its renders of the sequence (BRIEF §14.5,
/// renders are uploaded on request). The render keeps its id on the server, so both sides recognise it; when the
+4 -3
View File
@@ -42,15 +42,16 @@ public static class SequenceEndpoints
sequences.MapGet("/{id:guid}/analysis/report", ReportAsync).Requires(Permissions.Read);
sequences.MapGet("/{id:guid}/stats", StatsAsync).Requires(Permissions.Read);
sequences.MapGet("/{id:guid}/renders", RendersAsync).Requires(Permissions.Read);
// Renders made on a client, sent on request (BRIEF §14.5); chunks go through /uploads.
// Renders made on a client, sent on request (BRIEF §14.5) by the sync of an editor's copy; chunks go through /uploads.
// Edit, not Upload: render outputs count against no quota, so an upload-only account cannot add them.
sequences.MapPost("/{id:guid}/renders", async (HttpContext c, Caller caller, Guid id, RenderUploadRequest request, RenderUploads uploads) =>
(await uploads.StartAsync(caller, id, request, c.RequestAborted)).ToResult(c, r => Results.Json(r, ProtocolJson.Default.StartUploadResponse,
statusCode: r.AlreadyExists ? StatusCodes.Status200OK : StatusCodes.Status201Created))).Requires(Permissions.Upload | Permissions.Edit);
statusCode: r.AlreadyExists ? StatusCodes.Status200OK : StatusCodes.Status201Created))).Requires(Permissions.Edit);
sequences.MapPost("/{id:guid}/renders/{uploadId:guid}/complete", async (HttpContext c, Caller caller, Guid id, Guid uploadId, RenderUploads uploads,
IHostApplicationLifetime lifetime) =>
// The commit runs to the end even if the client disconnects meanwhile.
(await uploads.CompleteAsync(caller, id, uploadId, lifetime.ApplicationStopping)).ToResult(c, r => Results.Json(r, ProtocolJson.Default.RenderDto)))
.Requires(Permissions.Upload | Permissions.Edit);
.Requires(Permissions.Edit);
}
private static async Task<IResult> ListAsync(HttpContext context, TitanoDatabase db, ServerArchive archive, int? year, string? camera, string? status,
+26 -6
View File
@@ -1,7 +1,5 @@
using Microsoft.AspNetCore.Http.Features;
using Titano.Core.Model;
using Titano.Protocol;
using Titano.Server.Configuration;
using Titano.Server.Security;
using Titano.Server.Storage;
@@ -9,10 +7,13 @@ namespace Titano.Server.Api;
/// <summary>
/// <c>/api/v1/uploads</c> (BRIEF §14.4). Chunk, state and cancel calls also serve render nodes uploading their output,
/// which start and complete through the node endpoints.
/// which start and complete through the node endpoints. <c>POST /uploads/cards</c> takes the reports of a card import a
/// client streams through these uploads and tells every connected client (BRIEF §14.3 <c>cardEvent</c>).
/// </summary>
public static class UploadEndpoints
{
private const int MaxCardName = 200;
public static void Map(RouteGroupBuilder api)
{
var uploads = api.MapGroup("/uploads").Requires(Permissions.Upload | Permissions.RenderNode);
@@ -25,6 +26,7 @@ public static class UploadEndpoints
uploads.MapPost("/{id:guid}/complete", async (HttpContext context, Caller caller, Guid id, UploadService service) =>
(await service.CompleteAsync(caller, id)).ToResult(context, r => Results.Json(r, ProtocolJson.Default.CompleteUploadResponse)))
.Requires(Permissions.Upload);
uploads.MapPost("/cards", ReportCard).Requires(Permissions.Upload);
}
private static async Task<IResult> StartAsync(HttpContext context, Caller caller, StartUploadRequest request, UploadService service)
@@ -34,10 +36,28 @@ public static class UploadEndpoints
statusCode: r.AlreadyExists ? StatusCodes.Status200OK : StatusCodes.Status201Created));
}
private static async Task<IResult> ChunkAsync(HttpContext context, Caller caller, Guid id, int index, UploadService service, ServerOptions options)
/// <summary>
/// A card import's start, progress or end, published as a <see cref="CardEvent"/> naming who imports it; 204, also for
/// progress dropped because it came within a second of the last (<see cref="UploadService.PublishCard"/>).
/// </summary>
private static IResult ReportCard(HttpContext context, Caller caller, CardImportReport report, UploadService service)
{
if (report.ImportId == Guid.Empty) return ApiErrors.BadRequest(context, "bad_request", "importId");
var card = report.Card?.Trim();
if (string.IsNullOrEmpty(card) || card.Length > MaxCardName || card.Any(char.IsControl)) return ApiErrors.BadRequest(context, "bad_request", "card");
if (!CardImportStates.IsKnown(report.State)) return ApiErrors.BadRequest(context, "bad_request", "state");
if (report.Total < 0 || report.Done < 0 || report.Done > report.Total || report.Failed < 0 || report.Failed > report.Total)
return ApiErrors.BadRequest(context, "bad_request", "done");
return service.PublishCard(caller, new CardEvent(report.ImportId, card, report.State, report.Done, report.Total, report.Failed, caller.User.Username,
caller.ClientName)).ToResult(context, _ => Results.NoContent());
}
/// <summary>
/// Chunks are the only large request bodies; every other endpoint keeps Kestrel's small default limit. The service
/// raises it to the chunk size of this upload (fixed when it started) before it reads the body.
/// </summary>
private static async Task<IResult> ChunkAsync(HttpContext context, Caller caller, Guid id, int index, UploadService service)
{
// Chunks are the only large request bodies; every other endpoint keeps Kestrel's small default limit.
if (context.Features.Get<IHttpMaxRequestBodySizeFeature>() is { IsReadOnly: false } limit) limit.MaxRequestBodySize = options.ChunkSizeBytes;
var outcome = await service.ReceiveChunkAsync(caller, id, index, context.Request, context.RequestAborted);
return outcome.ToResult(context, r => Results.Json(r, ProtocolJson.Default.ChunkReceived));
}
+16 -4
View File
@@ -1,3 +1,4 @@
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Repositories;
using Titano.Server.Configuration;
@@ -8,7 +9,8 @@ namespace Titano.Server.Storage;
/// Upload housekeeping (BRIEF §14.4): at start, uploads a crash left half-committed are settled; then every half hour
/// abandoned uploads expire, orphaned partial and staging files are removed, old upload records and dead tokens purged.
/// </summary>
public sealed class UploadMaintenance(TitanoDatabase db, ServerOptions options, UploadStore store, TimeProvider time, ILogger<UploadMaintenance> logger)
public sealed class UploadMaintenance(TitanoDatabase db, ServerOptions options, ServerArchive archive, UploadStore store, TimeProvider time,
ILogger<UploadMaintenance> logger)
: BackgroundService
{
private static readonly TimeSpan Interval = TimeSpan.FromMinutes(30);
@@ -44,14 +46,15 @@ public sealed class UploadMaintenance(TitanoDatabase db, ServerOptions options,
}
/// <summary>
/// Uploads left committing by a crash: committed when the frame with their hash exists, otherwise back to receiving
/// (the partial file is intact, so the client simply completes again).
/// Uploads left committing by a crash: committed when an intact frame stands for their content as at the start of an
/// upload (<see cref="UploadRules.StandIn"/>), otherwise back to receiving (the partial file is intact, so the client
/// simply completes again and the ingest files or repairs it).
/// </summary>
public async Task RecoverAsync(CancellationToken cancellationToken)
{
foreach (var upload in await db.Uploads.ListByStateAsync(UploadState.Committing, cancellationToken))
{
var frame = upload.JobId is null ? (await db.Frames.FindBySha256Async(upload.Sha256, cancellationToken)).FirstOrDefault() : null;
var frame = upload.JobId is null ? await StandInAsync(upload, cancellationToken) : null;
if (frame is not null)
{
await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Committed, frame.Id, cancellationToken);
@@ -65,6 +68,15 @@ public sealed class UploadMaintenance(TitanoDatabase db, ServerOptions options,
}
}
/// <summary>The intact frame that settles an interrupted commit, or null when the client must complete it again.</summary>
private async Task<Frame?> StandInAsync(Upload upload, CancellationToken cancellationToken)
{
var copies = await db.Frames.FindBySha256Async(upload.Sha256, cancellationToken);
if (copies.Count == 0) return null;
var target = await UploadRules.TargetAsync(db, archive.Id, upload.SequenceId, upload.SessionKey, upload.UserId, cancellationToken);
return UploadRules.StandIn(archive.Root, copies, target);
}
public async Task SweepAsync(CancellationToken cancellationToken)
{
var now = time.GetUtcNow();
+37
View File
@@ -1,3 +1,6 @@
using Titano.Core.Model;
using Titano.Data;
namespace Titano.Server.Storage;
/// <summary>Validation shared by frame and render uploads.</summary>
@@ -30,6 +33,40 @@ public static class UploadRules
return received;
}
/// <summary>The frame's original is in the archive with its recorded size.</summary>
public static bool IsOnDisk(string archiveRoot, Frame frame) =>
ArchivePathGuard.ExistingFile(archiveRoot, frame.RelativePath) is { } file && file.Length == frame.Size;
/// <summary>
/// Not flagged missing or corrupt, and <see cref="IsOnDisk"/>: the copy holds its content, so it may stand for an upload
/// of the same content; a damaged one is repaired by uploading the content again.
/// </summary>
public static bool IsIntact(string archiveRoot, Frame frame) =>
(frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) == 0 && IsOnDisk(archiveRoot, frame);
/// <summary>
/// The frame that stands for an upload of content the archive already has (<paramref name="copies"/>): an intact copy,
/// the one in the upload's <paramref name="target"/> sequence first. Null when there is none, or when the target holds
/// the content only in damaged copies: the upload's bytes repair them, whatever other sequences hold.
/// </summary>
public static Frame? StandIn(string archiveRoot, IReadOnlyList<Frame> copies, Guid? target)
{
var intact = copies.Where(f => IsIntact(archiveRoot, f)).ToList();
if (copies.Any(f => f.SequenceId == target) && !intact.Any(f => f.SequenceId == target)) return null;
return intact.FirstOrDefault(f => f.SequenceId == target) ?? intact.FirstOrDefault();
}
/// <summary>
/// The sequence an upload files into: its own, or the one its session key names (the user's own key without one);
/// null while that sequence does not exist yet.
/// </summary>
public static async Task<Guid?> TargetAsync(TitanoDatabase db, Guid archiveId, Guid? sequenceId, string? sessionKey, Guid userId,
CancellationToken cancellationToken) =>
sequenceId ?? await db.Sequences.FindBySessionKeyAsync(archiveId, SessionKeyOf(sessionKey, userId), cancellationToken).ConfigureAwait(false);
/// <summary>The session key an upload without a sequence is grouped by: the client's, or one per user.</summary>
public static string SessionKeyOf(string? sessionKey, Guid userId) => sessionKey ?? "user-" + userId.ToString("N");
/// <summary>Free bytes on the volume holding <paramref name="path"/>, or null when the platform cannot tell.</summary>
public static long? FreeBytes(string path)
{
+73 -15
View File
@@ -1,5 +1,6 @@
using System.Collections.Concurrent;
using System.Globalization;
using Microsoft.AspNetCore.Http.Features;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Data.Repositories;
@@ -15,9 +16,10 @@ using UploadStateDto = Titano.Protocol.UploadState;
namespace Titano.Server.Storage;
/// <summary>
/// Chunked, resumable, hash-verified frame uploads (BRIEF §14.4): start (short-circuit on a known SHA-256, resume an
/// unfinished upload, quota and disk checks), idempotent chunks, and completion that stages the file on the archive
/// volume, verifies its hash and hands it to <see cref="IArchiveIngest"/>.
/// Chunked, resumable, hash-verified frame uploads (BRIEF §14.4): start (short-circuit on a known SHA-256 held by an
/// intact frame, resume an unfinished upload, quota and disk checks), idempotent chunks, and completion that stages the
/// file on the archive volume, verifies its hash and hands it to <see cref="IArchiveIngest"/>, which repairs a missing or
/// damaged frame of that content (no quota is charged for a repair: the archive already counts those bytes).
/// </summary>
public sealed class UploadService(
TitanoDatabase db,
@@ -34,7 +36,14 @@ public sealed class UploadService(
/// <summary>Space kept free on the upload volume beyond the announced size.</summary>
private const long DiskReserve = 64L * 1024 * 1024;
/// <summary>Card events one account may publish per minute: progress once a second leaves room for every start and end.</summary>
private const int CardEventsPerMinute = 120;
private static readonly TimeSpan CardProgressInterval = TimeSpan.FromSeconds(1);
private static readonly TimeSpan CardEventWindow = TimeSpan.FromMinutes(1);
private readonly ConcurrentDictionary<Guid, int> _chunksInFlight = new();
private readonly ConcurrentDictionary<Guid, CardEvents> _cardEvents = new();
public async Task<Outcome<StartUploadResponse>> StartAsync(Caller caller, StartUploadRequest request, CancellationToken cancellationToken)
{
@@ -43,22 +52,23 @@ public sealed class UploadService(
if (request.Size <= 0) return Fail<StartUploadResponse>(400, "bad_request", "size");
if (request.Size > options.MaxUploadBytes) return Fail<StartUploadResponse>(413, "too_large", options.MaxUploadBytes.ToString(CultureInfo.InvariantCulture));
if (request.SessionKey is { Length: > 200 }) return Fail<StartUploadResponse>(400, "bad_request", "sessionKey");
if (request.SequenceId is { } target && await db.Sequences.GetAsync(target, cancellationToken) is null)
if (request.SequenceId is { } requested && await db.Sequences.GetAsync(requested, cancellationToken) is null)
return Fail<StartUploadResponse>(404, "not_found", "sequence");
var sha = request.Sha256.ToLowerInvariant();
var known = await db.Frames.FindBySha256Async(sha, cancellationToken);
if (known.Count > 0)
{
var frame = known.FirstOrDefault(f => f.SequenceId == request.SequenceId) ?? known[0];
return new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, frame.Id);
}
var sessionKey = string.IsNullOrWhiteSpace(request.SessionKey) ? null : request.SessionKey.Trim();
var copies = await db.Frames.FindBySha256Async(sha, cancellationToken);
var target = copies.Count == 0 ? null : await UploadRules.TargetAsync(db, archive.Id, request.SequenceId, sessionKey, caller.Id, cancellationToken);
// Only a copy that is still whole stands for the upload: a client may delete its file on this answer.
if (UploadRules.StandIn(archive.Root, copies, target) is { } known)
return new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, known.Id);
var resumable = await db.Uploads.FindReceivingAsync(caller.Id, sha, cancellationToken);
if (resumable is not null && resumable.Size == request.Size && resumable.SequenceId == request.SequenceId && store.Exists(resumable.Id))
return Started(resumable);
if (caller.User.QuotaBytes > 0)
// A repair puts back bytes the archive already counts: no quota for it.
if (caller.User.QuotaBytes > 0 && !copies.Any(f => f.SequenceId == target))
{
var pending = await db.Uploads.PendingBytesAsync(caller.Id, cancellationToken);
if (caller.User.UsedBytes + pending + request.Size > caller.User.QuotaBytes)
@@ -81,7 +91,7 @@ public sealed class UploadService(
State = UploadState.Receiving,
Created = now,
UpdatedAt = now,
SessionKey = string.IsNullOrWhiteSpace(request.SessionKey) ? null : request.SessionKey.Trim(),
SessionKey = sessionKey,
}, cancellationToken);
store.Create(upload.Id, upload.Size);
return Started(upload);
@@ -97,6 +107,8 @@ public sealed class UploadService(
var expected = Math.Min(upload.ChunkSize, upload.Size - (long)index * upload.ChunkSize);
if (request.ContentLength is { } announced && announced != expected) return Fail<ChunkReceived>(400, "chunk_size", expected.ToString(CultureInfo.InvariantCulture));
if (upload.HasChunk(index)) return new ChunkReceived(index, UploadRules.ReceivedChunks(upload));
// The upload keeps the chunk size it started with: a smaller setting since a restart must not refuse its chunks (413).
if (request.HttpContext.Features.Get<IHttpMaxRequestBodySizeFeature>() is { IsReadOnly: false } limit) limit.MaxRequestBodySize = upload.ChunkSize;
if (_chunksInFlight.AddOrUpdate(caller.Id, 1, (_, n) => n + 1) > options.ConcurrentChunksPerUser)
{
@@ -154,7 +166,7 @@ public sealed class UploadService(
return Fail<CompleteUploadResponse>(409, "upload_state");
var user = await db.Users.GetAsync(caller.Id, stopping);
if (user is { QuotaBytes: > 0 } && user.UsedBytes + upload.Size > user.QuotaBytes)
if (user is { QuotaBytes: > 0 } && user.UsedBytes + upload.Size > user.QuotaBytes && !await HeldByTargetAsync(upload, stopping))
{
await FailAsync(upload);
return Fail<CompleteUploadResponse>(403, "quota_exceeded", user.QuotaBytes.ToString(CultureInfo.InvariantCulture));
@@ -170,7 +182,7 @@ public sealed class UploadService(
archive.Id,
upload.SequenceId,
NewSequenceTitle: null,
upload.SequenceId is null ? upload.SessionKey ?? "user-" + caller.Id.ToString("N") : null,
upload.SequenceId is null ? UploadRules.SessionKeyOf(upload.SessionKey, caller.Id) : null,
staged,
upload.FileName,
upload.Size,
@@ -190,7 +202,7 @@ public sealed class UploadService(
await db.Uploads.TryTransitionAsync(id, UploadState.Committing, UploadState.Committed, result.FrameId, CancellationToken.None);
store.Delete(id);
if (File.Exists(staged)) UploadStore.TryDelete(staged);
if (!result.Duplicate) await db.Users.AddUsedBytesAsync(caller.Id, upload.Size, CancellationToken.None);
if (!result.Duplicate && !result.Repaired) await db.Users.AddUsedBytesAsync(caller.Id, upload.Size, CancellationToken.None);
if (await db.Sequences.GetAsync(result.SequenceId, CancellationToken.None) is { } sequence)
{
await sequenceJobs.FramesAddedAsync(sequence, CancellationToken.None);
@@ -199,6 +211,32 @@ public sealed class UploadService(
return new CompleteUploadResponse(result.FrameId, result.SequenceId, result.Index);
}
/// <summary>
/// Tells every connected client about a card import (BRIEF §14.3 <c>cardEvent</c>), so one account cannot crowd their
/// event queues: its progress goes out at most once a second (a report sooner is dropped, the next one replaces it as
/// on the client), and at most 120 of its events a minute (429 beyond). False when the report was dropped.
/// </summary>
public Outcome<bool> PublishCard(Caller caller, CardEvent card)
{
var now = time.GetUtcNow();
var sent = _cardEvents.GetOrAdd(caller.Id, _ => new CardEvents());
lock (sent.Gate)
{
var progress = card.State == CardImportStates.Progress;
if (progress && now - sent.LastProgress < CardProgressInterval) return false;
while (sent.Recent.Count > 0 && now - sent.Recent.Peek() >= CardEventWindow) sent.Recent.Dequeue();
if (sent.Recent.Count >= CardEventsPerMinute)
{
var wait = Math.Max(1, (int)Math.Ceiling((CardEventWindow - (now - sent.Recent.Peek())).TotalSeconds));
return Fail<bool>(429, "rate_limited", wait.ToString(CultureInfo.InvariantCulture));
}
sent.Recent.Enqueue(now);
if (progress) sent.LastProgress = now;
}
events.Publish(card);
return true;
}
/// <summary>
/// Copies a fully received upload to the archive staging folder and checks its SHA-256. On a mismatch the upload
/// fails, its files are deleted and null is returned; the client starts over.
@@ -230,6 +268,18 @@ public sealed class UploadService(
store.Delete(upload.Id);
}
/// <summary>
/// The sequence the upload files into holds its content already: filing it adds no bytes (an intact copy makes it a
/// duplicate, a damaged one is repaired with it).
/// </summary>
private async Task<bool> HeldByTargetAsync(Upload upload, CancellationToken cancellationToken)
{
var copies = await db.Frames.FindBySha256Async(upload.Sha256, cancellationToken);
if (copies.Count == 0) return false;
var target = await UploadRules.TargetAsync(db, archive.Id, upload.SequenceId, upload.SessionKey, upload.UserId, cancellationToken);
return copies.Any(f => f.SequenceId == target);
}
private StartUploadResponse Started(Upload upload) =>
new(upload.Id, upload.ChunkSize, UploadRules.ReceivedChunks(upload), AlreadyExists: false, FrameId: null);
@@ -239,4 +289,12 @@ public sealed class UploadService(
}
private static Outcome<T> Fail<T>(int status, string code, string? details = null) => Outcome<T>.Fail(status, code, details);
/// <summary>The card events one account published lately.</summary>
private sealed class CardEvents
{
public Lock Gate { get; } = new();
public Queue<DateTimeOffset> Recent { get; } = new();
public DateTimeOffset LastProgress { get; set; } = DateTimeOffset.MinValue;
}
}
+40 -4
View File
@@ -7,8 +7,8 @@ using Titano.Core.Localization;
namespace Titano.Tools.Commands;
/// <summary>
/// <c>i18n check</c>: completeness of <c>en</c> and <c>it</c>, placeholder parity, length budgets and that
/// every key used in code/XAML/admin JS exists (BRIEF §16).
/// <c>i18n check</c>: completeness of <c>en</c> and <c>it</c>, placeholder parity, length budgets, that every key
/// used in code/XAML/admin JS exists and that every error code the server answers with has its message (BRIEF §16).
/// <c>i18n export --out dir</c>: one JSON per culture for the web admin.
/// <c>i18n missing --culture xx [--all]</c>: untranslated (or all) keys as TSV for a translator or reviewer.
/// <c>i18n import --culture xx file.tsv</c>: merges translated <c>key&lt;TAB&gt;text</c> rows into the culture's resx files.
@@ -95,6 +95,8 @@ internal sealed partial class I18nCommand : ICommand
if (en.Keys.Any(k => k.StartsWith(key + ".", StringComparison.Ordinal) && PluralSuffix().IsMatch(k[(key.Length + 1)..]))) continue;
errors.Add($"{Path.GetRelativePath(root, file)}: unknown key {key}");
}
foreach (var (file, code, key) in MissingErrorMessages(root, en.Keys.ToHashSet(StringComparer.Ordinal)))
errors.Add($"{Path.GetRelativePath(root, file)}: error code {code} has no message {key}");
foreach (var w in warnings.Take(50)) Console.WriteLine("warning: " + w);
if (warnings.Count > 50) Console.WriteLine($"warning: … {warnings.Count - 50} more");
@@ -286,8 +288,7 @@ internal sealed partial class I18nCommand : ICommand
var src = Path.Combine(root, "src");
foreach (var file in Directory.EnumerateFiles(src, "*.*", SearchOption.AllDirectories))
{
if (file.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal)
|| file.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal)) continue;
if (IsBuildOutput(file)) continue;
var ext = Path.GetExtension(file);
Regex? regex = ext switch
{
@@ -307,9 +308,44 @@ internal sealed partial class I18nCommand : ICommand
}
}
/// <summary>
/// Error codes of the server (literals passed to <c>ApiErrors</c>, <c>Outcome.Fail</c> and the local <c>Fail</c> and
/// <c>TooMany</c> helpers) whose message <c>Server.Error.&lt;Code&gt;</c> is not in <paramref name="keys"/>, each once.
/// <c>ApiErrors.Message</c> builds that key at run time, so the scan of used keys cannot see it.
/// </summary>
internal static IEnumerable<(string File, string Code, string Key)> MissingErrorMessages(string root, IReadOnlySet<string> keys)
{
var reported = new HashSet<string>(StringComparer.Ordinal);
var server = Path.Combine(root, "src", "Titano.Server");
foreach (var file in Directory.EnumerateFiles(server, "*.cs", SearchOption.AllDirectories).Order(StringComparer.Ordinal))
{
if (IsBuildOutput(file)) continue;
foreach (var code in ErrorCodes(File.ReadAllText(file)))
{
var key = ErrorKey(code);
if (!keys.Contains(key) && reported.Add(code)) yield return (file, code, key);
}
}
}
/// <summary>The literal error codes (snake_case) a C# source passes to the server's error helpers.</summary>
internal static IEnumerable<string> ErrorCodes(string source) => ErrorCodeRegex().Matches(source).Select(m => m.Groups[1].Value);
/// <summary>The message key of an error code, built like <c>ApiErrors.Message</c>: <c>render_exists</c> → <c>Server.Error.RenderExists</c>.</summary>
internal static string ErrorKey(string code) =>
"Server.Error." + string.Concat(code.Split('_', StringSplitOptions.RemoveEmptyEntries).Select(part => char.ToUpperInvariant(part[0]) + part[1..]));
private static bool IsBuildOutput(string file) =>
file.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal)
|| file.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal);
[GeneratedRegex(@"\{(\d+)(?:[,:][^}]*)?\}")]
private static partial Regex PlaceholderRegex();
/// <summary>A call of an error helper up to its first string argument (no statement end in between) when that is a snake_case code.</summary>
[GeneratedRegex(@"(?:\bApiErrors\.(?:Result|WriteAsync|BadRequest|Conflict|Message)|\bFail(?:<[^;()]*?>)?|\bTooMany)\([^;""]*?""([a-z][a-z0-9_]*)""")]
private static partial Regex ErrorCodeRegex();
[GeneratedRegex(@"\b(?:L|Plural|Loc\.Get|LocKey)\(\s*""([A-Z][A-Za-z0-9]*\.[A-Za-z0-9_.]+)""")]
private static partial Regex CsKeyRegex();
+5 -4
View File
@@ -40,7 +40,8 @@ public interface IUploadEngine : INotifyPropertyChanged
/// <summary>
/// Works through the <see cref="UploadQueue"/> with <see cref="Parallelism"/> concurrent files: hash, upload
/// (resumable chunks; the server verifies the SHA-256), then optionally delete the source the server confirmed.
/// (resumable chunks; the server verifies the SHA-256), then optionally delete the source whose bytes the server
/// received and verified. A file the server already held is kept: no copy of it was verified on this run.
/// Lives on the UI thread: state changes happen there while hashing and HTTP run on the thread pool.
/// </summary>
public sealed class UploadEngine : IUploadEngine, IDisposable
@@ -221,7 +222,7 @@ public sealed class UploadEngine : IUploadEngine, IDisposable
item.State = outcome == UploadOutcome.Verified ? UploadItemState.Verified : UploadItemState.Skipped;
_queue.OnChanged();
ItemConfirmed?.Invoke(this, item);
if (_deleteAfterUpload()) DeleteConfirmedSource(item);
if (outcome == UploadOutcome.Verified && _deleteAfterUpload()) DeleteConfirmedSource(item);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
@@ -312,8 +313,8 @@ public sealed class UploadEngine : IUploadEngine, IDisposable
}
/// <summary>
/// BRIEF §0.2 rule 8: deletes only a file the server confirmed by hash, and only when it is still exactly the
/// bytes that were hashed (same size and write time).
/// BRIEF §0.2 rule 8: deletes only a file whose bytes the server received and verified by hash before committing
/// them, and only when it is still exactly the bytes that were hashed (same size and write time).
/// </summary>
private static void DeleteConfirmedSource(UploadItem item)
{