diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx
index 441e327a..84cf4086 100644
--- a/i18n/en/Server.resx
+++ b/i18n/en/Server.resx
@@ -77,6 +77,7 @@
The proxy is smaller than this archive's proxies.long
This upload would exceed your quota.long
Too many attempts; wait a minute and try again.long
+ This render is already filed under another sequence.long
Choose a password different from the current one.long
You cannot do this to your own account.long
A job is working on this sequence or its archive; try again when it is free.long
diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx
index de2bba4d..b0aa9af3 100644
--- a/i18n/it/Server.it.resx
+++ b/i18n/it/Server.it.resx
@@ -75,6 +75,7 @@
Il proxy è più piccolo dei proxy di questo archivio.
Questo caricamento supererebbe la tua quota.
Troppi tentativi; attendi un minuto e riprova.
+ Questo render è già archiviato in un'altra sequenza.
Scegli una password diversa da quella attuale.
Non puoi farlo sul tuo account.
Un'attività sta lavorando su questa sequenza o sul suo archivio; riprova quando è libera.
diff --git a/src/Titano.App/Import/ServerImportSink.cs b/src/Titano.App/Import/ServerImportSink.cs
index d65b352e..f05584fa 100644
--- a/src/Titano.App/Import/ServerImportSink.cs
+++ b/src/Titano.App/Import/ServerImportSink.cs
@@ -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
/// 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.
///
public sealed class ServerImportSink(TitanoClient client, string stagingDirectory) : IImportSink
{
@@ -25,6 +26,27 @@ public sealed class ServerImportSink(TitanoClient client, string stagingDirector
/// Every file committed or refused so far, by card path; pass it to .
public ImportSinkReport Report { get; } = new();
+ ///
+ /// Runs a confirmed plan into the server through this sink () and tells the server's
+ /// other clients about it as (BRIEF §14.3 cardEvent): started, its progress, and
+ /// finished, also when it stopped early.
+ ///
+ public async Task RunAsync(ImportPlan plan, string card, bool verify, IProgress? 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> CommitAsync(PlannedSession session, IReadOnlyList files, CancellationToken cancellationToken)
{
var results = new List(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;
}
+
+///
+/// The reports of one card import into the server (BRIEF §14.3 cardEvent, §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.
+///
+/// Photos of the plan, skipped ones included (like ).
+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 _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);
+
+ /// Progress that reaches (the screen's own) and these reports.
+ public IProgress Forward(IProgress? 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);
+ }
+
+ ///
+ /// Reports the end: every photo handled when the import gave an , 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.
+ ///
+ 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? inner) : IProgress
+ {
+ public void Report(ImportProgress value)
+ {
+ inner?.Report(value);
+ reporter.Report(value);
+ }
+ }
+}
diff --git a/src/Titano.App/Sections/ImportViewModel.cs b/src/Titano.App/Sections/ImportViewModel.cs
index e237ee84..96d76ba1 100644
--- a/src/Titano.App/Sections/ImportViewModel.cs
+++ b/src/Titano.App/Sections/ImportViewModel.cs
@@ -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 RunServerAsync(ImportPlan plan, ImportChoices choices, Uri address, string token, IProgress progress,
- CancellationToken ct)
+ private async Task RunServerAsync(ImportPlan plan, ImportChoices choices, string card, Uri address, string token,
+ IProgress 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
{
diff --git a/src/Titano.Core/Project/ProjectSettings.cs b/src/Titano.Core/Project/ProjectSettings.cs
index 9a52011a..d6c22280 100644
--- a/src/Titano.Core/Project/ProjectSettings.cs
+++ b/src/Titano.Core/Project/ProjectSettings.cs
@@ -174,6 +174,9 @@ public sealed record ProjectSettings
{
public const int CurrentVersion = 1;
+ /// Layout of a project edited as JSON (): indented like .
+ 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();
- /// Frame indices excluded from renders.
+ /// Frame indices excluded from renders (positions in capture order; see ).
public IReadOnlyList ExcludedFrames { get; init; } = [];
/// Index of the hero frame (sequence thumbnail).
@@ -237,6 +240,52 @@ public sealed record ProjectSettings
target[name] = value?.DeepClone();
}
}
+
+ ///
+ /// Moves the frame positions of a project — , and the
+ /// virtual-camera s — after frames were inserted before them: 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 is not a project object.
+ ///
+ public static string? MoveFramePositions(string json, IReadOnlyDictionary 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())
+ {
+ 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 replace, IReadOnlyDictionary moves)
+ {
+ if (position is not JsonValue value || !value.TryGetValue(out var old) || !moves.TryGetValue(old, out var now) || now == old) return false;
+ replace(JsonValue.Create(now));
+ return true;
+ }
}
[JsonSourceGenerationOptions(
diff --git a/src/Titano.Data/Archiving/ArchiveIndexer.cs b/src/Titano.Data/Archiving/ArchiveIndexer.cs
index ff13cb34..a85265da 100644
--- a/src/Titano.Data/Archiving/ArchiveIndexer.cs
+++ b/src/Titano.Data/Archiving/ArchiveIndexer.cs
@@ -91,18 +91,28 @@ public sealed class ArchiveIndexer
return new ScanSummary(folders.Count, indexed, adopted, removed, failed);
}
- /// Writes a sequence's sidecar into the index (row, frames, session keys) and records the folder stamps.
+ ///
+ /// 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 ().
+ ///
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);
+ }
+
+ ///
+ /// Applies 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 () 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.
+ ///
+ private async Task UpdateAndSyncAsync(Archive archive, ArchivePaths paths, SequencePaths sequence, Guid sequenceId,
+ Func 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;
+ }
}
/// Indexes one folder; returns the sidecar bytes when they were read and not rewritten since (for the snapshot).
@@ -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;
}
+ /// The index holds a project for this sequence and other frames than the sidecar: its positions may move.
+ private async Task MayMovePositionsAsync(SequenceManifest manifest, CancellationToken cancellationToken) =>
+ await _db.Sequences.GetAsync(manifest.Id, cancellationToken).ConfigureAwait(false) is { SettingsJson: not null } indexed
+ && indexed.FramesVersion != manifest.Versions.Frames;
+
/// A sidecar for a folder that has none; ids of a sequence the index already knew at this folder are kept.
private async Task AdoptAsync(SequencePaths sequence, Locations locations, CancellationToken cancellationToken)
{
diff --git a/src/Titano.Data/Archiving/ArchiveIngest.cs b/src/Titano.Data/Archiving/ArchiveIngest.cs
index 29a31c2a..750e260a 100644
--- a/src/Titano.Data/Archiving/ArchiveIngest.cs
+++ b/src/Titano.Data/Archiving/ArchiveIngest.cs
@@ -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.
///
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;
}
+ ///
+ /// A sequence created without photos (POST /api/v1/sequences, 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.
+ ///
+ 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;
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ 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();
+ }
+ }
+
+ /// A new folder for : the plan's folder or the archive's folder template, made unique.
+ private async Task 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);
+ }
+
/// The first free variant of , claimed by creating its sidecar (first writer wins).
private static SequencePaths ClaimFolder(ArchivePaths paths, string wanted, HashSet 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(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(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();
+ 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)(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;
}
- /// Appends the new rows when the index was in step with the sidecar; otherwise resyncs the whole sequence.
- private async Task IndexAsync(Archive archive, SequencePaths sequence, SequenceManifest manifest, int before, List appended,
- CancellationToken cancellationToken)
+ /// The frame still holds its content: not flagged missing or corrupt, and its file is there with its size.
+ 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;
+ }
+
+ ///
+ /// Puts a verified copy where a damaged frame's file belongs. A file still there (corrupt, or another size) moves aside
+ /// as name.damaged-<time>, 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.
+ ///
+ 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;
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ private async Task IndexAsync(Archive archive, SequencePaths sequence, SequenceManifest manifest, int before, List 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)
{
diff --git a/src/Titano.Data/Archiving/IArchiveIngest.cs b/src/Titano.Data/Archiving/IArchiveIngest.cs
index c8c1cb76..b21a4b0a 100644
--- a/src/Titano.Data/Archiving/IArchiveIngest.cs
+++ b/src/Titano.Data/Archiving/IArchiveIngest.cs
@@ -17,8 +17,12 @@ public sealed record IngestRequest(
DateTime? ClientCapturedAt,
Guid? UserId);
-/// The committed frame; when the sequence already held a frame with that SHA-256.
-public sealed record IngestResult(Guid SequenceId, Guid FrameId, int Index, string RelativePath, bool Duplicate);
+///
+/// The committed frame; 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, and the archive holds no more bytes than before.
+///
+public sealed record IngestResult(Guid SequenceId, Guid FrameId, int Index, string RelativePath, bool Duplicate, bool Repaired = false);
///
/// Commits staged files into the archive layout (originals folder, naming templates, sequence.json written
diff --git a/src/Titano.Data/Archiving/ProjectPositions.cs b/src/Titano.Data/Archiving/ProjectPositions.cs
new file mode 100644
index 00000000..8aefeab7
--- /dev/null
+++ b/src/Titano.Data/Archiving/ProjectPositions.cs
@@ -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;
+
+///
+/// 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.
+///
+internal static class ProjectPositions
+{
+ ///
+ /// The index's copy of the project (the one in force) and the same project with its positions moved to the order of
+ /// ; null when nothing moves. A project.json the index has no copy of was written by
+ /// another process against its own frames, so it is left to that writer.
+ ///
+ 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(manifest.Frames.Count);
+ foreach (var frame in manifest.Frames) now[frame.Id] = frame.I;
+ var moves = new Dictionary();
+ 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;
+ }
+
+ ///
+ /// Mirrors moved positions into project.json 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.
+ ///
+ 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);
+ }
+ }
+
+ /// Same JSON content whatever the layout (an index may store it normalised).
+ private static bool SameJson(string a, string b)
+ {
+ try
+ {
+ return JsonNode.DeepEquals(JsonNode.Parse(a), JsonNode.Parse(b));
+ }
+ catch (JsonException)
+ {
+ return false;
+ }
+ }
+}
diff --git a/src/Titano.Data/Repositories/FrameRepository.cs b/src/Titano.Data/Repositories/FrameRepository.cs
index cb10e5e7..f732b18d 100644
--- a/src/Titano.Data/Repositories/FrameRepository.cs
+++ b/src/Titano.Data/Repositories/FrameRepository.cs
@@ -10,6 +10,9 @@ public readonly record struct FrameIntegrity(Guid FrameId, FrameFlags Flags, str
/// A frame and the sequence it belongs to.
public readonly record struct FrameRef(Guid FrameId, Guid SequenceId);
+/// Where a frame stands in its sequence.
+public readonly record struct FramePosition(Guid FrameId, int Index);
+
/// A frame whose content (SHA-256) also exists elsewhere in the archive.
public sealed record DuplicateFrame(string Sha256, Guid FrameId, Guid SequenceId, int Index, string RelativePath);
@@ -66,6 +69,11 @@ public sealed class FrameRepository
public Task> FindBySha256Async(string sha256, CancellationToken cancellationToken = default) =>
_db.ListAsync($"SELECT {Columns} FROM frames WHERE sha256 = $1 ORDER BY sequence_id, idx", [sha256.ToLowerInvariant()], Map, cancellationToken);
+ /// Id and index of every frame of a sequence, in index order.
+ public Task> 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);
+
/// Writes analysis results for many frames in one transaction; returns the number of frames updated.
public Task UpdateLightStatsAsync(IReadOnlyList stats, CancellationToken cancellationToken = default) =>
_db.InTransactionAsync(async session =>
diff --git a/src/Titano.Protocol/Client/TitanoClient.cs b/src/Titano.Protocol/Client/TitanoClient.cs
index 2d8c3dfa..58c8ea60 100644
--- a/src/Titano.Protocol/Client/TitanoClient.cs
+++ b/src/Titano.Protocol/Client/TitanoClient.cs
@@ -192,6 +192,13 @@ public sealed class TitanoClient : IDisposable
return await RetryAsync(() => SendAsync(HttpMethod.Post, $"api/v1/uploads/{uploadId}/complete", ProtocolJson.Default.CompleteUploadResponse, ct), ct).ConfigureAwait(false);
}
+ ///
+ /// Reports a card import this client streams into the server (started, progress, finished); the server tells every
+ /// connected client with a (BRIEF §14.3).
+ ///
+ public Task ReportCardAsync(CardImportReport report, CancellationToken ct = default) =>
+ SendAsync(HttpMethod.Post, "api/v1/uploads/cards", report, ProtocolJson.Default.CardImportReport, ct);
+
///
/// Render node: uploads the output of a claimed job in resumable chunks, then completes the job; the server verifies
/// the SHA-256 in and files the render under the sequence's exports (BRIEF §14.7).
diff --git a/src/Titano.Protocol/Events.cs b/src/Titano.Protocol/Events.cs
index e149000c..c760510c 100644
--- a/src/Titano.Protocol/Events.cs
+++ b/src/Titano.Protocol/Events.cs
@@ -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;
+///
+/// A card import that a connected client streams into the server (BRIEF §14.4), as that client reported it
+/// (): is one of ,
+/// counts the photos of its plan handled so far (failures included), and
+/// say who imports it.
+///
+public sealed record CardEvent(Guid ImportId, string Card, string State, int Done, int Total, int Failed, string User, string? ClientName) : ServerEvent;
+
+/// States of a card import report and of its .
+public static class CardImportStates
+{
+ public const string Started = "started";
+ public const string Progress = "progress";
+
+ /// The import ended: every photo handled, or fewer when it stopped early.
+ 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;
diff --git a/src/Titano.Protocol/ProtocolJson.cs b/src/Titano.Protocol/ProtocolJson.cs
index 7af9a1b2..ab3ffa80 100644
--- a/src/Titano.Protocol/ProtocolJson.cs
+++ b/src/Titano.Protocol/ProtocolJson.cs
@@ -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))]
[JsonSerializable(typeof(CreateJobRequest))]
diff --git a/src/Titano.Protocol/Uploads.cs b/src/Titano.Protocol/Uploads.cs
index 3be2f2e7..6977ef12 100644
--- a/src/Titano.Protocol/Uploads.cs
+++ b/src/Titano.Protocol/Uploads.cs
@@ -17,6 +17,13 @@ public sealed record CompleteUploadResponse(Guid FrameId, Guid SequenceId, int I
/// GET /api/v1/uploads/{id}: resume state.
public sealed record UploadState(Guid UploadId, string FileName, long Size, string Sha256, int ChunkSize, IReadOnlyList Received, string State);
+///
+/// POST /api/v1/uploads/cards: 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 (BRIEF §14.3).
+/// is the client's import plan, the card's name as the client shows it.
+///
+public sealed record CardImportReport(Guid ImportId, string Card, string State, int Done, int Total, int Failed);
+
///
/// POST /api/v1/sequences/{id}/renders: 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
diff --git a/src/Titano.Server/Api/SequenceEndpoints.cs b/src/Titano.Server/Api/SequenceEndpoints.cs
index f3ec9993..2071c602 100644
--- a/src/Titano.Server/Api/SequenceEndpoints.cs
+++ b/src/Titano.Server/Api/SequenceEndpoints.cs
@@ -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 ListAsync(HttpContext context, TitanoDatabase db, ServerArchive archive, int? year, string? camera, string? status,
diff --git a/src/Titano.Server/Api/UploadEndpoints.cs b/src/Titano.Server/Api/UploadEndpoints.cs
index 92ccfa53..56755b08 100644
--- a/src/Titano.Server/Api/UploadEndpoints.cs
+++ b/src/Titano.Server/Api/UploadEndpoints.cs
@@ -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;
///
/// /api/v1/uploads (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. POST /uploads/cards takes the reports of a card import a
+/// client streams through these uploads and tells every connected client (BRIEF §14.3 cardEvent).
///
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 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 ChunkAsync(HttpContext context, Caller caller, Guid id, int index, UploadService service, ServerOptions options)
+ ///
+ /// A card import's start, progress or end, published as a naming who imports it; 204, also for
+ /// progress dropped because it came within a second of the last ().
+ ///
+ 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());
+ }
+
+ ///
+ /// 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.
+ ///
+ private static async Task 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() 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));
}
diff --git a/src/Titano.Server/Storage/UploadMaintenance.cs b/src/Titano.Server/Storage/UploadMaintenance.cs
index 3abe04c1..eedb4d82 100644
--- a/src/Titano.Server/Storage/UploadMaintenance.cs
+++ b/src/Titano.Server/Storage/UploadMaintenance.cs
@@ -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.
///
-public sealed class UploadMaintenance(TitanoDatabase db, ServerOptions options, UploadStore store, TimeProvider time, ILogger logger)
+public sealed class UploadMaintenance(TitanoDatabase db, ServerOptions options, ServerArchive archive, UploadStore store, TimeProvider time,
+ ILogger logger)
: BackgroundService
{
private static readonly TimeSpan Interval = TimeSpan.FromMinutes(30);
@@ -44,14 +46,15 @@ public sealed class UploadMaintenance(TitanoDatabase db, ServerOptions options,
}
///
- /// 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 (), otherwise back to receiving (the partial file is intact, so the client
+ /// simply completes again and the ingest files or repairs it).
///
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,
}
}
+ /// The intact frame that settles an interrupted commit, or null when the client must complete it again.
+ private async Task 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();
diff --git a/src/Titano.Server/Storage/UploadRules.cs b/src/Titano.Server/Storage/UploadRules.cs
index 9dd31eef..a25d82fa 100644
--- a/src/Titano.Server/Storage/UploadRules.cs
+++ b/src/Titano.Server/Storage/UploadRules.cs
@@ -1,3 +1,6 @@
+using Titano.Core.Model;
+using Titano.Data;
+
namespace Titano.Server.Storage;
/// Validation shared by frame and render uploads.
@@ -30,6 +33,40 @@ public static class UploadRules
return received;
}
+ /// The frame's original is in the archive with its recorded size.
+ public static bool IsOnDisk(string archiveRoot, Frame frame) =>
+ ArchivePathGuard.ExistingFile(archiveRoot, frame.RelativePath) is { } file && file.Length == frame.Size;
+
+ ///
+ /// Not flagged missing or corrupt, and : 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.
+ ///
+ public static bool IsIntact(string archiveRoot, Frame frame) =>
+ (frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) == 0 && IsOnDisk(archiveRoot, frame);
+
+ ///
+ /// The frame that stands for an upload of content the archive already has (): an intact copy,
+ /// the one in the upload's 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.
+ ///
+ public static Frame? StandIn(string archiveRoot, IReadOnlyList 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();
+ }
+
+ ///
+ /// 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.
+ ///
+ public static async Task 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);
+
+ /// The session key an upload without a sequence is grouped by: the client's, or one per user.
+ public static string SessionKeyOf(string? sessionKey, Guid userId) => sessionKey ?? "user-" + userId.ToString("N");
+
/// Free bytes on the volume holding , or null when the platform cannot tell.
public static long? FreeBytes(string path)
{
diff --git a/src/Titano.Server/Storage/UploadService.cs b/src/Titano.Server/Storage/UploadService.cs
index 327bd02d..22f799bc 100644
--- a/src/Titano.Server/Storage/UploadService.cs
+++ b/src/Titano.Server/Storage/UploadService.cs
@@ -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;
///
-/// 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 .
+/// 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 , which repairs a missing or
+/// damaged frame of that content (no quota is charged for a repair: the archive already counts those bytes).
///
public sealed class UploadService(
TitanoDatabase db,
@@ -34,7 +36,14 @@ public sealed class UploadService(
/// Space kept free on the upload volume beyond the announced size.
private const long DiskReserve = 64L * 1024 * 1024;
+ /// Card events one account may publish per minute: progress once a second leaves room for every start and end.
+ private const int CardEventsPerMinute = 120;
+
+ private static readonly TimeSpan CardProgressInterval = TimeSpan.FromSeconds(1);
+ private static readonly TimeSpan CardEventWindow = TimeSpan.FromMinutes(1);
+
private readonly ConcurrentDictionary _chunksInFlight = new();
+ private readonly ConcurrentDictionary _cardEvents = new();
public async Task> StartAsync(Caller caller, StartUploadRequest request, CancellationToken cancellationToken)
{
@@ -43,22 +52,23 @@ public sealed class UploadService(
if (request.Size <= 0) return Fail(400, "bad_request", "size");
if (request.Size > options.MaxUploadBytes) return Fail(413, "too_large", options.MaxUploadBytes.ToString(CultureInfo.InvariantCulture));
if (request.SessionKey is { Length: > 200 }) return Fail(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(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(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() 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(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(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);
}
+ ///
+ /// Tells every connected client about a card import (BRIEF §14.3 cardEvent), 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.
+ ///
+ public Outcome 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(429, "rate_limited", wait.ToString(CultureInfo.InvariantCulture));
+ }
+ sent.Recent.Enqueue(now);
+ if (progress) sent.LastProgress = now;
+ }
+ events.Publish(card);
+ return true;
+ }
+
///
/// 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);
}
+ ///
+ /// 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).
+ ///
+ private async Task 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 Fail(int status, string code, string? details = null) => Outcome.Fail(status, code, details);
+
+ /// The card events one account published lately.
+ private sealed class CardEvents
+ {
+ public Lock Gate { get; } = new();
+ public Queue Recent { get; } = new();
+ public DateTimeOffset LastProgress { get; set; } = DateTimeOffset.MinValue;
+ }
}
diff --git a/src/Titano.Tools/Commands/I18nCommand.cs b/src/Titano.Tools/Commands/I18nCommand.cs
index 49b0f02b..04cffe0b 100644
--- a/src/Titano.Tools/Commands/I18nCommand.cs
+++ b/src/Titano.Tools/Commands/I18nCommand.cs
@@ -7,8 +7,8 @@ using Titano.Core.Localization;
namespace Titano.Tools.Commands;
///
-/// i18n check: completeness of en and it, placeholder parity, length budgets and that
-/// every key used in code/XAML/admin JS exists (BRIEF §16).
+/// i18n check: completeness of en and it, 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).
/// i18n export --out dir: one JSON per culture for the web admin.
/// i18n missing --culture xx [--all]: untranslated (or all) keys as TSV for a translator or reviewer.
/// i18n import --culture xx file.tsv: merges translated key<TAB>text 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
}
}
+ ///
+ /// Error codes of the server (literals passed to ApiErrors, Outcome.Fail and the local Fail and
+ /// TooMany helpers) whose message Server.Error.<Code> is not in , each once.
+ /// ApiErrors.Message builds that key at run time, so the scan of used keys cannot see it.
+ ///
+ internal static IEnumerable<(string File, string Code, string Key)> MissingErrorMessages(string root, IReadOnlySet keys)
+ {
+ var reported = new HashSet(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);
+ }
+ }
+ }
+
+ /// The literal error codes (snake_case) a C# source passes to the server's error helpers.
+ internal static IEnumerable ErrorCodes(string source) => ErrorCodeRegex().Matches(source).Select(m => m.Groups[1].Value);
+
+ /// The message key of an error code, built like ApiErrors.Message: render_exists → Server.Error.RenderExists.
+ 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();
+ /// A call of an error helper up to its first string argument (no statement end in between) when that is a snake_case code.
+ [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();
diff --git a/src/Titano.Uploader/Uploads/UploadEngine.cs b/src/Titano.Uploader/Uploads/UploadEngine.cs
index a6f26697..b37cf888 100644
--- a/src/Titano.Uploader/Uploads/UploadEngine.cs
+++ b/src/Titano.Uploader/Uploads/UploadEngine.cs
@@ -40,7 +40,8 @@ public interface IUploadEngine : INotifyPropertyChanged
///
/// Works through the with 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.
///
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
}
///
- /// 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).
///
private static void DeleteConfirmedSource(UploadItem item)
{
diff --git a/tests/Titano.App.Tests/Import/ServerImportSinkTests.cs b/tests/Titano.App.Tests/Import/ServerImportSinkTests.cs
index 49d8f170..b957ad21 100644
--- a/tests/Titano.App.Tests/Import/ServerImportSinkTests.cs
+++ b/tests/Titano.App.Tests/Import/ServerImportSinkTests.cs
@@ -1,3 +1,4 @@
+using System.Collections.Concurrent;
using System.IO;
using System.Net;
using System.Net.Http;
@@ -113,7 +114,110 @@ public sealed class ServerImportSinkTests(TestContext context)
Assert.True(ImportPlans.Totals(unlimited, verify: true).HasEnoughSpace);
}
- /// Start, chunk and complete of BRIEF §14.4, plus the title update; the hash is checked at completion.
+ [Test]
+ public async Task AnImportIntoTheServerIsReportedAsCardEventsFromStartToFinish()
+ {
+ var card = Card(context.CreateTempDirectory("card"), 8, Start);
+ var staging = context.CreateTempDirectory("staging");
+ var server = new FakeUploadServer(chunkSize: 4096);
+ using var client = new TitanoClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
+ var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
+ var progress = new List();
+
+ var outcome = await new ServerImportSink(client, staging).RunAsync(plan, "EOS R5 · card A", true, new SyncProgress(progress.Add),
+ context.Cancellation);
+
+ Assert.True(outcome.IsComplete);
+ Assert.NotEmpty(progress);
+ var reports = server.Cards.ToList();
+ Assert.Equal(CardImportStates.Started, reports[0].State);
+ Assert.Equal((CardImportStates.Finished, plan.FileCount, plan.FileCount, 0), (reports[^1].State, reports[^1].Done, reports[^1].Total, reports[^1].Failed));
+ Assert.True(reports.All(r => r.ImportId == plan.Id && r.Card == "EOS R5 · card A"), "every report names the import");
+ Assert.True(reports.Skip(1).SkipLast(1).All(r => r.State == CardImportStates.Progress), "progress in between");
+ }
+
+ [Test]
+ public async Task AServerWithoutCardEventsStillTakesTheImport()
+ {
+ var card = Card(context.CreateTempDirectory("card"), 8, Start);
+ var staging = context.CreateTempDirectory("staging");
+ var server = new FakeUploadServer(chunkSize: 4096) { CardsUnsupported = true };
+ using var client = new TitanoClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
+ var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
+
+ var outcome = await new ServerImportSink(client, staging).RunAsync(plan, "EOS R5 · card A", true, null, context.Cancellation);
+
+ Assert.Equal(8, outcome.Copied);
+ Assert.Equal(1, server.CardAttempts, "a server that answers 404 gets no further reports");
+ }
+
+ [Test]
+ public async Task ReportsWaitingForASlowServerAreReplacedByNewerOnes()
+ {
+ var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var server = new FakeUploadServer(chunkSize: 4096) { CardGate = gate.Task };
+ using var client = new TitanoClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
+ var time = new ManualTime();
+ var reporter = new CardImportReporter(client, Guid.CreateVersion7(), "EOS R5 · card A", 100, time);
+
+ reporter.Started();
+ await server.CardArrived.Task.WaitAsync(TimeSpan.FromSeconds(10));
+ reporter.Report(Progress(10));
+ reporter.Report(Progress(20));
+ time.Advance(TimeSpan.FromSeconds(1));
+ reporter.Report(Progress(30));
+ var finished = reporter.FinishedAsync(null);
+ gate.SetResult();
+ await finished.WaitAsync(TimeSpan.FromSeconds(10));
+
+ // The start was on its way; progress 10 waited and was replaced by 30 (20 came within the second), then by the end.
+ Assert.SequenceEqual([(CardImportStates.Started, 0), (CardImportStates.Finished, 30)], server.Cards.Select(r => (r.State, r.Done)));
+ // Nothing follows the end, not even progress a second later.
+ time.Advance(TimeSpan.FromSeconds(1));
+ reporter.Report(Progress(40));
+ await reporter.FinishedAsync(null).WaitAsync(TimeSpan.FromSeconds(10));
+ Assert.Equal(2, server.CardAttempts);
+ }
+
+ [Test]
+ public async Task AnImportOverDoesNotWaitForAServerThatDoesNotAnswer()
+ {
+ var server = new FakeUploadServer(chunkSize: 4096) { CardGate = new TaskCompletionSource().Task };
+ using var client = new TitanoClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
+ var reporter = new CardImportReporter(client, Guid.CreateVersion7(), "EOS R5 · card A", 100);
+
+ reporter.Started();
+ await server.CardArrived.Task.WaitAsync(TimeSpan.FromSeconds(10));
+ var clock = System.Diagnostics.Stopwatch.StartNew();
+ await reporter.FinishedAsync(null).WaitAsync(TimeSpan.FromSeconds(8));
+
+ // The start hangs (each report would wait 10 s): the end gives both up after two seconds.
+ Assert.True(clock.Elapsed < TimeSpan.FromSeconds(6), $"finished after {clock.Elapsed}");
+ Assert.Empty(server.Cards);
+ for (var i = 0; i < 25 && server.CardAttempts < 2; i++) await Task.Delay(20);
+ Assert.Equal(1, server.CardAttempts, "the end was never sent once given up");
+ }
+
+ private static ImportProgress Progress(int done) => new(done, 100, done * 10L, 1000, done, 0, 0, null);
+
+ /// Reports synchronously (Progress<T> posts and may arrive late).
+ private sealed class SyncProgress(Action report) : IProgress
+ {
+ public void Report(T value) => report(value);
+ }
+
+ private sealed class ManualTime : TimeProvider
+ {
+ private long _ticks;
+
+ public override long TimestampFrequency => TimeSpan.TicksPerSecond;
+
+ public override long GetTimestamp() => Interlocked.Read(ref _ticks);
+
+ public void Advance(TimeSpan by) => Interlocked.Add(ref _ticks, by.Ticks);
+ }
+
+ /// Start, chunk and complete of BRIEF §14.4, plus the title update and card reports; the hash is checked at completion.
private sealed class FakeUploadServer(int chunkSize) : HttpMessageHandler
{
private readonly Dictionary _open = [];
@@ -130,9 +234,34 @@ public sealed class ServerImportSinkTests(TestContext context)
/// Answer 401 to new uploads once this many were committed (the sign-in expired).
public int? SignedOutAfter { get; init; }
+ /// Card reports taken, in order (they arrive on another thread than the uploads).
+ public ConcurrentQueue Cards { get; } = new();
+
+ public int CardAttempts => _cardAttempts;
+
+ /// A server from before card events: 404.
+ public bool CardsUnsupported { get; init; }
+
+ /// Card reports wait for this (a slow server); says when the first one is waiting.
+ public Task? CardGate { get; init; }
+
+ public TaskCompletionSource CardArrived { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+
+ private int _cardAttempts;
+
protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var path = request.RequestUri!.AbsolutePath.Trim('/').Split('/');
+ if (request.Method == HttpMethod.Post && path is ["api", "v1", "uploads", "cards"])
+ {
+ Interlocked.Increment(ref _cardAttempts);
+ if (CardsUnsupported) return new HttpResponseMessage(HttpStatusCode.NotFound);
+ var report = (await request.Content!.ReadFromJsonAsync(ProtocolJson.Default.CardImportReport, cancellationToken))!;
+ CardArrived.TrySetResult();
+ if (CardGate is { } gate) await gate.WaitAsync(cancellationToken);
+ Cards.Enqueue(report);
+ return new HttpResponseMessage(HttpStatusCode.NoContent);
+ }
if (request.Method == HttpMethod.Post && path is ["api", "v1", "uploads"])
{
var start = (await request.Content!.ReadFromJsonAsync(ProtocolJson.Default.StartUploadRequest, cancellationToken))!;
diff --git a/tests/Titano.App.Tests/Uploader/UploadEngineTests.cs b/tests/Titano.App.Tests/Uploader/UploadEngineTests.cs
index f2d940bb..0c6062fb 100644
--- a/tests/Titano.App.Tests/Uploader/UploadEngineTests.cs
+++ b/tests/Titano.App.Tests/Uploader/UploadEngineTests.cs
@@ -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");
});
diff --git a/tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs b/tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs
index 2536f475..2eb939f7 100644
--- a/tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs
+++ b/tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs
@@ -121,6 +121,52 @@ public sealed class ProjectSettingsTests
public void ProjectMustBeAnObject() =>
Assert.Throws(() => ProjectSettings.FromJson("[1, 2]"));
+ [Test]
+ public void FramePositionsFollowInsertedFramesAndOtherMembersStay()
+ {
+ var project = new ProjectSettings
+ {
+ ExcludedFrames = [3, 7, 40],
+ HeroFrame = 2,
+ Camera = new CameraSettings { Keyframes = [new CameraKey(0, 0.5, 0.5, 1, 0), new CameraKey(7, 0.4, 0.5, 1.5, 0)] },
+ Exposure = new ExposureSettings { DeflickerWindow = new Auto().WithManual(41) },
+ };
+ // Two frames inserted before position 3 and one before position 7; 40 is no frame of the old list and stays.
+ var moves = new Dictionary { [0] = 0, [1] = 1, [2] = 4, [3] = 5, [4] = 6, [5] = 7, [6] = 8, [7] = 10 };
+
+ var moved = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.MoveFramePositions(project.ToJson(), moves)));
+
+ Assert.SequenceEqual([5, 10, 40], moved.ExcludedFrames);
+ Assert.Equal(4, moved.HeroFrame);
+ Assert.SequenceEqual([0, 10], moved.Camera.Keyframes.Select(k => k.Frame));
+ Assert.Equal((0.4, 1.5), (moved.Camera.Keyframes[1].CenterX, moved.Camera.Keyframes[1].Zoom));
+ Assert.Equal(41, moved.Exposure.DeflickerWindow.Manual);
+ }
+
+ [Test]
+ public void MovingPositionsEditsTheJsonInPlace()
+ {
+ const string project = """{ "ExcludedFrames": [1, 2], "heroFrame": null, "futureOption": { "keep": [1, 2] }, "camera": { "keyframes": [ { "frame": 1.5 } ] } }""";
+
+ var moved = Assert.NotNull(ProjectSettings.MoveFramePositions(project, new Dictionary { [1] = 3 }));
+
+ var json = System.Text.Json.Nodes.JsonNode.Parse(moved)!;
+ Assert.SequenceEqual([3, 2], json["ExcludedFrames"]!.AsArray().Select(n => n!.GetValue()));
+ Assert.Equal("""{"keep":[1,2]}""", json["futureOption"]!.ToJsonString());
+ Assert.Null(json["heroFrame"]);
+ Assert.Equal(1.5, json["camera"]!["keyframes"]![0]!["frame"]!.GetValue());
+ }
+
+ [Test]
+ public void NothingToMoveGivesNoNewProject()
+ {
+ Assert.Null(ProjectSettings.MoveFramePositions(new ProjectSettings { ExcludedFrames = [1] }.ToJson(), new Dictionary()));
+ Assert.Null(ProjectSettings.MoveFramePositions(new ProjectSettings { ExcludedFrames = [1] }.ToJson(), new Dictionary { [2] = 3, [1] = 1 }));
+ Assert.Null(ProjectSettings.MoveFramePositions("not json", new Dictionary { [1] = 2 }));
+ Assert.Null(ProjectSettings.MoveFramePositions("[1, 2]", new Dictionary { [1] = 2 }));
+ Assert.Null(ProjectSettings.MoveFramePositions("""{ "heroFrame": 1, "HeroFrame": 1 }""", new Dictionary { [1] = 2 }));
+ }
+
[Test]
public void BuiltInPresetIdsAreUnique() =>
Assert.Equal(ExportPresets.BuiltIn.Count, ExportPresets.BuiltIn.Select(p => p.Id).Distinct().Count());
diff --git a/tests/Titano.Data.Tests/Archiving/ArchiveIngestTests.cs b/tests/Titano.Data.Tests/Archiving/ArchiveIngestTests.cs
index d9184407..548f799c 100644
--- a/tests/Titano.Data.Tests/Archiving/ArchiveIngestTests.cs
+++ b/tests/Titano.Data.Tests/Archiving/ArchiveIngestTests.cs
@@ -1,5 +1,10 @@
+using System.Text.Json.Nodes;
using Titano.Core.Archiving;
+using Titano.Core.IO;
+using Titano.Core.Model;
+using Titano.Core.Project;
using Titano.Data.Archiving;
+using Titano.Data.Repositories;
using Titano.Testing;
using static Titano.Data.Tests.Archiving.ArchiveFixture;
@@ -121,4 +126,209 @@ 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((false, true), (original.Repaired, repaired.Repaired));
+ 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.Equal((false, true), (repaired.Duplicate, repaired.Repaired));
+ 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);
+ }
+
+ [Test]
+ public async Task ASequenceAdoptedAtTheRootIsNeverMovedWhenItsSidecarIsGone()
+ {
+ await using var fx = await CreateAsync(context);
+ Photos.WriteSeries(fx.Archive.RootPath, Start, 2);
+ await fx.ScanAsync();
+ var adopted = Assert.NotNull((await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id, fx.Ct)).SingleOrDefault());
+ Assert.Equal(string.Empty, adopted.Folder);
+ File.Delete(fx.Paths.Sequence(string.Empty).ManifestPath);
+
+ // It held photos, so it is no sequence waiting for a folder: the commit reports the missing sidecar.
+ var staged = fx.Stage(Start.AddMinutes(5), 3);
+ await Assert.ThrowsAsync(() => fx.Service.Ingest.CommitAsync(Request(fx, staged, sequenceId: adopted.Id), fx.Ct));
+
+ var row = (await fx.Db.Sequences.GetAsync(adopted.Id))!;
+ Assert.Equal((string.Empty, 2), (row.Folder, row.FrameCount));
+ Assert.Count(2, await fx.Db.Frames.ListBySequenceAsync(adopted.Id));
+ Assert.False(Directory.Exists(Path.Combine(fx.Archive.RootPath, "2026")), "no folder was claimed for it");
+ Assert.FileExists(staged.Path);
+ }
+
+ [Test]
+ public async Task FramesInsertedBeforeOthersTakeTheProjectPositionsAlong()
+ {
+ await using var fx = await CreateAsync(context);
+ var results = new List();
+ for (var i = 0; i < 5; i++) results.Add(await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start.AddMinutes(1 + i), 10 + i)), fx.Ct));
+ var sequenceId = results[0].SequenceId;
+ var folder = fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(sequenceId))!.Folder);
+ var project = new ProjectSettings
+ {
+ ExcludedFrames = [3],
+ HeroFrame = 1,
+ Camera = new CameraSettings { Keyframes = [new CameraKey(0, 0.5, 0.5, 1, 0), new CameraKey(4, 0.4, 0.5, 1.5, 0)] },
+ }.ToJson();
+ AtomicFile.WriteAllText(folder.ProjectPath, project);
+ var edited = await fx.Db.Sequences.EditAsync(sequenceId, new SequenceEdit { SettingsJson = project, HeroFrameId = results[1].FrameId }, null, fx.Ct);
+ var version = edited.Sequence!.SettingsVersion;
+
+ // Two photos captured before every other one, and one between the third and the fourth, arrive later.
+ await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start, 20)), fx.Ct);
+ await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start.AddSeconds(30), 21)), fx.Ct);
+ await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start.AddMinutes(3.5), 22)), fx.Ct);
+
+ var row = (await fx.Db.Sequences.GetAsync(sequenceId))!;
+ var frames = await fx.Db.Frames.ListBySequenceAsync(sequenceId);
+ var moved = ProjectSettings.FromJson(row.SettingsJson!);
+ Assert.SequenceEqual([results[3].FrameId], moved.ExcludedFrames.Select(i => frames[i].Id));
+ Assert.Equal(results[1].FrameId, frames[moved.HeroFrame!.Value].Id);
+ Assert.SequenceEqual([results[0].FrameId, results[4].FrameId], moved.Camera.Keyframes.Select(k => frames[k.Frame].Id));
+ Assert.Equal(version, row.SettingsVersion);
+ Assert.Equal(results[1].FrameId, row.HeroFrameId);
+ Assert.True(JsonNode.DeepEquals(JsonNode.Parse(row.SettingsJson!), JsonNode.Parse(File.ReadAllText(folder.ProjectPath))), "project.json mirrors the index");
+ }
+
+ [Test]
+ public async Task PhotosAFolderScanFindsMoveTheProjectPositionsButUnknownMembersStay()
+ {
+ await using var fx = await CreateAsync(context);
+ var late = await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start.AddMinutes(1), 1)), fx.Ct);
+ await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start.AddMinutes(2), 2)), fx.Ct);
+ var row = (await fx.Db.Sequences.GetAsync(late.SequenceId))!;
+ var folder = fx.Paths.Sequence(row.Folder);
+ // A project with a member from a newer Titano; only the index copy holds it (the API edited it).
+ const string project = "{ \"excludedFrames\": [1], \"heroFrame\": 0, \"futureOption\": { \"keep\": true } }";
+ await fx.Db.Sequences.EditAsync(late.SequenceId, new SequenceEdit { SettingsJson = project }, null, fx.Ct);
+
+ File.WriteAllBytes(folder.File("originals/early.JPG"), Photos.Jpeg(Start, 3));
+ await fx.Service.Indexer.ReconcileAsync(fx.Archive, (await fx.Db.Sequences.GetAsync(late.SequenceId))!, fx.Ct);
+
+ var settings = (await fx.Db.Sequences.GetAsync(late.SequenceId))!.SettingsJson!;
+ var moved = ProjectSettings.FromJson(settings);
+ Assert.SequenceEqual([2], moved.ExcludedFrames);
+ Assert.Equal(1, moved.HeroFrame);
+ Assert.Contains("futureOption", settings);
+ Assert.True(JsonNode.DeepEquals(JsonNode.Parse(settings), JsonNode.Parse(File.ReadAllText(folder.ProjectPath))), "project.json mirrors the index");
+ }
+
+ [Test]
+ public async Task AScanMovesTheProjectPositionsOnlyBetweenProjectSaves()
+ {
+ await using var fx = await CreateAsync(context);
+ var late = await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start.AddMinutes(1), 1)), fx.Ct);
+ await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start.AddMinutes(2), 2)), fx.Ct);
+ var id = late.SequenceId;
+ var folder = fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(id))!.Folder);
+ var version = (await fx.Db.Sequences.EditAsync(id, new SequenceEdit { SettingsJson = "{ \"excludedFrames\": [1] }" }, null, fx.Ct)).Sequence!.SettingsVersion;
+
+ // Another process files a photo captured before both into the sidecar; this index learns of it from a scan.
+ var photos = ArchiveScanner.PhotoDirectory(folder);
+ var stamp = Directory.GetLastWriteTimeUtc(photos);
+ File.WriteAllBytes(folder.File("originals/early.JPG"), Photos.Jpeg(Start, 3));
+ ManifestStore.WriteSequence(folder.ManifestPath, SequenceAdopter.Reconcile(folder, ManifestStore.ReadSequence(folder.ManifestPath), fx.Ct)!);
+ Directory.SetLastWriteTimeUtc(photos, stamp);
+
+ // An editor saving the project holds the sequence lease (LocalSequenceSource.SaveProjectAsync).
+ var save = await LeaseFile.AcquireAsync(fx.Paths.LocksDirectory, $"seq-{id:N}", "editor", TimeSpan.FromSeconds(5), cancellationToken: fx.Ct);
+ var scan = Task.Run(() => fx.ScanAsync());
+ await Task.Delay(500, fx.Ct);
+ Assert.False(scan.IsCompleted, "the scan waits for the save");
+ // The save stores the positions its editor knew, as of the frames before the scan.
+ Assert.Equal(SequenceEditOutcome.Updated,
+ (await fx.Db.Sequences.EditAsync(id, new SequenceEdit { SettingsJson = "{ \"excludedFrames\": [0, 1] }" }, version, fx.Ct)).Outcome);
+ save.Dispose();
+ Assert.Equal(1, (await scan).Indexed);
+
+ var row = (await fx.Db.Sequences.GetAsync(id))!;
+ Assert.Equal(3, row.FrameCount);
+ Assert.SequenceEqual([1, 2], ProjectSettings.FromJson(row.SettingsJson!).ExcludedFrames);
+ }
}
diff --git a/tests/Titano.Server.Tests/Events/EventTests.cs b/tests/Titano.Server.Tests/Events/EventTests.cs
index 820c0678..bf9a3fe5 100644
--- a/tests/Titano.Server.Tests/Events/EventTests.cs
+++ b/tests/Titano.Server.Tests/Events/EventTests.cs
@@ -1,4 +1,5 @@
using System.Net;
+using System.Net.Http.Json;
using System.Net.WebSockets;
using Microsoft.Extensions.DependencyInjection;
using Titano.Core.Model;
@@ -74,6 +75,119 @@ public sealed class EventTests(TestContext context)
await plain.ExpectErrorAsync(HttpStatusCode.BadRequest, "websocket_required");
}
+ [Test]
+ public async Task ACardImportReportedByOneClientReachesTheOthersAsCardEvents()
+ {
+ await using var server = await TestServer.StartAsync(context);
+ var (uploaderHttp, _, uploaderToken) = await server.UserAsync("studio-pc", "uploader");
+ var (_, _, editorToken) = await server.UserAsync("alberto", "editor");
+
+ using var listener = new TitanoClient(server.HttpBase, new CertificatePinning([]), "laptop") { Token = editorToken };
+ using var listening = CancellationTokenSource.CreateLinkedTokenSource(context.Cancellation);
+ listening.CancelAfter(TimeSpan.FromSeconds(20));
+ var received = new List();
+ var connected = new TaskCompletionSource();
+ var reader = Task.Run(async () =>
+ {
+ var events = listener.EventsAsync(listening.Token).GetAsyncEnumerator(listening.Token);
+ var first = events.MoveNextAsync();
+ connected.TrySetResult();
+ try
+ {
+ if (!await first) return;
+ do
+ {
+ if (events.Current is CardEvent card) received.Add(card);
+ if (events.Current is CardEvent { State: CardImportStates.Finished }) return;
+ }
+ while (await events.MoveNextAsync());
+ }
+ finally
+ {
+ await events.DisposeAsync();
+ }
+ });
+ await connected.Task;
+ await WaitForSubscriberAsync(server);
+
+ // The importing client (an upload-only account is enough) reports through the protocol client.
+ using var importer = new TitanoClient(server.HttpBase, new CertificatePinning([]), "Titano (STUDIO)") { Token = uploaderToken };
+ var importId = Guid.CreateVersion7();
+ await importer.ReportCardAsync(new CardImportReport(importId, "EOS R5 · card A", CardImportStates.Started, 0, 120, 0), context.Cancellation);
+ await importer.ReportCardAsync(new CardImportReport(importId, "EOS R5 · card A", CardImportStates.Progress, 60, 120, 1), context.Cancellation);
+ await importer.ReportCardAsync(new CardImportReport(importId, "EOS R5 · card A", CardImportStates.Finished, 120, 120, 2), context.Cancellation);
+ await reader.WaitAsync(TimeSpan.FromSeconds(20));
+
+ Assert.SequenceEqual([CardImportStates.Started, CardImportStates.Progress, CardImportStates.Finished], received.Select(e => e.State));
+ Assert.True(received.All(e => e.ImportId == importId && e.Card == "EOS R5 · card A" && e.Total == 120), "every event names the import");
+ Assert.Equal((60, 1), (received[1].Done, received[1].Failed));
+ // Who imports: the account and the client name it signed in with.
+ Assert.Equal(("studio-pc", "tests"), (received[2].User, received[2].ClientName));
+
+ // Reports are checked like any request.
+ foreach (var (report, field) in new[]
+ {
+ (new CardImportReport(Guid.Empty, "card", CardImportStates.Started, 0, 1, 0), "importId"),
+ (new CardImportReport(importId, " ", CardImportStates.Started, 0, 1, 0), "card"),
+ (new CardImportReport(importId, "card", "paused", 0, 1, 0), "state"),
+ (new CardImportReport(importId, "card", CardImportStates.Progress, 2, 1, 0), "done"),
+ })
+ {
+ using var refused = await uploaderHttp.PostAsJsonAsync("/api/v1/uploads/cards", report, ProtocolJson.Default.CardImportReport);
+ Assert.Equal(field, (await refused.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request")).Details);
+ }
+ var (viewer, _, _) = await server.UserAsync("guest", "viewer");
+ using var forbidden = await viewer.PostAsJsonAsync("/api/v1/uploads/cards", new CardImportReport(importId, "card", CardImportStates.Started, 0, 1, 0),
+ ProtocolJson.Default.CardImportReport);
+ await forbidden.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
+ }
+
+ [Test]
+ public async Task OneAccountsCardReportsCannotCrowdTheEventQueues()
+ {
+ var clock = new ManualTimeProvider();
+ await using var server = await TestServer.StartAsync(context, services: s => s.AddSingleton(clock));
+ var (uploader, _, _) = await server.UserAsync("studio-pc", "uploader");
+ var (other, _, _) = await server.UserAsync("roof-pc", "uploader");
+ using var subscription = server.Services.GetRequiredService().Subscribe();
+ var importId = Guid.CreateVersion7();
+
+ // Progress goes out at most once a second; the reports in between are taken and dropped.
+ for (var done = 1; done <= 5; done++) await ReportCardAsync(uploader, new CardImportReport(importId, "card", CardImportStates.Progress, done, 100, 0));
+ clock.Advance(TimeSpan.FromSeconds(1));
+ await ReportCardAsync(uploader, new CardImportReport(importId, "card", CardImportStates.Progress, 6, 100, 0));
+ Assert.SequenceEqual([1, 6], CardEvents(subscription).Select(e => e.Done));
+
+ // Starts and ends always go out, up to 120 events of one account a minute.
+ for (var i = 0; i < 118; i++) await ReportCardAsync(uploader, new CardImportReport(Guid.CreateVersion7(), "card", CardImportStates.Started, 0, 100, 0));
+ using (var refused = await uploader.PostAsJsonAsync("/api/v1/uploads/cards",
+ new CardImportReport(importId, "card", CardImportStates.Finished, 100, 100, 0), ProtocolJson.Default.CardImportReport))
+ Assert.Equal("59", (await refused.ExpectErrorAsync(HttpStatusCode.TooManyRequests, "rate_limited")).Details);
+ await ReportCardAsync(other, new CardImportReport(Guid.CreateVersion7(), "card", CardImportStates.Started, 0, 100, 0));
+ Assert.Count(119, CardEvents(subscription));
+
+ clock.Advance(TimeSpan.FromMinutes(1));
+ await ReportCardAsync(uploader, new CardImportReport(importId, "card", CardImportStates.Finished, 100, 100, 0));
+ Assert.SequenceEqual([CardImportStates.Finished], CardEvents(subscription).Select(e => e.State));
+ }
+
+ private static async Task ReportCardAsync(HttpClient client, CardImportReport report)
+ {
+ using var response = await client.PostAsJsonAsync("/api/v1/uploads/cards", report, ProtocolJson.Default.CardImportReport);
+ await response.ExpectAsync(HttpStatusCode.NoContent);
+ }
+
+ /// The card events published since the last call.
+ private static List CardEvents(Titano.Server.Events.EventHub.Subscription subscription)
+ {
+ var events = new List();
+ while (subscription.Reader.TryRead(out var e))
+ {
+ if (e is CardEvent card) events.Add(card);
+ }
+ return events;
+ }
+
private static async Task WaitForSubscriberAsync(TestServer server)
{
var hub = server.Services.GetRequiredService();
diff --git a/tests/Titano.Server.Tests/Storage/ArchiveModuleTests.cs b/tests/Titano.Server.Tests/Storage/ArchiveModuleTests.cs
index d819d2e6..1eb0bca2 100644
--- a/tests/Titano.Server.Tests/Storage/ArchiveModuleTests.cs
+++ b/tests/Titano.Server.Tests/Storage/ArchiveModuleTests.cs
@@ -4,8 +4,11 @@ using Titano.Core.Archiving;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Model;
using Titano.Server.Jobs;
+using Titano.Protocol;
+using Titano.Protocol.Client;
using Titano.Server.Storage;
using Titano.Testing;
+using UploadState = Titano.Data.Repositories.UploadState;
namespace Titano.Server.Tests.Storage;
@@ -123,11 +126,114 @@ public sealed class ArchiveModuleTests(TestContext context)
}
}
+ [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 photo = Photo(3);
+ // Room for the photo once: a repair puts back bytes the archive already counts.
+ var (editor, _, _) = await server.UserAsync("alberto", "editor", quotaBytes: photo.Length + 1000);
+ 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);
+ using var me = await editor.GetAsync("/api/v1/auth/me");
+ Assert.Equal(photo.Length, (await me.ReadAsync(ProtocolJson.Default.UserDto)).UsedBytes);
+ }
+
+ [Test]
+ public async Task AnIntactCopyElsewhereDoesNotStandForTheDamagedOneOfTheTargetSequence()
+ {
+ await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
+ var (editor, _, _) = await server.UserAsync("alberto", "editor");
+ var photo = Photo(4);
+ var roof = await Uploads.UploadAsync(editor, photo, "IMG_0001.JPG", sessionKey: "roof");
+ var path = Path.Combine(server.Options.ArchivePath, Assert.NotNull(await server.Database.Frames.GetAsync(roof.FrameId)).RelativePath);
+ File.Delete(path);
+ // With the roof's copy gone, the same photo is filed into a second sequence.
+ var yard = await Uploads.UploadAsync(editor, photo, "IMG_0001.JPG", sessionKey: "yard");
+ Assert.NotEqual(roof.SequenceId, yard.SequenceId);
+
+ // Into the roof sequence the yard's copy is no shortcut, not even for a commit a crash interrupted: the bytes come
+ // and the roof's frame gets its file back.
+ var start = await Uploads.StartAsync(editor, photo, "IMG_0001.JPG", roof.SequenceId);
+ var id = Assert.NotNull(start.UploadId);
+ Assert.Equal((true, yard.FrameId), await ShortcutAsync(editor, photo, "yard"));
+ for (var i = 0; i * start.ChunkSize < photo.Length; i++)
+ {
+ using var put = await Uploads.PutChunkAsync(editor, id, i, Uploads.Chunk(photo, start.ChunkSize, i));
+ await put.ExpectAsync(HttpStatusCode.OK);
+ }
+ Assert.True(await server.Database.Uploads.TryTransitionAsync(id, UploadState.Receiving, UploadState.Committing, cancellationToken: context.Cancellation));
+ await server.Services.GetRequiredService().RecoverAsync(context.Cancellation);
+ using var complete = await editor.PostAsync($"/api/v1/uploads/{id}/complete", null);
+ await complete.ExpectAsync(HttpStatusCode.OK);
+ var again = await complete.ReadAsync(ProtocolJson.Default.CompleteUploadResponse);
+
+ Assert.Equal((roof.FrameId, roof.Index), (again.FrameId, again.Index));
+ Assert.SequenceEqual(photo, await File.ReadAllBytesAsync(path));
+ // Each sequence's own copy answers for it.
+ Assert.Equal((true, roof.FrameId), await ShortcutAsync(editor, photo, "roof"));
+ Assert.Equal((true, yard.FrameId), await ShortcutAsync(editor, photo, "yard"));
+ }
+
+ private static async Task<(bool AlreadyExists, Guid? FrameId)> ShortcutAsync(HttpClient client, byte[] photo, string sessionKey)
+ {
+ var start = await Uploads.StartAsync(client, photo, "IMG_0001.JPG", sessionKey: sessionKey, expected: HttpStatusCode.OK);
+ return (start.AlreadyExists, start.FrameId);
+ }
+
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 + seed) % 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 });
}
}
diff --git a/tests/Titano.Server.Tests/Storage/UploadTests.cs b/tests/Titano.Server.Tests/Storage/UploadTests.cs
index bb072e69..aea2324e 100644
--- a/tests/Titano.Server.Tests/Storage/UploadTests.cs
+++ b/tests/Titano.Server.Tests/Storage/UploadTests.cs
@@ -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,98 @@ 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().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().Exists(id));
+ }
+
+ [Test]
+ public async Task AnUploadKeepsItsChunkSizeWhenTheSettingShrinks()
+ {
+ await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk * 2);
+ var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
+ var data = Uploads.Photo(Chunk * 3, 14);
+ var start = await Uploads.StartAsync(uploader, data);
+ var id = Assert.NotNull(start.UploadId);
+ Assert.Equal(Chunk * 2, start.ChunkSize);
+
+ // An administrator lowers the chunk size; the upload resumes with the size it started with.
+ server.Options.ChunkSizeBytes = Chunk;
+ var resumed = await Uploads.StartAsync(uploader, data);
+ Assert.Equal((id, Chunk * 2), (resumed.UploadId!.Value, resumed.ChunkSize));
+ for (var i = 0; i < 2; i++)
+ {
+ using var put = await Uploads.PutChunkAsync(uploader, id, i, Uploads.Chunk(data, Chunk * 2, i));
+ await put.ExpectAsync(HttpStatusCode.OK);
+ }
+ using var complete = await uploader.PostAsync($"/api/v1/uploads/{id}/complete", null);
+ await complete.ExpectAsync(HttpStatusCode.OK);
+
+ // A new upload takes the new size, and a body above it is refused.
+ var next = Uploads.Photo(Chunk * 2, 15);
+ var small = await Uploads.StartAsync(uploader, next);
+ Assert.Equal(Chunk, small.ChunkSize);
+ using var oversized = await Uploads.PutChunkAsync(uploader, small.UploadId!.Value, 0, next);
+ await oversized.ExpectErrorAsync(HttpStatusCode.BadRequest, "chunk_size");
+ }
+
+ [Test]
+ public async Task RenderUploadsNeedTheEditPermission()
+ {
+ await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk);
+ var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
+ var (editor, _, _) = await server.UserAsync("alberto", "editor");
+ var frame = await Uploads.UploadAsync(uploader, Uploads.Photo(5000, 16), sessionKey: "roof");
+ var output = Uploads.Photo(3000, 17);
+ var request = new RenderUploadRequest(Guid.CreateVersion7(), "Roof.mp4", output.Length, Uploads.Sha(output), "4K HEVC", "hevc", 3840, 2160, 30, 10, null);
+
+ // Render outputs count against no quota: an upload-only account cannot add them to any sequence.
+ using (var refused = await uploader.PostAsJsonAsync($"/api/v1/sequences/{frame.SequenceId}/renders", request, ProtocolJson.Default.RenderUploadRequest))
+ await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
+ using (var complete = await uploader.PostAsync($"/api/v1/sequences/{frame.SequenceId}/renders/{Guid.CreateVersion7()}/complete", null))
+ await complete.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
+ using var accepted = await editor.PostAsJsonAsync($"/api/v1/sequences/{frame.SequenceId}/renders", request, ProtocolJson.Default.RenderUploadRequest);
+ await accepted.ExpectAsync(HttpStatusCode.Created);
+ }
+
[Test]
public async Task TheProtocolClientUploadsAndDownloadsLikeTheUploader()
{
diff --git a/tests/Titano.Tools.Tests/I18nCommandTests.cs b/tests/Titano.Tools.Tests/I18nCommandTests.cs
index 129aa010..78fcf99b 100644
--- a/tests/Titano.Tools.Tests/I18nCommandTests.cs
+++ b/tests/Titano.Tools.Tests/I18nCommandTests.cs
@@ -1,9 +1,11 @@
+using System.Xml.Linq;
using Titano.Testing;
using Titano.Tools.Commands;
namespace Titano.Tools.Tests;
-/// i18n check flags an English text that counts something without plural forms (BRIEF §16).
+/// i18n check: English texts that count something need plural forms (BRIEF §16), and every error code
+/// of the server has its message, whose key is built at run time.
public sealed class I18nCommandTests
{
[Test]
@@ -56,4 +58,48 @@ public sealed class I18nCommandTests
Assert.Null(I18nCommand.CountedTally("Settings.Storage.Usage", "{0} used · {1} free"));
Assert.Null(I18nCommand.CountedTally("Import.Result.Skipped.other", "{0:N0} copied, {1:N0} skipped"));
}
+
+ [Test]
+ public void ErrorCodesAreTheLiteralsPassedToTheServerErrorHelpers()
+ {
+ const string source = """
+ if (bad) return ApiErrors.BadRequest(context, "invalid_filter", "status");
+ return known.SequenceId == sequenceId
+ ? new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, null)
+ : Outcome.Fail(409, "render_exists");
+ return Fail(400, "chunk_size", expected.ToString(CultureInfo.InvariantCulture));
+ DeleteBlock.Offline => ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable,
+ "archive_offline"),
+ return TooMany(context, "rate_limited", wait);
+ return ApiErrors.NotFound(context, "sequence");
+ return ApiErrors.BadRequest(context, code, setting, setting);
+ await FailAsync(upload, "not_a_code");
+ """;
+
+ Assert.SequenceEqual(["invalid_filter", "render_exists", "chunk_size", "archive_offline", "rate_limited"], I18nCommand.ErrorCodes(source).ToList());
+ }
+
+ [Test]
+ public void AnErrorCodeNamesItsMessageKeyLikeTheServer()
+ {
+ Assert.Equal("Server.Error.RenderExists", I18nCommand.ErrorKey("render_exists"));
+ Assert.Equal("Server.Error.Forbidden", I18nCommand.ErrorKey("forbidden"));
+ Assert.Equal("Server.Error.Http413", I18nCommand.ErrorKey("http_413"));
+ }
+
+ [Test]
+ public void EveryErrorCodeOfTheServerHasAnEnglishMessage()
+ {
+ var root = Args.RepoRoot();
+ var keys = XDocument.Load(Path.Combine(root, "i18n", "en", "Server.resx")).Root!.Elements("data")
+ .Select(d => (string)d.Attribute("name")!).ToHashSet(StringComparer.Ordinal);
+
+ var missing = I18nCommand.MissingErrorMessages(root, keys).ToList();
+
+ Assert.Empty(missing.Select(m => $"{m.Code} ({Path.GetFileName(m.File)})"));
+ var withoutOne = keys.Where(k => k != "Server.Error.RenderExists").ToHashSet(StringComparer.Ordinal);
+ var reported = I18nCommand.MissingErrorMessages(root, withoutOne).ToList();
+ Assert.Count(1, reported);
+ Assert.Equal(("render_exists", "Server.Error.RenderExists", "RenderUploads.cs"), (reported[0].Code, reported[0].Key, Path.GetFileName(reported[0].File)));
+ }
}