rocketmq-client-nodejs 1.0.7 → 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.
Files changed (164) hide show
  1. package/README.md +61 -0
  2. package/dist/client/BaseClient.d.ts +36 -1
  3. package/dist/client/BaseClient.js +176 -12
  4. package/dist/client/RpcClient.js +14 -2
  5. package/dist/client/RpcClientManager.d.ts +5 -0
  6. package/dist/client/RpcClientManager.js +25 -8
  7. package/dist/client/TelemetrySession.js +45 -10
  8. package/dist/consumer/ConsumeResult.d.ts +2 -2
  9. package/dist/consumer/ConsumeResult.js +6 -3
  10. package/dist/consumer/ConsumeService.d.ts +2 -1
  11. package/dist/consumer/ConsumeService.js +7 -3
  12. package/dist/consumer/ConsumeTask.d.ts +6 -1
  13. package/dist/consumer/ConsumeTask.js +36 -5
  14. package/dist/consumer/Consumer.d.ts +13 -5
  15. package/dist/consumer/Consumer.js +85 -24
  16. package/dist/consumer/FifoConsumeService.d.ts +2 -1
  17. package/dist/consumer/FifoConsumeService.js +3 -3
  18. package/dist/consumer/LiteFifoConsumeService.d.ts +2 -1
  19. package/dist/consumer/LiteFifoConsumeService.js +3 -3
  20. package/dist/consumer/LitePushConsumerImpl.d.ts +12 -1
  21. package/dist/consumer/LitePushConsumerImpl.js +19 -4
  22. package/dist/consumer/LiteSimpleConsumer.d.ts +177 -0
  23. package/dist/consumer/LiteSimpleConsumer.js +126 -0
  24. package/dist/consumer/LiteSimpleConsumerImpl.d.ts +133 -0
  25. package/dist/consumer/LiteSimpleConsumerImpl.js +187 -0
  26. package/dist/consumer/LiteStandardConsumeService.d.ts +2 -1
  27. package/dist/consumer/LiteStandardConsumeService.js +3 -3
  28. package/dist/consumer/LiteSubscriptionManager.d.ts +27 -6
  29. package/dist/consumer/LiteSubscriptionManager.js +32 -24
  30. package/dist/consumer/ProcessQueue.d.ts +10 -0
  31. package/dist/consumer/ProcessQueue.js +47 -7
  32. package/dist/consumer/PushConsumer.d.ts +17 -0
  33. package/dist/consumer/PushConsumer.js +87 -7
  34. package/dist/consumer/PushConsumerGaugeObserver.d.ts +33 -0
  35. package/dist/consumer/PushConsumerGaugeObserver.js +60 -0
  36. package/dist/consumer/PushSubscriptionSettings.d.ts +8 -1
  37. package/dist/consumer/PushSubscriptionSettings.js +33 -6
  38. package/dist/consumer/SimpleConsumer.js +10 -1
  39. package/dist/consumer/StandardConsumeService.d.ts +2 -1
  40. package/dist/consumer/StandardConsumeService.js +3 -3
  41. package/dist/consumer/index.d.ts +1 -0
  42. package/dist/consumer/index.js +2 -1
  43. package/dist/exception/PayloadEmptyException.d.ts +20 -0
  44. package/dist/exception/PayloadEmptyException.js +28 -0
  45. package/dist/exception/StatusChecker.js +8 -1
  46. package/dist/exception/index.d.ts +1 -0
  47. package/dist/exception/index.js +2 -1
  48. package/dist/hook/Attribute.d.ts +26 -0
  49. package/dist/hook/Attribute.js +37 -0
  50. package/dist/hook/AttributeKey.d.ts +32 -0
  51. package/dist/hook/AttributeKey.js +43 -0
  52. package/dist/hook/CompositedMessageInterceptor.d.ts +31 -0
  53. package/dist/hook/CompositedMessageInterceptor.js +84 -0
  54. package/dist/hook/InflightRequestCountInterceptor.d.ts +28 -0
  55. package/dist/hook/InflightRequestCountInterceptor.js +44 -0
  56. package/dist/hook/MessageHookPoints.d.ts +54 -0
  57. package/dist/hook/MessageHookPoints.js +59 -0
  58. package/dist/hook/MessageHookPointsStatus.d.ts +24 -0
  59. package/dist/hook/MessageHookPointsStatus.js +29 -0
  60. package/dist/hook/MessageInterceptor.d.ts +34 -0
  61. package/dist/hook/MessageInterceptor.js +19 -0
  62. package/dist/hook/MessageInterceptorContext.d.ts +31 -0
  63. package/dist/hook/MessageInterceptorContext.js +19 -0
  64. package/dist/hook/MessageInterceptorContextImpl.d.ts +39 -0
  65. package/dist/hook/MessageInterceptorContextImpl.js +57 -0
  66. package/dist/hook/MessageMeterInterceptor.d.ts +39 -0
  67. package/dist/hook/MessageMeterInterceptor.js +149 -0
  68. package/dist/hook/index.d.ts +26 -0
  69. package/dist/hook/index.js +43 -0
  70. package/dist/index.d.ts +1 -0
  71. package/dist/index.js +2 -1
  72. package/dist/metrics/ClientMeter.d.ts +42 -0
  73. package/dist/metrics/ClientMeter.js +75 -0
  74. package/dist/metrics/ClientMeterManager.d.ts +42 -0
  75. package/dist/metrics/ClientMeterManager.js +127 -0
  76. package/dist/metrics/EmptyGaugeObserver.d.ts +28 -0
  77. package/dist/metrics/EmptyGaugeObserver.js +34 -0
  78. package/dist/metrics/GaugeEnum.d.ts +32 -0
  79. package/dist/metrics/GaugeEnum.js +37 -0
  80. package/dist/metrics/GaugeObserver.d.ts +29 -0
  81. package/dist/metrics/GaugeObserver.js +19 -0
  82. package/dist/metrics/HistogramEnum.d.ts +54 -0
  83. package/dist/metrics/HistogramEnum.js +71 -0
  84. package/dist/metrics/InvocationStatus.d.ts +26 -0
  85. package/dist/metrics/InvocationStatus.js +33 -0
  86. package/dist/metrics/Metric.d.ts +30 -0
  87. package/dist/metrics/Metric.js +44 -0
  88. package/dist/metrics/MetricLabels.d.ts +27 -0
  89. package/dist/metrics/MetricLabels.js +34 -0
  90. package/dist/metrics/index.d.ts +25 -0
  91. package/dist/metrics/index.js +42 -0
  92. package/dist/producer/Producer.js +33 -5
  93. package/dist/producer/PublishingLoadBalancer.js +9 -3
  94. package/dist/retry/CustomizedBackoffRetryPolicy.d.ts +37 -0
  95. package/dist/retry/CustomizedBackoffRetryPolicy.js +72 -0
  96. package/dist/retry/ExponentialBackoffRetryPolicy.js +10 -6
  97. package/dist/retry/RetryPolicy.d.ts +1 -1
  98. package/dist/retry/index.d.ts +1 -0
  99. package/dist/retry/index.js +2 -1
  100. package/dist/route/Endpoints.d.ts +6 -0
  101. package/dist/route/Endpoints.js +56 -4
  102. package/dist/route/IpNameResolver.d.ts +28 -0
  103. package/dist/route/IpNameResolver.js +104 -0
  104. package/dist/util/Semaphore.d.ts +47 -0
  105. package/dist/util/Semaphore.js +82 -0
  106. package/dist/util/index.js +6 -3
  107. package/package.json +6 -2
  108. package/src/client/BaseClient.ts +202 -12
  109. package/src/client/RpcClient.ts +14 -1
  110. package/src/client/RpcClientManager.ts +27 -8
  111. package/src/client/TelemetrySession.ts +47 -9
  112. package/src/consumer/ConsumeResult.ts +5 -2
  113. package/src/consumer/ConsumeService.ts +9 -2
  114. package/src/consumer/ConsumeTask.ts +43 -3
  115. package/src/consumer/Consumer.ts +103 -23
  116. package/src/consumer/FifoConsumeService.ts +4 -2
  117. package/src/consumer/LiteFifoConsumeService.ts +4 -2
  118. package/src/consumer/LitePushConsumerImpl.ts +21 -3
  119. package/src/consumer/LiteSimpleConsumer.ts +251 -0
  120. package/src/consumer/LiteSimpleConsumerImpl.ts +221 -0
  121. package/src/consumer/LiteStandardConsumeService.ts +4 -2
  122. package/src/consumer/LiteSubscriptionManager.ts +63 -36
  123. package/src/consumer/ProcessQueue.ts +54 -3
  124. package/src/consumer/PushConsumer.ts +98 -5
  125. package/src/consumer/PushConsumerGaugeObserver.ts +60 -0
  126. package/src/consumer/PushSubscriptionSettings.ts +38 -7
  127. package/src/consumer/SimpleConsumer.ts +9 -0
  128. package/src/consumer/StandardConsumeService.ts +4 -2
  129. package/src/consumer/index.ts +1 -0
  130. package/src/exception/PayloadEmptyException.ts +25 -0
  131. package/src/exception/StatusChecker.ts +7 -0
  132. package/src/exception/index.ts +1 -0
  133. package/src/hook/Attribute.ts +36 -0
  134. package/src/hook/AttributeKey.ts +42 -0
  135. package/src/hook/CompositedMessageInterceptor.ts +92 -0
  136. package/src/hook/InflightRequestCountInterceptor.ts +46 -0
  137. package/src/hook/MessageHookPoints.ts +55 -0
  138. package/src/hook/MessageHookPointsStatus.ts +25 -0
  139. package/src/hook/MessageInterceptor.ts +35 -0
  140. package/src/hook/MessageInterceptorContext.ts +33 -0
  141. package/src/hook/MessageInterceptorContextImpl.ts +68 -0
  142. package/src/hook/MessageMeterInterceptor.ts +162 -0
  143. package/src/hook/index.ts +27 -0
  144. package/src/index.ts +1 -0
  145. package/src/metrics/ClientMeter.ts +81 -0
  146. package/src/metrics/ClientMeterManager.ts +145 -0
  147. package/src/metrics/EmptyGaugeObserver.ts +36 -0
  148. package/src/metrics/GaugeEnum.ts +33 -0
  149. package/src/metrics/GaugeObserver.ts +32 -0
  150. package/src/metrics/HistogramEnum.ts +69 -0
  151. package/src/metrics/InvocationStatus.ts +28 -0
  152. package/src/metrics/Metric.ts +42 -0
  153. package/src/metrics/MetricLabels.ts +31 -0
  154. package/src/metrics/index.ts +26 -0
  155. package/src/producer/Producer.ts +37 -6
  156. package/src/producer/PublishingLoadBalancer.ts +8 -2
  157. package/src/retry/CustomizedBackoffRetryPolicy.ts +81 -0
  158. package/src/retry/ExponentialBackoffRetryPolicy.ts +11 -6
  159. package/src/retry/RetryPolicy.ts +1 -1
  160. package/src/retry/index.ts +1 -0
  161. package/src/route/Endpoints.ts +52 -3
  162. package/src/route/IpNameResolver.ts +119 -0
  163. package/src/util/Semaphore.ts +82 -0
  164. package/src/util/index.ts +5 -2
