rocketmq-client-nodejs 1.0.6 → 1.0.8

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 (33) hide show
  1. package/dist/consumer/ConsumeResult.d.ts +38 -3
  2. package/dist/consumer/ConsumeResult.js +61 -7
  3. package/dist/consumer/FifoConsumeService.d.ts +33 -1
  4. package/dist/consumer/FifoConsumeService.js +72 -87
  5. package/dist/consumer/LiteFifoConsumeService.d.ts +44 -0
  6. package/dist/consumer/LiteFifoConsumeService.js +94 -0
  7. package/dist/consumer/LitePushConsumer.d.ts +14 -0
  8. package/dist/consumer/LitePushConsumer.js +25 -4
  9. package/dist/consumer/LitePushConsumerImpl.d.ts +9 -0
  10. package/dist/consumer/LitePushConsumerImpl.js +30 -1
  11. package/dist/consumer/LiteStandardConsumeService.d.ts +32 -0
  12. package/dist/consumer/LiteStandardConsumeService.js +63 -0
  13. package/dist/consumer/ProcessQueue.js +54 -8
  14. package/dist/consumer/PushConsumer.d.ts +1 -0
  15. package/dist/consumer/PushConsumer.js +49 -7
  16. package/dist/consumer/index.d.ts +2 -0
  17. package/dist/consumer/index.js +3 -1
  18. package/dist/message/MessageView.d.ts +8 -1
  19. package/dist/message/MessageView.js +11 -1
  20. package/dist/util/index.js +6 -3
  21. package/package.json +1 -1
  22. package/proto/apache/rocketmq/v2/definition.proto +1 -1
  23. package/src/consumer/ConsumeResult.ts +65 -3
  24. package/src/consumer/FifoConsumeService.ts +78 -93
  25. package/src/consumer/LiteFifoConsumeService.ts +103 -0
  26. package/src/consumer/LitePushConsumer.ts +29 -3
  27. package/src/consumer/LitePushConsumerImpl.ts +36 -0
  28. package/src/consumer/LiteStandardConsumeService.ts +73 -0
  29. package/src/consumer/ProcessQueue.ts +75 -8
  30. package/src/consumer/PushConsumer.ts +48 -6
  31. package/src/consumer/index.ts +2 -0
  32. package/src/message/MessageView.ts +12 -1
  33. package/src/util/index.ts +5 -2
@@ -0,0 +1,73 @@
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 { MessageView } from '../message';
19
+ import { ConsumeService } from './ConsumeService';
20
+ import { MessageListener } from './MessageListener';
21
+ import type { ProcessQueue } from './ProcessQueue';
22
+ import { ILogger, getDefaultLogger } from '../client/Logger';
23
+
24
+ /**
25
+ * Standard consume service for lite push consumer.
26
+ *
27
+ * <p>Similar to {@link StandardConsumeService}, but uses
28
+ * {@link ProcessQueue#eraseFifoMessage} for local retry on failure, avoiding
29
+ * frequent server requests.</p>
30
+ */
31
+ export class LiteStandardConsumeService extends ConsumeService {
32
+ readonly #logger: ILogger;
33
+
34
+ constructor(clientId: string, messageListener: MessageListener) {
35
+ super(clientId, messageListener);
36
+ this.#logger = getDefaultLogger();
37
+ }
38
+
39
+ consume(pq: ProcessQueue, messageViews: MessageView[]): void {
40
+ if (!pq || !messageViews) {
41
+ this.#logger.error('[Bug] Invalid arguments for consume, pq=%s, messageViews=%s, clientId=%s', pq, messageViews, this.clientId);
42
+ return;
43
+ }
44
+
45
+ this.#logger.debug?.('LiteStandardConsumeService.consume called, messageCount=%d, clientId=%s', messageViews.length, this.clientId);
46
+
47
+ for (const messageView of messageViews) {
48
+ if (messageView.corrupted) {
49
+ this.#logger.error('Message is corrupted for lite standard consumption, prepare to discard it, mq=%s, '
50
+ + 'messageId=%s, clientId=%s',
51
+ pq.getMessageQueue(), messageView.messageId, this.clientId);
52
+ pq.discardMessage(messageView);
53
+ continue;
54
+ }
55
+
56
+ this.#logger.debug?.('Consuming lite message, messageId=%s, topic=%s, liteTopic=%s, clientId=%s',
57
+ messageView.messageId, messageView.topic, messageView.liteTopic, this.clientId);
58
+
59
+ this.consumeMessage(messageView)
60
+ .then(result => {
61
+ this.#logger.debug?.('Lite message consumed successfully, messageId=%s, result=%s, clientId=%s',
62
+ messageView.messageId, result, this.clientId);
63
+ // Use eraseFifoMessage for local retry on failure, avoiding frequent server requests.
64
+ pq.eraseFifoMessage(messageView, result);
65
+ })
66
+ .catch(err => {
67
+ // Should never reach here.
68
+ this.#logger.error('[Bug] Exception raised in lite standard consumption callback, clientId=%s, error=%s',
69
+ this.clientId, err);
70
+ });
71
+ }
72
+ }
73
+ }
@@ -20,7 +20,7 @@ import { Code } from '../../proto/apache/rocketmq/v2/definition_pb';
20
20
  import { MessageView } from '../message';
