Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(net): a session layer for online games that do not share a tick

yhhcedf9cb11666
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 51f719f00..75df8ac83 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@ published separately; it ships inside the editor.
### Added
+- **A session layer for online games that do not share a tick.** `esengine/session` is the request and reply side of a game played asynchronously over a shared world. A `SessionHost` on the server authenticates each connection before it serves anything, limits frame size and message rate, pings the client, and lets a newer connection for the same player replace the older one. A `ClientSession` on the device dials, redials with backoff and jitter when the link drops, waits for the server before a request goes out, and keeps its event subscriptions across reconnects. Every request carries a key, so one that was lost on the way back and is sent again is answered from memory instead of running twice (a purchase, a departure); `serverNow()` gives the server's clock, corrected for the link's delay. `defineContract` writes every request and event once, with `s.object`, `s.int` and the other validators: the server checks each request against it, the client checks each reply, and both are typed from it; its `fingerprint` lets a server turn away a client built against another contract. `acceptWebSocket` hands a `ws` socket to a host, and `IdempotencyStore` is where a server with several processes keeps the answers in one place. `NetChannel` gained the keyed requests, a heartbeat, a rate limit, a frame size limit and `NetRequestError` (`timeout`, `closed`, `rate-limited`, `retry`, `remote`) for them. Replication is untouched.
- **A random generator that gives the same numbers on every host.** `createRng(seed)` returns a seeded generator (`float`, `int`, `chance`, `pick`, `weighted`, `shuffle`) whose sequence is the same on a server, a browser, a mini-game and a phone, because it uses only 32-bit integer arithmetic. `fork(label)` makes a named stream that does not move when another stream draws more, and `hashSeed` turns a number, a string or a list of them into a seed. It is for rules that a server settles and a client previews, which must agree; `Math.random` cannot be seeded and is not the same anywhere.
- **Sharpen on WebGL2.** The `sharpen` effect was a compute shader, so a device with no compute stage (WebGL2, which is most of the small-game targets) left it out and showed the picture as it was. It now has a fragment pass of the same arithmetic that stands in where there is no compute stage: on WebGPU the two draw the identical picture, pixel for pixel, and a test switch in the render host (`noCompute`) checks that. Flat areas are untouched and an edge cannot overshoot past what is on either side of it.
- **Blob shadows.** A `BlobShadow` component puts a soft dark disc on the ground under an entity: no shadow map, no light, no extra pass, which is the shadow a phone can afford. It fades and shrinks as the thing leaves the ground (`fadeHeight`, `shrink`), follows the ground (`groundY`, or a height function from `setBlobShadowGround` for ground that is not flat) and is hidden by what stands in front of it. It is a disc, not the light's shadow: it does not stretch with the sun or land on a wall. The same picture on WebGL2 and WebGPU.
diff --git a/pipeline/src/bundle/engineSubpaths.ts b/pipeline/src/bundle/engineSubpaths.ts
index 69cb1615a..232fa5adb 100644
--- a/pipeline/src/bundle/engineSubpaths.ts
+++ b/pipeline/src/bundle/engineSubpaths.ts
@@ -26,6 +26,7 @@ export const ESENGINE_SUBPATHS: Readonly<Record<string, string>> = {
'esengine/debug-channel': 'debug-channel/index.js',
'esengine/ai': 'ai/index.js',
'esengine/replication': 'net/replication/index.js',
+ 'esengine/session': 'net/session/index.js',
'esengine/gameplay': 'gameplay/index.js',
'esengine/dragonbones': 'dragonbones/index.js',
'esengine/physics': 'physics/index.js',
@@ -43,9 +44,10 @@ export const ESENGINE_SUBPATHS: Readonly<Record<string, string>> = {
/**
* Subpaths that are not modules a project picks: the engine binary every target
* loads, a platform adapter an entry chooses rather than content asking for it,
- * and the debug channel a development export adds. Named here so the pickable set is derived rather than written twice.
+ * the debug channel a development export adds, and the session layer, which a
+ * game's own code imports and nothing in a scene asks for. Named here so the pickable set is derived rather than written twice.
*/
-export const NOT_A_MODULE: ReadonlySet<string> = new Set(['esengine/wasm', 'esengine/debug-channel', 'esengine/douyin', 'esengine/kuaishou', 'esengine/bilibili', 'esengine/quickgame', 'esengine/alipay', 'esengine/huawei', 'esengine/openpaas']);
+export const NOT_A_MODULE: ReadonlySet<string> = new Set(['esengine/wasm', 'esengine/debug-channel', 'esengine/session', 'esengine/douyin', 'esengine/kuaishou', 'esengine/bilibili', 'esengine/quickgame', 'esengine/alipay', 'esengine/huawei', 'esengine/openpaas']);
/** The modules a project can force in or refuse, as `features.modules` keys it. */
export const ENGINE_MODULES: readonly string[] =
diff --git a/sdk/etc/replication.api.md b/sdk/etc/replication.api.md
index 8f7eef52f..70a49ad4e 100644
--- a/sdk/etc/replication.api.md
+++ b/sdk/etc/replication.api.md
@@ -168,15 +168,20 @@ dispose: (reason?: string) => void
handle: <Req = unknown, Res = unknown>(type: string, handler: RequestHandler<Req, Res>) => () => void
on: <T = unknown>(type: string, handler: MessageHandler<T>) => () => void
onBinary: (channel: number, handler: BinaryHandler) => () => void
-request: <Res = unknown, Req = unknown>(type: string, payload: Req, timeoutMs?: number) => Promise<Res>
+request: <Res = unknown, Req = unknown>(type: string, payload: Req, options?: number | RequestOptions) => Promise<Res>
send: <T = unknown>(type: string, payload: T) => void
sendBinary: (channel: number, payload: Uint8Array) => void
+setIdempotencyScope: (scope: string) => void
static new (transport: NetTransport, opts?: NetChannelOptions): NetChannel
static prototype: NetChannel
```
## NetChannelOptions — interface @experimental
```
+heartbeat: NetHeartbeatOptions | undefined
+idempotency: IdempotencyStore | undefined
+idempotencyScope: string | undefined
+limits: NetLimitOptions | undefined
requestTimeoutMs: number | undefined
```
diff --git a/sdk/etc/session.api.md b/sdk/etc/session.api.md
new file mode 100644
index 000000000..aedd4a396
--- /dev/null
+++ b/sdk/etc/session.api.md
@@ -0,0 +1,360 @@
+# API surface — esengine/session
+
+<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
+Symbols: 0 public · 0 beta · 49 experimental · 0 deprecated
+
+## AcceptWebSocketOptions — interface @experimental
+```
+maxBufferedBytes: number | undefined
+```
+
+## AcceptedConnection — interface @experimental
+```
+close: (code?: number, reason?: string) => void
+onClose: (handler: () => void) => () => void
+transport: NetTransport
+```
+
+## ClientSession — class @experimental
+```
+close: () => void
+on: <T = unknown>(type: string, handler: MessageHandler<T>) => () => void
+onState: (handler: StateHandler) => () => void
+request: <Res = unknown, Req = unknown>(type: string, payload: Req, options?: SessionRequestOptions) => Promise<Res>
+send: (type: string, payload: unknown) => void
+serverNow: () => number
+start: () => Promise<SessionWelcome>
+state: SessionState
+welcome: SessionWelcome | null
+static new (options: ClientSessionOptions): ClientSession
+static prototype: ClientSession
+```
+
+## ClientSessionOptions — interface @experimental
+```
+backoff: SessionBackoff | undefined
+connect: () => PlatformSocket
+credentials: () => unknown | Promise<unknown>
+heartbeat: false | { intervalMs: number; timeoutMs: number; } | undefined
+maxFrameBytes: number | undefined
+random: (() => number) | undefined
+readyTimeoutMs: number | undefined
+requestTimeoutMs: number | undefined
+retries: number | undefined
+retryDelayMs: number | undefined
+```
+
+## Contract — interface @experimental
+```
+broadcast: <K extends keyof E & string, Ctx extends SessionContext>(host: SessionHost<Ctx>, type: K, payload: Infer<E[K]>, filter?: (ctx: Ctx) => boolean) => number
+client: (session: ClientSession) => ContractClient<R>
+fingerprint: string
+on: <K extends keyof E & string>(session: ClientSession, type: K, handler: MessageHandler<Infer<E[K]>>) => () => void
+push: <K extends keyof E & string>(host: SessionHost<never>, playerId: string, type: K, payload: Infer<E[K]>) => boolean
+serve: <Ctx extends SessionContext>(host: SessionHost<Ctx>, impl: ContractImpl<R, Ctx>) => () => void
+```
+
+## ContractClient — type @experimental
+```
+{
+ [K in keyof R]: (payload: ReqOf<R[K]>, options?: SessionRequestOptions) => Promise<ResOf<R[K]>>;
+}
+```
+
+## ContractImpl — type @experimental
+```
+{
+ [K in keyof R]: (payload: ReqOf<R[K]>, ctx: Ctx, session: ServerSession<Ctx>) => ResOf<R[K]> | Promise<ResOf<R[K]>>;
+}
+```
+
+## IdempotencyBegin — type @experimental
+```
+| { state: 'new' }
+ /** Already answered: reply with this and do not run the handler. */
+ | { state: 'done'; outcome: IdempotentOutcome }
+ /** Another call with this key is running; resolves with its outcome. */
+ | { state: 'busy'; outcome: Promise<IdempotentOutcome | null> }
+```
+
+## IdempotencyStore — interface @experimental
+```
+abandon: (key: string) => void | Promise<void>
+begin: (key: string) => IdempotencyBegin | Promise<IdempotencyBegin>
+finish: (key: string, outcome: IdempotentOutcome) => void | Promise<void>
+```
+
+## IdempotentOutcome — interface @experimental
+```
+d: unknown
+```
+
+## Infer — type @experimental
+```
+S extends Schema<infer T> ? T : never
+```
+
+## MemoryIdempotencyOptions — interface @experimental
+```
+maxEntries: number | undefined
+now: (() => number) | undefined
+ttlMs: number | undefined
+```
+
+## MemoryIdempotencyStore — class @experimental
+```
+abandon: (key: string) => void
+begin: (key: string) => IdempotencyBegin
+finish: (key: string, outcome: IdempotentOutcome) => void
+size: number
+static new (options?: MemoryIdempotencyOptions): MemoryIdempotencyStore
+static prototype: MemoryIdempotencyStore
+```
+
+## MessageHandler — type @experimental
+```
+(payload: T) => void
+```
+
+## NET_ATTEMPT_FAILED — const @experimental
+```
+"the first attempt failed, retry"
+```
+
+## NET_RATE_LIMITED — const @experimental
+```
+"rate limited"
+```
+
+## NetChannel — class @experimental
+```
+dispose: (reason?: string) => void
+handle: <Req = unknown, Res = unknown>(type: string, handler: RequestHandler<Req, Res>) => () => void
+on: <T = unknown>(type: string, handler: MessageHandler<T>) => () => void
+onBinary: (channel: number, handler: BinaryHandler) => () => void
+request: <Res = unknown, Req = unknown>(type: string, payload: Req, options?: number | RequestOptions) => Promise<Res>
+send: <T = unknown>(type: string, payload: T) => void
+sendBinary: (channel: number, payload: Uint8Array) => void
+setIdempotencyScope: (scope: string) => void
+static new (transport: NetTransport, opts?: NetChannelOptions): NetChannel
+static prototype: NetChannel
+```
+
+## NetChannelOptions — interface @experimental
+```
+heartbeat: NetHeartbeatOptions | undefined
+idempotency: IdempotencyStore | undefined
+idempotencyScope: string | undefined
+limits: NetLimitOptions | undefined
+requestTimeoutMs: number | undefined
+```
+
+## NetHeartbeatOptions — interface @experimental
+```
+intervalMs: number
+onDead: () => void
+timeoutMs: number
+```
+
+## NetLimitOptions — interface @experimental
+```
+burst: number | undefined
+maxFrameBytes: number | undefined
+messagesPerSecond: number | undefined
+onViolation: ((kind: NetViolation) => void) | undefined
+```
+
+## NetRequestError — class @experimental
+```
+code: NetRequestErrorCode
+retryable: boolean
+static new (message: string, code: NetRequestErrorCode): NetRequestError
+static prototype: NetRequestError
+```
+
+## NetRequestErrorCode — type @experimental
+```
+'timeout' | 'closed' | 'rate-limited' | 'retry' | 'remote'
+```
+
+## NetTransport — interface @experimental
+```
+on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
+send: (data: string | ArrayBuffer) => void
+```
+
+## NetViolation — type @experimental
+```
+'frame-size' | 'rate'
+```
+
+## ReliableOrderedTransport — interface @experimental
+```
+delivery: "reliable-ordered"
+on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
+send: (data: string | ArrayBuffer) => void
+```
+
+## RequestDef — interface @experimental
+```
+req: Schema<Req>
+res: Schema<Res>
+```
+
+## RequestHandler — type @experimental
+```
+(payload: Req) => Res | Promise<Res>
+```
+
+## RequestOptions — interface @experimental
+```
+idempotencyKey: string | undefined
+timeoutMs: number | undefined
+```
+
+## SESSION_HELLO — const @experimental
+```
+"session:hello"
+```
+
+## SESSION_PROTOCOL_VERSION — const @experimental
+```
+1
+```
+
+## Schema — interface @experimental
+```
+describe: () => string
+parse: (value: unknown, path?: string) => T
+```
+
+## SchemaError — class @experimental
+```
+path: string
+static new (path: string, message: string): SchemaError
+static prototype: SchemaError
+```
+
+## ServerSession — interface @experimental
+```
+close: (code?: number, reason?: string) => void
+ctx: Ctx
+push: (type: string, payload: unknown) => void
+```
+
+## SessionBackoff — interface @experimental
+```
+factor: number | undefined
+initialMs: number | undefined
+jitter: number | undefined
+maxMs: number | undefined
+```
+
+## SessionCloseCode — const @experimental
+```
+{ readonly replaced: 4001; readonly helloTimeout: 4002; readonly unavailable: 4003; readonly abuse: 4004; }
+```
+
+## SessionContext — interface @experimental
+```
+playerId: string
+```
+
+## SessionHandler — type @experimental
+```
+(payload: Req, ctx: Ctx, session: ServerSession<Ctx>) => Res | Promise<Res>
+```
+
+## SessionHelloRequest — interface @experimental
+```
+credentials: unknown
+version: number
+```
+
+## SessionHelloResponse — type @experimental
+```
+| {
+ ok: true;
+ playerId: string;
+ /** The server's clock at the moment it answered, in epoch milliseconds. */
+ serverTimeMs: number;
+ /** Anything the game wants the client to have at once (a renewed token). */
+ data?: unknown;
+ }
+ | { ok: false; error: string; /** Retrying cannot help; the client stops. */ fatal: boolean }
+```
+
+## SessionHost — class @experimental
+```
+accept: (connection: AcceptedConnection) => void
+broadcast: (type: string, payload: unknown, filter?: (ctx: Ctx) => boolean) => number
+close: (code?: number, reason?: string) => void
+connectionCount: number
+handle: <Req = unknown, Res = unknown>(type: string, handler: SessionHandler<Ctx, Req, Res>) => () => void
+playerCount: number
+push: (playerId: string, type: string, payload: unknown) => boolean
+static new <Ctx extends SessionContext = SessionContext>(options: SessionHostOptions<Ctx>): SessionHost<Ctx>
+static prototype: SessionHost<any>
+```
+
+## SessionHostOptions — interface @experimental
+```
+authenticate: (credentials: unknown, connection: AcceptedConnection) => Ctx | Promise<Ctx>
+heartbeat: false | { intervalMs: number; timeoutMs: number; } | undefined
+helloTimeoutMs: number | undefined
+idempotency: IdempotencyStore | undefined
+limits: Pick<NetLimitOptions, "maxFrameBytes" | "messagesPerSecond" | "burst"> | undefined
+maxSessions: number | undefined
+maxViolationsPerMinute: number | undefined
+requestTimeoutMs: number | undefined
+```
+
+## SessionRejected — class @experimental
+```
+fatal: boolean
+static new (message: string, fatal?: boolean): SessionRejected
+static prototype: SessionRejected
+```
+
+## SessionRequestOptions — interface @experimental
+```
+idempotencyKey: string | undefined
+retries: number | undefined
+timeoutMs: number | undefined
+```
+
+## SessionState — type @experimental
+```
+'idle' | 'connecting' | 'ready' | 'reconnecting' | 'closed'
+```
+
+## SessionWelcome — interface @experimental
+```
+data: unknown
+playerId: string
+```
+
+## WebSocketLike — interface @experimental
+```
+bufferedAmount: number | undefined
+close: (code?: number, reason?: string) => void
+on: { (event: "message", listener: (data: unknown, isBinary: boolean) => void): unknown; (event: "close", listener: () => void): unknown; (event: "error", listener: (err: unknown) => void): unknown; }
+send: (data: string | ArrayBufferLike | ArrayBufferView) => void
+terminate: (() => void) | undefined
+```
+
+## acceptWebSocket — function @experimental
+```
+<Ctx extends SessionContext>(host: SessionHost<Ctx>, socket: WebSocketLike, options?: AcceptWebSocketOptions): void
+```
+
+## defineContract — function @experimental
+```
+<R extends RequestDefs, E extends EventDefs = Record<never, never>>(def: { requests: R; events?: E; }): Contract<R, E>
+```
+
+## s — const @experimental
+```
+{ string(opts?: { min?: number; max?: number; pattern?: RegExp; }): Schema<string>; int(opts?: { min?: number; max?: number; }): Schema<number>; number(opts?: { min?: number; max?: number; }): Schema<number>; boolean(): Schema<boolean>; literal<const T extends string | number | boolean | null>(value: T): Schema<T>; enum<const T extends readonly [string, ...string[]]>(values: T): Schema<T[number]>; array<T>(item: Schema<T>, opts?: { max?: number; }): Schema<T[]>; object<S extends Shape>(shape: S): Schema<ObjectOf<S>>; record<T>(value: Schema<T>, opts?: { maxKeys?: number; }): Schema<Record<string, T>>; optional<T>(inner: Schema<T>): Schema<T | undefined>; nullable<T>(inner: Schema<T>): Schema<T | null>; unknown(): Schema<unknown>; }
+```
+
diff --git a/sdk/package.json b/sdk/package.json
index 5b23f9a8e..9441a6df1 100644
--- a/sdk/package.json
+++ b/sdk/package.json
@@ -31,6 +31,7 @@
"./dist/debug-channel/index.js",
"./dist/ai/index.js",
"./dist/net/replication/index.js",
+ "./dist/net/session/index.js",
"./dist/gameplay/index.js",
"./dist/physics/index.js",
"./dist/physics3d/index.js",
@@ -138,6 +139,10 @@
"import": "./dist/net/replication/index.js",
"types": "./dist/net/replication/index.d.ts"
},
+ "./session": {
+ "import": "./dist/net/session/index.js",
+ "types": "./dist/net/session/index.d.ts"
+ },
"./gameplay": {
"import": "./dist/gameplay/index.js",
"types": "./dist/gameplay/index.d.ts"
diff --git a/sdk/rolldown.config.js b/sdk/rolldown.config.js
index e64bd2ab8..b6f4e44dc 100644
--- a/sdk/rolldown.config.js
+++ b/sdk/rolldown.config.js
@@ -118,6 +118,7 @@ export default defineConfig([
'ai/index': 'src/ai/index.ts',
'net/replication/index': 'src/net/replication/index.ts',
'net/session/index': 'src/net/session/index.ts',
+ 'net/session/index': 'src/net/session/index.ts',
'gameplay/index': 'src/gameplay/index.ts',
'dragonbones/index': 'src/dragonbones/index.ts',
'douyin/index': 'src/platform/douyin/index.ts',
diff --git a/sdk/rollup.config.js b/sdk/rollup.config.js
index 1369ab47d..442fc9f61 100644
--- a/sdk/rollup.config.js
+++ b/sdk/rollup.config.js
@@ -39,6 +39,7 @@ export default [
'debug-channel/index': 'src/debug-channel/index.ts',
'ai/index': 'src/ai/index.ts',
'net/replication/index': 'src/net/replication/index.ts',
+ 'net/session/index': 'src/net/session/index.ts',
'gameplay/index': 'src/gameplay/index.ts',
'dragonbones/index': 'src/dragonbones/index.ts',
'wasm': 'src/wasm.ts',
diff --git a/sdk/src/net/IdempotencyStore.ts b/sdk/src/net/IdempotencyStore.ts
new file mode 100644
index 000000000..4dd190d45
--- /dev/null
+++ b/sdk/src/net/IdempotencyStore.ts
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file IdempotencyStore.ts
+ * @brief Remembers what a request answered, so a retry of the same request
+ * returns that answer instead of running the handler a second time.
+ * A request that spends something (a purchase, a departure) must not
+ * run twice because a reply was lost on the way back.
+ */
+
+/** What a handler returned, as it went on the wire. */
+export interface IdempotentOutcome {
+ d?: unknown;
+}
+
+export type IdempotencyBegin =
+ /** First sight of the key: run the handler, then call `finish` or `abandon`. */
+ | { state: 'new' }
+ /** Already answered: reply with this and do not run the handler. */
+ | { state: 'done'; outcome: IdempotentOutcome }
+ /** Another call with this key is running; resolves with its outcome. */
+ | { state: 'busy'; outcome: Promise<IdempotentOutcome | null> };
+
+/**
+ * The seam a server plugs a shared store into (Redis, a database row) when
+ * retries can land on a different process than the original. The store in this
+ * file keeps keys in one process's memory.
+ */
+export interface IdempotencyStore {
+ begin(key: string): IdempotencyBegin | Promise<IdempotencyBegin>;
+ /** Keep the outcome for later retries. */
+ finish(key: string, outcome: IdempotentOutcome): void | Promise<void>;
+ /** The handler failed unexpectedly: free the key so a retry runs again. */
+ abandon(key: string): void | Promise<void>;
+}
+
+export interface MemoryIdempotencyOptions {
+ /** How long an answer is remembered. Default 10 minutes. */
+ ttlMs?: number;
+ /** The most answers kept; the oldest go first. Default 100,000. */
+ maxEntries?: number;
+ /** Clock, for tests. */
+ now?: () => number;
+}
+
+interface Entry {
+ expires: number;
+ outcome: IdempotentOutcome | null;
+ waiters: ((outcome: IdempotentOutcome | null) => void)[];
+}
+
+export class MemoryIdempotencyStore implements IdempotencyStore {
+ private readonly entries_ = new Map<string, Entry>();
+ private readonly ttl_: number;
+ private readonly max_: number;
+ private readonly now_: () => number;
+
+ constructor(options: MemoryIdempotencyOptions = {}) {
+ this.ttl_ = options.ttlMs ?? 10 * 60_000;
+ this.max_ = options.maxEntries ?? 100_000;
+ this.now_ = options.now ?? Date.now;
+ }
+
+ get size(): number {
+ return this.entries_.size;
+ }
+
+ begin(key: string): IdempotencyBegin {
+ const entry = this.entries_.get(key);
+ if (entry && entry.outcome === null) {
+ return { state: 'busy', outcome: new Promise((resolve) => entry.waiters.push(resolve)) };
+ }
+ if (entry && entry.expires > this.now_()) {
+ return { state: 'done', outcome: entry.outcome! };
+ }
+ this.entries_.delete(key);
+ this.evict_();
+ this.entries_.set(key, { expires: Number.POSITIVE_INFINITY, outcome: null, waiters: [] });
+ return { state: 'new' };
+ }
+
+ finish(key: string, outcome: IdempotentOutcome): void {
+ const entry = this.entries_.get(key);
+ if (!entry) return;
+ entry.outcome = outcome;
+ entry.expires = this.now_() + this.ttl_;
+ // A re-insert moves the key to the newest end of the map's order.
+ this.entries_.delete(key);
+ this.entries_.set(key, entry);
+ for (const wake of entry.waiters) wake(outcome);
+ entry.waiters = [];
+ }
+
+ abandon(key: string): void {
+ const entry = this.entries_.get(key);
+ if (!entry) return;
+ this.entries_.delete(key);
+ for (const wake of entry.waiters) wake(null);
+ }
+
+ private evict_(): void {
+ const now = this.now_();
+ for (const [key, entry] of this.entries_) {
+ if (this.entries_.size < this.max_ && entry.expires > now) break;
+ if (entry.outcome === null) continue;
+ this.entries_.delete(key);
+ }
+ }
+}
diff --git a/sdk/src/net/NetChannel.ts b/sdk/src/net/NetChannel.ts
index 54dccc18a..198e1a666 100644
--- a/sdk/src/net/NetChannel.ts
+++ b/sdk/src/net/NetChannel.ts
@@ -8,6 +8,7 @@
* RPC (`handle`/`request`) with a small JSON envelope. Transport-
* agnostic — anything that can `send` and surface `message` events works.
*/
+import type { IdempotencyStore } from './IdempotencyStore';
/** The minimal socket surface NetChannel drives (GameSocket / WeChatSocket fit). */
export interface NetTransport {
@@ -30,15 +31,88 @@ export type MessageHandler<T = unknown> = (payload: T) => void;
export type RequestHandler<Req = unknown, Res = unknown> = (payload: Req) => Res | Promise<Res>;
export type BinaryHandler = (payload: Uint8Array) => void;
+/** What the peer answers when it refuses a message for coming too fast. */
+export const NET_RATE_LIMITED = 'rate limited';
+/** What the peer answers a retry whose first attempt threw: the key is free, send it again. */
+export const NET_ATTEMPT_FAILED = 'the first attempt failed, retry';
+
+/**
+ * Why a request did not return a value.
+ *
+ * - `timeout`: no answer in time; the peer may or may not have run it.
+ * - `closed`: the channel went away with the request in flight; same doubt.
+ * - `rate-limited` / `retry`: the peer ran nothing and says to send it again.
+ * - `remote`: the peer's handler threw, or has none; its message is in `message`.
+ */
+export type NetRequestErrorCode = 'timeout' | 'closed' | 'rate-limited' | 'retry' | 'remote';
+
+export class NetRequestError extends Error {
+ constructor(message: string, readonly code: NetRequestErrorCode) {
+ super(message);
+ this.name = 'NetRequestError';
+ }
+
+ /** True when sending the same request again, with the same key, is safe. */
+ get retryable(): boolean {
+ return this.code !== 'remote';
+ }
+}
+
+/** Why a channel dropped or refused something the peer sent. */
+export type NetViolation = 'frame-size' | 'rate';
+
+export interface NetHeartbeatOptions {
+ /** How often to ping the peer. */
+ intervalMs: number;
+ /** Silence longer than this (no frame of any kind) means the peer is gone. */
+ timeoutMs: number;
+ /** Called once, when the peer has been silent for `timeoutMs`. */
+ onDead: () => void;
+}
+
+export interface NetLimitOptions {
+ /** Larger frames are dropped before they are parsed. Binary frames count too. */
+ maxFrameBytes?: number;
+ /** Sustained control messages (events and requests) per second. Binary frames are not limited. */
+ messagesPerSecond?: number;
+ /** Messages allowed at once before the sustained rate applies. Default: one second's worth. */
+ burst?: number;
+ /** Called for every dropped frame or refused message. */
+ onViolation?: (kind: NetViolation) => void;
+}
+
export interface NetChannelOptions {
/** Default RPC timeout in ms (0 disables). Default 10000. */
requestTimeoutMs?: number;
+ /**
+ * Answer a retried request from memory. Only requests that carry a key
+ * (`idempotencyKey` on the sender) are looked up; the rest run as before.
+ */
+ idempotency?: IdempotencyStore;
+ /** Prefixes every key so two players cannot collide on one. Usually the player id. */
+ idempotencyScope?: string;
+ /** Ping the peer and report when it goes silent. */
+ heartbeat?: NetHeartbeatOptions;
+ limits?: NetLimitOptions;
+}
+
+export interface RequestOptions {
+ /** RPC timeout in ms (0 disables). */
+ timeoutMs?: number;
+ /**
+ * Names this intent. A retry with the same key gets the first attempt's
+ * answer instead of running the handler again. One key per intent (one
+ * click), not per attempt.
+ */
+ idempotencyKey?: string;
}
interface WireEvent { k: 'event'; t: string; d: unknown; }
-interface WireReq { k: 'req'; t: string; id: number; d: unknown; }
+interface WireReq { k: 'req'; t: string; id: number; d: unknown; ik?: string; }
interface WireRes { k: 'res'; id: number; d?: unknown; e?: string; }
-type Wire = WireEvent | WireReq | WireRes;
+interface WirePing { k: 'ping'; n: number; }
+interface WirePong { k: 'pong'; n: number; }
+type Wire = WireEvent | WireReq | WireRes | WirePing | WirePong;
interface Pending {
resolve: (value: unknown) => void;
@@ -65,12 +139,28 @@ export class NetChannel {
private readonly pending = new Map<number, Pending>();
private readonly defaultTimeout: number;
private readonly offMessage_: () => void;
+ private readonly idempotency_: IdempotencyStore | undefined;
+ private scope_: string;
+ private readonly limits_: NetLimitOptions;
+ private readonly bucketCapacity_: number;
+ private heartbeatTimer_: ReturnType<typeof setInterval> | null = null;
+ private bucket_: number;
+ private bucketAt_ = Date.now();
+ private lastHeard_ = Date.now();
private nextId = 1;
+ private nextPing_ = 1;
constructor(transport: NetTransport, opts: NetChannelOptions = {}) {
this.transport = transport;
this.defaultTimeout = opts.requestTimeoutMs ?? 10000;
+ this.idempotency_ = opts.idempotency;
+ this.scope_ = opts.idempotencyScope ?? '';
+ this.limits_ = opts.limits ?? {};
+ const rate = this.limits_.messagesPerSecond ?? 0;
+ this.bucketCapacity_ = rate > 0 ? Math.max(1, this.limits_.burst ?? rate) : 0;
+ this.bucket_ = this.bucketCapacity_;
this.offMessage_ = transport.on('message', (data) => this.handleIncoming_(data));
+ if (opts.heartbeat) this.startHeartbeat_(opts.heartbeat);
}
/** Subscribe to a typed event. Returns an unsubscribe function. */
@@ -100,19 +190,26 @@ export class NetChannel {
};
}
- /** Send a request and await the peer's response (rejects on timeout / remote error). */
- request<Res = unknown, Req = unknown>(type: string, payload: Req, timeoutMs?: number): Promise<Res> {
+ /**
+ * Send a request and await the peer's response (rejects on timeout / remote
+ * error). A number is the timeout in ms; an options object adds an
+ * idempotency key.
+ */
+ request<Res = unknown, Req = unknown>(type: string, payload: Req, options?: number | RequestOptions): Promise<Res> {
const id = this.nextId++;
- const limit = timeoutMs ?? this.defaultTimeout;
+ const opts: RequestOptions = typeof options === 'number' ? { timeoutMs: options } : options ?? {};
+ const limit = opts.timeoutMs ?? this.defaultTimeout;
return new Promise<Res>((resolve, reject) => {
const timer = limit > 0
? setTimeout(() => {
this.pending.delete(id);
- reject(new Error(`net request "${type}" timed out after ${limit}ms`));
+ reject(new NetRequestError(`net request "${type}" timed out after ${limit}ms`, 'timeout'));
}, limit)
: null;
this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });
- this.send_({ k: 'req', t: type, id, d: payload });
+ const wire: WireReq = { k: 'req', t: type, id, d: payload };
+ if (opts.idempotencyKey !== undefined) wire.ik = opts.idempotencyKey;
+ this.send_(wire);
});
}
@@ -135,12 +232,21 @@ export class NetChannel {
this.transport.send(frame.buffer);
}
+ /**
+ * Scope later idempotency keys to this owner. A server knows the player only
+ * after the hello, so the scope is set once the connection has authenticated.
+ */
+ setIdempotencyScope(scope: string): void {
+ this.scope_ = scope;
+ }
+
/** Reject all in-flight requests and drop handlers (call on disconnect). */
dispose(reason = 'net channel closed'): void {
this.offMessage_();
+ if (this.heartbeatTimer_) { clearInterval(this.heartbeatTimer_); this.heartbeatTimer_ = null; }
for (const [, p] of this.pending) {
if (p.timer) clearTimeout(p.timer);
- p.reject(new Error(reason));
+ p.reject(new NetRequestError(reason, 'closed'));
}
this.pending.clear();
this.handlers.clear();
@@ -154,7 +260,42 @@ export class NetChannel {
this.transport.send(JSON.stringify(wire));
}
+ private startHeartbeat_(beat: NetHeartbeatOptions): void {
+ const timer = setInterval(() => {
+ if (Date.now() - this.lastHeard_ > beat.timeoutMs) {
+ clearInterval(timer);
+ this.heartbeatTimer_ = null;
+ beat.onDead();
+ return;
+ }
+ this.send_({ k: 'ping', n: this.nextPing_++ });
+ }, beat.intervalMs);
+ // A heartbeat must not keep a server process alive by itself.
+ (timer as { unref?: () => void }).unref?.();
+ this.heartbeatTimer_ = timer;
+ }
+
+ /** Spend one message from the bucket; false when the peer is over its rate. */
+ private admit_(): boolean {
+ if (this.bucketCapacity_ === 0) return true;
+ const now = Date.now();
+ const refill = ((now - this.bucketAt_) / 1000) * (this.limits_.messagesPerSecond ?? 0);
+ this.bucketAt_ = now;
+ this.bucket_ = Math.min(this.bucketCapacity_, this.bucket_ + refill);
+ if (this.bucket_ < 1) return false;
+ this.bucket_ -= 1;
+ return true;
+ }
+
private handleIncoming_(data: string | ArrayBuffer): void {
+ this.lastHeard_ = Date.now();
+ const max = this.limits_.maxFrameBytes;
+ if (max !== undefined) {
+ // A string's length counts UTF-16 units, not bytes; the bound only has
+ // to keep a hostile frame from being parsed, not measure it exactly.
+ const size = typeof data === 'string' ? data.length : data.byteLength;
+ if (size > max) { this.limits_.onViolation?.('frame-size'); return; }
+ }
if (typeof data !== 'string') {
const view = new Uint8Array(data);
if (view.byteLength === 0) return;
@@ -165,8 +306,20 @@ export class NetChannel {
try { msg = JSON.parse(data) as Wire; } catch { return; }
if (!msg || typeof (msg as { k?: unknown }).k !== 'string') return;
switch (msg.k) {
- case 'event': this.dispatchEvent_(msg.t, msg.d); break;
- case 'req': this.handleRequest_(msg); break;
+ case 'ping': this.send_({ k: 'pong', n: msg.n }); break;
+ case 'pong': break;
+ case 'event':
+ if (!this.admit_()) { this.limits_.onViolation?.('rate'); break; }
+ this.dispatchEvent_(msg.t, msg.d);
+ break;
+ case 'req':
+ if (!this.admit_()) {
+ this.limits_.onViolation?.('rate');
+ this.send_({ k: 'res', id: msg.id, e: NET_RATE_LIMITED });
+ break;
+ }
+ this.handleRequest_(msg);
+ break;
case 'res': this.resolvePending_(msg); break;
}
}
@@ -183,20 +336,68 @@ export class NetChannel {
this.send_({ k: 'res', id: msg.id, e: `no request handler for "${msg.t}"` });
return;
}
+ const store = this.idempotency_;
+ if (store && typeof msg.ik === 'string') {
+ void this.handleIdempotent_(store, `${this.scope_}\u0000${msg.t}\u0000${msg.ik}`, handler, msg);
+ return;
+ }
Promise.resolve()
.then(() => handler(msg.d))
.then(
(result) => this.send_({ k: 'res', id: msg.id, d: result }),
- (err) => this.send_({ k: 'res', id: msg.id, e: err instanceof Error ? err.message : String(err) }),
+ (err) => this.send_({ k: 'res', id: msg.id, e: errorText(err) }),
);
}
+ /**
+ * Run a keyed request at most once to completion. A handler that returns has
+ * its answer kept, so a retry replays it; one that throws frees the key and
+ * the retry runs again — a business refusal belongs in the return value.
+ */
+ private async handleIdempotent_(store: IdempotencyStore, key: string, handler: RequestHandler, msg: WireReq): Promise<void> {
+ try {
+ const begin = await store.begin(key);
+ if (begin.state === 'done') {
+ this.send_({ k: 'res', id: msg.id, d: begin.outcome.d });
+ return;
+ }
+ if (begin.state === 'busy') {
+ const outcome = await begin.outcome;
+ if (outcome) this.send_({ k: 'res', id: msg.id, d: outcome.d });
+ else this.send_({ k: 'res', id: msg.id, e: NET_ATTEMPT_FAILED });
+ return;
+ }
+ let result: unknown;
+ try {
+ result = await handler(msg.d);
+ } catch (err) {
+ await store.abandon(key);
+ this.send_({ k: 'res', id: msg.id, e: errorText(err) });
+ return;
+ }
+ await store.finish(key, { d: result });
+ this.send_({ k: 'res', id: msg.id, d: result });
+ } catch (err) {
+ this.send_({ k: 'res', id: msg.id, e: errorText(err) });
+ }
+ }
+
private resolvePending_(msg: WireRes): void {
const p = this.pending.get(msg.id);
if (!p) return;
this.pending.delete(msg.id);
if (p.timer) clearTimeout(p.timer);
- if (msg.e !== undefined) p.reject(new Error(msg.e));
+ if (msg.e !== undefined) p.reject(new NetRequestError(msg.e, remoteCode(msg.e)));
else p.resolve(msg.d);
}
}
+
+function remoteCode(message: string): NetRequestErrorCode {
+ if (message === NET_RATE_LIMITED) return 'rate-limited';
+ if (message === NET_ATTEMPT_FAILED) return 'retry';
+ return 'remote';
+}
+
+function errorText(err: unknown): string {
+ return err instanceof Error ? err.message : String(err);
+}
diff --git a/sdk/src/net/session/ClientSession.ts b/sdk/src/net/session/ClientSession.ts
new file mode 100644
index 000000000..a17ded107
--- /dev/null
+++ b/sdk/src/net/session/ClientSession.ts
@@ -0,0 +1,307 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ClientSession.ts
+ * @brief The client end of a player session: one object a game holds for its
+ * whole run, however many times the link underneath drops. It dials,
+ * says hello, redials with backoff when the link is lost, and sends each
+ * request under a key so a retry after a lost reply never runs twice.
+ * Subscriptions made on the session survive every reconnect.
+ */
+import { NetChannel, NetRequestError, type MessageHandler } from '../NetChannel';
+import type { PlatformSocket } from '../../platform/types';
+import {
+ SESSION_HELLO,
+ SESSION_PROTOCOL_VERSION,
+ SessionCloseCode,
+ type SessionHelloRequest,
+ type SessionHelloResponse,
+} from './protocol';
+
+export type SessionState = 'idle' | 'connecting' | 'ready' | 'reconnecting' | 'closed';
+
+export interface SessionBackoff {
+ initialMs?: number;
+ maxMs?: number;
+ factor?: number;
+ /** Fraction of each delay randomised away, 0 to 1. Spreads a crowd's redials. */
+ jitter?: number;
+}
+
+export interface ClientSessionOptions {
+ /** A fresh, unopened socket each call (`() => createSocket({ url })`). */
+ connect: () => PlatformSocket;
+ /** Sent in every hello, first dial and redial alike. */
+ credentials: () => unknown | Promise<unknown>;
+ /** Ping the server; `false` turns it off. Default 15 s interval, 45 s timeout. */
+ heartbeat?: { intervalMs: number; timeoutMs: number } | false;
+ backoff?: SessionBackoff;
+ /** Extra sends of a request whose outcome was unknown or refused as retryable. Default 3. */
+ retries?: number;
+ /** Wait before the first retry; doubles each time. Default 300 ms. */
+ retryDelayMs?: number;
+ /** How long a request waits for the session to be ready before it fails. Default 15 s. */
+ readyTimeoutMs?: number;
+ /** Per-attempt timeout for a request. Default 10 s. */
+ requestTimeoutMs?: number;
+ /** Largest frame this side will accept from the server. Default 1 MiB. */
+ maxFrameBytes?: number;
+ /** For jitter; defaults to Math.random. */
+ random?: () => number;
+}
+
+export interface SessionRequestOptions {
+ /** Reuse a key across calls that mean the same intent; default a fresh one per call. */
+ idempotencyKey?: string;
+ timeoutMs?: number;
+ /** Overrides the session's retry count for this call. 0 sends once. */
+ retries?: number;
+}
+
+export interface SessionWelcome {
+ playerId: string;
+ data?: unknown;
+}
+
+type StateHandler = (state: SessionState, reason?: string) => void;
+
+export class ClientSession {
+ private readonly options_: ClientSessionOptions;
+ private readonly listeners_ = new Map<string, Set<MessageHandler>>();
+ private readonly stateHandlers_ = new Set<StateHandler>();
+ private readonly readyWaiters_: { resolve: () => void; reject: (e: Error) => void }[] = [];
+ private state_: SessionState = 'idle';
+ private socket_: PlatformSocket | null = null;
+ private channel_: NetChannel | null = null;
+ private attached_ = new Set<string>();
+ private attempt_ = 0;
+ private redialTimer_: ReturnType<typeof setTimeout> | null = null;
+ private offsetMs_ = 0;
+ private welcome_: SessionWelcome | null = null;
+ private firstReady_: { resolve: (w: SessionWelcome) => void; reject: (e: Error) => void } | null = null;
+ private keySeq_ = 0;
+ private readonly keyPrefix_: string;
+
+ constructor(options: ClientSessionOptions) {
+ this.options_ = options;
+ this.keyPrefix_ = Math.floor((options.random ?? Math.random)() * 0xffffffff).toString(36)
+ + Date.now().toString(36);
+ }
+
+ get state(): SessionState {
+ return this.state_;
+ }
+
+ /** Who the server says this is, once the first hello has succeeded. */
+ get welcome(): SessionWelcome | null {
+ return this.welcome_;
+ }
+
+ /** The server's clock now, in epoch ms, corrected for this device's drift and the link's delay. */
+ serverNow(): number {
+ return Date.now() + this.offsetMs_;
+ }
+
+ /** Observe state changes. Returns an unsubscribe. */
+ onState(handler: StateHandler): () => void {
+ this.stateHandlers_.add(handler);
+ return () => this.stateHandlers_.delete(handler);
+ }
+
+ /** Subscribe to a server-pushed event. Survives reconnects. */
+ on<T = unknown>(type: string, handler: MessageHandler<T>): () => void {
+ let set = this.listeners_.get(type);
+ if (!set) { set = new Set(); this.listeners_.set(type, set); }
+ set.add(handler as MessageHandler);
+ this.attach_(type);
+ return () => {
+ const s = this.listeners_.get(type);
+ if (s) { s.delete(handler as MessageHandler); if (s.size === 0) this.listeners_.delete(type); }
+ };
+ }
+
+ /**
+ * Dial and say hello. Resolves with the welcome once; later drops redial by
+ * themselves. Rejects if the server refuses the player for good.
+ */
+ start(): Promise<SessionWelcome> {
+ if (this.state_ !== 'idle') return Promise.reject(new Error(`[net] session already ${this.state_}`));
+ return new Promise<SessionWelcome>((resolve, reject) => {
+ this.firstReady_ = { resolve, reject };
+ this.dial_();
+ });
+ }
+
+ /** Fire-and-forget to the server. Dropped while the link is down. */
+ send(type: string, payload: unknown): void {
+ if (this.state_ === 'ready') this.channel_?.send(type, payload);
+ }
+
+ /**
+ * Ask the server and wait for the answer. Waits for the session to be ready,
+ * and when an attempt is lost or told to retry, sends it again under the same
+ * key so the server answers once however many times it arrives.
+ */
+ async request<Res = unknown, Req = unknown>(type: string, payload: Req, options: SessionRequestOptions = {}): Promise<Res> {
+ const key = options.idempotencyKey ?? `${this.keyPrefix_}-${(++this.keySeq_).toString(36)}`;
+ const retries = options.retries ?? this.options_.retries ?? 3;
+ let delay = this.options_.retryDelayMs ?? 300;
+ for (let attempt = 0; ; attempt++) {
+ await this.whenReady_();
+ try {
+ return await this.channel_!.request<Res, Req>(type, payload, {
+ idempotencyKey: key,
+ timeoutMs: options.timeoutMs ?? this.options_.requestTimeoutMs,
+ });
+ } catch (err) {
+ const retryable = err instanceof NetRequestError && err.retryable;
+ if (!retryable || attempt >= retries) throw err;
+ await sleep(delay);
+ delay *= 2;
+ }
+ }
+ }
+
+ /** Leave for good: no redial, requests in flight fail. */
+ close(): void {
+ if (this.state_ === 'closed') return;
+ this.finish_('closed by the game');
+ }
+
+ // -- internals ------------------------------------------------------------
+
+ private setState_(state: SessionState, reason?: string): void {
+ if (this.state_ === state) return;
+ this.state_ = state;
+ for (const h of [...this.stateHandlers_]) h(state, reason);
+ }
+
+ private attach_(type: string): void {
+ const channel = this.channel_;
+ if (!channel || this.attached_.has(type)) return;
+ this.attached_.add(type);
+ channel.on(type, (payload) => {
+ for (const h of [...(this.listeners_.get(type) ?? [])]) h(payload);
+ });
+ }
+
+ private dial_(): void {
+ if (this.state_ === 'closed') return;
+ this.setState_(this.welcome_ ? 'reconnecting' : 'connecting');
+ this.attempt_++;
+ let socket: PlatformSocket;
+ try {
+ socket = this.options_.connect();
+ } catch {
+ this.scheduleRedial_();
+ return;
+ }
+ this.socket_ = socket;
+ let lost = false;
+ const onLost = (code: number): void => {
+ if (lost) return;
+ lost = true;
+ this.linkLost_(socket, code);
+ };
+ socket.on('open', () => void this.hello_(socket));
+ socket.on('close', onLost);
+ // A dial that fails outright can report only an error and never a close.
+ socket.on('error', () => { if (socket.readyState === 'closed') onLost(1006); });
+ socket.connect();
+ }
+
+ private async hello_(socket: PlatformSocket): Promise<void> {
+ const o = this.options_;
+ const beat = o.heartbeat === false ? undefined : (o.heartbeat ?? { intervalMs: 15_000, timeoutMs: 45_000 });
+ const channel = new NetChannel(socket, {
+ requestTimeoutMs: o.requestTimeoutMs,
+ heartbeat: beat && { ...beat, onDead: () => socket.close(4000, 'heartbeat timeout') },
+ limits: { maxFrameBytes: o.maxFrameBytes ?? 1024 * 1024 },
+ });
+ this.channel_ = channel;
+ this.attached_ = new Set();
+ for (const type of this.listeners_.keys()) this.attach_(type);
+ try {
+ const credentials = await o.credentials();
+ const sent = Date.now();
+ const res = await channel.request<SessionHelloResponse, SessionHelloRequest>(
+ SESSION_HELLO, { version: SESSION_PROTOCOL_VERSION, credentials }, o.requestTimeoutMs,
+ );
+ if (this.channel_ !== channel) return;
+ if (!res.ok) {
+ if (res.fatal) this.finish_(res.error);
+ else socket.close(1000, 'hello refused');
+ return;
+ }
+ const received = Date.now();
+ this.offsetMs_ = res.serverTimeMs + (received - sent) / 2 - received;
+ this.welcome_ = { playerId: res.playerId, data: res.data };
+ this.attempt_ = 0;
+ this.setState_('ready');
+ for (const w of this.readyWaiters_.splice(0)) w.resolve();
+ this.firstReady_?.resolve(this.welcome_);
+ this.firstReady_ = null;
+ } catch {
+ // A hello that never came back is a dead link; closing hands it to the redial.
+ if (this.channel_ === channel) socket.close(1000, 'hello failed');
+ }
+ }
+
+ private linkLost_(socket: PlatformSocket, code: number): void {
+ if (this.socket_ !== socket) return;
+ this.channel_?.dispose('session link lost');
+ this.channel_ = null;
+ this.socket_ = null;
+ if (this.state_ === 'closed') return;
+ if (code === SessionCloseCode.replaced) {
+ // Another device took the player; fighting it would trade the seat back and forth.
+ this.finish_('replaced by a newer connection');
+ return;
+ }
+ this.scheduleRedial_();
+ }
+
+ private scheduleRedial_(): void {
+ if (this.state_ === 'closed') return;
+ this.setState_(this.welcome_ ? 'reconnecting' : 'connecting');
+ const b = this.options_.backoff ?? {};
+ const base = Math.min(b.maxMs ?? 30_000, (b.initialMs ?? 500) * (b.factor ?? 2) ** Math.max(0, this.attempt_ - 1));
+ const jitter = b.jitter ?? 0.3;
+ const delay = base * (1 - jitter * (this.options_.random ?? Math.random)());
+ this.redialTimer_ = setTimeout(() => { this.redialTimer_ = null; this.dial_(); }, delay);
+ }
+
+ private whenReady_(): Promise<void> {
+ if (this.state_ === 'ready') return Promise.resolve();
+ if (this.state_ === 'closed') return Promise.reject(new Error('[net] the session is closed'));
+ return new Promise<void>((resolve, reject) => {
+ const waiter = { resolve, reject };
+ const timer = setTimeout(() => {
+ const i = this.readyWaiters_.indexOf(waiter);
+ if (i >= 0) this.readyWaiters_.splice(i, 1);
+ reject(new Error('[net] the session did not become ready in time'));
+ }, this.options_.readyTimeoutMs ?? 15_000);
+ waiter.resolve = () => { clearTimeout(timer); resolve(); };
+ waiter.reject = (e) => { clearTimeout(timer); reject(e); };
+ this.readyWaiters_.push(waiter);
+ });
+ }
+
+ private finish_(reason: string): void {
+ if (this.redialTimer_) { clearTimeout(this.redialTimer_); this.redialTimer_ = null; }
+ const socket = this.socket_;
+ this.socket_ = null;
+ this.channel_?.dispose('session closed');
+ this.channel_ = null;
+ this.setState_('closed', reason);
+ socket?.close(1000, 'closed');
+ const err = new Error(`[net] session closed: ${reason}`);
+ for (const w of this.readyWaiters_.splice(0)) w.reject(err);
+ this.firstReady_?.reject(err);
+ this.firstReady_ = null;
+ }
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((r) => setTimeout(r, ms));
+}
diff --git a/sdk/src/net/session/SessionHost.ts b/sdk/src/net/session/SessionHost.ts
new file mode 100644
index 000000000..6bb400bc5
--- /dev/null
+++ b/sdk/src/net/session/SessionHost.ts
@@ -0,0 +1,247 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file SessionHost.ts
+ * @brief The server end of a player session. It accepts connections from any
+ * transport, serves nothing but the hello until `authenticate` names the
+ * player, then serves the game's handlers with the player's context —
+ * behind frame limits, a rate limit, a heartbeat and a retry-safe
+ * request store. A host holds no game state: every handler gets the
+ * player from its context, so any number of hosts can run side by side.
+ */
+import {
+ NetChannel,
+ type NetHeartbeatOptions,
+ type NetLimitOptions,
+ type NetTransport,
+} from '../NetChannel';
+import { MemoryIdempotencyStore, type IdempotencyStore } from '../IdempotencyStore';
+import {
+ SESSION_HELLO,
+ SESSION_PROTOCOL_VERSION,
+ SessionCloseCode,
+ type SessionHelloRequest,
+ type SessionHelloResponse,
+} from './protocol';
+
+/** One accepted connection, whatever carries it (a `ws` socket, a test pipe). */
+export interface AcceptedConnection {
+ transport: NetTransport;
+ close(code?: number, reason?: string): void;
+ /** Called once when the link is gone, from either side. */
+ onClose(handler: () => void): () => void;
+}
+
+/** What `authenticate` returns: at least who the player is. */
+export interface SessionContext {
+ playerId: string;
+}
+
+/** Throw from `authenticate` to refuse a player with a message the client sees. */
+export class SessionRejected extends Error {
+ constructor(message: string, readonly fatal = true) {
+ super(message);
+ this.name = 'SessionRejected';
+ }
+}
+
+export interface SessionHostOptions<Ctx extends SessionContext> {
+ /** Turn the hello's credentials into a player, or throw {@link SessionRejected}. */
+ authenticate(credentials: unknown, connection: AcceptedConnection): Ctx | Promise<Ctx>;
+ /**
+ * Where retried requests are remembered. The default lives in this process;
+ * give hosts that share players one shared store, or a retry that lands on
+ * another host runs twice.
+ */
+ idempotency?: IdempotencyStore;
+ /** Ping each client; `false` turns it off. Default 15 s interval, 45 s timeout. */
+ heartbeat?: { intervalMs: number; timeoutMs: number } | false;
+ /** Default 64 KiB frames, 20 messages a second with a burst of 40. */
+ limits?: Pick<NetLimitOptions, 'maxFrameBytes' | 'messagesPerSecond' | 'burst'>;
+ /** Violations tolerated per minute before the connection is dropped. Default 100. */
+ maxViolationsPerMinute?: number;
+ /** A connection that has not said hello by now is closed. Default 5 s. */
+ helloTimeoutMs?: number;
+ /** Most connections at once; the next is refused. Default unlimited. */
+ maxSessions?: number;
+ /** Request timeout the channels use for the host's own calls. Default 10 s. */
+ requestTimeoutMs?: number;
+}
+
+export type SessionHandler<Ctx extends SessionContext, Req, Res> =
+ (payload: Req, ctx: Ctx, session: ServerSession<Ctx>) => Res | Promise<Res>;
+
+/** An authenticated player's connection, as a handler sees it. */
+export interface ServerSession<Ctx extends SessionContext> {
+ readonly ctx: Ctx;
+ /** Fire-and-forget an event to this player. */
+ push(type: string, payload: unknown): void;
+ close(code?: number, reason?: string): void;
+}
+
+interface Live<Ctx extends SessionContext> extends ServerSession<Ctx> {
+ channel: NetChannel;
+}
+
+export class SessionHost<Ctx extends SessionContext = SessionContext> {
+ private readonly options_: SessionHostOptions<Ctx>;
+ private readonly store_: IdempotencyStore;
+ private readonly handlers_ = new Map<string, SessionHandler<Ctx, never, unknown>>();
+ private readonly byPlayer_ = new Map<string, Live<Ctx>>();
+ private readonly connections_ = new Set<AcceptedConnection>();
+ private closed_ = false;
+
+ constructor(options: SessionHostOptions<Ctx>) {
+ this.options_ = options;
+ this.store_ = options.idempotency ?? new MemoryIdempotencyStore();
+ }
+
+ /** Connections currently open, authenticated or not. */
+ get connectionCount(): number {
+ return this.connections_.size;
+ }
+
+ /** Players with an authenticated connection to this host. */
+ get playerCount(): number {
+ return this.byPlayer_.size;
+ }
+
+ /**
+ * Serve a request type to every authenticated player. Registered before or
+ * after connections arrive; a connection sees the handlers present when its
+ * hello succeeded.
+ */
+ handle<Req = unknown, Res = unknown>(type: string, handler: SessionHandler<Ctx, Req, Res>): () => void {
+ if (type === SESSION_HELLO) throw new Error(`[net] "${SESSION_HELLO}" is the handshake and cannot be handled`);
+ this.handlers_.set(type, handler as SessionHandler<Ctx, never, unknown>);
+ return () => {
+ if (this.handlers_.get(type) === (handler as unknown)) this.handlers_.delete(type);
+ };
+ }
+
+ /** Send an event to one player if they are connected to this host. */
+ push(playerId: string, type: string, payload: unknown): boolean {
+ const live = this.byPlayer_.get(playerId);
+ if (!live) return false;
+ live.push(type, payload);
+ return true;
+ }
+
+ /**
+ * Send an event to every authenticated player on this host. Across several
+ * hosts, fan out through a shared bus and call this on each; a host does not
+ * know about the others.
+ */
+ broadcast(type: string, payload: unknown, filter?: (ctx: Ctx) => boolean): number {
+ let sent = 0;
+ for (const live of this.byPlayer_.values()) {
+ if (filter && !filter(live.ctx)) continue;
+ live.push(type, payload);
+ sent++;
+ }
+ return sent;
+ }
+
+ /** Take over one connection. Returns at once; everything after runs on events. */
+ accept(connection: AcceptedConnection): void {
+ const max = this.options_.maxSessions;
+ if (this.closed_ || (max !== undefined && this.connections_.size >= max)) {
+ connection.close(SessionCloseCode.unavailable, 'unavailable');
+ return;
+ }
+ this.connections_.add(connection);
+
+ const channel = this.makeChannel_(connection);
+ let live: Live<Ctx> | null = null;
+ let authenticating = false;
+ const helloTimer = setTimeout(() => {
+ if (!live) connection.close(SessionCloseCode.helloTimeout, 'hello timeout');
+ }, this.options_.helloTimeoutMs ?? 5000);
+ (helloTimer as { unref?: () => void }).unref?.();
+
+ const offClose = connection.onClose(() => {
+ clearTimeout(helloTimer);
+ offClose();
+ this.connections_.delete(connection);
+ if (live && this.byPlayer_.get(live.ctx.playerId) === live) this.byPlayer_.delete(live.ctx.playerId);
+ channel.dispose('connection closed');
+ });
+
+ channel.handle<SessionHelloRequest, SessionHelloResponse>(SESSION_HELLO, async (hello) => {
+ if (live || authenticating) return { ok: false, error: 'already authenticated', fatal: false };
+ if (!hello || hello.version !== SESSION_PROTOCOL_VERSION) {
+ return { ok: false, error: `session protocol v${hello?.version}, server runs v${SESSION_PROTOCOL_VERSION}`, fatal: true };
+ }
+ authenticating = true;
+ try {
+ const ctx = await this.options_.authenticate(hello.credentials, connection);
+ if (typeof ctx?.playerId !== 'string' || ctx.playerId === '') {
+ return { ok: false, error: 'authentication produced no player', fatal: true };
+ }
+ if (!this.connections_.has(connection)) return { ok: false, error: 'connection closed', fatal: false };
+ clearTimeout(helloTimer);
+ live = this.admit_(connection, channel, ctx);
+ return { ok: true, playerId: ctx.playerId, serverTimeMs: Date.now() };
+ } catch (err) {
+ if (err instanceof SessionRejected) return { ok: false, error: err.message, fatal: err.fatal };
+ return { ok: false, error: 'authentication unavailable', fatal: false };
+ } finally {
+ authenticating = false;
+ }
+ });
+ }
+
+ /** Close every connection and refuse new ones. */
+ close(code: number = SessionCloseCode.unavailable, reason = 'shutting down'): void {
+ this.closed_ = true;
+ for (const connection of [...this.connections_]) connection.close(code, reason);
+ }
+
+ // -- internals ------------------------------------------------------------
+
+ private makeChannel_(connection: AcceptedConnection): NetChannel {
+ const o = this.options_;
+ const beat = o.heartbeat === false ? undefined : (o.heartbeat ?? { intervalMs: 15_000, timeoutMs: 45_000 });
+ const heartbeat: NetHeartbeatOptions | undefined = beat && {
+ ...beat,
+ onDead: () => connection.close(1001, 'heartbeat timeout'),
+ };
+ const budget = o.maxViolationsPerMinute ?? 100;
+ let violations = 0;
+ let windowStart = Date.now();
+ return new NetChannel(connection.transport, {
+ requestTimeoutMs: o.requestTimeoutMs,
+ idempotency: this.store_,
+ heartbeat,
+ limits: {
+ maxFrameBytes: o.limits?.maxFrameBytes ?? 64 * 1024,
+ messagesPerSecond: o.limits?.messagesPerSecond ?? 20,
+ burst: o.limits?.burst ?? 40,
+ onViolation: () => {
+ const now = Date.now();
+ if (now - windowStart > 60_000) { windowStart = now; violations = 0; }
+ if (++violations > budget) connection.close(SessionCloseCode.abuse, 'rate limit');
+ },
+ },
+ });
+ }
+
+ private admit_(connection: AcceptedConnection, channel: NetChannel, ctx: Ctx): Live<Ctx> {
+ const previous = this.byPlayer_.get(ctx.playerId);
+ const live: Live<Ctx> = {
+ ctx,
+ channel,
+ push: (type, payload) => channel.send(type, payload),
+ close: (code, reason) => connection.close(code, reason),
+ };
+ this.byPlayer_.set(ctx.playerId, live);
+ // Replace after the swap, so the old link's own close does not delete the new entry.
+ previous?.close(SessionCloseCode.replaced, 'replaced by a newer connection');
+
+ channel.setIdempotencyScope(ctx.playerId);
+ for (const [type, handler] of this.handlers_) {
+ channel.handle(type, (payload) => (handler as SessionHandler<Ctx, unknown, unknown>)(payload, ctx, live));
+ }
+ return live;
+ }
+}
diff --git a/sdk/src/net/session/acceptWebSocket.ts b/sdk/src/net/session/acceptWebSocket.ts
new file mode 100644
index 000000000..fd6227aa1
--- /dev/null
+++ b/sdk/src/net/session/acceptWebSocket.ts
@@ -0,0 +1,107 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file acceptWebSocket.ts
+ * @brief Hand a server-side WebSocket to a {@link SessionHost}. Written against
+ * the surface of the `ws` package rather than importing it: the game's
+ * server owns its `ws` install, listener, TLS and proxy settings, and
+ * this is only the seam between that socket and a session.
+ */
+import type { AcceptedConnection, SessionHost, SessionContext } from './SessionHost';
+
+/** The part of a `ws` WebSocket this adapter uses. */
+export interface WebSocketLike {
+ on(event: 'message', listener: (data: unknown, isBinary: boolean) => void): unknown;
+ on(event: 'close', listener: () => void): unknown;
+ on(event: 'error', listener: (err: unknown) => void): unknown;
+ send(data: string | ArrayBufferLike | ArrayBufferView): void;
+ close(code?: number, reason?: string): void;
+ /** Bytes accepted by `send` but not yet written to the network. */
+ readonly bufferedAmount?: number;
+ terminate?(): void;
+}
+
+export interface AcceptWebSocketOptions {
+ /** A client this far behind on reading is dropped rather than buffered for. Default 4 MiB. */
+ maxBufferedBytes?: number;
+}
+
+/** Close code for a client too slow to keep up (RFC 6455 "try again later"). */
+const TOO_SLOW = 1013;
+
+export function acceptWebSocket<Ctx extends SessionContext>(
+ host: SessionHost<Ctx>,
+ socket: WebSocketLike,
+ options: AcceptWebSocketOptions = {},
+): void {
+ const maxBuffered = options.maxBufferedBytes ?? 4 * 1024 * 1024;
+ const messageHandlers = new Set<(d: string | ArrayBuffer) => void>();
+ const closeHandlers = new Set<() => void>();
+ let closed = false;
+
+ const finish = (): void => {
+ if (closed) return;
+ closed = true;
+ for (const h of [...closeHandlers]) h();
+ closeHandlers.clear();
+ messageHandlers.clear();
+ };
+
+ socket.on('message', (data, isBinary) => {
+ if (closed) return;
+ const frame = isBinary ? toArrayBuffer(data) : String(data);
+ for (const h of [...messageHandlers]) h(frame);
+ });
+ socket.on('close', finish);
+ // `ws` follows an error with a close; the listener only keeps it from being thrown.
+ socket.on('error', () => {});
+
+ const connection: AcceptedConnection = {
+ transport: {
+ send(data) {
+ if (closed) return;
+ if ((socket.bufferedAmount ?? 0) > maxBuffered) {
+ connection.close(TOO_SLOW, 'client too slow');
+ return;
+ }
+ try { socket.send(data); } catch { connection.close(1011, 'send failed'); }
+ },
+ on(_event, handler) {
+ messageHandlers.add(handler);
+ return () => messageHandlers.delete(handler);
+ },
+ },
+ close(code, reason) {
+ if (closed) return;
+ try { socket.close(code, reason); } catch { socket.terminate?.(); }
+ // `ws` reports the close only after the peer answers; do not wait on a dead peer.
+ finish();
+ },
+ onClose(handler) {
+ if (closed) { queueMicrotask(handler); return () => {}; }
+ closeHandlers.add(handler);
+ return () => closeHandlers.delete(handler);
+ },
+ };
+ host.accept(connection);
+}
+
+function toArrayBuffer(data: unknown): ArrayBuffer {
+ if (data instanceof ArrayBuffer) return data;
+ if (ArrayBuffer.isView(data)) {
+ const copy = new Uint8Array(data.byteLength);
+ copy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
+ return copy.buffer;
+ }
+ if (Array.isArray(data)) {
+ const total = data.reduce((n: number, part: ArrayBufferView) => n + part.byteLength, 0);
+ const out = new Uint8Array(total);
+ let at = 0;
+ for (const part of data as ArrayBufferView[]) {
+ out.set(new Uint8Array(part.buffer, part.byteOffset, part.byteLength), at);
+ at += part.byteLength;
+ }
+ return out.buffer;
+ }
+ return new ArrayBuffer(0);
+}
diff --git a/sdk/src/net/session/contract.ts b/sdk/src/net/session/contract.ts
new file mode 100644
index 000000000..d62f07380
--- /dev/null
+++ b/sdk/src/net/session/contract.ts
@@ -0,0 +1,139 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file contract.ts
+ * @brief One definition of every request and event a game's client and server
+ * exchange. The server's handlers and the client's calls are typed from
+ * it, requests are checked on arrival, and replies are checked on
+ * receipt — so a client built before a change cannot half-understand a
+ * server built after it.
+ */
+import type { MessageHandler } from '../NetChannel';
+import { hashSeed } from '../../math/random';
+import type { ClientSession, SessionRequestOptions } from './ClientSession';
+import type { ServerSession, SessionContext, SessionHost } from './SessionHost';
+import { SchemaError, type Infer, type Schema } from './schema';
+
+export interface RequestDef<Req = unknown, Res = unknown> {
+ req: Schema<Req>;
+ res: Schema<Res>;
+}
+
+// `any` here, not `unknown`: a schema's type is read out of it by inference, and
+// `Schema<{ ... }>` is not assignable to `Schema<unknown>` through its `parse`.
+type RequestDefs = Record<string, RequestDef<any, any>>;
+type EventDefs = Record<string, Schema<any>>;
+
+type ReqOf<D> = D extends RequestDef<infer Q, unknown> ? Q : never;
+type ResOf<D> = D extends RequestDef<unknown, infer R> ? R : never;
+
+/** What the server writes for each request: the parsed payload in, the reply out. */
+export type ContractImpl<R extends RequestDefs, Ctx extends SessionContext> = {
+ [K in keyof R]: (payload: ReqOf<R[K]>, ctx: Ctx, session: ServerSession<Ctx>) => ResOf<R[K]> | Promise<ResOf<R[K]>>;
+};
+
+/** What the client calls for each request. */
+export type ContractClient<R extends RequestDefs> = {
+ [K in keyof R]: (payload: ReqOf<R[K]>, options?: SessionRequestOptions) => Promise<ResOf<R[K]>>;
+};
+
+export interface Contract<R extends RequestDefs, E extends EventDefs> {
+ /**
+ * A short stable text for the whole definition. Send it in the hello's
+ * credentials and compare on the server to turn away a client built against
+ * a different contract, instead of failing on its first odd request.
+ */
+ readonly fingerprint: string;
+ /** Register every request on the host, each checked against its schema. */
+ serve<Ctx extends SessionContext>(host: SessionHost<Ctx>, impl: ContractImpl<R, Ctx>): () => void;
+ /** Typed calls over a session; replies are checked before they are returned. */
+ client(session: ClientSession): ContractClient<R>;
+ /** Send a typed event to one player. */
+ push<K extends keyof E & string>(host: SessionHost<never>, playerId: string, type: K, payload: Infer<E[K]>): boolean;
+ /** Send a typed event to every player on the host. */
+ broadcast<K extends keyof E & string, Ctx extends SessionContext>(
+ host: SessionHost<Ctx>, type: K, payload: Infer<E[K]>, filter?: (ctx: Ctx) => boolean,
+ ): number;
+ /** Subscribe to a typed event on the client; payloads are checked before the handler sees them. */
+ on<K extends keyof E & string>(session: ClientSession, type: K, handler: MessageHandler<Infer<E[K]>>): () => void;
+}
+
+export function defineContract<R extends RequestDefs, E extends EventDefs = Record<never, never>>(
+ def: { requests: R; events?: E },
+): Contract<R, E> {
+ const events = (def.events ?? {}) as E;
+ const requestNames = Object.keys(def.requests);
+ const eventNames = Object.keys(events);
+ const description = [
+ ...requestNames.map((n) => `${n}(${def.requests[n]!.req.describe()})=>${def.requests[n]!.res.describe()}`),
+ ...eventNames.map((n) => `event ${n}(${events[n]!.describe()})`),
+ ].join(';');
+ const fingerprint = hashSeed(description).toString(16).padStart(8, '0');
+
+ return {
+ fingerprint,
+
+ serve(host, impl) {
+ const offs = requestNames.map((name) => {
+ const entry = def.requests[name]!;
+ const run = impl[name];
+ if (!run) throw new Error(`[contract] no implementation for request "${name}"`);
+ return host.handle(name, async (raw, ctx, session) => {
+ let payload: unknown;
+ try {
+ payload = entry.req.parse(raw);
+ } catch (err) {
+ if (err instanceof SchemaError) throw new Error(`invalid ${name} request: ${err.message}`);
+ throw err;
+ }
+ const result = await (run as (p: unknown, c: typeof ctx, s: typeof session) => unknown)(payload, ctx, session);
+ // A reply that breaks the contract is the server's bug; say so loudly
+ // here rather than let a client discover it.
+ try {
+ return entry.res.parse(result);
+ } catch (err) {
+ if (err instanceof SchemaError) throw new Error(`server bug: ${name} replied with ${err.message}`);
+ throw err;
+ }
+ });
+ });
+ const unknown = Object.keys(impl).filter((k) => !requestNames.includes(k));
+ if (unknown.length > 0) {
+ for (const off of offs) off();
+ throw new Error(`[contract] implementation has requests the contract does not: ${unknown.join(', ')}`);
+ }
+ return () => { for (const off of offs) off(); };
+ },
+
+ client(session) {
+ const out: Record<string, unknown> = {};
+ for (const name of requestNames) {
+ const entry = def.requests[name]!;
+ out[name] = async (payload: unknown, options?: SessionRequestOptions) => {
+ const checked = (entry.req as Schema<unknown>).parse(payload);
+ const reply = await session.request(name, checked, options);
+ return entry.res.parse(reply);
+ };
+ }
+ return out as ContractClient<R>;
+ },
+
+ push(host, playerId, type, payload) {
+ return host.push(playerId, type, events[type]!.parse(payload));
+ },
+
+ broadcast(host, type, payload, filter) {
+ return host.broadcast(type, events[type]!.parse(payload), filter);
+ },
+
+ on(session, type, handler) {
+ const schema = events[type];
+ if (!schema) throw new Error(`[contract] no event "${type}"`);
+ return session.on(type, (raw) => {
+ let payload: Infer<E[typeof type]>;
+ try { payload = schema.parse(raw) as Infer<E[typeof type]>; } catch { return; }
+ handler(payload);
+ });
+ },
+ };
+}
diff --git a/sdk/src/net/session/index.ts b/sdk/src/net/session/index.ts
new file mode 100644
index 000000000..49eb62ba2
--- /dev/null
+++ b/sdk/src/net/session/index.ts
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file index.ts
+ * @brief `esengine/session` — an online game's request/response layer: typed
+ * contracts, retry-safe requests, a reconnecting client session and the
+ * server host that authenticates and serves it. Independent of the
+ * engine's replication; built for asynchronous play where players act
+ * on a shared world without sharing a tick.
+ */
+export {
+ NetChannel,
+ NetRequestError,
+ NET_RATE_LIMITED,
+ NET_ATTEMPT_FAILED,
+ type NetTransport,
+ type ReliableOrderedTransport,
+ type NetChannelOptions,
+ type NetHeartbeatOptions,
+ type NetLimitOptions,
+ type NetViolation,
+ type NetRequestErrorCode,
+ type RequestOptions,
+ type MessageHandler,
+ type RequestHandler,
+} from '../NetChannel';
+export {
+ MemoryIdempotencyStore,
+ type IdempotencyStore,
+ type IdempotencyBegin,
+ type IdempotentOutcome,
+ type MemoryIdempotencyOptions,
+} from '../IdempotencyStore';
+export {
+ SESSION_PROTOCOL_VERSION,
+ SESSION_HELLO,
+ SessionCloseCode,
+ type SessionHelloRequest,
+ type SessionHelloResponse,
+} from './protocol';
+export {
+ SessionHost,
+ SessionRejected,
+ type AcceptedConnection,
+ type SessionContext,
+ type SessionHostOptions,
+ type SessionHandler,
+ type ServerSession,
+} from './SessionHost';
+export {
+ ClientSession,
+ type ClientSessionOptions,
+ type SessionBackoff,
+ type SessionRequestOptions,
+ type SessionState,
+ type SessionWelcome,
+} from './ClientSession';
+export { acceptWebSocket, type WebSocketLike, type AcceptWebSocketOptions } from './acceptWebSocket';
+export { s, SchemaError, type Schema, type Infer } from './schema';
+export {
+ defineContract,
+ type Contract,
+ type ContractClient,
+ type ContractImpl,
+ type RequestDef,
+} from './contract';
diff --git a/sdk/src/net/session/protocol.ts b/sdk/src/net/session/protocol.ts
new file mode 100644
index 000000000..5d50a1a3f
--- /dev/null
+++ b/sdk/src/net/session/protocol.ts
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file protocol.ts
+ * @brief The one handshake a session runs before any game request: the client
+ * names itself, the server decides who it is and tells it the time.
+ */
+
+/** Bumped when the hello changes shape; a mismatch refuses the connection. */
+export const SESSION_PROTOCOL_VERSION = 1;
+
+/** The request type of the handshake. Nothing else is served before it succeeds. */
+export const SESSION_HELLO = 'session:hello';
+
+/** Close codes the server uses, so a client can tell why it was let go. */
+export const SessionCloseCode = {
+ /** Another connection for the same player took this one's place. */
+ replaced: 4001,
+ /** No valid hello arrived in time. */
+ helloTimeout: 4002,
+ /** The server is full or shutting down; try later. */
+ unavailable: 4003,
+ /** The peer kept breaking the frame or rate limits. */
+ abuse: 4004,
+} as const;
+
+export interface SessionHelloRequest {
+ version: number;
+ /** Whatever the game's `authenticate` understands: a token, a device id. */
+ credentials: unknown;
+}
+
+export type SessionHelloResponse =
+ | {
+ ok: true;
+ playerId: string;
+ /** The server's clock at the moment it answered, in epoch milliseconds. */
+ serverTimeMs: number;
+ /** Anything the game wants the client to have at once (a renewed token). */
+ data?: unknown;
+ }
+ | { ok: false; error: string; /** Retrying cannot help; the client stops. */ fatal: boolean };
diff --git a/sdk/src/net/session/schema.ts b/sdk/src/net/session/schema.ts
new file mode 100644
index 000000000..23d521f27
--- /dev/null
+++ b/sdk/src/net/session/schema.ts
@@ -0,0 +1,171 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file schema.ts
+ * @brief Small runtime validators that also give the TypeScript type. A server
+ * never trusts what a client sent, so each request is parsed against the
+ * same definition the client's types came from — written once.
+ */
+
+/** Thrown by `parse` with the path of the first thing that was wrong. */
+export class SchemaError extends Error {
+ constructor(readonly path: string, message: string) {
+ super(path ? `${path}: ${message}` : message);
+ this.name = 'SchemaError';
+ }
+}
+
+export interface Schema<T> {
+ /** Returns a clean copy of `value` typed as `T`, or throws {@link SchemaError}. */
+ parse(value: unknown, path?: string): T;
+ /** A stable text form, so two builds can tell whether they agree on the shape. */
+ describe(): string;
+}
+
+/** The TypeScript type a schema parses to. */
+export type Infer<S> = S extends Schema<infer T> ? T : never;
+
+const fail = (path: string, message: string): never => { throw new SchemaError(path, message); };
+const at = (path: string, key: string | number): string => (path ? `${path}.${key}` : String(key));
+
+const NO_PROTO = new Set(['__proto__', 'constructor', 'prototype']);
+
+type Shape = Record<string, Schema<unknown>>;
+type OptionalKeys<S extends Shape> = { [K in keyof S]: undefined extends Infer<S[K]> ? K : never }[keyof S];
+type Flat<T> = { [K in keyof T]: T[K] };
+type ObjectOf<S extends Shape> =
+ Flat<{ [K in Exclude<keyof S, OptionalKeys<S>>]: Infer<S[K]> } & { [K in OptionalKeys<S>]?: Infer<S[K]> }>;
+
+export const s = {
+ string(opts: { min?: number; max?: number; pattern?: RegExp } = {}): Schema<string> {
+ const max = opts.max ?? 1024;
+ return {
+ parse(v, path = '') {
+ if (typeof v !== 'string') return fail(path, 'expected a string');
+ if (v.length < (opts.min ?? 0)) return fail(path, `shorter than ${opts.min}`);
+ if (v.length > max) return fail(path, `longer than ${max}`);
+ if (opts.pattern && !opts.pattern.test(v)) return fail(path, 'does not match the required pattern');
+ return v;
+ },
+ describe: () => `string(${opts.min ?? 0}..${max}${opts.pattern ? `,/${opts.pattern.source}/` : ''})`,
+ };
+ },
+
+ int(opts: { min?: number; max?: number } = {}): Schema<number> {
+ const min = opts.min ?? Number.MIN_SAFE_INTEGER;
+ const max = opts.max ?? Number.MAX_SAFE_INTEGER;
+ return {
+ parse(v, path = '') {
+ if (typeof v !== 'number' || !Number.isSafeInteger(v)) return fail(path, 'expected an integer');
+ if (v < min || v > max) return fail(path, `outside ${min}..${max}`);
+ return v;
+ },
+ describe: () => `int(${min}..${max})`,
+ };
+ },
+
+ number(opts: { min?: number; max?: number } = {}): Schema<number> {
+ const min = opts.min ?? -Infinity;
+ const max = opts.max ?? Infinity;
+ return {
+ parse(v, path = '') {
+ if (typeof v !== 'number' || !Number.isFinite(v)) return fail(path, 'expected a finite number');
+ if (v < min || v > max) return fail(path, `outside ${min}..${max}`);
+ return v;
+ },
+ describe: () => `number(${min}..${max})`,
+ };
+ },
+
+ boolean(): Schema<boolean> {
+ return {
+ parse: (v, path = '') => (typeof v === 'boolean' ? v : fail(path, 'expected a boolean')),
+ describe: () => 'boolean',
+ };
+ },
+
+ literal<const T extends string | number | boolean | null>(value: T): Schema<T> {
+ return {
+ parse: (v, path = '') => (v === value ? (v as T) : fail(path, `expected ${JSON.stringify(value)}`)),
+ describe: () => `literal(${JSON.stringify(value)})`,
+ };
+ },
+
+ /** One of a fixed list of strings. */
+ enum<const T extends readonly [string, ...string[]]>(values: T): Schema<T[number]> {
+ const set = new Set<string>(values);
+ return {
+ parse: (v, path = '') => (typeof v === 'string' && set.has(v) ? (v as T[number]) : fail(path, `expected one of ${values.join(', ')}`)),
+ describe: () => `enum(${values.join('|')})`,
+ };
+ },
+
+ array<T>(item: Schema<T>, opts: { max?: number } = {}): Schema<T[]> {
+ const max = opts.max ?? 256;
+ return {
+ parse(v, path = '') {
+ if (!Array.isArray(v)) return fail(path, 'expected an array');
+ if (v.length > max) return fail(path, `more than ${max} items`);
+ return v.map((x, i) => item.parse(x, at(path, i)));
+ },
+ describe: () => `array(${item.describe()},max ${max})`,
+ };
+ },
+
+ /** An object with exactly these keys; any other key in the input is dropped. */
+ object<S extends Shape>(shape: S): Schema<ObjectOf<S>> {
+ const keys = Object.keys(shape);
+ for (const k of keys) if (NO_PROTO.has(k)) throw new Error(`[schema] "${k}" cannot be a key`);
+ return {
+ parse(v, path = '') {
+ if (typeof v !== 'object' || v === null || Array.isArray(v)) return fail(path, 'expected an object');
+ const input = v as Record<string, unknown>;
+ const out: Record<string, unknown> = {};
+ for (const k of keys) {
+ const value = shape[k]!.parse(Object.prototype.hasOwnProperty.call(input, k) ? input[k] : undefined, at(path, k));
+ if (value !== undefined) out[k] = value;
+ }
+ return out as ObjectOf<S>;
+ },
+ describe: () => `{${keys.map((k) => `${k}:${shape[k]!.describe()}`).join(',')}}`,
+ };
+ },
+
+ /** An object used as a map from string keys to one kind of value. */
+ record<T>(value: Schema<T>, opts: { maxKeys?: number } = {}): Schema<Record<string, T>> {
+ const maxKeys = opts.maxKeys ?? 256;
+ return {
+ parse(v, path = '') {
+ if (typeof v !== 'object' || v === null || Array.isArray(v)) return fail(path, 'expected an object');
+ const keys = Object.keys(v);
+ if (keys.length > maxKeys) return fail(path, `more than ${maxKeys} keys`);
+ const out: Record<string, T> = {};
+ for (const k of keys) {
+ if (NO_PROTO.has(k)) return fail(at(path, k), 'key not allowed');
+ out[k] = value.parse((v as Record<string, unknown>)[k], at(path, k));
+ }
+ return out;
+ },
+ describe: () => `record(${value.describe()},max ${maxKeys})`,
+ };
+ },
+
+ optional<T>(inner: Schema<T>): Schema<T | undefined> {
+ return {
+ parse: (v, path = '') => (v === undefined ? undefined : inner.parse(v, path)),
+ describe: () => `optional(${inner.describe()})`,
+ };
+ },
+
+ nullable<T>(inner: Schema<T>): Schema<T | null> {
+ return {
+ parse: (v, path = '') => (v === null ? null : inner.parse(v, path)),
+ describe: () => `nullable(${inner.describe()})`,
+ };
+ },
+
+ /** Anything JSON can carry. Use sparingly: nothing about it is checked. */
+ unknown(): Schema<unknown> {
+ return { parse: (v) => v, describe: () => 'unknown' };
+ },
+};
diff --git a/sdk/tests/net-channel-hardening.test.ts b/sdk/tests/net-channel-hardening.test.ts
new file mode 100644
index 000000000..6cc41731f
--- /dev/null
+++ b/sdk/tests/net-channel-hardening.test.ts
@@ -0,0 +1,188 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { NetChannel, type NetChannelOptions, type NetTransport, type NetViolation } from '../src/net/NetChannel';
+import { MemoryIdempotencyStore } from '../src/net/IdempotencyStore';
+
+type Frame = string | ArrayBuffer;
+
+function pair(): [NetTransport & { drop: boolean }, NetTransport & { drop: boolean }] {
+ const ha = new Set<(d: Frame) => void>();
+ const hb = new Set<(d: Frame) => void>();
+ const make = (mine: Set<(d: Frame) => void>, theirs: Set<(d: Frame) => void>) => {
+ const t = {
+ drop: false,
+ send: (d: Frame) => { if (!t.drop) for (const h of [...theirs]) h(d); },
+ on: (_e: 'message', h: (d: Frame) => void) => { mine.add(h); return () => mine.delete(h); },
+ };
+ return t;
+ };
+ return [make(ha, hb), make(hb, ha)];
+}
+
+function link(server: NetChannelOptions = {}, client: NetChannelOptions = {}) {
+ const [tc, ts] = pair();
+ return { tc, ts, client: new NetChannel(tc, client), server: new NetChannel(ts, server) };
+}
+
+afterEach(() => { vi.useRealTimers(); });
+
+describe('idempotent requests', () => {
+ it('runs a keyed handler once and replays its answer to a retry', async () => {
+ const { client, server } = link({ idempotency: new MemoryIdempotencyStore(), idempotencyScope: 'p1' });
+ let runs = 0;
+ server.handle('buy', () => ({ bought: ++runs }));
+ const a = await client.request('buy', {}, { idempotencyKey: 'click-1' });
+ const b = await client.request('buy', {}, { idempotencyKey: 'click-1' });
+ expect(a).toEqual({ bought: 1 });
+ expect(b).toEqual({ bought: 1 });
+ expect(runs).toBe(1);
+ const c = await client.request('buy', {}, { idempotencyKey: 'click-2' });
+ expect(c).toEqual({ bought: 2 });
+ });
+
+ it('a retry that arrives while the first is still running waits for it', async () => {
+ const { client, server } = link({ idempotency: new MemoryIdempotencyStore() });
+ let release!: () => void;
+ const gate = new Promise<void>((r) => { release = r; });
+ let runs = 0;
+ server.handle('slow', async () => { runs++; await gate; return 'ok'; });
+ const first = client.request('slow', {}, { idempotencyKey: 'k' });
+ const second = client.request('slow', {}, { idempotencyKey: 'k' });
+ await Promise.resolve();
+ release();
+ expect(await first).toBe('ok');
+ expect(await second).toBe('ok');
+ expect(runs).toBe(1);
+ });
+
+ it('a handler that throws frees the key, so the retry runs again', async () => {
+ const { client, server } = link({ idempotency: new MemoryIdempotencyStore() });
+ let runs = 0;
+ server.handle('flaky', () => { if (++runs === 1) throw new Error('boom'); return 'fine'; });
+ await expect(client.request('flaky', {}, { idempotencyKey: 'k' })).rejects.toThrow('boom');
+ expect(await client.request('flaky', {}, { idempotencyKey: 'k' })).toBe('fine');
+ expect(runs).toBe(2);
+ });
+
+ it('keys are scoped: another player or another request type does not collide', async () => {
+ const store = new MemoryIdempotencyStore();
+ const one = link({ idempotency: store, idempotencyScope: 'p1' });
+ const two = link({ idempotency: store, idempotencyScope: 'p2' });
+ let runs = 0;
+ for (const s of [one.server, two.server]) {
+ s.handle('a', () => ++runs);
+ s.handle('b', () => ++runs);
+ }
+ await one.client.request('a', {}, { idempotencyKey: 'k' });
+ await two.client.request('a', {}, { idempotencyKey: 'k' });
+ await one.client.request('b', {}, { idempotencyKey: 'k' });
+ expect(runs).toBe(3);
+ });
+
+ it('an unkeyed request still runs every time, with or without a store', async () => {
+ const { client, server } = link({ idempotency: new MemoryIdempotencyStore() });
+ let runs = 0;
+ server.handle('n', () => ++runs);
+ await client.request('n', {});
+ await client.request('n', {});
+ expect(runs).toBe(2);
+ });
+
+ it('the numeric timeout argument still works', async () => {
+ vi.useFakeTimers();
+ const [tc] = pair();
+ const client = new NetChannel(tc);
+ const p = client.request('never', {}, 50);
+ const caught = p.catch((e: Error) => e.message);
+ await vi.advanceTimersByTimeAsync(60);
+ expect(await caught).toContain('timed out after 50ms');
+ });
+});
+
+describe('memory idempotency store', () => {
+ it('forgets an answer after its ttl', async () => {
+ let t = 0;
+ const store = new MemoryIdempotencyStore({ ttlMs: 100, now: () => t });
+ expect((await store.begin('k')).state).toBe('new');
+ store.finish('k', { d: 1 });
+ t = 50;
+ expect((await store.begin('k')).state).toBe('done');
+ t = 150;
+ expect((await store.begin('k')).state).toBe('new');
+ });
+
+ it('stays under its cap by dropping the oldest finished answers', () => {
+ const store = new MemoryIdempotencyStore({ maxEntries: 3 });
+ for (let i = 0; i < 10; i++) { store.begin(`k${i}`); store.finish(`k${i}`, { d: i }); }
+ expect(store.size).toBeLessThanOrEqual(3);
+ expect(store.begin('k9').state).toBe('done');
+ });
+});
+
+describe('frame and rate limits', () => {
+ it('drops an oversize frame before parsing it', () => {
+ const seen: NetViolation[] = [];
+ const { client, server } = link({ limits: { maxFrameBytes: 100, onViolation: (k) => seen.push(k) } });
+ const got: unknown[] = [];
+ server.on('say', (p) => got.push(p));
+ client.send('say', 'x'.repeat(500));
+ client.send('say', 'hi');
+ expect(got).toEqual(['hi']);
+ expect(seen).toEqual(['frame-size']);
+ });
+
+ it('refuses messages over the sustained rate, answers requests, and recovers', async () => {
+ vi.useFakeTimers();
+ const seen: NetViolation[] = [];
+ const { client, server } = link({ limits: { messagesPerSecond: 10, burst: 3, onViolation: (k) => seen.push(k) } });
+ const got: number[] = [];
+ server.on<number>('tick', (n) => got.push(n));
+ server.handle('echo', (x) => x);
+ for (let i = 0; i < 6; i++) client.send('tick', i);
+ expect(got).toEqual([0, 1, 2]);
+ expect(seen.length).toBe(3);
+
+ const refused = client.request('echo', 1).catch((e: Error) => e.message);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(await refused).toBe('rate limited');
+
+ await vi.advanceTimersByTimeAsync(1000);
+ client.send('tick', 99);
+ expect(got.at(-1)).toBe(99);
+ });
+
+ it('does not rate-limit binary frames', () => {
+ const { client, server } = link({ limits: { messagesPerSecond: 1, burst: 1 } });
+ let n = 0;
+ server.onBinary(7, () => n++);
+ for (let i = 0; i < 20; i++) client.sendBinary(7, new Uint8Array([1]));
+ expect(n).toBe(20);
+ });
+});
+
+describe('heartbeat', () => {
+ it('stays quiet while the peer answers, and reports once when it goes silent', async () => {
+ vi.useFakeTimers();
+ const dead = vi.fn();
+ const { tc, client, server } = link({}, { heartbeat: { intervalMs: 100, timeoutMs: 350, onDead: dead } });
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(dead).not.toHaveBeenCalled();
+
+ tc.drop = true;
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(dead).toHaveBeenCalledTimes(1);
+ client.dispose();
+ server.dispose();
+ });
+
+ it('stops its timer on dispose', async () => {
+ vi.useFakeTimers();
+ const dead = vi.fn();
+ const { tc, client } = link({}, { heartbeat: { intervalMs: 100, timeoutMs: 200, onDead: dead } });
+ tc.drop = true;
+ client.dispose();
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(dead).not.toHaveBeenCalled();
+ });
+});
diff --git a/sdk/tests/net-contract.test.ts b/sdk/tests/net-contract.test.ts
new file mode 100644
index 000000000..d0f4789c1
--- /dev/null
+++ b/sdk/tests/net-contract.test.ts
@@ -0,0 +1,82 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect, expectTypeOf } from 'vitest';
+import { s, SchemaError, type Infer } from '../src/net/session/schema';
+import { defineContract } from '../src/net/session/contract';
+
+describe('schema', () => {
+ it('accepts a good value and returns a clean copy', () => {
+ const shape = s.object({ id: s.string({ max: 8 }), n: s.int({ min: 1, max: 9 }), tags: s.array(s.string(), { max: 2 }) });
+ const input = { id: 'abc', n: 3, tags: ['x'], extra: 'dropped' };
+ const out = shape.parse(input);
+ expect(out).toEqual({ id: 'abc', n: 3, tags: ['x'] });
+ expect(out).not.toBe(input);
+ expectTypeOf<Infer<typeof shape>>().toEqualTypeOf<{ id: string; n: number; tags: string[] }>();
+ });
+
+ it('names the path of the first problem', () => {
+ const shape = s.object({ order: s.object({ qty: s.int({ min: 1 }) }) });
+ expect(() => shape.parse({ order: { qty: 0 } })).toThrow('order.qty: outside 1..');
+ expect(() => shape.parse({ order: { qty: 1.5 } })).toThrow('order.qty: expected an integer');
+ expect(() => shape.parse(null)).toThrow(SchemaError);
+ });
+
+ it('bounds strings, arrays and records so a request cannot be made huge', () => {
+ expect(() => s.string({ max: 3 }).parse('abcd')).toThrow('longer than 3');
+ expect(() => s.string().parse('x'.repeat(1025))).toThrow('longer than 1024');
+ expect(() => s.array(s.int()).parse(new Array(300).fill(1))).toThrow('more than 256');
+ expect(() => s.record(s.int(), { maxKeys: 2 }).parse({ a: 1, b: 2, c: 3 })).toThrow('more than 2 keys');
+ });
+
+ it('refuses keys that could poison a prototype', () => {
+ expect(() => s.record(s.int()).parse(JSON.parse('{"__proto__": 1}'))).toThrow('key not allowed');
+ expect(() => s.object({ ['__proto__']: s.int() })).toThrow('cannot be a key');
+ expect(({} as Record<string, unknown>).polluted).toBeUndefined();
+ });
+
+ it('optional, nullable, enum and literal behave', () => {
+ const shape = s.object({ a: s.optional(s.int()), b: s.nullable(s.string()), c: s.enum(['x', 'y']), d: s.literal(1) });
+ expect(shape.parse({ b: null, c: 'x', d: 1 })).toEqual({ b: null, c: 'x', d: 1 });
+ expect(() => shape.parse({ b: null, c: 'z', d: 1 })).toThrow('expected one of x, y');
+ expect(() => shape.parse({ b: null, c: 'x', d: 2 })).toThrow('expected 1');
+ expect(() => shape.parse({ c: 'x', d: 1 })).toThrow('b: expected a string');
+ expectTypeOf<Infer<typeof shape>>().toEqualTypeOf<{ a?: number | undefined; b: string | null; c: 'x' | 'y'; d: 1 }>();
+ });
+
+ it('rejects NaN and Infinity where a number is expected', () => {
+ expect(() => s.number().parse(Number.NaN)).toThrow();
+ expect(() => s.number().parse(Infinity)).toThrow();
+ expect(() => s.int().parse(2 ** 60)).toThrow();
+ });
+});
+
+const contract = defineContract({
+ requests: {
+ trade: { req: s.object({ offer: s.string({ max: 16 }), qty: s.int({ min: 1, max: 9 }) }), res: s.object({ paid: s.int() }) },
+ ping: { req: s.object({}), res: s.literal('pong') },
+ },
+ events: { radio: s.object({ from: s.string(), text: s.string({ max: 200 }) }) },
+});
+
+describe('defineContract', () => {
+ it('fingerprint is stable and moves with the shape', () => {
+ const again = defineContract({
+ requests: {
+ trade: { req: s.object({ offer: s.string({ max: 16 }), qty: s.int({ min: 1, max: 9 }) }), res: s.object({ paid: s.int() }) },
+ ping: { req: s.object({}), res: s.literal('pong') },
+ },
+ events: { radio: s.object({ from: s.string(), text: s.string({ max: 200 }) }) },
+ });
+ expect(again.fingerprint).toBe(contract.fingerprint);
+ const changed = defineContract({ requests: { ping: { req: s.object({}), res: s.literal('pong') } } });
+ expect(changed.fingerprint).not.toBe(contract.fingerprint);
+ expect(contract.fingerprint).toMatch(/^[0-9a-f]{8}$/);
+ });
+
+ it('types the client from the definition', () => {
+ type Client = ReturnType<typeof contract.client>;
+ expectTypeOf<Parameters<Client['trade']>[0]>().toEqualTypeOf<{ offer: string; qty: number }>();
+ expectTypeOf<ReturnType<Client['trade']>>().toEqualTypeOf<Promise<{ paid: number }>>();
+ expectTypeOf<ReturnType<Client['ping']>>().toEqualTypeOf<Promise<'pong'>>();
+ });
+});
diff --git a/sdk/tests/net-session-ws.test.ts b/sdk/tests/net-session-ws.test.ts
new file mode 100644
index 000000000..a60bcacc8
--- /dev/null
+++ b/sdk/tests/net-session-ws.test.ts
@@ -0,0 +1,125 @@
+// @vitest-environment node
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The session layer over real sockets: a `ws` server hands each
+ * connection to a SessionHost, and a ClientSession rides the platform
+ * GameSocket on the global WebSocket. Loopback TCP in between.
+ */
+import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from 'vitest';
+import { WebSocketServer } from 'ws';
+import { GameSocket } from '../src/net/GameSocket';
+import { ClientSession } from '../src/net/session/ClientSession';
+import { SessionHost, SessionRejected } from '../src/net/session/SessionHost';
+import { acceptWebSocket } from '../src/net/session/acceptWebSocket';
+import { defineContract } from '../src/net/session/contract';
+import { s } from '../src/net/session/schema';
+
+const contract = defineContract({
+ requests: {
+ buy: { req: s.object({ item: s.enum(['water', 'food']), qty: s.int({ min: 1, max: 5 }) }), res: s.object({ credits: s.int() }) },
+ },
+ events: { radio: s.object({ text: s.string() }) },
+});
+
+describe('session over real WebSockets', () => {
+ let wss: WebSocketServer;
+ let url: string;
+ const wallet = new Map<string, number>();
+ let runs = 0;
+ const host = new SessionHost({
+ authenticate: (c) => {
+ const t = (c as { token?: string; contract?: string }) ?? {};
+ if (t.contract !== contract.fingerprint) throw new SessionRejected('update the game');
+ if (!t.token) throw new SessionRejected('no token');
+ return { playerId: t.token };
+ },
+ });
+ contract.serve(host, {
+ buy: ({ qty }, ctx) => {
+ runs++;
+ const left = (wallet.get(ctx.playerId) ?? 100) - qty * 10;
+ wallet.set(ctx.playerId, left);
+ return { credits: left };
+ },
+ });
+
+ beforeAll(async () => {
+ wss = new WebSocketServer({ port: 0, host: '127.0.0.1', maxPayload: 1 << 20 });
+ wss.on('connection', (socket) => acceptWebSocket(host, socket));
+ await new Promise<void>((r) => wss.on('listening', () => r()));
+ url = `ws://127.0.0.1:${(wss.address() as { port: number }).port}`;
+ });
+ afterAll(async () => {
+ host.close();
+ await new Promise<void>((r) => wss.close(() => r()));
+ });
+
+ const opened: ClientSession[] = [];
+ afterEach(() => { for (const c of opened.splice(0)) c.close(); });
+ const session = (token: string, fingerprint = contract.fingerprint) => {
+ const c = new ClientSession({
+ connect: () => new GameSocket({ url }),
+ credentials: () => ({ token, contract: fingerprint }),
+ backoff: { initialMs: 10, maxMs: 50, jitter: 0 },
+ retryDelayMs: 10,
+ });
+ opened.push(c);
+ return c;
+ };
+
+ it('serves a typed request end to end', async () => {
+ const c = session('p-typed');
+ await c.start();
+ const api = contract.client(c);
+ expect(await api.buy({ item: 'water', qty: 2 })).toEqual({ credits: 80 });
+ await expect(api.buy({ item: 'water', qty: 0 })).rejects.toThrow('qty');
+ });
+
+ it('the server refuses a request the contract does not allow', async () => {
+ const c = session('p-bad');
+ await c.start();
+ await expect(c.request('buy', { item: 'gold', qty: 1 })).rejects.toThrow('invalid buy request');
+ expect(wallet.has('p-bad')).toBe(false);
+ });
+
+ it('turns away a client built against another contract', async () => {
+ const c = session('p-old', 'deadbeef');
+ await expect(c.start()).rejects.toThrow('update the game');
+ });
+
+ it('survives the server dropping every socket: redials, keeps subscriptions, never double-spends', async () => {
+ const c = session('p-drop');
+ const heard: string[] = [];
+ contract.on(c, 'radio', (m) => heard.push(m.text));
+ await c.start();
+ const api = contract.client(c);
+ await api.buy({ item: 'food', qty: 1 });
+
+ const states: string[] = [];
+ c.onState((st) => states.push(st));
+ for (const sock of wss.clients) sock.terminate();
+ // The redial is fast enough to pass through 'reconnecting' between two polls, so record it.
+ await vi.waitFor(() => expect(states).toEqual(['reconnecting', 'ready']), { timeout: 2000 });
+
+ const before = runs;
+ const after = await api.buy({ item: 'food', qty: 1 }, { idempotencyKey: 'one-click' });
+ expect(after.credits).toBe(80);
+ // The same intent sent again lands on the new connection and is answered from memory.
+ const again = await api.buy({ item: 'food', qty: 1 }, { idempotencyKey: 'one-click' });
+ expect(again).toEqual(after);
+ expect(runs).toBe(before + 1);
+
+ contract.broadcast(host, 'radio', { text: 'back on air' });
+ await vi.waitFor(() => expect(heard).toEqual(['back on air']));
+ });
+
+ it('a new connection for the same player closes the old one for good', async () => {
+ const a = session('p-twin');
+ await a.start();
+ const b = session('p-twin');
+ await b.start();
+ await vi.waitFor(() => expect(a.state).toBe('closed'), { timeout: 2000 });
+ expect(b.state).toBe('ready');
+ });
+});
diff --git a/sdk/tests/net-session.test.ts b/sdk/tests/net-session.test.ts
new file mode 100644
index 000000000..e202bf988
--- /dev/null
+++ b/sdk/tests/net-session.test.ts
@@ -0,0 +1,258 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { ClientSession, type ClientSessionOptions } from '../src/net/session/ClientSession';
+import { SessionHost, SessionRejected, type AcceptedConnection, type SessionContext, type SessionHostOptions } from '../src/net/session/SessionHost';
+import { SessionCloseCode } from '../src/net/session/protocol';
+import type { PlatformSocket, PlatformSocketEvents } from '../src/platform/types';
+
+type Frame = string | ArrayBuffer;
+
+/** An in-memory network between client sockets and one host, with a way to cut it. */
+class FakeNet {
+ readonly live = new Set<{ shutdown(code: number, reason: string): void }>();
+ readonly serverCloses: number[] = [];
+ down = false;
+ dials = 0;
+ constructor(readonly host: SessionHost<TestCtx>) {}
+
+ socket(): PlatformSocket {
+ const events = new Map<string, Set<(...a: never[]) => void>>();
+ const emit = <K extends keyof PlatformSocketEvents>(e: K, ...a: PlatformSocketEvents[K]) =>
+ events.get(e)?.forEach((f) => (f as (...x: PlatformSocketEvents[K]) => void)(...a));
+ const toServer = new Set<(d: Frame) => void>();
+ const closeHandlers = new Set<() => void>();
+ let open = false;
+ const link = {
+ shutdown: (code: number, reason: string, byServer = false) => {
+ if (!open) return;
+ open = false;
+ client.readyState = 'closed';
+ this.live.delete(link);
+ if (byServer) this.serverCloses.push(code);
+ queueMicrotask(() => { emit('close', code, reason); closeHandlers.forEach((h) => h()); });
+ },
+ };
+ const client: PlatformSocket = {
+ delivery: 'reliable-ordered',
+ readyState: 'closed',
+ on: (e, h) => {
+ let set = events.get(e);
+ if (!set) { set = new Set(); events.set(e, set); }
+ set.add(h as never);
+ return () => set!.delete(h as never);
+ },
+ connect: () => {
+ this.dials++;
+ client.readyState = 'connecting';
+ queueMicrotask(() => {
+ if (this.down) { client.readyState = 'closed'; emit('error', new Error('refused')); return; }
+ open = true;
+ client.readyState = 'open';
+ this.live.add(link);
+ this.host.accept(conn);
+ emit('open');
+ });
+ },
+ send: (d) => { if (open) queueMicrotask(() => { if (open) toServer.forEach((h) => h(d)); }); },
+ close: (code = 1000, reason = '') => link.shutdown(code, reason),
+ };
+ const conn: AcceptedConnection = {
+ transport: {
+ send: (d) => { if (open) queueMicrotask(() => { if (open) emit('message', d); }); },
+ on: (_e, h) => { toServer.add(h); return () => toServer.delete(h); },
+ },
+ close: (code = 1000, reason = '') => link.shutdown(code, reason, true),
+ onClose: (h) => { closeHandlers.add(h); return () => closeHandlers.delete(h); },
+ };
+ return client;
+ }
+
+ cut(): void {
+ for (const l of [...this.live]) l.shutdown(1006, 'cut');
+ }
+}
+
+interface TestCtx extends SessionContext { name: string }
+
+function setup(hostOpts: Partial<SessionHostOptions<TestCtx>> = {}) {
+ const host = new SessionHost<TestCtx>({
+ authenticate: (c) => {
+ const token = (c as { token?: string })?.token;
+ if (token === 'bad') throw new SessionRejected('bad token');
+ if (token === 'later') throw new SessionRejected('try again later', false);
+ if (!token) throw new SessionRejected('no token');
+ return { playerId: token, name: `player-${token}` };
+ },
+ ...hostOpts,
+ });
+ const net = new FakeNet(host);
+ const client = (token: string, opts: Partial<ClientSessionOptions> = {}) =>
+ new ClientSession({
+ connect: () => net.socket(),
+ credentials: () => ({ token }),
+ backoff: { initialMs: 5, maxMs: 20, jitter: 0 },
+ retryDelayMs: 5,
+ heartbeat: false,
+ ...opts,
+ });
+ return { host, net, client };
+}
+
+const closed: ClientSession[] = [];
+afterEach(() => { for (const c of closed.splice(0)) c.close(); vi.useRealTimers(); });
+const track = (c: ClientSession) => { closed.push(c); return c; };
+
+describe('SessionHost + ClientSession', () => {
+ it('says hello, becomes ready, and shares the server clock', async () => {
+ const { host, client } = setup();
+ const s = track(client('ann'));
+ const welcome = await s.start();
+ expect(welcome.playerId).toBe('ann');
+ expect(s.state).toBe('ready');
+ expect(host.playerCount).toBe(1);
+ expect(Math.abs(s.serverNow() - Date.now())).toBeLessThan(500);
+ });
+
+ it('serves no game request before the hello succeeded', async () => {
+ const { host, net } = setup();
+ host.handle('secret', () => 'data');
+ const { NetChannel } = await import('../src/net/NetChannel');
+ const raw = net.socket();
+ const channel = new NetChannel(raw);
+ raw.connect();
+ await vi.waitFor(() => expect(raw.readyState).toBe('open'));
+ await expect(channel.request('secret', {})).rejects.toThrow('no request handler');
+ });
+
+ it('a fatal refusal stops the session and does not redial', async () => {
+ const { net, client } = setup();
+ const s = track(client('bad'));
+ await expect(s.start()).rejects.toThrow('bad token');
+ expect(s.state).toBe('closed');
+ const dials = net.dials;
+ await new Promise((r) => setTimeout(r, 50));
+ expect(net.dials).toBe(dials);
+ });
+
+ it('a refusal that is not fatal is retried', async () => {
+ const { net, client } = setup();
+ const s = track(client('later'));
+ void s.start().catch(() => {});
+ await vi.waitFor(() => expect(net.dials).toBeGreaterThan(2));
+ expect(s.state).not.toBe('closed');
+ });
+
+ it('passes the player to handlers, and request answers come back', async () => {
+ const { host, client } = setup();
+ host.handle<{ n: number }, { who: string; n: number }>('echo', (p, ctx) => ({ who: ctx.name, n: p.n }));
+ const s = track(client('bo'));
+ await s.start();
+ expect(await s.request('echo', { n: 4 })).toEqual({ who: 'player-bo', n: 4 });
+ });
+
+ it('a remote error is not retried', async () => {
+ const { host, client } = setup();
+ let runs = 0;
+ host.handle('fail', () => { runs++; throw new Error('no stock'); });
+ const s = track(client('cy'));
+ await s.start();
+ await expect(s.request('fail', {})).rejects.toThrow('no stock');
+ expect(runs).toBe(1);
+ });
+
+ it('a reply lost with the link is retried under the same key and runs once', async () => {
+ const { host, net, client } = setup();
+ let runs = 0;
+ host.handle('buy', () => {
+ runs++;
+ net.cut(); // the work is done, the answer never arrives
+ return { bought: runs };
+ });
+ const s = track(client('dee'));
+ await s.start();
+ const answer = await s.request('buy', {});
+ expect(answer).toEqual({ bought: 1 });
+ expect(runs).toBe(1);
+ expect(net.dials).toBe(2); // the link really dropped and the request really came again
+ expect(s.state).toBe('ready');
+ });
+
+ it('redials after a cut and keeps its event subscriptions', async () => {
+ const { host, net, client } = setup();
+ const s = track(client('eve'));
+ const heard: unknown[] = [];
+ s.on('radio', (m) => heard.push(m));
+ await s.start();
+ const states: string[] = [];
+ s.onState((st) => states.push(st));
+ net.cut();
+ await vi.waitFor(() => expect(states).toEqual(['reconnecting', 'ready']));
+ expect(host.push('eve', 'radio', 'hello again')).toBe(true);
+ await vi.waitFor(() => expect(heard).toEqual(['hello again']));
+ });
+
+ it('a request issued while the link is down waits for it and then goes through', async () => {
+ const { host, net, client } = setup();
+ host.handle('ping', () => 'pong');
+ const s = track(client('fay'));
+ await s.start();
+ net.down = true;
+ net.cut();
+ await vi.waitFor(() => expect(s.state).toBe('reconnecting'));
+ const pending = s.request('ping', {});
+ await new Promise((r) => setTimeout(r, 30));
+ net.down = false;
+ expect(await pending).toBe('pong');
+ });
+
+ it('a newer connection for the same player replaces the older, which stays closed', async () => {
+ const { host, client } = setup();
+ const first = track(client('gil'));
+ await first.start();
+ const second = track(client('gil'));
+ await second.start();
+ await vi.waitFor(() => expect(first.state).toBe('closed'));
+ expect(second.state).toBe('ready');
+ expect(host.playerCount).toBe(1);
+ await expect(first.request('x', {})).rejects.toThrow('closed');
+ });
+
+ it('closes a connection that never says hello', async () => {
+ const { net } = setup({ helloTimeoutMs: 20 });
+ const raw = net.socket();
+ raw.connect();
+ await vi.waitFor(() => expect(net.serverCloses).toContain(SessionCloseCode.helloTimeout));
+ });
+
+ it('refuses connections past maxSessions', async () => {
+ const { net, client } = setup({ maxSessions: 1 });
+ const a = track(client('hal'));
+ await a.start();
+ const raw = net.socket();
+ raw.connect();
+ await vi.waitFor(() => expect(net.serverCloses).toContain(SessionCloseCode.unavailable));
+ });
+
+ it('drops a connection that keeps breaking its limits', async () => {
+ const { host, net, client } = setup({ limits: { messagesPerSecond: 1, burst: 1 }, maxViolationsPerMinute: 3 });
+ host.handle('noop', () => null);
+ const s = track(client('ivy'));
+ await s.start();
+ for (let i = 0; i < 30; i++) s.send('noop', i);
+ await vi.waitFor(() => expect(net.serverCloses).toContain(SessionCloseCode.abuse));
+ });
+
+ it('broadcast reaches every player that passes the filter', async () => {
+ const { host, client } = setup();
+ const a = track(client('a1'));
+ const b = track(client('b1'));
+ const got: string[] = [];
+ a.on('n', () => got.push('a1'));
+ b.on('n', () => got.push('b1'));
+ await a.start();
+ await b.start();
+ expect(host.broadcast('n', 1, (ctx) => ctx.playerId === 'b1')).toBe(1);
+ await vi.waitFor(() => expect(got).toEqual(['b1']));
+ });
+});
diff --git a/tools/lib/sdkProgram.mjs b/tools/lib/sdkProgram.mjs
index 0ec4d11d0..05bc407c5 100644
--- a/tools/lib/sdkProgram.mjs
+++ b/tools/lib/sdkProgram.mjs
@@ -73,6 +73,7 @@ export const ENTRIES = {
'debug-channel': 'src/debug-channel/index.ts',
'ai': 'src/ai/index.ts',
'replication': 'src/net/replication/index.ts',
+ 'session': 'src/net/session/index.ts',
'gameplay': 'src/gameplay/index.ts',
'wasm': 'src/wasm.ts',
'wechat': 'src/index.wechat.ts',
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index d465812a4..0d8344c64 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -3014,6 +3014,8 @@ export const NOTED = {
{"note":"Sharpen on WebGL2."},
'feat(math): a seeded random generator that gives the same numbers on every host':
{"note":"A random generator that gives the same numbers on every host."},
+ 'feat(net): a session layer for online games that do not share a tick':
+ {"note":"A session layer for online games that do not share a tick."},
"perf(sdk): a blank mini-game package no longer carries terrain and water":
{"note":"A blank mini-game package no longer carries terrain and water."},
};