Deliver large scoped snapshots reliably

This commit is contained in:
Meta Vens 2026-07-12 08:42:08 +01:00
commit c398bad186
4 changed files with 133 additions and 34 deletions

View file

@ -270,7 +270,7 @@ namespace GameCult.Networking
var storedAt = ResolveStoredAt(options);
var documents = new List<CultNetRawDocumentRecord>();
foreach (var document in cache.AllEntries)
void AddDocument(object document, string key)
{
var descriptor = _documents.GetRequired(document.GetType());
var binding = GetByDocumentType(document.GetType()) ??
@ -282,27 +282,11 @@ namespace GameCult.Networking
if (requestedSchemaIds != null && !MatchesRequestedSchema(descriptor, binding, requestedSchemaIds))
{
continue;
return;
}
var handleMethod = typeof(CultCache)
.GetMethod(nameof(CultCache.TryGetHandle))!
.MakeGenericMethod(document.GetType());
var handleObject = handleMethod.Invoke(cache, new[] { document });
if (handleObject == null)
{
continue;
}
var keyProperty = handleObject.GetType().GetProperty("Value");
var handleValue = keyProperty?.GetValue(handleObject) ?? handleObject;
var recordKeyProperty = handleValue.GetType().GetProperty("Key");
var recordKey = recordKeyProperty?.GetValue(handleValue);
var valueProperty = recordKey?.GetType().GetProperty("Value");
var key = (string?)(valueProperty?.GetValue(recordKey)) ?? string.Empty;
if (requestedRecordKeys != null && !requestedRecordKeys.Contains(key))
{
continue;
return;
}
documents.Add(new CultNetRawDocumentRecord
@ -319,6 +303,36 @@ namespace GameCult.Networking
});
}
if (requestedRecordKeys != null)
{
foreach (var key in requestedRecordKeys)
{
var document = cache.Get(new CultRecordKey(key));
if (document != null)
AddDocument(document, key);
}
}
else
{
foreach (var document in cache.AllEntries)
{
var handleMethod = typeof(CultCache)
.GetMethod(nameof(CultCache.TryGetHandle))!
.MakeGenericMethod(document.GetType());
var handleObject = handleMethod.Invoke(cache, new[] { document });
if (handleObject == null)
continue;
var keyProperty = handleObject.GetType().GetProperty("Value");
var handleValue = keyProperty?.GetValue(handleObject) ?? handleObject;
var recordKeyProperty = handleValue.GetType().GetProperty("Key");
var recordKey = recordKeyProperty?.GetValue(handleValue);
var valueProperty = recordKey?.GetType().GetProperty("Value");
var key = (string?)(valueProperty?.GetValue(recordKey)) ?? string.Empty;
AddDocument(document, key);
}
}
return new CultNetSnapshotResponseRawMessage
{
MessageId = RequireNonEmpty(messageId, nameof(messageId)),

View file

@ -216,7 +216,7 @@ namespace GameCult.Networking
Dispatch(message);
}
Thread.Sleep(5);
Thread.Sleep(1);
}
}

View file

