Skip to content

Commit 121fd7c

Browse files
refactor: do not reuse the same packet ID for retries
The packet ID cannot be used for deduplication, because it's only unique for the given session. If you reconnect on another server and try to resend a packet, then the server won't be able to know whether the packet has already been processed or not.
1 parent 46213a6 commit 121fd7c

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
lines changed

lib/socket.ts

+12-5
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,12 @@ export interface SocketOptions {
7070
}
7171

7272
type QueuedPacket = {
73+
/**
74+
* Only used for debugging purposes. To allow deduplication on the server side, one should include a unique offset in
75+
* the packet, for example with crypto.randomUUID().
76+
*
77+
* @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID
78+
*/
7379
id: number;
7480
args: unknown[];
7581
flags: Flags;
@@ -225,6 +231,11 @@ export class Socket<
225231
* @private
226232
*/
227233
private _queue: Array<QueuedPacket> = [];
234+
/**
235+
* A sequence to generate the ID of the {@link QueuedPacket}.
236+
* @private
237+
*/
238+
private _queueSeq: number = 0;
228239

229240
private readonly nsp: string;
230241
private readonly _opts: SocketOptions;
@@ -501,7 +512,7 @@ export class Socket<
501512
}
502513

503514
const packet = {
504-
id: this.ids++,
515+
id: this._queueSeq++,
505516
tryCount: 0,
506517
pending: false,
507518
args,
@@ -563,12 +574,8 @@ export class Socket<
563574
packet.pending = true;
564575
packet.tryCount++;
565576
debug("sending packet [%d] (try n°%d)", packet.id, packet.tryCount);
566-
const currentId = this.ids;
567-
this.ids = packet.id; // the same id is reused for consecutive retries, in order to allow deduplication on the server side
568577
this.flags = packet.flags;
569-
570578
this.emit.apply(this, packet.args);
571-
this.ids = currentId; // restore offset
572579
}
573580

574581
/**

test/retry.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -68,9 +68,9 @@ describe("retry", () => {
6868
const expected = [
6969
"0",
7070
'20["ack"]',
71-
'20["ack"]',
72-
'20["ack"]',
73-
'20["ack"]',
71+
'21["ack"]',
72+
'22["ack"]',
73+
'23["ack"]',
7474
"1",
7575
];
7676

0 commit comments

Comments
 (0)