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
@@ -46,6 +46,11 @@ export interface SimpleConsumerOptions extends ConsumerOptions {
46
46
  awaitDuration?: number;
47
47
  /**
48
48
  * max retry attempts for temporary errors (e.g., internal server error), default is 3
49
+ * Includes the initial request and must be a positive safe integer; 1 disables retries.
50
+ * Unlike Java's single receive attempt, Node retains its existing retry configuration.
51
+ * Once routing is ready, the maximum RPC wait and backoff budget is
52
+ * maxRetryAttempts * (requestTimeout + awaitDuration) + (maxRetryAttempts - 1) * 1000ms,
53
+ * excluding route queries, message decoding, hooks, and event-loop scheduling.
49
54
  */
50
55
  maxRetryAttempts?: number;
51
56
  }
@@ -59,6 +64,16 @@ export class SimpleConsumer extends Consumer {
59
64
  #topicIndex = RANDOM_INDEX;
60
65
 
61
66
  constructor(options: SimpleConsumerOptions) {
67
+ if (options.awaitDuration !== undefined && (!Number.isFinite(options.awaitDuration) || options.awaitDuration <= 0)) {
68
+ throw new TypeError('awaitDuration should be positive');
69
+ }
70
+ if (!(options.subscriptions instanceof Map) || options.subscriptions.size === 0) {
71
+ throw new TypeError('subscriptions must be a non-empty Map');
72
+ }
73
+ if (options.maxRetryAttempts !== undefined &&
74
+ (!Number.isSafeInteger(options.maxRetryAttempts) || options.maxRetryAttempts <= 0)) {
75
+ throw new TypeError('maxRetryAttempts must be a positive safe integer');
76
+ }
62
77
  options.topics = Array.from(options.subscriptions.keys());
63
78
  super(options);
64
79
  for (const [ topic, filter ] of options.subscriptions.entries()) {
@@ -92,12 +107,12 @@ export class SimpleConsumer extends Consumer {
92
107
  protected wrapHeartbeatRequest() {
93
108
  return new HeartbeatRequest()
94
109
  .setClientType(this.getClientType())
95
- .setGroup(createResource(this.consumerGroup));
110
+ .setGroup(createResource(this.consumerGroup, this.namespace));
96
111
  }
97
112
 
98
113
  protected wrapNotifyClientTerminationRequest() {
99
114
  return new NotifyClientTerminationRequest()
100
- .setGroup(createResource(this.consumerGroup));
115
+ .setGroup(createResource(this.consumerGroup, this.namespace));
101
116
  }
102
117
 
103
118
  protected onTopicRouteDataUpdate(topic: string, topicRouteData: TopicRouteData) {
@@ -152,31 +167,18 @@ export class SimpleConsumer extends Consumer {
152
167
  const request = this.wrapReceiveMessageRequest(maxMessageNum, mq, filterExpression,
153
168
  invisibleDuration, this.#awaitDuration);
154
169
 
155
- // Retry logic for temporary errors
156
- let lastError: Error | undefined;
157
- for (let attempt = 1; attempt <= this.#maxRetryAttempts; attempt++) {
170
+ for (let attempt = 1; ; attempt++) {
158
171
  try {
159
172
  return await this.receiveMessage(request, mq, this.#awaitDuration);
160
173
  } catch (err) {
161
- lastError = err as Error;
162
-
163
- // Only retry on internal server errors (temporary errors)
164
- if (err instanceof InternalErrorException) {
165
- if (attempt < this.#maxRetryAttempts) {
166
- this.logger.warn('Received temporary error from server, will retry after %dms, attempt=%d/%d, topic=%s, clientId=%s, error=%s',
167
- RETRY_DELAY_MS, attempt, this.#maxRetryAttempts, topic, this.clientId, err.message);
168
- await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));
169
- continue;
170
- }
174
+ if (!(err instanceof InternalErrorException) || attempt >= this.#maxRetryAttempts) {
175
+ throw err;
171
176
  }
172
-
173
- // For non-retryable errors or max attempts reached, throw immediately
174
- throw err;
177
+ this.logger.warn('Received temporary error from server, will retry after %dms, attempt=%d/%d, topic=%s, clientId=%s, error=%s',
178
+ RETRY_DELAY_MS, attempt, this.#maxRetryAttempts, topic, this.clientId, err.message);
179
+ await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));
175
180
  }
176
181
  }
177
-
178
- // This should never be reached, but just in case
179
- throw lastError;
180
182
  }
181
183
 
182
184
  async ack(message: MessageView) {
@@ -191,8 +193,13 @@ export class SimpleConsumer extends Consumer {
191
193
  throw new Error('Simple consumer is not running, cannot change invisible duration');
192
194
  }
193
195
  const response = await this.invisibleDuration(message, invisibleDuration);
194
- // Refresh receipt handle manually
195
- (message as any).receiptHandle = response;
196
+ this.#refreshReceiptHandle(message, response);
197
+ }
198
+
199
+ #refreshReceiptHandle(message: MessageView, receiptHandle: string) {
200
+ // Update the caller-readonly receiptHandle after successful renewal without changing MessageView's public signature.
201
+ const mutableMessage = message as { receiptHandle: string };
202
+ mutableMessage.receiptHandle = receiptHandle;
196
203
  }
197
204
 
198
205
  #nextTopic() {
@@ -39,12 +39,12 @@ export class SimpleSubscriptionSettings extends Settings {
39
39
 
40
40
  toProtobuf(): SettingsPB {
41
41
  const subscription = new Subscription()
42
- .setGroup(createResource(this.group))
42
+ .setGroup(createResource(this.group, this.namespace))
43
43
  .setLongPollingTimeout(createDuration(this.longPollingTimeout));
44
44
 
45
45
  for (const [ topic, filterExpression ] of this.subscriptionExpressions.entries()) {
46
46
  subscription.addSubscriptions()
47
- .setTopic(createResource(topic))
47
+ .setTopic(createResource(topic, this.namespace))
48
48
  .setExpression(filterExpression.toProtobuf());
49
49
  }
50
50
  return new SettingsPB()
@@ -18,17 +18,18 @@
18
18
  import { MessageView } from '../message';
19
19
  import { MessageInterceptor } from '../hook';
20
20
  import { ConsumeService } from './ConsumeService';
21
+ import { ConsumeResult } from './ConsumeResult';
21
22
  import { MessageListener } from './MessageListener';
22
23
  import type { ProcessQueue } from './ProcessQueue';
23
- import { getDefaultLogger } from '../client';
24
+ import { ILogger, getDefaultLogger } from '../client/Logger';
24
25
 
25
26
  export class StandardConsumeService extends ConsumeService {
26
- private readonly logger = getDefaultLogger();
27
+ private readonly logger: ILogger;
27
28
 
28
- // eslint-disable-next-line @typescript-eslint/no-useless-constructor
29
29
  constructor(clientId: string, messageListener: MessageListener,
30
- messageInterceptor?: MessageInterceptor, consumerGroup?: string) {
30
+ messageInterceptor?: MessageInterceptor, consumerGroup?: string, logger?: ILogger) {
31
31
  super(clientId, messageListener, messageInterceptor, consumerGroup);
32
+ this.logger = logger ?? getDefaultLogger();
32
33
  }
33
34
 
34
35
  consume(pq: ProcessQueue, messageViews: MessageView[]): void {
@@ -50,9 +51,17 @@ export class StandardConsumeService extends ConsumeService {
50
51
  pq.eraseMessage(messageView, result);
51
52
  })
52
53
  .catch(err => {
53
- this.logger.error('Message consumption failed, messageId=%s, error=%s',
54
+ // consumeMessage never rejects, so this is a settlement that threw synchronously.
55
+ // Nack the message so it still leaves the cache and releases its permit; otherwise
56
+ // it would hold the permit until shutdown times out waiting for it.
57
+ this.logger.error('Failed to settle the consumed message, nack it instead, messageId=%s, error=%s',
54
58
  messageView.messageId, err);
55
- // Should never reach here.
59
+ try {
60
+ pq.eraseMessage(messageView, ConsumeResult.FAILURE);
61
+ } catch (e) {
62
+ this.logger.error('Failed to nack the message after the settlement failure, messageId=%s, error=%s',
63
+ messageView.messageId, e);
64
+ }
56
65
  });
57
66
  }
58
67
  }
@@ -26,12 +26,12 @@ export class SubscriptionLoadBalancer {
26
26
 
27
27
  constructor(topicRouteData: TopicRouteData, index?: number) {
28
28
  this.#messageQueues = topicRouteData.messageQueues.filter(mq => {
29
- return mq.queueId === MASTER_BROKER_ID && (mq.permission === Permission.READ || mq.permission === Permission.READ_WRITE);
29
+ return mq.broker.id === MASTER_BROKER_ID && (mq.permission === Permission.READ || mq.permission === Permission.READ_WRITE);
30
30
  });
31
- this.#index = index === undefined ? randomInt(this.#messageQueues.length) : index;
32
31
  if (this.#messageQueues.length === 0) {
33
32
  throw new Error(`No readable message queue found, topicRouteData=${JSON.stringify(topicRouteData)}`);
34
33
  }
34
+ this.#index = index === undefined ? randomInt(this.#messageQueues.length) : index;
35
35
  }
36
36
 
37
37
  update(topicRouteData: TopicRouteData) {
@@ -18,11 +18,13 @@
18
18
  import { ClientException } from './ClientException';
19
19
 
20
20
  export class InternalErrorException extends ClientException {
21
+ readonly retryable = true;
22
+
21
23
  constructor(code: number, message: string, requestId?: string) {
22
24
  super(code, message, requestId);
23
25
  this.name = 'InternalErrorException';
24
26
  // Mark this as a potentially retryable error (temporary server-side issue)
25
- (this as any).retryable = true;
27
+ // The class field explicitly declares retryable.
26
28
  }
27
29
 
28
30
  /**
@@ -33,7 +33,9 @@ import { UnsupportedException } from './UnsupportedException';
33
33
 
34
34
  export class StatusChecker {
35
35
  static check(status?: Status.AsObject, requestId?: string) {
36
- if (!status) return;
36
+ if (!status) {
37
+ throw new InternalErrorException(Code.INTERNAL_SERVER_ERROR, 'status was not set by server', requestId);
38
+ }
37
39
  switch (status.code) {
38
40
  case Code.OK:
39
41
  case Code.MULTIPLE_RESULTS:
@@ -66,7 +68,6 @@ export class StatusChecker {
66
68
  case Code.FORBIDDEN:
67
69
  throw new ForbiddenException(status.code, status.message, requestId);
68
70
  case Code.MESSAGE_NOT_FOUND:
69
- return;
70
71
  case Code.NOT_FOUND:
71
72
  case Code.TOPIC_NOT_FOUND:
72
73
  case Code.CONSUMER_GROUP_NOT_FOUND:
@@ -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 { Code, Status } from '../../proto/apache/rocketmq/v2/definition_pb';
19
+ import { StatusChecker } from './StatusChecker';
20
+
21
+ // Allow empty results only for receive operations without changing the public StatusChecker.check signature.
22
+ export function checkReceiveStatus(status?: Status.AsObject, requestId?: string) {
23
+ if (status?.code === Code.MESSAGE_NOT_FOUND) return;
24
+ StatusChecker.check(status, requestId);
25
+ }
@@ -15,6 +15,7 @@
15
15
  * limitations under the License.
16
16
  */
17
17
 
18
+ import type { ILogger } from '../client/Logger';
18
19
  import { Attribute } from './Attribute';
19
20
  import { AttributeKey } from './AttributeKey';
20
21
  import { MessageHookPointsStatus } from './MessageHookPointsStatus';
@@ -33,9 +34,11 @@ const INTERCEPTOR_ATTRIBUTES_KEY = AttributeKey
33
34
  */
34
35
  export class CompositedMessageInterceptor implements MessageInterceptor {
35
36
  readonly #interceptors: MessageInterceptor[] = [];
37
+ readonly #logger?: ILogger;
36
38
 
37
- constructor(interceptors: MessageInterceptor[] = []) {
39
+ constructor(interceptors: MessageInterceptor[] = [], logger?: ILogger) {
38
40
  this.#interceptors.push(...interceptors);
41
+ this.#logger = logger;
39
42
  }
40
43
 
41
44
  addInterceptor(interceptor: MessageInterceptor) {
@@ -58,9 +61,10 @@ export class CompositedMessageInterceptor implements MessageInterceptor {
58
61
  try {
59
62
  this.#interceptors[index].doBefore(context, messages);
60
63
  } catch (t) {
61
- // Interceptors must never break the message pipeline.
64
+ // Interceptors must never break the message pipeline. Standalone instances without
65
+ // a client logger fall back to the console.
62
66
  // eslint-disable-next-line no-console
63
- console.error(
67
+ (this.#logger ?? console).error(
64
68
  '[CompositedMessageInterceptor] Exception raised while handling messages before hook point=%s, error=%s',
65
69
  context0.getMessageHookPoints(), t);
66
70
  }
@@ -83,7 +87,7 @@ export class CompositedMessageInterceptor implements MessageInterceptor {
83
87
  this.#interceptors[index].doAfter(context, messages);
84
88
  } catch (t) {
85
89
  // eslint-disable-next-line no-console
86
- console.error(
90
+ (this.#logger ?? console).error(
87
91
  '[CompositedMessageInterceptor] Exception raised while handling messages after hook point=%s, error=%s',
88
92
  context0.getMessageHookPoints(), t);
89
93
  }
@@ -35,7 +35,10 @@ export class MessageInterceptorContextImpl implements MessageInterceptorContext
35
35
  attributes?: Map<AttributeKey<any>, Attribute<any>>) {
36
36
  this.#messageHookPoints = messageHookPoints;
37
37
  this.#status = status;
38
- this.#attributes = new Map(attributes ?? []);
38
+ this.#attributes = new Map();
39
+ for (const [ key, value ] of attributes ?? []) {
40
+ this.putAttribute(key, value);
41
+ }
39
42
  }
40
43
 
41
44
  /**
@@ -55,11 +58,23 @@ export class MessageInterceptorContextImpl implements MessageInterceptorContext
55
58
  }
56
59
 
57
60
  putAttribute<T>(key: AttributeKey<T>, value: Attribute<T>) {
58
- this.#attributes.set(key, value);
61
+ // Java compares AttributeKeys by name; preserve the public Map<AttributeKey, Attribute> representation.
62
+ const existing = this.findKey(key);
63
+ this.#attributes.set(existing ?? key, value);
59
64
  }
60
65
 
61
66
  getAttribute<T>(key: AttributeKey<T>): Attribute<T> | undefined {
62
- return this.#attributes.get(key) as Attribute<T> | undefined;
67
+ const existing = this.findKey(key);
68
+ return existing ? this.#attributes.get(existing) as Attribute<T> | undefined : undefined;
69
+ }
70
+
71
+ private findKey<T>(key: AttributeKey<T>): AttributeKey<T> | undefined {
72
+ for (const candidate of this.#attributes.keys()) {
73
+ if (candidate.name === key.name) {
74
+ return candidate;
75
+ }
76
+ }
77
+ return undefined;
63
78
  }
64
79
 
65
80
  getAttributes(): Map<AttributeKey<any>, Attribute<any>> {
@@ -40,18 +40,40 @@ export class Message {
40
40
  liteTopic?: string;
41
41
 
42
42
  constructor(options: MessageOptions) {
43
+ if (options.keys !== undefined) {
44
+ if (!Array.isArray(options.keys)) {
45
+ throw new TypeError('keys must be an array');
46
+ }
47
+ for (const key of options.keys) {
48
+ if (typeof key !== 'string' || key.trim().length === 0) {
49
+ throw new TypeError('key should not be blank');
50
+ }
51
+ }
52
+ }
53
+ if (options.properties !== undefined) {
54
+ if (!(options.properties instanceof Map)) {
55
+ throw new TypeError('properties must be a Map');
56
+ }
57
+ for (const [ key, value ] of options.properties) {
58
+ if (typeof key !== 'string' || key.trim().length === 0) {
59
+ throw new TypeError('property key should not be blank');
60
+ }
61
+ if (typeof value !== 'string' || value.trim().length === 0) {
62
+ throw new TypeError('property value should not be blank');
63
+ }
64
+ }
65
+ }
43
66
  let finalDeliveryTimestamp = options.deliveryTimestamp;
44
67
  if (options.delay && !finalDeliveryTimestamp) {
45
68
  finalDeliveryTimestamp = new Date(Date.now() + options.delay);
46
69
  }
47
70
 
48
- const hasPriority = options.priority !== undefined;
49
71
  const hasLiteTopic = options.liteTopic !== undefined;
50
72
  const hasTimedDelivery = finalDeliveryTimestamp !== undefined;
51
73
  const hasGroup = options.messageGroup !== undefined;
52
74
 
53
- if (hasPriority) {
54
- if (options.priority === undefined || options.priority < 0) {
75
+ if (options.priority !== undefined) {
76
+ if (options.priority < 0) {
55
77
  throw new Error('priority must be greater than or equal to 0');
56
78
  }
57
79
  if (hasTimedDelivery || hasGroup || hasLiteTopic) {
@@ -51,6 +51,7 @@ export class MessageView {
51
51
  const digestType = bodyDigest.type;
52
52
  const checksum = bodyDigest.checksum;
53
53
  let expectedChecksum = '';
54
+ let corrupted = false;
54
55
  let bodyBytes = Buffer.from(message.getBody_asU8());
55
56
  switch (digestType) {
56
57
  case DigestType.CRC32:
@@ -63,15 +64,21 @@ export class MessageView {
63
64
  expectedChecksum = sha1CheckSum(bodyBytes);
64
65
  break;
65
66
  default:
66
- // log.error("Unsupported message body digest algorithm, digestType={}, topic={}, messageId={}",
67
- // digestType, topic, messageId);
67
+ break;
68
68
  }
69
69
  if (expectedChecksum && expectedChecksum !== checksum) {
70
- this.corrupted = true;
70
+ corrupted = true;
71
71
  }
72
72
  if (systemProperties.getBodyEncoding() === Encoding.GZIP) {
73
- bodyBytes = gunzipSync(bodyBytes);
73
+ try {
74
+ bodyBytes = gunzipSync(bodyBytes);
75
+ } catch {
76
+ // Keep the raw body and let the consumer discard the message, as Java MessageViewImpl#fromProtobuf does,
77
+ // instead of failing the whole received batch.
78
+ corrupted = true;
79
+ }
74
80
  }
81
+ this.corrupted = corrupted;
75
82
 
76
83
  for (const [ key, value ] of message.getUserPropertiesMap().entries()) {
77
84
  this.properties.set(key, value);
@@ -94,6 +101,8 @@ export class MessageView {
94
101
  this.endpoints = messageQueue.broker.endpoints;
95
102
  }
96
103
  this.body = bodyBytes;
104
+ // Record the local decode completion time for consumption wait and processing latency metrics.
105
+ this.decodeTimestamp = new Date();
97
106
  }
98
107
 
99
108
  /**
@@ -40,7 +40,7 @@ export class PublishingMessage extends Message {
40
40
  // Generate message id.
41
41
  this.messageId = MessageIdFactory.create().toString();
42
42
  // Normal message.
43
- if (!this.messageGroup && !this.liteTopic && !this.deliveryTimestamp && !this.priority && !txEnabled) {
43
+ if (!this.messageGroup && !this.liteTopic && !this.deliveryTimestamp && this.priority === undefined && !txEnabled) {
44
44
  this.messageType = MessageType.NORMAL;
45
45
  return;
46
46
  }
@@ -60,13 +60,13 @@ export class PublishingMessage extends Message {
60
60
  return;
61
61
  }
62
62
  // Priority message.
63
- if (this.priority && !txEnabled) {
63
+ if (this.priority !== undefined && !txEnabled) {
64
64
  this.messageType = MessageType.PRIORITY;
65
65
  return;
66
66
  }
67
67
  // Transaction message.
68
68
  if (!this.messageGroup &&
69
- !this.liteTopic && !this.deliveryTimestamp && !this.priority && txEnabled) {
69
+ !this.liteTopic && !this.deliveryTimestamp && this.priority === undefined && txEnabled) {
70
70
  this.messageType = MessageType.TRANSACTION;
71
71
  return;
72
72
  }
@@ -19,11 +19,13 @@ import { Attributes, Meter } from '@opentelemetry/api';
19
19
  import {
20
20
  MeterProvider as SdkMeterProvider,
21
21
  PeriodicExportingMetricReader,
22
+ ResourceMetrics,
22
23
  View,
23
24
  } from '@opentelemetry/sdk-metrics';
24
25
  import { Resource } from '@opentelemetry/resources';
25
26
  import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-grpc';
26
27
  import { ChannelCredentials, Metadata } from '@grpc/grpc-js';
28
+ import { isIPv6 } from 'node:net';
27
29
  import { ILogger } from '../client/Logger';
28
30
  import { ClientMeter } from './ClientMeter';
29
31
  import { GaugeObserver } from './GaugeObserver';
@@ -35,6 +37,73 @@ const METRIC_EXPORTER_RPC_TIMEOUT = 5000;
35
37
  const METRIC_READER_INTERVAL = 60000;
36
38
  const METRIC_INSTRUMENTATION_NAME = 'org.apache.rocketmq.message';
37
39
 
40
+ type ExportCallback = Parameters<OTLPMetricExporter['export']>[1];
41
+ type ExportResult = Parameters<ExportCallback>[0];
42
+
43
+ // OTel 0.57.2 accepts a Metadata instance and caches it on the first export. Use a fresh exporter
44
+ // per round to refresh signatures and close its channel afterward; inherit aggregation/temporality choices.
45
+ class SignedMetricExporter extends OTLPMetricExporter {
46
+ private readonly pending = new Set<Promise<void>>();
47
+ private closed = false;
48
+
49
+ constructor(private readonly urls: string[], private readonly metadataProvider: () => Metadata) {
50
+ super({ url: urls[0], credentials: ChannelCredentials.createInsecure() });
51
+ }
52
+
53
+ override export(metrics: ResourceMetrics, callback: ExportCallback): void {
54
+ if (this.closed) {
55
+ callback({ code: 1, error: new Error('Metric exporter is shut down') });
56
+ return;
57
+ }
58
+ const completion = this.exportOnce(metrics).then(callback, error => {
59
+ callback({ code: 1, error: error instanceof Error ? error : new Error(String(error)) });
60
+ });
61
+ this.pending.add(completion);
62
+ void completion.then(() => this.pending.delete(completion), () => this.pending.delete(completion));
63
+ }
64
+
65
+ private async exportOnce(metrics: ResourceMetrics): Promise<ExportResult> {
66
+ const deadline = Date.now() + METRIC_EXPORTER_RPC_TIMEOUT;
67
+ const start = Math.floor(Math.random() * this.urls.length);
68
+ let result: ExportResult = { code: 1, error: new Error('No metric endpoint is available') };
69
+ // Randomize the starting address and fail over as Java's multi-address resolver does; all attempts share one timeout.
70
+ for (let index = 0; index < this.urls.length; index++) {
71
+ const remaining = deadline - Date.now();
72
+ if (remaining <= 0) {
73
+ break;
74
+ }
75
+ let exporter: OTLPMetricExporter | undefined;
76
+ try {
77
+ exporter = new OTLPMetricExporter({
78
+ url: this.urls[(start + index) % this.urls.length],
79
+ credentials: ChannelCredentials.createInsecure(),
80
+ timeoutMillis: Math.max(1, Math.floor(remaining / (this.urls.length - index))),
81
+ metadata: this.metadataProvider(),
82
+ });
83
+ result = await new Promise<ExportResult>(resolve => exporter!.export(metrics, resolve));
84
+ } catch (error) {
85
+ result = { code: 1, error: error instanceof Error ? error : new Error(String(error)) };
86
+ } finally {
87
+ await exporter?.shutdown();
88
+ }
89
+ if (result.code === 0) {
90
+ break;
91
+ }
92
+ }
93
+ return result;
94
+ }
95
+
96
+ override async forceFlush(): Promise<void> {
97
+ await Promise.all(this.pending);
98
+ }
99
+
100
+ override async shutdown(): Promise<void> {
101
+ this.closed = true;
102
+ await this.forceFlush();
103
+ await super.shutdown();
104
+ }
105
+ }
106
+
38
107
  /**
39
108
  * Owns the OpenTelemetry metric pipeline for a single client. On every settings
40
109
  * command it lazily (re)builds an SdkMeterProvider that exports the four
@@ -48,6 +117,8 @@ export class ClientMeterManager {
48
117
  private readonly logger: ILogger;
49
118
  private clientMeter: ClientMeter;
50
119
  private gaugeObserver: GaugeObserver = EmptyGaugeObserver.EMPTY;
120
+ private pending: Promise<void> = Promise.resolve();
121
+ private shutdownPromise?: Promise<void>;
51
122
 
52
123
  constructor(clientId: string, metadataProvider: () => Metadata, logger: ILogger) {
53
124
  this.clientId = clientId;
@@ -68,11 +139,30 @@ export class ClientMeterManager {
68
139
  return this.clientMeter.enabled;
69
140
  }
70
141
 
71
- async shutdown() {
72
- await this.clientMeter.shutdown();
142
+ shutdown(): Promise<void> {
143
+ this.shutdownPromise ??= this.enqueue(async () => {
144
+ const meter = this.clientMeter;
145
+ this.clientMeter = ClientMeter.disabledInstance();
146
+ await meter.shutdown();
147
+ });
148
+ return this.shutdownPromise;
73
149
  }
74
150
 
75
- async reset(metric: Metric): Promise<void> {
151
+ reset(metric: Metric): Promise<void> {
152
+ if (this.shutdownPromise) {
153
+ return this.shutdownPromise;
154
+ }
155
+ return this.enqueue(() => this.resetMeter(metric));
156
+ }
157
+
158
+ // Settings handlers do not await reset; serialize disable/enable and shutdown in invocation order.
159
+ private enqueue(operation: () => Promise<void>): Promise<void> {
160
+ const result = this.pending.then(operation);
161
+ this.pending = result.catch(() => undefined);
162
+ return result;
163
+ }
164
+
165
+ private async resetMeter(metric: Metric): Promise<void> {
76
166
  try {
77
167
  if (this.clientMeter.satisfy(metric)) {
78
168
  this.logger.info('Metric settings is satisfied by the current message meter, metric=%j, clientId=%s',
@@ -86,22 +176,14 @@ export class ClientMeterManager {
86
176
  return;
87
177
  }
88
178
  const endpoints = metric.endpoints;
89
- // Use the first address as the OTLP/gRPC target. The exporter's URL is
90
- // normalized to "host:port" internally, which gRPC-js resolves through
91
- // its default DNS resolver (a single IP works fine; the custom `ip`
92
- // resolver is used for the primary RPC channels).
93
- const address = endpoints.addressesList[0];
94
- const url = `http://${address.host}:${address.port}`;
95
- const exporter = new OTLPMetricExporter({
96
- url,
97
- credentials: ChannelCredentials.createInsecure(),
98
- timeoutMillis: METRIC_EXPORTER_RPC_TIMEOUT,
99
- // Per-request signing mirrors the Java client's AuthInterceptor. The
100
- // d.ts types this field as `Metadata`, but the runtime (and the
101
- // exporter's own merge logic in otlp-grpc-exporter-base) expects a
102
- // function returning freshly-signed Metadata.
103
- metadata: (() => this.metadataProvider()) as unknown as Metadata,
179
+ const urls = endpoints.addressesList.map(address => {
180
+ const host = isIPv6(address.host) ? `[${address.host}]` : address.host;
181
+ return `http://${host}:${address.port}`;
104
182
  });
183
+ if (urls.length === 0) {
184
+ throw new Error('Metric endpoints must contain at least one address');
185
+ }
186
+ const exporter = new SignedMetricExporter(urls, this.metadataProvider);
105
187
 
106
188
  const reader = new PeriodicExportingMetricReader({
107
189
  exporter,