@ -1508,6 +1508,8 @@ namespace GameCult.Networking
/// </summary>
public sealed class CultNetRudpSocketTransportConnection : IDisposable
{
private const int MinimumReceiveBufferBytes = 4 * 1024 * 1024;
private const int WireBurstPackets = 1;
private readonly Socket _socket;
private readonly CultNetRudpSession _session;
private readonly CultNetRudpSocketMode _mode;
@ -1657,10 +1659,7 @@ namespace GameCult.Networking
/// </summary>
public void Send(string channelId, byte[] payload)
{
foreach (var packet in _session.SendMany(channelId, payload, ChannelSendOptions(channelId), _maxFragmentBytes))
{
SendPacket(packet);
}
SendPackets(_session.SendMany(channelId, payload, ChannelSendOptions(channelId), _maxFragmentBytes));
_stats.FramesSent++;
}
@ -1929,9 +1928,16 @@ namespace GameCult.Networking
/// </summary>
public void PollResends()
{
foreach (var packet in _session.DueResends(NowMs()))
SendPackets(_session.DueResends(NowMs()));
}
private void SendPackets(IReadOnlyList<CultNetRudpPacket> packets)
{
for (var index = 0; index < packets.Count; index++)
{
SendPacket(packet);
SendPacket(packets[index]);
if ((index + 1) % WireBurstPackets == 0)
Thread.Sleep(1);
}
}
@ -2072,6 +2078,8 @@ namespace GameCult.Networking
/// </summary>
public sealed class CultNetRudpSocketTransportServer : IDisposable
{
private const int MinimumReceiveBufferBytes = 4 * 1024 * 1024;
private const int WireBurstPackets = 1;
private readonly Socket _socket;
private readonly uint _connectionId;
private readonly uint _initialSequence;
@ -2092,6 +2100,10 @@ namespace GameCult.Networking
if (options == null) throw new ArgumentNullException(nameof(options));
if (string.IsNullOrWhiteSpace(options.RuntimeId)) throw new ArgumentException("Runtime id is required.", nameof(options));
_socket = options.Socket ?? throw new ArgumentNullException(nameof(options.Socket));
if (_socket.ReceiveBufferSize < MinimumReceiveBufferBytes)
_socket.ReceiveBufferSize = MinimumReceiveBufferBytes;
if (_socket.ReceiveBufferSize < MinimumReceiveBufferBytes)
_socket.ReceiveBufferSize = MinimumReceiveBufferBytes;
_connectionId = options.ConnectionId;
_initialSequence = options.InitialSequence;
_resendDelayMs = options.ResendDelayMs;
@ -2135,10 +2147,7 @@ namespace GameCult.Networking
public void Send(CultNetRudpSocketServerPeer peer, string channelId, byte[] payload)
{
if (peer == null) throw new ArgumentNullException(nameof(peer));
foreach (var packet in peer.Session.SendMany(channelId, payload, ChannelSendOptions(channelId), _maxFragmentBytes))
{
SendPacket(peer.RemoteEndPoint, packet);
}
SendPackets(peer, peer.Session.SendMany(channelId, payload, ChannelSendOptions(channelId), _maxFragmentBytes));
_stats.FramesSent++;
}
@ -2287,10 +2296,17 @@ namespace GameCult.Networking
{
foreach (var peer in _peers.Values.ToArray())
{
foreach (var packet in peer.Session.DueResends(NowMs()))
{
SendPacket(peer.RemoteEndPoint, packet);
}
SendPackets(peer, peer.Session.DueResends(NowMs()));
}
}
private void SendPackets(CultNetRudpSocketServerPeer peer, IReadOnlyList<CultNetRudpPacket> packets)
{
for (var index = 0; index < packets.Count; index++)
{
SendPacket(peer.RemoteEndPoint, packets[index]);
if ((index + 1) % WireBurstPackets == 0)
Thread.Sleep(1);
}
}

View file

@ -1024,6 +1024,7 @@ namespace GameCult.Networking.Tests
Assert.That(server.Profile.Transports[0].Protocol, Is.EqualTo("rudp"));
Assert.That(client.Stats.FramesSent, Is.EqualTo(1));
Assert.That(server.Stats.FramesReceived, Is.EqualTo(1));
}
[Test]
@ -1260,6 +1261,74 @@ namespace GameCult.Networking.Tests
Assert.That(server.Profile.Transports[0].Protocol, Is.EqualTo("rudp"));
}
[Test]
public async Task RudpCultNetSchemaServer_DeliversLargeSnapshotResponse()
{
using var server = new RudpCultNetSchemaServer(new RudpCultNetSchemaServerOptions
{
RuntimeId = "csharp-rudp-large-snapshot-host",
Socket = BindUdpSocket(),
MaxFragmentBytes = 1024,
MaxPendingReliablePackets = 1024
});
var responseCompletion = new TaskCompletionSource<CultNetSnapshotResponseRawMessage>(
TaskCreationOptions.RunContinuationsAsynchronously);
var serverFailure = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
server.OnCultNet<CultNetSnapshotRequestMessage>((request, peer) => peer.SendCultNet(
new CultNetSnapshotResponseRawMessage
{
MessageId = request.MessageId,
Documents =
[
new CultNetRawDocumentRecord
{
SchemaId = "test.large.snapshot.v1",
RecordKey = "test:large:snapshot",
PayloadEncoding = "messagepack",
Payload = Enumerable.Range(0, 128 * 1024)
.Select(index => (byte)(index % 251)).ToArray()
}
]
}));
using var cancellation = new CancellationTokenSource();
var serverThread = new Thread(() =>
{
try
{
while (!cancellation.IsCancellationRequested)
{
_ = server.PollOnceAsync().GetAwaiter().GetResult();
Thread.Sleep(1);
}
}
catch (Exception error) { serverFailure.TrySetResult(error); }
}) { IsBackground = true };
serverThread.Start();
using var client = CultNetSchemaClients.CreateRudp(
runtimeId: "csharp-rudp-large-snapshot-client",
maxFragmentBytes: 1024);
client.OnCultNet<CultNetSnapshotResponseRawMessage>(response => responseCompletion.TrySetResult(response));
client.Connect("127.0.0.1", server.LocalEndPoint.Port);
await WaitUntilAsync(() => client.Connected, TimeSpan.FromSeconds(2));
client.SendCultNet(new CultNetSnapshotRequestMessage
{
MessageId = "large-snapshot",
SchemaIds = ["test.large.snapshot.v1"],
RecordKeys = ["test:large:snapshot"]
});
var completed = await Task.WhenAny(responseCompletion.Task, serverFailure.Task, Task.Delay(5000));
if (completed == serverFailure.Task) throw await serverFailure.Task;
if (completed != responseCompletion.Task)
Assert.Fail($"Large snapshot timed out; server sent {server.Stats.BytesSent} bytes, received {server.Stats.BytesReceived} bytes, transports {server.Profile.Transports.Count()}.");
var response = await AwaitWithTimeout(responseCompletion.Task, TimeSpan.FromMilliseconds(1));
cancellation.Cancel();
Assert.That(response.Documents, Has.Length.EqualTo(1));
Assert.That(response.Documents[0].Payload, Has.Length.EqualTo(128 * 1024));
}
[Test]
public void RudpSocketTransport_ErgonomicHelpersCarryNamedChannels()
{