rocketmq-client-nodejs 1.0.8 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +61 -0
- package/dist/client/BaseClient.d.ts +44 -1
- package/dist/client/BaseClient.js +353 -85
- package/dist/client/Logger.js +9 -6
- package/dist/client/RpcClient.js +42 -134
- package/dist/client/RpcClientManager.d.ts +22 -17
- package/dist/client/RpcClientManager.js +61 -56
- package/dist/client/TelemetrySession.js +107 -17
- package/dist/consumer/ConsumeService.d.ts +2 -1
- package/dist/consumer/ConsumeService.js +12 -6
- package/dist/consumer/ConsumeTask.d.ts +6 -1
- package/dist/consumer/ConsumeTask.js +36 -5
- package/dist/consumer/Consumer.d.ts +13 -5
- package/dist/consumer/Consumer.js +94 -33
- package/dist/consumer/FifoConsumeService.d.ts +3 -1
- package/dist/consumer/FifoConsumeService.js +4 -4
- package/dist/consumer/LiteConsumerSupport.d.ts +25 -0
- package/dist/consumer/LiteConsumerSupport.js +47 -0
- package/dist/consumer/LiteFifoConsumeService.d.ts +3 -1
- package/dist/consumer/LiteFifoConsumeService.js +4 -4
- package/dist/consumer/LitePushConsumerImpl.d.ts +15 -4
- package/dist/consumer/LitePushConsumerImpl.js +26 -30
- package/dist/consumer/LiteSimpleConsumer.d.ts +177 -0
- package/dist/consumer/LiteSimpleConsumer.js +126 -0
- package/dist/consumer/LiteSimpleConsumerImpl.d.ts +133 -0
- package/dist/consumer/LiteSimpleConsumerImpl.js +179 -0
- package/dist/consumer/LiteStandardConsumeService.d.ts +3 -1
- package/dist/consumer/LiteStandardConsumeService.js +4 -4
- package/dist/consumer/LiteSubscriptionManager.d.ts +27 -6
- package/dist/consumer/LiteSubscriptionManager.js +36 -27
- package/dist/consumer/OffsetOption.d.ts +1 -0
- package/dist/consumer/OffsetOption.js +10 -4
- package/dist/consumer/ProcessQueue.d.ts +17 -1
- package/dist/consumer/ProcessQueue.js +134 -91
- package/dist/consumer/PushConsumer.d.ts +17 -0
- package/dist/consumer/PushConsumer.js +117 -26
- package/dist/consumer/PushConsumerGaugeObserver.d.ts +33 -0
- package/dist/consumer/PushConsumerGaugeObserver.js +60 -0
- package/dist/consumer/PushSubscriptionSettings.d.ts +8 -1
- package/dist/consumer/PushSubscriptionSettings.js +35 -8
- package/dist/consumer/SimpleConsumer.d.ts +5 -0
- package/dist/consumer/SimpleConsumer.js +33 -20
- package/dist/consumer/SimpleSubscriptionSettings.js +3 -3
- package/dist/consumer/StandardConsumeService.d.ts +3 -1
- package/dist/consumer/StandardConsumeService.js +17 -8
- package/dist/consumer/SubscriptionLoadBalancer.js +3 -3
- package/dist/consumer/index.d.ts +1 -0
- package/dist/consumer/index.js +2 -1
- package/dist/exception/InternalErrorException.d.ts +1 -0
- package/dist/exception/InternalErrorException.js +3 -2
- package/dist/exception/PayloadEmptyException.d.ts +20 -0
- package/dist/exception/PayloadEmptyException.js +28 -0
- package/dist/exception/StatusChecker.js +11 -4
- package/dist/exception/index.d.ts +1 -0
- package/dist/exception/index.js +2 -1
- package/dist/exception/receiveStatus.d.ts +18 -0
- package/dist/exception/receiveStatus.js +28 -0
- package/dist/hook/Attribute.d.ts +26 -0
- package/dist/hook/Attribute.js +37 -0
- package/dist/hook/AttributeKey.d.ts +32 -0
- package/dist/hook/AttributeKey.js +43 -0
- package/dist/hook/CompositedMessageInterceptor.d.ts +32 -0
- package/dist/hook/CompositedMessageInterceptor.js +87 -0
- package/dist/hook/InflightRequestCountInterceptor.d.ts +28 -0
- package/dist/hook/InflightRequestCountInterceptor.js +44 -0
- package/dist/hook/MessageHookPoints.d.ts +54 -0
- package/dist/hook/MessageHookPoints.js +59 -0
- package/dist/hook/MessageHookPointsStatus.d.ts +24 -0
- package/dist/hook/MessageHookPointsStatus.js +29 -0
- package/dist/hook/MessageInterceptor.d.ts +34 -0
- package/dist/hook/MessageInterceptor.js +19 -0
- package/dist/hook/MessageInterceptorContext.d.ts +31 -0
- package/dist/hook/MessageInterceptorContext.js +19 -0
- package/dist/hook/MessageInterceptorContextImpl.d.ts +40 -0
- package/dist/hook/MessageInterceptorContextImpl.js +71 -0
- package/dist/hook/MessageMeterInterceptor.d.ts +39 -0
- package/dist/hook/MessageMeterInterceptor.js +149 -0
- package/dist/hook/index.d.ts +26 -0
- package/dist/hook/index.js +43 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -1
- package/dist/message/Message.js +26 -4
- package/dist/message/MessageView.js +15 -5
- package/dist/message/PublishingMessage.js +4 -4
- package/dist/metrics/ClientMeter.d.ts +42 -0
- package/dist/metrics/ClientMeter.js +75 -0
- package/dist/metrics/ClientMeterManager.d.ts +46 -0
- package/dist/metrics/ClientMeterManager.js +203 -0
- package/dist/metrics/EmptyGaugeObserver.d.ts +28 -0
- package/dist/metrics/EmptyGaugeObserver.js +34 -0
- package/dist/metrics/GaugeEnum.d.ts +32 -0
- package/dist/metrics/GaugeEnum.js +37 -0
- package/dist/metrics/GaugeObserver.d.ts +29 -0
- package/dist/metrics/GaugeObserver.js +19 -0
- package/dist/metrics/HistogramEnum.d.ts +54 -0
- package/dist/metrics/HistogramEnum.js +71 -0
- package/dist/metrics/InvocationStatus.d.ts +26 -0
- package/dist/metrics/InvocationStatus.js +33 -0
- package/dist/metrics/Metric.d.ts +30 -0
- package/dist/metrics/Metric.js +44 -0
- package/dist/metrics/MetricLabels.d.ts +27 -0
- package/dist/metrics/MetricLabels.js +34 -0
- package/dist/metrics/index.d.ts +25 -0
- package/dist/metrics/index.js +42 -0
- package/dist/producer/Producer.d.ts +8 -2
- package/dist/producer/Producer.js +83 -34
- package/dist/producer/PublishingLoadBalancer.js +11 -5
- package/dist/producer/PublishingSettings.js +1 -3
- package/dist/producer/SendReceipt.js +3 -2
- package/dist/producer/Transaction.d.ts +2 -1
- package/dist/producer/Transaction.js +9 -8
- package/dist/producer/index.d.ts +1 -0
- package/dist/producer/index.js +2 -2
- package/dist/retry/CustomizedBackoffRetryPolicy.d.ts +37 -0
- package/dist/retry/CustomizedBackoffRetryPolicy.js +72 -0
- package/dist/retry/ExponentialBackoffRetryPolicy.js +10 -6
- package/dist/retry/RetryPolicy.d.ts +1 -1
- package/dist/retry/index.d.ts +1 -0
- package/dist/retry/index.js +2 -1
- package/dist/route/Endpoints.d.ts +6 -0
- package/dist/route/Endpoints.js +69 -9
- package/dist/route/IpNameResolver.d.ts +28 -0
- package/dist/route/IpNameResolver.js +104 -0
- package/dist/route/MessageQueue.js +7 -2
- package/dist/route/TopicRouteData.d.ts +5 -0
- package/dist/route/TopicRouteData.js +22 -1
- package/dist/util/Semaphore.d.ts +47 -0
- package/dist/util/Semaphore.js +82 -0
- package/dist/util/index.d.ts +1 -1
- package/dist/util/index.js +9 -6
- package/dist/util/rpcContext.d.ts +20 -0
- package/dist/util/rpcContext.js +35 -0
- package/package.json +11 -4
- package/src/client/BaseClient.ts +392 -91
- package/src/client/Logger.ts +9 -5
- package/src/client/RpcClient.ts +62 -133
- package/src/client/RpcClientManager.ts +103 -60
- package/src/client/TelemetrySession.ts +112 -17
- package/src/consumer/ConsumeService.ts +16 -5
- package/src/consumer/ConsumeTask.ts +43 -3
- package/src/consumer/Consumer.ts +116 -35
- package/src/consumer/FifoConsumeService.ts +5 -3
- package/src/consumer/LiteConsumerSupport.ts +49 -0
- package/src/consumer/LiteFifoConsumeService.ts +5 -3
- package/src/consumer/LitePushConsumerImpl.ts +34 -23
- package/src/consumer/LiteSimpleConsumer.ts +251 -0
- package/src/consumer/LiteSimpleConsumerImpl.ts +214 -0
- package/src/consumer/LiteStandardConsumeService.ts +5 -3
- package/src/consumer/LiteSubscriptionManager.ts +66 -41
- package/src/consumer/OffsetOption.ts +10 -3
- package/src/consumer/ProcessQueue.ts +165 -107
- package/src/consumer/PushConsumer.ts +133 -24
- package/src/consumer/PushConsumerGaugeObserver.ts +60 -0
- package/src/consumer/PushSubscriptionSettings.ts +40 -9
- package/src/consumer/SimpleConsumer.ts +39 -23
- package/src/consumer/SimpleSubscriptionSettings.ts +2 -2
- package/src/consumer/StandardConsumeService.ts +18 -7
- package/src/consumer/SubscriptionLoadBalancer.ts +2 -2
- package/src/consumer/index.ts +1 -0
- package/src/exception/InternalErrorException.ts +3 -1
- package/src/exception/PayloadEmptyException.ts +25 -0
- package/src/exception/StatusChecker.ts +10 -2
- package/src/exception/index.ts +1 -0
- package/src/exception/receiveStatus.ts +25 -0
- package/src/hook/Attribute.ts +36 -0
- package/src/hook/AttributeKey.ts +42 -0
- package/src/hook/CompositedMessageInterceptor.ts +96 -0
- package/src/hook/InflightRequestCountInterceptor.ts +46 -0
- package/src/hook/MessageHookPoints.ts +55 -0
- package/src/hook/MessageHookPointsStatus.ts +25 -0
- package/src/hook/MessageInterceptor.ts +35 -0
- package/src/hook/MessageInterceptorContext.ts +33 -0
- package/src/hook/MessageInterceptorContextImpl.ts +83 -0
- package/src/hook/MessageMeterInterceptor.ts +162 -0
- package/src/hook/index.ts +27 -0
- package/src/index.ts +1 -0
- package/src/message/Message.ts +25 -3
- package/src/message/MessageView.ts +13 -4
- package/src/message/PublishingMessage.ts +3 -3
- package/src/metrics/ClientMeter.ts +81 -0
- package/src/metrics/ClientMeterManager.ts +227 -0
- package/src/metrics/EmptyGaugeObserver.ts +36 -0
- package/src/metrics/GaugeEnum.ts +33 -0
- package/src/metrics/GaugeObserver.ts +32 -0
- package/src/metrics/HistogramEnum.ts +69 -0
- package/src/metrics/InvocationStatus.ts +28 -0
- package/src/metrics/Metric.ts +42 -0
- package/src/metrics/MetricLabels.ts +31 -0
- package/src/metrics/index.ts +26 -0
- package/src/producer/Producer.ts +94 -38
- package/src/producer/PublishingLoadBalancer.ts +10 -4
- package/src/producer/PublishingSettings.ts +0 -2
- package/src/producer/SendReceipt.ts +2 -1
- package/src/producer/Transaction.ts +12 -11
- package/src/producer/index.ts +1 -1
- package/src/retry/CustomizedBackoffRetryPolicy.ts +81 -0
- package/src/retry/ExponentialBackoffRetryPolicy.ts +11 -6
- package/src/retry/RetryPolicy.ts +1 -1
- package/src/retry/index.ts +1 -0
- package/src/route/Endpoints.ts +65 -8
- package/src/route/IpNameResolver.ts +119 -0
- package/src/route/MessageQueue.ts +6 -1
- package/src/route/TopicRouteData.ts +22 -1
- package/src/util/Semaphore.ts +82 -0
- package/src/util/index.ts +8 -5
- package/src/util/rpcContext.ts +34 -0
package/src/client/BaseClient.ts
CHANGED
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
import { debuglog } from 'node:util';
|
|
19
19
|
import { randomUUID } from 'node:crypto';
|
|
20
20
|
import { Metadata } from '@grpc/grpc-js';
|
|
21
|
+
import { getRequestId } from '../util/rpcContext';
|
|
21
22
|
import {
|
|
22
23
|
Settings as SettingsPB,
|
|
23
24
|
Status,
|
|
@@ -28,8 +29,10 @@ import {
|
|
|
28
29
|
QueryRouteRequest,
|
|
29
30
|
RecoverOrphanedTransactionCommand,
|
|
30
31
|
VerifyMessageCommand,
|
|
32
|
+
VerifyMessageResult,
|
|
31
33
|
PrintThreadStackTraceCommand,
|
|
32
34
|
ReconnectEndpointsCommand,
|
|
35
|
+
NotifyUnsubscribeLiteCommand,
|
|
33
36
|
TelemetryCommand,
|
|
34
37
|
ThreadStackTrace,
|
|
35
38
|
HeartbeatRequest,
|
|
@@ -37,7 +40,14 @@ import {
|
|
|
37
40
|
} from '../../proto/apache/rocketmq/v2/service_pb';
|
|
38
41
|
import { createResource, getRequestDateTime, sign } from '../util';
|
|
39
42
|
import { TopicRouteData, Endpoints } from '../route';
|
|
40
|
-
import { ClientException, StatusChecker } from '../exception';
|
|
43
|
+
import { ClientException, NotFoundException, StatusChecker } from '../exception';
|
|
44
|
+
import {
|
|
45
|
+
CompositedMessageInterceptor,
|
|
46
|
+
GeneralMessage,
|
|
47
|
+
MessageInterceptor,
|
|
48
|
+
MessageInterceptorContext,
|
|
49
|
+
MessageMeterInterceptor,
|
|
50
|
+
} from '../hook';
|
|
41
51
|
import { Settings } from './Settings';
|
|
42
52
|
import { UserAgent } from './UserAgent';
|
|
43
53
|
import { ILogger, getDefaultLogger } from './Logger';
|
|
@@ -45,9 +55,22 @@ import { SessionCredentials } from './SessionCredentials';
|
|
|
45
55
|
import { RpcClientManager } from './RpcClientManager';
|
|
46
56
|
import { TelemetrySession } from './TelemetrySession';
|
|
47
57
|
import { ClientId } from './ClientId';
|
|
58
|
+
import { ClientMeterManager } from '../metrics';
|
|
59
|
+
import { Metric } from '../metrics/Metric';
|
|
48
60
|
|
|
49
61
|
const debug = debuglog('rocketmq-client-nodejs:client:BaseClient');
|
|
50
62
|
|
|
63
|
+
// Trigger transport self-healing (D-2) after this many consecutive heartbeat failures
|
|
64
|
+
const HEARTBEAT_TRANSPORT_RECOVERY_THRESHOLD = 2;
|
|
65
|
+
// Minimum interval between transport-recovery attempts per endpoints
|
|
66
|
+
const TRANSPORT_RECOVERY_COOLDOWN = 30 * 1000;
|
|
67
|
+
// Default bound for waiting the server-pushed Settings command during startup.
|
|
68
|
+
// Java's startUp does not wait for settings at all; Node keeps the wait so
|
|
69
|
+
// consumers see server-provided settings before startup() resolves, but the
|
|
70
|
+
// wait must be bounded so a silent remote makes startup() reject (notifying
|
|
71
|
+
// the caller) instead of hanging forever.
|
|
72
|
+
const DEFAULT_FIRST_SETTINGS_TIMEOUT = 30 * 1000;
|
|
73
|
+
|
|
51
74
|
export interface BaseClientOptions {
|
|
52
75
|
sslEnabled?: boolean;
|
|
53
76
|
/**
|
|
@@ -63,6 +86,11 @@ export interface BaseClientOptions {
|
|
|
63
86
|
requestTimeout?: number;
|
|
64
87
|
logger?: ILogger;
|
|
65
88
|
topics?: string[];
|
|
89
|
+
/**
|
|
90
|
+
* Message interceptor(s) invoked around send/receive/consume/ack hook points,
|
|
91
|
+
* mirroring the Java client's MessageInterceptor chain.
|
|
92
|
+
*/
|
|
93
|
+
messageInterceptor?: MessageInterceptor | MessageInterceptor[];
|
|
66
94
|
}
|
|
67
95
|
|
|
68
96
|
/**
|
|
@@ -81,6 +109,10 @@ export abstract class BaseClient {
|
|
|
81
109
|
protected readonly endpoints: Endpoints;
|
|
82
110
|
protected readonly isolated = new Map<string, Endpoints>();
|
|
83
111
|
protected readonly requestTimeout: number;
|
|
112
|
+
// Internal-only bound for the startup wait on the first server-pushed
|
|
113
|
+
// Settings command. Deliberately NOT part of BaseClientOptions so the
|
|
114
|
+
// public API surface stays unchanged; tests may override it via a cast.
|
|
115
|
+
private firstSettingsTimeoutMs = DEFAULT_FIRST_SETTINGS_TIMEOUT;
|
|
84
116
|
protected readonly topics = new Set<string>();
|
|
85
117
|
protected readonly topicRouteCache = new Map<string, TopicRouteData>();
|
|
86
118
|
// In-flight route query futures to avoid duplicate queries for the same topic
|
|
@@ -88,10 +120,16 @@ export abstract class BaseClient {
|
|
|
88
120
|
protected readonly logger: ILogger;
|
|
89
121
|
protected readonly rpcClientManager: RpcClientManager;
|
|
90
122
|
readonly #telemetrySessions = new Map<string, TelemetrySession>();
|
|
123
|
+
readonly #compositedMessageInterceptor: CompositedMessageInterceptor;
|
|
124
|
+
protected readonly clientMeterManager: ClientMeterManager;
|
|
91
125
|
#startupResolve?: () => void;
|
|
92
126
|
#startupReject?: (err: Error) => void;
|
|
93
127
|
#timers: NodeJS.Timeout[] = [];
|
|
94
128
|
#running = false;
|
|
129
|
+
// Consecutive heartbeat failure counts keyed by endpoints facade (D-2 transport self-healing)
|
|
130
|
+
readonly #heartbeatFailureCounts = new Map<string, number>();
|
|
131
|
+
// Last transport-recovery timestamps per endpoints facade, to throttle recovery attempts
|
|
132
|
+
readonly #lastTransportRecoveryTimes = new Map<string, number>();
|
|
95
133
|
|
|
96
134
|
/**
|
|
97
135
|
* Get the client type.
|
|
@@ -119,7 +157,19 @@ export abstract class BaseClient {
|
|
|
119
157
|
}
|
|
120
158
|
}
|
|
121
159
|
|
|
160
|
+
if (options.topics !== undefined) {
|
|
161
|
+
if (!Array.isArray(options.topics)) {
|
|
162
|
+
throw new TypeError('topics must be an array');
|
|
163
|
+
}
|
|
164
|
+
for (const topic of options.topics) {
|
|
165
|
+
if (typeof topic !== 'string' || topic.trim().length === 0) {
|
|
166
|
+
throw new TypeError('topic must be a non-empty string');
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
122
171
|
this.logger = options.logger ?? getDefaultLogger();
|
|
172
|
+
this.#compositedMessageInterceptor = new CompositedMessageInterceptor([], this.logger);
|
|
123
173
|
this.sslEnabled = options.sslEnabled === true;
|
|
124
174
|
this.endpoints = new Endpoints(options.endpoints);
|
|
125
175
|
this.namespace = options.namespace ?? '';
|
|
@@ -128,11 +178,23 @@ export abstract class BaseClient {
|
|
|
128
178
|
// Default request timeout is 3000ms
|
|
129
179
|
this.requestTimeout = options.requestTimeout ?? 3000;
|
|
130
180
|
this.rpcClientManager = new RpcClientManager(this, this.logger);
|
|
181
|
+
// Wire the metrics pipeline: a dedicated meter manager plus an interceptor
|
|
182
|
+
// that records the four RocketMQ histograms around the SEND/RECEIVE/CONSUME
|
|
183
|
+
// hook points. Mirrors Java's ClientImpl#initClientMeterManager.
|
|
184
|
+
this.clientMeterManager = new ClientMeterManager(this.clientId, () => this.getRequestMetadata(), this.logger);
|
|
185
|
+
this.addMessageInterceptor(
|
|
186
|
+
new MessageMeterInterceptor(this.clientMeterManager, this.clientId, () => this.getConsumerGroup()));
|
|
131
187
|
if (options.topics) {
|
|
132
188
|
for (const topic of options.topics) {
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
189
|
+
this.topics.add(topic);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
// Register message interceptors provided by the user (allowed before startup only).
|
|
193
|
+
if (options.messageInterceptor) {
|
|
194
|
+
const interceptors = Array.isArray(options.messageInterceptor)
|
|
195
|
+
? options.messageInterceptor : [ options.messageInterceptor ];
|
|
196
|
+
for (const interceptor of interceptors) {
|
|
197
|
+
this.addMessageInterceptor(interceptor);
|
|
136
198
|
}
|
|
137
199
|
}
|
|
138
200
|
}
|
|
@@ -149,6 +211,17 @@ export abstract class BaseClient {
|
|
|
149
211
|
const err = new Error(`Startup the rocketmq client failed, clientId=${this.clientId}, error=${e}`);
|
|
150
212
|
this.logger.error(err);
|
|
151
213
|
err.cause = e;
|
|
214
|
+
// Release everything acquired by the failed startup before surfacing
|
|
215
|
+
// the error, mirroring Java PushConsumerImpl#startUp which calls
|
|
216
|
+
// shutDown() before rethrowing. Otherwise the route/settings/heartbeat
|
|
217
|
+
// timers and telemetry sessions keep running on an instance whose
|
|
218
|
+
// startup() rejected and which the caller is about to abandon.
|
|
219
|
+
try {
|
|
220
|
+
await this.shutdown();
|
|
221
|
+
} catch (cleanupError) {
|
|
222
|
+
this.logger.warn('Failed to clean up after the startup failure, clientId=%s, error=%s',
|
|
223
|
+
this.clientId, cleanupError instanceof Error ? cleanupError.message : String(cleanupError));
|
|
224
|
+
}
|
|
152
225
|
throw err;
|
|
153
226
|
}
|
|
154
227
|
this.logger.info('Startup the rocketmq client successfully, clientId=%s', this.clientId);
|
|
@@ -158,81 +231,132 @@ export abstract class BaseClient {
|
|
|
158
231
|
this.logger.info('Begin to execute startup flow, clientId=%s, topics=%d',
|
|
159
232
|
this.clientId, this.topics.size);
|
|
160
233
|
|
|
161
|
-
//
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
if (lastError && !this.topicRouteCache.size) {
|
|
185
|
-
throw new Error(`Failed to fetch topic routes after ${maxAttempts} attempts`, { cause: lastError });
|
|
186
|
-
}
|
|
234
|
+
// Create the first-settings promise before any await: updateRoutes() below opens
|
|
235
|
+
// telemetry sessions and syncs settings while it is still iterating the topics, so a
|
|
236
|
+
// server-pushed Settings callback can fire long before the code below reaches the
|
|
237
|
+
// await. Registering the resolvers only at the await point would silently drop that
|
|
238
|
+
// first callback and leave startup hanging until the periodic settings sync fires
|
|
239
|
+
// (5 minutes later).
|
|
240
|
+
const firstSettingsPromise = this.topics.size > 0
|
|
241
|
+
? new Promise<void>((resolve, reject) => {
|
|
242
|
+
this.#startupReject = reject;
|
|
243
|
+
this.#startupResolve = resolve;
|
|
244
|
+
})
|
|
245
|
+
: undefined;
|
|
246
|
+
// A status-only telemetry command can reach onUnknownCommand() while
|
|
247
|
+
// updateRoutes() (or its retry backoff) is still pending, rejecting this
|
|
248
|
+
// promise before the await below attaches a rejection handler. Under
|
|
249
|
+
// Node.js's default unhandled-rejection behavior that terminates the
|
|
250
|
+
// process even though startup() would surface the error to its caller,
|
|
251
|
+
// so attach a no-op handler immediately; the await below still observes
|
|
252
|
+
// the error and propagates it to the caller.
|
|
253
|
+
void firstSettingsPromise?.catch(() => undefined);
|
|
187
254
|
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
this.
|
|
255
|
+
try {
|
|
256
|
+
// Fetch topic route with retry mechanism (align with Java client)
|
|
257
|
+
const maxAttempts = 3;
|
|
258
|
+
let fetched = false;
|
|
259
|
+
let lastError: Error | undefined;
|
|
260
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
261
|
+
try {
|
|
262
|
+
await this.updateRoutes();
|
|
263
|
+
this.logger.info('Fetch topic route successfully during startup, clientId=%s, attempt=%d',
|
|
264
|
+
this.clientId, attempt);
|
|
265
|
+
fetched = true;
|
|
266
|
+
break;
|
|
267
|
+
} catch (e) {
|
|
268
|
+
lastError = e as Error;
|
|
269
|
+
// Not-found errors will never succeed on retry — fail fast, aligned
|
|
270
|
+
// with the Java client which surfaces NotFoundException immediately.
|
|
271
|
+
if (e instanceof NotFoundException) {
|
|
272
|
+
throw e;
|
|
273
|
+
}
|
|
274
|
+
if (attempt < maxAttempts) {
|
|
275
|
+
const backoffMs = 1000 * attempt; // Simple linear backoff: 1s, 2s, 3s
|
|
276
|
+
this.logger.warn('Fetch topic route failed during startup, will retry, clientId=%s, attempt=%d/%d, error=%s, backoff=%dms',
|
|
277
|
+
this.clientId, attempt, maxAttempts, e instanceof Error ? e.message : String(e), backoffMs);
|
|
278
|
+
await this.sleep(backoffMs);
|
|
279
|
+
} else {
|
|
280
|
+
this.logger.error('Fetch topic route failed after %d attempts, clientId=%s, error=%s',
|
|
281
|
+
maxAttempts, this.clientId, e instanceof Error ? e.message : String(e));
|
|
282
|
+
}
|
|
283
|
+
}
|
|
196
284
|
}
|
|
197
|
-
}, 30000));
|
|
198
285
|
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
} catch (e) {
|
|
204
|
-
this.logger.error('Failed to sync settings, clientId=%s, error=%s',
|
|
205
|
-
this.clientId, e instanceof Error ? e.message : String(e));
|
|
286
|
+
// Every topic must be routable, mirroring Java ClientImpl#startUp which fails
|
|
287
|
+
// after the last attempt even if some topics were fetched successfully.
|
|
288
|
+
if (!fetched) {
|
|
289
|
+
throw new Error(`Failed to fetch topic routes after ${maxAttempts} attempts`, { cause: lastError });
|
|
206
290
|
}
|
|
207
|
-
}, 5 * 60000));
|
|
208
|
-
|
|
209
|
-
// heartbeat every 10s
|
|
210
|
-
this.#timers.push(setInterval(async () => {
|
|
211
|
-
this.#doHeartbeat();
|
|
212
|
-
}, 10000));
|
|
213
291
|
|
|
214
|
-
|
|
215
|
-
|
|
292
|
+
this.logger.info('Topic routes updated, clientId=%s', this.clientId);
|
|
293
|
+
// update topic route every 30s
|
|
294
|
+
this.#timers.push(setInterval(async () => {
|
|
295
|
+
try {
|
|
296
|
+
await this.updateRoutes();
|
|
297
|
+
} catch (e) {
|
|
298
|
+
this.logger.error('Failed to update routes periodically, clientId=%s, error=%s',
|
|
299
|
+
this.clientId, e instanceof Error ? e.message : String(e));
|
|
300
|
+
}
|
|
301
|
+
}, 30000));
|
|
216
302
|
|
|
217
|
-
|
|
218
|
-
this.
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
303
|
+
// sync settings every 5m
|
|
304
|
+
this.#timers.push(setInterval(async () => {
|
|
305
|
+
try {
|
|
306
|
+
this.#syncSettings();
|
|
307
|
+
} catch (e) {
|
|
308
|
+
this.logger.error('Failed to sync settings, clientId=%s, error=%s',
|
|
309
|
+
this.clientId, e instanceof Error ? e.message : String(e));
|
|
310
|
+
}
|
|
311
|
+
}, 5 * 60000));
|
|
312
|
+
|
|
313
|
+
// heartbeat every 10s
|
|
314
|
+
this.#timers.push(setInterval(async () => {
|
|
315
|
+
this.doHeartbeat();
|
|
316
|
+
}, 10000));
|
|
317
|
+
|
|
318
|
+
if (firstSettingsPromise) {
|
|
319
|
+
this.logger.info('Waiting for first onSettingsCommand, clientId=%s, timeout=%dms',
|
|
320
|
+
this.clientId, this.firstSettingsTimeoutMs);
|
|
321
|
+
await this.#awaitFirstSettings(firstSettingsPromise);
|
|
322
|
+
this.logger.info('Received first onSettingsCommand, clientId=%s', this.clientId);
|
|
323
|
+
}
|
|
324
|
+
this.#running = true;
|
|
325
|
+
} finally {
|
|
326
|
+
// Never leave the resolvers dangling across exits: on the early-throw
|
|
327
|
+
// (route fetch failure) and first-settings rejection paths they would
|
|
328
|
+
// otherwise settle an abandoned promise long after startup is over.
|
|
226
329
|
this.#startupReject = undefined;
|
|
227
330
|
this.#startupResolve = undefined;
|
|
228
331
|
}
|
|
229
|
-
this.#running = true;
|
|
230
332
|
}
|
|
231
333
|
|
|
232
334
|
isRunning(): boolean {
|
|
233
335
|
return this.#running;
|
|
234
336
|
}
|
|
235
337
|
|
|
338
|
+
/**
|
|
339
|
+
* Bound the wait for the first server-pushed Settings command so a silent
|
|
340
|
+
* remote makes startup() reject with a clear error instead of hanging
|
|
341
|
+
* forever; the rejection also triggers the startup cleanup path.
|
|
342
|
+
*/
|
|
343
|
+
async #awaitFirstSettings(firstSettingsPromise: Promise<void>): Promise<void> {
|
|
344
|
+
let timer: NodeJS.Timeout | undefined;
|
|
345
|
+
try {
|
|
346
|
+
const timeoutPromise = new Promise<never>((_, reject) => {
|
|
347
|
+
timer = setTimeout(() => reject(new Error(
|
|
348
|
+
`Timed out waiting for the first settings command within ${this.firstSettingsTimeoutMs}ms, ` +
|
|
349
|
+
`clientId=${this.clientId}`,
|
|
350
|
+
)), this.firstSettingsTimeoutMs);
|
|
351
|
+
});
|
|
352
|
+
await Promise.race([ firstSettingsPromise, timeoutPromise ]);
|
|
353
|
+
} finally {
|
|
354
|
+
if (timer) {
|
|
355
|
+
clearTimeout(timer);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
236
360
|
protected sleep(ms: number): Promise<void> {
|
|
237
361
|
return new Promise(resolve => setTimeout(resolve, ms));
|
|
238
362
|
}
|
|
@@ -260,16 +384,27 @@ export abstract class BaseClient {
|
|
|
260
384
|
// 4. Close RPC connections
|
|
261
385
|
this.rpcClientManager.close();
|
|
262
386
|
|
|
387
|
+
// 4.5 Close the metrics export pipeline (flushes pending exports and releases
|
|
388
|
+
// the OTLP/gRPC channel). Mirrors ClientImpl#shutdown's meter manager close.
|
|
389
|
+
await this.clientMeterManager.shutdown();
|
|
390
|
+
|
|
263
391
|
// 5. Clear caches
|
|
264
392
|
this.topicRouteCache.clear();
|
|
265
393
|
this.inflightRouteFutures.clear();
|
|
266
394
|
this.isolated.clear();
|
|
267
395
|
|
|
268
396
|
this.logger.info('Shutdown the rocketmq client successfully, clientId=%s', this.clientId);
|
|
269
|
-
|
|
397
|
+
// The default logger is shared by the process and an injected logger is owned
|
|
398
|
+
// by the caller, so the client closes neither; late callbacks may still log.
|
|
270
399
|
}
|
|
271
400
|
|
|
272
|
-
|
|
401
|
+
/**
|
|
402
|
+
* Send one heartbeat round to every route endpoint, mirroring Java
|
|
403
|
+
* ClientImpl#doHeartbeat. TypeScript-private (not #private) so regression
|
|
404
|
+
* tests can invoke it through a cast; it stays invisible on the public API
|
|
405
|
+
* surface (.d.ts exposes it as private and subclasses cannot access it).
|
|
406
|
+
*/
|
|
407
|
+
private async doHeartbeat() {
|
|
273
408
|
try {
|
|
274
409
|
const request = this.wrapHeartbeatRequest();
|
|
275
410
|
const endpointsList = this.getTotalRouteEndpoints();
|
|
@@ -277,21 +412,79 @@ export abstract class BaseClient {
|
|
|
277
412
|
debug('No endpoints available for heartbeat, clientId=%s', this.clientId);
|
|
278
413
|
return;
|
|
279
414
|
}
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
await this.rpcClientManager.heartbeat(endpoints, request, this.requestTimeout);
|
|
283
|
-
} catch (e) {
|
|
284
|
-
// Log but don't throw - heartbeat is best-effort
|
|
285
|
-
this.logger.warn('Heartbeat failed for endpoints=%s, clientId=%s, error=%s',
|
|
286
|
-
endpoints.facade, this.clientId, e instanceof Error ? e.message : String(e));
|
|
287
|
-
}
|
|
288
|
-
}
|
|
415
|
+
// Send heartbeats concurrently so a slow endpoint does not block the others.
|
|
416
|
+
await Promise.all(endpointsList.map(endpoints => this.#heartbeat(endpoints, request)));
|
|
289
417
|
} catch (e) {
|
|
290
418
|
this.logger.error('Unexpected error in heartbeat, clientId=%s, error=%s',
|
|
291
419
|
this.clientId, e instanceof Error ? e.message : String(e));
|
|
292
420
|
}
|
|
293
421
|
}
|
|
294
422
|
|
|
423
|
+
async #heartbeat(endpoints: Endpoints, request: HeartbeatRequest) {
|
|
424
|
+
try {
|
|
425
|
+
const response = await this.rpcClientManager.heartbeat(endpoints, request, this.requestTimeout);
|
|
426
|
+
// Business-level errors (e.g. UNRECOGNIZED_CLIENT_TYPE when the
|
|
427
|
+
// remote no longer holds this client's settings) arrive as normal
|
|
428
|
+
// gRPC responses; without this check the client stays blind to
|
|
429
|
+
// settings loss and never re-registers. Mirrors Java
|
|
430
|
+
// ClientImpl#doHeartbeat which checks the response status.
|
|
431
|
+
StatusChecker.check(response.getStatus()?.toObject(), getRequestId(response));
|
|
432
|
+
// Heartbeat succeeded: the remote is reachable again, so rejoin any
|
|
433
|
+
// isolated endpoints (mirrors Java ClientImpl#doHeartbeat).
|
|
434
|
+
if (this.isolated.delete(endpoints.facade)) {
|
|
435
|
+
this.logger.info('Isolated endpoints rejoined after successful heartbeat, endpoints=%s, clientId=%s',
|
|
436
|
+
endpoints.facade, this.clientId);
|
|
437
|
+
}
|
|
438
|
+
this.#heartbeatFailureCounts.delete(endpoints.facade);
|
|
439
|
+
} catch (e) {
|
|
440
|
+
// Log but don't throw - heartbeat is best-effort
|
|
441
|
+
this.logger.warn('Heartbeat failed for endpoints=%s, clientId=%s, error=%s',
|
|
442
|
+
endpoints.facade, this.clientId, e instanceof Error ? e.message : String(e));
|
|
443
|
+
this.#onHeartbeatFailure(endpoints);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* Handle a heartbeat failure: after consecutive failures, rebuild the transport
|
|
449
|
+
* layer for the affected endpoints (evict the stale RpcClient channel and refresh
|
|
450
|
+
* the telemetry session), throttled by a per-endpoints cooldown.
|
|
451
|
+
*/
|
|
452
|
+
#onHeartbeatFailure(endpoints: Endpoints) {
|
|
453
|
+
const failureCount = (this.#heartbeatFailureCounts.get(endpoints.facade) ?? 0) + 1;
|
|
454
|
+
this.#heartbeatFailureCounts.set(endpoints.facade, failureCount);
|
|
455
|
+
if (failureCount < HEARTBEAT_TRANSPORT_RECOVERY_THRESHOLD) {
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
const now = Date.now();
|
|
459
|
+
if (now - (this.#lastTransportRecoveryTimes.get(endpoints.facade) ?? 0) < TRANSPORT_RECOVERY_COOLDOWN) {
|
|
460
|
+
debug('Transport recovery throttled by cooldown, endpoints=%s, clientId=%s',
|
|
461
|
+
endpoints.facade, this.clientId);
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
this.#lastTransportRecoveryTimes.set(endpoints.facade, now);
|
|
465
|
+
this.logger.warn('Consecutive heartbeat failures detected, rebuilding transport layer, endpoints=%s, failureCount=%d, clientId=%s',
|
|
466
|
+
endpoints.facade, failureCount, this.clientId);
|
|
467
|
+
// 1. Evict the possibly stale RpcClient so a fresh channel is established on next use.
|
|
468
|
+
try {
|
|
469
|
+
this.rpcClientManager.evict(endpoints);
|
|
470
|
+
} catch (e) {
|
|
471
|
+
this.logger.warn('Failed to evict rpc client, endpoints=%s, clientId=%s, error=%s',
|
|
472
|
+
endpoints.facade, this.clientId, e instanceof Error ? e.message : String(e));
|
|
473
|
+
}
|
|
474
|
+
// 2. Release and drop the telemetry session, then eagerly rebuild it to re-sync settings.
|
|
475
|
+
const session = this.#telemetrySessions.get(endpoints.facade);
|
|
476
|
+
if (session) {
|
|
477
|
+
session.release();
|
|
478
|
+
this.#telemetrySessions.delete(endpoints.facade);
|
|
479
|
+
}
|
|
480
|
+
try {
|
|
481
|
+
this.getTelemetrySession(endpoints).syncSettings();
|
|
482
|
+
} catch (e) {
|
|
483
|
+
this.logger.warn('Failed to rebuild telemetry session, endpoints=%s, clientId=%s, error=%s',
|
|
484
|
+
endpoints.facade, this.clientId, e instanceof Error ? e.message : String(e));
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
|
|
295
488
|
#getTotalRouteEndpointsMap() {
|
|
296
489
|
const endpointsMap = new Map<string, Endpoints>();
|
|
297
490
|
for (const topicRoute of this.topicRouteCache.values()) {
|
|
@@ -356,12 +549,12 @@ export abstract class BaseClient {
|
|
|
356
549
|
|
|
357
550
|
async #fetchTopicRoute(topic: string) {
|
|
358
551
|
const req = new QueryRouteRequest();
|
|
359
|
-
req.setTopic(createResource(topic));
|
|
552
|
+
req.setTopic(createResource(topic, this.namespace));
|
|
360
553
|
req.setEndpoints(this.endpoints.toProtobuf());
|
|
361
554
|
|
|
362
555
|
try {
|
|
363
556
|
const response = await this.rpcClientManager.queryRoute(this.endpoints, req, this.requestTimeout);
|
|
364
|
-
StatusChecker.check(response.getStatus()?.toObject());
|
|
557
|
+
StatusChecker.check(response.getStatus()?.toObject(), getRequestId(response));
|
|
365
558
|
const topicRouteData = new TopicRouteData(response.getMessageQueuesList());
|
|
366
559
|
const newEndpoints = this.findNewRouteEndpoints(topicRouteData.getTotalEndpoints());
|
|
367
560
|
for (const endpoints of newEndpoints) {
|
|
@@ -444,6 +637,15 @@ export abstract class BaseClient {
|
|
|
444
637
|
return metadata;
|
|
445
638
|
}
|
|
446
639
|
|
|
640
|
+
/**
|
|
641
|
+
* Consumer group of this client, used as a metric attribute for consumer
|
|
642
|
+
* histograms/gauges. Producers have no consumer group, so the base
|
|
643
|
+
* implementation returns undefined; Consumer overrides this.
|
|
644
|
+
*/
|
|
645
|
+
getConsumerGroup(): string | undefined {
|
|
646
|
+
return undefined;
|
|
647
|
+
}
|
|
648
|
+
|
|
447
649
|
protected abstract getSettings(): Settings;
|
|
448
650
|
|
|
449
651
|
/**
|
|
@@ -465,13 +667,31 @@ export abstract class BaseClient {
|
|
|
465
667
|
|
|
466
668
|
/**
|
|
467
669
|
* Notify remote that current client is prepared to be terminated.
|
|
670
|
+
*
|
|
671
|
+
* Best-effort like Java ClientImpl#notifyClientTermination: a failing or
|
|
672
|
+
* unreachable endpoint is only logged, so shutdown always goes on to
|
|
673
|
+
* release the telemetry sessions, RPC channels and meters.
|
|
468
674
|
*/
|
|
469
675
|
async #notifyClientTermination() {
|
|
470
676
|
this.logger.info('Notify remote that client is terminated, clientId=%s', this.clientId);
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
677
|
+
let request: NotifyClientTerminationRequest;
|
|
678
|
+
try {
|
|
679
|
+
request = this.wrapNotifyClientTerminationRequest();
|
|
680
|
+
} catch (e) {
|
|
681
|
+
this.logger.error('[Bug] Failed to wrap notify client termination request, clientId=%s, error=%s',
|
|
682
|
+
this.clientId, e instanceof Error ? e.message : String(e));
|
|
683
|
+
return;
|
|
474
684
|
}
|
|
685
|
+
const endpointsList = this.getTotalRouteEndpoints();
|
|
686
|
+
const results = await Promise.allSettled(endpointsList.map(endpoints =>
|
|
687
|
+
this.rpcClientManager.notifyClientTermination(endpoints, request, this.requestTimeout)));
|
|
688
|
+
results.forEach((result, i) => {
|
|
689
|
+
if (result.status === 'rejected') {
|
|
690
|
+
const e = result.reason;
|
|
691
|
+
this.logger.warn('Failed to notify remote that client is terminated, clientId=%s, endpoints=%s, error=%s',
|
|
692
|
+
this.clientId, endpointsList[i].facade, e instanceof Error ? e.message : String(e));
|
|
693
|
+
}
|
|
694
|
+
});
|
|
475
695
|
}
|
|
476
696
|
|
|
477
697
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
@@ -481,7 +701,7 @@ export abstract class BaseClient {
|
|
|
481
701
|
|
|
482
702
|
onUnknownCommand(endpoints: Endpoints, status: Status.AsObject) {
|
|
483
703
|
try {
|
|
484
|
-
StatusChecker.check(status);
|
|
704
|
+
StatusChecker.check(status, getRequestId(status));
|
|
485
705
|
} catch (err) {
|
|
486
706
|
this.logger.error('Get error status from telemetry session, status=%j, endpoints=%j, clientId=%s',
|
|
487
707
|
status, endpoints, this.clientId);
|
|
@@ -492,43 +712,85 @@ export abstract class BaseClient {
|
|
|
492
712
|
onSettingsCommand(_endpoints: Endpoints, settings: SettingsPB) {
|
|
493
713
|
this.logger.info('Received settings command, clientId=%s, settings=%j',
|
|
494
714
|
this.clientId, settings.toObject());
|
|
495
|
-
|
|
496
|
-
|
|
715
|
+
const metric = new Metric(settings.getMetric());
|
|
716
|
+
this.clientMeterManager.reset(metric);
|
|
497
717
|
this.getSettings().sync(settings);
|
|
498
718
|
this.logger.info('Sync settings=%j, clientId=%s', this.getSettings(), this.clientId);
|
|
499
719
|
this.#startupResolve && this.#startupResolve();
|
|
500
720
|
}
|
|
501
721
|
|
|
502
722
|
onRecoverOrphanedTransactionCommand(_endpoints: Endpoints, command: RecoverOrphanedTransactionCommand) {
|
|
723
|
+
// The base client does not support transactions; subclasses (e.g. Producer) override
|
|
724
|
+
// this method to recover orphaned transactional messages. Mirroring the Java client
|
|
725
|
+
// (ClientImpl#onRecoverOrphanedTransactionCommand), no reply is sent back to remote.
|
|
503
726
|
this.logger.warn('Ignore orphaned transaction recovery command from remote, which is not expected, clientId=%s, command=%j',
|
|
504
727
|
this.clientId, command.toObject());
|
|
505
|
-
// const telemetryCommand = new TelemetryCommand();
|
|
506
|
-
// telemetryCommand.setStatus(new Status().setCode(Code.NOT_IMPLEMENTED));
|
|
507
|
-
// telemetryCommand.setRecoverOrphanedTransactionCommand(new RecoverOrphanedTransactionCommand());
|
|
508
|
-
// this.telemetry(endpoints, telemetryCommand);
|
|
509
728
|
}
|
|
510
729
|
|
|
511
730
|
onVerifyMessageCommand(endpoints: Endpoints, command: VerifyMessageCommand) {
|
|
512
731
|
const obj = command.toObject();
|
|
513
732
|
this.logger.warn('Ignore verify message command from remote, which is not expected, clientId=%s, command=%j',
|
|
514
733
|
this.clientId, obj);
|
|
734
|
+
// Respond with VerifyMessageResult carrying the same nonce, mirroring the Java
|
|
735
|
+
// client (BaseClient#onVerifyMessageCommand), instead of echoing the command.
|
|
515
736
|
const telemetryCommand = new TelemetryCommand();
|
|
516
737
|
telemetryCommand.setStatus(new Status().setCode(Code.NOT_IMPLEMENTED));
|
|
517
|
-
telemetryCommand.
|
|
738
|
+
telemetryCommand.setVerifyMessageResult(new VerifyMessageResult().setNonce(obj.nonce));
|
|
518
739
|
this.telemetry(endpoints, telemetryCommand);
|
|
519
740
|
}
|
|
520
741
|
|
|
742
|
+
/**
|
|
743
|
+
* Handle the notify-unsubscribe-lite command sent by remote when a lite topic
|
|
744
|
+
* subscription must be dropped (e.g. quota violation or administrative action).
|
|
745
|
+
*
|
|
746
|
+
* The base client ignores it, mirroring Java ClientImpl#onNotifyUnsubscribeLiteCommand;
|
|
747
|
+
* lite consumers override it to drive their lite subscription manager.
|
|
748
|
+
*/
|
|
749
|
+
onNotifyUnsubscribeLiteCommand(endpoints: Endpoints, command: NotifyUnsubscribeLiteCommand) {
|
|
750
|
+
this.logger.warn('Ignore notify unsubscribe lite command from remote, which is not expected, clientId=%s, endpoints=%s, command=%j',
|
|
751
|
+
this.clientId, endpoints.facade, command.toObject());
|
|
752
|
+
}
|
|
753
|
+
|
|
521
754
|
onPrintThreadStackTraceCommand(endpoints: Endpoints, command: PrintThreadStackTraceCommand) {
|
|
522
755
|
const obj = command.toObject();
|
|
523
|
-
this.logger.
|
|
756
|
+
this.logger.info('Received print thread stack trace command from remote, clientId=%s, command=%j',
|
|
524
757
|
this.clientId, obj);
|
|
525
|
-
const nonce = obj.nonce;
|
|
526
758
|
const telemetryCommand = new TelemetryCommand();
|
|
527
|
-
telemetryCommand.setThreadStackTrace(new ThreadStackTrace()
|
|
759
|
+
telemetryCommand.setThreadStackTrace(new ThreadStackTrace()
|
|
760
|
+
.setThreadStackTrace(this.#buildProcessDiagnostics())
|
|
761
|
+
.setNonce(obj.nonce));
|
|
528
762
|
telemetryCommand.setStatus(new Status().setCode(Code.OK));
|
|
529
763
|
this.telemetry(endpoints, telemetryCommand);
|
|
530
764
|
}
|
|
531
765
|
|
|
766
|
+
/**
|
|
767
|
+
* Build Node.js process diagnostics in place of Java-style thread stack traces.
|
|
768
|
+
* Java sends per-thread stacks via ThreadMXBean; Node.js is single-threaded per
|
|
769
|
+
* process, so we expose the closest equivalent runtime snapshot.
|
|
770
|
+
*/
|
|
771
|
+
#buildProcessDiagnostics(): string {
|
|
772
|
+
const mem = process.memoryUsage();
|
|
773
|
+
const formatBytes = (bytes: number) => `${(bytes / 1024 / 1024).toFixed(2)}MB`;
|
|
774
|
+
const lines = [
|
|
775
|
+
`Process: pid=${process.pid}, node=${process.version}, platform=${process.platform}, arch=${process.arch}`,
|
|
776
|
+
`Uptime: ${process.uptime().toFixed(3)}s`,
|
|
777
|
+
`Memory: rss=${formatBytes(mem.rss)}, heapUsed=${formatBytes(mem.heapUsed)}, ` +
|
|
778
|
+
`heapTotal=${formatBytes(mem.heapTotal)}, external=${formatBytes(mem.external)}, ` +
|
|
779
|
+
`arrayBuffers=${formatBytes(mem.arrayBuffers)}`,
|
|
780
|
+
];
|
|
781
|
+
try {
|
|
782
|
+
const activeHandles = (process as unknown as { _getActiveHandles?: () => object[] })._getActiveHandles?.() ?? [];
|
|
783
|
+
lines.push(`Active handles: ${activeHandles.length}`);
|
|
784
|
+
for (const handle of activeHandles.slice(0, 20)) {
|
|
785
|
+
const name = handle?.constructor?.name ?? typeof handle;
|
|
786
|
+
lines.push(` - ${name}`);
|
|
787
|
+
}
|
|
788
|
+
} catch {
|
|
789
|
+
// active handles are best-effort
|
|
790
|
+
}
|
|
791
|
+
return lines.join('\n');
|
|
792
|
+
}
|
|
793
|
+
|
|
532
794
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
533
795
|
onReconnectEndpointsCommand(endpoints: Endpoints, _command: ReconnectEndpointsCommand) {
|
|
534
796
|
this.logger.info('Received reconnect endpoints command from remote, will refresh telemetry session, endpoints=%s, clientId=%s',
|
|
@@ -547,6 +809,45 @@ export abstract class BaseClient {
|
|
|
547
809
|
return this.endpoints;
|
|
548
810
|
}
|
|
549
811
|
|
|
812
|
+
/**
|
|
813
|
+
* Add a message interceptor to the client. Interceptors can only be registered
|
|
814
|
+
* before the client is running, mirroring Java ClientImpl#addMessageInterceptor.
|
|
815
|
+
*/
|
|
816
|
+
addMessageInterceptor(messageInterceptor: MessageInterceptor) {
|
|
817
|
+
if (this.isRunning()) {
|
|
818
|
+
this.logger.warn('Message interceptor can only be added before the client is running, ignore it, clientId=%s',
|
|
819
|
+
this.clientId);
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
this.#compositedMessageInterceptor.addInterceptor(messageInterceptor);
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
/**
|
|
826
|
+
* Invoke the interceptor chain before a hook point is executed.
|
|
827
|
+
*/
|
|
828
|
+
doBefore(context: MessageInterceptorContext, generalMessages: GeneralMessage[]) {
|
|
829
|
+
try {
|
|
830
|
+
this.#compositedMessageInterceptor.doBefore(context, generalMessages);
|
|
831
|
+
} catch (t) {
|
|
832
|
+
// Should never reach here, the composite interceptor guards each interceptor.
|
|
833
|
+
this.logger.error('[Bug] Exception raised while handling messages, clientId=%s, error=%s',
|
|
834
|
+
this.clientId, t);
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
/**
|
|
839
|
+
* Invoke the interceptor chain after a hook point is executed.
|
|
840
|
+
*/
|
|
841
|
+
doAfter(context: MessageInterceptorContext, generalMessages: GeneralMessage[]) {
|
|
842
|
+
try {
|
|
843
|
+
this.#compositedMessageInterceptor.doAfter(context, generalMessages);
|
|
844
|
+
} catch (t) {
|
|
845
|
+
// Should never reach here, the composite interceptor guards each interceptor.
|
|
846
|
+
this.logger.error('[Bug] Exception raised while handling messages, clientId=%s, error=%s',
|
|
847
|
+
this.clientId, t);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
|
|
550
851
|
/**
|
|
551
852
|
* Get the RPC client manager.
|
|
552
853
|
*
|