feat(server): publish card imports as cardEvent
BRIEF §14.3 lists cardEvent among the WebSocket events, but the server had none. A client importing a card into the server now reports its start, progress (at most once a second, a report still waiting replaced by the next) and end to the new POST /api/v1/uploads/cards (Upload permission; import id, card name, state, done, total, failed), and the server publishes a CardEvent naming the account and client to every connected client; the protocol client parses it and offers ReportCardAsync. A report that fails is logged and never stops the import; a server without the endpoint gets no more reports (SRS-10). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
9 files changed
+376
-6
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,88 @@ 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)));
|
||||
reporter.Report(Progress(40));
|
||||
Assert.Count(2, server.Cards);
|
||||
}
|
||||
|
||||
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 +212,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))!;
|
||||
|
||||
@@ -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,73 @@ 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");
|
||||
}
|
||||
|
||||
private static async Task WaitForSubscriberAsync(TestServer server)
|
||||
{
|
||||
var hub = server.Services.GetRequiredService<Titano.Server.Events.EventHub>();
|
||||
|
||||
Reference in new issue
Block a user