This is an automated email from the ASF dual-hosted git repository.

RongtongJin pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/rocketmq-clients.git


The following commit(s) were added to refs/heads/master by this push:
     new b55273ba fix(nodejs): check the heartbeat response status instead of 
discarding it (#1491)
b55273ba is described below

commit b55273baed3ab8fab6e1d4ace77e3410cfdbc5b9
Author: Quan <[email protected]>
AuthorDate: Wed Nov 11 10:30:24 2026 +0800

    fix(nodejs): check the heartbeat response status instead of discarding it 
(#1491)
    
    - BaseClient: run StatusChecker on the heartbeat response; business-level 
errors such as UNRECOGNIZED_CLIENT_TYPE (the proxy no longer holds this 
client's settings) arrive as normal gRPC responses and were silently treated as 
success
    - Count a non-OK status as a heartbeat failure so the existing 
consecutive-failure transport recovery kicks in: evict the channel and rebuild 
the telemetry session, which re-registers the settings
    - Rename #doHeartbeat to a TypeScript-private doHeartbeat (invisible on the 
public API surface) so the regression test can invoke it through a cast, 
mirroring Java ClientImpl#doHeartbeat behavior
    - Extend BaseClient.test.ts with a heartbeat status regression test
---
 nodejs/src/client/BaseClient.ts       |  18 +++++-
 nodejs/test/client/BaseClient.test.ts | 110 ++++++++++++++++++++++++++++++++++
 2 files changed, 125 insertions(+), 3 deletions(-)

diff --git a/nodejs/src/client/BaseClient.ts b/nodejs/src/client/BaseClient.ts
index 14929159..f48c84d6 100644
--- a/nodejs/src/client/BaseClient.ts
+++ b/nodejs/src/client/BaseClient.ts
@@ -276,7 +276,7 @@ export abstract class BaseClient {
 
       // heartbeat every 10s
       this.#timers.push(setInterval(async () => {
-        this.#doHeartbeat();
+        this.doHeartbeat();
       }, 10000));
 
       // doStats every 60s
@@ -345,7 +345,13 @@ export abstract class BaseClient {
     setImmediate(() => this.logger.close && this.logger.close());
   }
 