@@ -38,9 +38,11 @@ import { ConsumeService } from './ConsumeService';
38
38
  import { StandardConsumeService } from './StandardConsumeService';
39
39
  import { FifoConsumeService } from './FifoConsumeService';
40
40
  import { ProcessQueue } from './ProcessQueue';
41
+ import { PushConsumerGaugeObserver } from './PushConsumerGaugeObserver';
41
42
  import { Assignment } from './Assignment';
42
43
  import { Assignments } from './Assignments';
43
44
  import { MessageListener } from './MessageListener';
45
+ import { InflightRequestCountInterceptor } from '../hook';
44
46
 
45
47
  const ASSIGNMENT_SCAN_SCHEDULE_DELAY = 1000;
46
48
  const ASSIGNMENT_SCAN_SCHEDULE_PERIOD = 5000;
@@ -52,6 +54,12 @@ export interface PushConsumerOptions extends ConsumerOptions {
52
54
  maxCacheMessageSizeInBytes?: number;
53
55
  longPollingTimeout?: number;
54
56
  enableFifoConsumeAccelerator?: boolean;
57
+ /**
58
+ * Max number of messages in-flight per process queue. Mirrors Java's
59
+ * consumeConcurrentlyMax (default 32) and backs the ProcessQueue semaphore
60
+ * that applies consumption backpressure.
61
+ */
62
+ consumeConcurrentlyMax?: number;
55
63
  }
