C# QUIC server: retain the newest latest-only frame per (channel, body)
CultMeshQuicRealtimeServer mirrors the TS provider: a `_retained` dictionary holds the newest latest-only frame per (channel, body) key, updated in BroadcastAsync with the same CultMeshGeneration comparison the receive-side filter already uses. AcceptLoopAsync seeds a newly accepted client with the retained frames. Both the retained update+fan-out and the client registration+seed run under one lock (`_retainedGate`), so a seed and a concurrent broadcast are totally ordered and a client can never end up seeded with a frame older than one it already received via broadcast. Reliable- ordered frames are events and are never retained. CultMeshGeneration is now internal so the server can reuse the transport's own generation comparison instead of a second implementation. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
parent
1c87251d80
commit
680af452c6
2 changed files with 120 additions and 5 deletions
|
|
@ -158,6 +158,16 @@ public sealed class CultMeshQuicRealtimeServer : IAsyncDisposable
|
|||
private readonly CancellationTokenSource _shutdown = new();
|
||||
private readonly ConcurrentDictionary<CultMeshQuicRealtimeTransport, byte> _clients = new();
|
||||
private readonly CultMeshRealtimeInbox _received = new();
|
||||
/// <summary>Guards <see cref="_retained"/> together with client registration, so a newly
|
||||
/// accepted client's seed and a concurrent broadcast's retained update are totally ordered:
|
||||
/// a client only ever becomes visible to <see cref="BroadcastAsync"/> already carrying the
|
||||
/// newest retained generation, and can never be seeded with a frame older than one it already
|
||||
/// received via broadcast.</summary>
|
||||
private readonly object _retainedGate = new();
|
||||
/// <summary>The newest `latest-only` frame broadcast so far per `(channel, body)` key, seeded
|
||||
/// into every client accepted after that broadcast. Reliable-ordered frames are events, not
|
||||
/// state, and are never retained.</summary>
|
||||
private readonly Dictionary<string, CultMeshRealtimeFrame> _retained = new(StringComparer.Ordinal);
|
||||
private readonly TaskCompletionSource<Exception> _backgroundFailure = new(
|
||||
TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private readonly Task _acceptLoop;
|
||||
|
|
@ -222,10 +232,22 @@ public sealed class CultMeshQuicRealtimeServer : IAsyncDisposable
|
|||
|
||||
if (frame.Delivery == CultMeshRealtimeDelivery.LatestOnly)
|
||||
{
|
||||
foreach (var client in _clients.Keys)
|
||||
var key = frame.ChannelId + "\u001f" + frame.BodyId;
|
||||
var candidate = new CultMeshQuicRealtimeTransport.CultMeshGeneration(frame.ProducerEpoch, frame.Sequence);
|
||||
lock (_retainedGate)
|
||||
{
|
||||
if (client.TryPublishLatest(frame)) continue;
|
||||
if (_clients.TryRemove(client, out _)) client.Dispose();
|
||||
if (!_retained.TryGetValue(key, out var current) ||
|
||||
candidate.CompareTo(new CultMeshQuicRealtimeTransport.CultMeshGeneration(
|
||||
current.ProducerEpoch, current.Sequence)) > 0)
|
||||
{
|
||||
_retained[key] = frame;
|
||||
}
|
||||
|
||||
foreach (var client in _clients.Keys)
|
||||
{
|
||||
if (client.TryPublishLatest(frame)) continue;
|
||||
if (_clients.TryRemove(client, out _)) client.Dispose();
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
|
@ -284,7 +306,11 @@ public sealed class CultMeshQuicRealtimeServer : IAsyncDisposable
|
|||
connection.RemoteEndPoint?.ToString() ?? "quic-peer",
|
||||
connection,
|
||||
frame => _received.Publish(frame));
|
||||
_clients.TryAdd(transport, 0);
|
||||
lock (_retainedGate)
|
||||
{
|
||||
_clients.TryAdd(transport, 0);
|
||||
foreach (var retainedFrame in _retained.Values) transport.TryPublishLatest(retainedFrame);
|
||||
}
|
||||
_ = transport.Completion.ContinueWith(
|
||||
completed =>
|
||||
{
|
||||
|
|
@ -559,7 +585,7 @@ internal sealed class CultMeshQuicRealtimeTransport : ICultMeshRealtimeTransport
|
|||
_received.Publish(frame);
|
||||
}
|
||||
|
||||
private readonly record struct CultMeshGeneration(long ProducerEpoch, long Sequence) : IComparable<CultMeshGeneration>
|
||||
internal readonly record struct CultMeshGeneration(long ProducerEpoch, long Sequence) : IComparable<CultMeshGeneration>
|
||||
{
|
||||
public int CompareTo(CultMeshGeneration other)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -138,6 +138,95 @@ public sealed class CultMeshQuicRealtimeTransportTests
|
|||
"a late older generation must not twitch the consumer backwards");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASessionAttachingAfterTwoLatestOnlyBroadcastsReceivesExactlyTheNewerFrame()
|
||||
{
|
||||
if (!QuicListener.IsSupported) Assert.Ignore("MsQuic is unavailable on this test host.");
|
||||
using var certificate = CreateCertificate();
|
||||
await using var server = await CultMeshQuicRealtimeServer.ListenAsync(new CultMeshQuicRealtimeServerOptions
|
||||
{
|
||||
ListenEndPoint = new IPEndPoint(IPAddress.Loopback, 0),
|
||||
ServerCertificate = certificate
|
||||
});
|
||||
|
||||
await server.BroadcastAsync(Frame(1, CultMeshRealtimeDelivery.LatestOnly));
|
||||
await server.BroadcastAsync(Frame(2, CultMeshRealtimeDelivery.LatestOnly));
|
||||
|
||||
// Attach only after both broadcasts above have already completed:
|
||||
// whatever this session receives came from the retained seed on
|
||||
// attach, not from `BroadcastAsync`'s own fan-out.
|
||||
var runtimeId = CultMeshRuntimeId.Parse("service:aetheria.daemon");
|
||||
var target = new CultMeshSessionTarget("aetheria", runtimeId.Value);
|
||||
using var sessions = CreateSessions(server, out _);
|
||||
var session = await sessions.ConnectRealtimeAsync(target);
|
||||
|
||||
var seeded = await session.ReceiveAsync().WaitAsync(TimeSpan.FromSeconds(5));
|
||||
|
||||
seeded.Sequence.Should().Be(2, "a late joiner must be seeded with the newest retained generation");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RetentionKeepsTheNewerGenerationWhenAnOlderOneBroadcastsAfterward()
|
||||
{
|
||||
if (!QuicListener.IsSupported) Assert.Ignore("MsQuic is unavailable on this test host.");
|
||||
using var certificate = CreateCertificate();
|
||||
await using var server = await CultMeshQuicRealtimeServer.ListenAsync(new CultMeshQuicRealtimeServerOptions
|
||||
{
|
||||
ListenEndPoint = new IPEndPoint(IPAddress.Loopback, 0),
|
||||
ServerCertificate = certificate
|
||||
});
|
||||
|
||||
await server.BroadcastAsync(Frame(5, CultMeshRealtimeDelivery.LatestOnly, producerEpoch: 9));
|
||||
// An older generation broadcast afterward must not overwrite the
|
||||
// retained frame: a plain last-write-wins assignment would regress this.
|
||||
await server.BroadcastAsync(Frame(3, CultMeshRealtimeDelivery.LatestOnly, producerEpoch: 7));
|
||||
|
||||
var runtimeId = CultMeshRuntimeId.Parse("service:aetheria.daemon");
|
||||
var target = new CultMeshSessionTarget("aetheria", runtimeId.Value);
|
||||
using var sessions = CreateSessions(server, out _);
|
||||
var session = await sessions.ConnectRealtimeAsync(target);
|
||||
|
||||
var seeded = await session.ReceiveAsync().WaitAsync(TimeSpan.FromSeconds(5));
|
||||
|
||||
seeded.ProducerEpoch.Should().Be(9);
|
||||
seeded.Sequence.Should().Be(5, "an older generation must not replace the retained newer one");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AReliableOrderedFrameIsNeverRetainedAndIsNotDeliveredToALateJoiner()
|
||||
{
|
||||
if (!QuicListener.IsSupported) Assert.Ignore("MsQuic is unavailable on this test host.");
|
||||
using var certificate = CreateCertificate();
|
||||
await using var server = await CultMeshQuicRealtimeServer.ListenAsync(new CultMeshQuicRealtimeServerOptions
|
||||
{
|
||||
ListenEndPoint = new IPEndPoint(IPAddress.Loopback, 0),
|
||||
ServerCertificate = certificate
|
||||
});
|
||||
var runtimeId = CultMeshRuntimeId.Parse("service:aetheria.daemon");
|
||||
var target = new CultMeshSessionTarget("aetheria", runtimeId.Value);
|
||||
|
||||
using (var firstSessions = CreateSessions(server, out _))
|
||||
{
|
||||
var firstSession = await firstSessions.ConnectRealtimeAsync(target);
|
||||
await WaitUntilAsync(() => server.ConnectionCount == 1);
|
||||
await server.BroadcastAsync(Frame(9, CultMeshRealtimeDelivery.ReliableOrdered));
|
||||
var atFirst = await firstSession.ReceiveAsync().WaitAsync(TimeSpan.FromSeconds(5));
|
||||
atFirst.Sequence.Should().Be(9);
|
||||
}
|
||||
await WaitUntilAsync(() => server.ConnectionCount == 0);
|
||||
|
||||
// A real latest-only frame follows, so the assertion below proves the
|
||||
// reliable-ordered frame specifically was never retained, rather than
|
||||
// merely proving the server had nothing at all to seed.
|
||||
await server.BroadcastAsync(Frame(1, CultMeshRealtimeDelivery.LatestOnly));
|
||||
using var secondSessions = CreateSessions(server, out _);
|
||||
var secondSession = await secondSessions.ConnectRealtimeAsync(target);
|
||||
var seeded = await secondSession.ReceiveAsync().WaitAsync(TimeSpan.FromSeconds(5));
|
||||
|
||||
seeded.Delivery.Should().Be(CultMeshRealtimeDelivery.LatestOnly);
|
||||
seeded.Sequence.Should().Be(1, "only the latest-only frame may be seeded, never the reliable-ordered one");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task UnreliableDeliveryFailsClosedUntilANativeDatagramConnectorExists()
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue