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
@@ -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