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 b992f437 fix(nodejs): retry telemetry stream renewal with backoff 
instead of dying on failure (#1490)
b992f437 is described below

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

    fix(nodejs): retry telemetry stream renewal with backoff instead of dying 
on failure (#1490)
    
    - TelemetrySession: wrap the reconnect timer callback in try/catch and 
reschedule with exponential backoff (1s..60s), so a transient stream-creation 
failure no longer escapes as an uncaughtException that permanently ends the 
reconnect loop
    - Reset the backoff once inbound data proves the stream alive
    - refresh(): schedule a background retry when the renewal fails instead of 
leaving the session dead
    - Add regression tests in test/client/TelemetrySession.test.ts
---
 nodejs/src/client/TelemetrySession.ts       |  32 ++++++-
 nodejs/test/client/TelemetrySession.test.ts | 136 ++++++++++++++++++++++++++++
 2 files changed, 163 insertions(+), 5 deletions(-)

diff --git a/nodejs/src/client/TelemetrySession.ts 
b/nodejs/src/client/TelemetrySession.ts
index 782481fb..b9dbebfe 100644
--- a/nodejs/src/client/TelemetrySession.ts
+++ b/nodejs/src/client/TelemetrySession.ts
@@ -29,6 +29,9 @@ export class TelemetrySession {
   #isRefreshing = false;
   #released = false;
   #reconnectTimer?: NodeJS.Timeout;
+  // Consecutive failed reconnect attempts, driving the exponential backoff
+  // delay; reset once the stream is proven alive by inbound data.
+  #reconnectAttempts = 0;
 
   constructor(baseClient: BaseClient, endpoints: Endpoints, logger: ILogger) {
     this.#endpoints = endpoints;
@@ -93,6 +96,9 @@ export class TelemetrySession {
     } catch (err) {
       this.#logger.error('Failed to refresh telemetry session, endpoints=%s, 
clientId=%s, error=%s',
         this.#endpoints, this.#baseClient.clientId, err);
+      // The stream is gone and the renewal failed; keep retrying in the
+      // background instead of leaving the session permanently dead.
+      this.#scheduleRenewStream();
     } finally {
       this.#isRefreshing = false;
     }
@@ -119,6 +125,8 @@ export class TelemetrySession {
   }
 
   #onData(command: TelemetryCommand) {
+    // Inbound data proves the stream is alive: reset the reconnect backoff.
+    this.#reconnectAttempts = 0;
     const endpoints = this.#endpoints;
     const clientId = this.#baseClient.clientId;
     const commandCase = command.getCommandCase();
@@ -169,21 +177,35 @@ export class TelemetrySession {
   }
 
   /**
-   * Schedule a telemetry stream renewal. The timer is tracked so that it can
-   * be cancelled on release(), and a pending timer doubles as a guard to
-   * prevent error/end events from scheduling duplicate reconnects.
+   * Schedule a telemetry stream renewal with exponential backoff (1s, 2s,
+   * 4s, ... capped at 60s). The timer is tracked so that it can be cancelled
+   * on release(), and a pending timer doubles as a guard to prevent
+   * error/end events from scheduling duplicate reconnects.
    */
   #scheduleRenewStream() {
     if (this.#released || this.#reconnectTimer) {
       return;
     }
+    const delay = Math.min(1000 * 2 ** this.#reconnectAttempts, 60000);
+    this.#reconnectAttempts++;
     this.#reconnectTimer = setTimeout(() => {
       this.#reconnectTimer = undefined;
       if (this.#released) {
         return;
       }
-      this.#renewStream(false);
-    }, 1000);
+      try {
+        this.#renewStream(false);
+      } catch (err) {
+        // Never rethrow here: an exception escaping a timer callback becomes
+        // an uncaughtException, and without this catch a single transient
+        // stream-creation failure would permanently end the reconnect loop
+        // and the session would never be able to re-register settings.
+        this.#logger.error('Failed to renew telemetry stream, will retry, 
endpoints=%s, clientId=%s, attempt=%d, error=%s',
+          this.#endpoints, this.#baseClient.clientId, this.#reconnectAttempts,
+          err instanceof Error ? err.message : String(err));
+        this.#scheduleRenewStream();
+      }
+    }, delay);
   }
 
   #onError(err: Error) {
