From 4a54966b105abc677dc895119e00647f97a07f54 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 16 Jun 2026 05:29:45 +0100 Subject: [PATCH] Add portable reconnect controllers --- docs/cultnet-transport-parity.md | 14 ++- docs/runtime-parity-scope.md | 23 ++-- packages/cultcache-py/PARITY.md | 10 +- .../cultcache-py/src/cultnet_py/__init__.py | 4 + .../cultcache-py/src/cultnet_py/transport.py | 46 ++++++++ packages/cultcache-py/tests/test_cultcache.py | 33 ++++++ .../kotlin/org/gamecult/cultmesh/CultMesh.kt | 88 ++++++++++++++ packages/cultnet-rs/src/transport.rs | 90 +++++++++++++++ packages/cultnet-rs/tests/cultnet.rs | 39 +++++++ packages/cultnet-ts/src/index.ts | 2 + packages/cultnet-ts/src/transport.ts | 63 ++++++++++ packages/cultnet-ts/test/cultnet.test.ts | 39 +++++++ src/GameCult.Networking/CultNetTransport.cs | 109 ++++++++++++++++++ .../NetworkingTests.cs | 36 ++++++ 14 files changed, 576 insertions(+), 20 deletions(-) diff --git a/docs/cultnet-transport-parity.md b/docs/cultnet-transport-parity.md index 43700efe..85ff0ee4 100644 --- a/docs/cultnet-transport-parity.md +++ b/docs/cultnet-transport-parity.md @@ -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 diff --git a/docs/runtime-parity-scope.md b/docs/runtime-parity-scope.md index c1f3a216..fcbd7e5f 100644 --- a/docs/runtime-parity-scope.md +++ b/docs/runtime-parity-scope.md @@ -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 diff --git a/packages/cultcache-py/PARITY.md b/packages/cultcache-py/PARITY.md index 11fa864b..474f79d2 100644 --- a/packages/cultcache-py/PARITY.md +++ b/packages/cultcache-py/PARITY.md @@ -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. diff --git a/packages/cultcache-py/src/cultnet_py/__init__.py b/packages/cultcache-py/src/cultnet_py/__init__.py index 0e0221cf..34ca6e03 100644 --- a/packages/cultcache-py/src/cultnet_py/__init__.py +++ b/packages/cultcache-py/src/cultnet_py/__init__.py @@ -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", diff --git a/packages/cultcache-py/src/cultnet_py/transport.py b/packages/cultcache-py/src/cultnet_py/transport.py index 02b3a027..113b0298 100644 --- a/packages/cultcache-py/src/cultnet_py/transport.py +++ b/packages/cultcache-py/src/cultnet_py/transport.py @@ -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 diff --git a/packages/cultcache-py/tests/test_cultcache.py b/packages/cultcache-py/tests/test_cultcache.py index c0e659a7..a23273cb 100644 --- a/packages/cultcache-py/tests/test_cultcache.py +++ b/packages/cultcache-py/tests/test_cultcache.py @@ -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) diff --git a/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/CultMesh.kt b/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/CultMesh.kt index 36320c1c..c0ca7ab7 100644 --- a/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/CultMesh.kt +++ b/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/CultMesh.kt @@ -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) { 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 diff --git a/packages/cultnet-rs/src/transport.rs b/packages/cultnet-rs/src/transport.rs index 824279ea..d7aad261 100644 --- a/packages/cultnet-rs/src/transport.rs +++ b/packages/cultnet-rs/src/transport.rs @@ -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, + pub exhausted: bool, +} + +#[derive(Clone, Debug)] +pub struct CultNetReconnectController { + pub policy: CultNetReconnectPolicy, + attempt: u32, + next_attempt_at_ms: Option, + 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 { + 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, diff --git a/packages/cultnet-rs/tests/cultnet.rs b/packages/cultnet-rs/tests/cultnet.rs index f42ccab9..6a48548d 100644 --- a/packages/cultnet-rs/tests/cultnet.rs +++ b/packages/cultnet-rs/tests/cultnet.rs @@ -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 { diff --git a/packages/cultnet-ts/src/index.ts b/packages/cultnet-ts/src/index.ts index 4d746518..0ffc98f4 100644 --- a/packages/cultnet-ts/src/index.ts +++ b/packages/cultnet-ts/src/index.ts @@ -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, diff --git a/packages/cultnet-ts/src/transport.ts b/packages/cultnet-ts/src/transport.ts index f09f428e..60c14445 100644 --- a/packages/cultnet-ts/src/transport.ts +++ b/packages/cultnet-ts/src/transport.ts @@ -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; diff --git a/packages/cultnet-ts/test/cultnet.test.ts b/packages/cultnet-ts/test/cultnet.test.ts index 202e9c84..a133fd1a 100644 --- a/packages/cultnet-ts/test/cultnet.test.ts +++ b/packages/cultnet-ts/test/cultnet.test.ts @@ -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 }); diff --git a/src/GameCult.Networking/CultNetTransport.cs b/src/GameCult.Networking/CultNetTransport.cs index b5d72c1a..18fc1122 100644 --- a/src/GameCult.Networking/CultNetTransport.cs +++ b/src/GameCult.Networking/CultNetTransport.cs @@ -138,6 +138,115 @@ namespace GameCult.Networking } } + /// + /// Decision emitted by the portable reconnect controller. + /// + public sealed class CultNetReconnectDecision + { + /// + /// Gets or sets the scheduled attempt number. + /// + public int Attempt { get; set; } + /// + /// Gets or sets whether another attempt should be made. + /// + public bool ShouldRetry { get; set; } + /// + /// Gets or sets the computed delay before the next attempt. + /// + public int DelayMs { get; set; } + /// + /// Gets or sets the absolute scheduler time for the next attempt. + /// + public long? NextAttemptAtMs { get; set; } + /// + /// Gets or sets whether the policy has exhausted its attempts. + /// + public bool Exhausted { get; set; } + } + + /// + /// Portable reconnect attempt scheduler for CultNet transports. + /// + public sealed class CultNetReconnectController + { + /// + /// Initializes a new instance of the class. + /// + public CultNetReconnectController(CultNetReconnectPolicy? policy = null) + { + Policy = policy ?? CultNetReconnectPolicies.CreateDefault(); + } + + /// + /// Gets the reconnect policy. + /// + public CultNetReconnectPolicy Policy { get; } + /// + /// Gets the last scheduled attempt number. + /// + public int Attempt { get; private set; } + /// + /// Gets the absolute scheduler time for the next attempt. + /// + public long? NextAttemptAtMs { get; private set; } + /// + /// Gets a value indicating whether the policy exhausted reconnect attempts. + /// + public bool Exhausted { get; private set; } + + /// + /// Clears attempt state after a successful connection. + /// + public void Reset() + { + Attempt = 0; + NextAttemptAtMs = null; + Exhausted = false; + } + + /// + /// Returns whether a caller may attempt to connect at the supplied scheduler time. + /// + public bool CanAttempt(long nowMs) + { + return !Exhausted && (!NextAttemptAtMs.HasValue || nowMs >= NextAttemptAtMs.Value); + } + + /// + /// Records a failed connection attempt and schedules the next retry. + /// + 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 + }; + } + } + /// /// Options for creating a TCP framed transport profile. /// diff --git a/tests/GameCult.Networking.Tests/NetworkingTests.cs b/tests/GameCult.Networking.Tests/NetworkingTests.cs index eb9cb0e6..69df5c81 100644 --- a/tests/GameCult.Networking.Tests/NetworkingTests.cs +++ b/tests/GameCult.Networking.Tests/NetworkingTests.cs @@ -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() {