Add portable reconnect controllers

This commit is contained in:
Meta Vens 2026-06-16 05:29:45 +01:00
commit 4a54966b10
14 changed files with 576 additions and 20 deletions

View file

@ -226,8 +226,13 @@ Current progress:
`cultnet.reconnect_policy.v0` document and deterministic exponential delay
helper, and RUDP transport profiles advertise that policy under
`reconnectPolicy`. This gives discovery the same policy language for
reconnect posture; it does not yet claim automatic reconnect orchestration or
production service adoption of that policy.
reconnect posture.
- TypeScript, C#, Rust, Python, and Kotlin now share a portable reconnect
controller shape over that policy: failed connection attempts produce the
same attempt number, delay, next-attempt time, exhaustion signal, and
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.
- 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
@ -254,8 +259,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 broaden RUDP interop
into automatic reconnect orchestration and the wider schema-message matrix.
service bodies behind their shared transport ports, then wire daemon/socket
reconnect loops through the shared controller and broaden the RUDP
schema-message matrix.
## RUDP Packet Contract V0

View file

@ -30,11 +30,11 @@ 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 advertisement, 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 advertisement, 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 advertisement, 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 advertisement, 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 |
| Kotlin | JVM/Android client substrate | Typed MessagePack cache, schema/shard catalogs, authority leases, stream catalog, branded `CultMesh` facade, RUDP client/server sugar, RUDP reconnect policy advertisement, schema-v0 MessagePack over RUDP evidence | C# SoA store, full C# server daemon, or Unity hot-loop memory layout |
| 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 |
| 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 |
| Kotlin | JVM/Android client substrate | Typed MessagePack cache, schema/shard catalogs, authority leases, stream catalog, branded `CultMesh` facade, RUDP client/server sugar, RUDP reconnect policy/controller, schema-v0 MessagePack over RUDP evidence | C# SoA store, full C# server daemon, or Unity hot-loop memory layout |
## Evidence Gates
@ -45,8 +45,8 @@ CultMesh.
MessagePack over RUDP for C#, Rust, Python, and Kotlin peers against
TypeScript. Those RUDP schema-message tests also assert the advertised
`reconnectPolicy` profile field from C#, Rust, Python, and Kotlin peers.
Runtime-local tests cover the deterministic delay helper in C#, TypeScript,
Rust, Python, and Kotlin.
Runtime-local tests cover the deterministic delay helper and reconnect
controller in C#, TypeScript, Rust, Python, and Kotlin.
- `packages/cultcache-py/PARITY.md` is the Python-specific audit ledger. Its
"Still Not Claimed" section is part of the contract, not an apology.
- `docs/cultnet-transport-parity.md` is the transport ownership map. It tracks
@ -60,10 +60,11 @@ CultMesh.
- Broaden service adoption so remaining daemon and production paths use the
shared transport port consistently instead of keeping raw
TCP/LiteNetLib/WebSocket ownership in individual bodies.
- Extend RUDP interop evidence through automatic reconnect orchestration and
the wider schema-message matrix. RUDP profiles now advertise the portable
reconnect policy across the targeted runtimes; service adoption of that
policy is a separate claim.
- 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.
- 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

@ -102,8 +102,8 @@ CultCache, CultNet, and CultMesh. It is evidence, not confetti.
timeout state, fragmentation/reassembly, reliable ordered `schema` delivery,
unreliable sequenced `latest`, unreliable unordered `realtime`, resend
pressure, bounded reliable-send backpressure, and the portable
`cultnet.reconnect_policy.v0` delay-policy helper advertised through RUDP
transport profiles. The TypeScript interop harness proves bidirectional Python/TypeScript RUDP socket exchange,
`cultnet.reconnect_policy.v0` delay-policy helper plus reconnect controller
advertised through RUDP transport profiles. The TypeScript interop harness proves bidirectional Python/TypeScript RUDP socket exchange,
packet-loss recovery, reordering recovery, fragmentation, ping/pong, and
disconnect reason propagation through the shared wire language.
- Python CultMesh discovery client:
@ -286,9 +286,9 @@ node --test packages\cultnet-ts\dist-test\test\interop\cultnet-interop.test.js
raw client, and interop peer still use the TCP-framed schema lane for many
service and harness flows, while `docs/cultnet-transport-parity.md` tracks the
remaining work to put broader server-side bodies behind the shared transport
port instead of cloning LiteNetLib. The reconnect policy helper is portable
and advertised by RUDP profiles; automatic reconnect orchestration is not yet
claimed for Python service bodies.
port instead of cloning LiteNetLib. The reconnect policy/controller primitive
is portable and advertised by RUDP profiles; automatic reconnect use by
Python service bodies is not yet claimed.
- Python does not implement the full C# daemon/server stack. Its current role is
package runtime, raw interop peer, launchable local CultMesh endpoint, local
CultMesh session facade, and typed state participant.

