From d8143cc0676aa7a8bdcf162f2dc4fcd9f6070bc5 Mon Sep 17 00:00:00 2001 From: Damien Arrachequesne Date: Mon, 6 Feb 2023 18:00:14 +0100 Subject: [PATCH] refactor: do not persist session if connection state recovery if disabled This is a follow-up commit of [1]. Without it, adapter.persistSession() would be called even if the connection state recovery feature was disabled. [1]: https://github.com/socketio/socket.io/commit/54d5ee05a684371191e207b8089f09fc24eb5107 --- lib/socket.ts | 5 ++++- test/connection-state-recovery.ts | 29 +++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/lib/socket.ts b/lib/socket.ts index b5a6e60894..416ca8ab1e 100644 --- a/lib/socket.ts +++ b/lib/socket.ts @@ -742,7 +742,10 @@ export class Socket< debug("closing socket - reason %s", reason); this.emitReserved("disconnecting", reason, description); - if (RECOVERABLE_DISCONNECT_REASONS.has(reason)) { + if ( + this.server._opts.connectionStateRecovery && + RECOVERABLE_DISCONNECT_REASONS.has(reason) + ) { debug("connection state recovery is enabled for sid %s", this.id); this.adapter.persistSession({ sid: this.id, diff --git a/test/connection-state-recovery.ts b/test/connection-state-recovery.ts index c1058c3368..9d20579953 100644 --- a/test/connection-state-recovery.ts +++ b/test/connection-state-recovery.ts @@ -2,6 +2,7 @@ import { Server, Socket } from ".."; import expect from "expect.js"; import { waitFor, eioHandshake, eioPush, eioPoll } from "./support/util"; import { createServer, Server as HttpServer } from "http"; +import { Adapter } from "socket.io-adapter"; async function init(httpServer: HttpServer, io: Server) { // Engine.IO handshake @@ -215,4 +216,32 @@ describe("connection state recovery", () => { io.close(); }); + + it("should not call adapter#persistSession or adapter#restoreSession if disabled", async () => { + const httpServer = createServer().listen(0); + + class DummyAdapter extends Adapter { + override persistSession(session) { + expect.fail(); + } + + override restoreSession(pid, offset) { + expect.fail(); + return Promise.reject("should not happen"); + } + } + + const io = new Server(httpServer, { + adapter: DummyAdapter, + }); + + // Engine.IO handshake + const sid = await eioHandshake(httpServer); + + await eioPush(httpServer, sid, '40{"pid":"foo","offset":"bar"}'); + await eioPoll(httpServer, sid); + await eioPush(httpServer, sid, "1"); + + io.close(); + }); });