rocketmq-client-nodejs 1.1.0 → 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.
Files changed (109) hide show
  1. package/dist/client/BaseClient.d.ts +8 -0
  2. package/dist/client/BaseClient.js +197 -93
  3. package/dist/client/Logger.js +9 -6
  4. package/dist/client/RpcClient.js +29 -133
  5. package/dist/client/RpcClientManager.d.ts +17 -17
  6. package/dist/client/RpcClientManager.js +38 -50
  7. package/dist/client/TelemetrySession.js +68 -13
  8. package/dist/consumer/ConsumeService.js +6 -4
  9. package/dist/consumer/ConsumeTask.js +5 -5
  10. package/dist/consumer/Consumer.js +13 -13
  11. package/dist/consumer/FifoConsumeService.d.ts +2 -1
  12. package/dist/consumer/FifoConsumeService.js +3 -3
  13. package/dist/consumer/LiteConsumerSupport.d.ts +25 -0
  14. package/dist/consumer/LiteConsumerSupport.js +47 -0
  15. package/dist/consumer/LiteFifoConsumeService.d.ts +2 -1
  16. package/dist/consumer/LiteFifoConsumeService.js +4 -4
  17. package/dist/consumer/LitePushConsumerImpl.d.ts +3 -3
  18. package/dist/consumer/LitePushConsumerImpl.js +10 -29
  19. package/dist/consumer/LiteSimpleConsumerImpl.js +6 -14
  20. package/dist/consumer/LiteStandardConsumeService.d.ts +2 -1
  21. package/dist/consumer/LiteStandardConsumeService.js +3 -3
  22. package/dist/consumer/LiteSubscriptionManager.js +10 -9
  23. package/dist/consumer/OffsetOption.d.ts +1 -0
  24. package/dist/consumer/OffsetOption.js +10 -4
  25. package/dist/consumer/ProcessQueue.d.ts +7 -1
  26. package/dist/consumer/ProcessQueue.js +95 -90
  27. package/dist/consumer/PushConsumer.js +79 -27
  28. package/dist/consumer/PushSubscriptionSettings.js +3 -3
  29. package/dist/consumer/SimpleConsumer.d.ts +5 -0
  30. package/dist/consumer/SimpleConsumer.js +24 -20
  31. package/dist/consumer/SimpleSubscriptionSettings.js +3 -3
  32. package/dist/consumer/StandardConsumeService.d.ts +2 -1
  33. package/dist/consumer/StandardConsumeService.js +16 -7
  34. package/dist/consumer/SubscriptionLoadBalancer.js +3 -3
  35. package/dist/exception/InternalErrorException.d.ts +1 -0
  36. package/dist/exception/InternalErrorException.js +3 -2
  37. package/dist/exception/StatusChecker.js +4 -4
  38. package/dist/exception/receiveStatus.d.ts +18 -0
  39. package/dist/exception/receiveStatus.js +28 -0
  40. package/dist/hook/CompositedMessageInterceptor.d.ts +2 -1
  41. package/dist/hook/CompositedMessageInterceptor.js +8 -5
  42. package/dist/hook/MessageInterceptorContextImpl.d.ts +1 -0
  43. package/dist/hook/MessageInterceptorContextImpl.js +18 -4
  44. package/dist/message/Message.js +26 -4
  45. package/dist/message/MessageView.js +15 -5
  46. package/dist/message/PublishingMessage.js +4 -4
  47. package/dist/metrics/ClientMeterManager.d.ts +4 -0
  48. package/dist/metrics/ClientMeterManager.js +95 -19
  49. package/dist/producer/Producer.d.ts +8 -2
  50. package/dist/producer/Producer.js +66 -45
  51. package/dist/producer/PublishingLoadBalancer.js +3 -3
  52. package/dist/producer/PublishingSettings.js +1 -3
  53. package/dist/producer/SendReceipt.js +3 -2
  54. package/dist/producer/Transaction.d.ts +2 -1
  55. package/dist/producer/Transaction.js +9 -8
  56. package/dist/producer/index.d.ts +1 -0
  57. package/dist/producer/index.js +2 -2
  58. package/dist/route/Endpoints.js +17 -9
  59. package/dist/route/MessageQueue.js +7 -2
  60. package/dist/route/TopicRouteData.d.ts +5 -0
  61. package/dist/route/TopicRouteData.js +22 -1
  62. package/dist/util/index.d.ts +1 -1
  63. package/dist/util/index.js +9 -6
  64. package/dist/util/rpcContext.d.ts +20 -0
  65. package/dist/util/rpcContext.js +35 -0
  66. package/package.json +6 -3
  67. package/src/client/BaseClient.ts +211 -100
  68. package/src/client/Logger.ts +9 -5
  69. package/src/client/RpcClient.ts +48 -132
  70. package/src/client/RpcClientManager.ts +76 -52
  71. package/src/client/TelemetrySession.ts +70 -13
  72. package/src/consumer/ConsumeService.ts +7 -3
  73. package/src/consumer/ConsumeTask.ts +4 -4
  74. package/src/consumer/Consumer.ts +16 -15
  75. package/src/consumer/FifoConsumeService.ts +2 -2
  76. package/src/consumer/LiteConsumerSupport.ts +49 -0
  77. package/src/consumer/LiteFifoConsumeService.ts +3 -3
  78. package/src/consumer/LitePushConsumerImpl.ts +15 -22
  79. package/src/consumer/LiteSimpleConsumerImpl.ts +7 -14
  80. package/src/consumer/LiteStandardConsumeService.ts +2 -2
  81. package/src/consumer/LiteSubscriptionManager.ts +12 -14
  82. package/src/consumer/OffsetOption.ts +10 -3
  83. package/src/consumer/ProcessQueue.ts +123 -108
  84. package/src/consumer/PushConsumer.ts +83 -26
  85. package/src/consumer/PushSubscriptionSettings.ts +2 -2
  86. package/src/consumer/SimpleConsumer.ts +30 -23
  87. package/src/consumer/SimpleSubscriptionSettings.ts +2 -2
  88. package/src/consumer/StandardConsumeService.ts +15 -6
  89. package/src/consumer/SubscriptionLoadBalancer.ts +2 -2
  90. package/src/exception/InternalErrorException.ts +3 -1
  91. package/src/exception/StatusChecker.ts +3 -2
  92. package/src/exception/receiveStatus.ts +25 -0
  93. package/src/hook/CompositedMessageInterceptor.ts +8 -4
  94. package/src/hook/MessageInterceptorContextImpl.ts +18 -3
  95. package/src/message/Message.ts +25 -3
  96. package/src/message/MessageView.ts +13 -4
  97. package/src/message/PublishingMessage.ts +3 -3
  98. package/src/metrics/ClientMeterManager.ts +100 -18
  99. package/src/producer/Producer.ts +71 -46
  100. package/src/producer/PublishingLoadBalancer.ts +2 -2
  101. package/src/producer/PublishingSettings.ts +0 -2
  102. package/src/producer/SendReceipt.ts +2 -1
  103. package/src/producer/Transaction.ts +12 -11
  104. package/src/producer/index.ts +1 -1
  105. package/src/route/Endpoints.ts +16 -8
  106. package/src/route/MessageQueue.ts +6 -1
  107. package/src/route/TopicRouteData.ts +22 -1
  108. package/src/util/index.ts +8 -5
  109. package/src/util/rpcContext.ts +34 -0
