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 1ea0c5f4 fix(nodejs): harden client lifecycle and telemetry session 
like the Java client (#1502)
1ea0c5f4 is described below

commit 1ea0c5f47fff1e172b361a7fd694bf002f47f1c0
Author: Quan <[email protected]>
AuthorDate: Wed Nov 18 21:18:32 2026 +0800

    fix(nodejs): harden client lifecycle and telemetry session like the Java 
client (#1502)
    
    - Keep releasing resources on shutdown when notifying termination fails
    - Fail startup when any topic route cannot be fetched after retries
    - Do not keep the process alive for a client that is never started
    - Stop telemetry stream errors and handler failures from crashing the 
process
    - Warn when an interceptor is added while running and fix the idle reclaim 
log
    - Cover lifecycle, heartbeat, route cache, telemetry dispatch and RPC 
delegation
---
 nodejs/src/client/BaseClient.ts                |  37 +-
 nodejs/src/client/RpcClientManager.ts          |   5 +-
 nodejs/src/client/TelemetrySession.ts          |  49 ++-
 nodejs/test/client/BaseClientLifecycle.test.ts | 463 +++++++++++++++++++++++++
 nodejs/test/client/RpcClient.test.ts           |  74 +++-
 nodejs/test/client/RpcClientManager.test.ts    | 157 +++++++++
 nodejs/test/client/TelemetrySession.test.ts    | 146 ++++++++
 7 files changed, 915 insertions(+), 16 deletions(-)

diff --git a/nodejs/src/client/BaseClient.ts b/nodejs/src/client/BaseClient.ts
index 5cb935dc..73b80c81 100644
--- a/nodejs/src/client/BaseClient.ts
+++ b/nodejs/src/client/BaseClient.ts
@@ -253,12 +253,14 @@ export abstract class BaseClient {
     try {
       // Fetch topic route with retry mechanism (align with Java client)
       const maxAttempts = 3;
+      let fetched = false;
       let lastError: Error | undefined;
       for (let attempt = 1; attempt <= maxAttempts; attempt++) {
         try {
           await this.updateRoutes();
           this.logger.info('Fetch topic route successfully during startup, 
clientId=%s, attempt=%d',
             this.clientId, attempt);
+          fetched = true;
           break;
         } catch (e) {
           lastError = e as Error;
@@ -279,7 +281,9 @@ export abstract class BaseClient {
         }
       }
 
-      if (lastError && !this.topicRouteCache.size) {
+      // Every topic must be routable, mirroring Java ClientImpl#startUp which 
fails
+      // after the last attempt even if some topics were fetched successfully.
+      if (!fetched) {
         throw new Error(`Failed to fetch topic routes after ${maxAttempts} 
attempts`, { cause: lastError });
       }
 
@@ -661,13 +665,31 @@ export abstract class BaseClient {
 
   /**
    * Notify remote that current client is prepared to be terminated.
+   *
+   * Best-effort like Java ClientImpl#notifyClientTermination: a failing or
+   * unreachable endpoint is only logged, so shutdown always goes on to
+   * release the telemetry sessions, RPC channels and meters.
    */
   async #notifyClientTermination() {
     this.logger.info('Notify remote that client is terminated, clientId=%s', 
this.clientId);
-    const request = this.wrapNotifyClientTerminationRequest();
-    for (const endpoints of this.getTotalRouteEndpoints()) {
-      await this.rpcClientManager.notifyClientTermination(endpoints, request, 
this.requestTimeout);
+    let request: NotifyClientTerminationRequest;
+    try {
+      request = this.wrapNotifyClientTerminationRequest();
+    } catch (e) {
+      this.logger.error('[Bug] Failed to wrap notify client termination 
request, clientId=%s, error=%s',
+        this.clientId, e instanceof Error ? e.message : String(e));
+      return;
     }
+    const endpointsList = this.getTotalRouteEndpoints();
+    const results = await Promise.allSettled(endpointsList.map(endpoints =>
+      this.rpcClientManager.notifyClientTermination(endpoints, request, 
this.requestTimeout)));
+    results.forEach((result, i) => {
+      if (result.status === 'rejected') {
+        const e = result.reason;
+        this.logger.warn('Failed to notify remote that client is terminated, 
clientId=%s, endpoints=%s, error=%s',
+          this.clientId, endpointsList[i].facade, e instanceof Error ? 
e.message : String(e));
+      }
+    });
   }
 
   // eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -790,9 +812,12 @@ export abstract class BaseClient {
    * before the client is running, mirroring Java 
ClientImpl#addMessageInterceptor.
    */
   addMessageInterceptor(messageInterceptor: MessageInterceptor) {
-    if (!this.isRunning()) {
-      this.#compositedMessageInterceptor.addInterceptor(messageInterceptor);
+    if (this.isRunning()) {
+      this.logger.warn('Message interceptor can only be added before the 
client is running, ignore it, clientId=%s',
+        this.clientId);
+      return;
     }
+    this.#compositedMessageInterceptor.addInterceptor(messageInterceptor);
   }
 
   /**
diff --git a/nodejs/src/client/RpcClientManager.ts 
b/nodejs/src/client/RpcClientManager.ts
index 9e2ac88c..6e455957 100644
--- a/nodejs/src/client/RpcClientManager.ts
+++ b/nodejs/src/client/RpcClientManager.ts
@@ -59,6 +59,9 @@ export class RpcClientManager {
     this.#clearIdleRpcClientsTimer = setInterval(() => {
       this.#clearIdleRpcClients();
     }, RPC_CLIENT_IDLE_CHECK_PERIOD);
+    // Housekeeping only: a client that is constructed but never started must
+    // not keep the process alive.
+    this.#clearIdleRpcClientsTimer.unref();
   }
 
   #clearIdleRpcClients() {
@@ -67,7 +70,7 @@ export class RpcClientManager {
       if (idleDuration > RPC_CLIENT_MAX_IDLE_DURATION) {
         rpcClient.close();
         this.#rpcClients.delete(facade);
-        this.#logger.info('[RpcClientManager] Rpc client has been idle for a 
long time, endpoints=%s, idleDuration=%s, clientId=%s',
+        this.#logger.info('[RpcClientManager] Rpc client has been idle for a 
long time, endpoints=%s, idleDuration=%dms, maxIdleDuration=%dms, clientId=%s',
           facade, idleDuration, RPC_CLIENT_MAX_IDLE_DURATION, 
this.#baseClient.clientId);
       }
     }
diff --git a/nodejs/src/client/TelemetrySession.ts 
b/nodejs/src/client/TelemetrySession.ts
index b9dbebfe..e469907b 100644
--- a/nodejs/src/client/TelemetrySession.ts
+++ b/nodejs/src/client/TelemetrySession.ts
@@ -25,7 +25,8 @@ export class TelemetrySession {
   #endpoints: Endpoints;
   #baseClient: BaseClient;
   #logger: ILogger;
-  #stream: ClientDuplexStream<TelemetryCommand, TelemetryCommand>;
+  // Live stream, or undefined while closed (released or awaiting reconnect).
+  #stream?: ClientDuplexStream<TelemetryCommand, TelemetryCommand>;
   #isRefreshing = false;
   #released = false;
   #reconnectTimer?: NodeJS.Timeout;
@@ -57,9 +58,17 @@ export class TelemetrySession {
   }
 
   #closeStream() {
+    const stream = this.#stream;
+    if (!stream) {
+      return;
+    }
+    this.#stream = undefined;
     try {
-      this.#stream.end();
-      this.#stream.removeAllListeners();
+      stream.removeAllListeners();
+      // The remote may still finish the call with a non-OK status after the
+      // half-close; an 'error' event without any listener would crash the 
process.
+      stream.on('error', () => undefined);
+      stream.end();
     } catch (e) {
       this.#logger.warn('Failed to release telemetry session gracefully, 
endpoints=%s, clientId=%s, error=%s',
         this.#endpoints, this.#baseClient.clientId, e instanceof Error ? 
e.message : String(e));
@@ -67,7 +76,19 @@ export class TelemetrySession {
   }
 
   write(command: TelemetryCommand) {
-    this.#stream.write(command);
+    const stream = this.#stream;
+    if (!stream) {
+      // Released, or waiting for reconnect: the renewed stream syncs settings 
itself.
+      this.#logger.warn('Telemetry stream is not available, drop the command, 
endpoints=%s, clientId=%s, released=%s',
+        this.#endpoints, this.#baseClient.clientId, this.#released);
+      return;
+    }
+    try {
+      stream.write(command);
+    } catch (e) {
+      this.#logger.error('Failed to write telemetry command, endpoints=%s, 
clientId=%s, error=%s',
+        this.#endpoints, this.#baseClient.clientId, e instanceof Error ? 
e.message : String(e));
+    }
   }
 
   syncSettings() {
@@ -108,10 +129,11 @@ export class TelemetrySession {
     try {
       this.#logger.debug?.('Creating telemetry stream, endpoints=%s, 
clientId=%s, inited=%s',
         this.#endpoints, this.#baseClient.clientId, inited);
-      this.#stream = this.#baseClient.createTelemetryStream(this.#endpoints);
-      this.#stream.on('data', this.#onData.bind(this));
-      this.#stream.once('error', this.#onError.bind(this));
-      this.#stream.once('end', this.#onEnd.bind(this));
+      const stream = this.#baseClient.createTelemetryStream(this.#endpoints);
+      stream.on('data', this.#onData.bind(this));
+      stream.once('error', this.#onError.bind(this));
+      stream.once('end', this.#onEnd.bind(this));
+      this.#stream = stream;
       if (!inited) {
         this.#logger.info('Syncing settings to new stream, endpoints=%s, 
clientId=%s',
           this.#endpoints, this.#baseClient.clientId);
@@ -127,6 +149,17 @@ export class TelemetrySession {
   #onData(command: TelemetryCommand) {
     // Inbound data proves the stream is alive: reset the reconnect backoff.
     this.#reconnectAttempts = 0;
+    try {
+      this.#dispatch(command);
+    } catch (e) {
+      // Mirrors Java ClientSessionImpl#onNext: a failing handler must not
+      // escape the stream callback as an uncaughtException.
+      this.#logger.error('[Bug] Unexpected exception raised while receiving 
command from remote, endpoints=%s, clientId=%s, error=%s',
+        this.#endpoints, this.#baseClient.clientId, e instanceof Error ? 
e.message : String(e));
+    }
+  }
+
+  #dispatch(command: TelemetryCommand) {
     const endpoints = this.#endpoints;
     const clientId = this.#baseClient.clientId;
     const commandCase = command.getCommandCase();
diff --git a/nodejs/test/client/BaseClientLifecycle.test.ts 
b/nodejs/test/client/BaseClientLifecycle.test.ts
new file mode 100644
index 00000000..3aac6b3d
--- /dev/null
+++ b/nodejs/test/client/BaseClientLifecycle.test.ts
@@ -0,0 +1,463 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { strict as assert } from 'node:assert';
+import { hostname } from 'node:os';
+import * as sinon from 'sinon';
+import { ClientType, Code, Settings as SettingsPB } from 
'../../proto/apache/rocketmq/v2/definition_pb';
+import {
+  HeartbeatRequest,
+  HeartbeatResponse,
+  NotifyClientTerminationRequest,
+  NotifyClientTerminationResponse,
+  PrintThreadStackTraceCommand,
+  QueryRouteResponse,
+  RecoverOrphanedTransactionCommand,
+  TelemetryCommand,
+  VerifyMessageCommand,
+} from '../../proto/apache/rocketmq/v2/service_pb';
+import { BaseClient, BaseClientOptions } from '../../src/client/BaseClient';
+import { ClientId } from '../../src/client/ClientId';
+import { Settings } from '../../src/client/Settings';
+import { MessageHookPoints, MessageInterceptor, MessageInterceptorContextImpl 
} from '../../src/hook';
+import { Endpoints, TopicRouteData } from '../../src/route';
+import { createFakeRpcClientManager, createSilentLogger, deferred, 
FakeTelemetryStream, installFakeRpcClientManager } from '../support/fakes';
+import { buildRoute, buildSettings, buildStatus } from '../support/protobuf';
+
+const BROKER_A = '127.0.0.1:8081';
+const BROKER_B = '127.0.0.1:8082';
+
+class StubSettings extends Settings {
+  constructor() {
+    super('', 'test-client-id', ClientType.PRODUCER, new Endpoints(BROKER_A), 
3000);
+  }
+
+  toProtobuf(): SettingsPB {
+    return new SettingsPB();
+  }
+
+  sync(): void {
+    // the lifecycle tests do not depend on settings content
+  }
+}
+
+class TestClient extends BaseClient {
+  readonly routeUpdates: Array<[ string, TopicRouteData ]> = [];
+
+  protected getClientType(): ClientType {
+    return ClientType.PRODUCER;
+  }
+
+  protected getSettings(): Settings {
+    return new StubSettings();
+  }
+
+  protected wrapHeartbeatRequest(): HeartbeatRequest {
+    return new HeartbeatRequest();
+  }
+
+  protected wrapNotifyClientTerminationRequest(): 
NotifyClientTerminationRequest {
+    return new NotifyClientTerminationRequest();
+  }
+
+  protected onTopicRouteDataUpdate(topic: string, topicRouteData: 
TopicRouteData) {
+    this.routeUpdates.push([ topic, topicRouteData ]);
+  }
+
+  route(topic: string) {
+    return this.getRouteData(topic);
+  }
+
+  heartbeat(): Promise<void> {
+    return (this as any).doHeartbeat();
+  }
+
+  get isolatedEndpoints() {
+    return this.isolated;
+  }
+
+  get routeCache() {
+    return this.topicRouteCache;
+  }
+}
+
+function routeResponse(...brokers: string[]) {
+  const route = buildRoute({ brokers: brokers.map((endpoints, i) => ({ name: 
`broker-${i}`, endpoints })) });
+  return new QueryRouteResponse().setStatus(buildStatus())
+    .setMessageQueuesList(route.messageQueues.map(mq => mq.toProtobuf()));
+}
+
+function heartbeatResponse(code = Code.OK) {
+  return new HeartbeatResponse().setStatus(buildStatus(code, code === Code.OK 
? '' : 'heartbeat rejected'));
+}
+
+function createHarness(options: Partial<BaseClientOptions> = {}) {
+  const logger = createSilentLogger();
+  const client = new TestClient({ endpoints: BROKER_A, namespace: '', logger, 
...options });
+  const rpc = installFakeRpcClientManager(client, 
createFakeRpcClientManager());
+  const streams: FakeTelemetryStream[] = [];
+  rpc.telemetry.callsFake(() => {
+    const stream = new FakeTelemetryStream();
+    streams.push(stream);
+    return stream.asGrpcStream();
+  });
+  rpc.notifyClientTermination.resolves(new 
NotifyClientTerminationResponse().setStatus(buildStatus()));
+  const meterShutdown = sinon.spy((client as any).clientMeterManager, 
'shutdown');
+  return { client, rpc, logger, streams, meterShutdown };
+}
+
+async function startClient(harness: ReturnType<typeof createHarness>, clock: 
sinon.SinonFakeTimers) {
+  const startup = harness.client.startup();
+  await clock.tickAsync(0);
+  harness.client.onSettingsCommand(harness.client.getEndpoints(), 
buildSettings());
+  await startup;
+}
+
+describe('BaseClient lifecycle', () => {
+  let clock: sinon.SinonFakeTimers;
+
+  beforeEach(() => {
+    // Start from the real wall clock: the transport recovery cooldown 
compares against epoch-based timestamps.
+    clock = sinon.useFakeTimers({ now: Date.now() });
+  });
+
+  afterEach(() => {
+    clock.restore();
+    sinon.restore();
+  });
+
+  describe('shutdown', () => {
+    it('keeps releasing resources when notifying termination to one endpoint 
fails', async () => {
+      const harness = createHarness({ topics: [ 'topic-a' ] });
+      harness.rpc.queryRoute.resolves(routeResponse(BROKER_A, BROKER_B));
+      await startClient(harness, clock);
+      assert.strictEqual(harness.streams.length, 2);
+      harness.rpc.notifyClientTermination.callsFake(async endpoints => {
+        if (endpoints.facade === BROKER_A) {
+          throw new Error('broker unreachable');
+        }
+        return new NotifyClientTerminationResponse().setStatus(buildStatus());
+      });
+
+      await harness.client.shutdown();
+
+      sinon.assert.calledTwice(harness.rpc.notifyClientTermination);
+      assert.ok(harness.streams.every(stream => stream.writableEnded), 'every 
telemetry stream must be released');
+      sinon.assert.calledOnce(harness.rpc.close);
+      sinon.assert.calledOnce(harness.meterShutdown);
+      assert.strictEqual(harness.client.routeCache.size, 0);
+      assert.strictEqual(harness.client.isRunning(), false);
+      assert.strictEqual(clock.countTimers(), 0, 'no timer may survive 
shutdown');
+      sinon.assert.calledWithMatch(harness.logger.warn, /Failed to notify 
remote/, sinon.match.any, BROKER_A);
+    });
+
+    it('can be called repeatedly', async () => {
+      const harness = createHarness({ topics: [ 'topic-a' ] });
+      harness.rpc.queryRoute.resolves(routeResponse(BROKER_A));
+      await startClient(harness, clock);
+
+      await harness.client.shutdown();
+      await harness.client.shutdown();
+
+      sinon.assert.calledOnce(harness.rpc.notifyClientTermination);
+      assert.strictEqual(harness.client.isRunning(), false);
+      assert.strictEqual(clock.countTimers(), 0);
+    });
+
+    it('works on a client that never started', async () => {
+      const harness = createHarness({ topics: [ 'topic-a' ] });
+      await harness.client.shutdown();
+      sinon.assert.notCalled(harness.rpc.notifyClientTermination);
+      sinon.assert.calledOnce(harness.rpc.close);
+      assert.strictEqual(clock.countTimers(), 0);
+    });
+  });
+
+  describe('startup failure', () => {
+    it('leaves no timer or telemetry session after the route query keeps 
failing', async () => {
+      const harness = createHarness({ topics: [ 'topic-a' ] });
+      harness.rpc.queryRoute.rejects(new Error('route unavailable'));
+
+      const assertion = assert.rejects(harness.client.startup(), /Startup the 
rocketmq client failed/);
+      await clock.tickAsync(3000);
+      await assertion;
+
+      sinon.assert.calledThrice(harness.rpc.queryRoute);
+      assert.strictEqual(harness.streams.length, 0);
+      sinon.assert.calledOnce(harness.rpc.close);
+      assert.strictEqual(clock.countTimers(), 0);
+      assert.strictEqual(harness.client.isRunning(), false);
+    });
+
+    it('fails when one of several topics keeps failing even if the others are 
routable', async () => {
+      const harness = createHarness({ topics: [ 'topic-a', 'topic-b' ] });
+      harness.rpc.queryRoute.callsFake(async (_endpoints, request) => {
+        if (request.getTopic()?.getName() === 'topic-b') {
+          throw new Error('route unavailable for topic-b');
+        }
+        return routeResponse(BROKER_A);
+      });
+
+      const assertion = assert.rejects(harness.client.startup(), /Failed to 
fetch topic routes after 3 attempts/);
+      await clock.tickAsync(3000);
+      await assertion;
+
+      assert.strictEqual(harness.client.isRunning(), false);
+      assert.ok(harness.streams.every(stream => stream.writableEnded), 
'telemetry of the routable topic must be released');
+      assert.strictEqual(clock.countTimers(), 0);
+    });
+
+    it('succeeds when a failed route query recovers on retry', async () => {
+      const harness = createHarness({ topics: [ 'topic-a' ] });
+      harness.rpc.queryRoute.onFirstCall().rejects(new Error('route 
unavailable'));
+      harness.rpc.queryRoute.resolves(routeResponse(BROKER_A));
+
+      const startup = harness.client.startup();
+      await clock.tickAsync(1000);
+      harness.client.onSettingsCommand(harness.client.getEndpoints(), 
buildSettings());
+      await startup;
+
+      sinon.assert.calledTwice(harness.rpc.queryRoute);
+      assert.strictEqual(harness.client.isRunning(), true);
+      await harness.client.shutdown();
+    });
+
+    it('releases timers and telemetry sessions when the first settings never 
arrive', async () => {
+      const harness = createHarness({ topics: [ 'topic-a' ] });
+      harness.rpc.queryRoute.resolves(routeResponse(BROKER_A));
+      harness.rpc.heartbeat.resolves(heartbeatResponse());
+
+      const assertion = assert.rejects(harness.client.startup(), /Timed out 
waiting for the first settings/);
+      await clock.tickAsync(30000);
+      await assertion;
+
+      assert.strictEqual(harness.streams.length, 1);
+      assert.ok(harness.streams[0].writableEnded);
+      assert.strictEqual(clock.countTimers(), 0);
+    });
+
+    it('rejects startup when the remote answers with an error status on 
telemetry', async () => {
+      const harness = createHarness({ topics: [ 'topic-a' ] });
+      harness.rpc.queryRoute.resolves(routeResponse(BROKER_A));
+
+      const assertion = assert.rejects(harness.client.startup(), /permission 
denied/);
+      await clock.tickAsync(0);
+      harness.streams[0].receive(new 
TelemetryCommand().setStatus(buildStatus(Code.FORBIDDEN, 'permission denied')));
+      await assertion;
+      assert.strictEqual(clock.countTimers(), 0);
+    });
+  });
+
+  describe('heartbeat', () => {
+    async function startedHarness() {
+      const harness = createHarness({ topics: [ 'topic-a' ] });
+      harness.rpc.queryRoute.resolves(routeResponse(BROKER_A));
+      await startClient(harness, clock);
+      return harness;
+    }
+
+    it('sends nothing when no route endpoints are known', async () => {
+      const harness = createHarness();
+      await harness.client.heartbeat();
+      sinon.assert.notCalled(harness.rpc.heartbeat);
+    });
+
+    it('resets the failure count after a successful heartbeat', async () => {
+      const harness = await startedHarness();
+      
harness.rpc.heartbeat.onCall(0).resolves(heartbeatResponse(Code.INTERNAL_SERVER_ERROR));
+      harness.rpc.heartbeat.onCall(1).resolves(heartbeatResponse());
+      
harness.rpc.heartbeat.onCall(2).resolves(heartbeatResponse(Code.INTERNAL_SERVER_ERROR));
+      for (let i = 0; i < 3; i++) {
+        await harness.client.heartbeat();
+      }
+      sinon.assert.notCalled(harness.rpc.evict);
+      await harness.client.shutdown();
+    });
+
+    it('rebuilds the transport at the threshold and throttles recovery by the 
cooldown', async () => {
+      const harness = await startedHarness();
+      harness.rpc.heartbeat.rejects(new Error('deadline exceeded'));
+
+      await harness.client.heartbeat();
+      sinon.assert.notCalled(harness.rpc.evict);
+      await harness.client.heartbeat();
+      sinon.assert.calledOnce(harness.rpc.evict);
+      assert.strictEqual(harness.streams.length, 2, 'telemetry session must be 
rebuilt');
+      assert.ok(harness.streams[0].writableEnded, 'the stale telemetry stream 
must be released');
+      assert.strictEqual(harness.streams[1].writes.length, 1, 'settings must 
be re-synced');
+
+      await harness.client.heartbeat();
+      sinon.assert.calledOnce(harness.rpc.evict);
+      // Move the wall clock past the cooldown without firing the periodic 
tasks.
+      clock.setSystemTime(Date.now() + 30000);
+      await harness.client.heartbeat();
+      sinon.assert.calledTwice(harness.rpc.evict);
+      await harness.client.shutdown();
+    });
+
+    it('rejoins isolated endpoints after a successful heartbeat', async () => {
+      const harness = await startedHarness();
+      harness.client.isolatedEndpoints.set(BROKER_A, new Endpoints(BROKER_A));
+      harness.rpc.heartbeat.resolves(heartbeatResponse());
+      await harness.client.heartbeat();
+      assert.strictEqual(harness.client.isolatedEndpoints.size, 0);
+      await harness.client.shutdown();
+    });
+  });
+
+  describe('route cache', () => {
+    it('shares one in-flight query among concurrent callers of the same 
topic', async () => {
+      const harness = createHarness();
+      const pending = deferred<QueryRouteResponse>();
+      harness.rpc.queryRoute.callsFake(() => pending.promise);
+
+      const first = harness.client.route('topic-a');
+      const second = harness.client.route('topic-a');
+      pending.resolve(routeResponse(BROKER_A));
+
+      assert.strictEqual(await first, await second);
+      sinon.assert.calledOnce(harness.rpc.queryRoute);
+      assert.strictEqual(await harness.client.route('topic-a'), await first, 
'cached route must be reused');
+      sinon.assert.calledOnce(harness.rpc.queryRoute);
+    });
+
+    it('does not cache a failed query', async () => {
+      const harness = createHarness();
+      harness.rpc.queryRoute.onFirstCall().rejects(new Error('route 
unavailable'));
+      harness.rpc.queryRoute.onSecondCall().resolves(routeResponse(BROKER_A));
+
+      await assert.rejects(harness.client.route('topic-a'), /route 
unavailable/);
+      assert.strictEqual(harness.client.routeCache.size, 0);
+      await harness.client.route('topic-a');
+      sinon.assert.calledTwice(harness.rpc.queryRoute);
+      assert.strictEqual(harness.client.routeCache.size, 1);
+    });
+
+    it('rejects an error status without caching it', async () => {
+      const harness = createHarness();
+      harness.rpc.queryRoute.resolves(new 
QueryRouteResponse().setStatus(buildStatus(Code.TOPIC_NOT_FOUND, 'no topic')));
+      await assert.rejects(harness.client.route('topic-a'), /no topic/);
+      assert.strictEqual(harness.client.routeCache.size, 0);
+      assert.strictEqual(harness.client.routeUpdates.length, 0);
+    });
+
+    it('opens telemetry only for new endpoints and reports every route 
update', async () => {
+      const harness = createHarness();
+      harness.rpc.queryRoute.onFirstCall().resolves(routeResponse(BROKER_A));
+      harness.rpc.queryRoute.onSecondCall().resolves(routeResponse(BROKER_A, 
BROKER_B));
+
+      await harness.client.route('topic-a');
+      await harness.client.route('topic-b');
+
+      assert.deepStrictEqual(harness.client.routeUpdates.map(([ topic ]) => 
topic), [ 'topic-a', 'topic-b' ]);
+      
assert.strictEqual(harness.client.routeUpdates[1][1].getTotalEndpoints().length,
 2);
+      assert.strictEqual(harness.streams.length, 2, 'only the new endpoints 
get a telemetry session');
+      assert.ok(harness.streams.every(stream => stream.writes.length === 1), 
'settings must be synced once per session');
+    });
+  });
+
+  describe('telemetry command dispatch', () => {
+    async function sessionHarness() {
+      const harness = createHarness();
+      harness.rpc.queryRoute.resolves(routeResponse(BROKER_A));
+      await harness.client.route('topic-a');
+      const stream = harness.streams[0];
+      stream.writes.length = 0;
+      return { ...harness, stream };
+    }
+
+    it('applies a settings command', async () => {
+      const { client, stream } = await sessionHarness();
+      const onSettings = sinon.spy(client, 'onSettingsCommand');
+      const settings = buildSettings();
+      stream.receive(new TelemetryCommand().setSettings(settings));
+      sinon.assert.calledOnce(onSettings);
+      assert.strictEqual(onSettings.firstCall.args[1].toObject().clientType, 
settings.getClientType());
+    });
+
+    it('ignores an orphaned transaction recovery command on the base client', 
async () => {
+      const { stream, logger } = await sessionHarness();
+      stream.receive(new 
TelemetryCommand().setRecoverOrphanedTransactionCommand(new 
RecoverOrphanedTransactionCommand()));
+      sinon.assert.calledWithMatch(logger.warn, /Ignore orphaned transaction 
recovery command/);
+      assert.deepStrictEqual(stream.writes, []);
+    });
+
+    it('answers a verify message command with NOT_IMPLEMENTED and the same 
nonce', async () => {
+      const { stream } = await sessionHarness();
+      stream.receive(new TelemetryCommand().setVerifyMessageCommand(new 
VerifyMessageCommand().setNonce('nonce-1')));
+      assert.strictEqual(stream.writes.length, 1);
+      assert.strictEqual(stream.writes[0].getStatus()?.getCode(), 
Code.NOT_IMPLEMENTED);
+      
assert.strictEqual(stream.writes[0].getVerifyMessageResult()?.getNonce(), 
'nonce-1');
+    });
+
+    it('answers a print thread stack trace command with process diagnostics', 
async () => {
+      const { stream } = await sessionHarness();
+      stream.receive(new TelemetryCommand()
+        .setPrintThreadStackTraceCommand(new 
PrintThreadStackTraceCommand().setNonce('nonce-2')));
+      assert.strictEqual(stream.writes.length, 1);
+      assert.strictEqual(stream.writes[0].getStatus()?.getCode(), Code.OK);
+      assert.strictEqual(stream.writes[0].getThreadStackTrace()?.getNonce(), 
'nonce-2');
+      
assert.match(stream.writes[0].getThreadStackTrace()?.getThreadStackTrace() ?? 
'', /^Process: pid=/);
+    });
+
+    it('only logs an unknown command carrying an OK status', async () => {
+      const { client, stream, logger } = await sessionHarness();
+      const onUnknown = sinon.spy(client, 'onUnknownCommand');
+      stream.receive(new TelemetryCommand().setStatus(buildStatus()));
+      sinon.assert.calledOnce(onUnknown);
+      sinon.assert.calledWithMatch(logger.warn, /unrecognized command/);
+      sinon.assert.neverCalledWithMatch(logger.error, /error status/);
+    });
+  });
+
+  describe('message interceptor', () => {
+    it('warns and ignores an interceptor added while running', async () => {
+      const harness = createHarness({ topics: [ 'topic-a' ] });
+      harness.rpc.queryRoute.resolves(routeResponse(BROKER_A));
+      await startClient(harness, clock);
+      const interceptor: MessageInterceptor = { doBefore: sinon.spy(), 
doAfter: sinon.spy() };
+
+      harness.client.addMessageInterceptor(interceptor);
+      harness.client.doBefore(new 
MessageInterceptorContextImpl(MessageHookPoints.SEND), []);
+
+      sinon.assert.notCalled(interceptor.doBefore as sinon.SinonSpy);
+      sinon.assert.calledWithMatch(harness.logger.warn, /Message interceptor 
can only be added before/);
+      await harness.client.shutdown();
+    });
+
+    it('accepts an interceptor added before startup', () => {
+      const harness = createHarness();
+      const interceptor: MessageInterceptor = { doBefore: sinon.spy(), 
doAfter: sinon.spy() };
+      harness.client.addMessageInterceptor(interceptor);
+      harness.client.doBefore(new 
MessageInterceptorContextImpl(MessageHookPoints.SEND), []);
+      sinon.assert.calledOnce(interceptor.doBefore as sinon.SinonSpy);
+    });
+  });
+});
+
+describe('ClientId', () => {
+  it('follows the Java layout and increases within the process', () => {
+    const first = ClientId.create();
+    const second = ClientId.create();
+    const pattern = /^(.+)@(\d+)@(\d+)@([0-9a-z]+)$/;
+    const current = pattern.exec(first)!;
+    const next = pattern.exec(second)!;
+    assert.deepStrictEqual(current.slice(1, 3), [ hostname(), 
String(process.pid) ]);
+    assert.strictEqual(Number(next[3]), Number(current[3]) + 1);
+    assert.notStrictEqual(first, second);
+  });
+});
diff --git a/nodejs/test/client/RpcClient.test.ts 
b/nodejs/test/client/RpcClient.test.ts
index aae27e86..0309cd79 100644
--- a/nodejs/test/client/RpcClient.test.ts
+++ b/nodejs/test/client/RpcClient.test.ts
@@ -16,6 +16,8 @@
  */
 
 import { strict as assert } from 'node:assert';
+import { Readable } from 'node:stream';
+import * as sinon from 'sinon';
 import {
   Server,
   ServerCredentials,
@@ -24,7 +26,7 @@ import {
   sendUnaryData,
   Metadata,
 } from '@grpc/grpc-js';
-import { MessagingServiceService } from 
'../../proto/apache/rocketmq/v2/service_grpc_pb';
+import { MessagingServiceClient, MessagingServiceService } from 
'../../proto/apache/rocketmq/v2/service_grpc_pb';
 import { TelemetryCommand, HeartbeatRequest, HeartbeatResponse } from 
'../../proto/apache/rocketmq/v2/service_pb';
 import { Code, Status } from '../../proto/apache/rocketmq/v2/definition_pb';
 import { RpcClient } from '../../src/client/RpcClient';
@@ -148,3 +150,73 @@ describe('test/client/RpcClient.test.ts', () => {
     }
   });
 });
+
+describe('RpcClient call options', () => {
+  const unaryMethods = [
+    'queryRoute', 'heartbeat', 'sendMessage', 'queryAssignment', 'ackMessage',
+    'forwardMessageToDeadLetterQueue', 'updateOffset', 'getOffset', 
'queryOffset',
+    'endTransaction', 'notifyClientTermination', 'changeInvisibleDuration',
+    'recallMessage', 'syncLiteSubscription',
+  ] as const;
+  const streamingMethods = [ 'receiveMessage', 'pullMessage' ] as const;
+  const current = {} as { clock: sinon.SinonFakeTimers; client: RpcClient };
+
+  beforeEach(() => {
+    current.clock = sinon.useFakeTimers({ now: 1000000 });
+    current.client = new RpcClient(new Endpoints('127.0.0.1:8081'), false);
+  });
+
+  afterEach(() => {
+    current.client.close();
+    current.clock.restore();
+    sinon.restore();
+  });
+
+  function callOf(method: string) {
+    return (current.client as any)[method].bind(current.client);
+  }
+
+  for (const method of unaryMethods) {
+    it(`${method} sets the deadline and passes the response and the error 
through`, async () => {
+      const response = { method };
+      const failure = new Error(`${method} failed`);
+      const stub = sinon.stub(MessagingServiceClient.prototype, method as 
never) as sinon.SinonStub;
+      stub.onFirstCall().callsFake((_req, _md, _options, callback) => 
callback(null, response));
+      stub.onSecondCall().callsFake((_req, _md, _options, callback) => 
callback(failure));
+      const call = callOf(method);
+
+      assert.strictEqual(await call({}, new Metadata(), 3000), response);
+      assert.deepStrictEqual(stub.firstCall.args[2], { deadline: 1000000 + 
3000 });
+      await assert.rejects(call({}, new Metadata(), 5000), err => err === 
failure);
+      assert.deepStrictEqual(stub.secondCall.args[2], { deadline: 1000000 + 
5000 });
+    });
+  }
+
+  for (const method of streamingMethods) {
+    it(`${method} sets the deadline, collects every response and passes the 
error through`, async () => {
+      const failure = new Error(`${method} failed`);
+      const stub = sinon.stub(MessagingServiceClient.prototype, method as 
never) as sinon.SinonStub;
+      stub.onFirstCall().returns(Readable.from([ 'r1', 'r2' ]));
+      stub.onSecondCall().returns(new Readable({
+        objectMode: true,
+        read() {
+          this.destroy(failure);
+        },
+      }));
+      const call = callOf(method);
+
+      assert.deepStrictEqual(await call({}, new Metadata(), 3000), [ 'r1', 
'r2' ]);
+      assert.deepStrictEqual(stub.firstCall.args[2], { deadline: 1000000 + 
3000 });
+      await assert.rejects(call({}, new Metadata(), 3000), err => err === 
failure);
+    });
+  }
+
+  it('tracks the idle duration from the last call', async () => {
+    const stub = sinon.stub(MessagingServiceClient.prototype, 'heartbeat' as 
never) as sinon.SinonStub;
+    stub.callsFake((_req, _md, _options, callback) => callback(null, {}));
+    current.clock.tick(5000);
+    assert.strictEqual(current.client.idleDuration(), 5000);
+    await current.client.heartbeat(new HeartbeatRequest(), new Metadata(), 
3000);
+    assert.strictEqual(current.client.idleDuration(), 0);
+  });
+});
diff --git a/nodejs/test/client/RpcClientManager.test.ts 
b/nodejs/test/client/RpcClientManager.test.ts
new file mode 100644
index 00000000..cbfad23e
--- /dev/null
+++ b/nodejs/test/client/RpcClientManager.test.ts
@@ -0,0 +1,157 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { strict as assert } from 'node:assert';
+import { format } from 'node:util';
+import * as sinon from 'sinon';
+import { Metadata } from '@grpc/grpc-js';
+import { HeartbeatRequest, HeartbeatResponse } from 
'../../proto/apache/rocketmq/v2/service_pb';
+import type { BaseClient } from '../../src/client/BaseClient';
+import { Producer } from '../../src/producer';
+import { RpcClient } from '../../src/client/RpcClient';
+import { RpcClientManager } from '../../src/client/RpcClientManager';
+import { Endpoints } from '../../src/route';
+import { createSilentLogger } from '../support/fakes';
+
+const BROKER_A = new Endpoints('127.0.0.1:8081');
+const BROKER_B = new Endpoints('127.0.0.1:8082');
+
+function createManager() {
+  const logger = createSilentLogger();
+  const baseClient = {
+    clientId: 'test-client-id',
+    sslEnabled: false,
+    getRequestMetadata: () => new Metadata(),
+  } as unknown as BaseClient;
+  return { manager: new RpcClientManager(baseClient, logger), logger };
+}
+
+describe('RpcClientManager', () => {
+  let heartbeatTargets: RpcClient[];
+
+  beforeEach(() => {
+    heartbeatTargets = [];
+    sinon.stub(RpcClient.prototype, 'heartbeat').callsFake(async 
function(this: RpcClient) {
+      heartbeatTargets.push(this);
+      return new HeartbeatResponse();
+    });
+    sinon.stub(RpcClient.prototype, 'close');
+  });
+
+  afterEach(() => sinon.restore());
+
+  it('does not keep the process alive with its idle check timer', () => {
+    const setIntervalSpy = sinon.spy(global, 'setInterval');
+    const { manager } = createManager();
+    try {
+      sinon.assert.calledOnce(setIntervalSpy);
+      const timer = setIntervalSpy.firstCall.returnValue as unknown as 
NodeJS.Timeout;
+      assert.strictEqual(timer.hasRef(), false);
+    } finally {
+      manager.close();
+    }
+  });
+
+  it('does not keep the process alive for a client that is constructed but 
never started', () => {
+    const setIntervalSpy = sinon.spy(global, 'setInterval');
+    const producer = new Producer({ endpoints: '127.0.0.1:8081', namespace: 
'', logger: createSilentLogger() });
+    try {
+      const timers = setIntervalSpy.returnValues as unknown as 
NodeJS.Timeout[];
+      assert.ok(timers.length > 0);
+      assert.ok(timers.every(timer => !timer.hasRef()), 'a never-started 
client must not hold a referenced interval');
+    } finally {
+      producer.getRpcClientManager().close();
+    }
+  });
+
+  it('reuses one RpcClient per endpoints facade', async () => {
+    const { manager } = createManager();
+    await manager.heartbeat(BROKER_A, new HeartbeatRequest(), 3000);
+    await manager.heartbeat(new Endpoints('127.0.0.1:8081'), new 
HeartbeatRequest(), 3000);
+    await manager.heartbeat(BROKER_B, new HeartbeatRequest(), 3000);
+    assert.strictEqual(heartbeatTargets[0], heartbeatTargets[1]);
+    assert.notStrictEqual(heartbeatTargets[0], heartbeatTargets[2]);
+    manager.close();
+  });
+
+  it('rebuilds the RpcClient after evict', async () => {
+    const { manager } = createManager();
+    await manager.heartbeat(BROKER_A, new HeartbeatRequest(), 3000);
+    manager.evict(BROKER_A);
+    sinon.assert.calledOnce(RpcClient.prototype.close as sinon.SinonStub);
+    manager.evict(BROKER_A);
+    sinon.assert.calledOnce(RpcClient.prototype.close as sinon.SinonStub);
+    await manager.heartbeat(BROKER_A, new HeartbeatRequest(), 3000);
+    assert.notStrictEqual(heartbeatTargets[0], heartbeatTargets[1]);
+    manager.close();
+  });
+
+  it('rejects every call after close and tolerates a repeated close', async () 
=> {
+    const { manager } = createManager();
+    await manager.heartbeat(BROKER_A, new HeartbeatRequest(), 3000);
+    manager.close();
+    manager.close();
+    sinon.assert.calledOnce(RpcClient.prototype.close as sinon.SinonStub);
+    await assert.rejects(manager.heartbeat(BROKER_A, new HeartbeatRequest(), 
3000), /already closed/);
+    assert.throws(() => manager.telemetry(BROKER_A, new Metadata()), /already 
closed/);
+  });
+
+  it('delegates every RPC to the RpcClient with fresh request metadata', async 
() => {
+    const methods = [
+      'queryRoute', 'sendMessage', 'queryAssignment', 'receiveMessage', 
'ackMessage',
+      'forwardMessageToDeadLetterQueue', 'pullMessage', 'updateOffset', 
'getOffset', 'queryOffset',
+      'endTransaction', 'changeInvisibleDuration', 'notifyClientTermination', 
'recallMessage',
+      'syncLiteSubscription',
+    ] as const;
+    const { manager } = createManager();
+    for (const method of methods) {
+      const response = { method };
+      const stub = sinon.stub(RpcClient.prototype, method).resolves(response 
as never);
+      const request = {};
+      assert.strictEqual(await (manager as any)[method](BROKER_A, request, 
3000), response);
+      sinon.assert.calledOnce(stub);
+      assert.strictEqual(stub.firstCall.args[0], request);
+      assert.ok(stub.firstCall.args[1] instanceof Metadata);
+      assert.strictEqual(stub.firstCall.args[2], 3000);
+    }
+    const stream = {};
+    const telemetry = sinon.stub(RpcClient.prototype, 
'telemetry').returns(stream as never);
+    const metadata = new Metadata();
+    assert.strictEqual(manager.telemetry(BROKER_A, metadata), stream);
+    sinon.assert.calledOnceWithExactly(telemetry, metadata);
+    manager.close();
+  });
+
+  it('closes clients idle beyond the threshold and logs the real idle 
duration', async () => {
+    const clock = sinon.useFakeTimers();
+    try {
+      const { manager, logger } = createManager();
+      await manager.heartbeat(BROKER_A, new HeartbeatRequest(), 3000);
+      clock.tick(30 * 60000);
+      sinon.assert.notCalled(RpcClient.prototype.close as sinon.SinonStub);
+      clock.tick(60000);
+      sinon.assert.calledOnce(RpcClient.prototype.close as sinon.SinonStub);
+      const line = format(...logger.info.lastCall.args as [ string, 
...unknown[] ]);
+      assert.match(line, /endpoints=127\.0\.0\.1:8081, idleDuration=\d+ms, 
maxIdleDuration=1800000ms, clientId=test-client-id$/);
+      await manager.heartbeat(BROKER_A, new HeartbeatRequest(), 3000);
+      assert.notStrictEqual(heartbeatTargets[0], heartbeatTargets[1], 'a 
reclaimed client is rebuilt on next use');
+      manager.close();
+    } finally {
+      clock.restore();
+    }
+  });
+});
diff --git a/nodejs/test/client/TelemetrySession.test.ts 
b/nodejs/test/client/TelemetrySession.test.ts
index 538cfcee..9c0846ac 100644
--- a/nodejs/test/client/TelemetrySession.test.ts
+++ b/nodejs/test/client/TelemetrySession.test.ts
@@ -28,10 +28,16 @@
 
 import * as assert from 'node:assert';
 import { EventEmitter } from 'node:events';
+import * as sinon from 'sinon';
+import { Metadata, Server, ServerCredentials, ServerDuplexStream, status as 
GrpcStatus } from '@grpc/grpc-js';
 import { TelemetrySession } from '../../src/client/TelemetrySession';
+import { RpcClient } from '../../src/client/RpcClient';
+import { MessagingServiceService } from 
'../../proto/apache/rocketmq/v2/service_grpc_pb';
 import { TelemetryCommand } from '../../proto/apache/rocketmq/v2/service_pb';
 import { Endpoints } from '../../src/route';
 import { ILogger } from '../../src/client/Logger';
+import { createSilentLogger, FakeTelemetryStream } from '../support/fakes';
+import { buildSettings } from '../support/protobuf';
 
 function makeFakeStream() {
   const stream: any = new EventEmitter();
@@ -132,4 +138,144 @@ describe('TelemetrySession reconnect', () => {
       'settings must be synced on the refreshed stream');
     session.release();
   });
+
+  it('keeps the reconnect backoff at 1s while the stream keeps delivering data 
before failing', async () => {
+    const clock = sinon.useFakeTimers();
+    try {
+      const streams: FakeTelemetryStream[] = [];
+      const baseClient: any = {
+        clientId: 'test-client',
+        settingsCommand: () => new TelemetryCommand(),
+        onSettingsCommand: () => undefined,
+        createTelemetryStream: () => {
+          const stream = new FakeTelemetryStream();
+          streams.push(stream);
+          return stream.asGrpcStream();
+        },
+      };
+      const session = new TelemetrySession(baseClient, new 
Endpoints('127.0.0.1:8081'), createSilentLogger());
+      for (let round = 1; round <= 3; round++) {
+        streams[round - 1].receive(new 
TelemetryCommand().setSettings(buildSettings()));
+        streams[round - 1].fail(new Error('stream broken'));
+        await clock.tickAsync(999);
+        assert.strictEqual(streams.length, round, 'reconnect must not happen 
before the 1s backoff');
+        await clock.tickAsync(1);
+        assert.strictEqual(streams.length, round + 1, 'reconnect must happen 
after the 1s backoff');
+      }
+      session.release();
+    } finally {
+      clock.restore();
+    }
+  });
+});
+
+describe('TelemetrySession released stream', () => {
+  function makeClient(streams: FakeTelemetryStream[], overrides: 
Record<string, unknown> = {}) {
+    return {
+      clientId: 'test-client',
+      settingsCommand: () => new TelemetryCommand(),
+      createTelemetryStream: () => {
+        const stream = new FakeTelemetryStream();
+        streams.push(stream);
+        return stream.asGrpcStream();
+      },
+      ...overrides,
+    } as any;
+  }
+
+  it('drops writes after release instead of raising an unhandled stream 
error', async () => {
+    const streams: FakeTelemetryStream[] = [];
+    const logger = createSilentLogger();
+    const session = new TelemetrySession(makeClient(streams), new 
Endpoints('127.0.0.1:8081'), logger);
+    session.release();
+    session.syncSettings();
+    session.write(new TelemetryCommand());
+    await sleep(20);
+    assert.strictEqual(streams.length, 1, 'a released session must not reopen 
a stream');
+    assert.deepStrictEqual(streams[0].writes, [], 'nothing may reach the ended 
stream');
+    sinon.assert.called(logger.warn);
+  });
+
+  it('drops writes during the reconnect backoff instead of writing to the 
ended stream', async () => {
+    const clock = sinon.useFakeTimers();
+    try {
+      const streams: FakeTelemetryStream[] = [];
+      const session = new TelemetrySession(makeClient(streams), new 
Endpoints('127.0.0.1:8081'), createSilentLogger());
+      streams[0].fail(new Error('stream broken'));
+      session.write(new TelemetryCommand());
+      await clock.tickAsync(0);
+      assert.deepStrictEqual(streams[0].writes, [], 'the ended stream must not 
receive writes');
+      await clock.tickAsync(1000);
+      assert.strictEqual(streams.length, 2, 'reconnect must still happen after 
the dropped write');
+      assert.strictEqual(streams[1].writes.length, 1, 'settings must be synced 
on the renewed stream');
+      session.release();
+    } finally {
+      clock.restore();
+    }
+  });
+
+  it('logs instead of throwing when a command handler fails', () => {
+    const streams: FakeTelemetryStream[] = [];
+    const logger = createSilentLogger();
+    const client = makeClient(streams, {
+      onSettingsCommand: () => {
+        throw new Error('handler failure');
+      },
+    });
+    const session = new TelemetrySession(client, new 
Endpoints('127.0.0.1:8081'), logger);
+    assert.doesNotThrow(() => streams[0].receive(new 
TelemetryCommand().setSettings(buildSettings())));
+    sinon.assert.calledWithMatch(logger.error, /\[Bug\]/);
+    session.release();
+  });
+
+  describe('with a real gRPC stream', () => {
+    let server: Server;
+    let port: number;
+
+    before(async () => {
+      server = new Server();
+      server.addService(MessagingServiceService, {
+        telemetry(call: ServerDuplexStream<TelemetryCommand, 
TelemetryCommand>) {
+          call.on('data', () => undefined);
+          // Answer the client half-close with a non-OK status, as a remote
+          // that is going away would.
+          call.on('end', () => call.emit('error', { code: 
GrpcStatus.UNAVAILABLE, details: 'remote is going away' }));
+        },
+      } as any);
+      port = await new Promise<number>((resolve, reject) => {
+        server.bindAsync('127.0.0.1:0', ServerCredentials.createInsecure(), 
(err, boundPort) => {
+          if (err) return reject(err);
+          resolve(boundPort);
+        });
+      });
+    });
+
+    after(() => {
+      server.forceShutdown();
+    });
+
+    it('swallows the remote error status that arrives after release', async () 
=> {
+      const endpoints = new Endpoints(`127.0.0.1:${port}`);
+      const rpcClient = new RpcClient(endpoints, false);
+      const uncaught: unknown[] = [];
+      const listeners = process.listeners('uncaughtException');
+      process.removeAllListeners('uncaughtException');
+      process.on('uncaughtException', err => uncaught.push(err));
+      try {
+        const client = makeClient([], { createTelemetryStream: () => 
rpcClient.telemetry(new Metadata()) });
+        const session = new TelemetrySession(client, endpoints, 
createSilentLogger());
+        session.syncSettings();
+        await sleep(100);
+        session.release();
+        await sleep(200);
+      } finally {
+        process.removeAllListeners('uncaughtException');
+        for (const listener of listeners) {
+          process.on('uncaughtException', listener);
+        }
+        rpcClient.close();
+      }
+      assert.deepStrictEqual(uncaught, [], 'a status error after release must 
not become an uncaught exception');
+    });
+  });
 });

Reply via email to