Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions packages/socket.io-adapter/lib/in-memory-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -411,13 +411,29 @@ export class SessionAwareAdapter extends Adapter {

private sessions: Map<PrivateSessionId, SessionWithTimestamp> = new Map();
private packets: PersistedPacket[] = [];
private cleanupTimer: NodeJS.Timeout | undefined;

constructor(readonly nsp: any) {
super(nsp);
this.maxDisconnectionDuration =
nsp.server.opts.connectionStateRecovery.maxDisconnectionDuration;
}

override close() {
clearInterval(this.cleanupTimer);
this.cleanupTimer = undefined;
}

const timer = setInterval(() => {
/**
* The timer only runs while there is something to clean up, so that it does not retain the adapter (and its
* namespace) once they are not used anymore. It is started again on demand, as the server can be restarted after
* having been closed.
*/
private startCleanupTimer() {
if (this.cleanupTimer) {
return;
}
this.cleanupTimer = setInterval(() => {
const threshold = Date.now() - this.maxDisconnectionDuration;
this.sessions.forEach((session, sessionId) => {
const hasExpired = session.disconnectedAt < threshold;
Expand All @@ -432,14 +448,19 @@ export class SessionAwareAdapter extends Adapter {
break;
}
}
if (this.sessions.size === 0 && this.packets.length === 0) {
clearInterval(this.cleanupTimer);
this.cleanupTimer = undefined;
}
}, 60 * 1000);
// prevents the timer from keeping the process alive
timer.unref();
this.cleanupTimer.unref();
}

override persistSession(session: SessionToPersist) {
(session as SessionWithTimestamp).disconnectedAt = Date.now();
this.sessions.set(session.pid, session as SessionWithTimestamp);
this.startCleanupTimer();
}

override restoreSession(
Expand Down Expand Up @@ -493,6 +514,7 @@ export class SessionAwareAdapter extends Adapter {
data: packet.data,
emittedAt: Date.now(),
});
this.startCleanupTimer();
}
super.broadcast(packet, opts);
}
Expand Down
88 changes: 88 additions & 0 deletions packages/socket.io-adapter/test/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Adapter, SessionAwareAdapter } from "../lib";
import expect = require("expect.js");
import { install, type InstalledClock } from "@sinonjs/fake-timers";

describe("socket.io-adapter", () => {
it("should add/remove sockets", () => {
Expand Down Expand Up @@ -551,5 +552,92 @@ describe("socket.io-adapter", () => {

expect(session).to.be(null);
});

describe("cleanup timer", () => {
let clock: InstalledClock;
let adapter: SessionAwareAdapter;

const persistSession = (pid: string) =>
adapter.persistSession({ sid: "abc", pid, data: "ghi", rooms: ["r1"] });

const broadcast = () =>
adapter.broadcast(
{ nsp: "/", type: 2, data: ["hello"] },
{ rooms: new Set(), except: new Set() },
);

const storedItems = () => [
adapter["sessions"].size,
adapter["packets"].length,
];

beforeEach(() => {
clock = install();
adapter = new SessionAwareAdapter({
server: {
encoder: {
encode(packet) {
return packet;
},
},
opts: {
connectionStateRecovery: {
maxDisconnectionDuration: 5000,
},
},
},
});
});

afterEach(() => clock.uninstall());

it("should only run while there is something to clean up", () => {
expect(clock.countTimers()).to.be(0);

persistSession("def");
broadcast();
expect(clock.countTimers()).to.be(1);

clock.tick(60_000);
expect(storedItems()).to.eql([0, 0]);
expect(clock.countTimers()).to.be(0);
});

it("should keep running until everything has expired", () => {
persistSession("def");
clock.tick(58_000);
broadcast();

clock.tick(2_000);
expect(storedItems()).to.eql([0, 1]);
expect(clock.countTimers()).to.be(1);

clock.tick(60_000);
expect(storedItems()).to.eql([0, 0]);
expect(clock.countTimers()).to.be(0);
});

it("should be stopped when the adapter is closed", () => {
persistSession("def");
broadcast();

adapter.close();
expect(clock.countTimers()).to.be(0);
});

it("should be started again when the adapter is reused after having been closed", () => {
persistSession("def");
broadcast();
adapter.close();

persistSession("jkl");
expect(storedItems()).to.eql([2, 1]);
expect(clock.countTimers()).to.be(1);

clock.tick(60_000);
expect(storedItems()).to.eql([0, 0]);
expect(clock.countTimers()).to.be(0);
});
});
});
});