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:
Claude committed 2026-10-12 09:40:53 +00:00
1 parent 01e17c9961
commit bb55e47b47
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&lt;T&gt; 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))!;