Skip to content

Commit

Permalink
refactor: do not reuse the same packet ID for retries
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
darrachequesne committed Feb 20, 2023
1 parent 46213a6 commit 121fd7c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
17 changes: 12 additions & 5 deletions lib/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,12 @@ export interface SocketOptions {
}

type QueuedPacket = {
/**
* Only used for debugging purposes. To allow deduplication on the server side, one should include a unique offset in
* the packet, for example with crypto.randomUUID().
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID
*/
id: number;
args: unknown[];
flags: Flags;
Expand Down Expand Up @@ -225,6 +231,11 @@ export class Socket<
* @private
*/
private _queue: Array<QueuedPacket> = [];
/**
* A sequence to generate the ID of the {@link QueuedPacket}.
* @private
*/
private _queueSeq: number = 0;

private readonly nsp: string;
private readonly _opts: SocketOptions;
Expand Down Expand Up @@ -501,7 +512,7 @@ export class Socket<
}

const packet = {
id: this.ids++,
id: this._queueSeq++,
tryCount: 0,
pending: false,
args,
Expand Down Expand Up @@ -563,12 +574,8 @@ export class Socket<
packet.pending = true;
packet.tryCount++;
debug("sending packet [%d] (try n°%d)", packet.id, packet.tryCount);
const currentId = this.ids;
this.ids = packet.id; // the same id is reused for consecutive retries, in order to allow deduplication on the server side
this.flags = packet.flags;

this.emit.apply(this, packet.args);
this.ids = currentId; // restore offset
}

/**
Expand Down
6 changes: 3 additions & 3 deletions test/retry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,9 @@ describe("retry", () => {
const expected = [
"0",
'20["ack"]',
'20["ack"]',
'20["ack"]',
'20["ack"]',
'21["ack"]',
'22["ack"]',
'23["ack"]',
"1",
];

Expand Down

0 comments on commit 121fd7c

Please sign in to comment.