CultLib/src/GameCult.Networking/CultNetRudpSchemaServer.cs

380 lines
15 KiB
C#
Raw Normal View History

2026-06-17 14:48:53 +01:00
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
2026-06-17 14:48:53 +01:00
using System.Net;
using System.Net.Sockets;
C#: a handler's fault ends the session without blaming the peer The schema server's backstop ended every session with "session refused a packet", including when the fault was the server's own: for example a handler's response too large to send, or a refusal the handler did not type. Decoding and handling are now two catches: - A message that cannot be decoded is the peer's. The session ends with the refusal reason. - A handler fault ends the session with "server could not handle a message". The transport's EndRefusedPeer becomes EndPeerSession(peer, reason). It reports whether it ended the session, so the log says when a response that failed after its first fragment had already ended it over the send. Before, the log reported that it ended a session that was already gone. The comment said that ending the session matched cultmesh-py. It does not: Python silently skips a malformed frame. The honest anchor is the C# TCP schema server, whose ServePeerAsync ends the one peer whose message fails to decode or handle. The comment now says so. Pinned, each by a test that kills its mutant: - a handler fault's goodbye carries the server's reason, not the refusal (mutant: the refusal reason); - the post-fragment-0 path logs that the session had already ended (mutant: a constant outcome); - EndPeerSession says no goodbye to a replaced peer's endpoint (mutant: the Ended check dropped); - a refused peer's frames still queued are never handled (mutant: the queue purge dropped). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 20:19:29 +02:00
using System.Text;
2026-06-17 14:48:53 +01:00
using System.Threading.Tasks;
using GameCult.Logging;
2026-06-17 14:48:53 +01:00
namespace GameCult.Networking
{
2026-07-14 03:26:43 +01:00
/// <summary>
/// Result of a bounded non-blocking RUDP schema-server drain.
/// </summary>
public readonly struct RudpCultNetSchemaPollResult
{
public RudpCultNetSchemaPollResult(int transportItemsConsumed, int messagesDispatched)
{
TransportItemsConsumed = transportItemsConsumed;
MessagesDispatched = messagesDispatched;
}
/// <summary>Gets transport work consumed, including ACK and connection control packets.</summary>
public int TransportItemsConsumed { get; }
/// <summary>Gets application schema messages dispatched.</summary>
public int MessagesDispatched { get; }
}
2026-06-17 14:48:53 +01:00
/// <summary>
/// Options for hosting schema-v0 messages over the native CultNet RUDP listener.
/// </summary>
public sealed class RudpCultNetSchemaServerOptions
{
/// <summary>
/// Gets or sets the runtime id advertised by the RUDP listener.
/// </summary>
public string RuntimeId { get; set; } = "csharp-rudp-schema-server";
/// <summary>
/// Gets or sets the UDP socket used by the listener. When omitted, a loopback socket is created.
/// </summary>
public Socket? Socket { get; set; }
/// <summary>
/// Gets or sets the accepted RUDP connection id.
/// </summary>
public uint ConnectionId { get; set; } = 0x43554c54;
/// <summary>
/// Gets or sets the first local packet sequence for each accepted peer. Unset, each peer's
/// session draws its own at random.
2026-06-17 14:48:53 +01:00
/// </summary>
public uint? InitialSequence { get; set; }
2026-06-17 14:48:53 +01:00
/// <summary>
/// Gets or sets the resend delay in milliseconds.
/// </summary>
public long ResendDelayMs { get; set; } = 25;
/// <summary>
/// Gets or sets the advertised transport id.
/// </summary>
public string TransportId { get; set; } = "schema-rudp";
/// <summary>
/// Gets or sets the maximum fragment size for schema-channel payloads.
/// </summary>
public int? MaxFragmentBytes { get; set; } = 1024;
/// <summary>
/// Gets or sets the maximum pending reliable packet count.
/// </summary>
public int? MaxPendingReliablePackets { get; set; }
/// <summary>
/// Gets or sets the payload sent with accept packets.
/// </summary>
public byte[]? AcceptPayload { get; set; }
}
/// <summary>
/// Peer context for a schema-v0 RUDP server.
/// </summary>
public sealed class RudpCultNetSchemaServerPeer : ICultNetSchemaServerPeer, ICultNetSchemaServerPeerLocation
2026-06-17 14:48:53 +01:00
{
private readonly RudpCultNetSchemaServer _server;
internal RudpCultNetSchemaServerPeer(
RudpCultNetSchemaServer server,
CultNetRudpSocketServerPeer transportPeer)
{
_server = server;
TransportPeer = transportPeer;
}
/// <summary>
/// Gets the underlying RUDP transport peer.
/// </summary>
public CultNetRudpSocketServerPeer TransportPeer { get; }
/// <summary>
/// Gets the UDP endpoint for this peer.
/// </summary>
public EndPoint RemoteEndPoint => TransportPeer.RemoteEndPoint;
/// <summary>
/// Sends a schema-v0 response to this peer.
/// </summary>
public void SendCultNet<TMessage>(TMessage message)
where TMessage : ICultNetSchemaMessage
{
_server.SendCultNet(TransportPeer, message);
}
}
/// <summary>
/// Multi-peer schema-v0 host over the native CultNet RUDP transport.
/// </summary>
public sealed class RudpCultNetSchemaServer : ICultNetSchemaServer, ICultNetSchemaServerPeerLifecycle, IDisposable
2026-06-17 14:48:53 +01:00
{
private readonly Socket _socket;
private readonly CultNetRudpSocketTransportServer _transport;
private readonly ConcurrentDictionary<Type, Delegate> _handlers = new();
private readonly ConcurrentDictionary<Delegate, Delegate> _schemaPeerAdapters = new();
2026-06-17 14:48:53 +01:00
private bool _disposed;
private ILogger _logger = new NullLogger();
/// <summary>
/// Gets or sets the logger used by the server. R-AM: the dispatch backstop in DispatchAsync
/// logs every untyped fault through this instead of swallowing it silently.
/// </summary>
public ILogger Logger
{
get => _logger;
set => _logger = value ?? new NullLogger();
}
2026-06-17 14:48:53 +01:00
/// <summary>
/// Creates a schema-v0 RUDP server.
/// </summary>
public RudpCultNetSchemaServer(RudpCultNetSchemaServerOptions? options = null)
{
options ??= new RudpCultNetSchemaServerOptions();
var socket = options.Socket;
if (socket == null)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
}
_socket = socket;
_transport = new CultNetRudpSocketTransportServer(new CultNetRudpSocketTransportServerOptions
{
RuntimeId = options.RuntimeId,
Socket = socket,
ConnectionId = options.ConnectionId,
InitialSequence = options.InitialSequence,
ResendDelayMs = options.ResendDelayMs,
TransportId = options.TransportId,
MaxFragmentBytes = options.MaxFragmentBytes,
MaxPendingReliablePackets = options.MaxPendingReliablePackets,
AcceptPayload = options.AcceptPayload
});
_transport.PeerDisconnected += OnTransportPeerDisconnected;
2026-06-17 14:48:53 +01:00
}
/// <summary>
/// Gets the underlying RUDP listener profile.
/// </summary>
public CultNetTransportProfile Profile => _transport.Profile;
/// <summary>
/// Gets the local UDP endpoint.
/// </summary>
public IPEndPoint LocalEndPoint => (IPEndPoint)_socket.LocalEndPoint!;
/// <summary>
/// Gets a snapshot of the current transfer counters.
/// </summary>
public CultNetTransportStats Stats => _transport.Stats;
C#: a handler's fault ends the session without blaming the peer The schema server's backstop ended every session with "session refused a packet", including when the fault was the server's own: for example a handler's response too large to send, or a refusal the handler did not type. Decoding and handling are now two catches: - A message that cannot be decoded is the peer's. The session ends with the refusal reason. - A handler fault ends the session with "server could not handle a message". The transport's EndRefusedPeer becomes EndPeerSession(peer, reason). It reports whether it ended the session, so the log says when a response that failed after its first fragment had already ended it over the send. Before, the log reported that it ended a session that was already gone. The comment said that ending the session matched cultmesh-py. It does not: Python silently skips a malformed frame. The honest anchor is the C# TCP schema server, whose ServePeerAsync ends the one peer whose message fails to decode or handle. The comment now says so. Pinned, each by a test that kills its mutant: - a handler fault's goodbye carries the server's reason, not the refusal (mutant: the refusal reason); - the post-fragment-0 path logs that the session had already ended (mutant: a constant outcome); - EndPeerSession says no goodbye to a replaced peer's endpoint (mutant: the Ended check dropped); - a refused peer's frames still queued are never handled (mutant: the queue purge dropped). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 20:19:29 +02:00
// The listener this server drives, for tests that inject send failures through its seams.
internal CultNetRudpSocketTransportServer Transport => _transport;
/// <summary>
/// Gets the currently tracked RUDP peers.
/// </summary>
public IReadOnlyCollection<CultNetRudpSocketServerPeer> Peers => _transport.Peers;
/// <inheritdoc />
public event Action<ICultNetSchemaServerPeer>? PeerDisconnected;
2026-06-17 14:48:53 +01:00
/// <summary>
/// Registers a schema-v0 handler.
/// </summary>
public void OnCultNet<TMessage>(Func<TMessage, RudpCultNetSchemaServerPeer, Task> callback)
where TMessage : ICultNetSchemaMessage
{
if (callback == null) throw new ArgumentNullException(nameof(callback));
_handlers.AddOrUpdate(
typeof(TMessage),
_ => callback,
(type, current) =>
{
var combined = Delegate.Combine(current, callback) as Func<TMessage, RudpCultNetSchemaServerPeer, Task>;
return combined ?? throw new InvalidOperationException($"Failed to combine delegates for {type.Name}.");
});
}
/// <summary>
/// Registers a schema-v0 handler.
/// </summary>
public void OnCultNet<TMessage>(Action<TMessage, RudpCultNetSchemaServerPeer> callback)
where TMessage : ICultNetSchemaMessage
{
if (callback == null) throw new ArgumentNullException(nameof(callback));
OnCultNet<TMessage>((message, peer) =>
{
callback(message, peer);
return Task.CompletedTask;
});
}
/// <inheritdoc />
public void OnCultNet<TMessage>(Func<TMessage, ICultNetSchemaServerPeer, Task> callback)
where TMessage : ICultNetSchemaMessage
{
if (callback == null) throw new ArgumentNullException(nameof(callback));
Func<TMessage, RudpCultNetSchemaServerPeer, Task> adapter = (message, peer) => callback(message, peer);
_schemaPeerAdapters[callback] = adapter;
OnCultNet(adapter);
}
/// <inheritdoc />
public void RemoveCultNetMessageListener<TMessage>(Delegate callback)
where TMessage : ICultNetSchemaMessage
{
if (_schemaPeerAdapters.TryRemove(callback, out var adapter))
{
callback = adapter;
}
if (!_handlers.TryGetValue(typeof(TMessage), out var current))
{
return;
}
var next = Delegate.Remove(current, callback);
if (next == null)
{
_handlers.TryRemove(typeof(TMessage), out _);
}
else
{
_handlers[typeof(TMessage)] = next;
}
}
2026-06-17 14:48:53 +01:00
/// <summary>
/// Sends a schema-v0 message to a transport peer.
/// </summary>
public void SendCultNet<TMessage>(CultNetRudpSocketServerPeer peer, TMessage message)
where TMessage : ICultNetSchemaMessage
{
_transport.SendSchemaMessage(peer, message);
}
/// <summary>
/// Polls one packet/frame and dispatches at most one schema-v0 message.
/// </summary>
public async Task<bool> PollOnceAsync()
{
2026-07-14 03:26:43 +01:00
if (!_transport.TryReceiveOnce(out var delivered) || delivered == null)
2026-06-17 14:48:53 +01:00
{
return false;
}
2026-07-14 03:26:43 +01:00
return await DispatchAsync(delivered).ConfigureAwait(false);
}
/// <summary>
/// Drains up to <paramref name="maxTransportItems"/> immediately available transport work items.
/// Control packets count as progress so callers only idle when the transport is actually empty.
/// </summary>
public async Task<RudpCultNetSchemaPollResult> PollAvailableAsync(int maxTransportItems)
{
if (maxTransportItems <= 0) throw new ArgumentOutOfRangeException(nameof(maxTransportItems));
var consumed = 0;
var dispatched = 0;
while (consumed < maxTransportItems && _transport.TryReceiveOnce(out var delivered))
{
consumed++;
if (delivered != null && await DispatchAsync(delivered).ConfigureAwait(false))
dispatched++;
}
return new RudpCultNetSchemaPollResult(consumed, dispatched);
}
C#: a handler's fault ends the session without blaming the peer The schema server's backstop ended every session with "session refused a packet", including when the fault was the server's own: for example a handler's response too large to send, or a refusal the handler did not type. Decoding and handling are now two catches: - A message that cannot be decoded is the peer's. The session ends with the refusal reason. - A handler fault ends the session with "server could not handle a message". The transport's EndRefusedPeer becomes EndPeerSession(peer, reason). It reports whether it ended the session, so the log says when a response that failed after its first fragment had already ended it over the send. Before, the log reported that it ended a session that was already gone. The comment said that ending the session matched cultmesh-py. It does not: Python silently skips a malformed frame. The honest anchor is the C# TCP schema server, whose ServePeerAsync ends the one peer whose message fails to decode or handle. The comment now says so. Pinned, each by a test that kills its mutant: - a handler fault's goodbye carries the server's reason, not the refusal (mutant: the refusal reason); - the post-fragment-0 path logs that the session had already ended (mutant: a constant outcome); - EndPeerSession says no goodbye to a replaced peer's endpoint (mutant: the Ended check dropped); - a refused peer's frames still queued are never handled (mutant: the queue purge dropped). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 20:19:29 +02:00
/// <summary>
/// The goodbye's reason when a handler fails on a peer's message: the server could not handle
/// it, which says nothing about whether the peer's packet was well formed.
/// </summary>
internal static readonly byte[] HandlerFailedReason = Encoding.UTF8.GetBytes("server could not handle a message");
private static string SessionOutcome(bool ended) =>
ended ? "that peer's session ended." : "that peer's session had already ended.";
2026-07-14 03:26:43 +01:00
private async Task<bool> DispatchAsync(CultNetRudpSocketServerFrame delivered)
{
if (!string.Equals(delivered.Frame.ChannelId, "schema", StringComparison.Ordinal))
return false;
C#: a peer's undecodable message ends that peer's session, never the poll RudpCultNetSchemaServer decoded each schema frame outside its per-message backstop, so a malformed payload (0xc1) or a well-formed message with an unknown schemaVersion threw MessagePackSerializationException out of PollAvailableAsync and PollOnceAsync. The drain aborted: a good peer's request in the same drain went unserved, a consumer loop that did not catch died, and the bad frame was already acknowledged while its peer stayed connected. Decoding now runs inside the backstop. A peer whose message cannot be decoded or handled has its session ended: the transport's new EndRefusedPeer sends the refusal goodbye under the gate, counts the drop in PacketsDropped, drops that peer's frames still queued, forgets the peer and raises PeerDisconnected. A session that already ended (replaced by a new Connect, or ended by a send failure) gets no goodbye, since the endpoint may belong to a new session. Other peers in the drain are still served. Ending the session matches cultmesh-py's server, where one peer's bad message ends that peer; runtime parity is the reason. The log names the fault's type only and never its message, because the decoder's message quotes the peer's input (the unknown schemaVersion). The dispatch-backstop test now asserts that rule instead of the handler message it used to require. Tests, each failing on the pre-fix code: a malformed payload and an unknown schemaVersion each leave the good peer served without Poll throwing (also through PollOnceAsync); the bad peer's session ends, counted and told; the log carries the type and not the canary value. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 17:23:40 +02:00
// A peer's message that cannot be decoded (malformed bytes, an unknown schemaVersion) or
C#: a handler's fault ends the session without blaming the peer The schema server's backstop ended every session with "session refused a packet", including when the fault was the server's own: for example a handler's response too large to send, or a refusal the handler did not type. Decoding and handling are now two catches: - A message that cannot be decoded is the peer's. The session ends with the refusal reason. - A handler fault ends the session with "server could not handle a message". The transport's EndRefusedPeer becomes EndPeerSession(peer, reason). It reports whether it ended the session, so the log says when a response that failed after its first fragment had already ended it over the send. Before, the log reported that it ended a session that was already gone. The comment said that ending the session matched cultmesh-py. It does not: Python silently skips a malformed frame. The honest anchor is the C# TCP schema server, whose ServePeerAsync ends the one peer whose message fails to decode or handle. The comment now says so. Pinned, each by a test that kills its mutant: - a handler fault's goodbye carries the server's reason, not the refusal (mutant: the refusal reason); - the post-fragment-0 path logs that the session had already ended (mutant: a constant outcome); - EndPeerSession says no goodbye to a replaced peer's endpoint (mutant: the Ended check dropped); - a refused peer's frames still queued are never handled (mutant: the queue purge dropped). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 20:19:29 +02:00
// handled ends that peer's session, never the poll: the drain goes on serving every other
// peer. The transport already acknowledged the frame, so the session cannot be kept (a
// retransmit would never be handled). The peer is told, and the drop is counted and logged.
// The C# TCP schema server (CultNetTcpSchemaTransport.ServePeerAsync) likewise ends the one
// peer whose message fails to decode or handle. A handler is still expected to answer its
// own typed refusals on the wire (HandleSnapshotRequestV1Async does, R-AM); this is the
// backstop for whatever it does not. The log names the fault's type only: its message can
// quote what the peer sent.
ICultNetSchemaMessage message;
R-AG/R-AK: checked C# cursor-length arithmetic, a dispatch backstop, and the redundant guard R-AG. ReadLengthPrefixedFields tested pos + length > bytes.Length in int math; a length prefix near int.MaxValue overflowed the unchecked add, slipped past the guard, and Encoding.UTF8.GetString threw ArgumentOutOfRangeException instead of this method returning null the way every other malformed shape already does. Promotes to long before the add, which cannot itself overflow (both operands stay far under long's range), so the guard sees the true sum. CultNetRudpSchemaServer.DispatchAsync gains a catch around the handler invocation: HandleSnapshotRequestV1Async already answers cursor_invalid/selection_invalid/reference_outside_target for its three typed exceptions, but nothing stopped an untyped one from an unanticipated bug reaching DynamicInvoke's caller and stalling the poll loop for every other peer. Answers nothing on the wire (an exception this generic carries no typed refusal to report) and drops the one malformed dispatch, the same as an unregistered handler already does. Hostile-cursor tests (CultNetSelectionFixBatchTests.cs) feed CultNetSelectionCursor.Parse a length prefix near int.MaxValue (C#'s own proven overflow), near usize::MAX (Rust's proven overflow, fed here too per the ruling), wider than any integer type, and negative-looking - each asserted to throw the typed CultNetSelectionCursorException. R-AK. Deletes ReferenceMembers's `!member.IsReference` guard. CultCache.ReferencesOf (CultCache.cs:262-278) already searches only its own reference members for a role match and returns empty for anything else; index aliases are unique per descriptor, so a data member's own role string can never coincide with a reference member's. Verified before deleting: traced ReferencesOf's role lookup directly rather than trusting the ruling's premise. A second copy of the same exclusion here was duplicate authority, not a second decision. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 04:44:09 +02:00
try
2026-06-17 14:48:53 +01:00
{
C#: a handler's fault ends the session without blaming the peer The schema server's backstop ended every session with "session refused a packet", including when the fault was the server's own: for example a handler's response too large to send, or a refusal the handler did not type. Decoding and handling are now two catches: - A message that cannot be decoded is the peer's. The session ends with the refusal reason. - A handler fault ends the session with "server could not handle a message". The transport's EndRefusedPeer becomes EndPeerSession(peer, reason). It reports whether it ended the session, so the log says when a response that failed after its first fragment had already ended it over the send. Before, the log reported that it ended a session that was already gone. The comment said that ending the session matched cultmesh-py. It does not: Python silently skips a malformed frame. The honest anchor is the C# TCP schema server, whose ServePeerAsync ends the one peer whose message fails to decode or handle. The comment now says so. Pinned, each by a test that kills its mutant: - a handler fault's goodbye carries the server's reason, not the refusal (mutant: the refusal reason); - the post-fragment-0 path logs that the session had already ended (mutant: a constant outcome); - EndPeerSession says no goodbye to a replaced peer's endpoint (mutant: the Ended check dropped); - a refused peer's frames still queued are never handled (mutant: the queue purge dropped). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 20:19:29 +02:00
message = CultNetSchemaMessageSerialization.Deserialize(delivered.Frame.Payload);
}
catch (Exception ex)
{
// The peer sent something no runtime can read: the refusal is the peer's.
var ended = _transport.EndPeerSession(delivered.Peer, CultNetRudpSession.RefusedPacketReason);
Logger.LogError($"CultNet RUDP schema server could not decode a peer's message ({ex.GetType().Name}); {SessionOutcome(ended)}");
return false;
}
C#: a peer's undecodable message ends that peer's session, never the poll RudpCultNetSchemaServer decoded each schema frame outside its per-message backstop, so a malformed payload (0xc1) or a well-formed message with an unknown schemaVersion threw MessagePackSerializationException out of PollAvailableAsync and PollOnceAsync. The drain aborted: a good peer's request in the same drain went unserved, a consumer loop that did not catch died, and the bad frame was already acknowledged while its peer stayed connected. Decoding now runs inside the backstop. A peer whose message cannot be decoded or handled has its session ended: the transport's new EndRefusedPeer sends the refusal goodbye under the gate, counts the drop in PacketsDropped, drops that peer's frames still queued, forgets the peer and raises PeerDisconnected. A session that already ended (replaced by a new Connect, or ended by a send failure) gets no goodbye, since the endpoint may belong to a new session. Other peers in the drain are still served. Ending the session matches cultmesh-py's server, where one peer's bad message ends that peer; runtime parity is the reason. The log names the fault's type only and never its message, because the decoder's message quotes the peer's input (the unknown schemaVersion). The dispatch-backstop test now asserts that rule instead of the handler message it used to require. Tests, each failing on the pre-fix code: a malformed payload and an unknown schemaVersion each leave the good peer served without Poll throwing (also through PollOnceAsync); the bad peer's session ends, counted and told; the log carries the type and not the canary value. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 17:23:40 +02:00
C#: a handler's fault ends the session without blaming the peer The schema server's backstop ended every session with "session refused a packet", including when the fault was the server's own: for example a handler's response too large to send, or a refusal the handler did not type. Decoding and handling are now two catches: - A message that cannot be decoded is the peer's. The session ends with the refusal reason. - A handler fault ends the session with "server could not handle a message". The transport's EndRefusedPeer becomes EndPeerSession(peer, reason). It reports whether it ended the session, so the log says when a response that failed after its first fragment had already ended it over the send. Before, the log reported that it ended a session that was already gone. The comment said that ending the session matched cultmesh-py. It does not: Python silently skips a malformed frame. The honest anchor is the C# TCP schema server, whose ServePeerAsync ends the one peer whose message fails to decode or handle. The comment now says so. Pinned, each by a test that kills its mutant: - a handler fault's goodbye carries the server's reason, not the refusal (mutant: the refusal reason); - the post-fragment-0 path logs that the session had already ended (mutant: a constant outcome); - EndPeerSession says no goodbye to a replaced peer's endpoint (mutant: the Ended check dropped); - a refused peer's frames still queued are never handled (mutant: the queue purge dropped). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 20:19:29 +02:00
if (!_handlers.TryGetValue(message.GetType(), out var handler) || handler == null)
{
return false;
}
try
{
R-AG/R-AK: checked C# cursor-length arithmetic, a dispatch backstop, and the redundant guard R-AG. ReadLengthPrefixedFields tested pos + length > bytes.Length in int math; a length prefix near int.MaxValue overflowed the unchecked add, slipped past the guard, and Encoding.UTF8.GetString threw ArgumentOutOfRangeException instead of this method returning null the way every other malformed shape already does. Promotes to long before the add, which cannot itself overflow (both operands stay far under long's range), so the guard sees the true sum. CultNetRudpSchemaServer.DispatchAsync gains a catch around the handler invocation: HandleSnapshotRequestV1Async already answers cursor_invalid/selection_invalid/reference_outside_target for its three typed exceptions, but nothing stopped an untyped one from an unanticipated bug reaching DynamicInvoke's caller and stalling the poll loop for every other peer. Answers nothing on the wire (an exception this generic carries no typed refusal to report) and drops the one malformed dispatch, the same as an unregistered handler already does. Hostile-cursor tests (CultNetSelectionFixBatchTests.cs) feed CultNetSelectionCursor.Parse a length prefix near int.MaxValue (C#'s own proven overflow), near usize::MAX (Rust's proven overflow, fed here too per the ruling), wider than any integer type, and negative-looking - each asserted to throw the typed CultNetSelectionCursorException. R-AK. Deletes ReferenceMembers's `!member.IsReference` guard. CultCache.ReferencesOf (CultCache.cs:262-278) already searches only its own reference members for a role match and returns empty for anything else; index aliases are unique per descriptor, so a data member's own role string can never coincide with a reference member's. Verified before deleting: traced ReferencesOf's role lookup directly rather than trusting the ruling's premise. A second copy of the same exclusion here was duplicate authority, not a second decision. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 04:44:09 +02:00
var result = handler.DynamicInvoke(message, new RudpCultNetSchemaServerPeer(this, delivered.Peer));
if (result is Task task)
{
await task.ConfigureAwait(false);
}
}
catch (Exception ex)
R-AG/R-AK: checked C# cursor-length arithmetic, a dispatch backstop, and the redundant guard R-AG. ReadLengthPrefixedFields tested pos + length > bytes.Length in int math; a length prefix near int.MaxValue overflowed the unchecked add, slipped past the guard, and Encoding.UTF8.GetString threw ArgumentOutOfRangeException instead of this method returning null the way every other malformed shape already does. Promotes to long before the add, which cannot itself overflow (both operands stay far under long's range), so the guard sees the true sum. CultNetRudpSchemaServer.DispatchAsync gains a catch around the handler invocation: HandleSnapshotRequestV1Async already answers cursor_invalid/selection_invalid/reference_outside_target for its three typed exceptions, but nothing stopped an untyped one from an unanticipated bug reaching DynamicInvoke's caller and stalling the poll loop for every other peer. Answers nothing on the wire (an exception this generic carries no typed refusal to report) and drops the one malformed dispatch, the same as an unregistered handler already does. Hostile-cursor tests (CultNetSelectionFixBatchTests.cs) feed CultNetSelectionCursor.Parse a length prefix near int.MaxValue (C#'s own proven overflow), near usize::MAX (Rust's proven overflow, fed here too per the ruling), wider than any integer type, and negative-looking - each asserted to throw the typed CultNetSelectionCursorException. R-AK. Deletes ReferenceMembers's `!member.IsReference` guard. CultCache.ReferencesOf (CultCache.cs:262-278) already searches only its own reference members for a role match and returns empty for anything else; index aliases are unique per descriptor, so a data member's own role string can never coincide with a reference member's. Verified before deleting: traced ReferencesOf's role lookup directly rather than trusting the ruling's premise. A second copy of the same exclusion here was duplicate authority, not a second decision. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 04:44:09 +02:00
{
C#: a peer's undecodable message ends that peer's session, never the poll RudpCultNetSchemaServer decoded each schema frame outside its per-message backstop, so a malformed payload (0xc1) or a well-formed message with an unknown schemaVersion threw MessagePackSerializationException out of PollAvailableAsync and PollOnceAsync. The drain aborted: a good peer's request in the same drain went unserved, a consumer loop that did not catch died, and the bad frame was already acknowledged while its peer stayed connected. Decoding now runs inside the backstop. A peer whose message cannot be decoded or handled has its session ended: the transport's new EndRefusedPeer sends the refusal goodbye under the gate, counts the drop in PacketsDropped, drops that peer's frames still queued, forgets the peer and raises PeerDisconnected. A session that already ended (replaced by a new Connect, or ended by a send failure) gets no goodbye, since the endpoint may belong to a new session. Other peers in the drain are still served. Ending the session matches cultmesh-py's server, where one peer's bad message ends that peer; runtime parity is the reason. The log names the fault's type only and never its message, because the decoder's message quotes the peer's input (the unknown schemaVersion). The dispatch-backstop test now asserts that rule instead of the handler message it used to require. Tests, each failing on the pre-fix code: a malformed payload and an unknown schemaVersion each leave the good peer served without Poll throwing (also through PollOnceAsync); the bad peer's session ends, counted and told; the log carries the type and not the canary value. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 17:23:40 +02:00
// DynamicInvoke wraps a synchronously-thrown handler fault in TargetInvocationException;
C#: a handler's fault ends the session without blaming the peer The schema server's backstop ended every session with "session refused a packet", including when the fault was the server's own: for example a handler's response too large to send, or a refusal the handler did not type. Decoding and handling are now two catches: - A message that cannot be decoded is the peer's. The session ends with the refusal reason. - A handler fault ends the session with "server could not handle a message". The transport's EndRefusedPeer becomes EndPeerSession(peer, reason). It reports whether it ended the session, so the log says when a response that failed after its first fragment had already ended it over the send. Before, the log reported that it ended a session that was already gone. The comment said that ending the session matched cultmesh-py. It does not: Python silently skips a malformed frame. The honest anchor is the C# TCP schema server, whose ServePeerAsync ends the one peer whose message fails to decode or handle. The comment now says so. Pinned, each by a test that kills its mutant: - a handler fault's goodbye carries the server's reason, not the refusal (mutant: the refusal reason); - the post-fragment-0 path logs that the session had already ended (mutant: a constant outcome); - EndPeerSession says no goodbye to a replaced peer's endpoint (mutant: the Ended check dropped); - a refused peer's frames still queued are never handled (mutant: the queue purge dropped). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 20:19:29 +02:00
// name the real fault, not that wrapper. The fault is the server's (a response too large
// to send, a handler bug) or a refusal the handler did not type, so the goodbye does not
// say the peer's packet was refused. A response that failed after its first fragment
// already ended the session over the send, and the log says so.
var reported = ex is System.Reflection.TargetInvocationException { InnerException: { } inner } ? inner : ex;
C#: a handler's fault ends the session without blaming the peer The schema server's backstop ended every session with "session refused a packet", including when the fault was the server's own: for example a handler's response too large to send, or a refusal the handler did not type. Decoding and handling are now two catches: - A message that cannot be decoded is the peer's. The session ends with the refusal reason. - A handler fault ends the session with "server could not handle a message". The transport's EndRefusedPeer becomes EndPeerSession(peer, reason). It reports whether it ended the session, so the log says when a response that failed after its first fragment had already ended it over the send. Before, the log reported that it ended a session that was already gone. The comment said that ending the session matched cultmesh-py. It does not: Python silently skips a malformed frame. The honest anchor is the C# TCP schema server, whose ServePeerAsync ends the one peer whose message fails to decode or handle. The comment now says so. Pinned, each by a test that kills its mutant: - a handler fault's goodbye carries the server's reason, not the refusal (mutant: the refusal reason); - the post-fragment-0 path logs that the session had already ended (mutant: a constant outcome); - EndPeerSession says no goodbye to a replaced peer's endpoint (mutant: the Ended check dropped); - a refused peer's frames still queued are never handled (mutant: the queue purge dropped). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 20:19:29 +02:00
var ended = _transport.EndPeerSession(delivered.Peer, HandlerFailedReason);
Logger.LogError($"CultNet RUDP schema server's {message.GetType().Name} handler failed ({reported.GetType().Name}); {SessionOutcome(ended)}");
R-AG/R-AK: checked C# cursor-length arithmetic, a dispatch backstop, and the redundant guard R-AG. ReadLengthPrefixedFields tested pos + length > bytes.Length in int math; a length prefix near int.MaxValue overflowed the unchecked add, slipped past the guard, and Encoding.UTF8.GetString threw ArgumentOutOfRangeException instead of this method returning null the way every other malformed shape already does. Promotes to long before the add, which cannot itself overflow (both operands stay far under long's range), so the guard sees the true sum. CultNetRudpSchemaServer.DispatchAsync gains a catch around the handler invocation: HandleSnapshotRequestV1Async already answers cursor_invalid/selection_invalid/reference_outside_target for its three typed exceptions, but nothing stopped an untyped one from an unanticipated bug reaching DynamicInvoke's caller and stalling the poll loop for every other peer. Answers nothing on the wire (an exception this generic carries no typed refusal to report) and drops the one malformed dispatch, the same as an unregistered handler already does. Hostile-cursor tests (CultNetSelectionFixBatchTests.cs) feed CultNetSelectionCursor.Parse a length prefix near int.MaxValue (C#'s own proven overflow), near usize::MAX (Rust's proven overflow, fed here too per the ruling), wider than any integer type, and negative-looking - each asserted to throw the typed CultNetSelectionCursorException. R-AK. Deletes ReferenceMembers's `!member.IsReference` guard. CultCache.ReferencesOf (CultCache.cs:262-278) already searches only its own reference members for a role match and returns empty for anything else; index aliases are unique per descriptor, so a data member's own role string can never coincide with a reference member's. Verified before deleting: traced ReferencesOf's role lookup directly rather than trusting the ruling's premise. A second copy of the same exclusion here was duplicate authority, not a second decision. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 04:44:09 +02:00
return false;
2026-06-17 14:48:53 +01:00
}
return true;
}
/// <summary>
/// Sends any reliable packets whose resend timers are due.
/// </summary>
public void PollResends()
{
_transport.PollResends();
}
/// <inheritdoc />
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
_transport.PeerDisconnected -= OnTransportPeerDisconnected;
2026-06-17 14:48:53 +01:00
_transport.Dispose();
}
private void OnTransportPeerDisconnected(CultNetRudpSocketServerPeer peer)
{
PeerDisconnected?.Invoke(new RudpCultNetSchemaServerPeer(this, peer));
}
2026-06-17 14:48:53 +01:00
}
}