21
21
  import { MessageQueue } from '../route';
22
22
  import { TooManyRequestsException } from '../exception';
23
- import { ConsumeResult } from './ConsumeResult';
23
+ import { ConsumeResult, ConsumeResultSuspend } from './ConsumeResult';
24
24
  import { FilterExpression } from './FilterExpression';
25
25
  import type { PushConsumer } from './PushConsumer';
26
26
 
@@ -73,6 +73,9 @@ export class ProcessQueue {
73
73
  }
74
74
 
75
75
  cacheMessages(messageList: MessageView[]): void {
76
+ if (!messageList || messageList.length === 0) {
77
+ return;
78
+ }
76
79
  for (const messageView of messageList) {
77
80
  this.#cachedMessages.push(messageView);
78
81
  this.#cachedMessagesBytes += messageView.body.length;
@@ -187,6 +190,11 @@ export class ProcessQueue {
187
190
  }
188
191
 
189
192
  eraseMessage(messageView: MessageView, consumeResult: ConsumeResult): void {
193
+ if (!messageView) {
194
+ return;
195
+ }
196
+ consumeResult = this.#convertSuspendResultIfNeeded(consumeResult);
197
+ this.#statsConsumptionResult(consumeResult);
190
198
  const task = consumeResult === ConsumeResult.SUCCESS
191
199
  ? this.#ackMessage(messageView)
192
200
  : this.#nackMessage(messageView);
@@ -210,7 +218,11 @@ export class ProcessQueue {
210
218
  if (status?.code !== Code.OK) {
211
219
  await this.#ackMessageLater(messageView, attempt + 1);
212
220
  }
213
- } catch {
221
+ } catch (err) {
222
+ (this.#consumer as any).logger?.warn(
223
+ 'Failed to ack message, attempt=%d, messageId=%s, error=%s',
224
+ attempt, messageView.messageId, err,
225
+ );
214
226
  await this.#ackMessageLater(messageView, attempt + 1);
215
227
  }
216
228
  }
@@ -243,7 +255,11 @@ export class ProcessQueue {
243
255
  if (status?.code !== Code.OK) {
244
256
  await this.#changeInvisibleDurationLater(messageView, duration, attempt + 1);
245
257
  }
246
- } catch {
258
+ } catch (err) {
259
+ (this.#consumer as any).logger?.warn(
260
+ 'Failed to change invisible duration, attempt=%d, duration=%dms, messageId=%s, error=%s',
261
+ attempt, duration, messageView.messageId, err,
262
+ );
247
263
  await this.#changeInvisibleDurationLater(messageView, duration, attempt + 1);
248
264
  }
249
265
  }
@@ -256,22 +272,51 @@ export class ProcessQueue {
256
272
  }
257
273
 
258
274
  async eraseFifoMessage(messageView: MessageView, consumeResult: ConsumeResult): Promise<void> {
275
+ if (!messageView) {
276
+ return;
277
+ }
278
+ consumeResult = this.#convertSuspendResultIfNeeded(consumeResult);
279
+ this.#statsConsumptionResult(consumeResult);
259
280
  const retryPolicy = this.#consumer.getRetryPolicy();
260
281
  const maxAttempts = retryPolicy?.getMaxAttempts() ?? 1;
261
282
  const attempt = messageView.deliveryAttempt ?? 1;
283
+ const messageId = messageView.messageId;
284
+ const clientId = (this.#consumer as any).clientId;
262
285
 
263
286
  if (consumeResult === ConsumeResult.FAILURE && attempt < maxAttempts) {
264
287
  const nextAttemptDelay = retryPolicy?.getNextAttemptDelay(attempt) ?? 0;
288
+ // Increment delivery attempt before redelivering
289
+ messageView.incrementAndGetDeliveryAttempt();
290
+ (this.#consumer as any).logger?.debug(
291
+ 'Prepare to redeliver the fifo message because of the consumption failure, maxAttempts=%d, '
292
+ + 'attempt=%d, mq=%s, messageId=%s, nextAttemptDelay=%d, clientId=%s',
293
+ maxAttempts, messageView.deliveryAttempt, this.#mq, messageId, nextAttemptDelay, clientId,
294
+ );
265
295
  // Redeliver the fifo message
266
296
  const result = await this.#consumer.getConsumeService().consumeMessage(messageView, nextAttemptDelay);
267
297
  await this.eraseFifoMessage(messageView, result);
298
+ return;
299
+ }
300
+
301
+ if (consumeResult === ConsumeResult.SUCCESS) {
302
+ await this.#ackMessage(messageView);
303
+ } else if (consumeResult instanceof ConsumeResultSuspend) {
304
+ const suspendTimeMs = consumeResult.suspendTimeMs;
305
+ (this.#consumer as any).logger?.info(
306
+ 'Suspend consumption, consumerGroup=%s, topic=%s, liteTopic=%s, messageId=%s, result=%s',
307
+ this.#consumer.getConsumerGroup(), messageView.topic, messageView.liteTopic ?? '',
308
+ messageId, consumeResult,
309
+ );
310
+ await this.#changeInvisibleDuration(messageView, suspendTimeMs);
268
311
  } else {
269
- const task = consumeResult === ConsumeResult.SUCCESS
270
- ? this.#ackMessage(messageView)
271
- : this.#forwardToDeadLetterQueue(messageView);
272
- await task;
273
- this.#evictCache(messageView);
312
+ (this.#consumer as any).logger?.info(
313
+ 'Failed to consume fifo message finally, run out of attempt times, maxAttempts=%d, attempt=%d, '
314
+ + 'mq=%s, messageId=%s, clientId=%s',
315
+ maxAttempts, attempt, this.#mq, messageId, clientId,
316
+ );
317
+ await this.#forwardToDeadLetterQueue(messageView);
274
318
  }
319
+ this.#evictCache(messageView);
275
320
  }
276
321
 
277
322
  async #forwardToDeadLetterQueue(messageView: MessageView, attempt = 1): Promise<void> {
@@ -325,6 +370,28 @@ export class ProcessQueue {
325
370
  }
326
371
  }
327
372
 
373
+ #convertSuspendResultIfNeeded(consumeResult: ConsumeResult): ConsumeResult {
374
+ if (consumeResult instanceof ConsumeResultSuspend) {
375
+ if (!(this.#consumer as any).isLiteConsumer?.()) {
376
+ (this.#consumer as any).logger?.warn(
377
+ 'Only LitePushConsumer support ConsumeResultSuspend! Convert to ConsumeResult.FAILURE, '
378
+ + 'consumerGroup=%s, consumerType=%s',
379
+ this.#consumer.getConsumerGroup(), this.#consumer.constructor.name,
380
+ );
381
+ return ConsumeResult.FAILURE;
382
+ }
383
+ }
384
+ return consumeResult;
385
+ }
386
+
387
+ #statsConsumptionResult(consumeResult: ConsumeResult): void {
388
+ if (consumeResult === ConsumeResult.SUCCESS) {
389
+ this.#consumer.incrementConsumptionOkQuantity();
390
+ return;
391
+ }
392
+ this.#consumer.incrementConsumptionErrorQuantity();
393
+ }
394
+
328
395
  cachedMessagesCount(): number {
329
396
  return this.#cachedMessages.length;
330
397
  }