diff --git a/nodejs/test/client/TelemetrySession.test.ts 
b/nodejs/test/client/TelemetrySession.test.ts
new file mode 100644
index 00000000..76466b99
--- /dev/null
+++ b/nodejs/test/client/TelemetrySession.test.ts
@@ -0,0 +1,136 @@
+/**
+ * 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.
+ */
+
+/**
+ * Regression tests for the telemetry reconnect loop.
+ *
+ * The reconnect timer callback used to call #renewStream(false) unguarded;
+ * since #renewStream rethrows stream-creation failures, a single transient
+ * failure escaped the setTimeout callback as an uncaughtException and
+ * permanently ended the reconnect loop — the session could never re-register
+ * settings afterwards. The callback now catches failures and reschedules with
+ * exponential backoff until release().
+ */
+
+import { describe, it } from 'node:test';
+import * as assert from 'node:assert';
+import { EventEmitter } from 'node:events';
+import { TelemetrySession } from '../../src/client/TelemetrySession';
+import { TelemetryCommand } from '../../proto/apache/rocketmq/v2/service_pb';
+import { Endpoints } from '../../src/route';
+import { ILogger } from '../../src/client/Logger';
+
+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;
+}
+
+function makeFakeLogger(): ILogger & { errors: string[] } {
+  const errors: string[] = [];
+  return {
+    errors,
+    info: () => undefined,
+    warn: () => undefined,
+    error: (msg: string) => { errors.push(msg); },
+    debug: () => undefined,
+  } as never;
+}
+
+interface HarnessOptions {
+  // Stream creation fails this many times before succeeding
+  failures: number;
+}
+
+function makeHarness(options: HarnessOptions) {
+  const streams: any[] = [];
+  let remainingFailures = options.failures;
+  let calls = 0;
+  const settingsCommand = new TelemetryCommand();
+  const baseClient: any = {
+    clientId: 'test-client',
+    sslEnabled: false,
+    settingsCommand: () => settingsCommand,
+    createTelemetryStream: () => {
+      calls++;
+      // The very first call (constructor) always succeeds; failures are
+      // injected into subsequent reconnect attempts only.
+      if (calls > 1 && remainingFailures > 0) {
+        remainingFailures--;
+        throw new Error('transient stream creation failure');
+      }
+      const stream = makeFakeStream();
+      streams.push(stream);
+      return stream;
+    },
+  };
+  return { baseClient, streams, settingsCommand };
+}
+
+const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
+
+describe('TelemetrySession reconnect', () => {
+  it('keeps retrying with backoff after transient stream-creation failures and 
re-syncs settings', async () => {
+    const harness = makeHarness({ failures: 1 });
+    const session = new TelemetrySession(harness.baseClient, new 
Endpoints('127.0.0.1:8081'), makeFakeLogger());
+    assert.strictEqual(harness.streams.length, 1, 'initial stream should be 
created');
+
+    // Stream error triggers the reconnect loop; the next creation attempt
+    // fails transiently and must be retried instead of ending the loop.
+    harness.streams[0].emit('error', new Error('stream broken'));
+
+    // Backoff: first retry after ~1s fails, second retry after ~2s succeeds.
+    await sleep(3600);
+
+    assert.strictEqual(harness.streams.length, 2,
+      'reconnect loop must survive the transient failure and establish a new 
stream');
+    assert.ok(harness.streams[1].writes.includes(harness.settingsCommand),
+      'settings must be re-synced on the new stream');
+    session.release();
+  });
+
+  it('release() cancels a pending reconnect', async () => {
+    const harness = makeHarness({ failures: 0 });
+    const session = new TelemetrySession(harness.baseClient, new 
Endpoints('127.0.0.1:8081'), makeFakeLogger());
+    harness.streams[0].emit('error', new Error('stream broken'));
+    session.release();
+
+    await sleep(1300);
+    assert.strictEqual(harness.streams.length, 1, 'no reconnect may happen 
after release');
+  });
+
+  it('refresh() schedules a retry when the renewal fails', async () => {
+    const harness = makeHarness({ failures: 1 });
+    const session = new TelemetrySession(harness.baseClient, new 
Endpoints('127.0.0.1:8081'), makeFakeLogger());
+
+    // refresh closes the current stream and renews; the renewal fails once
+    // and must be retried in the background instead of leaving the session 
dead.
+    session.refresh();
+    await sleep(1300);
+
+    assert.strictEqual(harness.streams.length, 2,
+      'refresh failure must be followed by a background retry');
+    assert.ok(harness.streams[1].writes.includes(harness.settingsCommand),
+      'settings must be synced on the refreshed stream');
+    session.release();
+  });
+});

Reply via email to