diff --git a/packages/socket.io-client/lib/socket.ts b/packages/socket.io-client/lib/socket.ts index 13c0ed97c..bf656c8de 100644 --- a/packages/socket.io-client/lib/socket.ts +++ b/packages/socket.io-client/lib/socket.ts @@ -459,6 +459,17 @@ export class Socket< this.flags = {}; + if (discardPacket && packet.id !== undefined) { + // the server will never acknowledge a discarded packet + const ack = this.acks[packet.id]; + delete this.acks[packet.id]; + + // note: handlers that do not accept an error as first argument are ignored here + if (ack.withError) { + ack.call(this, new Error("packet has been discarded")); + } + } + return this; } diff --git a/packages/socket.io-client/test/socket.ts b/packages/socket.io-client/test/socket.ts index 0149ad64b..9af5b59c5 100644 --- a/packages/socket.io-client/test/socket.ts +++ b/packages/socket.io-client/test/socket.ts @@ -421,6 +421,48 @@ describe("socket", () => { }); }); + it("should not keep the ack handler of a discarded volatile packet (callback)", () => { + const socket = io(BASE_URL, { forceNew: true, autoConnect: false }); + + socket.volatile.emit("getId", () => {}); + + // @ts-ignore property 'acks' is private + expect(Object.keys(socket.acks).length).to.eql(0); + }); + + it("should ack with an error when a volatile packet is discarded (callback & timeout)", () => { + return wrap((done) => { + const socket = io(BASE_URL, { forceNew: true, autoConnect: false }); + + socket.volatile.timeout(10_000).emit("getId", (err) => { + expect(err).to.be.an(Error); + + // @ts-ignore property 'acks' is private + expect(Object.keys(socket.acks).length).to.eql(0); + + done(); + }); + }); + }); + + it("should reject when a volatile packet is discarded (promise)", () => { + return wrap(async (done) => { + const socket = io(BASE_URL, { forceNew: true, autoConnect: false }); + + try { + await socket.volatile.emitWithAck("getId"); + done(new Error("should not happen")); + } catch (e) { + expect(e).to.be.an(Error); + + // @ts-ignore property 'acks' is private + expect(Object.keys(socket.acks).length).to.eql(0); + + done(); + } + }); + }); + it("should send a volatile packet when the socket is connected and the pipe is ready", () => { return wrap((done) => { const socket = io(BASE_URL, { forceNew: true });