@@ -16,14 +16,16 @@
16
16
  */
17
17
 
18
18
  import { randomUUID } from 'node:crypto';
19
- import { Code } from '../../proto/apache/rocketmq/v2/definition_pb';
19
+ import { Code, Status } 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 { getRequestId } from '../util/rpcContext';
23
24
  import { ConsumeResult, ConsumeResultSuspend } from './ConsumeResult';
24
25
  import { FilterExpression } from './FilterExpression';
25
26
  import type { PushConsumer } from './PushConsumer';
26
27
  import { Semaphore } from '../util/Semaphore';
28
+ import { ILogger, getDefaultLogger } from '../client/Logger';
27
29
 
28
30
  const ACK_MESSAGE_FAILURE_BACKOFF_DELAY = 1000;
29
31
  const CHANGE_INVISIBLE_DURATION_FAILURE_BACKOFF_DELAY = 1000;
@@ -36,6 +38,9 @@ const RECEIVING_BACKOFF_DELAY_WHEN_PERMITS_EXHAUSTED = 20;
36
38
 
37
39
  export class ProcessQueue {
38
40
  readonly #consumer: PushConsumer;
41
+ readonly #logger: ILogger;
42
+ readonly #clientId: string;
43
+ readonly #liteConsumer: boolean;
39
44
  #dropped = false;
40
45
  readonly #mq: MessageQueue;
41
46
  readonly #filterExpression: FilterExpression;
@@ -44,16 +49,35 @@ export class ProcessQueue {
44
49
  #activityTime = Date.now();
45
50
  #cacheFullTime = 0;
46
51
  #aborted = false;
52
+ #inflightReceives = 0;
47
53
  // Bounds in-flight messages per queue; mirrors Java ProcessQueueImpl permits.
48
54
  readonly #semaphore: Semaphore;
49
55
 
50
- constructor(consumer: PushConsumer, mq: MessageQueue, filterExpression: FilterExpression) {
56
+ // `context` carries the logger and identity of the owning consumer. PushConsumer always passes it;
57
+ // when omitted they are read from the consumer so existing three-argument calls keep working.
58
+ constructor(consumer: PushConsumer, mq: MessageQueue, filterExpression: FilterExpression,
59
+ context?: { logger: ILogger; clientId: string; liteConsumer: boolean }) {
60
+ context = context ?? ProcessQueue.#contextOf(consumer);
51
61
  this.#consumer = consumer;
62
+ this.#logger = context.logger;
63
+ this.#clientId = context.clientId;
64
+ this.#liteConsumer = context.liteConsumer;
52
65
  this.#mq = mq;
53
66
  this.#filterExpression = filterExpression;
54
67
  this.#semaphore = new Semaphore(consumer.getPushConsumerSettings().getConsumeConcurrentlyMax());
55
68
  }
56
69
 
70
+ static #contextOf(consumer: PushConsumer) {
71
+ // logger and isLiteConsumer() are protected on the consumer; this is the only place
72
+ // that reads them, for callers constructing a process queue without a context.
73
+ const legacy = consumer as unknown as { logger?: ILogger; isLiteConsumer?: () => boolean };
74
+ return {
75
+ logger: legacy.logger ?? getDefaultLogger(),
76
+ clientId: consumer.clientId,
77
+ liteConsumer: legacy.isLiteConsumer?.() ?? false,
78
+ };
79
+ }
80
+
57
81
  getMessageQueue(): MessageQueue {
58
82
  return this.#mq;
59
83
  }
@@ -121,7 +145,10 @@ export class ProcessQueue {
121
145
  }
122
146
 
123
147
  fetchMessageImmediately(): void {
124
- (this.#consumer as any).logger?.info('ProcessQueue.fetchMessageImmediately called, mq=%s@%s@%d',
148
+ if (this.#dropped || this.#aborted) {
149
+ return;
150
+ }
151
+ this.#logger.info('ProcessQueue.fetchMessageImmediately called, mq=%s@%s@%d',
125
152
  this.#mq.topic.name, this.#mq.broker.name, this.#mq.queueId);
126
153
  this.#receiveMessageImmediately();
127
154
  }
@@ -134,9 +161,13 @@ export class ProcessQueue {
134
161
  }
135
162
 
136
163
  #receiveMessageLater(delay: number, attemptId?: string): void {
137
- if (this.#aborted) return;
164
+ if (this.#dropped || this.#aborted) {
165
+ return;
166
+ }
138
167
  setTimeout(() => {
139
- if (this.#aborted) return;
168
+ if (this.#dropped || this.#aborted) {
169
+ return;
170
+ }
140
171
  this.#receiveMessage(attemptId);
141
172
  }, delay);
142
173
  }
@@ -161,7 +192,9 @@ export class ProcessQueue {
161
192
  }
162
193
 
163
194
  #receiveMessageImmediately(attemptId?: string): void {
164
- if (this.#aborted) return;
195
+ if (this.#dropped || this.#aborted) {
196
+ return;
197
+ }
165
198
  // Apply backpressure: when every consumption permit is in use (i.e. the
166
199
  // maximum number of messages is in-flight), stop fetching until messages are
167
200
  // settled and permits are released. Mirrors Java's tryAcquirePermit gate.
@@ -178,30 +211,34 @@ export class ProcessQueue {
178
211
  );
179
212
  this.#activityTime = Date.now();
180
213
 
181
- (this.#consumer as any).logger?.debug?.('Start to receive message, mq=%s@%s@%d, batchSize=%d, attemptId=%s',
214
+ this.#logger.debug?.('Start to receive message, mq=%s@%s@%d, batchSize=%d, attemptId=%s',
182
215
  this.#mq.topic.name, this.#mq.broker.name, this.#mq.queueId, batchSize, attemptId);
183
216
 
184
- this.#consumer.receiveMessage(request, this.#mq, longPollingTimeout)
185
- .then(messages => {
186
- if (messages.length > 0) {
187
- (this.#consumer as any).logger?.debug?.('Received messages, count=%d, mq=%s@%s@%d',
188
- messages.length, this.#mq.topic.name, this.#mq.broker.name, this.#mq.queueId);
189
- }
190
- this.#onReceiveMessageResult(messages);
191
- })
217
+ const receiving = this.#consumer.receiveMessage(request, this.#mq, longPollingTimeout);
218
+ this.#inflightReceives++;
219
+ receiving.then(messages => {
220
+ if (messages.length > 0) {
221
+ this.#logger.debug?.('Received messages, count=%d, mq=%s@%s@%d',
222
+ messages.length, this.#mq.topic.name, this.#mq.broker.name, this.#mq.queueId);
223
+ }
224
+ this.#onReceiveMessageResult(messages);
225
+ })
192
226
  .catch(err => {
193
- (this.#consumer as any).logger?.error('Failed to receive message, mq=%s@%s@%d, error=%s',
227
+ this.#logger.error('Failed to receive message, mq=%s@%s@%d, error=%s',
194
228
  this.#mq.topic.name, this.#mq.broker.name, this.#mq.queueId, err);
195
229
  this.onReceiveMessageException(err, attemptId);
196
- });
230
+ })
231
+ .finally(() => { this.#inflightReceives--; });
197
232
  } catch (err) {
198
- (this.#consumer as any).logger?.error('Exception in receiveMessage, mq=%s@%s@%d, error=%s',
233
+ this.#logger.error('Exception in receiveMessage, mq=%s@%s@%d, error=%s',
199
234
  this.#mq.topic.name, this.#mq.broker.name, this.#mq.queueId, err);
200
235
  this.onReceiveMessageException(err as Error, attemptId);
201
236
  }
202
237
  }
203
238
 
204
239
  #onReceiveMessageResult(messages: MessageView[]): void {
240
+ // Continue processing fetched messages after drop; after abort, leave them for server redelivery.
241
+ if (this.#aborted) return;
205
242
  if (messages.length > 0) {
206
243
  this.cacheMessages(messages);
207
244
  this.#consumer.getConsumeService().consume(this, messages);
@@ -240,36 +277,51 @@ export class ProcessQueue {
240
277
  });
241
278
  }
242
279
 
243
- async #ackMessage(messageView: MessageView, attempt = 1): Promise<void> {
244
- try {
245
- const endpoints = messageView.endpoints;
246
- const response = await this.#consumer.ackMessageViaRpc(
247
- endpoints,
248
- this.#consumer.wrapAckMessageRequest(messageView),
249
- this.#consumer.requestTimeoutValue,
250
- messageView,
251
- );
252
- const status = response.getStatus()?.toObject();
253
- if (status?.code === Code.INVALID_RECEIPT_HANDLE) {
254
- return; // Forgive to retry
255
- }
256
- if (status?.code !== Code.OK) {
257
- await this.#ackMessageLater(messageView, attempt + 1);
280
+ // Log settlement failures and retry at fixed intervals; do not send initial or retry RPCs after abort.
281
+ // forgiveInvalidReceiptHandle stops retrying on INVALID_RECEIPT_HANDLE (ack and
282
+ // change invisible duration only; Java has no such branch for DLQ forwarding).
283
+ async #settleWithRetry(messageView: MessageView, operation: string,
284
+ rpc: () => Promise<{ getStatus(): { toObject(): Status.AsObject } | undefined }>,
285
+ backoffDelay: number, forgiveInvalidReceiptHandle: boolean): Promise<void> {
286
+ let attempt = 1;
287
+ while (!this.#aborted) {
288
+ try {
289
+ const response = await rpc();
290
+ const status = response.getStatus()?.toObject();
291
+ if (status?.code === Code.OK) {
292
+ return;
293
+ }
294
+ const requestId = getRequestId(response);
295
+ if (forgiveInvalidReceiptHandle && status?.code === Code.INVALID_RECEIPT_HANDLE) {
296
+ this.#logger.error(
297
+ 'Failed to %s due to the invalid receipt handle, forgive to retry, attempt=%d, messageId=%s, '
298
+ + 'requestId=%s, status message=[%s]',
299
+ operation, attempt, messageView.messageId, requestId, status.message,
300
+ );
301
+ return;
302
+ }
303
+ this.#logger.error(
304
+ 'Failed to %s, would retry later, attempt=%d, messageId=%s, code=%s, requestId=%s, status message=[%s]',
305
+ operation, attempt, messageView.messageId, status?.code, requestId, status?.message,
306
+ );
307
+ } catch (err) {
308
+ this.#logger.warn(
309
+ 'Failed to %s, attempt=%d, messageId=%s, error=%s',
310
+ operation, attempt, messageView.messageId, err,
311
+ );
258
312
  }
259
- } catch (err) {
260
- (this.#consumer as any).logger?.warn(
261
- 'Failed to ack message, attempt=%d, messageId=%s, error=%s',
262
- attempt, messageView.messageId, err,
263
- );
264
- await this.#ackMessageLater(messageView, attempt + 1);
313
+ attempt++;
314
+ if (this.#aborted) return;
315
+ await new Promise<void>(resolve => setTimeout(resolve, backoffDelay));
316
+ if (this.#aborted) return;
265
317
  }
266
318
  }
267
319
 
268
- async #ackMessageLater(messageView: MessageView, attempt: number): Promise<void> {
269
- if (this.#aborted) return;
270
- await new Promise<void>(resolve => setTimeout(resolve, ACK_MESSAGE_FAILURE_BACKOFF_DELAY));
271
- if (this.#aborted) return;
272
- await this.#ackMessage(messageView, attempt);
320
+ async #ackMessage(messageView: MessageView): Promise<void> {
321
+ await this.#settleWithRetry(messageView, 'ack message',
322
+ () => this.#consumer.ackMessageViaRpc(messageView.endpoints,
323
+ this.#consumer.wrapAckMessageRequest(messageView), this.#consumer.requestTimeoutValue, messageView),
324
+ ACK_MESSAGE_FAILURE_BACKOFF_DELAY, true);
273
325
  }
274
326
 
275
327
  async #nackMessage(messageView: MessageView): Promise<void> {
@@ -278,55 +330,36 @@ export class ProcessQueue {
278
330
  await this.#changeInvisibleDuration(messageView, delay);
279
331
  }
280
332
 
281
- async #changeInvisibleDuration(messageView: MessageView, duration: number, attempt = 1): Promise<void> {
282
- try {
283
- const endpoints = messageView.endpoints;
284
- const response = await this.#consumer.changeInvisibleDurationViaRpc(
285
- endpoints,
333
+ async #changeInvisibleDuration(messageView: MessageView, duration: number): Promise<void> {
334
+ await this.#settleWithRetry(messageView, 'change invisible duration',
335
+ () => this.#consumer.changeInvisibleDurationViaRpc(messageView.endpoints,
286
336
  this.#consumer.wrapChangeInvisibleDurationRequest(messageView, duration),
287
- this.#consumer.requestTimeoutValue,
288
- messageView,
289
- );
290
- const status = response.getStatus()?.toObject();
291
- if (status?.code === Code.INVALID_RECEIPT_HANDLE) {
292
- return; // Forgive to retry
293
- }
294
- if (status?.code !== Code.OK) {
295
- await this.#changeInvisibleDurationLater(messageView, duration, attempt + 1);
296
- }
297
- } catch (err) {
298
- (this.#consumer as any).logger?.warn(
299
- 'Failed to change invisible duration, attempt=%d, duration=%dms, messageId=%s, error=%s',
300
- attempt, duration, messageView.messageId, err,
301
- );
302
- await this.#changeInvisibleDurationLater(messageView, duration, attempt + 1);
303
- }
304
- }
305
-
306
- async #changeInvisibleDurationLater(messageView: MessageView, duration: number, attempt: number): Promise<void> {
307
- if (this.#aborted) return;
308
- await new Promise<void>(resolve => setTimeout(resolve, CHANGE_INVISIBLE_DURATION_FAILURE_BACKOFF_DELAY));
309
- if (this.#aborted) return;
310
- await this.#changeInvisibleDuration(messageView, duration, attempt);
337
+ this.#consumer.requestTimeoutValue, messageView),
338
+ CHANGE_INVISIBLE_DURATION_FAILURE_BACKOFF_DELAY, true);
311
339
  }
312
340
 
313
341
  async eraseFifoMessage(messageView: MessageView, consumeResult: ConsumeResult): Promise<void> {
314
342
  if (!messageView) {
315
343
  return;
316
344
  }
345
+ if (this.#aborted) {
346
+ // Once aborted, skip local retries and settlement RPCs, but still release the cache permit.
347
+ this.#evictCache(messageView);
348
+ return;
349
+ }
317
350
  consumeResult = this.#convertSuspendResultIfNeeded(consumeResult);
318
351
  this.#statsConsumptionResult(consumeResult);
319
352
  const retryPolicy = this.#consumer.getRetryPolicy();
320
353
  const maxAttempts = retryPolicy?.getMaxAttempts() ?? 1;
321
354
  const attempt = messageView.deliveryAttempt ?? 1;
322
355
  const messageId = messageView.messageId;
323
- const clientId = (this.#consumer as any).clientId;
356
+ const clientId = this.#clientId;
324
357
 
325
358
  if (consumeResult === ConsumeResult.FAILURE && attempt < maxAttempts) {
326
359
  const nextAttemptDelay = retryPolicy?.getNextAttemptDelay(attempt) ?? 0;
327
360
  // Increment delivery attempt before redelivering
328
361
  messageView.incrementAndGetDeliveryAttempt();
329
- (this.#consumer as any).logger?.debug(
362
+ this.#logger.debug?.(
330
363
  'Prepare to redeliver the fifo message because of the consumption failure, maxAttempts=%d, '
331
364
  + 'attempt=%d, mq=%s, messageId=%s, nextAttemptDelay=%d, clientId=%s',
332
365
  maxAttempts, messageView.deliveryAttempt, this.#mq, messageId, nextAttemptDelay, clientId,
@@ -341,14 +374,14 @@ export class ProcessQueue {
341
374
  await this.#ackMessage(messageView);
342
375
  } else if (consumeResult instanceof ConsumeResultSuspend) {
343
376
  const suspendTimeMs = consumeResult.suspendTimeMs;
344
- (this.#consumer as any).logger?.info(
377
+ this.#logger.info(
345
378
  'Suspend consumption, consumerGroup=%s, topic=%s, liteTopic=%s, messageId=%s, result=%s',
346
379
  this.#consumer.getConsumerGroup(), messageView.topic, messageView.liteTopic ?? '',
347
380
  messageId, consumeResult,
348
381
  );
349
382
  await this.#changeInvisibleDuration(messageView, suspendTimeMs);
350
383
  } else {
351
- (this.#consumer as any).logger?.info(
384
+ this.#logger.info(
352
385
  'Failed to consume fifo message finally, run out of attempt times, maxAttempts=%d, attempt=%d, '
353
386
  + 'mq=%s, messageId=%s, clientId=%s',
354
387
  maxAttempts, attempt, this.#mq, messageId, clientId,
@@ -358,36 +391,13 @@ export class ProcessQueue {
358
391
  this.#evictCache(messageView);
359
392
  }
360
393
 
361
- async #forwardToDeadLetterQueue(messageView: MessageView, attempt = 1): Promise<void> {
362
- try {
363
- const endpoints = messageView.endpoints;
364
- const response = await this.#consumer.forwardMessageToDeadLetterQueueViaRpc(
365
- endpoints,
394
+ async #forwardToDeadLetterQueue(messageView: MessageView): Promise<void> {
395
+ // A missing status is not OK either and is retried, mirroring Java ProcessQueueImpl.
396
+ await this.#settleWithRetry(messageView, 'forward message to dead letter queue',
397
+ () => this.#consumer.forwardMessageToDeadLetterQueueViaRpc(messageView.endpoints,
366
398
  this.#consumer.wrapForwardMessageToDeadLetterQueueRequest(messageView),
367
- this.#consumer.requestTimeoutValue,
368
- messageView,
369
- );
370
- const status = response.getStatus();
371
- if (!status) {
372
- throw new Error('Missing status in forward to dead letter queue response');
373
- }
374
- const statusObj = status.toObject();
375
- if (statusObj.code !== Code.OK) {
376
- await this.#forwardToDeadLetterQueueLater(messageView, attempt + 1);
377
- }
378
- } catch (err) {
379
- if ((err as Error).message === 'Missing status in forward to dead letter queue response') {
380
- throw err; // Re-throw critical error
381
- }
382
- await this.#forwardToDeadLetterQueueLater(messageView, attempt + 1);
383
- }
384
- }
385
-
386
- async #forwardToDeadLetterQueueLater(messageView: MessageView, attempt: number): Promise<void> {
387
- if (this.#aborted) return;
388
- await new Promise<void>(resolve => setTimeout(resolve, FORWARD_MESSAGE_TO_DLQ_FAILURE_BACKOFF_DELAY));
389
- if (this.#aborted) return;
390
- await this.#forwardToDeadLetterQueue(messageView, attempt);
399
+ this.#consumer.requestTimeoutValue, messageView),
400
+ FORWARD_MESSAGE_TO_DLQ_FAILURE_BACKOFF_DELAY, false);
391
401
  }
392
402
 
393
403
  discardMessage(messageView: MessageView): void {
@@ -415,8 +425,8 @@ export class ProcessQueue {
415
425
 
416
426
  #convertSuspendResultIfNeeded(consumeResult: ConsumeResult): ConsumeResult {
417
427
  if (consumeResult instanceof ConsumeResultSuspend) {
418
- if (!(this.#consumer as any).isLiteConsumer?.()) {
419
- (this.#consumer as any).logger?.warn(
428
+ if (!this.#liteConsumer) {
429
+ this.#logger.warn(
420
430
  'Only LitePushConsumer support ConsumeResultSuspend! Convert to ConsumeResult.FAILURE, '
421
431
  + 'consumerGroup=%s, consumerType=%s',
422
432
  this.#consumer.getConsumerGroup(), this.#consumer.constructor.name,
@@ -443,6 +453,11 @@ export class ProcessQueue {
443
453
  return this.#cachedMessagesBytes;
444
454
  }
445
455
 
456
+ // Release a removed queue only after receive callbacks finish and all cached messages are settled.
457
+ isDrained(): boolean {
458
+ return this.#inflightReceives === 0 && this.#cachedMessages.length === 0;
459
+ }
460
+
446
461
  abort(): void {
447
462
  this.#aborted = true;
448
463
  }
@@ -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';
@@ -78,13 +79,25 @@ export class PushConsumer extends Consumer {
78
79
  readonly #maxCacheMessageSizeInBytes: number;
79
80
  readonly #enableFifoConsumeAccelerator: boolean;
80
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>();
81
84
  readonly #metrics = new ConsumeMetrics();
82
85
  readonly #inflightRequestCountInterceptor: InflightRequestCountInterceptor;
83
86
  #consumeService!: ConsumeService;
84
87
  #scanAssignmentTimer?: NodeJS.Timeout;
85
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;
86
93
 
87
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
+ }
88
101
  options.topics = Array.from(options.subscriptions.keys());
89
102
  super(options);
90
103
 
@@ -136,6 +149,16 @@ export class PushConsumer extends Consumer {
136
149
  clearInterval(this.#scanAssignmentTimer);
137
150
  this.#scanAssignmentTimer = undefined;
138
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
+ }
139
162
  throw err;
140
163
  }
141
164
  }
@@ -151,6 +174,7 @@ export class PushConsumer extends Consumer {
151
174
 
152
175
  async shutdown() {
153
176
  this.logger.info('Begin to shutdown the rocketmq push consumer, clientId=%s', this.clientId);
177
+ this.#shuttingDown = true;
154
178
  // Stop scanning assignments
155
179
  if (this.#scanAssignmentTimer) {
156
180
  clearInterval(this.#scanAssignmentTimer);
@@ -172,10 +196,11 @@ export class PushConsumer extends Consumer {
172
196
  // Reserve a short buffer for the ack/changeInvisibleDuration callbacks to be sent
173
197
  await this.sleep(1000);
174
198
  // Abort process queues and consume service, no more messages will be received or consumed
175
- for (const { pq } of this.#processQueueTable.values()) {
199
+ for (const pq of this.#settlingProcessQueues()) {
176
200
  pq.abort();
177
201
  }
178
202
  this.#processQueueTable.clear();
203
+ this.#droppedProcessQueues.clear();
179
204
  if (this.#consumeService) {
180
205
  this.logger.info('Shutting down consume service, clientId=%s', this.clientId);
181
206
  this.#consumeService.abort();
@@ -194,10 +219,10 @@ export class PushConsumer extends Consumer {
194
219
  const maxWaitingTime = this.requestTimeoutValue
195
220
  + this.getPushConsumerSettings().getLongPollingTimeout();
196
221
  const endTime = Date.now() + maxWaitingTime;
197
- while ([ ...this.#processQueueTable.values() ].some(({ pq }) => pq.cachedMessagesCount() > 0)) {
222
+ while (this.#settlingProcessQueues().some(pq => pq.cachedMessagesCount() > 0)) {
198
223
  if (Date.now() > endTime) {
199
- const remaining = [ ...this.#processQueueTable.values() ]
200
- .reduce((count, { pq }) => count + pq.cachedMessagesCount(), 0);
224
+ const remaining = this.#settlingProcessQueues()
225
+ .reduce((count, pq) => count + pq.cachedMessagesCount(), 0);
201
226
  this.logger.warn('Timeout waiting for the cached messages to be consumed, clientId=%s, '
202
227
  + 'remainingCachedMessages=%d', this.clientId, remaining);
203
228
  return;
@@ -237,12 +262,12 @@ export class PushConsumer extends Consumer {
237
262
  protected wrapHeartbeatRequest() {
238
263
  return new HeartbeatRequest()
239
264
  .setClientType(this.getClientType())
240
- .setGroup(createResource(this.consumerGroup));
265
+ .setGroup(createResource(this.consumerGroup, this.namespace));
241
266
  }
242
267
 
243
268
  protected wrapNotifyClientTerminationRequest() {
244
269
  return new NotifyClientTerminationRequest()
245
- .setGroup(createResource(this.consumerGroup));
270
+ .setGroup(createResource(this.consumerGroup, this.namespace));
246
271
  }
247
272
 
248
273
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -263,9 +288,9 @@ export class PushConsumer extends Consumer {
263
288
  // composited interceptor chain), mirroring Java PushConsumerImpl.
264
289
  if (this.#pushSubscriptionSettings.isFifo()) {
265
290
  return new FifoConsumeService(this.clientId, this.#messageListener, this.#enableFifoConsumeAccelerator,
266
- this, this.consumerGroup);
291
+ this, this.consumerGroup, this.logger);
267
292
  }
268
- return new StandardConsumeService(this.clientId, this.#messageListener, this, this.consumerGroup);
293
+ return new StandardConsumeService(this.clientId, this.#messageListener, this, this.consumerGroup, this.logger);
269
294
  }
270
295
 
271
296
  async subscribe(topic: string, filterExpression: FilterExpression) {
@@ -363,7 +388,7 @@ export class PushConsumer extends Consumer {
363
388
  attemptId?: string,
364
389
  ) {
365
390
  const request = new ReceiveMessageRequest()
366
- .setGroup(createResource(this.consumerGroup))
391
+ .setGroup(createResource(this.consumerGroup, this.namespace))
367
392
  .setMessageQueue(mq.toProtobuf())
368
393
  .setFilterExpression(filterExpression.toProtobuf())
369
394
  .setLongPollingTimeout(createDuration(longPollingTimeout))
@@ -386,8 +411,8 @@ export class PushConsumer extends Consumer {
386
411
 
387
412
  wrapAckMessageRequest(messageView: MessageView) {
388
413
  const request = new AckMessageRequest()
389
- .setGroup(createResource(this.consumerGroup))
390
- .setTopic(createResource(messageView.topic));
414
+ .setGroup(createResource(this.consumerGroup, this.namespace))
415
+ .setTopic(createResource(messageView.topic, this.namespace));
391
416
  const entry = request.addEntries()
392
417
  .setMessageId(messageView.messageId)
393
418
  .setReceiptHandle(messageView.receiptHandle);
@@ -402,8 +427,8 @@ export class PushConsumer extends Consumer {
402
427
 
403
428
  wrapChangeInvisibleDurationRequest(messageView: MessageView, invisibleDuration: number) {
404
429
  const request = new ChangeInvisibleDurationRequest()
405
- .setGroup(createResource(this.consumerGroup))
406
- .setTopic(createResource(messageView.topic))
430
+ .setGroup(createResource(this.consumerGroup, this.namespace))
431
+ .setTopic(createResource(messageView.topic, this.namespace))
407
432
  .setReceiptHandle(messageView.receiptHandle)
408
433
  .setInvisibleDuration(createDuration(invisibleDuration))
409
434
  .setMessageId(messageView.messageId);
@@ -420,8 +445,8 @@ export class PushConsumer extends Consumer {
420
445
  wrapForwardMessageToDeadLetterQueueRequest(messageView: MessageView) {
421
446
  const retryPolicy = this.getRetryPolicy();
422
447
  const request = new ForwardMessageToDeadLetterQueueRequest()
423
- .setGroup(createResource(this.consumerGroup))
424
- .setTopic(createResource(messageView.topic))
448
+ .setGroup(createResource(this.consumerGroup, this.namespace))
449
+ .setTopic(createResource(messageView.topic, this.namespace))
425
450
  .setReceiptHandle(messageView.receiptHandle)
426
451
  .setMessageId(messageView.messageId)
427
452
  .setDeliveryAttempt(messageView.deliveryAttempt ?? 0)
@@ -465,6 +490,7 @@ export class PushConsumer extends Consumer {
465
490
 
466
491
  #scanAssignments() {
467
492
  try {
493
+ this.#pruneDroppedProcessQueues();
468
494
  this.logger.debug?.('Scanning assignments, clientId=%s, subscriptionCount=%d',
469
495
  this.clientId, this.#subscriptionExpressions.size);
470
496
  for (const [ topic, filterExpression ] of this.#subscriptionExpressions) {
@@ -508,15 +534,11 @@ export class PushConsumer extends Consumer {
508
534
 
509
535
  async #queryAssignment(topic: string): Promise<Assignments> {
510
536
  const topicRouteData = await this.getRouteData(topic);
511
- const endpointsList = topicRouteData.getTotalEndpoints();
512
- if (endpointsList.length === 0) {
513
- throw new Error(`No endpoints available for topic=${topic}`);
514
- }
515
- const endpoints = endpointsList[0];
537
+ const endpoints = topicRouteData.pickEndpointsToQueryAssignments();
516
538
 
517
539
  const request = new QueryAssignmentRequest()
518
- .setTopic(createResource(topic))
519
- .setGroup(createResource(this.consumerGroup))
540
+ .setTopic(createResource(topic, this.namespace))
541
+ .setGroup(createResource(this.consumerGroup, this.namespace))
520
542
  .setEndpoints(this.endpoints.toProtobuf());
521
543
 
522
544
  const response = await this.rpcClientManager.queryAssignment(
@@ -526,7 +548,7 @@ export class PushConsumer extends Consumer {
526
548
  if (!status) {
527
549
  throw new Error('Missing status in query assignment response');
528
550
  }
529
- StatusChecker.check(status.toObject());
551
+ StatusChecker.check(status.toObject(), getRequestId(response));
530
552
 
531
553
  const assignmentList = response.getAssignmentsList().map(assignment => {
532
554
  const mqPb = assignment.getMessageQueue()!;
@@ -538,6 +560,15 @@ export class PushConsumer extends Consumer {
538
560
  }
539
561
 
540
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
+ }
541
572
  const latestMqKeys = new Set<string>();
542
573
  for (const assignment of assignments.getAssignmentList()) {
543
574
  latestMqKeys.add(this.#mqKey(assignment.messageQueue));
@@ -589,19 +620,40 @@ export class PushConsumer extends Consumer {
589
620
  if (entry) {
590
621
  entry.pq.drop();
591
622
  this.#processQueueTable.delete(mqKey);
623
+ this.#pruneDroppedProcessQueues();
624
+ this.#droppedProcessQueues.add(entry.pq);
592
625
  }
593
626
  }
594
627
 
628
+ #pruneDroppedProcessQueues() {
629
+ for (const pq of this.#droppedProcessQueues) {
630
+ if (pq.isDrained()) {
631
+ pq.abort();
632
+ this.#droppedProcessQueues.delete(pq);
633
+ }
634
+ }
635
+ }
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
+
595
643
  #createProcessQueue(mq: MessageQueue, filterExpression: FilterExpression): ProcessQueue | null {
596
644
  const mqKey = this.#mqKey(mq);
597
645
  if (this.#processQueueTable.has(mqKey)) {
598
646
  return null;
599
647
  }
600
- const processQueue = new ProcessQueue(this, mq, filterExpression);
648
+ const processQueue = new ProcessQueue(this, mq, filterExpression, this.#processQueueContext());
601
649
  this.#processQueueTable.set(mqKey, { mq, pq: processQueue });
602
650
  return processQueue;
603
651
  }
604
652
 
653
+ #processQueueContext() {
654
+ return { logger: this.logger, clientId: this.clientId, liteConsumer: this.isLiteConsumer() };
655
+ }
656
+
605
657
  /**
606
658
  * Create a virtual process queue for Lite consumer.
607
659
  * Lite consumers use a special message queue with queueId=-1 to receive messages.
@@ -612,6 +664,11 @@ export class PushConsumer extends Consumer {
612
664
  */
613
665
  protected createVirtualProcessQueueForLite(topic: string, filterExpression: FilterExpression) {
614
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
+ }
615
672
  if (!topic || topic.trim().length === 0) {
616
673
  throw new Error('topic should not be blank');
617
674
  }
@@ -629,7 +686,7 @@ export class PushConsumer extends Consumer {
629
686
  // Create a virtual message queue with queueId=-1
630
687
  const virtualMqPb = new MessageQueuePB();
631
688
  virtualMqPb.setId(-1); // Virtual queue ID for Lite consumer
632
- virtualMqPb.setTopic(createResource(topic));
689
+ virtualMqPb.setTopic(createResource(topic, this.namespace));
633
690
  virtualMqPb.setBroker(broker.toProtobuf());
634
691
  virtualMqPb.setPermission(Permission.READ);
635
692
  virtualMqPb.setAcceptMessageTypesList([ MessageType.LITE ]);
@@ -643,7 +700,7 @@ export class PushConsumer extends Consumer {
643
700
  return;
644
701
  }
645
702
 
646
- const processQueue = new ProcessQueue(this, virtualMq, filterExpression);
703
+ const processQueue = new ProcessQueue(this, virtualMq, filterExpression, this.#processQueueContext());
647
704
  this.#processQueueTable.set(mqKey, { mq: virtualMq, pq: processQueue });
648
705
 
649
706
  this.logger.info('Created virtual process queue for Lite consumer, mq=%s, clientId=%s',
@@ -86,11 +86,11 @@ export class PushSubscriptionSettings extends Settings {
86
86
 
87
87
  toProtobuf(): SettingsPB {
88
88
  const subscription = new Subscription()
89
- .setGroup(createResource(this.#group));
89
+ .setGroup(createResource(this.#group, this.namespace));
90
90
 
91
91
  for (const [ topic, filterExpression ] of this.#subscriptionExpressions.entries()) {
92
92
  subscription.addSubscriptions()
93
- .setTopic(createResource(topic))
93
+ .setTopic(createResource(topic, this.namespace))
94
94
  .setExpression(filterExpression.toProtobuf());
95
95
  }
96
96