Route C# client reconnect through controller

This commit is contained in:
Meta Vens 2026-06-16 05:45:26 +01:00
commit 6a369d1050
5 changed files with 102 additions and 24 deletions

View file

@ -233,6 +233,11 @@ Current progress:
successful-connection reset semantics. This is the orchestration primitive
service loops must use; it does not yet claim every production daemon or
socket path automatically redials through it.
- The C# LiteNetLib `Client` reconnect loop now consumes
`CultNetReconnectController` directly instead of owning a private attempt
counter and duplicate backoff constants. It still owns LiteNetLib socket
mechanics and UI-facing reconnect state; the controller owns retry attempt
scheduling.
- Kotlin now mirrors the C#/TypeScript/Python local authority lease gate:
peer cards may advertise `authorityLeaseId`, but `CultMeshAuthorityLeaseCatalog`
owns role/shard/time authorization so discovery contact cannot impersonate
@ -259,9 +264,9 @@ Current progress:
transport; discovery contact remains separate from trust, which is still
gated by the authority lease catalog.
- The remaining parity work is to move the remaining TCP/LiteNetLib/WebSocket
service bodies behind their shared transport ports, then wire daemon/socket
reconnect loops through the shared controller and broaden the RUDP
schema-message matrix.
service bodies behind their shared transport ports, then wire the remaining
daemon/socket reconnect loops through the shared controller and broaden the
RUDP schema-message matrix.
## RUDP Packet Contract V0

View file

@ -30,7 +30,7 @@ CultMesh.
| Runtime | Role | Claimed parity | Not claimed |
| --- | --- | --- | --- |
| C# | Reference implementation and production game/server substrate | CultCache typed documents and SoA, CultNet schema-v0, LiteNetLib production path, shared transport profiles, shared RUDP socket transport, RUDP reconnect policy/controller, CultMesh node/session/catalog/stream/simulation surfaces | No need to abandon LiteNetLib before the CultNet adapter fully owns production service adoption |
| C# | Reference implementation and production game/server substrate | CultCache typed documents and SoA, CultNet schema-v0, LiteNetLib production path, shared transport profiles, shared RUDP socket transport, RUDP reconnect policy/controller, LiteNetLib client reconnect-controller adoption, CultMesh node/session/catalog/stream/simulation surfaces | No need to abandon LiteNetLib before the CultNet adapter fully owns production service adoption |
| Python | Package runtime, local daemon endpoint, raw interop peer, typed state participant | CultCache/CultNet/CultMesh package surface, schema catalogs, shard catalogs/logs, local TCP CultMesh server, session/prediction/simulation fact helpers, authority leases, streams, RUDP codec/session/socket transport, RUDP reconnect policy/controller, schema-v0 MessagePack over RUDP evidence, benchmark evidence against C# cache paths | Universal C# throughput, full C# daemon/server stack, and RUDP as the only public service pipe |
| TypeScript | Node/browser-adjacent projection and interop runtime | CultCache parity tests, CultNet schema-v0 peer, transport profiles, TCP-framed transport port, shared RUDP socket transport, RUDP reconnect policy/controller, local CultMesh node/catalog/authority/stream ergonomics | Full C# game session/server stack |
| Rust | Low-level cache/transport/runtime substrate | CultCache/CultNet interop lane, transport profiles, TCP-framed port, shared RUDP codec/session/socket transport, RUDP reconnect policy/controller, schema-v0 MessagePack over RUDP evidence, small CultMesh facade for peer cards, authority leases, RUDP endpoint parsing, and peer-card RUDP client construction | Full CultMesh game-session/server facade, stream catalog, or production game-session server |
@ -62,9 +62,9 @@ CultMesh.
TCP/LiteNetLib/WebSocket ownership in individual bodies.
- Extend RUDP interop evidence through daemon/socket reconnect loops and the
wider schema-message matrix. RUDP profiles now advertise the portable
reconnect policy and runtime-local tests prove the shared controller across
the targeted runtimes; service adoption of that controller is a separate
claim.
reconnect policy, runtime-local tests prove the shared controller across the
targeted runtimes, and the C# LiteNetLib client uses that controller; broader
service adoption remains a separate claim.
- Keep Kotlin ergonomic parity moving with Android/JVM-shaped APIs instead of
backfilling C# server responsibilities it should not own.
- Keep performance claims evidence-bound: C# owns SoA; Python has benchmark

View file

