Merge origin/main into hands/variants-c2a-main (main-into-c2a)

Sixteen conflicted files resolved by the spec's rule: main owns payload
ownership, bounds and the Clock seam; C2a owns persistence semantics and exact
binding. MintStoredAt is internal static (previous, now); the cache and the
store pass their cache's Clock. Package versions are main's. The cultmesh-ts
payload-parse acceptance and its test are deleted under retire-schema-alias;
peer snapshot reads take the schema's own id, else an id the definition lists
as compatible. The held firstRecordAtKey fallback is removed: main's handles
take definitions only, so nothing could reach it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-14 04:06:41 +02:00
commit 3b83cb6c08
287 changed files with 55077 additions and 1820 deletions

View file

@ -56,9 +56,12 @@ public static class CultDocumentMessagePackSerialization
private static MessagePackSerializerOptions Compose(IFormatterResolver[] consumerResolvers)
{
// The guard goes first and wraps whatever formatter the rest of the composite would hand out, so a consumer
// resolver still encodes an arm while the key check runs.
var inner = CompositeResolver.Create(
consumerResolvers.Append(CultDocumentResolver.Instance).Append(CultMathResolver.Instance).Append(StandardResolver.Instance).ToArray());
return MessagePackSerializerOptions.Standard
.WithResolver(CompositeResolver.Create(
consumerResolvers.Append(CultDocumentResolver.Instance).Append(CultMathResolver.Instance).Append(StandardResolver.Instance).ToArray()))
.WithResolver(CompositeResolver.Create(new CultUnionGuard(inner), inner))
.WithSecurity(CultMessagePackSecurity.Instance);
}
@ -81,7 +84,9 @@ public static class CultDocumentMessagePackSerialization
{
if (registry == null) throw new ArgumentNullException(nameof(registry));
if (value != null) registry.GetRequired(type);
return MessagePackSerializer.Serialize(type, value, OptionsFor(type.Assembly));
var payload = MessagePackSerializer.Serialize(type, value, OptionsFor(type.Assembly));
CultPayloadDepth.Check(payload, type, PayloadDirection.Write);
return payload;
}
public static object DeserializeUntyped(Type type, byte[] payload)
@ -93,6 +98,7 @@ public static class CultDocumentMessagePackSerialization
{
if (registry == null) throw new ArgumentNullException(nameof(registry));
registry.GetRequired(type);
CultPayloadDepth.Check(payload, type, PayloadDirection.Read);
return MessagePackSerializer.Deserialize(type, payload, OptionsFor(type.Assembly))
?? throw new InvalidOperationException($"MessagePack returned null for Cult document type {type.FullName}.");
}

View file