-  async #doHeartbeat() {
+  /**
+   * Send one heartbeat round to every route endpoint, mirroring Java
+   * ClientImpl#doHeartbeat. TypeScript-private (not #private) so regression
+   * tests can invoke it through a cast; it stays invisible on the public API
+   * surface (.d.ts exposes it as private and subclasses cannot access it).
+   */
+  private async doHeartbeat() {
     try {
       const request = this.wrapHeartbeatRequest();
       const endpointsList = this.getTotalRouteEndpoints();
@@ -355,7 +361,13 @@ export abstract class BaseClient {
       }
       for (const endpoints of endpointsList) {
         try {
-          await this.rpcClientManager.heartbeat(endpoints, request, 
this.requestTimeout);
+          const response = await this.rpcClientManager.heartbeat(endpoints, 
request, this.requestTimeout);
+          // Business-level errors (e.g. UNRECOGNIZED_CLIENT_TYPE when the
+          // remote no longer holds this client's settings) arrive as normal
+          // gRPC responses; without this check the client stays blind to
+          // settings loss and never re-registers. Mirrors Java
+          // ClientImpl#doHeartbeat which checks the response status.
+          StatusChecker.check(response.getStatus()?.toObject());
           // Heartbeat succeeded: the remote is reachable again, so rejoin any
           // isolated endpoints (mirrors Java ClientImpl#doHeartbeat).
           if (this.isolated.delete(endpoints.facade)) {
diff --git a/nodejs/test/client/BaseClient.test.ts 
b/nodejs/test/client/BaseClient.test.ts
index 960d25c8..7e441f93 100644
--- a/nodejs/test/client/BaseClient.test.ts
+++ b/nodejs/test/client/BaseClient.test.ts
@@ -26,14 +26,23 @@
 
 import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
+import { EventEmitter } from 'node:events';
+import { format } from 'node:util';
 import {
+  AddressScheme,
+  Broker as BrokerPB,
   ClientType,
   Code,
+  Endpoints as EndpointsPB,
+  MessageQueue as MessageQueuePB,
+  Permission,
+  Resource,
   Settings as SettingsPB,
   Status,
 } from '../../proto/apache/rocketmq/v2/definition_pb';
 import {
   HeartbeatRequest,
+  HeartbeatResponse,
   NotifyClientTerminationRequest,
   QueryRouteResponse,
 } from '../../proto/apache/rocketmq/v2/service_pb';
@@ -84,6 +93,31 @@ class TestClient extends BaseClient {
       return response;
     };
   }
+
+  /** Test hook: route query returning one real message queue, so the route
+   * cache yields a heartbeat target endpoint. */
+  mockQueryRouteWithQueue(delayMs: number) {
+    const self = this as unknown as { rpcClientManager: Record<string, 
unknown> };
+    self.rpcClientManager.queryRoute = async () => {
+      await sleep(delayMs);
+      const endpointsPb = new EndpointsPB();
+      endpointsPb.setScheme(AddressScheme.IPV4);
+      endpointsPb.addAddresses().setHost('127.0.0.1').setPort(8081);
+      const brokerPb = new BrokerPB();
+      brokerPb.setName('broker-a');
+      brokerPb.setId(0);
+      brokerPb.setEndpoints(endpointsPb);
+      const mqPb = new MessageQueuePB();
+      mqPb.setId(0);
+      mqPb.setTopic(new Resource().setName('topic-A'));
+      mqPb.setBroker(brokerPb);
+      mqPb.setPermission(Permission.READ_WRITE);
+      const response = new QueryRouteResponse();
+      response.setStatus(new Status().setCode(Code.OK));
+      response.addMessageQueues(mqPb);
+      return response;
+    };
+  }
 }
 
 function sleep(ms: number): Promise<void> {
@@ -150,3 +184,79 @@ describe('BaseClient startup first-settings promise', () 
=> {
     }
   });
 });
+
+describe('BaseClient heartbeat response status check', () => {
+  function makeFakeStream() {
+    const stream: any = new EventEmitter();
+    stream.writes = [] as unknown[];
+    stream.write = (command: unknown) => {
+      stream.writes.push(command);
+      return true;
+    };
+    stream.end = () => undefined;
+    return stream;
+  }
+
+  it('treats an error status in the heartbeat response as a failure and 
rebuilds transport', async () => {
+    const warnings: string[] = [];
+    const logger: any = {
+      info: () => undefined,
+      warn: (...args: unknown[]) => { warnings.push(format(...args as [ string 
])); },
+      error: () => undefined,
+      debug: () => undefined,
+    };
+    const client = new TestClient({
+      endpoints: '127.0.0.1:8081',
+      namespace: 'test-namespace',
+      topics: [ 'topic-A' ],
+      logger,
+    });
+
+    // Replace the real RPC manager (closing it first to stop its idle-check
+    // timer) with a fake whose heartbeat returns UNRECOGNIZED_CLIENT_TYPE —
+    // the signal a proxy sends when it no longer holds the client's settings.
+    (client as any).rpcClientManager.close();
+    const streams: any[] = [];
+    let evictCount = 0;
+    (client as any).rpcClientManager = {
+      queryRoute: async () => {
+        throw new Error('use mockQueryRouteWithQueue');
+      },
+      heartbeat: async () => new HeartbeatResponse()
+        .setStatus(new 
Status().setCode(Code.UNRECOGNIZED_CLIENT_TYPE).setMessage('client type 
unrecognized')),
+      telemetry: () => {
+        const stream = makeFakeStream();
+        streams.push(stream);
+        return stream;
+      },
+      evict: () => { evictCount++; },
+      notifyClientTermination: async () => ({}),
+      close: () => undefined,
+    };
+    client.mockQueryRouteWithQueue(10);
+
+    const startupPromise = client.startup();
+    await sleep(20);
+    client.onSettingsCommand(client.getEndpoints(), new SettingsPB());
+    await startupPromise;
+    // The route fetch opened one telemetry session and synced settings to it.
+    assert.strictEqual(streams.length, 1);
+
+    // Heartbeat round 1: the error status must be treated as a failure
+    // (pre-fix the response was discarded and this counted as a success).
+    await (client as any).doHeartbeat();
+    assert.ok(warnings.some(w => w.includes('Heartbeat failed') && 
w.includes('client type unrecognized')),
+      'an error status in the heartbeat response must be logged as a failure');
+    assert.strictEqual(evictCount, 0, 'first failure is below the recovery 
threshold');
+
+    // Heartbeat round 2: consecutive failures reach the threshold and trigger
+    // transport recovery — evict the channel and rebuild telemetry so the
+    // settings get re-registered.
+    await (client as any).doHeartbeat();
+    assert.strictEqual(evictCount, 1, 'transport recovery must evict the stale 
rpc client');
+    assert.strictEqual(streams.length, 2, 'telemetry session must be rebuilt');
+    assert.ok(streams[1].writes.length >= 1, 'settings must be re-synced on 
the rebuilt stream');
+
+    await client.shutdown();
+  });
+});

Reply via email to