From 429b08a0e1087d963a5770aa273d431a72af093f Mon Sep 17 00:00:00 2001 From: Vladimir Dementyev Date: Mon, 26 Feb 2024 17:00:01 -0800 Subject: [PATCH] fix(core): do not send pongs when cable is not connected Fixes #33 --- packages/core/CHANGELOG.md | 2 ++ packages/core/action_cable_ext/index.js | 5 ++++- packages/core/action_cable_ext/index.test.ts | 10 ++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index ecc4f51..49732f9 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -2,6 +2,8 @@ ## master +- Do not try to send `pong` if cable is no longer connected. ([@palkan][]) + ## 0.7.12 (2024-01-08) - Omit `undefined` within Channels' params to fix invalid JSON serialization. ([@ardecvz][]) diff --git a/packages/core/action_cable_ext/index.js b/packages/core/action_cable_ext/index.js index 464a002..9cfac3b 100644 --- a/packages/core/action_cable_ext/index.js +++ b/packages/core/action_cable_ext/index.js @@ -152,6 +152,9 @@ export class ActionCableExtendedProtocol extends ActionCableProtocol { // Send pongs asynchrounously—no need to block the main thread async sendPong() { await new Promise(resolve => setTimeout(resolve, 0)) - this.cable.send({ command: 'pong' }) + // Only send pong if the connection is still open + if (this.cable.state === 'connected') { + this.cable.send({ command: 'pong' }) + } } } diff --git a/packages/core/action_cable_ext/index.test.ts b/packages/core/action_cable_ext/index.test.ts index 63fbdea..401cd46 100644 --- a/packages/core/action_cable_ext/index.test.ts +++ b/packages/core/action_cable_ext/index.test.ts @@ -289,6 +289,7 @@ describe('receive', () => { }) it('sends pong in response to ping', async () => { + cable.connected() protocol.receive({ type: 'ping', message: '42' }) expect(cable.lastPingedAt).toEqual(42) @@ -299,6 +300,15 @@ describe('receive', () => { command: 'pong' }) }) + + it('does not try to send pong if cable is no longer connected', async () => { + protocol.receive({ type: 'ping', message: '42' }) + expect(cable.lastPingedAt).toEqual(42) + cable.disconnected() + await new Promise(resolve => setTimeout(resolve, 0)) + + expect(cable.mailbox).toHaveLength(0) + }) }) })