@ -7,7 +7,15 @@ namespace GameCult.Caching.MessagePack;
// UntrustedData, plus a collision-resistant comparer for CultRecordRef<T> dictionary keys over the key string.
public sealed class CultMessagePackSecurity : MessagePackSecurity
{
public static readonly CultMessagePackSecurity Instance = new(UntrustedData);
/// <summary>
/// The deepest a document payload may nest, on read and on write, in every CultCache runtime: every MessagePack array and
/// map counts, read by a formatter or skipped past it, and the outermost array is depth 1. A payload of this depth is
/// accepted and one container deeper is refused. MessagePack's own object-graph counter is set to the same value as a
/// backstop; the rule itself is <c>CultPayloadDepth.Check</c>, run by the document serialization entry points.
/// </summary>
public const int MaximumPayloadDepth = 256;
public static readonly CultMessagePackSecurity Instance = new(UntrustedData.WithMaximumObjectGraphDepth(MaximumPayloadDepth));
private CultMessagePackSecurity(MessagePackSecurity copyFrom) : base(copyFrom) { }

View file

@ -0,0 +1,94 @@
using System;
using System.Buffers.Binary;
using MessagePack;
namespace GameCult.Caching.MessagePack;
internal enum PayloadDirection { Read, Write }
/// <summary>
/// The one payload nesting count. Walks the MessagePack headers of a document payload iteratively, counting every array and
/// map (read by a formatter or skipped past it; the outermost array is depth 1) and refusing the first container past
/// <see cref="CultMessagePackSecurity.MaximumPayloadDepth"/>. Scalars are skipped by length, nothing is allocated per
/// element, and the count stack is bounded by the limit. A refusal names the type, the depth reached and the limit,
/// never payload bytes. A payload that ends early is the deserializer's to refuse.
/// </summary>
internal static class CultPayloadDepth
{
public static void Check(ReadOnlySpan<byte> bytes, Type type, PayloadDirection direction)
{
const int limit = CultMessagePackSecurity.MaximumPayloadDepth;
Span<long> remaining = stackalloc long[limit];
var depth = 0;
long position = 0;
while (position < bytes.Length)
{
var code = bytes[(int)position];
long children = 0;
long header = 0;
long skip = 0;
var container = false;
switch (code)
{
case <= 0x7f or >= 0xe0 or 0xc0 or 0xc1 or 0xc2 or 0xc3: skip = 1; break;
case <= 0x8f: container = true; header = 1; children = 2L * (code & 0x0f); break;
case <= 0x9f: container = true; header = 1; children = code & 0x0f; break;
case <= 0xbf: skip = 1 + (code & 0x1f); break;
case 0xc4 or 0xd9: if (!Length(bytes, position, 1, out var l8)) return; skip = 2 + l8; break;
case 0xc5 or 0xda: if (!Length(bytes, position, 2, out var l16)) return; skip = 3 + l16; break;
case 0xc6 or 0xdb: if (!Length(bytes, position, 4, out var l32)) return; skip = 5 + l32; break;
case 0xc7: if (!Length(bytes, position, 1, out var e8)) return; skip = 3 + e8; break;
case 0xc8: if (!Length(bytes, position, 2, out var e16)) return; skip = 4 + e16; break;
case 0xc9: if (!Length(bytes, position, 4, out var e32)) return; skip = 6 + e32; break;
case 0xca or 0xce or 0xd2: skip = 5; break;
case 0xcb or 0xcf or 0xd3: skip = 9; break;
case 0xcc or 0xd0: skip = 2; break;
case 0xcd or 0xd1 or 0xd4: skip = 3; break;
case 0xd5: skip = 4; break;
case 0xd6: skip = 6; break;
case 0xd7: skip = 10; break;
case 0xd8: skip = 18; break;
case 0xdc: if (!Length(bytes, position, 2, out var a16)) return; container = true; header = 3; children = a16; break;
case 0xdd: if (!Length(bytes, position, 4, out var a32)) return; container = true; header = 5; children = a32; break;
case 0xde: if (!Length(bytes, position, 2, out var m16)) return; container = true; header = 3; children = 2 * m16; break;
default: if (!Length(bytes, position, 4, out var m32)) return; container = true; header = 5; children = 2 * m32; break;
}
if (container)
{
if (depth == limit)
throw new MessagePackSerializationException(
$"{type.FullName} payload nests {limit + 1} MessagePack containers deep; the limit is {limit} (refused on {(direction == PayloadDirection.Read ? "read" : "write")}).");
position += header;
if (children > 0)
{
remaining[depth++] = children;
continue;
}
}
else
{
position += skip;
}
// One element is complete; close every container it was the last element of.
while (depth > 0 && --remaining[depth - 1] == 0) depth--;
if (depth == 0) return;
}
}
// The big-endian length that follows the code byte, when the payload is long enough to hold it.
private static bool Length(ReadOnlySpan<byte> bytes, long position, int width, out long length)
{
length = 0;
if (position + 1 + width > bytes.Length) return false;
var field = bytes.Slice((int)position + 1, width);
length = width switch
{
1 => field[0],
2 => BinaryPrimitives.ReadUInt16BigEndian(field),
_ => BinaryPrimitives.ReadUInt32BigEndian(field)
};
return true;
}
}

View file

@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using MessagePack;
using MessagePack.Formatters;
namespace GameCult.Caching.MessagePack;
/// <summary>
/// The one place an unknown union arm or an unnamed subtype is decided. A union is an abstract class or interface carrying
/// its own [Union] attributes (never inherited: a union whose arms are also a union has its own key set). MessagePack-CSharp
/// still encodes the [key, armSlots] shape; this wraps its formatter so that a key the union does not declare is refused on
/// read, and a value whose runtime type is not a declared arm is refused on write, where MessagePack alone yields null and nil.
/// </summary>
internal sealed class CultUnionGuard(IFormatterResolver inner) : IFormatterResolver
{
public IMessagePackFormatter<T>? GetFormatter<T>()
{
var arms = typeof(T).GetCustomAttributes<UnionAttribute>(inherit: false).ToArray();
return arms.Length == 0 || inner.GetFormatter<T>() is not { } formatter ? null : new Formatter<T>(formatter, arms);
}
private sealed class Formatter<T>(IMessagePackFormatter<T> inner, UnionAttribute[] arms) : IMessagePackFormatter<T>
{
private readonly HashSet<int> keys = arms.Select(arm => arm.Key).ToHashSet();
private readonly HashSet<Type> types = arms.Select(arm => arm.SubType).ToHashSet();
public void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options)
{
if (value != null && !types.Contains(value.GetType()))
throw new MessagePackSerializationException($"{value.GetType().FullName} is not an arm of union {typeof(T).FullName}; it would be written as nil.");
inner.Serialize(ref writer, value, options);
}
public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
// Peek only the arm's first two tokens; any other shape is the inner formatter's to refuse.
var peek = reader.CreatePeekReader();
if (!peek.TryReadNil() && peek.NextMessagePackType == MessagePackType.Array && peek.ReadArrayHeader() == 2)
{
var declared = string.Join(", ", keys.OrderBy(k => k));
if (peek.NextMessagePackType != MessagePackType.Integer)
throw new MessagePackSerializationException($"Union {typeof(T).FullName} has a non-integer arm key (slot 0 of the arm); declared keys: {declared}.");
if (!TryReadKey(ref peek, out var key))
throw new MessagePackSerializationException($"Union {typeof(T).FullName} has an arm key outside Int32 (slot 0 of the arm); declared keys: {declared}.");
if (!keys.Contains(key))
throw new MessagePackSerializationException($"Union {typeof(T).FullName} has no arm for key {key} (slot 0 of the arm); declared keys: {declared}.");
if (peek.TryReadNil())
throw new MessagePackSerializationException($"Union {typeof(T).FullName} arm {key} has nil slots (slot 1 of the arm); declared keys: {declared}.");
}
return inner.Deserialize(ref reader, options);
}
// An arm key is an Int32; a wider or unsigned-64 integer is out of range, never an OverflowException.
private static bool TryReadKey(ref MessagePackReader reader, out int key)
{
key = 0;
if (reader.NextCode == MessagePackCode.UInt64)
{
var wide = reader.ReadUInt64();
if (wide > int.MaxValue) return false;
key = (int)wide;
return true;
}
var value = reader.ReadInt64();
if (value < int.MinValue || value > int.MaxValue) return false;
key = (int)value;
return true;
}
}
}

View file

