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