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 f7293cf5 fix(nodejs): bound the startup wait for first settings and
clean up on failure (#1492)
f7293cf5 is described below
commit f7293cf57916aaeec6048bd8c0cb20f990d5ac70
Author: Quan <[email protected]>
AuthorDate: Wed Nov 11 10:44:07 2026 +0800
fix(nodejs): bound the startup wait for first settings and clean up on
failure (#1492)
- BaseClient: bound the wait for the first server-pushed Settings command
with an internal 30s limit (no public API surface change); on timeout or any
startup error, run the full shutdown cleanup (timers, telemetry sessions, RPC
manager) before rejecting, mirroring Java PushConsumerImpl#startUp which calls
shutDown() before rethrowing
- Previously a silent remote left startup() pending forever while the
route/settings/heartbeat timers kept running, leaking the instance and its
heartbeat traffic
- PushConsumer: startup failure now runs the full shutdown instead of only
clearing the scan timer
- Extend BaseClient.test.ts: startup rejects within the timeout and
releases resources when settings never arrive; settings arriving within the
timeout still complete startup without triggering cleanup
Co-authored-by: 通融 <[email protected]>
---
nodejs/src/client/BaseClient.ts | 48 ++++++++++++++++++++++-
nodejs/src/consumer/PushConsumer.ts | 10 +++++
nodejs/test/client/BaseClient.test.ts | 72 ++++++++++++++++++++++++++++++++++-
3 files changed, 126 insertions(+), 4 deletions(-)
diff --git a/nodejs/src/client/BaseClient.ts b/nodejs/src/client/BaseClient.ts
index f48c84d6..42db765d 100644
--- a/nodejs/src/client/BaseClient.ts
+++ b/nodejs/src/client/BaseClient.ts
@@ -63,6 +63,12 @@ const debug =
debuglog('rocketmq-client-nodejs:client:BaseClient');
const HEARTBEAT_TRANSPORT_RECOVERY_THRESHOLD = 2;
// Minimum interval between transport-recovery attempts per endpoints
const TRANSPORT_RECOVERY_COOLDOWN = 30 * 1000;
+// Default bound for waiting the server-pushed Settings command during startup.
+// Java's startUp does not wait for settings at all; Node keeps the wait so
+// consumers see server-provided settings before startup() resolves, but the
+// wait must be bounded so a silent remote makes startup() reject (notifying
+// the caller) instead of hanging forever.
+const DEFAULT_FIRST_SETTINGS_TIMEOUT = 30 * 1000;
export interface BaseClientOptions {
sslEnabled?: boolean;
@@ -102,6 +108,10 @@ export abstract class BaseClient {
protected readonly endpoints: Endpoints;
protected readonly isolated = new Map<string, Endpoints>();
protected readonly requestTimeout: number;
+ // Internal-only bound for the startup wait on the first server-pushed
+ // Settings command. Deliberately NOT part of BaseClientOptions so the
+ // public API surface stays unchanged; tests may override it via a cast.
+ private firstSettingsTimeoutMs = DEFAULT_FIRST_SETTINGS_TIMEOUT;
protected readonly topics = new Set<string>();
protected readonly topicRouteCache = new Map<string, TopicRouteData>();
// In-flight route query futures to avoid duplicate queries for the same
topic
@@ -190,6 +200,17 @@ export abstract class BaseClient {
const err = new Error(`Startup the rocketmq client failed,
clientId=${this.clientId}, error=${e}`);
this.logger.error(err);
err.cause = e;
+ // Release everything acquired by the failed startup before surfacing
+ // the error, mirroring Java PushConsumerImpl#startUp which calls
+ // shutDown() before rethrowing. Otherwise the route/settings/heartbeat
+ // timers and telemetry sessions keep running on an instance whose
+ // startup() rejected and which the caller is about to abandon.
+ try {
+ await this.shutdown();
+ } catch (cleanupError) {
+ this.logger.warn('Failed to clean up after the startup failure,
clientId=%s, error=%s',
+ this.clientId, cleanupError instanceof Error ? cleanupError.message
: String(cleanupError));
+ }
throw err;
}
this.logger.info('Startup the rocketmq client successfully, clientId=%s',
this.clientId);
@@ -283,8 +304,9 @@ export abstract class BaseClient {
// doStats()
if (firstSettingsPromise) {
- this.logger.info('Waiting for first onSettingsCommand, clientId=%s',
this.clientId);
- await firstSettingsPromise;
+ this.logger.info('Waiting for first onSettingsCommand, clientId=%s,
timeout=%dms',
+ this.clientId, this.firstSettingsTimeoutMs);
+ await this.#awaitFirstSettings(firstSettingsPromise);
this.logger.info('Received first onSettingsCommand, clientId=%s',
this.clientId);
}
this.#running = true;
@@ -301,6 +323,28 @@ export abstract class BaseClient {
return this.#running;
}
+ /**
+ * Bound the wait for the first server-pushed Settings command so a silent
+ * remote makes startup() reject with a clear error instead of hanging
+ * forever; the rejection also triggers the startup cleanup path.
+ */
+ async #awaitFirstSettings(firstSettingsPromise: Promise<void>):
Promise<void> {
+ let timer: NodeJS.Timeout | undefined;
+ try {
+ const timeoutPromise = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error(
+ `Timed out waiting for the first settings command within
${this.firstSettingsTimeoutMs}ms, ` +
+ `clientId=${this.clientId}`,
+ )), this.firstSettingsTimeoutMs);
+ });
+ await Promise.race([ firstSettingsPromise, timeoutPromise ]);
+ } finally {
+ if (timer) {
+ clearTimeout(timer);
+ }
+ }
+ }
+
protected sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
diff --git a/nodejs/src/consumer/PushConsumer.ts
b/nodejs/src/consumer/PushConsumer.ts
index 8d39543a..e4981786 100644
--- a/nodejs/src/consumer/PushConsumer.ts
+++ b/nodejs/src/consumer/PushConsumer.ts
@@ -140,6 +140,16 @@ export class PushConsumer extends Consumer {
clearInterval(this.#scanAssignmentTimer);
this.#scanAssignmentTimer = undefined;
}
+ // Full shutdown before rethrowing, mirroring Java
PushConsumerImpl#startUp
+ // (`shutDown(); throw t;`), so a failed startup never leaves base-client
+ // timers or telemetry sessions behind. Idempotent when super.startup()
+ // already cleaned up after its own failure.
+ try {
+ await this.shutdown();
+ } catch (cleanupError) {
+ this.logger.warn('Failed to clean up after the startup failure,
clientId=%s, error=%s',
+ this.clientId, cleanupError instanceof Error ? cleanupError.message
: String(cleanupError));
+ }
throw err;
}
}
diff --git a/nodejs/test/client/BaseClient.test.ts
b/nodejs/test/client/BaseClient.test.ts
index 7e441f93..544175a2 100644
--- a/nodejs/test/client/BaseClient.test.ts
+++ b/nodejs/test/client/BaseClient.test.ts
@@ -18,10 +18,15 @@
/**
* Regression tests for the startup first-settings promise:
* - a server-pushed Settings arriving while route updates are still pending
- * must complete startup (no 5-minute hang), and
+ * must complete startup (no 5-minute hang),
* - a status-only telemetry error arriving in the same window must reject
* startup() without being flagged as an unhandled rejection (which would
- * terminate the process under Node.js's default behavior).
+ * terminate the process under Node.js's default behavior), and
+ * - the wait for the first Settings is bounded: a silent remote must make
+ * startup() reject with a clear error and release every resource acquired
+ * by the failed startup (mirrors Java PushConsumerImpl#startUp which calls
+ * shutDown() before rethrowing), instead of hanging forever and leaking
+ * the route/settings/heartbeat timers.
*/
import { describe, it } from 'node:test';
@@ -260,3 +265,66 @@ describe('BaseClient heartbeat response status check', ()
=> {
await client.shutdown();
});
});
+
+describe('BaseClient startup first-settings timeout', () => {
+ function makeFakeRpcManager(state: { closeCount: number }) {
+ return {
+ queryRoute: async () => {
+ throw new Error('replaced by mockQueryRoute');
+ },
+ notifyClientTermination: async () => ({}),
+ telemetry: () => {
+ const stream: any = new EventEmitter();
+ stream.write = () => true;
+ stream.end = () => undefined;
+ return stream;
+ },
+ close: () => { state.closeCount++; },
+ };
+ }
+
+ it('rejects startup and releases resources when the first settings never
arrive', async () => {
+ const state = { closeCount: 0 };
+ const client = new TestClient({
+ endpoints: '127.0.0.1:8081',
+ namespace: 'test-namespace',
+ topics: [ 'topic-A' ],
+ });
+ // Internal-only knob (not part of the public options): shorten the
+ // first-settings wait so the test stays fast.
+ (client as any).firstSettingsTimeoutMs = 200;
+ // Stop the real RPC manager (idle-check timer) and swap in the fake.
+ (client as any).rpcClientManager.close();
+ (client as any).rpcClientManager = makeFakeRpcManager(state);
+ client.mockQueryRoute(10);
+
+ // The remote never pushes Settings: startup must reject within the
+ // timeout instead of hanging forever, and the failure path must run the
+ // full shutdown cleanup (closeCount proves it).
+ await assert.rejects(client.startup(), /Timed out waiting for the first
settings/);
+ assert.strictEqual(client.isRunning(), false);
+ assert.ok(state.closeCount >= 1,
+ 'failed startup must release the resources it acquired (rpc manager
closed)');
+ });
+
+ it('completes startup when the first settings arrive within the timeout',
async () => {
+ const state = { closeCount: 0 };
+ const client = new TestClient({
+ endpoints: '127.0.0.1:8081',
+ namespace: 'test-namespace',
+ topics: [ 'topic-A' ],
+ });
+ (client as any).firstSettingsTimeoutMs = 5000;
+ (client as any).rpcClientManager.close();
+ (client as any).rpcClientManager = makeFakeRpcManager(state);
+ client.mockQueryRoute(10);
+
+ const startupPromise = client.startup();
+ await sleep(30);
+ client.onSettingsCommand(client.getEndpoints(), new SettingsPB());
+ await startupPromise;
+ assert.strictEqual(client.isRunning(), true);
+ assert.strictEqual(state.closeCount, 0, 'successful startup must not
trigger the cleanup path');
+ await client.shutdown();
+ });
+});