From 756da4894393d1b2ba761263dd715276f5a01a02 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 21:32:05 +0200 Subject: [PATCH] cultnet-ts: a Connect from another endpoint replaces the peer; a flush is bound to its session; a busy operation session is not idle A server-mode transport treated a Connect from a new endpoint as a repeated Connect once the session was connected: the new client got an Ack and never an Accept, and the old session never ended. Only a Connect from the accepted endpoint repeats; another endpoint resets the session and gets its Accept. A flush recorded nothing about the session it started in, so a disconnect listener that reconnected cleared the end reason before the 5 ms poll saw it. Sessions now carry a generation; a flush fails if its generation ended. The operation service's idle sweep deleted a session whose handler was still running, losing the response. A session with a handler running, or one that finished a handler within the idle window, is not idle. Co-Authored-By: Claude Opus 5.5 --- packages/cultnet-ts/src/operation-service.ts | 16 ++- packages/cultnet-ts/src/rudp.ts | 40 +++++-- packages/cultnet-ts/test/cultnet.test.ts | 119 +++++++++++++++++++ 3 files changed, 162 insertions(+), 13 deletions(-) diff --git a/packages/cultnet-ts/src/operation-service.ts b/packages/cultnet-ts/src/operation-service.ts index 433c762d..606cd418 100644 --- a/packages/cultnet-ts/src/operation-service.ts +++ b/packages/cultnet-ts/src/operation-service.ts @@ -51,6 +51,10 @@ export interface CultNetOperationClientOptions { interface RemoteSession { session: CultNetRudpSession; remote: RemoteInfo; + /** Handlers running for this session; a session serving a request is not idle. */ + handling: number; + /** When the last handler finished: the response still needs its acknowledgement. */ + lastHandledAtMs: number; } export async function startCultNetOperationServer( @@ -82,6 +86,7 @@ export async function startCultNetOperationServer( for (const [key, peer] of sessions) { // An abandoned client must not hold a slot forever, or the cap locks // every new client out. + if (peer.handling > 0 || now - peer.lastHandledAtMs < idleTimeoutMs) continue; if (peer.session.checkTimeout(now, idleTimeoutMs)) sessions.delete(key); } for (const peer of sessions.values()) { @@ -162,7 +167,7 @@ async function handleServerDatagram( if (packet.packetType === "connect") { if (!peer) { if (sessions.size >= MAX_OPERATION_SESSIONS) return false; - peer = { session: new CultNetRudpSession({ connectionId, resendDelayMs: 25 }), remote }; + peer = { session: new CultNetRudpSession({ connectionId, resendDelayMs: 25 }), remote, handling: 0, lastHandledAtMs: 0 }; sessions.set(key, peer); } // A Connect from an admitted peer repeats: the session answers with the @@ -189,7 +194,14 @@ async function handleServerDatagram( try { const message = parseCultNetMessage(decode(frame.payload)); if (message.schemaVersion !== "cultnet.operation_request.v0") continue; - const response = await options.handler(message); + peer.handling += 1; + let response: CultNetOperationResponseMessage; + try { + response = await options.handler(message); + } finally { + peer.handling -= 1; + peer.lastHandledAtMs = Date.now(); + } const payload = encode(encodeCultNetMessageForWire(response, "cultnet.schema.v0")); for (const responsePacket of peer.session.sendMany("schema", payload, { reliable: true, diff --git a/packages/cultnet-ts/src/rudp.ts b/packages/cultnet-ts/src/rudp.ts index 1dc4f032..7e99afe9 100644 --- a/packages/cultnet-ts/src/rudp.ts +++ b/packages/cultnet-ts/src/rudp.ts @@ -824,7 +824,12 @@ export class CultNetRudpSocketTransportConnection extends EventEmitter implement #remoteHost: string | undefined; #remotePort: number | undefined; #closed = false; - /** Why the session ended, while it is over; cleared by the next Connect. */ + // A flush belongs to the session it started in. Each session start advances + // the generation; each session end records the generation it ended and why. + // A reconnect from a disconnect listener starts a new generation but cannot + // un-end the old one. + #generation = 0; + #endedGeneration = -1; #endedReason: Uint8Array | undefined; readonly #stats: CultNetTransportStats = { bytesReceived: 0, @@ -887,7 +892,7 @@ export class CultNetRudpSocketTransportConnection extends EventEmitter implement if (this.#mode !== "client") { throw new Error("Only a client RUDP socket transport can initiate connect."); } - this.#endedReason = undefined; + this.#generation += 1; this.#sendPacket(this.#session.createConnect(Date.now(), payload)); } @@ -905,12 +910,13 @@ export class CultNetRudpSocketTransportConnection extends EventEmitter implement async flush(timeoutMs = 30_000): Promise { const deadline = Date.now() + Math.max(0, timeoutMs); + const generation = this.#generation; for (;;) { // An ended session forgot its unacknowledged writes; reporting them - // flushed would be a lie. - if (this.#endedReason !== undefined) { + // flushed would be a lie, even if a new session has since begun. + if (this.#endedGeneration >= generation) { throw new Error( - `RUDP session ended before its reliable writes were acknowledged: ${Buffer.from(this.#endedReason).toString("utf8")}`, + `RUDP session ended before its reliable writes were acknowledged: ${Buffer.from(this.#endedReason ?? new Uint8Array()).toString("utf8")}`, ); } if (this.#session.outstandingReliablePacketCount === 0) { @@ -928,6 +934,11 @@ export class CultNetRudpSocketTransportConnection extends EventEmitter implement } } + #endGeneration(reason: Uint8Array): void { + this.#endedGeneration = this.#generation; + this.#endedReason = reason; + } + ping(payload = new Uint8Array()): void { this.#sendPacket(this.#session.createPing(payload)); } @@ -961,7 +972,7 @@ export class CultNetRudpSocketTransportConnection extends EventEmitter implement // The goodbye is built after the reset, or its ack field would acknowledge // the very frame the session refused. this.#session.resetPeerState(); - this.#endedReason = reason; + this.#endGeneration(reason); try { this.#sendPacket(this.#session.createDisconnect(reason)); } catch { @@ -996,6 +1007,7 @@ export class CultNetRudpSocketTransportConnection extends EventEmitter implement return; } + let movedEndpoint = false; if (!this.#remoteHost || this.#remotePort === undefined) { if (this.#mode === "server" && packet.packetType !== "connect") { this.#stats.packetsDropped += 1; @@ -1005,6 +1017,7 @@ export class CultNetRudpSocketTransportConnection extends EventEmitter implement this.#remotePort = remote.port; } else if (remote.address !== this.#remoteHost || remote.port !== this.#remotePort) { if (this.#mode === "server" && packet.packetType === "connect") { + movedEndpoint = true; this.#remoteHost = remote.address; this.#remotePort = remote.port; } else { @@ -1014,15 +1027,20 @@ export class CultNetRudpSocketTransportConnection extends EventEmitter implement } if (this.#mode === "server" && packet.packetType === "connect") { - // A repeated Connect from the accepted peer resets nothing: the session - // answers it with the Accept already owed. - if (!this.#session.connected) { + // Only a Connect from the endpoint already accepted repeats, and the + // session answers it with the Accept owed. A Connect from another + // endpoint replaces the peer: the old session's writes die with it. + const repeated = this.#session.connected && !movedEndpoint; + if (!repeated) { + if (this.#session.connected) { + this.#endGeneration(Buffer.from("replaced by a new Connect", "utf8")); + } this.#session.resetPeerState(); } let accept: CultNetRudpPacket; try { accept = this.#session.acceptConnect(packet, Date.now()); - this.#endedReason = undefined; + if (!repeated) this.#generation += 1; } catch { this.#stats.packetsDropped += 1; return; @@ -1060,7 +1078,7 @@ export class CultNetRudpSocketTransportConnection extends EventEmitter implement } satisfies CultNetTransportFrame); } if (result.disconnected) { - this.#endedReason = result.disconnectReason ?? new Uint8Array(); + this.#endGeneration(result.disconnectReason ?? new Uint8Array()); this.emit("disconnect", { reason: result.disconnectReason ?? new Uint8Array() }); this.emit("close"); return; diff --git a/packages/cultnet-ts/test/cultnet.test.ts b/packages/cultnet-ts/test/cultnet.test.ts index cf4af8c0..bdaa9509 100644 --- a/packages/cultnet-ts/test/cultnet.test.ts +++ b/packages/cultnet-ts/test/cultnet.test.ts @@ -2220,3 +2220,122 @@ test("operation service frees the slots of abandoned sessions once they idle out await server.close(); } }); + +test("server-mode transport replaces its peer when a Connect arrives from another endpoint", async () => { + const serverSocket = await bindUdpSocket(); + const socketA = await bindUdpSocket(); + const socketB = await bindUdpSocket(); + const connectionId = 0x10203058; + const server = new CultNetRudpSocketTransportConnection({ + runtimeId: "rudp-server", + socket: serverSocket, + mode: "server", + connectionId, + resendPollMs: 1000, + }); + const receivedByB: CultNetRudpPacket[] = []; + socketB.on("message", (wire) => receivedByB.push(decodeRudpPacket(wire))); + const frames: string[] = []; + server.on("frame", (frame: { payload: Uint8Array }) => frames.push(Buffer.from(frame.payload).toString("utf8"))); + const peerA = new CultNetRudpSession({ connectionId }); + const peerB = new CultNetRudpSession({ connectionId }); + const send = (socket: Socket, packet: CultNetRudpPacket) => + socket.send(encodeRudpPacket(packet), udpPort(serverSocket), "127.0.0.1"); + try { + send(socketA, peerA.createConnect(0)); + await waitFor(() => server.connected, "A accepted"); + send(socketB, peerB.createConnect(0)); + await waitFor(() => receivedByB.some((p) => p.packetType === "accept"), "B's Accept"); + peerB.receive(receivedByB.find((p) => p.packetType === "accept")!, 0); + + // B owns the session; A's traffic is a stranger's and is dropped. + const [fromA] = peerA.sendMany("schema", Buffer.from("from-A"), { reliable: true, ordered: true, nowMs: 0 }); + send(socketA, fromA!); + const [fromB] = peerB.sendMany("schema", Buffer.from("from-B"), { reliable: true, ordered: true, nowMs: 0 }); + send(socketB, fromB!); + await waitFor(() => frames.length > 0, "B's frame"); + await new Promise((resolve) => setTimeout(resolve, 30)); + assert.deepEqual(frames, ["from-B"]); + assert.equal(server.stats.packetsDropped, 1); + } finally { + socketA.close(); + socketB.close(); + assert.doesNotThrow(() => server.close()); + } +}); + +test("operation service does not idle out a session while its handler is running", async () => { + const respond = (request: CultNetOperationRequestMessage): CultNetOperationResponseMessage => ({ + schemaVersion: "cultnet.operation_response.v0", + messageId: request.messageId, + serviceId: request.serviceId, + operation: request.operation, + status: "ok", + payloadSchema: "gamecult.eve.plugin_abi.response.v1", + payloadEncoding: "messagepack-base64", + payload: request.payload, + diagnostics: [], + sourceRuntimeId: "sai-sidecar", + }); + const server = await startCultNetOperationServer({ + runtimeId: "sai-sidecar", + sessionIdleTimeoutMs: 200, + handler: async (request) => { + await new Promise((resolve) => setTimeout(resolve, 700)); + return respond(request); + }, + }); + try { + const response = await invokeCultNetOperation(server.endpoint, { + schemaVersion: "cultnet.operation_request.v0", + messageId: "slow", + serviceId: "sai.vn", + operation: "describe", + payloadSchema: "gamecult.eve.plugin_abi.request.v1", + payloadEncoding: "messagepack-base64", + payload: "gaZzY2hlbWE=", + }, { runtimeId: "eve-test", timeoutMs: 3000 }); + assert.equal(response.messageId, "slow"); + } finally { + await server.close(); + } +}); + +test("a flush is bound to the session it started in, even when a disconnect listener reconnects", async () => { + const peerSocket = await bindUdpSocket(); + const clientSocket = await bindUdpSocket(); + const connectionId = 0x10203059; + const client = new CultNetRudpSocketTransportConnection({ + runtimeId: "rudp-client", + socket: clientSocket, + mode: "client", + remoteHost: "127.0.0.1", + remotePort: udpPort(peerSocket), + connectionId, + resendDelayMs: 1000, + resendPollMs: 1000, + }); + const received: CultNetRudpPacket[] = []; + let clientPort = 0; + peerSocket.on("message", (wire, remote) => { + clientPort = remote.port; + received.push(decodeRudpPacket(wire)); + }); + const peer = new CultNetRudpSession({ connectionId }); + try { + client.connect(); + await waitFor(() => received.some((p) => p.packetType === "connect"), "the Connect"); + const accept = peer.acceptConnect(received.find((p) => p.packetType === "connect")!, 0); + peerSocket.send(encodeRudpPacket(accept), clientPort, "127.0.0.1"); + await waitFor(() => client.connected, "the client connected"); + client.send("schema", Buffer.from("never acknowledged")); + client.on("disconnect", () => client.connect()); + const flushed = client.flush(500); + const outcome = assert.rejects(flushed, /ended before its reliable writes were acknowledged/); + peerSocket.send(encodeRudpPacket(peer.createDisconnect(Buffer.from("bye"))), clientPort, "127.0.0.1"); + await outcome; + } finally { + peerSocket.close(); + client.close(); + } +});