View file

@ -77,6 +77,8 @@ from .transport import (
CultNetRudpSocketTransportConnection,
CultNetRudpSocketTransportOptions,
CultNetReconnectPolicy,
CultNetReconnectController,
CultNetReconnectDecision,
CultNetTransportFrame,
CultNetTransportStats,
TcpFramedTransportConnection,
@ -145,6 +147,8 @@ __all__ = [
"CultNetRudpSocketTransportConnection",
"CultNetRudpSocketTransportOptions",
"CultNetReconnectPolicy",
"CultNetReconnectController",
"CultNetReconnectDecision",
"CultNetTransportFrame",
"CultNetTransportStats",
"TcpFramedTransportConnection",

View file

@ -69,6 +69,52 @@ def compute_reconnect_delay_ms(policy: CultNetReconnectPolicy, attempt: int, jit
return capped_base_delay + bounded_jitter
@dataclass(frozen=True)
class CultNetReconnectDecision:
attempt: int
should_retry: bool
delay_ms: int = 0
next_attempt_at_ms: int | None = None
exhausted: bool = False
@dataclass
class CultNetReconnectController:
policy: CultNetReconnectPolicy = field(default_factory=create_reconnect_policy)
attempt: int = 0
next_attempt_at_ms: int | None = None
exhausted: bool = False
def reset(self) -> None:
self.attempt = 0
self.next_attempt_at_ms = None
self.exhausted = False
def can_attempt(self, now_ms: int) -> bool:
return not self.exhausted and (self.next_attempt_at_ms is None or now_ms >= self.next_attempt_at_ms)
def record_failure(self, now_ms: int, jitter_ms: int = 0) -> CultNetReconnectDecision:
next_attempt = self.attempt + 1
if self.policy.max_attempts is not None and next_attempt > self.policy.max_attempts:
self.exhausted = True
self.next_attempt_at_ms = None
return CultNetReconnectDecision(
attempt=self.attempt,
should_retry=False,
exhausted=True,
)
self.attempt = next_attempt
delay_ms = compute_reconnect_delay_ms(self.policy, self.attempt, jitter_ms)
self.next_attempt_at_ms = int(now_ms) + delay_ms
return CultNetReconnectDecision(
attempt=self.attempt,
should_retry=True,
delay_ms=delay_ms,
next_attempt_at_ms=self.next_attempt_at_ms,
)
@dataclass(frozen=True)
class CultNetTransportFrame:
channel_id: str

View file

@ -83,6 +83,7 @@ from cultnet_py import (
create_rudp_transport_profile,
create_tcp_framed_transport_profile,
create_reconnect_policy,
CultNetReconnectController,
database_subscribe,
database_unsubscribe,
decode_frame,
@ -700,6 +701,38 @@ class CultCacheTests(unittest.TestCase):
self.assertEqual(compute_reconnect_delay_ms(policy, 9, 999), 30_250)
self.assertEqual(compute_reconnect_delay_ms(policy, 0, -5), 1_000)
def test_cultnet_reconnect_controller_schedules_attempts_and_reset(self) -> None:
controller = CultNetReconnectController(create_reconnect_policy(max_attempts=2))
first = controller.record_failure(10_000)
self.assertEqual(first.attempt, 1)
self.assertTrue(first.should_retry)
self.assertEqual(first.delay_ms, 1_000)
self.assertEqual(first.next_attempt_at_ms, 11_000)
self.assertFalse(first.exhausted)
self.assertFalse(controller.can_attempt(10_999))
self.assertTrue(controller.can_attempt(11_000))
second = controller.record_failure(11_000, 17)
self.assertEqual(second.attempt, 2)
self.assertEqual(second.delay_ms, 2_017)
self.assertEqual(second.next_attempt_at_ms, 13_017)
self.assertTrue(second.should_retry)
exhausted = controller.record_failure(13_017)
self.assertEqual(exhausted.attempt, 2)
self.assertFalse(exhausted.should_retry)
self.assertEqual(exhausted.delay_ms, 0)
self.assertIsNone(exhausted.next_attempt_at_ms)
self.assertTrue(exhausted.exhausted)
self.assertFalse(controller.can_attempt(99_000))
controller.reset()
self.assertEqual(controller.attempt, 0)
self.assertIsNone(controller.next_attempt_at_ms)
self.assertFalse(controller.exhausted)
self.assertTrue(controller.can_attempt(99_000))
def test_cultnet_rudp_session_handshake_acks_reliable_connect_and_accept_packets(self) -> None:
client = CultNetRudpSession(
CultNetRudpSessionOptions(connection_id=0x0A0B0C0D, initial_sequence=1, resend_delay_ms=50)

View file

@ -428,6 +428,60 @@ fun computeReconnectDelayMs(policy: CultNetReconnectPolicy, attempt: Int, jitter
return cappedBaseDelay + boundedJitter
}
data class CultNetReconnectDecision(
val attempt: Int,
val shouldRetry: Boolean,
val delayMs: Long = 0,
val nextAttemptAtMs: Long? = null,
val exhausted: Boolean = false,
)
class CultNetReconnectController(
val policy: CultNetReconnectPolicy = createReconnectPolicy(),
) {
var attempt: Int = 0
private set
var nextAttemptAtMs: Long? = null
private set
var exhausted: Boolean = false
private set
fun reset() {
attempt = 0
nextAttemptAtMs = null
exhausted = false
}
fun canAttempt(nowMs: Long): Boolean {
val next = nextAttemptAtMs
return !exhausted && (next == null || nowMs >= next)
}
fun recordFailure(nowMs: Long, jitterMs: Long = 0): CultNetReconnectDecision {
val nextAttempt = attempt + 1
if (policy.maxAttempts != null && nextAttempt > policy.maxAttempts) {
exhausted = true
nextAttemptAtMs = null
return CultNetReconnectDecision(
attempt = attempt,
shouldRetry = false,
exhausted = true,
)
}
attempt = nextAttempt
val delay = computeReconnectDelayMs(policy, attempt, jitterMs)
val nextAt = nowMs + delay
nextAttemptAtMs = nextAt
return CultNetReconnectDecision(
attempt = attempt,
shouldRetry = true,
delayMs = delay,
nextAttemptAtMs = nextAt,
)
}
}
data class CultNetTransportProfile(
val schemaVersion: String = "cultnet.transport_profile.v0",
val runtimeId: String,
@ -2402,6 +2456,7 @@ fun main(args: Array<String>) {
cultCacheRawSnapshotsRoundTripThroughCultNetMessages()
cultNetSchemaMessagesUseMessagePackMaps()
cultNetReconnectPolicyExposesPortableDelayContract()
cultNetReconnectControllerSchedulesAttemptsAndReset()
cultNetSchemaCatalogsRoundTripDescriptors()
cultMeshCatalogsRoundTripDiscoveryMessages()
cultMeshAuthorityLeasesGatePeerTrust()
@ -2601,6 +2656,39 @@ private fun cultNetReconnectPolicyExposesPortableDelayContract() {
check(computeReconnectDelayMs(policy, 0, -5) == 1_000L)
}
private fun cultNetReconnectControllerSchedulesAttemptsAndReset() {
val controller = CultNetReconnectController(createReconnectPolicy(maxAttempts = 2))
val first = controller.recordFailure(10_000)
check(first.attempt == 1)
check(first.shouldRetry)
check(first.delayMs == 1_000L)
check(first.nextAttemptAtMs == 11_000L)
check(!first.exhausted)
check(!controller.canAttempt(10_999))
check(controller.canAttempt(11_000))
val second = controller.recordFailure(11_000, 17)
check(second.attempt == 2)
check(second.delayMs == 2_017L)
check(second.nextAttemptAtMs == 13_017L)
check(second.shouldRetry)
val exhausted = controller.recordFailure(13_017)
check(exhausted.attempt == 2)
check(!exhausted.shouldRetry)
check(exhausted.delayMs == 0L)
check(exhausted.nextAttemptAtMs == null)
check(exhausted.exhausted)
check(!controller.canAttempt(99_000))
controller.reset()
check(controller.attempt == 0)
check(controller.nextAttemptAtMs == null)
check(!controller.exhausted)
check(controller.canAttempt(99_000))
}
private fun cultNetSchemaCatalogsRoundTripDescriptors() {
val catalog = CultNetSchemaCatalog()
var watched: CultNetSchemaDescriptor? = null

View file

@ -77,6 +77,96 @@ pub fn compute_reconnect_delay_ms(
capped_base_delay + jitter_ms.min(policy.max_jitter_ms)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CultNetReconnectDecision {
pub attempt: u32,
pub should_retry: bool,
pub delay_ms: u64,
pub next_attempt_at_ms: Option<u64>,
pub exhausted: bool,
}
#[derive(Clone, Debug)]
pub struct CultNetReconnectController {
pub policy: CultNetReconnectPolicy,
attempt: u32,
next_attempt_at_ms: Option<u64>,
exhausted: bool,
}
impl Default for CultNetReconnectController {
fn default() -> Self {
Self::new(create_reconnect_policy(Default::default()))
}
}
impl CultNetReconnectController {
pub fn new(policy: CultNetReconnectPolicy) -> Self {
Self {
policy,
attempt: 0,
next_attempt_at_ms: None,
exhausted: false,
}
}
pub fn attempt(&self) -> u32 {
self.attempt
}
pub fn next_attempt_at_ms(&self) -> Option<u64> {
self.next_attempt_at_ms
}
pub fn exhausted(&self) -> bool {
self.exhausted
}
pub fn reset(&mut self) {
self.attempt = 0;
self.next_attempt_at_ms = None;
self.exhausted = false;
}
pub fn can_attempt(&self, now_ms: u64) -> bool {
!self.exhausted
&& self
.next_attempt_at_ms
.is_none_or(|next_attempt_at_ms| now_ms >= next_attempt_at_ms)
}
pub fn record_failure(&mut self, now_ms: u64, jitter_ms: u64) -> CultNetReconnectDecision {
let next_attempt = self.attempt.saturating_add(1);
if self
.policy
.max_attempts
.is_some_and(|max_attempts| next_attempt > max_attempts)
{
self.exhausted = true;
self.next_attempt_at_ms = None;
return CultNetReconnectDecision {
attempt: self.attempt,
should_retry: false,
delay_ms: 0,
next_attempt_at_ms: None,
exhausted: true,
};
}
self.attempt = next_attempt;
let delay_ms = compute_reconnect_delay_ms(&self.policy, self.attempt, jitter_ms);
let next_attempt_at_ms = now_ms.saturating_add(delay_ms);
self.next_attempt_at_ms = Some(next_attempt_at_ms);
CultNetReconnectDecision {
attempt: self.attempt,
should_retry: true,
delay_ms,
next_attempt_at_ms: Some(next_attempt_at_ms),
exhausted: false,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct TcpFramedTransportProfileOptions {
pub transport_id: Option<String>,

View file

@ -16,6 +16,7 @@ use cultnet_rs::CultNetDocumentPutOptions;
use cultnet_rs::CultNetDocumentRegistry;
use cultnet_rs::CultNetMessage;
use cultnet_rs::CultNetMutationAuthority;
use cultnet_rs::CultNetReconnectController;
use cultnet_rs::CultNetReconnectPolicyOptions;
use cultnet_rs::CultNetRudpPacket;
use cultnet_rs::CultNetRudpPacketType;
@ -356,6 +357,44 @@ fn reconnect_policy_exposes_portable_delay_contract() {
assert_eq!(compute_reconnect_delay_ms(&policy, 0, 0), 1_000);
}
#[test]
fn reconnect_controller_schedules_attempts_and_reset() {
let policy = create_reconnect_policy(CultNetReconnectPolicyOptions {
max_attempts: Some(2),
..CultNetReconnectPolicyOptions::default()
});
let mut controller = CultNetReconnectController::new(policy);
let first = controller.record_failure(10_000, 0);
assert_eq!(first.attempt, 1);
assert!(first.should_retry);
assert_eq!(first.delay_ms, 1_000);
assert_eq!(first.next_attempt_at_ms, Some(11_000));
assert!(!first.exhausted);
assert!(!controller.can_attempt(10_999));
assert!(controller.can_attempt(11_000));
let second = controller.record_failure(11_000, 17);
assert_eq!(second.attempt, 2);
assert_eq!(second.delay_ms, 2_017);
assert_eq!(second.next_attempt_at_ms, Some(13_017));
assert!(second.should_retry);
let exhausted = controller.record_failure(13_017, 0);
assert_eq!(exhausted.attempt, 2);
assert!(!exhausted.should_retry);
assert_eq!(exhausted.delay_ms, 0);
assert_eq!(exhausted.next_attempt_at_ms, None);
assert!(exhausted.exhausted);
assert!(!controller.can_attempt(99_000));
controller.reset();
assert_eq!(controller.attempt(), 0);
assert_eq!(controller.next_attempt_at_ms(), None);
assert!(!controller.exhausted());
assert!(controller.can_attempt(99_000));
}
#[test]
fn rudp_session_handshake_acks_reliable_connect_and_accept_packets() -> Result<()> {
let mut client = CultNetRudpSession::new(CultNetRudpSessionOptions {

View file

@ -57,10 +57,12 @@ export {
export { encodeFrame, LengthPrefixedMessageFramer } from "./framing";
export { CultNetPeer, type CultNetPeerEvents } from "./peer";
export {
CultNetReconnectController,
TcpFramedTransportConnection,
computeCultNetReconnectDelayMs,
createCultNetReconnectPolicy,
createTcpFramedTransportProfile,
type CultNetReconnectDecision,
type CultNetReconnectPolicy,
type CultNetReconnectPolicyOptions,
type CultNetTransportConnection,

View file

@ -58,6 +58,69 @@ export function computeCultNetReconnectDelayMs(
return cappedBaseDelay + boundedJitter;
}
export interface CultNetReconnectDecision {
attempt: number;
shouldRetry: boolean;
delayMs: number;
nextAttemptAtMs?: number;
exhausted: boolean;
}
export class CultNetReconnectController {
#attempt = 0;
#nextAttemptAtMs: number | undefined;
#exhausted = false;
public constructor(public readonly policy: CultNetReconnectPolicy = createCultNetReconnectPolicy()) {}
public get attempt(): number {
return this.#attempt;
}
public get nextAttemptAtMs(): number | undefined {
return this.#nextAttemptAtMs;
}
public get exhausted(): boolean {
return this.#exhausted;
}
public reset(): void {
this.#attempt = 0;
this.#nextAttemptAtMs = undefined;
this.#exhausted = false;
}
public canAttempt(nowMs: number): boolean {
return !this.#exhausted && (this.#nextAttemptAtMs === undefined || nowMs >= this.#nextAttemptAtMs);
}
public recordFailure(nowMs: number, jitterMs = 0): CultNetReconnectDecision {
const nextAttempt = this.#attempt + 1;
if (this.policy.maxAttempts !== undefined && nextAttempt > this.policy.maxAttempts) {
this.#exhausted = true;
this.#nextAttemptAtMs = undefined;
return {
attempt: this.#attempt,
shouldRetry: false,
delayMs: 0,
exhausted: true,
};
}
this.#attempt = nextAttempt;
const delayMs = computeCultNetReconnectDelayMs(this.policy, this.#attempt, jitterMs);
this.#nextAttemptAtMs = nowMs + delayMs;
return {
attempt: this.#attempt,
shouldRetry: true,
delayMs,
nextAttemptAtMs: this.#nextAttemptAtMs,
exhausted: false,
};
}
}
export interface CultNetTransportConnectionEvents {
frame: (frame: CultNetTransportFrame) => void;
close: () => void;

View file

@ -23,6 +23,7 @@ import {
CultNetSecret,
CultNetServerSecurityOptions,
TcpFramedTransportConnection,
CultNetReconnectController,
cultNetSchemas,
cultNetBuiltinSchemaRegistry,
computeCultNetReconnectDelayMs,
@ -291,6 +292,44 @@ test("reconnect policy exposes the shared portable delay contract", () => {
assert.equal(computeCultNetReconnectDelayMs(policy, 0, -5), 1_000);
});
test("reconnect controller schedules attempts and reset with the shared policy", () => {
const policy = createCultNetReconnectPolicy({ maxAttempts: 2 });
const controller = new CultNetReconnectController(policy);
const first = controller.recordFailure(10_000);
assert.deepEqual(first, {
attempt: 1,
shouldRetry: true,
delayMs: 1_000,
nextAttemptAtMs: 11_000,
exhausted: false,
});
assert.equal(controller.canAttempt(10_999), false);
assert.equal(controller.canAttempt(11_000), true);
const second = controller.recordFailure(11_000, 17);
assert.equal(second.attempt, 2);
assert.equal(second.delayMs, 2_017);
assert.equal(second.nextAttemptAtMs, 13_017);
assert.equal(second.shouldRetry, true);
const exhausted = controller.recordFailure(13_017);
assert.deepEqual(exhausted, {
attempt: 2,
shouldRetry: false,
delayMs: 0,
exhausted: true,
});
assert.equal(controller.exhausted, true);
assert.equal(controller.canAttempt(99_000), false);
controller.reset();
assert.equal(controller.attempt, 0);
assert.equal(controller.nextAttemptAtMs, undefined);
assert.equal(controller.exhausted, false);
assert.equal(controller.canAttempt(99_000), true);
});
test("rudp session handshake acks reliable connect and accept packets", () => {
const client = new CultNetRudpSession({ connectionId: 0x0a0b0c0d, initialSequence: 1, resendDelayMs: 50 });
const server = new CultNetRudpSession({ connectionId: 0x0a0b0c0d, initialSequence: 100, resendDelayMs: 50 });

View file

@ -138,6 +138,115 @@ namespace GameCult.Networking
}
}
/// <summary>
/// Decision emitted by the portable reconnect controller.
/// </summary>
public sealed class CultNetReconnectDecision
{
/// <summary>
/// Gets or sets the scheduled attempt number.
/// </summary>
public int Attempt { get; set; }
/// <summary>
/// Gets or sets whether another attempt should be made.
/// </summary>
public bool ShouldRetry { get; set; }
/// <summary>
/// Gets or sets the computed delay before the next attempt.
/// </summary>
public int DelayMs { get; set; }
/// <summary>
/// Gets or sets the absolute scheduler time for the next attempt.
/// </summary>
public long? NextAttemptAtMs { get; set; }
/// <summary>
/// Gets or sets whether the policy has exhausted its attempts.
/// </summary>
public bool Exhausted { get; set; }
}
/// <summary>
/// Portable reconnect attempt scheduler for CultNet transports.
/// </summary>
public sealed class CultNetReconnectController
{
/// <summary>
/// Initializes a new instance of the <see cref="CultNetReconnectController"/> class.
/// </summary>
public CultNetReconnectController(CultNetReconnectPolicy? policy = null)
{
Policy = policy ?? CultNetReconnectPolicies.CreateDefault();
}
/// <summary>
/// Gets the reconnect policy.
/// </summary>
public CultNetReconnectPolicy Policy { get; }
/// <summary>
/// Gets the last scheduled attempt number.
/// </summary>
public int Attempt { get; private set; }
/// <summary>
/// Gets the absolute scheduler time for the next attempt.
/// </summary>
public long? NextAttemptAtMs { get; private set; }
/// <summary>
/// Gets a value indicating whether the policy exhausted reconnect attempts.
/// </summary>
public bool Exhausted { get; private set; }
/// <summary>
/// Clears attempt state after a successful connection.
/// </summary>
public void Reset()
{
Attempt = 0;
NextAttemptAtMs = null;
Exhausted = false;
}
/// <summary>
/// Returns whether a caller may attempt to connect at the supplied scheduler time.
/// </summary>
public bool CanAttempt(long nowMs)
{
return !Exhausted && (!NextAttemptAtMs.HasValue || nowMs >= NextAttemptAtMs.Value);
}
/// <summary>
/// Records a failed connection attempt and schedules the next retry.
/// </summary>
public CultNetReconnectDecision RecordFailure(long nowMs, int jitterMs = 0)
{
var nextAttempt = Attempt + 1;
if (Policy.MaxAttempts.HasValue && nextAttempt > Policy.MaxAttempts.Value)
{
Exhausted = true;
NextAttemptAtMs = null;
return new CultNetReconnectDecision
{
Attempt = Attempt,
ShouldRetry = false,
DelayMs = 0,
NextAttemptAtMs = null,
Exhausted = true
};
}
Attempt = nextAttempt;
var delayMs = CultNetReconnectPolicies.ComputeDelayMs(Policy, Attempt, jitterMs);
NextAttemptAtMs = nowMs + delayMs;
return new CultNetReconnectDecision
{
Attempt = Attempt,
ShouldRetry = true,
DelayMs = delayMs,
NextAttemptAtMs = NextAttemptAtMs,
Exhausted = false
};
}
}
/// <summary>
/// Options for creating a TCP framed transport profile.
/// </summary>

View file

@ -412,6 +412,42 @@ namespace GameCult.Networking.Tests
Assert.That(json, Does.Contain("\"maxAttempts\""));
}
[Test]
public void ReconnectController_SchedulesAttemptsAndReset()
{
var controller = new CultNetReconnectController(
CultNetReconnectPolicies.CreateDefault(maxAttempts: 2));
var first = controller.RecordFailure(10_000);
Assert.That(first.Attempt, Is.EqualTo(1));
Assert.That(first.ShouldRetry, Is.True);
Assert.That(first.DelayMs, Is.EqualTo(1_000));
Assert.That(first.NextAttemptAtMs, Is.EqualTo(11_000));
Assert.That(first.Exhausted, Is.False);
Assert.That(controller.CanAttempt(10_999), Is.False);
Assert.That(controller.CanAttempt(11_000), Is.True);
var second = controller.RecordFailure(11_000, 17);
Assert.That(second.Attempt, Is.EqualTo(2));
Assert.That(second.DelayMs, Is.EqualTo(2_017));
Assert.That(second.NextAttemptAtMs, Is.EqualTo(13_017));
Assert.That(second.ShouldRetry, Is.True);
var exhausted = controller.RecordFailure(13_017);
Assert.That(exhausted.Attempt, Is.EqualTo(2));
Assert.That(exhausted.ShouldRetry, Is.False);
Assert.That(exhausted.DelayMs, Is.EqualTo(0));
Assert.That(exhausted.NextAttemptAtMs, Is.Null);
Assert.That(exhausted.Exhausted, Is.True);
Assert.That(controller.CanAttempt(99_000), Is.False);
controller.Reset();
Assert.That(controller.Attempt, Is.EqualTo(0));
Assert.That(controller.NextAttemptAtMs, Is.Null);
Assert.That(controller.Exhausted, Is.False);
Assert.That(controller.CanAttempt(99_000), Is.True);
}
[Test]
public void RudpSession_HandshakeAcksReliableConnectAndAcceptPackets()
{