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
39 changes: 39 additions & 0 deletions packages/engine.io-client/lib/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -849,6 +849,45 @@ export class Socket extends Emitter<
}
}

/**
* Removes buffered packets sharing the given options object if none of them
* have already been handed to the transport.
*
* @param options - the options object shared by the packets to remove
* @private
*/
/* private */ _removeFromWriteBuffer(options: WriteOptions) {
if (!options) {
return;
}

const prevBufferLen = Math.min(
this._prevBufferLen,
this.writeBuffer.length,
);
for (let i = 0; i < prevBufferLen; i++) {
if (this.writeBuffer[i].options === options) {
return;
}
}

let removed = false;
for (let i = this.writeBuffer.length - 1; i >= prevBufferLen; i--) {
if (this.writeBuffer[i].options === options) {
this.writeBuffer.splice(i, 1);
removed = true;
}
}

if (
removed &&
0 === this.writeBuffer.length &&
"closing" === this.readyState
) {
this.emitReserved("drain");
}
}

/**
* Flush write buffers.
*
Expand Down
74 changes: 74 additions & 0 deletions packages/engine.io-client/test/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,80 @@ describe("Socket", function () {
});
});

describe("_removeFromWriteBuffer", () => {
it("should remove all matching packets that have not been flushed", () => {
const socket = Object.create(Socket.prototype);
const targetOptions = { compress: true };
const inFlightPacket = { type: "message", options: { compress: true } };
const otherPacket = { type: "message", options: { compress: true } };
socket.writeBuffer = [
inFlightPacket,
{ type: "message", options: targetOptions },
otherPacket,
{ type: "message", options: targetOptions },
];
socket._prevBufferLen = 1;
socket.readyState = "open";

socket._removeFromWriteBuffer(targetOptions);

expect(socket.writeBuffer).to.eql([inFlightPacket, otherPacket]);
});

it("should preserve all matching packets when one is already in flight", () => {
const socket = Object.create(Socket.prototype);
const targetOptions = { compress: true };
const packets = [
{ type: "message", options: targetOptions },
{ type: "message", options: targetOptions },
];
socket.writeBuffer = packets.slice();
socket._prevBufferLen = 1;
socket.readyState = "open";

socket._removeFromWriteBuffer(targetOptions);

expect(socket.writeBuffer).to.eql(packets);
});

it("should ignore falsy options", () => {
const socket = Object.create(Socket.prototype);
const packets = [{ type: "message" }, { type: "message", options: null }];
socket.writeBuffer = packets.slice();
socket._prevBufferLen = 0;
socket.readyState = "open";

socket._removeFromWriteBuffer(undefined);
socket._removeFromWriteBuffer(null);

expect(socket.writeBuffer).to.eql(packets);
});

it("should emit drain only when emptying writeBuffer while closing", () => {
const socket = Object.create(Socket.prototype);
const openOptions = { compress: true };
let drainCount = 0;
socket.on("drain", () => {
drainCount++;
});

socket.writeBuffer = [{ type: "message", options: openOptions }];
socket._prevBufferLen = 0;
socket.readyState = "open";
socket._removeFromWriteBuffer(openOptions);
expect(socket.writeBuffer).to.eql([]);
expect(drainCount).to.eql(0);

const closingOptions = { compress: true };
socket.writeBuffer = [{ type: "message", options: closingOptions }];
socket._prevBufferLen = 0;
socket.readyState = "closing";
socket._removeFromWriteBuffer(closingOptions);
expect(socket.writeBuffer).to.eql([]);
expect(drainCount).to.eql(1);
});
});

it("should not mutate the caller's transports option", () => {
const optsWithUri = { transports: ["websocket", "polling"] };
const optsWithoutUri = { transports: ["polling"] };
Expand Down
12 changes: 12 additions & 0 deletions packages/socket.io-client/lib/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,18 @@ export class Manager<
}
}

/**
* Removes a packet that has not yet been handed to the underlying transport.
*
* @param packet
* @private
*/
_removePacketFromBuffer(
packet: Partial<Packet & { query: string; options: any }>,
): void {
this.engine?._removeFromWriteBuffer?.(packet.options);
}