@@ -73,6 +73,7 @@ export class PushConsumer extends Consumer {
73
73
  readonly #metrics = new ConsumeMetrics();
74
74
  #consumeService!: ConsumeService;
75
75
  #scanAssignmentTimer?: NodeJS.Timeout;
76
+ #inflightReceiveRequestCount = 0;
76
77
 
77
78
  constructor(options: PushConsumerOptions) {
78
79
  options.topics = Array.from(options.subscriptions.keys());
@@ -103,7 +104,7 @@ export class PushConsumer extends Consumer {
103
104
  await super.startup();
104
105
  this.logger.info('Super startup completed, clientId=%s', this.clientId);
105
106
  try {
106
- this.#consumeService = this.#createConsumeService();
107
+ this.#consumeService = this.createConsumeService();
107
108
  // Start scanning assignments periodically
108
109
  this.startAssignmentScanning();
109
110
  this.logger.info('Push consumer started successfully, clientId=%s', this.clientId);
@@ -135,15 +136,26 @@ export class PushConsumer extends Consumer {
135
136
  clearInterval(this.#scanAssignmentTimer);
136
137
  this.#scanAssignmentTimer = undefined;
137
138
  }
138
- // Drop all process queues
139
+ // Drop all process queues to stop scheduling new receive requests
139
140
  this.logger.info('Dropping all process queues, clientId=%s, queueCount=%d',
140
141
  this.clientId, this.#processQueueTable.size);
141
142
  for (const { pq } of this.#processQueueTable.values()) {
142
143
  pq.drop();
144
+ }
145
+ // Wait for the inflight receive requests to be finished so that fetched messages can still be consumed
146
+ this.logger.info('Waiting for the inflight receive requests to be finished, clientId=%s', this.clientId);
147
+ await this.#waitForInflightReceiveRequestsFinished();
148
+ // Wait until every cached message has been consumed and settled (acked,
149
+ // redelivered or discarded), i.e. all consumption chains have quiesced
150
+ this.logger.info('Waiting for the cached messages to be consumed, clientId=%s', this.clientId);
151
+ await this.#waitForCachedMessagesConsumed();
152
+ // Reserve a short buffer for the ack/changeInvisibleDuration callbacks to be sent
153
+ await this.sleep(1000);
154
+ // Abort process queues and consume service, no more messages will be received or consumed
155
+ for (const { pq } of this.#processQueueTable.values()) {
143
156
  pq.abort();
144
157
  }
145
158
  this.#processQueueTable.clear();
146
- // Shutdown consume service
147
159
  if (this.#consumeService) {
148
160
  this.logger.info('Shutting down consume service, clientId=%s', this.clientId);
149
161
  this.#consumeService.abort();
@@ -152,6 +164,30 @@ export class PushConsumer extends Consumer {
152
164
  this.logger.info('Push consumer has been shutdown successfully, clientId=%s', this.clientId);
153
165
  }
154
166
 
167
+ async #waitForCachedMessagesConsumed(): Promise<void> {
168
+ // Every received message is cached before consumption and evicted from
169
+ // the cache once its consumption chain settles, so empty caches on all
170
+ // process queues mean consumption has fully quiesced.
171
+ while ([ ...this.#processQueueTable.values() ].some(({ pq }) => pq.cachedMessagesCount() > 0)) {
172
+ await this.sleep(100);
173
+ }
174
+ }
175
+
176
+ async #waitForInflightReceiveRequestsFinished(): Promise<void> {
177
+ const maxWaitingTime = this.requestTimeoutValue
178
+ + this.getPushConsumerSettings().getLongPollingTimeout();
179
+ const endTime = Date.now() + maxWaitingTime;
180
+ while (this.#inflightReceiveRequestCount > 0 && Date.now() <= endTime) {
181
+ await this.sleep(100);
182
+ }
183
+ if (this.#inflightReceiveRequestCount <= 0) {
184
+ this.logger.info('All inflight receive requests have been finished, clientId=%s', this.clientId);
185
+ } else {
186
+ this.logger.warn('Timeout waiting for all inflight receive requests to be finished, clientId=%s, '
187
+ + 'inflightReceiveRequestCount=%d', this.clientId, this.#inflightReceiveRequestCount);
188
+ }
189
+ }
190
+
155
191
  protected getSettings() {
156
192
  return this.#pushSubscriptionSettings;
157
193
  }
@@ -181,7 +217,7 @@ export class PushConsumer extends Consumer {
181
217
  // No-op for push consumer; assignments are queried separately
182
218
  }
183
219
 
184
- #createConsumeService(): ConsumeService {
220
+ protected createConsumeService(): ConsumeService {
185
221
  if (this.#pushSubscriptionSettings.isFifo()) {
186
222
  return new FifoConsumeService(this.clientId, this.#messageListener, this.#enableFifoConsumeAccelerator);
187
223
  }
@@ -296,7 +332,12 @@ export class PushConsumer extends Consumer {
296
332
  }
297
333
 
298
334
  async receiveMessage(request: ReceiveMessageRequest, mq: MessageQueue, awaitDuration: number) {
299
- return super.receiveMessage(request, mq, awaitDuration);
335
+ this.#inflightReceiveRequestCount++;
336
+ try {
337
+ return await super.receiveMessage(request, mq, awaitDuration);
338
+ } finally {
339
+ this.#inflightReceiveRequestCount--;
340
+ }
300
341
  }
301
342
 
302
343
  wrapAckMessageRequest(messageView: MessageView) {
@@ -323,9 +364,10 @@ export class PushConsumer extends Consumer {
323
364
  .setInvisibleDuration(createDuration(invisibleDuration))
324
365
  .setMessageId(messageView.messageId);
325
366
 
326
- // For lite consumers, must set liteTopic in request
367
+ // For lite consumers, must set liteTopic and suspend in request
327
368
  if (this.isLiteConsumer() && messageView.liteTopic) {
328
369
  request.setLiteTopic(messageView.liteTopic);
370
+ request.setSuspend(true);
329
371
  }
330
372
 
331
373
  return request;
@@ -29,6 +29,8 @@ export * from './ConsumeTask';
29
29
  export * from './ConsumeService';
30
30
  export * from './StandardConsumeService';
31
31
  export * from './FifoConsumeService';
32
+ export * from './LiteFifoConsumeService';
33
+ export * from './LiteStandardConsumeService';
32
34
  export * from './ProcessQueue';
33
35
  export * from './PushConsumer';
34
36
  export * from './LitePushConsumer';
@@ -36,7 +36,7 @@ export class MessageView {
36
36
  readonly keys: string[];
37
37
  readonly bornHost: string;
38
38
  readonly bornTimestamp?: Date;
39
- readonly deliveryAttempt?: number;
39
+ deliveryAttempt?: number;
40
40
  readonly endpoints: Endpoints;
41
41
  readonly receiptHandle: string;
42
42
  readonly offset?: number;
@@ -218,4 +218,15 @@ export class MessageView {
218
218
  getDeliveryAttempt(): number | undefined {
219
219
  return this.deliveryAttempt;
220
220
  }
221
+
222
+ /**
223
+ * Increment the delivery attempt and return the new value.
224
+ * Used by FIFO retry logic to track redelivery attempts.
225
+ *
226
+ * @return the incremented delivery attempt
227
+ */
228
+ incrementAndGetDeliveryAttempt(): number {
229
+ this.deliveryAttempt = (this.deliveryAttempt ?? 0) + 1;
230
+ return this.deliveryAttempt;
231
+ }
221
232
  }
package/src/util/index.ts CHANGED
@@ -45,9 +45,12 @@ export function sign(accessSecret: string, dateTime: string) {
45
45
  }
46
46
 
47
47
  export function createDuration(ms: number) {
48
- const nanos = ms % 1000 * 1000000;
48
+ // Duration.seconds is a protobuf int64 field, so it must be an integer;
49
+ // the remainder is carried by nanos. Non-integer seconds would fail
50
+ // serialization with 'Assertion failed'.
51
+ const nanos = Math.floor(ms % 1000 * 1000000);
49
52
  return new Duration()
50
- .setSeconds(ms / 1000)
53
+ .setSeconds(Math.floor(ms / 1000))
51
54
  .setNanos(nanos);
52
55
  }
53
56