diff --git a/Change-log.md b/Change-log.md index 47a843c..ab68562 100644 --- a/Change-log.md +++ b/Change-log.md @@ -1,5 +1,9 @@ # Change Log +# Unreleased + +- Support a callback for `heartbeatToleranceMultiplier`, evaluated on every incoming heartbeat check ([#755](https://github.com/stomp-js/stompjs/issues/755)). + # 7.5.0 (2026-10-15) - Fix [#743](https://github.com/stomp-js/stompjs/issues/743) diff --git a/spec/unit/heart-beat-callback.spec.ts b/spec/unit/heart-beat-callback.spec.ts index 483048b..a5e8487 100644 --- a/spec/unit/heart-beat-callback.spec.ts +++ b/spec/unit/heart-beat-callback.spec.ts @@ -1,12 +1,14 @@ import { expect, test } from '@playwright/test'; import sinon from 'sinon'; +import { Client, FrameImpl } from '../../src/index.js'; import { disconnectStomp, overRideFactory, stompClient, } from '../helpers/connect-helpers.js'; import { WrapperWS } from '../helpers/wrapper-ws.js'; -import { getLength } from '../helpers/utils.js'; +import { getLength, wait } from '../helpers/utils.js'; +import { parseFrame } from '../helpers/parse-frame.js'; test.describe('Client heartbeat handling (callbacks)', () => { let client: any; @@ -90,3 +92,105 @@ test.describe('Client heartbeat handling (callbacks)', () => { }); }); }); + +test.describe('Heartbeat tolerance lookup', () => { + let client: Client; + let serverHeartbeatInterval: number; + + test.beforeEach(() => { + client = stompClient(); + client.heartbeatIncoming = 250; + serverHeartbeatInterval = 250; + client.heartbeatOutgoing = 0; + + overRideFactory( + client, + class extends WrapperWS { + wrapOnMessage(ev: any) { + // Drop the server's heartbeat messages to simulate missed heartbeats. + // The client should close the connection once its tolerance is exceeded. + if (getLength(ev.data) === 1) { + return; + } + const incomingFrame = parseFrame(ev.data); + if (incomingFrame.command === 'CONNECTED') { + const frame = FrameImpl.fromRawFrame(incomingFrame, true); + // Advertise a shorter interval to speed up the client's checks. + // The connection and timers remain real; server heartbeats are dropped above. + frame.headers['heart-beat'] = `${serverHeartbeatInterval},0`; + ev = { data: frame.serialize() }; + } + super.wrapOnMessage(ev); + } + }, + ); + }); + + test.afterEach(async () => { + await disconnectStomp(client); + }); + + test('looks up changing tolerance on every check without reconnecting', async () => { + let multiplier = 2; + const getHeartbeatMultiplier = sinon.spy(() => multiplier); + const onHeartbeatLost = sinon.spy(); + const onConnect = sinon.spy(); + client.heartbeatToleranceMultiplier = getHeartbeatMultiplier; + client.onHeartbeatLost = onHeartbeatLost; + const closed = new Promise(resolve => { + client.onWebSocketClose = () => resolve(); + }); + + await new Promise(resolve => { + client.onConnect = () => { + onConnect(); + resolve(); + }; + client.activate(); + }); + expect(getHeartbeatMultiplier.called).toBe(false); + await expect + .poll(() => getHeartbeatMultiplier.callCount, { intervals: [20, 40, 50] }) + .toBeGreaterThanOrEqual(1); + + multiplier = 10; + await expect + .poll(() => getHeartbeatMultiplier.callCount, { intervals: [20, 40, 50] }) + .toBeGreaterThanOrEqual(3); + expect(onHeartbeatLost.called).toBe(false); + expect(client.connected).toBe(true); + expect(onConnect.calledOnce).toBe(true); + + multiplier = 1; + await closed; + expect(getHeartbeatMultiplier.callCount).toBeGreaterThanOrEqual(4); + expect(onHeartbeatLost.calledOnce).toBe(true); + expect(client.connected).toBe(false); + expect(onConnect.calledOnce).toBe(true); + }); + + test('applies the callback to the negotiated interval', async () => { + const onHeartbeatLost = sinon.spy(); + client.heartbeatToleranceMultiplier = () => 2; + client.onHeartbeatLost = onHeartbeatLost; + + serverHeartbeatInterval = 500; + + const closed = new Promise(resolve => { + client.onWebSocketClose = () => resolve(); + }); + await new Promise(resolve => { + client.onConnect = () => resolve(); + client.activate(); + }); + + // Beyond the unnegotiated 250 * 2 tolerance, but within 500 * 2. + await wait(750); + expect(onHeartbeatLost.called).toBe(false); + expect(client.connected).toBe(true); + + await closed; + expect(onHeartbeatLost.calledOnce).toBe(true); + expect(client.connected).toBe(false); + }); +}); diff --git a/src/client.ts b/src/client.ts index 0289e48..f6c3457 100644 --- a/src/client.ts +++ b/src/client.ts @@ -7,6 +7,7 @@ import { ActivationState, closeEventCallbackType, debugFnType, + HeartbeatToleranceMultiplier, emptyCallbackType, frameCallbackType, IPublishParams, @@ -172,6 +173,7 @@ export class Client { /** * Multiplier for adjusting tolerance when processing heartbeat signals. + * Accepts a number or a function of type `() => number`. * * Tolerance level is calculated using the multiplier: * `tolerance = heartbeatIncoming * heartbeatToleranceMultiplier`. @@ -184,7 +186,7 @@ export class Client { * client.heartbeatToleranceMultiplier = 2.5; // Tolerates longer delays * ``` */ - public heartbeatToleranceMultiplier: number = 2; + public heartbeatToleranceMultiplier: HeartbeatToleranceMultiplier = 2; /** * Interval (in milliseconds) for sending heartbeat signals to the server. diff --git a/src/stomp-config.ts b/src/stomp-config.ts index fb44ac7..a782d14 100644 --- a/src/stomp-config.ts +++ b/src/stomp-config.ts @@ -4,6 +4,7 @@ import { TickerStrategy, closeEventCallbackType, debugFnType, + HeartbeatToleranceMultiplier, frameCallbackType, messageCallbackType, ReconnectionTimeMode, @@ -64,7 +65,7 @@ export class StompConfig { /** * See [Client#heartbeatToleranceMultiplier]{@link Client#heartbeatToleranceMultiplier}. */ - public heartbeatToleranceMultiplier?: number; + public heartbeatToleranceMultiplier?: HeartbeatToleranceMultiplier; /** * See [Client#heartbeatOutgoing]{@link Client#heartbeatOutgoing}. diff --git a/src/stomp-handler.ts b/src/stomp-handler.ts index 4c3a57e..f7a52e9 100644 --- a/src/stomp-handler.ts +++ b/src/stomp-handler.ts @@ -10,6 +10,7 @@ import { Ticker } from './ticker.js'; import { closeEventCallbackType, debugFnType, + HeartbeatToleranceMultiplier, emptyCallbackType, frameCallbackType, IPublishParams, @@ -41,7 +42,7 @@ export class StompHandler { public heartbeatIncoming: number; - public heartbeatToleranceMultiplier: number; + public heartbeatToleranceMultiplier: HeartbeatToleranceMultiplier; public heartbeatOutgoing: number; @@ -338,7 +339,11 @@ export class StompHandler { this._ponger = setInterval(() => { const delta = Date.now() - this._lastServerActivityTS; // We wait multiple grace periods to be flexible on window's setInterval calls - if (delta > ttl * this.heartbeatToleranceMultiplier) { + const multiplier = + typeof this.heartbeatToleranceMultiplier === 'function' + ? this.heartbeatToleranceMultiplier() + : this.heartbeatToleranceMultiplier; + if (delta > ttl * multiplier) { this.debug(`did not receive server activity for the last ${delta}ms`); this.onHeartbeatLost(); this._closeOrDiscardWebsocket(); diff --git a/src/types.ts b/src/types.ts index 7b10abc..622eb14 100644 --- a/src/types.ts +++ b/src/types.ts @@ -10,6 +10,11 @@ import { Versions } from './versions.js'; */ export type debugFnType = (msg: string) => void; +/** + * Incoming heartbeat tolerance multiplier, or a synchronous lookup evaluated on each check. + */ +export type HeartbeatToleranceMultiplier = number | (() => number); + /** * This callback will receive a {@link IMessage} as parameter. * @@ -189,7 +194,7 @@ export interface IStomptHandlerConfig { connectHeaders: StompHeaders; disconnectHeaders: StompHeaders; heartbeatIncoming: number; - heartbeatGracePeriods: number; + heartbeatGracePeriods: HeartbeatToleranceMultiplier; heartbeatOutgoing: number; heartbeatStrategy: TickerStrategy; splitLargeFrames: boolean;