@ -49,7 +49,7 @@ namespace GameCult.Networking
private bool _disposed;
private bool _manualDisconnect;
private bool _isReconnecting;
private int _reconnectAttemptCount;
private readonly CultNetReconnectController _reconnectController;
private readonly ConcurrentDictionary<Type, Delegate> _messageDelegates = new();
private readonly ConcurrentDictionary<Type, Delegate> _cultNetMessageDelegates = new();
@ -59,9 +59,6 @@ namespace GameCult.Networking
private int _lastPort;
private readonly ClientSecurityOptions _security;
private ILogger _logger = new NullLogger();
private static readonly TimeSpan BaseReconnectDelay = TimeSpan.FromSeconds(1);
private static readonly TimeSpan MaxReconnectDelay = TimeSpan.FromSeconds(30);
private static readonly TimeSpan MaxReconnectJitter = TimeSpan.FromMilliseconds(250);
/// <summary>
/// Gets or sets the logger used by the client.
@ -82,6 +79,21 @@ namespace GameCult.Networking
/// </summary>
public ClientReconnectState ReconnectState { get; private set; } = ClientReconnectState.Idle;
/// <summary>
/// Gets the portable reconnect policy used by this client.
/// </summary>
public CultNetReconnectPolicy ReconnectPolicy => _reconnectController.Policy;
/// <summary>
/// Gets the last scheduled reconnect attempt number.
/// </summary>
public int ReconnectAttempt => _reconnectController.Attempt;
/// <summary>
/// Gets the absolute scheduler time for the next reconnect attempt.
/// </summary>
public long? NextReconnectAttemptAtMs => _reconnectController.NextAttemptAtMs;
/// <summary>
/// Gets or sets whether raw payload bodies may be logged for diagnostics.
/// </summary>
@ -106,9 +118,10 @@ namespace GameCult.Networking
/// Initializes a new client instance.
/// </summary>
/// <param name="security">Validated client security configuration. This must be provided explicitly by the caller.</param>
public Client(ClientSecurityOptions security)
public Client(ClientSecurityOptions security, CultNetReconnectPolicy? reconnectPolicy = null)
{
_security = security ?? throw new ArgumentNullException(nameof(security));
_reconnectController = new CultNetReconnectController(reconnectPolicy);
OnError += s => Logger.LogError(s);
}
@ -349,7 +362,7 @@ namespace GameCult.Networking
_isReconnecting = false;
if (resetReconnectBackoff)
{
_reconnectAttemptCount = 0;
_reconnectController.Reset();
}
SetReconnectState(ClientReconnectState.Idle);
_reconnectSubscription?.Dispose();
@ -428,7 +441,7 @@ namespace GameCult.Networking
{
Logger.LogInfo($"Peer {peer.Address}:{peer.Port} connected.");
_peer = peer;
_reconnectAttemptCount = 0;
_reconnectController.Reset();
SetReconnectState(ClientReconnectState.Idle);
if (Verified)
{
@ -474,6 +487,7 @@ namespace GameCult.Networking
_manualDisconnect = true;
_reconnectSubscription?.Dispose();
_reconnectSubscription = null;
_reconnectController.Reset();
SetReconnectState(ClientReconnectState.Idle);
DisposeTransport();
}
@ -490,6 +504,7 @@ namespace GameCult.Networking
_manualDisconnect = true;
_reconnectSubscription?.Dispose();
_reconnectSubscription = null;
_reconnectController.Reset();
SetReconnectState(ClientReconnectState.Idle);
DisposeTransport();
}
@ -502,8 +517,18 @@ namespace GameCult.Networking
}
_isReconnecting = true;
_reconnectAttemptCount++;
var delay = GetReconnectDelayForAttempt(_reconnectAttemptCount);
var decision = _reconnectController.RecordFailure(
CurrentSchedulerTimeMs(),
RandomNumberGenerator.GetInt32(ReconnectPolicy.MaxJitterMs + 1));
if (!decision.ShouldRetry)
{
_isReconnecting = false;
Logger.LogWarning("Reconnect attempts exhausted.");
SetReconnectState(ClientReconnectState.Idle);
return;
}
var delay = TimeSpan.FromMilliseconds(decision.DelayMs);
SetReconnectState(ClientReconnectState.WaitingToReconnect);
_reconnectSubscription = Observable.Timer(delay).Subscribe(_ =>
{
@ -526,12 +551,23 @@ namespace GameCult.Networking
internal static TimeSpan GetReconnectDelayForAttempt(int attempt)
{
var normalizedAttempt = Math.Max(1, attempt);
var exponentialSeconds = Math.Min(
MaxReconnectDelay.TotalSeconds,
BaseReconnectDelay.TotalSeconds * Math.Pow(2, normalizedAttempt - 1));
var jitterMilliseconds = RandomNumberGenerator.GetInt32((int)MaxReconnectJitter.TotalMilliseconds + 1);
return TimeSpan.FromSeconds(exponentialSeconds) + TimeSpan.FromMilliseconds(jitterMilliseconds);
var jitterMilliseconds = RandomNumberGenerator.GetInt32(CultNetReconnectPolicies.CreateDefault().MaxJitterMs + 1);
return GetReconnectDelayForAttempt(attempt, jitterMilliseconds, CultNetReconnectPolicies.CreateDefault());
}
internal static TimeSpan GetReconnectDelayForAttempt(
int attempt,
int jitterMs,
CultNetReconnectPolicy? policy = null)
{
var reconnectPolicy = policy ?? CultNetReconnectPolicies.CreateDefault();
return TimeSpan.FromMilliseconds(
CultNetReconnectPolicies.ComputeDelayMs(reconnectPolicy, attempt, jitterMs));
}
private static long CurrentSchedulerTimeMs()
{
return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
}
private void DisposeTransport()

View file

@ -361,7 +361,8 @@ The client:
- disposes its prior polling subscription before reconnecting
- stops the prior `NetManager`
- schedules reconnect with bounded exponential backoff and jitter
- schedules reconnect through `CultNetReconnectController`, using the same
`cultnet.reconnect_policy.v0` backoff contract advertised by RUDP profiles
- automatically re-verifies using the stored signed session token
- exposes reconnect state for UI/operator surfaces

View file

@ -3105,7 +3105,18 @@ namespace GameCult.Networking.Tests
[Test]
public void Client_Reconnect_Backoff_Is_Bounded_And_Grows()
{
var method = typeof(Client).GetMethod("GetReconnectDelayForAttempt", BindingFlags.Static | BindingFlags.NonPublic)!;
var method = typeof(Client).GetMethod(
"GetReconnectDelayForAttempt",
BindingFlags.Static | BindingFlags.NonPublic,
null,
new[] { typeof(int) },
null)!;
var deterministicMethod = typeof(Client).GetMethod(
"GetReconnectDelayForAttempt",
BindingFlags.Static | BindingFlags.NonPublic,
null,
new[] { typeof(int), typeof(int), typeof(CultNetReconnectPolicy) },
null)!;
var first = (TimeSpan)method.Invoke(null, new object[] { 1 })!;
var third = (TimeSpan)method.Invoke(null, new object[] { 3 })!;
@ -3117,6 +3128,31 @@ namespace GameCult.Networking.Tests
Assert.That(third, Is.LessThanOrEqualTo(TimeSpan.FromSeconds(4.25)));
Assert.That(tenth, Is.GreaterThanOrEqualTo(TimeSpan.FromSeconds(30)));
Assert.That(tenth, Is.LessThanOrEqualTo(TimeSpan.FromSeconds(30.25)));
var deterministic = (TimeSpan)deterministicMethod.Invoke(
null,
new object[] { 3, 17, CultNetReconnectPolicies.CreateDefault(maxAttempts: 8) })!;
Assert.That(deterministic, Is.EqualTo(TimeSpan.FromMilliseconds(4_017)));
}
[Test]
public void Client_Reconnect_Uses_Portable_Policy_Controller()
{
var policy = CultNetReconnectPolicies.CreateDefault("client-rudp", maxAttempts: 2);
var client = new Client(DevelopmentClientSecurity, policy);
Assert.That(client.ReconnectPolicy, Is.SameAs(policy));
Assert.That(client.ReconnectAttempt, Is.EqualTo(0));
Assert.That(client.NextReconnectAttemptAtMs, Is.Null);
var schedule = typeof(Client).GetMethod("ScheduleReconnect", BindingFlags.Instance | BindingFlags.NonPublic)!;
schedule.Invoke(client, Array.Empty<object>());
Assert.That(client.ReconnectAttempt, Is.EqualTo(1));
Assert.That(client.NextReconnectAttemptAtMs, Is.Not.Null);
Assert.That(client.ReconnectState, Is.EqualTo(ClientReconnectState.WaitingToReconnect));
client.Dispose();
}
[Test]