rocketmq-client-nodejs 1.0.8 → 1.1.0
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 +36 -1
- package/dist/client/BaseClient.js +176 -12
- package/dist/client/RpcClient.js +14 -2
- package/dist/client/RpcClientManager.d.ts +5 -0
- package/dist/client/RpcClientManager.js +25 -8
- package/dist/client/TelemetrySession.js +45 -10
- package/dist/consumer/ConsumeService.d.ts +2 -1
- package/dist/consumer/ConsumeService.js +7 -3
- 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 +85 -24
- package/dist/consumer/FifoConsumeService.d.ts +2 -1
- package/dist/consumer/FifoConsumeService.js +3 -3
- package/dist/consumer/LiteFifoConsumeService.d.ts +2 -1
- package/dist/consumer/LiteFifoConsumeService.js +3 -3
- package/dist/consumer/LitePushConsumerImpl.d.ts +12 -1
- package/dist/consumer/LitePushConsumerImpl.js +19 -4
- 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 +187 -0
- package/dist/consumer/LiteStandardConsumeService.d.ts +2 -1
- package/dist/consumer/LiteStandardConsumeService.js +3 -3
- package/dist/consumer/LiteSubscriptionManager.d.ts +27 -6
- package/dist/consumer/LiteSubscriptionManager.js +32 -24
- package/dist/consumer/ProcessQueue.d.ts +10 -0
- package/dist/consumer/ProcessQueue.js +43 -5
- package/dist/consumer/PushConsumer.d.ts +17 -0
- package/dist/consumer/PushConsumer.js +43 -4
- 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 +33 -6
- package/dist/consumer/SimpleConsumer.js +10 -1
- package/dist/consumer/StandardConsumeService.d.ts +2 -1
- package/dist/consumer/StandardConsumeService.js +3 -3
- package/dist/consumer/index.d.ts +1 -0
- package/dist/consumer/index.js +2 -1
- package/dist/exception/PayloadEmptyException.d.ts +20 -0
- package/dist/exception/PayloadEmptyException.js +28 -0
- package/dist/exception/StatusChecker.js +8 -1
- package/dist/exception/index.d.ts +1 -0
- package/dist/exception/index.js +2 -1
- 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 +31 -0
- package/dist/hook/CompositedMessageInterceptor.js +84 -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 +39 -0
- package/dist/hook/MessageInterceptorContextImpl.js +57 -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/metrics/ClientMeter.d.ts +42 -0
- package/dist/metrics/ClientMeter.js +75 -0
- package/dist/metrics/ClientMeterManager.d.ts +42 -0
- package/dist/metrics/ClientMeterManager.js +127 -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.js +33 -5
- package/dist/producer/PublishingLoadBalancer.js +9 -3
- 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 +56 -4
- package/dist/route/IpNameResolver.d.ts +28 -0
- package/dist/route/IpNameResolver.js +104 -0
- package/dist/util/Semaphore.d.ts +47 -0
- package/dist/util/Semaphore.js +82 -0
- package/package.json +6 -2
- package/src/client/BaseClient.ts +202 -12
- package/src/client/RpcClient.ts +14 -1
- package/src/client/RpcClientManager.ts +27 -8
- package/src/client/TelemetrySession.ts +47 -9
- package/src/consumer/ConsumeService.ts +9 -2
- package/src/consumer/ConsumeTask.ts +43 -3
- package/src/consumer/Consumer.ts +103 -23
- package/src/consumer/FifoConsumeService.ts +4 -2
- package/src/consumer/LiteFifoConsumeService.ts +4 -2
- package/src/consumer/LitePushConsumerImpl.ts +21 -3
- package/src/consumer/LiteSimpleConsumer.ts +251 -0
- package/src/consumer/LiteSimpleConsumerImpl.ts +221 -0
- package/src/consumer/LiteStandardConsumeService.ts +4 -2
- package/src/consumer/LiteSubscriptionManager.ts +63 -36
- package/src/consumer/ProcessQueue.ts +44 -1
- package/src/consumer/PushConsumer.ts +54 -2
- package/src/consumer/PushConsumerGaugeObserver.ts +60 -0
- package/src/consumer/PushSubscriptionSettings.ts +38 -7
- package/src/consumer/SimpleConsumer.ts +9 -0
- package/src/consumer/StandardConsumeService.ts +4 -2
- package/src/consumer/index.ts +1 -0
- package/src/exception/PayloadEmptyException.ts +25 -0
- package/src/exception/StatusChecker.ts +7 -0
- package/src/exception/index.ts +1 -0
- package/src/hook/Attribute.ts +36 -0
- package/src/hook/AttributeKey.ts +42 -0
- package/src/hook/CompositedMessageInterceptor.ts +92 -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 +68 -0
- package/src/hook/MessageMeterInterceptor.ts +162 -0
- package/src/hook/index.ts +27 -0
- package/src/index.ts +1 -0
- package/src/metrics/ClientMeter.ts +81 -0
- package/src/metrics/ClientMeterManager.ts +145 -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 +37 -6
- package/src/producer/PublishingLoadBalancer.ts +8 -2
- 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 +52 -3
- package/src/route/IpNameResolver.ts +119 -0
- package/src/util/Semaphore.ts +82 -0
package/src/client/BaseClient.ts
CHANGED
|
@@ -28,8 +28,10 @@ import {
|
|
|
28
28
|
QueryRouteRequest,
|
|
29
29
|
RecoverOrphanedTransactionCommand,
|
|
30
30
|
VerifyMessageCommand,
|
|
31
|
+
VerifyMessageResult,
|
|
31
32
|
PrintThreadStackTraceCommand,
|
|
32
33
|
ReconnectEndpointsCommand,
|
|
34
|
+
NotifyUnsubscribeLiteCommand,
|
|
33
35
|
TelemetryCommand,
|
|
34
36
|
ThreadStackTrace,
|
|
35
37
|
HeartbeatRequest,
|
|
@@ -37,7 +39,14 @@ import {
|
|
|
37
39
|
} from '../../proto/apache/rocketmq/v2/service_pb';
|
|
38
40
|
import { createResource, getRequestDateTime, sign } from '../util';
|
|
39
41
|
import { TopicRouteData, Endpoints } from '../route';
|
|
40
|
-
import { ClientException, StatusChecker } from '../exception';
|
|
42
|
+
import { ClientException, NotFoundException, StatusChecker } from '../exception';
|
|
43
|
+
import {
|
|
44
|
+
CompositedMessageInterceptor,
|
|
45
|
+
GeneralMessage,
|
|
46
|
+
MessageInterceptor,
|
|
47
|
+
MessageInterceptorContext,
|
|
48
|
+
MessageMeterInterceptor,
|
|
49
|
+
} from '../hook';
|
|
41
50
|
import { Settings } from './Settings';
|
|
42
51
|
import { UserAgent } from './UserAgent';
|
|
43
52
|
import { ILogger, getDefaultLogger } from './Logger';
|
|
@@ -45,9 +54,16 @@ import { SessionCredentials } from './SessionCredentials';
|
|
|
45
54
|
import { RpcClientManager } from './RpcClientManager';
|
|
46
55
|
import { TelemetrySession } from './TelemetrySession';
|
|
47
56
|
import { ClientId } from './ClientId';
|
|
57
|
+
import { ClientMeterManager } from '../metrics';
|
|
58
|
+
import { Metric } from '../metrics/Metric';
|
|
48
59
|
|
|
49
60
|
const debug = debuglog('rocketmq-client-nodejs:client:BaseClient');
|
|
50
61
|
|
|
62
|
+
// Trigger transport self-healing (D-2) after this many consecutive heartbeat failures
|
|
63
|
+
const HEARTBEAT_TRANSPORT_RECOVERY_THRESHOLD = 2;
|
|
64
|
+
// Minimum interval between transport-recovery attempts per endpoints
|
|
65
|
+
const TRANSPORT_RECOVERY_COOLDOWN = 30 * 1000;
|
|
66
|
+
|
|
51
67
|
export interface BaseClientOptions {
|
|
52
68
|
sslEnabled?: boolean;
|
|
53
69
|
/**
|
|
@@ -63,6 +79,11 @@ export interface BaseClientOptions {
|
|
|
63
79
|
requestTimeout?: number;
|
|
64
80
|
logger?: ILogger;
|
|
65
81
|
topics?: string[];
|
|
82
|
+
/**
|
|
83
|
+
* Message interceptor(s) invoked around send/receive/consume/ack hook points,
|
|
84
|
+
* mirroring the Java client's MessageInterceptor chain.
|
|
85
|
+
*/
|
|
86
|
+
messageInterceptor?: MessageInterceptor | MessageInterceptor[];
|
|
66
87
|
}
|
|
67
88
|
|
|
68
89
|
/**
|
|
@@ -88,10 +109,16 @@ export abstract class BaseClient {
|
|
|
88
109
|
protected readonly logger: ILogger;
|
|
89
110
|
protected readonly rpcClientManager: RpcClientManager;
|
|
90
111
|
readonly #telemetrySessions = new Map<string, TelemetrySession>();
|
|
112
|
+
readonly #compositedMessageInterceptor = new CompositedMessageInterceptor();
|
|
113
|
+
protected readonly clientMeterManager: ClientMeterManager;
|
|
91
114
|
#startupResolve?: () => void;
|
|
92
115
|
#startupReject?: (err: Error) => void;
|
|
93
116
|
#timers: NodeJS.Timeout[] = [];
|
|
94
117
|
#running = false;
|
|
118
|
+
// Consecutive heartbeat failure counts keyed by endpoints facade (D-2 transport self-healing)
|
|
119
|
+
readonly #heartbeatFailureCounts = new Map<string, number>();
|
|
120
|
+
// Last transport-recovery timestamps per endpoints facade, to throttle recovery attempts
|
|
121
|
+
readonly #lastTransportRecoveryTimes = new Map<string, number>();
|
|
95
122
|
|
|
96
123
|
/**
|
|
97
124
|
* Get the client type.
|
|
@@ -128,6 +155,12 @@ export abstract class BaseClient {
|
|
|
128
155
|
// Default request timeout is 3000ms
|
|
129
156
|
this.requestTimeout = options.requestTimeout ?? 3000;
|
|
130
157
|
this.rpcClientManager = new RpcClientManager(this, this.logger);
|
|
158
|
+
// Wire the metrics pipeline: a dedicated meter manager plus an interceptor
|
|
159
|
+
// that records the four RocketMQ histograms around the SEND/RECEIVE/CONSUME
|
|
160
|
+
// hook points. Mirrors Java's ClientImpl#initClientMeterManager.
|
|
161
|
+
this.clientMeterManager = new ClientMeterManager(this.clientId, () => this.getRequestMetadata(), this.logger);
|
|
162
|
+
this.addMessageInterceptor(
|
|
163
|
+
new MessageMeterInterceptor(this.clientMeterManager, this.clientId, () => this.getConsumerGroup()));
|
|
131
164
|
if (options.topics) {
|
|
132
165
|
for (const topic of options.topics) {
|
|
133
166
|
if (topic && topic.trim().length > 0) {
|
|
@@ -135,6 +168,14 @@ export abstract class BaseClient {
|
|
|
135
168
|
}
|
|
136
169
|
}
|
|
137
170
|
}
|
|
171
|
+
// Register message interceptors provided by the user (allowed before startup only).
|
|
172
|
+
if (options.messageInterceptor) {
|
|
173
|
+
const interceptors = Array.isArray(options.messageInterceptor)
|
|
174
|
+
? options.messageInterceptor : [ options.messageInterceptor ];
|
|
175
|
+
for (const interceptor of interceptors) {
|
|
176
|
+
this.addMessageInterceptor(interceptor);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
138
179
|
}
|
|
139
180
|
|
|
140
181
|
/**
|
|
@@ -169,6 +210,11 @@ export abstract class BaseClient {
|
|
|
169
210
|
break;
|
|
170
211
|
} catch (e) {
|
|
171
212
|
lastError = e as Error;
|
|
213
|
+
// Not-found errors will never succeed on retry — fail fast, aligned
|
|
214
|
+
// with the Java client which surfaces NotFoundException immediately.
|
|
215
|
+
if (e instanceof NotFoundException) {
|
|
216
|
+
throw e;
|
|
217
|
+
}
|
|
172
218
|
if (attempt < maxAttempts) {
|
|
173
219
|
const backoffMs = 1000 * attempt; // Simple linear backoff: 1s, 2s, 3s
|
|
174
220
|
this.logger.warn('Fetch topic route failed during startup, will retry, clientId=%s, attempt=%d/%d, error=%s, backoff=%dms',
|
|
@@ -260,13 +306,21 @@ export abstract class BaseClient {
|
|
|
260
306
|
// 4. Close RPC connections
|
|
261
307
|
this.rpcClientManager.close();
|
|
262
308
|
|
|
309
|
+
// 4.5 Close the metrics export pipeline (flushes pending exports and releases
|
|
310
|
+
// the OTLP/gRPC channel). Mirrors ClientImpl#shutdown's meter manager close.
|
|
311
|
+
await this.clientMeterManager.shutdown();
|
|
312
|
+
|
|
263
313
|
// 5. Clear caches
|
|
264
314
|
this.topicRouteCache.clear();
|
|
265
315
|
this.inflightRouteFutures.clear();
|
|
266
316
|
this.isolated.clear();
|
|
267
317
|
|
|
268
318
|
this.logger.info('Shutdown the rocketmq client successfully, clientId=%s', this.clientId);
|
|
269
|
-
|
|
319
|
+
// Defer closing the logger to the next macrotask: subclass shutdown()
|
|
320
|
+
// implementations (Producer / PushConsumer) emit their final log line right
|
|
321
|
+
// after super.shutdown(), and egg-logger throws "log stream had been closed"
|
|
322
|
+
// if it is used again after close().
|
|
323
|
+
setImmediate(() => this.logger.close && this.logger.close());
|
|
270
324
|
}
|
|
271
325
|
|
|
272
326
|
async #doHeartbeat() {
|
|
@@ -280,10 +334,18 @@ export abstract class BaseClient {
|
|
|
280
334
|
for (const endpoints of endpointsList) {
|
|
281
335
|
try {
|
|
282
336
|
await this.rpcClientManager.heartbeat(endpoints, request, this.requestTimeout);
|
|
337
|
+
// Heartbeat succeeded: the remote is reachable again, so rejoin any
|
|
338
|
+
// isolated endpoints (mirrors Java ClientImpl#doHeartbeat).
|
|
339
|
+
if (this.isolated.delete(endpoints.facade)) {
|
|
340
|
+
this.logger.info('Isolated endpoints rejoined after successful heartbeat, endpoints=%s, clientId=%s',
|
|
341
|
+
endpoints.facade, this.clientId);
|
|
342
|
+
}
|
|
343
|
+
this.#heartbeatFailureCounts.delete(endpoints.facade);
|
|
283
344
|
} catch (e) {
|
|
284
345
|
// Log but don't throw - heartbeat is best-effort
|
|
285
346
|
this.logger.warn('Heartbeat failed for endpoints=%s, clientId=%s, error=%s',
|
|
286
347
|
endpoints.facade, this.clientId, e instanceof Error ? e.message : String(e));
|
|
348
|
+
this.#onHeartbeatFailure(endpoints);
|
|
287
349
|
}
|
|
288
350
|
}
|
|
289
351
|
} catch (e) {
|
|
@@ -292,6 +354,47 @@ export abstract class BaseClient {
|
|
|
292
354
|
}
|
|
293
355
|
}
|
|
294
356
|
|
|
357
|
+
/**
|
|
358
|
+
* Handle a heartbeat failure: after consecutive failures, rebuild the transport
|
|
359
|
+
* layer for the affected endpoints (evict the stale RpcClient channel and refresh
|
|
360
|
+
* the telemetry session), throttled by a per-endpoints cooldown.
|
|
361
|
+
*/
|
|
362
|
+
#onHeartbeatFailure(endpoints: Endpoints) {
|
|
363
|
+
const failureCount = (this.#heartbeatFailureCounts.get(endpoints.facade) ?? 0) + 1;
|
|
364
|
+
this.#heartbeatFailureCounts.set(endpoints.facade, failureCount);
|
|
365
|
+
if (failureCount < HEARTBEAT_TRANSPORT_RECOVERY_THRESHOLD) {
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
const now = Date.now();
|
|
369
|
+
if (now - (this.#lastTransportRecoveryTimes.get(endpoints.facade) ?? 0) < TRANSPORT_RECOVERY_COOLDOWN) {
|
|
370
|
+
debug('Transport recovery throttled by cooldown, endpoints=%s, clientId=%s',
|
|
371
|
+
endpoints.facade, this.clientId);
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
this.#lastTransportRecoveryTimes.set(endpoints.facade, now);
|
|
375
|
+
this.logger.warn('Consecutive heartbeat failures detected, rebuilding transport layer, endpoints=%s, failureCount=%d, clientId=%s',
|
|
376
|
+
endpoints.facade, failureCount, this.clientId);
|
|
377
|
+
// 1. Evict the possibly stale RpcClient so a fresh channel is established on next use.
|
|
378
|
+
try {
|
|
379
|
+
this.rpcClientManager.evict(endpoints);
|
|
380
|
+
} catch (e) {
|
|
381
|
+
this.logger.warn('Failed to evict rpc client, endpoints=%s, clientId=%s, error=%s',
|
|
382
|
+
endpoints.facade, this.clientId, e instanceof Error ? e.message : String(e));
|
|
383
|
+
}
|
|
384
|
+
// 2. Release and drop the telemetry session, then eagerly rebuild it to re-sync settings.
|
|
385
|
+
const session = this.#telemetrySessions.get(endpoints.facade);
|
|
386
|
+
if (session) {
|
|
387
|
+
session.release();
|
|
388
|
+
this.#telemetrySessions.delete(endpoints.facade);
|
|
389
|
+
}
|
|
390
|
+
try {
|
|
391
|
+
this.getTelemetrySession(endpoints).syncSettings();
|
|
392
|
+
} catch (e) {
|
|
393
|
+
this.logger.warn('Failed to rebuild telemetry session, endpoints=%s, clientId=%s, error=%s',
|
|
394
|
+
endpoints.facade, this.clientId, e instanceof Error ? e.message : String(e));
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
295
398
|
#getTotalRouteEndpointsMap() {
|
|
296
399
|
const endpointsMap = new Map<string, Endpoints>();
|
|
297
400
|
for (const topicRoute of this.topicRouteCache.values()) {
|
|
@@ -444,6 +547,15 @@ export abstract class BaseClient {
|
|
|
444
547
|
return metadata;
|
|
445
548
|
}
|
|
446
549
|
|
|
550
|
+
/**
|
|
551
|
+
* Consumer group of this client, used as a metric attribute for consumer
|
|
552
|
+
* histograms/gauges. Producers have no consumer group, so the base
|
|
553
|
+
* implementation returns undefined; Consumer overrides this.
|
|
554
|
+
*/
|
|
555
|
+
getConsumerGroup(): string | undefined {
|
|
556
|
+
return undefined;
|
|
557
|
+
}
|
|
558
|
+
|
|
447
559
|
protected abstract getSettings(): Settings;
|
|
448
560
|
|
|
449
561
|
/**
|
|
@@ -492,43 +604,85 @@ export abstract class BaseClient {
|
|
|
492
604
|
onSettingsCommand(_endpoints: Endpoints, settings: SettingsPB) {
|
|
493
605
|
this.logger.info('Received settings command, clientId=%s, settings=%j',
|
|
494
606
|
this.clientId, settings.toObject());
|
|
495
|
-
|
|
496
|
-
|
|
607
|
+
const metric = new Metric(settings.getMetric());
|
|
608
|
+
this.clientMeterManager.reset(metric);
|
|
497
609
|
this.getSettings().sync(settings);
|
|
498
610
|
this.logger.info('Sync settings=%j, clientId=%s', this.getSettings(), this.clientId);
|
|
499
611
|
this.#startupResolve && this.#startupResolve();
|
|
500
612
|
}
|
|
501
613
|
|
|
502
614
|
onRecoverOrphanedTransactionCommand(_endpoints: Endpoints, command: RecoverOrphanedTransactionCommand) {
|
|
615
|
+
// The base client does not support transactions; subclasses (e.g. Producer) override
|
|
616
|
+
// this method to recover orphaned transactional messages. Mirroring the Java client
|
|
617
|
+
// (ClientImpl#onRecoverOrphanedTransactionCommand), no reply is sent back to remote.
|
|
503
618
|
this.logger.warn('Ignore orphaned transaction recovery command from remote, which is not expected, clientId=%s, command=%j',
|
|
504
619
|
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
620
|
}
|
|
510
621
|
|
|
511
622
|
onVerifyMessageCommand(endpoints: Endpoints, command: VerifyMessageCommand) {
|
|
512
623
|
const obj = command.toObject();
|
|
513
624
|
this.logger.warn('Ignore verify message command from remote, which is not expected, clientId=%s, command=%j',
|
|
514
625
|
this.clientId, obj);
|
|
626
|
+
// Respond with VerifyMessageResult carrying the same nonce, mirroring the Java
|
|
627
|
+
// client (BaseClient#onVerifyMessageCommand), instead of echoing the command.
|
|
515
628
|
const telemetryCommand = new TelemetryCommand();
|
|
516
629
|
telemetryCommand.setStatus(new Status().setCode(Code.NOT_IMPLEMENTED));
|
|
517
|
-
telemetryCommand.
|
|
630
|
+
telemetryCommand.setVerifyMessageResult(new VerifyMessageResult().setNonce(obj.nonce));
|
|
518
631
|
this.telemetry(endpoints, telemetryCommand);
|
|
519
632
|
}
|
|
520
633
|
|
|
634
|
+
/**
|
|
635
|
+
* Handle the notify-unsubscribe-lite command sent by remote when a lite topic
|
|
636
|
+
* subscription must be dropped (e.g. quota violation or administrative action).
|
|
637
|
+
*
|
|
638
|
+
* The base client ignores it, mirroring Java ClientImpl#onNotifyUnsubscribeLiteCommand;
|
|
639
|
+
* lite consumers override it to drive their lite subscription manager.
|
|
640
|
+
*/
|
|
641
|
+
onNotifyUnsubscribeLiteCommand(endpoints: Endpoints, command: NotifyUnsubscribeLiteCommand) {
|
|
642
|
+
this.logger.warn('Ignore notify unsubscribe lite command from remote, which is not expected, clientId=%s, endpoints=%s, command=%j',
|
|
643
|
+
this.clientId, endpoints.facade, command.toObject());
|
|
644
|
+
}
|
|
645
|
+
|
|
521
646
|
onPrintThreadStackTraceCommand(endpoints: Endpoints, command: PrintThreadStackTraceCommand) {
|
|
522
647
|
const obj = command.toObject();
|
|
523
|
-
this.logger.
|
|
648
|
+
this.logger.info('Received print thread stack trace command from remote, clientId=%s, command=%j',
|
|
524
649
|
this.clientId, obj);
|
|
525
|
-
const nonce = obj.nonce;
|
|
526
650
|
const telemetryCommand = new TelemetryCommand();
|
|
527
|
-
telemetryCommand.setThreadStackTrace(new ThreadStackTrace()
|
|
651
|
+
telemetryCommand.setThreadStackTrace(new ThreadStackTrace()
|
|
652
|
+
.setThreadStackTrace(this.#buildProcessDiagnostics())
|
|
653
|
+
.setNonce(obj.nonce));
|
|
528
654
|
telemetryCommand.setStatus(new Status().setCode(Code.OK));
|
|
529
655
|
this.telemetry(endpoints, telemetryCommand);
|
|
530
656
|
}
|
|
531
657
|
|
|
658
|
+
/**
|
|
659
|
+
* Build Node.js process diagnostics in place of Java-style thread stack traces.
|
|
660
|
+
* Java sends per-thread stacks via ThreadMXBean; Node.js is single-threaded per
|
|
661
|
+
* process, so we expose the closest equivalent runtime snapshot.
|
|
662
|
+
*/
|
|
663
|
+
#buildProcessDiagnostics(): string {
|
|
664
|
+
const mem = process.memoryUsage();
|
|
665
|
+
const formatBytes = (bytes: number) => `${(bytes / 1024 / 1024).toFixed(2)}MB`;
|
|
666
|
+
const lines = [
|
|
667
|
+
`Process: pid=${process.pid}, node=${process.version}, platform=${process.platform}, arch=${process.arch}`,
|
|
668
|
+
`Uptime: ${process.uptime().toFixed(3)}s`,
|
|
669
|
+
`Memory: rss=${formatBytes(mem.rss)}, heapUsed=${formatBytes(mem.heapUsed)}, ` +
|
|
670
|
+
`heapTotal=${formatBytes(mem.heapTotal)}, external=${formatBytes(mem.external)}, ` +
|
|
671
|
+
`arrayBuffers=${formatBytes(mem.arrayBuffers)}`,
|
|
672
|
+
];
|
|
673
|
+
try {
|
|
674
|
+
const activeHandles = (process as unknown as { _getActiveHandles?: () => object[] })._getActiveHandles?.() ?? [];
|
|
675
|
+
lines.push(`Active handles: ${activeHandles.length}`);
|
|
676
|
+
for (const handle of activeHandles.slice(0, 20)) {
|
|
677
|
+
const name = handle?.constructor?.name ?? typeof handle;
|
|
678
|
+
lines.push(` - ${name}`);
|
|
679
|
+
}
|
|
680
|
+
} catch {
|
|
681
|
+
// active handles are best-effort
|
|
682
|
+
}
|
|
683
|
+
return lines.join('\n');
|
|
684
|
+
}
|
|
685
|
+
|
|
532
686
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
533
687
|
onReconnectEndpointsCommand(endpoints: Endpoints, _command: ReconnectEndpointsCommand) {
|
|
534
688
|
this.logger.info('Received reconnect endpoints command from remote, will refresh telemetry session, endpoints=%s, clientId=%s',
|
|
@@ -547,6 +701,42 @@ export abstract class BaseClient {
|
|
|
547
701
|
return this.endpoints;
|
|
548
702
|
}
|
|
549
703
|
|
|
704
|
+
/**
|
|
705
|
+
* Add a message interceptor to the client. Interceptors can only be registered
|
|
706
|
+
* before the client is running, mirroring Java ClientImpl#addMessageInterceptor.
|
|
707
|
+
*/
|
|
708
|
+
addMessageInterceptor(messageInterceptor: MessageInterceptor) {
|
|
709
|
+
if (!this.isRunning()) {
|
|
710
|
+
this.#compositedMessageInterceptor.addInterceptor(messageInterceptor);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
/**
|
|
715
|
+
* Invoke the interceptor chain before a hook point is executed.
|
|
716
|
+
*/
|
|
717
|
+
doBefore(context: MessageInterceptorContext, generalMessages: GeneralMessage[]) {
|
|
718
|
+
try {
|
|
719
|
+
this.#compositedMessageInterceptor.doBefore(context, generalMessages);
|
|
720
|
+
} catch (t) {
|
|
721
|
+
// Should never reach here, the composite interceptor guards each interceptor.
|
|
722
|
+
this.logger.error('[Bug] Exception raised while handling messages, clientId=%s, error=%s',
|
|
723
|
+
this.clientId, t);
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/**
|
|
728
|
+
* Invoke the interceptor chain after a hook point is executed.
|
|
729
|
+
*/
|
|
730
|
+
doAfter(context: MessageInterceptorContext, generalMessages: GeneralMessage[]) {
|
|
731
|
+
try {
|
|
732
|
+
this.#compositedMessageInterceptor.doAfter(context, generalMessages);
|
|
733
|
+
} catch (t) {
|
|
734
|
+
// Should never reach here, the composite interceptor guards each interceptor.
|
|
735
|
+
this.logger.error('[Bug] Exception raised while handling messages, clientId=%s, error=%s',
|
|
736
|
+
this.clientId, t);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
|
|
550
740
|
/**
|
|
551
741
|
* Get the RPC client manager.
|
|
552
742
|
*
|
package/src/client/RpcClient.ts
CHANGED
|
@@ -53,6 +53,19 @@ import {
|
|
|
53
53
|
} from '../../proto/apache/rocketmq/v2/service_pb';
|
|
54
54
|
import { Endpoints } from '../route';
|
|
55
55
|
|
|
56
|
+
// Channel options mirroring the Java client's Netty channel configuration:
|
|
57
|
+
// keepalive probing plus unbounded message sizes (Java defaults to Integer.MAX_VALUE).
|
|
58
|
+
const GRPC_CHANNEL_OPTIONS = {
|
|
59
|
+
'grpc.keepalive_time_ms': 300000, // 5 minutes, same as Java DEFAULT_KEEP_ALIVE_TIME_MILLIS
|
|
60
|
+
'grpc.keepalive_timeout_ms': 30000, // 30 seconds, same as Java DEFAULT_KEEP_ALIVE_TIMEOUT_MILLIS
|
|
61
|
+
'grpc.keepalive_permit_without_calls': 1,
|
|
62
|
+
'grpc.max_send_message_length': 2 ** 31 - 1,
|
|
63
|
+
'grpc.max_receive_message_length': 2 ** 31 - 1,
|
|
64
|
+
// Use a local subchannel pool so each RpcClient owns its own connection
|
|
65
|
+
// instead of sharing one via grpc-js's global pool, aligning with the Java client.
|
|
66
|
+
'grpc.use_local_subchannel_pool': 1,
|
|
67
|
+
};
|
|
68
|
+
|
|
56
69
|
export class RpcClient {
|
|
57
70
|
#client: MessagingServiceClient;
|
|
58
71
|
#activityTime = Date.now();
|
|
@@ -60,7 +73,7 @@ export class RpcClient {
|
|
|
60
73
|
constructor(endpoints: Endpoints, sslEnabled: boolean) {
|
|
61
74
|
const address = endpoints.getGrpcTarget();
|
|
62
75
|
const grpcCredentials = sslEnabled ? ChannelCredentials.createSsl() : ChannelCredentials.createInsecure();
|
|
63
|
-
this.#client = new MessagingServiceClient(address, grpcCredentials);
|
|
76
|
+
this.#client = new MessagingServiceClient(address, grpcCredentials, GRPC_CHANNEL_OPTIONS);
|
|
64
77
|
}
|
|
65
78
|
|
|
66
79
|
#getAndActivityRpcClient() {
|
|
@@ -37,7 +37,10 @@ const RPC_CLIENT_MAX_IDLE_DURATION = 30 * 60000; // 30 minutes
|
|
|
37
37
|
const RPC_CLIENT_IDLE_CHECK_PERIOD = 60000;
|
|
38
38
|
|
|
39
39
|
export class RpcClientManager {
|
|
40
|
-
|
|
40
|
+
// Keyed by endpoints.facade (string) instead of the Endpoints object itself:
|
|
41
|
+
// Endpoints instances are recreated on every route fetch, so object keys would
|
|
42
|
+
// leak duplicate RpcClients for logically identical endpoints.
|
|
43
|
+
#rpcClients = new Map<string, RpcClient>();
|
|
41
44
|
#baseClient: BaseClient;
|
|
42
45
|
#logger: ILogger;
|
|
43
46
|
#clearIdleRpcClientsTimer: NodeJS.Timeout;
|
|
@@ -55,26 +58,42 @@ export class RpcClientManager {
|
|
|
55
58
|
}
|
|
56
59
|
|
|
57
60
|
#clearIdleRpcClients() {
|
|
58
|
-
for (const [
|
|
61
|
+
for (const [ facade, rpcClient ] of this.#rpcClients.entries()) {
|
|
59
62
|
const idleDuration = rpcClient.idleDuration();
|
|
60
63
|
if (idleDuration > RPC_CLIENT_MAX_IDLE_DURATION) {
|
|
61
64
|
rpcClient.close();
|
|
62
|
-
this.#rpcClients.delete(
|
|
65
|
+
this.#rpcClients.delete(facade);
|
|
63
66
|
this.#logger.info('[RpcClientManager] Rpc client has been idle for a long time, endpoints=%s, idleDuration=%s, clientId=%s',
|
|
64
|
-
|
|
67
|
+
facade, idleDuration, RPC_CLIENT_MAX_IDLE_DURATION, this.#baseClient.clientId);
|
|
65
68
|
}
|
|
66
69
|
}
|
|
67
70
|
}
|
|
68
71
|
|
|
69
72
|
#getRpcClient(endpoints: Endpoints) {
|
|
70
|
-
|
|
73
|
+
const facade = endpoints.facade;
|
|
74
|
+
let rpcClient = this.#rpcClients.get(facade);
|
|
71
75
|
if (!rpcClient) {
|
|
72
76
|
rpcClient = new RpcClient(endpoints, this.#baseClient.sslEnabled);
|
|
73
|
-
this.#rpcClients.set(
|
|
77
|
+
this.#rpcClients.set(facade, rpcClient);
|
|
74
78
|
}
|
|
75
79
|
return rpcClient;
|
|
76
80
|
}
|
|
77
81
|
|
|
82
|
+
/**
|
|
83
|
+
* Close and remove the RPC client bound to the given endpoints (e.g. after
|
|
84
|
+
* consecutive heartbeat failures), so a fresh channel is established on next use.
|
|
85
|
+
*/
|
|
86
|
+
evict(endpoints: Endpoints) {
|
|
87
|
+
const facade = endpoints.facade;
|
|
88
|
+
const rpcClient = this.#rpcClients.get(facade);
|
|
89
|
+
if (rpcClient) {
|
|
90
|
+
rpcClient.close();
|
|
91
|
+
this.#rpcClients.delete(facade);
|
|
92
|
+
this.#logger.info('[RpcClientManager] Rpc client evicted, endpoints=%s, clientId=%s',
|
|
93
|
+
facade, this.#baseClient.clientId);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
78
97
|
close() {
|
|
79
98
|
// Clear idle check timer first
|
|
80
99
|
if (this.#clearIdleRpcClientsTimer) {
|
|
@@ -82,12 +101,12 @@ export class RpcClientManager {
|
|
|
82
101
|
}
|
|
83
102
|
|
|
84
103
|
// Close all RPC clients and clear the map
|
|
85
|
-
for (const [
|
|
104
|
+
for (const [ facade, rpcClient ] of this.#rpcClients.entries()) {
|
|
86
105
|
try {
|
|
87
106
|
rpcClient.close();
|
|
88
107
|
} catch (e) {
|
|
89
108
|
this.#logger.warn('Failed to close RPC client for endpoints=%s, clientId=%s, error=%s',
|
|
90
|
-
|
|
109
|
+
facade, this.#baseClient.clientId, e instanceof Error ? e.message : String(e));
|
|
91
110
|
}
|
|
92
111
|
}
|
|
93
112
|
this.#rpcClients.clear();
|
|
@@ -27,6 +27,8 @@ export class TelemetrySession {
|
|
|
27
27
|
#logger: ILogger;
|
|
28
28
|
#stream: ClientDuplexStream<TelemetryCommand, TelemetryCommand>;
|
|
29
29
|
#isRefreshing = false;
|
|
30
|
+
#released = false;
|
|
31
|
+
#reconnectTimer?: NodeJS.Timeout;
|
|
30
32
|
|
|
31
33
|
constructor(baseClient: BaseClient, endpoints: Endpoints, logger: ILogger) {
|
|
32
34
|
this.#endpoints = endpoints;
|
|
@@ -38,8 +40,20 @@ export class TelemetrySession {
|
|
|
38
40
|
}
|
|
39
41
|
|
|
40
42
|
release() {
|
|
43
|
+
if (this.#released) {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
this.#released = true;
|
|
47
|
+
if (this.#reconnectTimer) {
|
|
48
|
+
clearTimeout(this.#reconnectTimer);
|
|
49
|
+
this.#reconnectTimer = undefined;
|
|
50
|
+
}
|
|
41
51
|
this.#logger.info('Begin to release telemetry session, endpoints=%s, clientId=%s',
|
|
42
52
|
this.#endpoints, this.#baseClient.clientId);
|
|
53
|
+
this.#closeStream();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
#closeStream() {
|
|
43
57
|
try {
|
|
44
58
|
this.#stream.end();
|
|
45
59
|
this.#stream.removeAllListeners();
|
|
@@ -70,7 +84,11 @@ export class TelemetrySession {
|
|
|
70
84
|
this.#endpoints, this.#baseClient.clientId);
|
|
71
85
|
|
|
72
86
|
try {
|
|
73
|
-
this
|
|
87
|
+
if (this.#reconnectTimer) {
|
|
88
|
+
clearTimeout(this.#reconnectTimer);
|
|
89
|
+
this.#reconnectTimer = undefined;
|
|
90
|
+
}
|
|
91
|
+
this.#closeStream();
|
|
74
92
|
this.#renewStream(false);
|
|
75
93
|
} catch (err) {
|
|
76
94
|
this.#logger.error('Failed to refresh telemetry session, endpoints=%s, clientId=%s, error=%s',
|
|
@@ -134,6 +152,12 @@ export class TelemetrySession {
|
|
|
134
152
|
this.#baseClient.onReconnectEndpointsCommand(endpoints, command.getReconnectEndpointsCommand()!);
|
|
135
153
|
break;
|
|
136
154
|
}
|
|
155
|
+
case TelemetryCommand.CommandCase.NOTIFY_UNSUBSCRIBE_LITE_COMMAND: {
|
|
156
|
+
this.#logger.info('Receive notify unsubscribe lite command from remote, endpoints=%s, clientId=%s',
|
|
157
|
+
endpoints, clientId);
|
|
158
|
+
this.#baseClient.onNotifyUnsubscribeLiteCommand(endpoints, command.getNotifyUnsubscribeLiteCommand()!);
|
|
159
|
+
break;
|
|
160
|
+
}
|
|
137
161
|
default: {
|
|
138
162
|
const commandObj = command.toObject();
|
|
139
163
|
this.#logger.warn('Receive unrecognized command from remote, endpoints=%s, commandCase=%j, command=%j, clientId=%s',
|
|
@@ -144,21 +168,35 @@ export class TelemetrySession {
|
|
|
144
168
|
}
|
|
145
169
|
}
|
|
146
170
|
|
|
171
|
+
/**
|
|
172
|
+
* Schedule a telemetry stream renewal. The timer is tracked so that it can
|
|
173
|
+
* be cancelled on release(), and a pending timer doubles as a guard to
|
|
174
|
+
* prevent error/end events from scheduling duplicate reconnects.
|
|
175
|
+
*/
|
|
176
|
+
#scheduleRenewStream() {
|
|
177
|
+
if (this.#released || this.#reconnectTimer) {
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
this.#reconnectTimer = setTimeout(() => {
|
|
181
|
+
this.#reconnectTimer = undefined;
|
|
182
|
+
if (this.#released) {
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
this.#renewStream(false);
|
|
186
|
+
}, 1000);
|
|
187
|
+
}
|
|
188
|
+
|
|
147
189
|
#onError(err: Error) {
|
|
148
190
|
this.#logger.error('Exception raised from stream response observer, endpoints=%s, clientId=%s, error=%s',
|
|
149
191
|
this.#endpoints, this.#baseClient.clientId, err);
|
|
150
|
-
this
|
|
151
|
-
|
|
152
|
-
this.#renewStream(false);
|
|
153
|
-
}, 1000);
|
|
192
|
+
this.#closeStream();
|
|
193
|
+
this.#scheduleRenewStream();
|
|
154
194
|
}
|
|
155
195
|
|
|
156
196
|
#onEnd() {
|
|
157
197
|
this.#logger.info('Receive completion for stream response observer, endpoints=%s, clientId=%s',
|
|
158
198
|
this.#endpoints, this.#baseClient.clientId);
|
|
159
|
-
this
|
|
160
|
-
|
|
161
|
-
this.#renewStream(false);
|
|
162
|
-
}, 1000);
|
|
199
|
+
this.#closeStream();
|
|
200
|
+
this.#scheduleRenewStream();
|
|
163
201
|
}
|
|
164
202
|
}
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
17
|
import { MessageView } from '../message';
|
|
18
|
+
import { MessageInterceptor } from '../hook';
|
|
18
19
|
import { ConsumeResult } from './ConsumeResult';
|
|
19
20
|
import { ConsumeTask } from './ConsumeTask';
|
|
20
21
|
import { MessageListener } from './MessageListener';
|
|
@@ -23,12 +24,17 @@ import type { ProcessQueue } from './ProcessQueue';
|
|
|
23
24
|
export abstract class ConsumeService {
|
|
24
25
|
protected readonly clientId: string;
|
|
25
26
|
readonly #messageListener: MessageListener;
|
|
27
|
+
readonly #messageInterceptor?: MessageInterceptor;
|
|
28
|
+
readonly #consumerGroup?: string;
|
|
26
29
|
#aborted = false;
|
|
27
30
|
#pendingTimers: Set<NodeJS.Timeout> = new Set();
|
|
28
31
|
|
|
29
|
-
constructor(clientId: string, messageListener: MessageListener
|
|
32
|
+
constructor(clientId: string, messageListener: MessageListener,
|
|
33
|
+
messageInterceptor?: MessageInterceptor, consumerGroup?: string) {
|
|
30
34
|
this.clientId = clientId;
|
|
31
35
|
this.#messageListener = messageListener;
|
|
36
|
+
this.#messageInterceptor = messageInterceptor;
|
|
37
|
+
this.#consumerGroup = consumerGroup;
|
|
32
38
|
}
|
|
33
39
|
|
|
34
40
|
abstract consume(pq: ProcessQueue, messageViews: MessageView[]): void;
|
|
@@ -37,7 +43,8 @@ export abstract class ConsumeService {
|
|
|
37
43
|
if (this.#aborted) {
|
|
38
44
|
return ConsumeResult.FAILURE;
|
|
39
45
|
}
|
|
40
|
-
const task = new ConsumeTask(this.clientId, this.#messageListener, messageView
|
|
46
|
+
const task = new ConsumeTask(this.clientId, this.#messageListener, messageView,
|
|
47
|
+
this.#messageInterceptor, this.#consumerGroup);
|
|
41
48
|
if (delay <= 0) {
|
|
42
49
|
return this.#executeTask(task);
|
|
43
50
|
}
|
|
@@ -16,24 +16,64 @@
|
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
18
|
import { MessageView } from '../message';
|
|
19
|
+
import {
|
|
20
|
+
Attribute,
|
|
21
|
+
AttributeKey,
|
|
22
|
+
MessageHookPoints,
|
|
23
|
+
MessageHookPointsStatus,
|
|
24
|
+
MessageInterceptor,
|
|
25
|
+
MessageInterceptorContextImpl,
|
|
26
|
+
} from '../hook';
|
|
19
27
|
import { ConsumeResult } from './ConsumeResult';
|
|
20
28
|
import { MessageListener } from './MessageListener';
|
|
21
29
|
|
|
30
|
+
// Context keys exposed to interceptors, mirroring the Java ConsumeTask keys.
|
|
31
|
+
export const REMOTE_ADDR_CONTEXT_KEY = AttributeKey.create<string>('remote_address');
|
|
32
|
+
export const MESSAGE_VIEW_CONTEXT_KEY = AttributeKey.create<MessageView>('message_view');
|
|
33
|
+
export const CONSUMER_GROUP_CONTEXT_KEY = AttributeKey.create<string>('consumer_group');
|
|
34
|
+
export const CONSUME_ERROR_CONTEXT_KEY = AttributeKey.create<unknown>('consume_error');
|
|
35
|
+
|
|
22
36
|
export class ConsumeTask {
|
|
23
37
|
readonly #messageListener: MessageListener;
|
|
24
38
|
readonly #messageView: MessageView;
|
|
39
|
+
readonly #consumerGroup?: string;
|
|
40
|
+
readonly #messageInterceptor?: MessageInterceptor;
|
|
25
41
|
|
|
26
|
-
constructor(_clientId: string, messageListener: MessageListener, messageView: MessageView
|
|
42
|
+
constructor(_clientId: string, messageListener: MessageListener, messageView: MessageView,
|
|
43
|
+
messageInterceptor?: MessageInterceptor, consumerGroup?: string) {
|
|
27
44
|
this.#messageListener = messageListener;
|
|
28
45
|
this.#messageView = messageView;
|
|
46
|
+
this.#messageInterceptor = messageInterceptor;
|
|
47
|
+
this.#consumerGroup = consumerGroup;
|
|
29
48
|
}
|
|
30
49
|
|
|
31
50
|
async call(): Promise<ConsumeResult> {
|
|
51
|
+
const generalMessages = [ this.#messageView ];
|
|
52
|
+
let context = new MessageInterceptorContextImpl(MessageHookPoints.CONSUME);
|
|
53
|
+
context.putAttribute(MESSAGE_VIEW_CONTEXT_KEY, Attribute.create(this.#messageView));
|
|
54
|
+
if (this.#consumerGroup) {
|
|
55
|
+
context.putAttribute(CONSUMER_GROUP_CONTEXT_KEY, Attribute.create(this.#consumerGroup));
|
|
56
|
+
}
|
|
57
|
+
let throwable: unknown;
|
|
58
|
+
let consumeResult: ConsumeResult;
|
|
59
|
+
if (this.#messageInterceptor) {
|
|
60
|
+
this.#messageInterceptor.doBefore(context, generalMessages);
|
|
61
|
+
}
|
|
32
62
|
try {
|
|
33
|
-
|
|
63
|
+
consumeResult = await this.#messageListener.consume(this.#messageView);
|
|
34
64
|
} catch (e) {
|
|
35
65
|
// Message listener raised an exception while consuming messages
|
|
36
|
-
|
|
66
|
+
throwable = e;
|
|
67
|
+
consumeResult = ConsumeResult.FAILURE;
|
|
68
|
+
}
|
|
69
|
+
const status = consumeResult === ConsumeResult.SUCCESS ? MessageHookPointsStatus.OK : MessageHookPointsStatus.ERROR;
|
|
70
|
+
context = MessageInterceptorContextImpl.withStatus(context, status);
|
|
71
|
+
if (throwable) {
|
|
72
|
+
context.putAttribute(CONSUME_ERROR_CONTEXT_KEY, Attribute.create(throwable));
|
|
73
|
+
}
|
|
74
|
+
if (this.#messageInterceptor) {
|
|
75
|
+
this.#messageInterceptor.doAfter(context, generalMessages);
|
|
37
76
|
}
|
|
77
|
+
return consumeResult;
|
|
38
78
|
}
|
|
39
79
|
}
|