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 can be told to redial now and says why its link ended

yhh0944507f422f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ef981e451..c9d15fe11 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@ published separately; it ships inside the editor.
### Added
+- **A session can be told to redial now, and says why its link ended.** `ClientSession.retryNow()` dials at once instead of waiting out the backoff, for a player who pressed "try again"; it does nothing when the session is ready, already dialling, or closed. `lastClose` is the WebSocket close code of the last link that ended (4003, `SessionCloseCode.unavailable`, is the server saying it is full or going away) until the next one is ready, and `attempts` counts dials since the session was last ready, so a screen can tell "reconnecting" from "the server is full" and say which attempt this is.
- **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.
diff --git a/sdk/etc/session.api.md b/sdk/etc/session.api.md
index aedd4a396..ca812ea8f 100644
--- a/sdk/etc/session.api.md
+++ b/sdk/etc/session.api.md
@@ -17,10 +17,13 @@ transport: NetTransport
## ClientSession — class @experimental
```
+attempts: number
close: () => void
+lastClose: { code: number; } | null
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>
+retryNow: () => void
send: (type: string, payload: unknown) => void
serverNow: () => number
start: () => Promise<SessionWelcome>
diff --git a/sdk/src/net/session/ClientSession.ts b/sdk/src/net/session/ClientSession.ts
index a17ded107..2d16b104b 100644
--- a/sdk/src/net/session/ClientSession.ts
+++ b/sdk/src/net/session/ClientSession.ts
@@ -75,6 +75,7 @@ export class ClientSession {
private channel_: NetChannel | null = null;
private attached_ = new Set<string>();
private attempt_ = 0;
+ private lastClose_: { code: number } | null = null;
private redialTimer_: ReturnType<typeof setTimeout> | null = null;
private offsetMs_ = 0;
private welcome_: SessionWelcome | null = null;
@@ -97,6 +98,19 @@ export class ClientSession {
return this.welcome_;
}
+ /**
+ * How the last link ended, until the next one is ready: the WebSocket close code (4003 is the
+ * server saying it is full or going away). Null while connected, or when no link has dropped yet.
+ */
+ get lastClose(): { code: number } | null {
+ return this.lastClose_;
+ }
+
+ /** Dial attempts since the last time the session was ready; 0 when ready. */
+ get attempts(): number {
+ return this.attempt_;
+ }
+
/** 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_;
@@ -162,6 +176,17 @@ export class ClientSession {
}
}
+ /**
+ * Redial now instead of waiting out the backoff, for a player who pressed "try again". Does nothing
+ * while a dial is already under way, when the session is ready, or once it has closed for good.
+ */
+ retryNow(): void {
+ if (this.redialTimer_ === null) return;
+ clearTimeout(this.redialTimer_);
+ this.redialTimer_ = null;
+ this.dial_();
+ }
+
/** Leave for good: no redial, requests in flight fail. */
close(): void {
if (this.state_ === 'closed') return;
@@ -237,6 +262,7 @@ export class ClientSession {
this.offsetMs_ = res.serverTimeMs + (received - sent) / 2 - received;
this.welcome_ = { playerId: res.playerId, data: res.data };
this.attempt_ = 0;
+ this.lastClose_ = null;
this.setState_('ready');
for (const w of this.readyWaiters_.splice(0)) w.resolve();
this.firstReady_?.resolve(this.welcome_);
@@ -253,6 +279,7 @@ export class ClientSession {
this.channel_ = null;
this.socket_ = null;
if (this.state_ === 'closed') return;
+ this.lastClose_ = { code };
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');
diff --git a/sdk/tests/net-session.test.ts b/sdk/tests/net-session.test.ts
index e202bf988..526beabd9 100644
--- a/sdk/tests/net-session.test.ts
+++ b/sdk/tests/net-session.test.ts
@@ -256,3 +256,44 @@ describe('SessionHost + ClientSession', () => {
await vi.waitFor(() => expect(got).toEqual(['b1']));
});
});
+
+describe('ClientSession: retry and the reason a link ended', () => {
+ it('retryNow dials at once instead of waiting out the backoff, and does nothing when there is nothing to wait for', async () => {
+ const { host, net, client } = setup();
+ host.handle('ping', () => 'pong');
+ const s = track(client('rita', { backoff: { initialMs: 60_000, maxMs: 60_000, jitter: 0 } }));
+ await s.start();
+ s.retryNow(); // ready: nothing to do
+ expect(s.state).toBe('ready');
+ net.down = true;
+ net.cut();
+ await vi.waitFor(() => expect(s.state).toBe('reconnecting'));
+ const dials = net.dials;
+ net.down = false;
+ s.retryNow();
+ await vi.waitFor(() => expect(s.state).toBe('ready'));
+ expect(net.dials).toBe(dials + 1);
+ expect(await s.request('ping', {})).toBe('pong');
+ s.close();
+ s.retryNow(); // closed: still nothing
+ expect(s.state).toBe('closed');
+ });
+
+ it('says how the last link ended, and forgets it once connected again', async () => {
+ const { net, client } = setup({ maxSessions: 1 });
+ const holder = track(client('hal'));
+ await holder.start();
+ expect(holder.lastClose).toBeNull();
+ expect(holder.attempts).toBe(0);
+
+ const full = track(client('fay'));
+ void full.start().catch(() => {});
+ await vi.waitFor(() => expect(full.lastClose?.code).toBe(SessionCloseCode.unavailable));
+ expect(full.attempts).toBeGreaterThan(0);
+
+ holder.close();
+ await vi.waitFor(() => expect(full.state).toBe('ready'));
+ expect(full.lastClose).toBeNull();
+ void net;
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index d69b0c8bc..7bd57e6c4 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -3016,6 +3016,8 @@ export const NOTED = {
{"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."},
+ 'feat(net): a session can be told to redial now and says why its link ended':
+ {"note":"A session can be told to redial now, and says why its link ended."},
"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."},
"perf(ecs): one stable sort for every component type, 239KB off the engine wasm":