/**
* Clean up transport subscriptions and packet buffer.
*
Expand Down
14 changes: 12 additions & 2 deletions packages/socket.io-client/lib/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ export class Socket<
debug("emitting packet with ack id %d", id);

const ack = args.pop() as (...args: any[]) => void;
this._registerAckCallback(id, ack);
this._registerAckCallback(id, ack, packet);
packet.id = id;
}

Expand All @@ -465,7 +465,11 @@ export class Socket<
/**
* @private
*/
private _registerAckCallback(id: number, ack: (...args: any[]) => void) {
private _registerAckCallback(
id: number,
ack: (...args: any[]) => void,
packet: Partial<Packet & { options: any }>,
) {
const timeout = this.flags.timeout ?? this._opts.ackTimeout;
if (timeout === undefined) {
this.acks[id] = ack;
Expand All @@ -475,12 +479,18 @@ export class Socket<
// @ts-ignore
const timer = this.io.setTimeoutFn(() => {
delete this.acks[id];
let removedFromSendBuffer = false;
for (let i = 0; i < this.sendBuffer.length; i++) {
if (this.sendBuffer[i].id === id) {
debug("removing packet with ack id %d from the buffer", id);
this.sendBuffer.splice(i, 1);
removedFromSendBuffer = true;
break;
}
}
if (!removedFromSendBuffer) {
this.io._removePacketFromBuffer(packet);
}
debug("event with ack id %d has timed out after %d ms", id, timeout);
ack.call(this, new Error("operation has timed out"));
}, timeout);
Expand Down
93 changes: 93 additions & 0 deletions packages/socket.io-client/test/node.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
const path = require("node:path");
const http = require("node:http");
const { execFile } = require("node:child_process");
import expect = require("expect.js");
import { Server } from "socket.io";
import { io } from "..";
import { wrap } from "./support/util";

describe("autoUnref option", function () {
before(function () {
Expand Down Expand Up @@ -51,3 +56,91 @@ describe("autoUnref option", function () {
}, 100);
});
});

describe("buffered timed-out events", function () {
before(function () {
if (process.env.WDIO_WORKER_ID !== undefined) {
return this.skip();
}
});

it("should not send a timed-out event queued behind an in-flight polling request", () => {
return wrap((done) => {
const httpServer = http.createServer();
const ioServer = new Server(httpServer);
const received: string[] = [];
let delayNextPost = false;

const existingListeners = httpServer.listeners("request").slice();
httpServer.removeAllListeners("request");
httpServer.on("request", (req, res) => {
if (delayNextPost && req.method === "POST") {
delayNextPost = false;
setTimeout(() => {
for (const listener of existingListeners) {
listener.call(httpServer, req, res);
}
}, 150);
return;
}
for (const listener of existingListeners) {
listener.call(httpServer, req, res);
}
});

ioServer.on("connection", (serverSocket) => {
serverSocket.on("test", (msg, cb) => {
received.push(msg);
cb("done");
});
});

httpServer.listen(0, () => {
const address = httpServer.address();
const port = typeof address === "object" && address ? address.port : 0;

const client = io(`http://localhost:${port}`, {
forceNew: true,
transports: ["polling"],
upgrade: false,
});

let timedOutErr: Error | null = null;
let oneAck: string | null = null;

const finish = (err?: Error) => {
client.disconnect();
ioServer.close(() => done(err));
};

client.on("connect", () => {
// wait one tick so the initial polling handshake POST finishes
setTimeout(() => {
delayNextPost = true;

client.emit("test", "one", (res) => {
oneAck = res;
});

client.timeout(50).emit("test", "two", (err) => {
timedOutErr = err;
});

client.timeout(5000).emit("test", "three", (err, res) => {
try {
expect(err).to.be(null);
expect(res).to.be("done");
expect(oneAck).to.be("done");
expect(timedOutErr).to.be.an(Error);
expect(received).to.eql(["one", "three"]);
finish();
} catch (e) {
finish(e as Error);
}
});
}, 20);
});
});
});
});
});
Loading