56
64
 
57
65
  class ConsumeMetrics {
@@ -71,8 +79,10 @@ export class PushConsumer extends Consumer {
71
79
  readonly #enableFifoConsumeAccelerator: boolean;
72
80
  readonly #processQueueTable = new Map<string /* mq key */, { mq: MessageQueue; pq: ProcessQueue }>();
73
81
  readonly #metrics = new ConsumeMetrics();
82
+ readonly #inflightRequestCountInterceptor: InflightRequestCountInterceptor;
74
83
  #consumeService!: ConsumeService;
75
84
  #scanAssignmentTimer?: NodeJS.Timeout;
85
+ #inflightReceiveRequestCount = 0;
76
86
 
77
87
  constructor(options: PushConsumerOptions) {
78
88
  options.topics = Array.from(options.subscriptions.keys());
@@ -91,9 +101,20 @@ export class PushConsumer extends Consumer {
91
101
  this.#maxCacheMessageSizeInBytes = options.maxCacheMessageSizeInBytes ?? 64 * 1024 * 1024;
92
102
  this.#enableFifoConsumeAccelerator = options.enableFifoConsumeAccelerator ?? false;
93
103
 
104
+ // Built-in interceptor tracking in-flight receive requests, mirroring Java PushConsumerImpl.
105
+ this.#inflightRequestCountInterceptor = new InflightRequestCountInterceptor();
106
+ this.addMessageInterceptor(this.#inflightRequestCountInterceptor);
107
+
108
+ // Register the consumer gauge observer so cached message count/bytes are
109
+ // exported to the broker. The provider reads the process-queue table lazily
110
+ // at scrape time, so registering here (before any queue exists) is safe.
111
+ this.clientMeterManager.setGaugeObserver(
112
+ new PushConsumerGaugeObserver(() => this.processQueues(), this.clientId, this.consumerGroup));
113
+
94
114
  this.#pushSubscriptionSettings = new PushSubscriptionSettings(
95
115
  options.namespace, this.clientId, this.getClientType(), this.endpoints,
96
116
  this.consumerGroup, this.requestTimeout, this.#subscriptionExpressions,
117
+ options.longPollingTimeout, options.consumeConcurrentlyMax,
97
118
  );
98
119
  }
99
120
 
@@ -135,15 +156,26 @@ export class PushConsumer extends Consumer {
135
156
  clearInterval(this.#scanAssignmentTimer);
136
157
  this.#scanAssignmentTimer = undefined;
137
158
  }
138
- // Drop all process queues
159
+ // Drop all process queues to stop scheduling new receive requests
139
160
  this.logger.info('Dropping all process queues, clientId=%s, queueCount=%d',
140
161
  this.clientId, this.#processQueueTable.size);
141
162
  for (const { pq } of this.#processQueueTable.values()) {
142
163
  pq.drop();
164
+ }
165
+ // Wait for the inflight receive requests to be finished so that fetched messages can still be consumed
166
+ this.logger.info('Waiting for the inflight receive requests to be finished, clientId=%s', this.clientId);
167
+ await this.#waitForInflightReceiveRequestsFinished();
168
+ // Wait until every cached message has been consumed and settled (acked,
169
+ // redelivered or discarded), i.e. all consumption chains have quiesced
170
+ this.logger.info('Waiting for the cached messages to be consumed, clientId=%s', this.clientId);
171
+ await this.#waitForCachedMessagesConsumed();
172
+ // Reserve a short buffer for the ack/changeInvisibleDuration callbacks to be sent
173
+ await this.sleep(1000);
174
+ // Abort process queues and consume service, no more messages will be received or consumed
175
+ for (const { pq } of this.#processQueueTable.values()) {
143
176
  pq.abort();
144
177
  }
145
178
  this.#processQueueTable.clear();
146
- // Shutdown consume service
147
179
  if (this.#consumeService) {
148
180
  this.logger.info('Shutting down consume service, clientId=%s', this.clientId);
149
181
  this.#consumeService.abort();
@@ -152,6 +184,43 @@ export class PushConsumer extends Consumer {
152
184
  this.logger.info('Push consumer has been shutdown successfully, clientId=%s', this.clientId);
153
185
  }
154
186
 
187
+ async #waitForCachedMessagesConsumed(): Promise<void> {
188
+ // Every received message is cached before consumption and evicted from
189
+ // the cache once its consumption chain settles, so empty caches on all
190
+ // process queues mean consumption has fully quiesced.
191
+ // Bound the wait with the same timeout as the inflight-receive drain
192
+ // (request timeout + long-polling timeout) so shutdown cannot hang forever
193
+ // on a stuck consumption chain.
194
+ const maxWaitingTime = this.requestTimeoutValue
195
+ + this.getPushConsumerSettings().getLongPollingTimeout();
196
+ const endTime = Date.now() + maxWaitingTime;
197
+ while ([ ...this.#processQueueTable.values() ].some(({ pq }) => pq.cachedMessagesCount() > 0)) {
198
+ if (Date.now() > endTime) {
199
+ const remaining = [ ...this.#processQueueTable.values() ]
200
+ .reduce((count, { pq }) => count + pq.cachedMessagesCount(), 0);
201
+ this.logger.warn('Timeout waiting for the cached messages to be consumed, clientId=%s, '
202
+ + 'remainingCachedMessages=%d', this.clientId, remaining);
203
+ return;
204
+ }
205
+ await this.sleep(100);
206
+ }
207
+ }
208
+
209
+ async #waitForInflightReceiveRequestsFinished(): Promise<void> {
210
+ const maxWaitingTime = this.requestTimeoutValue
211
+ + this.getPushConsumerSettings().getLongPollingTimeout();
212
+ const endTime = Date.now() + maxWaitingTime;
213
+ while (this.#inflightReceiveRequestCount > 0 && Date.now() <= endTime) {
214
+ await this.sleep(100);
215
+ }
216
+ if (this.#inflightReceiveRequestCount <= 0) {
217
+ this.logger.info('All inflight receive requests have been finished, clientId=%s', this.clientId);
218
+ } else {
219
+ this.logger.warn('Timeout waiting for all inflight receive requests to be finished, clientId=%s, '
220
+ + 'inflightReceiveRequestCount=%d', this.clientId, this.#inflightReceiveRequestCount);
221
+ }
222
+ }
223
+
155
224
  protected getSettings() {
156
225
  return this.#pushSubscriptionSettings;
157
226
  }
@@ -181,11 +250,22 @@ export class PushConsumer extends Consumer {
181
250
  // No-op for push consumer; assignments are queried separately
182
251
  }
183
252
 
253
+ /**
254
+ * Get the count of in-flight receive requests tracked by the built-in
255
+ * {@link InflightRequestCountInterceptor}, mirroring Java PushConsumerImpl.
256
+ */
257
+ protected getInflightReceiveRequestCountFromInterceptor(): number {
258
+ return this.#inflightRequestCountInterceptor.getInflightReceiveRequestCount();
259
+ }
260
+
184
261
  protected createConsumeService(): ConsumeService {
262
+ // `this` implements MessageInterceptor (doBefore/doAfter delegating to the
263
+ // composited interceptor chain), mirroring Java PushConsumerImpl.
185
264
  if (this.#pushSubscriptionSettings.isFifo()) {
186
- return new FifoConsumeService(this.clientId, this.#messageListener, this.#enableFifoConsumeAccelerator);
265
+ return new FifoConsumeService(this.clientId, this.#messageListener, this.#enableFifoConsumeAccelerator,
266
+ this, this.consumerGroup);
187
267
  }
188
- return new StandardConsumeService(this.clientId, this.#messageListener);
268
+ return new StandardConsumeService(this.clientId, this.#messageListener, this, this.consumerGroup);
189
269
  }
190
270
 
191
271
  async subscribe(topic: string, filterExpression: FilterExpression) {
@@ -296,7 +376,12 @@ export class PushConsumer extends Consumer {
296
376
  }
297
377
 
298
378
  async receiveMessage(request: ReceiveMessageRequest, mq: MessageQueue, awaitDuration: number) {
299
- return super.receiveMessage(request, mq, awaitDuration);
379
+ this.#inflightReceiveRequestCount++;
380
+ try {
381
+ return await super.receiveMessage(request, mq, awaitDuration);
382
+ } finally {
383
+ this.#inflightReceiveRequestCount--;
384
+ }
300
385
  }
301
386
 
302
387
  wrapAckMessageRequest(messageView: MessageView) {
@@ -356,6 +441,14 @@ export class PushConsumer extends Consumer {
356
441
  return this.#processQueueTable.size;
357
442
  }
358
443
 
444
+ /**
445
+ * All live process queues, used by the consumer gauge observer to aggregate
446
+ * cached message count/bytes. Reads the private table lazily at scrape time.
447
+ */
448
+ processQueues(): ProcessQueue[] {
449
+ return [ ...this.#processQueueTable.values() ].map(entry => entry.pq);
450
+ }
451
+
359
452
  cacheMessageBytesThresholdPerQueue(): number {
360
453
  const size = this.getQueueSize();
361
454
  if (size <= 0) return 0;
@@ -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
  }
@@ -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()!.toObject();
133
+ const exponential = backoffPolicy.getExponentialBackoff()!;
108
134
  this.retryPolicy = new ExponentialBackoffRetryPolicy(
109
135
  backoffPolicy.getMaxAttempts(),
110
- exponential.initial?.seconds,
111
- exponential.max?.seconds,
112
- exponential.multiplier,
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
- // CustomizedBackoffRetryPolicy not yet implemented in Node.js
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
  }
@@ -134,6 +134,9 @@ export class SimpleConsumer extends Consumer {
134
134
  }
135
135
 
136
136
  async receive(maxMessageNum = 10, invisibleDuration = 15000) {
137
+ if (!this.isRunning()) {
138
+ throw new Error('Simple consumer is not running, please call startup() first or check shutdown state');
139
+ }
137
140
  if (maxMessageNum <= 0) {
138
141
  throw new Error(`maxMessageNum must be greater than 0, but got ${maxMessageNum}`);
139
142
  }
@@ -177,10 +180,16 @@ export class SimpleConsumer extends Consumer {
177
180
  }
178
181
 
179
182
  async ack(message: MessageView) {
183
+ if (!this.isRunning()) {
184
+ throw new Error('Simple consumer is not running, cannot ack message');
185
+ }
180
186
  await this.ackMessage(message);
181
187
  }
182
188
 
183
189
  async changeInvisibleDuration(message: MessageView, invisibleDuration: number) {
190
+ if (!this.isRunning()) {
191
+ throw new Error('Simple consumer is not running, cannot change invisible duration');
192
+ }
184
193
  const response = await this.invisibleDuration(message, invisibleDuration);
185
194
  // Refresh receipt handle manually
186
195
  (message as any).receiptHandle = response;
@@ -16,6 +16,7 @@
16
16
  */
17
17
 
18
18
  import { MessageView } from '../message';
19
+ import { MessageInterceptor } from '../hook';
19
20
  import { ConsumeService } from './ConsumeService';
20
21
  import { MessageListener } from './MessageListener';
21
22
  import type { ProcessQueue } from './ProcessQueue';
@@ -25,8 +26,9 @@ export class StandardConsumeService extends ConsumeService {
25
26
  private readonly logger = getDefaultLogger();
26
27
 
27
28
  // eslint-disable-next-line @typescript-eslint/no-useless-constructor
28
- constructor(clientId: string, messageListener: MessageListener) {
29
- super(clientId, messageListener);
29
+ constructor(clientId: string, messageListener: MessageListener,
30
+ messageInterceptor?: MessageInterceptor, consumerGroup?: string) {
31
+ super(clientId, messageListener, messageInterceptor, consumerGroup);
30
32
  }
31
33
 
32
34
  consume(pq: ProcessQueue, messageViews: MessageView[]): void {
@@ -34,6 +34,7 @@ export * from './LiteStandardConsumeService';
34
34
  export * from './ProcessQueue';
35
35
  export * from './PushConsumer';
36
36
  export * from './LitePushConsumer';
37
+ export * from './LiteSimpleConsumer';
37
38
  export * from './OffsetOption';
38
39
  export { LitePushConsumerImpl } from './LitePushConsumerImpl';
39
40
  export { LiteSubscriptionManager } from './LiteSubscriptionManager';
@@ -0,0 +1,25 @@
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 { ClientException } from './ClientException';
19
+
20
+ export class PayloadEmptyException extends ClientException {
21
+ constructor(code: number, message: string, requestId?: string) {
22
+ super(code, message, requestId);
23
+ this.name = 'PayloadEmptyException';
24
+ }
25
+ }
@@ -19,8 +19,10 @@ import { Status, Code } from '../../proto/apache/rocketmq/v2/definition_pb';
19
19
  import { BadRequestException } from './BadRequestException';
20
20
  import { ForbiddenException } from './ForbiddenException';
21
21
  import { InternalErrorException } from './InternalErrorException';
22
+ import { LiteSubscriptionQuotaExceededException } from './LiteSubscriptionQuotaExceededException';
22
23
  import { LiteTopicQuotaExceededException } from './LiteTopicQuotaExceededException';
23
24
  import { NotFoundException } from './NotFoundException';
25
+ import { PayloadEmptyException } from './PayloadEmptyException';
24
26
  import { PayloadTooLargeException } from './PayloadTooLargeException';
25
27
  import { PaymentRequiredException } from './PaymentRequiredException';
26
28
  import { ProxyTimeoutException } from './ProxyTimeoutException';
@@ -44,6 +46,7 @@ export class StatusChecker {
44
46
  case Code.ILLEGAL_MESSAGE_KEY:
45
47
  case Code.ILLEGAL_MESSAGE_GROUP:
46
48
  case Code.ILLEGAL_MESSAGE_PROPERTY_KEY:
49
+ case Code.ILLEGAL_LITE_TOPIC:
47
50
  case Code.INVALID_TRANSACTION_ID:
48
51
  case Code.ILLEGAL_MESSAGE_ID:
49
52
  case Code.ILLEGAL_FILTER_EXPRESSION:
@@ -71,6 +74,8 @@ export class StatusChecker {
71
74
  case Code.PAYLOAD_TOO_LARGE:
72
75
  case Code.MESSAGE_BODY_TOO_LARGE:
73
76
  throw new PayloadTooLargeException(status.code, status.message, requestId);
77
+ case Code.MESSAGE_BODY_EMPTY:
78
+ throw new PayloadEmptyException(status.code, status.message, requestId);
74
79
  case Code.TOO_MANY_REQUESTS:
75
80
  throw new TooManyRequestsException(status.code, status.message, requestId);
76
81
  case Code.REQUEST_HEADER_FIELDS_TOO_LARGE:
@@ -90,6 +95,8 @@ export class StatusChecker {
90
95
  throw new UnsupportedException(status.code, status.message, requestId);
91
96
  case Code.LITE_TOPIC_QUOTA_EXCEEDED:
92
97
  throw new LiteTopicQuotaExceededException(status.code, status.message || '', requestId);
98
+ case Code.LITE_SUBSCRIPTION_QUOTA_EXCEEDED:
99
+ throw new LiteSubscriptionQuotaExceededException(status.code, requestId ?? null, status.message || '');
93
100
  default:
94
101
  throw new UnsupportedException(status.code, status.message, requestId);
95
102
  }
@@ -22,6 +22,7 @@ export * from './InternalErrorException';
22
22
  export * from './LiteSubscriptionQuotaExceededException';
23
23
  export * from './LiteTopicQuotaExceededException';
24
24
  export * from './NotFoundException';
25
+ export * from './PayloadEmptyException';
25
26
  export * from './PayloadTooLargeException';
26
27
  export * from './PaymentRequiredException';
27
28
  export * from './ProxyTimeoutException';
@@ -0,0 +1,36 @@
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
+ /**
19
+ * Immutable value holder shared through a {@link MessageInterceptorContext},
20
+ * mirroring org.apache.rocketmq.client.java.hook.Attribute.
21
+ */
22
+ export class Attribute<T> {
23
+ readonly #value: T;
24
+
25
+ private constructor(value: T) {
26
+ this.#value = value;
27
+ }
28
+
29
+ static create<T>(value: T): Attribute<T> {
30
+ return new Attribute(value);
31
+ }
32
+
33
+ get(): T {
34
+ return this.#value;
35
+ }
36
+ }
@@ -0,0 +1,42 @@
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
+ /**
19
+ * Typed key of a context attribute, mirroring
20
+ * org.apache.rocketmq.client.java.hook.AttributeKey.
21
+ *
22
+ * The type parameter is only used for compile-time typing of the associated value.
23
+ */
24
+ export class AttributeKey<T> {
25
+ readonly name: string;
26
+ /**
27
+ * Never assigned at runtime; it only carries the value type for compile-time typing.
28
+ */
29
+ readonly typeHint?: T;
30
+
31
+ constructor(name: string) {
32
+ this.name = name;
33
+ }
34
+
35
+ static create<T>(name: string): AttributeKey<T> {
36
+ return new AttributeKey<T>(name);
37
+ }
38
+
39
+ toString() {
40
+ return `AttributeKey(${this.name})`;
41
+ }
42
+ }
@@ -0,0 +1,92 @@
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 { Attribute } from './Attribute';
19
+ import { AttributeKey } from './AttributeKey';
20
+ import { MessageHookPointsStatus } from './MessageHookPointsStatus';
21
+ import { MessageInterceptorContext } from './MessageInterceptorContext';
22
+ import { MessageInterceptorContextImpl } from './MessageInterceptorContextImpl';
23
+ import { GeneralMessage, MessageInterceptor } from './MessageInterceptor';
24
+
25
+ // Key under which per-interceptor attributes are stashed between doBefore and doAfter.
26
+ const INTERCEPTOR_ATTRIBUTES_KEY = AttributeKey
27
+ .create<Map<number, Map<AttributeKey<any>, Attribute<any>>>>('composited_interceptor_attributes');
28
+
29
+ /**
30
+ * Composite interceptor which delegates to a chain of interceptors: doBefore runs
31
+ * in registration order while doAfter runs in reverse order, mirroring
32
+ * org.apache.rocketmq.client.java.hook.CompositedMessageInterceptor.
33
+ */
34
+ export class CompositedMessageInterceptor implements MessageInterceptor {
35
+ readonly #interceptors: MessageInterceptor[] = [];
36
+
37
+ constructor(interceptors: MessageInterceptor[] = []) {
38
+ this.#interceptors.push(...interceptors);
39
+ }
40
+
41
+ addInterceptor(interceptor: MessageInterceptor) {
42
+ this.#interceptors.push(interceptor);
43
+ }
44
+
45
+ get size() {
46
+ return this.#interceptors.length;
47
+ }
48
+
49
+ doBefore(context0: MessageInterceptorContext, messages: GeneralMessage[]) {
50
+ const attributeMap = new Map<number, Map<AttributeKey<any>, Attribute<any>>>();
51
+ // A single cumulative context is shared by the whole chain, mirroring the Java
52
+ // implementation, so that later interceptors observe what earlier ones recorded.
53
+ const context = new MessageInterceptorContextImpl(context0.getMessageHookPoints(), context0.getStatus());
54
+ for (let index = 0; index < this.#interceptors.length; index++) {
55
+ for (const [ key, value ] of context0.getAttributes()) {
56
+ context.putAttribute(key, value);
57
+ }
58
+ try {
59
+ this.#interceptors[index].doBefore(context, messages);
60
+ } catch (t) {
61
+ // Interceptors must never break the message pipeline.
62
+ // eslint-disable-next-line no-console
63
+ console.error(
64
+ '[CompositedMessageInterceptor] Exception raised while handling messages before hook point=%s, error=%s',
65
+ context0.getMessageHookPoints(), t);
66
+ }
67
+ attributeMap.set(index, context.getAttributes());
68
+ }
69
+ context0.putAttribute(INTERCEPTOR_ATTRIBUTES_KEY, Attribute.create(attributeMap));
70
+ }
71
+
72
+ doAfter(context0: MessageInterceptorContext, messages: GeneralMessage[]) {
73
+ const attributeMap = context0.getAttribute(INTERCEPTOR_ATTRIBUTES_KEY)?.get()
74
+ ?? new Map<number, Map<AttributeKey<any>, Attribute<any>>>();
75
+ for (let index = this.#interceptors.length - 1; index >= 0; index--) {
76
+ const attributes = attributeMap.get(index);
77
+ const context = new MessageInterceptorContextImpl(
78
+ context0.getMessageHookPoints(), context0.getStatus() ?? MessageHookPointsStatus.OK, attributes);
79
+ for (const [ key, value ] of context0.getAttributes()) {
80
+ context.putAttribute(key, value);
81
+ }
82
+ try {
83
+ this.#interceptors[index].doAfter(context, messages);
84
+ } catch (t) {
85
+ // eslint-disable-next-line no-console
86
+ console.error(
87
+ '[CompositedMessageInterceptor] Exception raised while handling messages after hook point=%s, error=%s',
88
+ context0.getMessageHookPoints(), t);
89
+ }
90
+ }
91
+ }
92
+ }