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
|
@@ -29,6 +29,7 @@ import { MessageView } from '../message';
|
|
|
29
29
|
import { Broker, MessageQueue, TopicRouteData } from '../route';
|
|
30
30
|
import { MessageQueue as MessageQueuePB, Broker as BrokerPB } from '../../proto/apache/rocketmq/v2/definition_pb';
|
|
31
31
|
import { StatusChecker } from '../exception';
|
|
32
|
+
import { getRequestId } from '../util/rpcContext';
|
|
32
33
|
import { RetryPolicy } from '../retry';
|
|
33
34
|
import { createDuration, createResource } from '../util';
|
|
34
35
|
import { Consumer, ConsumerOptions } from './Consumer';
|
|
@@ -38,9 +39,11 @@ import { ConsumeService } from './ConsumeService';
|
|
|
38
39
|
import { StandardConsumeService } from './StandardConsumeService';
|
|
39
40
|
import { FifoConsumeService } from './FifoConsumeService';
|
|
40
41
|
import { ProcessQueue } from './ProcessQueue';
|
|
42
|
+
import { PushConsumerGaugeObserver } from './PushConsumerGaugeObserver';
|
|
41
43
|
import { Assignment } from './Assignment';
|
|
42
44
|
import { Assignments } from './Assignments';
|
|
43
45
|
import { MessageListener } from './MessageListener';
|
|
46
|
+
import { InflightRequestCountInterceptor } from '../hook';
|
|
44
47
|
|
|
45
48
|
const ASSIGNMENT_SCAN_SCHEDULE_DELAY = 1000;
|
|
46
49
|
const ASSIGNMENT_SCAN_SCHEDULE_PERIOD = 5000;
|
|
@@ -52,6 +55,12 @@ export interface PushConsumerOptions extends ConsumerOptions {
|
|
|
52
55
|
maxCacheMessageSizeInBytes?: number;
|
|
53
56
|
longPollingTimeout?: number;
|
|
54
57
|
enableFifoConsumeAccelerator?: boolean;
|
|
58
|
+
/**
|
|
59
|
+
* Max number of messages in-flight per process queue. Mirrors Java's
|
|
60
|
+
* consumeConcurrentlyMax (default 32) and backs the ProcessQueue semaphore
|
|
61
|
+
* that applies consumption backpressure.
|
|
62
|
+
*/
|
|
63
|
+
consumeConcurrentlyMax?: number;
|
|
55
64
|
}
|
|
56
65
|
|
|
57
66
|
class ConsumeMetrics {
|
|
@@ -70,12 +79,25 @@ export class PushConsumer extends Consumer {
|
|
|
70
79
|
readonly #maxCacheMessageSizeInBytes: number;
|
|
71
80
|
readonly #enableFifoConsumeAccelerator: boolean;
|
|
72
81
|
readonly #processQueueTable = new Map<string /* mq key */, { mq: MessageQueue; pq: ProcessQueue }>();
|
|
82
|
+
// Retain queues removed by rebalance or expiry until receives and settlements finish; drain and abort them on shutdown.
|
|
83
|
+
readonly #droppedProcessQueues = new Set<ProcessQueue>();
|
|
73
84
|
readonly #metrics = new ConsumeMetrics();
|
|
85
|
+
readonly #inflightRequestCountInterceptor: InflightRequestCountInterceptor;
|
|
74
86
|
#consumeService!: ConsumeService;
|
|
75
87
|
#scanAssignmentTimer?: NodeJS.Timeout;
|
|
76
88
|
#inflightReceiveRequestCount = 0;
|
|
89
|
+
// Set as the very first action of shutdown() so late callbacks (e.g. an
|
|
90
|
+
// assignment scan RPC in flight that settles after shutdown) can no longer
|
|
91
|
+
// create process queues and resurrect the receive loop.
|
|
92
|
+
#shuttingDown = false;
|
|
77
93
|
|
|
78
94
|
constructor(options: PushConsumerOptions) {
|
|
95
|
+
if (!options.messageListener || typeof options.messageListener.consume !== 'function') {
|
|
96
|
+
throw new TypeError('messageListener must provide a consume function');
|
|
97
|
+
}
|
|
98
|
+
if (!(options.subscriptions instanceof Map) || options.subscriptions.size === 0) {
|
|
99
|
+
throw new TypeError('subscriptions must be a non-empty Map');
|
|
100
|
+
}
|
|
79
101
|
options.topics = Array.from(options.subscriptions.keys());
|
|
80
102
|
super(options);
|
|
81
103
|
|
|
@@ -92,9 +114,20 @@ export class PushConsumer extends Consumer {
|
|
|
92
114
|
this.#maxCacheMessageSizeInBytes = options.maxCacheMessageSizeInBytes ?? 64 * 1024 * 1024;
|
|
93
115
|
this.#enableFifoConsumeAccelerator = options.enableFifoConsumeAccelerator ?? false;
|
|
94
116
|
|
|
117
|
+
// Built-in interceptor tracking in-flight receive requests, mirroring Java PushConsumerImpl.
|
|
118
|
+
this.#inflightRequestCountInterceptor = new InflightRequestCountInterceptor();
|
|
119
|
+
this.addMessageInterceptor(this.#inflightRequestCountInterceptor);
|
|
120
|
+
|
|
121
|
+
// Register the consumer gauge observer so cached message count/bytes are
|
|
122
|
+
// exported to the broker. The provider reads the process-queue table lazily
|
|
123
|
+
// at scrape time, so registering here (before any queue exists) is safe.
|
|
124
|
+
this.clientMeterManager.setGaugeObserver(
|
|
125
|
+
new PushConsumerGaugeObserver(() => this.processQueues(), this.clientId, this.consumerGroup));
|
|
126
|
+
|
|
95
127
|
this.#pushSubscriptionSettings = new PushSubscriptionSettings(
|
|
96
128
|
options.namespace, this.clientId, this.getClientType(), this.endpoints,
|
|
97
129
|
this.consumerGroup, this.requestTimeout, this.#subscriptionExpressions,
|
|
130
|
+
options.longPollingTimeout, options.consumeConcurrentlyMax,
|
|
98
131
|
);
|
|
99
132
|
}
|
|
100
133
|
|
|
@@ -116,6 +149,16 @@ export class PushConsumer extends Consumer {
|
|
|
116
149
|
clearInterval(this.#scanAssignmentTimer);
|
|
117
150
|
this.#scanAssignmentTimer = undefined;
|
|
118
151
|
}
|
|
152
|
+
// Full shutdown before rethrowing, mirroring Java PushConsumerImpl#startUp
|
|
153
|
+
// (`shutDown(); throw t;`), so a failed startup never leaves base-client
|
|
154
|
+
// timers or telemetry sessions behind. Idempotent when super.startup()
|
|
155
|
+
// already cleaned up after its own failure.
|
|
156
|
+
try {
|
|
157
|
+
await this.shutdown();
|
|
158
|
+
} catch (cleanupError) {
|
|
159
|
+
this.logger.warn('Failed to clean up after the startup failure, clientId=%s, error=%s',
|
|
160
|
+
this.clientId, cleanupError instanceof Error ? cleanupError.message : String(cleanupError));
|
|
161
|
+
}
|
|
119
162
|
throw err;
|
|
120
163
|
}
|
|
121
164
|
}
|
|
@@ -131,6 +174,7 @@ export class PushConsumer extends Consumer {
|
|
|
131
174
|
|
|
132
175
|
async shutdown() {
|
|
133
176
|
this.logger.info('Begin to shutdown the rocketmq push consumer, clientId=%s', this.clientId);
|
|
177
|
+
this.#shuttingDown = true;
|
|
134
178
|
// Stop scanning assignments
|
|
135
179
|
if (this.#scanAssignmentTimer) {
|
|
136
180
|
clearInterval(this.#scanAssignmentTimer);
|
|
@@ -152,10 +196,11 @@ export class PushConsumer extends Consumer {
|
|
|
152
196
|
// Reserve a short buffer for the ack/changeInvisibleDuration callbacks to be sent
|
|
153
197
|
await this.sleep(1000);
|
|
154
198
|
// Abort process queues and consume service, no more messages will be received or consumed
|
|
155
|
-
for (const
|
|
199
|
+
for (const pq of this.#settlingProcessQueues()) {
|
|
156
200
|
pq.abort();
|
|
157
201
|
}
|
|
158
202
|
this.#processQueueTable.clear();
|
|
203
|
+
this.#droppedProcessQueues.clear();
|
|
159
204
|
if (this.#consumeService) {
|
|
160
205
|
this.logger.info('Shutting down consume service, clientId=%s', this.clientId);
|
|
161
206
|
this.#consumeService.abort();
|
|
@@ -168,7 +213,20 @@ export class PushConsumer extends Consumer {
|
|
|
168
213
|
// Every received message is cached before consumption and evicted from
|
|
169
214
|
// the cache once its consumption chain settles, so empty caches on all
|
|
170
215
|
// process queues mean consumption has fully quiesced.
|
|
171
|
-
|
|
216
|
+
// Bound the wait with the same timeout as the inflight-receive drain
|
|
217
|
+
// (request timeout + long-polling timeout) so shutdown cannot hang forever
|
|
218
|
+
// on a stuck consumption chain.
|
|
219
|
+
const maxWaitingTime = this.requestTimeoutValue
|
|
220
|
+
+ this.getPushConsumerSettings().getLongPollingTimeout();
|
|
221
|
+
const endTime = Date.now() + maxWaitingTime;
|
|
222
|
+
while (this.#settlingProcessQueues().some(pq => pq.cachedMessagesCount() > 0)) {
|
|
223
|
+
if (Date.now() > endTime) {
|
|
224
|
+
const remaining = this.#settlingProcessQueues()
|
|
225
|
+
.reduce((count, pq) => count + pq.cachedMessagesCount(), 0);
|
|
226
|
+
this.logger.warn('Timeout waiting for the cached messages to be consumed, clientId=%s, '
|
|
227
|
+
+ 'remainingCachedMessages=%d', this.clientId, remaining);
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
172
230
|
await this.sleep(100);
|
|
173
231
|
}
|
|
174
232
|
}
|
|
@@ -204,12 +262,12 @@ export class PushConsumer extends Consumer {
|
|
|
204
262
|
protected wrapHeartbeatRequest() {
|
|
205
263
|
return new HeartbeatRequest()
|
|
206
264
|
.setClientType(this.getClientType())
|
|
207
|
-
.setGroup(createResource(this.consumerGroup));
|
|
265
|
+
.setGroup(createResource(this.consumerGroup, this.namespace));
|
|
208
266
|
}
|
|
209
267
|
|
|
210
268
|
protected wrapNotifyClientTerminationRequest() {
|
|
211
269
|
return new NotifyClientTerminationRequest()
|
|
212
|
-
.setGroup(createResource(this.consumerGroup));
|
|
270
|
+
.setGroup(createResource(this.consumerGroup, this.namespace));
|
|
213
271
|
}
|
|
214
272
|
|
|
215
273
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
@@ -217,11 +275,22 @@ export class PushConsumer extends Consumer {
|
|
|
217
275
|
// No-op for push consumer; assignments are queried separately
|
|
218
276
|
}
|
|
219
277
|
|
|
278
|
+
/**
|
|
279
|
+
* Get the count of in-flight receive requests tracked by the built-in
|
|
280
|
+
* {@link InflightRequestCountInterceptor}, mirroring Java PushConsumerImpl.
|
|
281
|
+
*/
|
|
282
|
+
protected getInflightReceiveRequestCountFromInterceptor(): number {
|
|
283
|
+
return this.#inflightRequestCountInterceptor.getInflightReceiveRequestCount();
|
|
284
|
+
}
|
|
285
|
+
|
|
220
286
|
protected createConsumeService(): ConsumeService {
|
|
287
|
+
// `this` implements MessageInterceptor (doBefore/doAfter delegating to the
|
|
288
|
+
// composited interceptor chain), mirroring Java PushConsumerImpl.
|
|
221
289
|
if (this.#pushSubscriptionSettings.isFifo()) {
|
|
222
|
-
return new FifoConsumeService(this.clientId, this.#messageListener, this.#enableFifoConsumeAccelerator
|
|
290
|
+
return new FifoConsumeService(this.clientId, this.#messageListener, this.#enableFifoConsumeAccelerator,
|
|
291
|
+
this, this.consumerGroup, this.logger);
|
|
223
292
|
}
|
|
224
|
-
return new StandardConsumeService(this.clientId, this.#messageListener);
|
|
293
|
+
return new StandardConsumeService(this.clientId, this.#messageListener, this, this.consumerGroup, this.logger);
|
|
225
294
|
}
|
|
226
295
|
|
|
227
296
|
async subscribe(topic: string, filterExpression: FilterExpression) {
|
|
@@ -319,7 +388,7 @@ export class PushConsumer extends Consumer {
|
|
|
319
388
|
attemptId?: string,
|
|
320
389
|
) {
|
|
321
390
|
const request = new ReceiveMessageRequest()
|
|
322
|
-
.setGroup(createResource(this.consumerGroup))
|
|
391
|
+
.setGroup(createResource(this.consumerGroup, this.namespace))
|
|
323
392
|
.setMessageQueue(mq.toProtobuf())
|
|
324
393
|
.setFilterExpression(filterExpression.toProtobuf())
|
|
325
394
|
.setLongPollingTimeout(createDuration(longPollingTimeout))
|
|
@@ -342,8 +411,8 @@ export class PushConsumer extends Consumer {
|
|
|
342
411
|
|
|
343
412
|
wrapAckMessageRequest(messageView: MessageView) {
|
|
344
413
|
const request = new AckMessageRequest()
|
|
345
|
-
.setGroup(createResource(this.consumerGroup))
|
|
346
|
-
.setTopic(createResource(messageView.topic));
|
|
414
|
+
.setGroup(createResource(this.consumerGroup, this.namespace))
|
|
415
|
+
.setTopic(createResource(messageView.topic, this.namespace));
|
|
347
416
|
const entry = request.addEntries()
|
|
348
417
|
.setMessageId(messageView.messageId)
|
|
349
418
|
.setReceiptHandle(messageView.receiptHandle);
|
|
@@ -358,8 +427,8 @@ export class PushConsumer extends Consumer {
|
|
|
358
427
|
|
|
359
428
|
wrapChangeInvisibleDurationRequest(messageView: MessageView, invisibleDuration: number) {
|
|
360
429
|
const request = new ChangeInvisibleDurationRequest()
|
|
361
|
-
.setGroup(createResource(this.consumerGroup))
|
|
362
|
-
.setTopic(createResource(messageView.topic))
|
|
430
|
+
.setGroup(createResource(this.consumerGroup, this.namespace))
|
|
431
|
+
.setTopic(createResource(messageView.topic, this.namespace))
|
|
363
432
|
.setReceiptHandle(messageView.receiptHandle)
|
|
364
433
|
.setInvisibleDuration(createDuration(invisibleDuration))
|
|
365
434
|
.setMessageId(messageView.messageId);
|
|
@@ -376,8 +445,8 @@ export class PushConsumer extends Consumer {
|
|
|
376
445
|
wrapForwardMessageToDeadLetterQueueRequest(messageView: MessageView) {
|
|
377
446
|
const retryPolicy = this.getRetryPolicy();
|
|
378
447
|
const request = new ForwardMessageToDeadLetterQueueRequest()
|
|
379
|
-
.setGroup(createResource(this.consumerGroup))
|
|
380
|
-
.setTopic(createResource(messageView.topic))
|
|
448
|
+
.setGroup(createResource(this.consumerGroup, this.namespace))
|
|
449
|
+
.setTopic(createResource(messageView.topic, this.namespace))
|
|
381
450
|
.setReceiptHandle(messageView.receiptHandle)
|
|
382
451
|
.setMessageId(messageView.messageId)
|
|
383
452
|
.setDeliveryAttempt(messageView.deliveryAttempt ?? 0)
|
|
@@ -397,6 +466,14 @@ export class PushConsumer extends Consumer {
|
|
|
397
466
|
return this.#processQueueTable.size;
|
|
398
467
|
}
|
|
399
468
|
|
|
469
|
+
/**
|
|
470
|
+
* All live process queues, used by the consumer gauge observer to aggregate
|
|
471
|
+
* cached message count/bytes. Reads the private table lazily at scrape time.
|
|
472
|
+
*/
|
|
473
|
+
processQueues(): ProcessQueue[] {
|
|
474
|
+
return [ ...this.#processQueueTable.values() ].map(entry => entry.pq);
|
|
475
|
+
}
|
|
476
|
+
|
|
400
477
|
cacheMessageBytesThresholdPerQueue(): number {
|
|
401
478
|
const size = this.getQueueSize();
|
|
402
479
|
if (size <= 0) return 0;
|
|
@@ -413,6 +490,7 @@ export class PushConsumer extends Consumer {
|
|
|
413
490
|
|
|
414
491
|
#scanAssignments() {
|
|
415
492
|
try {
|
|
493
|
+
this.#pruneDroppedProcessQueues();
|
|
416
494
|
this.logger.debug?.('Scanning assignments, clientId=%s, subscriptionCount=%d',
|
|
417
495
|
this.clientId, this.#subscriptionExpressions.size);
|
|
418
496
|
for (const [ topic, filterExpression ] of this.#subscriptionExpressions) {
|
|
@@ -456,15 +534,11 @@ export class PushConsumer extends Consumer {
|
|
|
456
534
|
|
|
457
535
|
async #queryAssignment(topic: string): Promise<Assignments> {
|
|
458
536
|
const topicRouteData = await this.getRouteData(topic);
|
|
459
|
-
const
|
|
460
|
-
if (endpointsList.length === 0) {
|
|
461
|
-
throw new Error(`No endpoints available for topic=${topic}`);
|
|
462
|
-
}
|
|
463
|
-
const endpoints = endpointsList[0];
|
|
537
|
+
const endpoints = topicRouteData.pickEndpointsToQueryAssignments();
|
|
464
538
|
|
|
465
539
|
const request = new QueryAssignmentRequest()
|
|
466
|
-
.setTopic(createResource(topic))
|
|
467
|
-
.setGroup(createResource(this.consumerGroup))
|
|
540
|
+
.setTopic(createResource(topic, this.namespace))
|
|
541
|
+
.setGroup(createResource(this.consumerGroup, this.namespace))
|
|
468
542
|
.setEndpoints(this.endpoints.toProtobuf());
|
|
469
543
|
|
|
470
544
|
const response = await this.rpcClientManager.queryAssignment(
|
|
@@ -474,7 +548,7 @@ export class PushConsumer extends Consumer {
|
|
|
474
548
|
if (!status) {
|
|
475
549
|
throw new Error('Missing status in query assignment response');
|
|
476
550
|
}
|
|
477
|
-
StatusChecker.check(status.toObject());
|
|
551
|
+
StatusChecker.check(status.toObject(), getRequestId(response));
|
|
478
552
|
|
|
479
553
|
const assignmentList = response.getAssignmentsList().map(assignment => {
|
|
480
554
|
const mqPb = assignment.getMessageQueue()!;
|
|
@@ -486,6 +560,15 @@ export class PushConsumer extends Consumer {
|
|
|
486
560
|
}
|
|
487
561
|
|
|
488
562
|
#syncProcessQueue(topic: string, assignments: Assignments, filterExpression: FilterExpression) {
|
|
563
|
+
// An assignment scan RPC in flight when shutdown() started may settle
|
|
564
|
+
// after the process queue table has been dropped and cleared; creating
|
|
565
|
+
// queues there would resurrect an immortal receive loop with no lifecycle
|
|
566
|
+
// components left running.
|
|
567
|
+
if (this.#shuttingDown) {
|
|
568
|
+
this.logger.info('Ignore assignment sync because shutdown is in progress, topic=%s, clientId=%s',
|
|
569
|
+
topic, this.clientId);
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
489
572
|
const latestMqKeys = new Set<string>();
|
|
490
573
|
for (const assignment of assignments.getAssignmentList()) {
|
|
491
574
|
latestMqKeys.add(this.#mqKey(assignment.messageQueue));
|
|
@@ -537,19 +620,40 @@ export class PushConsumer extends Consumer {
|
|
|
537
620
|
if (entry) {
|
|
538
621
|
entry.pq.drop();
|
|
539
622
|
this.#processQueueTable.delete(mqKey);
|
|
623
|
+
this.#pruneDroppedProcessQueues();
|
|
624
|
+
this.#droppedProcessQueues.add(entry.pq);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
#pruneDroppedProcessQueues() {
|
|
629
|
+
for (const pq of this.#droppedProcessQueues) {
|
|
630
|
+
if (pq.isDrained()) {
|
|
631
|
+
pq.abort();
|
|
632
|
+
this.#droppedProcessQueues.delete(pq);
|
|
633
|
+
}
|
|
540
634
|
}
|
|
541
635
|
}
|
|
542
636
|
|
|
637
|
+
// Include removed queues that still have in-flight receives or cached messages.
|
|
638
|
+
#settlingProcessQueues(): ProcessQueue[] {
|
|
639
|
+
this.#pruneDroppedProcessQueues();
|
|
640
|
+
return [ ...this.processQueues(), ...this.#droppedProcessQueues ];
|
|
641
|
+
}
|
|
642
|
+
|
|
543
643
|
#createProcessQueue(mq: MessageQueue, filterExpression: FilterExpression): ProcessQueue | null {
|
|
544
644
|
const mqKey = this.#mqKey(mq);
|
|
545
645
|
if (this.#processQueueTable.has(mqKey)) {
|
|
546
646
|
return null;
|
|
547
647
|
}
|
|
548
|
-
const processQueue = new ProcessQueue(this, mq, filterExpression);
|
|
648
|
+
const processQueue = new ProcessQueue(this, mq, filterExpression, this.#processQueueContext());
|
|
549
649
|
this.#processQueueTable.set(mqKey, { mq, pq: processQueue });
|
|
550
650
|
return processQueue;
|
|
551
651
|
}
|
|
552
652
|
|
|
653
|
+
#processQueueContext() {
|
|
654
|
+
return { logger: this.logger, clientId: this.clientId, liteConsumer: this.isLiteConsumer() };
|
|
655
|
+
}
|
|
656
|
+
|
|
553
657
|
/**
|
|
554
658
|
* Create a virtual process queue for Lite consumer.
|
|
555
659
|
* Lite consumers use a special message queue with queueId=-1 to receive messages.
|
|
@@ -560,6 +664,11 @@ export class PushConsumer extends Consumer {
|
|
|
560
664
|
*/
|
|
561
665
|
protected createVirtualProcessQueueForLite(topic: string, filterExpression: FilterExpression) {
|
|
562
666
|
// Validate parameters
|
|
667
|
+
if (this.#shuttingDown) {
|
|
668
|
+
this.logger.info('Ignore virtual process queue creation because shutdown is in progress, topic=%s, clientId=%s',
|
|
669
|
+
topic, this.clientId);
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
563
672
|
if (!topic || topic.trim().length === 0) {
|
|
564
673
|
throw new Error('topic should not be blank');
|
|
565
674
|
}
|
|
@@ -577,7 +686,7 @@ export class PushConsumer extends Consumer {
|
|
|
577
686
|
// Create a virtual message queue with queueId=-1
|
|
578
687
|
const virtualMqPb = new MessageQueuePB();
|
|
579
688
|
virtualMqPb.setId(-1); // Virtual queue ID for Lite consumer
|
|
580
|
-
virtualMqPb.setTopic(createResource(topic));
|
|
689
|
+
virtualMqPb.setTopic(createResource(topic, this.namespace));
|
|
581
690
|
virtualMqPb.setBroker(broker.toProtobuf());
|
|
582
691
|
virtualMqPb.setPermission(Permission.READ);
|
|
583
692
|
virtualMqPb.setAcceptMessageTypesList([ MessageType.LITE ]);
|
|
@@ -591,7 +700,7 @@ export class PushConsumer extends Consumer {
|
|
|
591
700
|
return;
|
|
592
701
|
}
|
|
593
702
|
|
|
594
|
-
const processQueue = new ProcessQueue(this, virtualMq, filterExpression);
|
|
703
|
+
const processQueue = new ProcessQueue(this, virtualMq, filterExpression, this.#processQueueContext());
|
|
595
704
|
this.#processQueueTable.set(mqKey, { mq: virtualMq, pq: processQueue });
|
|
596
705
|
|
|
597
706
|
this.logger.info('Created virtual process queue for Lite consumer, mq=%s, clientId=%s',
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Licensed to the Apache Software Foundation (ASF) under one or more
|
|
3
|
+
* contributor license agreements. See the NOTICE file distributed with
|
|
4
|
+
* this work for additional information regarding copyright ownership.
|
|
5
|
+
* The ASF licenses this file to You under the Apache License, Version 2.0
|
|
6
|
+
* (the "License"); you may not use this file except in compliance with
|
|
7
|
+
* the License. You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { Attributes } from '@opentelemetry/api';
|
|
19
|
+
import { ProcessQueue } from './ProcessQueue';
|
|
20
|
+
import { GaugeEnum } from '../metrics/GaugeEnum';
|
|
21
|
+
import { GaugeObserver } from '../metrics/GaugeObserver';
|
|
22
|
+
import { MetricLabels } from '../metrics/MetricLabels';
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Aggregates the per-process-queue cache statistics of a push consumer into the
|
|
26
|
+
* two RocketMQ consumer gauges, mirroring the GaugeObserver implementation held
|
|
27
|
+
* by org.apache.rocketmq.client.java.impl.consumer.PushConsumerImpl.
|
|
28
|
+
*/
|
|
29
|
+
export class PushConsumerGaugeObserver implements GaugeObserver {
|
|
30
|
+
constructor(
|
|
31
|
+
private readonly processQueuesProvider: () => ProcessQueue[],
|
|
32
|
+
private readonly clientId: string,
|
|
33
|
+
private readonly consumerGroup: string,
|
|
34
|
+
) {
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
getGauges(): GaugeEnum[] {
|
|
38
|
+
return [ GaugeEnum.CONSUMER_CACHED_MESSAGES, GaugeEnum.CONSUMER_CACHED_BYTES ];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
getValues(gauge: GaugeEnum): Map<Attributes, number> {
|
|
42
|
+
const result = new Map<Attributes, number>();
|
|
43
|
+
const byTopic = new Map<string, number>();
|
|
44
|
+
for (const pq of this.processQueuesProvider()) {
|
|
45
|
+
const increment = gauge === GaugeEnum.CONSUMER_CACHED_MESSAGES
|
|
46
|
+
? pq.cachedMessagesCount()
|
|
47
|
+
: pq.cachedMessageBytes();
|
|
48
|
+
byTopic.set(pq.topic, (byTopic.get(pq.topic) ?? 0) + increment);
|
|
49
|
+
}
|
|
50
|
+
for (const [ topic, value ] of byTopic) {
|
|
51
|
+
const attributes: Attributes = {
|
|
52
|
+
[MetricLabels.TOPIC]: topic,
|
|
53
|
+
[MetricLabels.CLIENT_ID]: this.clientId,
|
|
54
|
+
[MetricLabels.CONSUMER_GROUP]: this.consumerGroup,
|
|
55
|
+
};
|
|
56
|
+
result.set(attributes, value);
|
|
57
|
+
}
|
|
58
|
+
return result;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -21,9 +21,10 @@ import {
|
|
|
21
21
|
Subscription,
|
|
22
22
|
RetryPolicy as RetryPolicyPB,
|
|
23
23
|
} from '../../proto/apache/rocketmq/v2/definition_pb';
|
|
24
|
+
import { Duration } from 'google-protobuf/google/protobuf/duration_pb';
|
|
24
25
|
import { Endpoints } from '../route';
|
|
25
26
|
import { Settings, UserAgent } from '../client';
|
|
26
|
-
import { ExponentialBackoffRetryPolicy, RetryPolicy } from '../retry';
|
|
27
|
+
import { CustomizedBackoffRetryPolicy, ExponentialBackoffRetryPolicy, RetryPolicy } from '../retry';
|
|
27
28
|
import { createDuration, createResource } from '../util';
|
|
28
29
|
import { FilterExpression } from './FilterExpression';
|
|
29
30
|
|
|
@@ -33,6 +34,7 @@ export class PushSubscriptionSettings extends Settings {
|
|
|
33
34
|
#fifo = false;
|
|
34
35
|
#receiveBatchSize = 32;
|
|
35
36
|
#longPollingTimeout = 30000; // ms
|
|
37
|
+
#consumeConcurrentlyMax = 32; // mirrors Java PushConsumerSettings default
|
|
36
38
|
|
|
37
39
|
constructor(
|
|
38
40
|
namespace: string,
|
|
@@ -43,6 +45,7 @@ export class PushSubscriptionSettings extends Settings {
|
|
|
43
45
|
requestTimeout: number,
|
|
44
46
|
subscriptionExpressions: Map<string, FilterExpression>,
|
|
45
47
|
longPollingTimeout?: number,
|
|
48
|
+
consumeConcurrentlyMax?: number,
|
|
46
49
|
) {
|
|
47
50
|
super(namespace, clientId, clientType, accessPoint, requestTimeout);
|
|
48
51
|
this.#group = consumerGroup;
|
|
@@ -50,6 +53,9 @@ export class PushSubscriptionSettings extends Settings {
|
|
|
50
53
|
if (longPollingTimeout !== undefined) {
|
|
51
54
|
this.#longPollingTimeout = longPollingTimeout;
|
|
52
55
|
}
|
|
56
|
+
if (consumeConcurrentlyMax !== undefined) {
|
|
57
|
+
this.#consumeConcurrentlyMax = consumeConcurrentlyMax;
|
|
58
|
+
}
|
|
53
59
|
}
|
|
54
60
|
|
|
55
61
|
isFifo(): boolean {
|
|
@@ -60,6 +66,16 @@ export class PushSubscriptionSettings extends Settings {
|
|
|
60
66
|
return this.#receiveBatchSize;
|
|
61
67
|
}
|
|
62
68
|
|
|
69
|
+
/**
|
|
70
|
+
* Maximum number of messages that may be in-flight (fetched but not yet
|
|
71
|
+
* settled) per process queue. The Node client previously had no equivalent of
|
|
72
|
+
* the Java {@code ProcessQueueImpl} permit, so consumption could grow
|
|
73
|
+
* unbounded; this bounds it and feeds the {@link ProcessQueue} semaphore.
|
|
74
|
+
*/
|
|
75
|
+
getConsumeConcurrentlyMax(): number {
|
|
76
|
+
return this.#consumeConcurrentlyMax;
|
|
77
|
+
}
|
|
78
|
+
|
|
63
79
|
getLongPollingTimeout(): number {
|
|
64
80
|
return this.#longPollingTimeout;
|
|
65
81
|
}
|
|
@@ -70,11 +86,11 @@ export class PushSubscriptionSettings extends Settings {
|
|
|
70
86
|
|
|
71
87
|
toProtobuf(): SettingsPB {
|
|
72
88
|
const subscription = new Subscription()
|
|
73
|
-
.setGroup(createResource(this.#group));
|
|
89
|
+
.setGroup(createResource(this.#group, this.namespace));
|
|
74
90
|
|
|
75
91
|
for (const [ topic, filterExpression ] of this.#subscriptionExpressions.entries()) {
|
|
76
92
|
subscription.addSubscriptions()
|
|
77
|
-
.setTopic(createResource(topic))
|
|
93
|
+
.setTopic(createResource(topic, this.namespace))
|
|
78
94
|
.setExpression(filterExpression.toProtobuf());
|
|
79
95
|
}
|
|
80
96
|
|
|
@@ -99,23 +115,38 @@ export class PushSubscriptionSettings extends Settings {
|
|
|
99
115
|
this.#longPollingTimeout = longPollingTimeout.getSeconds() * 1000 +
|
|
100
116
|
Math.floor(longPollingTimeout.getNanos() / 1000000);
|
|
101
117
|
}
|
|
118
|
+
// consumeConcurrentlyMax is absent from the generated proto in this fork;
|
|
119
|
+
// guard the accessor so we keep the default (32) until the field lands.
|
|
120
|
+
const consumeConcurrentlyMax = (subscription as { getConsumeConcurrentlyMax?: () => number | null }).getConsumeConcurrentlyMax?.();
|
|
121
|
+
if (typeof consumeConcurrentlyMax === 'number' && consumeConcurrentlyMax > 0) {
|
|
122
|
+
this.#consumeConcurrentlyMax = consumeConcurrentlyMax;
|
|
123
|
+
}
|
|
102
124
|
}
|
|
103
125
|
const backoffPolicy = settings.getBackoffPolicy();
|
|
104
126
|
if (backoffPolicy) {
|
|
127
|
+
// Convert protobuf Duration (seconds + nanos) to milliseconds without
|
|
128
|
+
// losing sub-second precision.
|
|
129
|
+
const toMillis = (duration?: Duration) =>
|
|
130
|
+
(duration ? duration.getSeconds() * 1000 + duration.getNanos() / 1e6 : 0);
|
|
105
131
|
switch (backoffPolicy.getStrategyCase()) {
|
|
106
132
|
case RetryPolicyPB.StrategyCase.EXPONENTIAL_BACKOFF: {
|
|
107
|
-
const exponential = backoffPolicy.getExponentialBackoff()
|
|
133
|
+
const exponential = backoffPolicy.getExponentialBackoff()!;
|
|
108
134
|
this.retryPolicy = new ExponentialBackoffRetryPolicy(
|
|
109
135
|
backoffPolicy.getMaxAttempts(),
|
|
110
|
-
exponential.
|
|
111
|
-
exponential.
|
|
112
|
-
exponential.
|
|
136
|
+
toMillis(exponential.getInitial()),
|
|
137
|
+
toMillis(exponential.getMax()),
|
|
138
|
+
exponential.getMultiplier(),
|
|
113
139
|
);
|
|
114
140
|
break;
|
|
115
141
|
}
|
|
116
|
-
case RetryPolicyPB.StrategyCase.CUSTOMIZED_BACKOFF:
|
|
117
|
-
|
|
142
|
+
case RetryPolicyPB.StrategyCase.CUSTOMIZED_BACKOFF: {
|
|
143
|
+
const customizedBackoff = backoffPolicy.getCustomizedBackoff()!;
|
|
144
|
+
const durations = customizedBackoff.getNextList().map((duration: Duration) => toMillis(duration));
|
|
145
|
+
if (durations.length > 0) {
|
|
146
|
+
this.retryPolicy = new CustomizedBackoffRetryPolicy(durations, backoffPolicy.getMaxAttempts());
|
|
147
|
+
}
|
|
118
148
|
break;
|
|
149
|
+
}
|
|
119
150
|
default:
|
|
120
151
|
break;
|
|
121
152
|
}
|
|
@@ -46,6 +46,11 @@ export interface SimpleConsumerOptions extends ConsumerOptions {
|
|
|
46
46
|
awaitDuration?: number;
|
|
47
47
|
/**
|
|
48
48
|
* max retry attempts for temporary errors (e.g., internal server error), default is 3
|
|
49
|
+
* Includes the initial request and must be a positive safe integer; 1 disables retries.
|
|
50
|
+
* Unlike Java's single receive attempt, Node retains its existing retry configuration.
|
|
51
|
+
* Once routing is ready, the maximum RPC wait and backoff budget is
|
|
52
|
+
* maxRetryAttempts * (requestTimeout + awaitDuration) + (maxRetryAttempts - 1) * 1000ms,
|
|
53
|
+
* excluding route queries, message decoding, hooks, and event-loop scheduling.
|
|
49
54
|
*/
|
|
50
55
|
maxRetryAttempts?: number;
|
|
51
56
|
}
|
|
@@ -59,6 +64,16 @@ export class SimpleConsumer extends Consumer {
|
|
|
59
64
|
#topicIndex = RANDOM_INDEX;
|
|
60
65
|
|
|
61
66
|
constructor(options: SimpleConsumerOptions) {
|
|
67
|
+
if (options.awaitDuration !== undefined && (!Number.isFinite(options.awaitDuration) || options.awaitDuration <= 0)) {
|
|
68
|
+
throw new TypeError('awaitDuration should be positive');
|
|
69
|
+
}
|
|
70
|
+
if (!(options.subscriptions instanceof Map) || options.subscriptions.size === 0) {
|
|
71
|
+
throw new TypeError('subscriptions must be a non-empty Map');
|
|
72
|
+
}
|
|
73
|
+
if (options.maxRetryAttempts !== undefined &&
|
|
74
|
+
(!Number.isSafeInteger(options.maxRetryAttempts) || options.maxRetryAttempts <= 0)) {
|
|
75
|
+
throw new TypeError('maxRetryAttempts must be a positive safe integer');
|
|
76
|
+
}
|
|
62
77
|
options.topics = Array.from(options.subscriptions.keys());
|
|
63
78
|
super(options);
|
|
64
79
|
for (const [ topic, filter ] of options.subscriptions.entries()) {
|
|
@@ -92,12 +107,12 @@ export class SimpleConsumer extends Consumer {
|
|
|
92
107
|
protected wrapHeartbeatRequest() {
|
|
93
108
|
return new HeartbeatRequest()
|
|
94
109
|
.setClientType(this.getClientType())
|
|
95
|
-
.setGroup(createResource(this.consumerGroup));
|
|
110
|
+
.setGroup(createResource(this.consumerGroup, this.namespace));
|
|
96
111
|
}
|
|
97
112
|
|
|
98
113
|
protected wrapNotifyClientTerminationRequest() {
|
|
99
114
|
return new NotifyClientTerminationRequest()
|
|
100
|
-
.setGroup(createResource(this.consumerGroup));
|
|
115
|
+
.setGroup(createResource(this.consumerGroup, this.namespace));
|
|
101
116
|
}
|
|
102
117
|
|
|
103
118
|
protected onTopicRouteDataUpdate(topic: string, topicRouteData: TopicRouteData) {
|
|
@@ -134,6 +149,9 @@ export class SimpleConsumer extends Consumer {
|
|
|
134
149
|
}
|
|
135
150
|
|
|
136
151
|
async receive(maxMessageNum = 10, invisibleDuration = 15000) {
|
|
152
|
+
if (!this.isRunning()) {
|
|
153
|
+
throw new Error('Simple consumer is not running, please call startup() first or check shutdown state');
|
|
154
|
+
}
|
|
137
155
|
if (maxMessageNum <= 0) {
|
|
138
156
|
throw new Error(`maxMessageNum must be greater than 0, but got ${maxMessageNum}`);
|
|
139
157
|
}
|
|
@@ -149,41 +167,39 @@ export class SimpleConsumer extends Consumer {
|
|
|
149
167
|
const request = this.wrapReceiveMessageRequest(maxMessageNum, mq, filterExpression,
|
|
150
168
|
invisibleDuration, this.#awaitDuration);
|
|
151
169
|
|
|
152
|
-
|
|
153
|
-
let lastError: Error | undefined;
|
|
154
|
-
for (let attempt = 1; attempt <= this.#maxRetryAttempts; attempt++) {
|
|
170
|
+
for (let attempt = 1; ; attempt++) {
|
|
155
171
|
try {
|
|
156
172
|
return await this.receiveMessage(request, mq, this.#awaitDuration);
|
|
157
173
|
} catch (err) {
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
// Only retry on internal server errors (temporary errors)
|
|
161
|
-
if (err instanceof InternalErrorException) {
|
|
162
|
-
if (attempt < this.#maxRetryAttempts) {
|
|
163
|
-
this.logger.warn('Received temporary error from server, will retry after %dms, attempt=%d/%d, topic=%s, clientId=%s, error=%s',
|
|
164
|
-
RETRY_DELAY_MS, attempt, this.#maxRetryAttempts, topic, this.clientId, err.message);
|
|
165
|
-
await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));
|
|
166
|
-
continue;
|
|
167
|
-
}
|
|
174
|
+
if (!(err instanceof InternalErrorException) || attempt >= this.#maxRetryAttempts) {
|
|
175
|
+
throw err;
|
|
168
176
|
}
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
177
|
+
this.logger.warn('Received temporary error from server, will retry after %dms, attempt=%d/%d, topic=%s, clientId=%s, error=%s',
|
|
178
|
+
RETRY_DELAY_MS, attempt, this.#maxRetryAttempts, topic, this.clientId, err.message);
|
|
179
|
+
await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));
|
|
172
180
|
}
|
|
173
181
|
}
|
|
174
|
-
|
|
175
|
-
// This should never be reached, but just in case
|
|
176
|
-
throw lastError;
|
|
177
182
|
}
|
|
178
183
|
|
|
179
184
|
async ack(message: MessageView) {
|
|
185
|
+
if (!this.isRunning()) {
|
|
186
|
+
throw new Error('Simple consumer is not running, cannot ack message');
|
|
187
|
+
}
|
|
180
188
|
await this.ackMessage(message);
|
|
181
189
|
}
|
|
182
190
|
|
|
183
191
|
async changeInvisibleDuration(message: MessageView, invisibleDuration: number) {
|
|
192
|
+
if (!this.isRunning()) {
|
|
193
|
+
throw new Error('Simple consumer is not running, cannot change invisible duration');
|
|
194
|
+
}
|
|
184
195
|
const response = await this.invisibleDuration(message, invisibleDuration);
|
|
185
|
-
|
|
186
|
-
|
|
196
|
+
this.#refreshReceiptHandle(message, response);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
#refreshReceiptHandle(message: MessageView, receiptHandle: string) {
|
|
200
|
+
// Update the caller-readonly receiptHandle after successful renewal without changing MessageView's public signature.
|
|
201
|
+
const mutableMessage = message as { receiptHandle: string };
|
|
202
|
+
mutableMessage.receiptHandle = receiptHandle;
|
|
187
203
|
}
|
|
188
204
|
|
|
189
205
|
#nextTopic() {
|
|
@@ -39,12 +39,12 @@ export class SimpleSubscriptionSettings extends Settings {
|
|
|
39
39
|
|
|
40
40
|
toProtobuf(): SettingsPB {
|
|
41
41
|
const subscription = new Subscription()
|
|
42
|
-
.setGroup(createResource(this.group))
|
|
42
|
+
.setGroup(createResource(this.group, this.namespace))
|
|
43
43
|
.setLongPollingTimeout(createDuration(this.longPollingTimeout));
|
|
44
44
|
|
|
45
45
|
for (const [ topic, filterExpression ] of this.subscriptionExpressions.entries()) {
|
|
46
46
|
subscription.addSubscriptions()
|
|
47
|
-
.setTopic(createResource(topic))
|
|
47
|
+
.setTopic(createResource(topic, this.namespace))
|
|
48
48
|
.setExpression(filterExpression.toProtobuf());
|
|
49
49
|
}
|
|
50
50
|
return new SettingsPB()
|