@ -364,6 +364,13 @@ array (an array of `key`/`type`/`payload`/`storedAt` maps) and replace it; C# ha
reader and refuses it. The shared byte vectors and each runtime's verdict are
`tests/vectors/document-variants-c2a/readability/manifest.txt`.
A record's payload nests at most 256 MessagePack containers. Every array and map
counts, whether a reader decodes it or skips past it, and the outermost array is
depth 1: a payload of depth 256 is accepted and one of depth 257 is refused. Every
runtime enforces the same bound on read and on write, and the refusal names the type,
the depth and the limit, never payload bytes. The vectors are in
`tests/vectors/union-parity` (`bounds-outcomes.msgpack`).
## Variant Records
A variant record is a record whose document is a base record's document with some

View file

@ -73,6 +73,27 @@ Typed lookups and watches (`Get<T>`, `GetAll<T>`, `GetByName<T>`,
type is assignable to `T`. A single-result lookup with several candidates
throws.
## Unions
A union is an abstract class or interface carrying `[Union(key, typeof(Arm))]`
attributes on itself (a union whose arms are also a union has its own key set;
attributes are not inherited). A union value is `nil` for a null reference, and
otherwise an arm: the two-element array `[key, armSlots]`, where `armSlots` is the
arm's own slot array (a unit arm is `[key, []]`). Keys start anywhere and may
have gaps.
- A key is the identity of an arm. It is never reused, and a retired arm's key
stays a gap.
- An arm key the reader's union does not declare is refused on read, in a field,
a list or an arm, with an error naming the union type and the key. The
payload is never echoed, and the value is never read back as `null`: a runtime
that cannot name an arm cannot re-encode it.
- A value whose runtime type is not exactly a declared arm is refused on write,
naming the union and the type. A subtype of an arm is not the arm.
- A store that holds a refused arm fails to load, and the error names the record
key and its schema id.
- Arm slots follow the slot rules below; this rule does not change them.
## Soft-migratable drift
CultCache accepts compatible drift only when the local reader can still map the

View file

@ -2525,18 +2525,18 @@ namespace GameCult.Caching
// Call under the gate that admits the result, so no load can land a later storedAt in between.
private CultStoredDocument Stamp(CultRecordKey key, CultDocumentDescriptor descriptor, object document) =>
new(key, MintStoredAt(PreviousStoredAt(key)), descriptor, document);
new(key, MintStoredAt(PreviousStoredAt(key), Clock()), descriptor, document);
// An unresolved variant: the admitting hold resolves it against its base before anything lands.
private CultStoredDocument StampVariant(CultRecordKey key, CultDocumentDescriptor descriptor, CultVariantDelta delta) =>
new(key, MintStoredAt(PreviousStoredAt(key)), descriptor, delta, null, _codec);
new(key, MintStoredAt(PreviousStoredAt(key), Clock()), descriptor, delta, null, _codec);
// The plain record a Flatten stages: the variant's resolved document, under the variant's own key and schema.
private CultStoredDocument StampFlatten(CultRecordKey key)
{
if (!_entries.TryGetValue(key.Value, out var existing) || existing.Variant == null)
throw new InvalidOperationException($"Flatten({key.Value}): the record is not a variant.");
return new CultStoredDocument(key, MintStoredAt(existing.StoredAt), existing.Descriptor, existing.Document) { Flattens = true };
return new CultStoredDocument(key, MintStoredAt(existing.StoredAt, Clock()), existing.Descriptor, existing.Document) { Flattens = true };
}
private string? PreviousStoredAt(CultRecordKey key) => _entries.TryGetValue(key.Value, out var previous) ? previous.StoredAt : null;
@ -2587,9 +2587,11 @@ namespace GameCult.Caching
throw new ArgumentException($"Expect({key.Value}) was given an instance this cache does not hold at that key.", nameof(current));
}
internal static string MintStoredAt(string? previous)
// The wall clock behind every storedAt. Internal: a test that writes a golden store pins it, so the bytes reproduce.
internal Func<DateTimeOffset> Clock { get; set; } = () => DateTimeOffset.UtcNow;
internal static string MintStoredAt(string? previous, DateTimeOffset now)
{
var now = DateTimeOffset.UtcNow;
if (previous != null &&
DateTimeOffset.TryParse(previous, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var last) &&
now <= last)
@ -3121,7 +3123,7 @@ namespace GameCult.Caching
{
// A value that no longer decodes refuses exactly as a plain record holding it does.
throw new InvalidOperationException(
$"Variant {key} overrides '{member.Member.Name}' (slot {slot}) with a value that does not decode as {member.MemberType.Name}: " +
$"Variant {key} (schema '{descriptor.SchemaId}') overrides '{member.Member.Name}' (slot {slot}) with a value that does not decode as {member.MemberType.Name}: " +
exception.GetBaseException().Message, exception);
}
@ -3612,7 +3614,18 @@ namespace GameCult.Caching
};
}
var document = deserializePayload(resolution.Descriptor.DocumentType, record.Payload);
object document;
try
{
document = deserializePayload(resolution.Descriptor.DocumentType, record.Payload);
}
catch (Exception exception) when (exception is not OperationCanceledException)
{
// The codec knows what it refused but not which record; the store does. Say both, and never null the record.
var causes = new List<string>();
for (var cause = exception; cause != null; cause = cause.InnerException) causes.Add(cause.Message);
throw new InvalidDataException($"Record '{record.Key}' (schema '{record.SchemaId}') cannot be decoded: {string.Join(" <- ", causes.Distinct())}", exception);
}
return new CultStoredDocument(
new CultRecordKey(record.Key),
record.StoredAt,
@ -3765,8 +3778,8 @@ namespace GameCult.Caching
// The one re-mint, for every store kind (storedat-on-change): a record written over one the store holds is stored at a storedAt
// later than the one it replaces, whoever wrote that. The staged storedAt stands only when it is already later (both parsed
// RoundtripKind; an unparsable one counts as not later); otherwise it is minted from the replaced one.
protected static string StoredAtOver(string storedAt, string replacedAt) =>
StoredLater(storedAt, replacedAt) ? storedAt : CultCache.MintStoredAt(replacedAt);
protected string StoredAtOver(string storedAt, string replacedAt) =>
StoredLater(storedAt, replacedAt) ? storedAt : CultCache.MintStoredAt(replacedAt, (Cache?.Clock ?? (() => DateTimeOffset.UtcNow))());
private static bool StoredLater(string storedAt, string than) =>
DateTimeOffset.TryParse(storedAt, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var later) &&

View file

@ -14,5 +14,6 @@
<PackageReference Include="MessagePack.Annotations" Version="3.1.7" />
<PackageReference Include="R3" Version="1.3.0" />
<PackageReference Include="ConcurrentHashSet " Version="1.3.0" />
<InternalsVisibleTo Include="GameCult.Caching.Tests" />
</ItemGroup>
</Project>

View file

@ -3,6 +3,7 @@ using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using GameCult.Logging;
@ -169,6 +170,9 @@ namespace GameCult.Networking
/// </summary>
public CultNetTransportStats Stats => _transport.Stats;
// 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>
@ -283,26 +287,47 @@ namespace GameCult.Networking
return new RudpCultNetSchemaPollResult(consumed, dispatched);
}
/// <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.";
private async Task<bool> DispatchAsync(CultNetRudpSocketServerFrame delivered)
{
if (!string.Equals(delivered.Frame.ChannelId, "schema", StringComparison.Ordinal))
return false;
var message = CultNetSchemaMessageSerialization.Deserialize(delivered.Frame.Payload);
// A peer's message that cannot be decoded (malformed bytes, an unknown schemaVersion) or
// 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;
try
{
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;
}
if (!_handlers.TryGetValue(message.GetType(), out var handler) || handler == null)
{
return false;
}
// R-AG: a handler is expected to catch its own typed refusals (HandleSnapshotRequestV1Async
// catches the three selection exceptions and answers cursor_invalid/selection_invalid/
// reference_outside_target on the wire, R-AM) - this catch is the backstop for whatever a
// handler does not, so an untyped exception from a malformed/hostile message can never
// reach the poll loop and stall the server for every other peer. It still answers nothing
// on the wire (an exception this generic carries no typed refusal to report) and drops the
// one malformed dispatch, exactly as an unregistered handler already does just above -
// R-AM: but it always logs. A backstop that swallows silently is a compensator, and an
// untested, unlogged one hid the SM-6 ArgumentNullException regression for a whole batch.
try
{
var result = handler.DynamicInvoke(message, new RudpCultNetSchemaServerPeer(this, delivered.Peer));
@ -313,11 +338,14 @@ namespace GameCult.Networking
}
catch (Exception ex)
{
// DynamicInvoke wraps a synchronously-thrown handler fault in TargetInvocationException,
// whose own .Message is the generic "Exception has been thrown by the target of an
// invocation." - log the real fault, not that wrapper.
// DynamicInvoke wraps a synchronously-thrown handler fault in TargetInvocationException;
// 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;
Logger.LogError($"CultNet RUDP schema dispatch failed for {message.GetType().Name}: {reported.Message}");
var ended = _transport.EndPeerSession(delivered.Peer, HandlerFailedReason);
Logger.LogError($"CultNet RUDP schema server's {message.GetType().Name} handler failed ({reported.GetType().Name}); {SessionOutcome(ended)}");
return false;
}
return true;

View file

@ -1,5 +1,6 @@
using System;
using System.Buffers.Binary;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.IO;
@ -39,6 +40,12 @@ namespace GameCult.Networking
/// the peer, or a packet the session refuses.
/// </summary>
public long PacketsDropped { get; internal set; }
/// <summary>
/// Gets the number of datagrams a multi-peer server could not send to one peer. Each is
/// that peer's lost datagram: a reliable packet stays pending and is resent, and no other
/// peer is affected. Zero for single-peer transports, whose callers get the send error.
/// </summary>
public long SendFailures { get; internal set; }
internal CultNetTransportStats Snapshot()
{
@ -48,7 +55,8 @@ namespace GameCult.Networking
FramesReceived = FramesReceived,
BytesSent = BytesSent,
BytesReceived = BytesReceived,
PacketsDropped = PacketsDropped
PacketsDropped = PacketsDropped,
SendFailures = SendFailures
};
}
}
@ -885,6 +893,10 @@ namespace GameCult.Networking
{
/// <summary>Maximum reliable packets admitted to the wire before acknowledgements advance the window.</summary>
public const int ReliableSendWindowPackets = 32;
// Flow window: a reliable packet is admitted only while its sequence is at most FlowWindowSequences above the
// lowest unacked one and the payload above that sequence stays within FlowWindowBytes.
private const uint FlowWindowSequences = 1023;
private const int FlowWindowBytes = 4 * 1024 * 1024;
private const int ReceivedSequenceWindow = 4096;
// How long a client keeps retransmitting a Connect nobody answered before it abandons that
// attempt for a fresh one. A Connect the server answers with an Ack, never an Accept, is one
@ -935,6 +947,9 @@ namespace GameCult.Networking
private readonly Dictionary<string, uint> _latestSequencedByChannel = new Dictionary<string, uint>(StringComparer.Ordinal);
private readonly object _pendingReliableGate = new object();
private readonly Dictionary<uint, PendingReliablePacket> _pendingReliable = new Dictionary<uint, PendingReliablePacket>();
// Payload sizes of acknowledged reliable sequences above the lowest unacknowledged one. The receiver still
// holds those bytes behind the gap, so the flow window keeps counting them until the lowest sequence passes them.
private readonly Dictionary<uint, int> _ackedAboveLowest = new Dictionary<uint, int>();
private readonly Queue<CultNetRudpPacket> _queuedReliable = new Queue<CultNetRudpPacket>();
// Every reliable sequence up to and including this one has been received since the peer state
// was last reset. Only the handshake seeds it: the peer's Connect on the accepting side, the
@ -1156,7 +1171,7 @@ namespace GameCult.Networking
options ??= new CultNetRudpSendOptions();
lock (_pendingReliableGate)
{
if (options.Reliable && _pendingReliable.Count >= ReliableSendWindowPackets)
if (options.Reliable && (_queuedReliable.Count > 0 || !WindowAdmits(_nextSequence, payload.Length)))
throw new InvalidOperationException("RUDP reliable send window is full; receive acknowledgements before sending.");
}
return SendMany(channelId, payload, options).First();
@ -1420,6 +1435,7 @@ namespace GameCult.Networking
lock (_pendingReliableGate)
{
_pendingReliable.Clear();
_ackedAboveLowest.Clear();
_queuedReliable.Clear();
}
}
@ -1446,10 +1462,79 @@ namespace GameCult.Networking
/// sequence, so the peer's sequences are forgotten before the goodbye is built: its ack field
/// would otherwise acknowledge the very frame the session refused.
/// </summary>
internal CultNetRudpPacket EndRefused()
internal CultNetRudpPacket EndRefused() => EndWith(RefusedPacketReason);
/// <summary>
/// Ends a session whose peer's frame the application above it refused or failed on, after the
/// session acknowledged it. As with <see cref="EndRefused"/>, the peer's sequences are forgotten
/// before the goodbye is built.
/// </summary>
internal CultNetRudpPacket EndWith(byte[] reason)
{
ResetPeerState();
return CreateDisconnect(RefusedPacketReason);
return CreateDisconnect(reason);
}
/// <summary>
/// Whether a failed send can never succeed for the datagram as built, so resending it is
/// pointless: it is too large for a datagram (EMSGSIZE, WSAEMSGSIZE), its address is
/// malformed for the socket (EINVAL, WSAEINVAL), or belongs to another address family
/// (EAFNOSUPPORT, WSAEAFNOSUPPORT). Everything else (no route, full buffers, firewall drops,
/// a refusal reported for an earlier datagram, an interrupted call) is a property of the path
/// or the moment and may pass, so it is a lost datagram, not a reason to end a session.
/// </summary>
internal static bool IsPermanentSendError(SocketException error) =>
error.SocketErrorCode == SocketError.MessageSize ||
error.SocketErrorCode == SocketError.InvalidArgument ||
error.SocketErrorCode == SocketError.AddressFamilyNotSupported;
internal const string UnsendablePacketReason = "packet could not be sent";
/// <summary>
/// The fixed name of a failed send's cause: EMSGSIZE, EINVAL or EAFNOSUPPORT for a failure
/// that can never pass (<see cref="IsPermanentSendError"/>), UNKNOWN for anything else, as
/// every runtime's goodbye names it. Never the error's own message, which is the platform's
/// wording.
/// </summary>
internal static string SendErrorCode(SocketException error) => error.SocketErrorCode switch
{
SocketError.MessageSize => "EMSGSIZE",
SocketError.InvalidArgument => "EINVAL",
SocketError.AddressFamilyNotSupported => "EAFNOSUPPORT",
_ => "UNKNOWN",
};
/// <summary>
/// Ends a session that owes its peer a packet that can never be sent as built. Resending it
/// would fail forever, and dropping it would leave a reliable sequence the peer waits on for
/// good, so the session cannot be kept. The goodbye's reason names the failure by its fixed
/// name (<see cref="SendErrorCode"/>).
/// </summary>
internal CultNetRudpPacket EndUnsendable(SocketException error)
{
ResetPeerState();
return CreateDisconnect(Encoding.UTF8.GetBytes(UnsendablePacketReason + ": " + SendErrorCode(error)));
}
internal uint NextSequence => _nextSequence;
/// <summary>
/// Undoes a send that never reached the wire: every packet it created at or after
/// <paramref name="firstSequence"/>, pending or queued, leaves no trace and its sequences are
/// reissued, so the peer never sees a gap. Only valid while nothing else has been sent since.
/// </summary>
internal void WithdrawSend(uint firstSequence)
{
lock (_pendingReliableGate)
{
foreach (var sequence in _pendingReliable.Keys.Where(sequence => sequence >= firstSequence).ToArray())
_pendingReliable.Remove(sequence);
var kept = _queuedReliable.Where(packet => packet.Sequence < firstSequence).ToArray();
_queuedReliable.Clear();
foreach (var packet in kept)
_queuedReliable.Enqueue(packet);
}
_nextSequence = firstSequence;
}
/// <summary>
@ -1573,17 +1658,39 @@ namespace GameCult.Networking
}
}
/// <summary>
/// Whether a reliable packet may go on the wire now: the window has a slot, and its sequence and the
/// payload above the lowest unacked sequence stay inside the flow window. With nothing pending, any
/// packet is admissible. Callers hold the pending gate.
/// </summary>
private bool WindowAdmits(uint sequence, int payloadLength)
{
if (_pendingReliable.Count >= ReliableSendWindowPackets)
return false;
if (_pendingReliable.Count == 0)
return true;
var lowest = _pendingReliable.Keys.Min();
long bytesAbove = 0;
foreach (var pending in _pendingReliable)
{
if (pending.Key > lowest)
bytesAbove += pending.Value.Packet.Payload.Length;
}
foreach (var length in _ackedAboveLowest.Values)
bytesAbove += length;
return sequence - lowest <= FlowWindowSequences && bytesAbove + payloadLength <= FlowWindowBytes;
}
private IReadOnlyList<CultNetRudpPacket> AdmitReliablePackets(
IReadOnlyList<CultNetRudpPacket> packets,
long nowMs)
{
lock (_pendingReliableGate)
{
var available = Math.Max(0, ReliableSendWindowPackets - _pendingReliable.Count);
var ready = new List<CultNetRudpPacket>(Math.Min(available, packets.Count));
var ready = new List<CultNetRudpPacket>();
foreach (var packet in packets)
{
if (ready.Count < available)
if (_queuedReliable.Count == 0 && WindowAdmits(packet.Sequence, packet.Payload.Length))
{
_pendingReliable[packet.Sequence] = new PendingReliablePacket
{
@ -1605,9 +1712,9 @@ namespace GameCult.Networking
{
lock (_pendingReliableGate)
{
var available = Math.Max(0, ReliableSendWindowPackets - _pendingReliable.Count);
var ready = new List<CultNetRudpPacket>(Math.Min(available, _queuedReliable.Count));
while (ready.Count < available && _queuedReliable.Count > 0)
var ready = new List<CultNetRudpPacket>();
while (_queuedReliable.Count > 0
&& WindowAdmits(_queuedReliable.Peek().Sequence, _queuedReliable.Peek().Payload.Length))
{
var packet = _queuedReliable.Dequeue();
_pendingReliable[packet.Sequence] = new PendingReliablePacket
@ -1641,17 +1748,36 @@ namespace GameCult.Networking
{
lock (_pendingReliableGate)
{
_pendingReliable.Remove(packet.Ack);
Acknowledge(packet.Ack);
for (var bit = 0; bit < 32; bit++)
{
if ((packet.AckMask & (1u << bit)) != 0 && packet.Ack > bit)
{
_pendingReliable.Remove(packet.Ack - (uint)bit - 1);
Acknowledge(packet.Ack - (uint)bit - 1);
}
}
// Acknowledged sizes stop counting once the lowest unacknowledged sequence passes them, and all
// of them stop when nothing is unacknowledged.
if (_pendingReliable.Count == 0)
{
_ackedAboveLowest.Clear();
}
else
{
var lowest = _pendingReliable.Keys.Min();
foreach (var sequence in _ackedAboveLowest.Keys.Where(sequence => sequence <= lowest).ToArray())
_ackedAboveLowest.Remove(sequence);
}
}
}
// Callers hold the pending gate.
private void Acknowledge(uint sequence)
{
if (_pendingReliable.Remove(sequence, out var pending))
_ackedAboveLowest[sequence] = pending.Packet.Payload.Length;
}
private static bool PacketAcknowledges(CultNetRudpPacket packet, uint sequence)
{
if (packet.Ack == sequence)
@ -2628,6 +2754,11 @@ namespace GameCult.Networking
/// Gets the last transport-level remote disconnect reason, if one was received.
/// </summary>
public byte[]? DisconnectReason { get; internal set; }
// The goodbye's reason once the session ended over a packet it could never send. Written
// under SessionGate by whichever thread's send found the failure; the polling thread reads
// it when it retires the peer.
internal byte[]? UnsendableReason { get; set; }
}
/// <summary>
@ -2665,6 +2796,10 @@ namespace GameCult.Networking
private readonly CultNetTransportStats _stats = new CultNetTransportStats();
private readonly Dictionary<string, CultNetRudpSocketServerPeer> _peers = new Dictionary<string, CultNetRudpSocketServerPeer>(StringComparer.Ordinal);
private readonly Queue<CultNetRudpSocketServerFrame> _deliveredFrames = new Queue<CultNetRudpSocketServerFrame>();
// Peers whose session ended over a packet it could never send, waiting for the polling thread
// to retire them. Only the polling thread changes _peers or raises PeerDisconnected; a send on
// a caller's thread ends the session and leaves the peer here.
private readonly ConcurrentQueue<CultNetRudpSocketServerPeer> _unsendablePeers = new ConcurrentQueue<CultNetRudpSocketServerPeer>();
private bool _disposed;
/// <summary>
@ -2726,8 +2861,28 @@ namespace GameCult.Networking
public void Send(CultNetRudpSocketServerPeer peer, string channelId, byte[] payload)
{
if (peer == null) throw new ArgumentNullException(nameof(peer));
SocketException? unsendable = null;
var failedIndex = 0;
long generation;
lock (peer.SessionGate)
SendPackets(peer, peer.Session.SendMany(channelId, payload, ChannelSendOptions(channelId), _maxFragmentBytes));
{
var firstSequence = peer.Session.NextSequence;
var packets = peer.Session.SendMany(channelId, payload, ChannelSendOptions(channelId), _maxFragmentBytes);
generation = peer.Session.Generation;
unsendable = SendPackets(peer, packets, out failedIndex);
// A caller-directed send that can never succeed is the caller's error and queues
// nothing. Only when earlier fragments are already on the wire has the peer seen
// part of it, and then the session cannot be kept.
if (unsendable != null && failedIndex == 0)
peer.Session.WithdrawSend(firstSequence);
}
if (unsendable != null)
{
// The polling thread retires the peer; this thread only ends its session.
if (failedIndex > 0)
EndUnsendableSession(peer, unsendable, generation);
throw unsendable;
}
_stats.FramesSent++;
}
@ -2772,6 +2927,7 @@ namespace GameCult.Networking
/// </summary>
public bool TryReceiveOnce(out CultNetRudpSocketServerFrame? delivered)
{
RetireUnsendablePeers();
if (_deliveredFrames.Count > 0)
{
delivered = _deliveredFrames.Dequeue();
@ -2834,13 +2990,24 @@ namespace GameCult.Networking
_peers.TryGetValue(peerKey, out var admitted);
// The admitted peer's session decides whether this Connect repeats the one it accepted:
// answer a repeat with the Accept already owed and queue nothing. Any other Connect is
// a new generation.
// a new generation, and the admitted peer's session ends here, under the gate every
// Send takes: a caller still holding the replaced peer can send nothing more into the
// endpoint the new session now owns.
if (admitted != null)
{
var repeats = false;
SocketException? unsendableReply = null;
long admittedGeneration;
lock (admitted.SessionGate)
{
if (admitted.Session.ConnectRepeats(packet))
admittedGeneration = admitted.Session.Generation;
if (!admitted.Session.ConnectRepeats(packet))
{
admitted.Session.ResetPeerState();
}
else
{
repeats = true;
CultNetRudpPacket reply;
try
{
@ -2851,10 +3018,15 @@ namespace GameCult.Networking
_stats.PacketsDropped++;
return true;
}
SendPacket(admitted.RemoteEndPoint, reply);
return true;
unsendableReply = SendPacket(admitted.RemoteEndPoint, reply);
}
}
if (repeats)
{
if (unsendableReply != null)
EndUnsendablePeer(admitted, unsendableReply, admittedGeneration);
return true;
}
}
var peer = new CultNetRudpSocketServerPeer(
@ -2867,9 +3039,20 @@ namespace GameCult.Networking
ResendDelayMs = _resendDelayMs,
MaxPendingReliablePackets = _maxPendingReliablePackets
}));
_peers[peerKey] = peer;
SocketException? unsendableAccept;
lock (peer.SessionGate)
SendPacket(peer.RemoteEndPoint, peer.Session.AcceptConnect(packet, NowMs(), _acceptPayload));
unsendableAccept = SendPacket(peer.RemoteEndPoint, peer.Session.AcceptConnect(packet, NowMs(), _acceptPayload));
if (unsendableAccept != null)
{
// The peer cannot be answered, so no session starts, and the one it replaced has
// already ended.
_peers.Remove(peerKey);
_stats.PacketsDropped++;
}
else
{
_peers[peerKey] = peer;
}
if (admitted != null)
{
admitted.DisconnectReason = ReplacedPeerReason;
@ -2886,6 +3069,8 @@ namespace GameCult.Networking
CultNetRudpReceiveResult? outcome;
CultNetRudpPacket? acknowledgement = null;
SocketException? unsendable = null;
long existingGeneration = 0;
lock (existingPeer.SessionGate)
{
try
@ -2902,20 +3087,15 @@ namespace GameCult.Networking
if (outcome == null)
{
try
{
SendPacket(existingPeer.RemoteEndPoint, existingPeer.Session.EndRefused());
}
catch (SocketException)
{
// Best effort: the session ends whether or not the peer hears it.
}
// The session ends whether or not the peer hears the goodbye.
SendPacket(existingPeer.RemoteEndPoint, existingPeer.Session.EndRefused());
}
else
{
existingGeneration = existingPeer.Session.Generation;
if (outcome.Reply != null)
SendPacket(existingPeer.RemoteEndPoint, outcome.Reply);
SendPackets(existingPeer, outcome.ReadyToSend);
unsendable = SendPacket(existingPeer.RemoteEndPoint, outcome.Reply);
unsendable ??= SendPackets(existingPeer, outcome.ReadyToSend, out _);
if (packet.PacketType == CultNetRudpPacketType.Data)
acknowledgement = existingPeer.Session.CreateAckForReceived(packet.Sequence);
}
@ -2952,8 +3132,10 @@ namespace GameCult.Networking
}
delivered = _deliveredFrames.Count > 0 ? _deliveredFrames.Dequeue() : null;
if (acknowledgement != null)
SendPacket(existingPeer.RemoteEndPoint, acknowledgement);
if (acknowledgement != null && unsendable == null)
unsendable = SendPacket(existingPeer.RemoteEndPoint, acknowledgement);
if (unsendable != null)
EndUnsendablePeer(existingPeer, unsendable, existingGeneration);
return true;
}
@ -2963,23 +3145,118 @@ namespace GameCult.Networking
/// </summary>
public void PollResends()
{
RetireUnsendablePeers();
if (_socket.Poll(0, SelectMode.SelectRead))
return;
foreach (var peer in _peers.Values.ToArray())
{
SocketException? unsendable;
long generation;
lock (peer.SessionGate)
SendPackets(peer, peer.Session.DueResends(NowMs()));
{
var due = peer.Session.DueResends(NowMs());
generation = peer.Session.Generation;
unsendable = SendPackets(peer, due, out _);
}
if (unsendable != null)
EndUnsendablePeer(peer, unsendable, generation);
}
}
private void SendPackets(CultNetRudpSocketServerPeer peer, IReadOnlyList<CultNetRudpPacket> packets)
// Stops at the first packet that can never be sent as built and returns its error and
// index; a transient failure is a lost datagram and the loop goes on.
private SocketException? SendPackets(CultNetRudpSocketServerPeer peer, IReadOnlyList<CultNetRudpPacket> packets, out int failedIndex)
{
failedIndex = 0;
for (var index = 0; index < packets.Count; index++)
{
SendPacket(peer.RemoteEndPoint, packets[index]);
var unsendable = SendPacket(peer.RemoteEndPoint, packets[index]);
if (unsendable != null)
{
failedIndex = index;
return unsendable;
}
if ((index + 1) % WireBurstPackets == 0 && index + 1 < packets.Count)
Thread.Yield();
}
return null;
}
// An admitted peer owes a packet that can never be sent as built. Inside a poll that ends the
// peer's session, never the poll: the peer is told, and PeerDisconnected carries a reason that
// names the error.
private void EndUnsendablePeer(CultNetRudpSocketServerPeer peer, SocketException error, long generation)
{
EndUnsendableSession(peer, error, generation);
RetireUnsendablePeers();
}
// Ends the session and tells the peer, on whichever thread found the failure. The peer stays in
// _peers until the polling thread retires it. The failure belongs to the generation the thread
// read under the gate when it sent; if that generation has already ended (another thread
// ended it over its own failure, or a new Connect from the endpoint replaced it), or the
// thread read it only after the session had ended (a Pong or ack answered on an ended
// session the polling thread has not yet retired), there is nothing left to end, and a
// goodbye would reach the session that now owns the endpoint or repeat the first one. The
// goodbye is built and sent under the gate, so no Connect is admitted between the two.
private void EndUnsendableSession(CultNetRudpSocketServerPeer peer, SocketException error, long generation)
{
lock (peer.SessionGate)
{
if (peer.Session.Generation != generation || peer.Session.Ended)
return;
var goodbye = peer.Session.EndUnsendable(error);
peer.UnsendableReason = goodbye.Payload;
SendPacket(peer.RemoteEndPoint, goodbye);
}
_unsendablePeers.Enqueue(peer);
}
// Polling thread only. Ends the session of a peer whose delivered frame the application could not
// decode or handle, with a goodbye carrying the application's reason. The frame is already
// acknowledged, so the session cannot be kept: a retransmit would never be handled. The peer
// is told, the drop is counted, and the peer's frames still queued are not delivered. A
// session that already ended (a new Connect replaced it, or a send failure ended it) owes no
// goodbye, since the endpoint may belong to a new session; the call then returns false.
internal bool EndPeerSession(CultNetRudpSocketServerPeer peer, byte[] reason)
{
if (peer == null) throw new ArgumentNullException(nameof(peer));
if (reason == null) throw new ArgumentNullException(nameof(reason));
_stats.PacketsDropped++;
lock (peer.SessionGate)
{
if (peer.Session.Ended)
return false;
SendPacket(peer.RemoteEndPoint, peer.Session.EndWith(reason));
}
var kept = _deliveredFrames.Where(frame => !ReferenceEquals(frame.Peer, peer)).ToArray();
_deliveredFrames.Clear();
foreach (var frame in kept)
_deliveredFrames.Enqueue(frame);
var key = RemoteKey(peer.RemoteEndPoint);
if (!_peers.TryGetValue(key, out var current) || !ReferenceEquals(current, peer))
return true;
_peers.Remove(key);
peer.DisconnectReason = reason;
PeerDisconnected?.Invoke(peer);
return true;
}
// Polling thread only. A peer a new Connect already replaced was reported then, and its key now
// names the peer that replaced it.
private void RetireUnsendablePeers()
{
while (_unsendablePeers.TryDequeue(out var peer))
{
var key = RemoteKey(peer.RemoteEndPoint);
if (!_peers.TryGetValue(key, out var current) || !ReferenceEquals(current, peer))
continue;
_peers.Remove(key);
peer.DisconnectReason = peer.UnsendableReason;
PeerDisconnected?.Invoke(peer);
}
}
/// <inheritdoc />
@ -2994,13 +3271,55 @@ namespace GameCult.Networking
_socket.Dispose();
}
private void SendPacket(EndPoint remoteEndPoint, CultNetRudpPacket packet)
// A transient send failure is that peer's lost datagram: counted, never thrown. A reliable
// packet stays pending and is resent; an unreliable one was allowed to be lost. A permanent
// failure (CultNetRudpSession.IsPermanentSendError) is returned: the datagram can never be
// sent as built, and the caller decides between refusing the send and ending the peer's
// session. Only an encode failure, the listener's own bug, throws.
private SocketException? SendPacket(EndPoint remoteEndPoint, CultNetRudpPacket packet)
{
var wire = CultNetRudpPacketCodec.Encode(packet);
var sent = _socket.SendTo(wire, remoteEndPoint);
_stats.BytesSent += sent;
BeforeSend?.Invoke(remoteEndPoint, packet);
try
{
if (UnsendableAfter.TryGetValue(remoteEndPoint, out var remaining))
{
if (remaining > 0)
{
UnsendableAfter[remoteEndPoint] = remaining - 1;
}
else
{
UnsendableAfter.Remove(remoteEndPoint);
throw new SocketException((int)SocketError.MessageSize);
}
}
if (FailingSendPeers.Contains(remoteEndPoint))
throw new SocketException((int)SocketError.HostUnreachable);
var sent = _socket.SendTo(wire, remoteEndPoint);
_stats.BytesSent += sent;
}
catch (SocketException error) when (CultNetRudpSession.IsPermanentSendError(error))
{
return error;
}
catch (SocketException)
{
_stats.SendFailures++;
}
return null;
}
// Test seams, standing in for paths a loopback peer cannot be made to have. Peers whose every
// datagram fails to send transiently:
internal HashSet<EndPoint> FailingSendPeers { get; } = new HashSet<EndPoint>();
// Peers whose next datagram after this many fails permanently, once.
internal Dictionary<EndPoint, int> UnsendableAfter { get; } = new Dictionary<EndPoint, int>();
// Runs before each datagram is sent, to order another thread's work between two sends.
internal Action<EndPoint, CultNetRudpPacket>? BeforeSend { get; set; }
private static string RemoteKey(EndPoint endpoint)
{
return endpoint.ToString() ?? string.Empty;

View file

@ -15,6 +15,10 @@
<PackageReference Include="Isopoh.Cryptography.Argon2" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="GameCult.Networking.Tests" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="..\..\contracts\cultnet\*.schema.json" LogicalName="GameCult.Networking.Contracts.%(Filename)%(Extension)" />
</ItemGroup>