Skip to content

Commit

Permalink
fix(WebSocketShard): cancel initial heartbeat in destroy (#9244)
Browse files Browse the repository at this point in the history
* fix(WebSocketShard): cancel initial heartbeat in destroy

* refactor: use try/catch/finally

* chore: add debug log
  • Loading branch information
didinele authored Mar 18, 2023
1 parent 51edba7 commit 9842082
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion packages/ws/src/ws/WebSocketShard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ export class WebSocketShard extends AsyncEventEmitter<WebSocketShardEventsMap> {

private sendRateLimitState: SendRateLimitState = getInitialSendRateLimitState();

private initialHeartbeatTimeoutController: AbortController | null = null;

private heartbeatInterval: NodeJS.Timer | null = null;

private lastHeartbeatAt = -1;
Expand Down Expand Up @@ -203,6 +205,11 @@ export class WebSocketShard extends AsyncEventEmitter<WebSocketShardEventsMap> {
clearInterval(this.heartbeatInterval);
}

if (this.initialHeartbeatTimeoutController) {
this.initialHeartbeatTimeoutController.abort();
this.initialHeartbeatTimeoutController = null;
}

this.lastHeartbeatAt = -1;

// Clear session state if applicable
Expand Down Expand Up @@ -568,7 +575,17 @@ export class WebSocketShard extends AsyncEventEmitter<WebSocketShardEventsMap> {
const firstWait = Math.floor(payload.d.heartbeat_interval * jitter);
this.debug([`Preparing first heartbeat of the connection with a jitter of ${jitter}; waiting ${firstWait}ms`]);

await sleep(firstWait);
try {
const controller = new AbortController();
this.initialHeartbeatTimeoutController = controller;
await sleep(firstWait, undefined, { signal: controller.signal });
} catch {
this.debug(['Cancelled initial heartbeat due to #destroy being called']);
return;
} finally {
this.initialHeartbeatTimeoutController = null;
}

await this.heartbeat();

this.debug([`First heartbeat sent, starting to beat every ${payload.d.heartbeat_interval}ms`]);
Expand Down

2 comments on commit 9842082

@vercel
Copy link

@vercel vercel bot commented on 9842082 Mar 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vercel
Copy link

@vercel vercel bot commented on 9842082 Mar 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.