rocketmq-client-nodejs 1.0.8 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/README.md +61 -0
  2. package/dist/client/BaseClient.d.ts +44 -1
  3. package/dist/client/BaseClient.js +353 -85
  4. package/dist/client/Logger.js +9 -6
  5. package/dist/client/RpcClient.js +42 -134
  6. package/dist/client/RpcClientManager.d.ts +22 -17
  7. package/dist/client/RpcClientManager.js +61 -56
  8. package/dist/client/TelemetrySession.js +107 -17
  9. package/dist/consumer/ConsumeService.d.ts +2 -1
  10. package/dist/consumer/ConsumeService.js +12 -6
  11. package/dist/consumer/ConsumeTask.d.ts +6 -1
  12. package/dist/consumer/ConsumeTask.js +36 -5
  13. package/dist/consumer/Consumer.d.ts +13 -5
  14. package/dist/consumer/Consumer.js +94 -33
  15. package/dist/consumer/FifoConsumeService.d.ts +3 -1
  16. package/dist/consumer/FifoConsumeService.js +4 -4
  17. package/dist/consumer/LiteConsumerSupport.d.ts +25 -0
  18. package/dist/consumer/LiteConsumerSupport.js +47 -0
  19. package/dist/consumer/LiteFifoConsumeService.d.ts +3 -1
  20. package/dist/consumer/LiteFifoConsumeService.js +4 -4
  21. package/dist/consumer/LitePushConsumerImpl.d.ts +15 -4
  22. package/dist/consumer/LitePushConsumerImpl.js +26 -30
  23. package/dist/consumer/LiteSimpleConsumer.d.ts +177 -0
  24. package/dist/consumer/LiteSimpleConsumer.js +126 -0
  25. package/dist/consumer/LiteSimpleConsumerImpl.d.ts +133 -0
  26. package/dist/consumer/LiteSimpleConsumerImpl.js +179 -0
  27. package/dist/consumer/LiteStandardConsumeService.d.ts +3 -1
  28. package/dist/consumer/LiteStandardConsumeService.js +4 -4
  29. package/dist/consumer/LiteSubscriptionManager.d.ts +27 -6
  30. package/dist/consumer/LiteSubscriptionManager.js +36 -27
  31. package/dist/consumer/OffsetOption.d.ts +1 -0
  32. package/dist/consumer/OffsetOption.js +10 -4
  33. package/dist/consumer/ProcessQueue.d.ts +17 -1
  34. package/dist/consumer/ProcessQueue.js +134 -91
  35. package/dist/consumer/PushConsumer.d.ts +17 -0
  36. package/dist/consumer/PushConsumer.js +117 -26
  37. package/dist/consumer/PushConsumerGaugeObserver.d.ts +33 -0
  38. package/dist/consumer/PushConsumerGaugeObserver.js +60 -0
  39. package/dist/consumer/PushSubscriptionSettings.d.ts +8 -1
  40. package/dist/consumer/PushSubscriptionSettings.js +35 -8
  41. package/dist/consumer/SimpleConsumer.d.ts +5 -0
  42. package/dist/consumer/SimpleConsumer.js +33 -20
  43. package/dist/consumer/SimpleSubscriptionSettings.js +3 -3
  44. package/dist/consumer/StandardConsumeService.d.ts +3 -1
  45. package/dist/consumer/StandardConsumeService.js +17 -8
  46. package/dist/consumer/SubscriptionLoadBalancer.js +3 -3
  47. package/dist/consumer/index.d.ts +1 -0
  48. package/dist/consumer/index.js +2 -1
  49. package/dist/exception/InternalErrorException.d.ts +1 -0
  50. package/dist/exception/InternalErrorException.js +3 -2
  51. package/dist/exception/PayloadEmptyException.d.ts +20 -0
  52. package/dist/exception/PayloadEmptyException.js +28 -0
  53. package/dist/exception/StatusChecker.js +11 -4
  54. package/dist/exception/index.d.ts +1 -0
  55. package/dist/exception/index.js +2 -1
  56. package/dist/exception/receiveStatus.d.ts +18 -0
  57. package/dist/exception/receiveStatus.js +28 -0
  58. package/dist/hook/Attribute.d.ts +26 -0
  59. package/dist/hook/Attribute.js +37 -0
  60. package/dist/hook/AttributeKey.d.ts +32 -0
  61. package/dist/hook/AttributeKey.js +43 -0
  62. package/dist/hook/CompositedMessageInterceptor.d.ts +32 -0
  63. package/dist/hook/CompositedMessageInterceptor.js +87 -0
  64. package/dist/hook/InflightRequestCountInterceptor.d.ts +28 -0
  65. package/dist/hook/InflightRequestCountInterceptor.js +44 -0
  66. package/dist/hook/MessageHookPoints.d.ts +54 -0
  67. package/dist/hook/MessageHookPoints.js +59 -0
  68. package/dist/hook/MessageHookPointsStatus.d.ts +24 -0
  69. package/dist/hook/MessageHookPointsStatus.js +29 -0
  70. package/dist/hook/MessageInterceptor.d.ts +34 -0
  71. package/dist/hook/MessageInterceptor.js +19 -0
  72. package/dist/hook/MessageInterceptorContext.d.ts +31 -0
  73. package/dist/hook/MessageInterceptorContext.js +19 -0
  74. package/dist/hook/MessageInterceptorContextImpl.d.ts +40 -0
  75. package/dist/hook/MessageInterceptorContextImpl.js +71 -0
  76. package/dist/hook/MessageMeterInterceptor.d.ts +39 -0
  77. package/dist/hook/MessageMeterInterceptor.js +149 -0
  78. package/dist/hook/index.d.ts +26 -0
  79. package/dist/hook/index.js +43 -0
  80. package/dist/index.d.ts +1 -0
  81. package/dist/index.js +2 -1
  82. package/dist/message/Message.js +26 -4
  83. package/dist/message/MessageView.js +15 -5
  84. package/dist/message/PublishingMessage.js +4 -4
  85. package/dist/metrics/ClientMeter.d.ts +42 -0
  86. package/dist/metrics/ClientMeter.js +75 -0
  87. package/dist/metrics/ClientMeterManager.d.ts +46 -0
  88. package/dist/metrics/ClientMeterManager.js +203 -0
  89. package/dist/metrics/EmptyGaugeObserver.d.ts +28 -0
  90. package/dist/metrics/EmptyGaugeObserver.js +34 -0
  91. package/dist/metrics/GaugeEnum.d.ts +32 -0
  92. package/dist/metrics/GaugeEnum.js +37 -0
  93. package/dist/metrics/GaugeObserver.d.ts +29 -0
  94. package/dist/metrics/GaugeObserver.js +19 -0
  95. package/dist/metrics/HistogramEnum.d.ts +54 -0
  96. package/dist/metrics/HistogramEnum.js +71 -0
  97. package/dist/metrics/InvocationStatus.d.ts +26 -0
  98. package/dist/metrics/InvocationStatus.js +33 -0
  99. package/dist/metrics/Metric.d.ts +30 -0
  100. package/dist/metrics/Metric.js +44 -0
  101. package/dist/metrics/MetricLabels.d.ts +27 -0
  102. package/dist/metrics/MetricLabels.js +34 -0
  103. package/dist/metrics/index.d.ts +25 -0
  104. package/dist/metrics/index.js +42 -0
  105. package/dist/producer/Producer.d.ts +8 -2
  106. package/dist/producer/Producer.js +83 -34
  107. package/dist/producer/PublishingLoadBalancer.js +11 -5
  108. package/dist/producer/PublishingSettings.js +1 -3
  109. package/dist/producer/SendReceipt.js +3 -2
  110. package/dist/producer/Transaction.d.ts +2 -1
  111. package/dist/producer/Transaction.js +9 -8
  112. package/dist/producer/index.d.ts +1 -0
  113. package/dist/producer/index.js +2 -2
  114. package/dist/retry/CustomizedBackoffRetryPolicy.d.ts +37 -0
  115. package/dist/retry/CustomizedBackoffRetryPolicy.js +72 -0
  116. package/dist/retry/ExponentialBackoffRetryPolicy.js +10 -6
  117. package/dist/retry/RetryPolicy.d.ts +1 -1
  118. package/dist/retry/index.d.ts +1 -0
  119. package/dist/retry/index.js +2 -1
  120. package/dist/route/Endpoints.d.ts +6 -0
  121. package/dist/route/Endpoints.js +69 -9
  122. package/dist/route/IpNameResolver.d.ts +28 -0
  123. package/dist/route/IpNameResolver.js +104 -0
  124. package/dist/route/MessageQueue.js +7 -2
  125. package/dist/route/TopicRouteData.d.ts +5 -0
  126. package/dist/route/TopicRouteData.js +22 -1
  127. package/dist/util/Semaphore.d.ts +47 -0
  128. package/dist/util/Semaphore.js +82 -0
  129. package/dist/util/index.d.ts +1 -1
  130. package/dist/util/index.js +9 -6
  131. package/dist/util/rpcContext.d.ts +20 -0
  132. package/dist/util/rpcContext.js +35 -0
  133. package/package.json +11 -4
  134. package/src/client/BaseClient.ts +392 -91
  135. package/src/client/Logger.ts +9 -5
  136. package/src/client/RpcClient.ts +62 -133
  137. package/src/client/RpcClientManager.ts +103 -60
  138. package/src/client/TelemetrySession.ts +112 -17
  139. package/src/consumer/ConsumeService.ts +16 -5
  140. package/src/consumer/ConsumeTask.ts +43 -3
  141. package/src/consumer/Consumer.ts +116 -35
  142. package/src/consumer/FifoConsumeService.ts +5 -3
  143. package/src/consumer/LiteConsumerSupport.ts +49 -0
  144. package/src/consumer/LiteFifoConsumeService.ts +5 -3
  145. package/src/consumer/LitePushConsumerImpl.ts +34 -23
  146. package/src/consumer/LiteSimpleConsumer.ts +251 -0
  147. package/src/consumer/LiteSimpleConsumerImpl.ts +214 -0
  148. package/src/consumer/LiteStandardConsumeService.ts +5 -3
  149. package/src/consumer/LiteSubscriptionManager.ts +66 -41
  150. package/src/consumer/OffsetOption.ts +10 -3
  151. package/src/consumer/ProcessQueue.ts +165 -107
  152. package/src/consumer/PushConsumer.ts +133 -24
  153. package/src/consumer/PushConsumerGaugeObserver.ts +60 -0
  154. package/src/consumer/PushSubscriptionSettings.ts +40 -9
  155. package/src/consumer/SimpleConsumer.ts +39 -23
  156. package/src/consumer/SimpleSubscriptionSettings.ts +2 -2
  157. package/src/consumer/StandardConsumeService.ts +18 -7
  158. package/src/consumer/SubscriptionLoadBalancer.ts +2 -2
  159. package/src/consumer/index.ts +1 -0
  160. package/src/exception/InternalErrorException.ts +3 -1
  161. package/src/exception/PayloadEmptyException.ts +25 -0
  162. package/src/exception/StatusChecker.ts +10 -2
  163. package/src/exception/index.ts +1 -0
  164. package/src/exception/receiveStatus.ts +25 -0
  165. package/src/hook/Attribute.ts +36 -0
  166. package/src/hook/AttributeKey.ts +42 -0
  167. package/src/hook/CompositedMessageInterceptor.ts +96 -0
  168. package/src/hook/InflightRequestCountInterceptor.ts +46 -0
  169. package/src/hook/MessageHookPoints.ts +55 -0
  170. package/src/hook/MessageHookPointsStatus.ts +25 -0
  171. package/src/hook/MessageInterceptor.ts +35 -0
  172. package/src/hook/MessageInterceptorContext.ts +33 -0
  173. package/src/hook/MessageInterceptorContextImpl.ts +83 -0
  174. package/src/hook/MessageMeterInterceptor.ts +162 -0
  175. package/src/hook/index.ts +27 -0
  176. package/src/index.ts +1 -0
  177. package/src/message/Message.ts +25 -3
  178. package/src/message/MessageView.ts +13 -4
  179. package/src/message/PublishingMessage.ts +3 -3
  180. package/src/metrics/ClientMeter.ts +81 -0
  181. package/src/metrics/ClientMeterManager.ts +227 -0
  182. package/src/metrics/EmptyGaugeObserver.ts +36 -0
  183. package/src/metrics/GaugeEnum.ts +33 -0
  184. package/src/metrics/GaugeObserver.ts +32 -0
  185. package/src/metrics/HistogramEnum.ts +69 -0
  186. package/src/metrics/InvocationStatus.ts +28 -0
  187. package/src/metrics/Metric.ts +42 -0
  188. package/src/metrics/MetricLabels.ts +31 -0
  189. package/src/metrics/index.ts +26 -0
  190. package/src/producer/Producer.ts +94 -38
  191. package/src/producer/PublishingLoadBalancer.ts +10 -4
  192. package/src/producer/PublishingSettings.ts +0 -2
  193. package/src/producer/SendReceipt.ts +2 -1
  194. package/src/producer/Transaction.ts +12 -11
  195. package/src/producer/index.ts +1 -1
  196. package/src/retry/CustomizedBackoffRetryPolicy.ts +81 -0
  197. package/src/retry/ExponentialBackoffRetryPolicy.ts +11 -6
  198. package/src/retry/RetryPolicy.ts +1 -1
  199. package/src/retry/index.ts +1 -0
  200. package/src/route/Endpoints.ts +65 -8
  201. package/src/route/IpNameResolver.ts +119 -0
  202. package/src/route/MessageQueue.ts +6 -1
  203. package/src/route/TopicRouteData.ts +22 -1
  204. package/src/util/Semaphore.ts +82 -0
  205. package/src/util/index.ts +8 -5
  206. package/src/util/rpcContext.ts +34 -0
@@ -0,0 +1,162 @@
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 { Attribute, AttributeKey, MessageHookPoints, MessageHookPointsStatus, MessageInterceptor, MessageInterceptorContext } from './';
20
+ import { GeneralMessage } from './MessageInterceptor';
21
+ import { MetricLabels } from '../metrics/MetricLabels';
22
+ import { InvocationStatus } from '../metrics/InvocationStatus';
23
+ import { HistogramEnum } from '../metrics/HistogramEnum';
24
+ import { ClientMeterManager } from '../metrics/ClientMeterManager';
25
+
26
+ /**
27
+ * Minimal message shape required to compute metric attributes / latencies.
28
+ * Covers both the producer's PublishingMessage (cast to GeneralMessage) and the
29
+ * consumer's MessageView (which implements GeneralMessage).
30
+ */
31
+ type MetricMessage = {
32
+ topic: string;
33
+ transportDeliveryTimestamp?: Date;
34
+ decodeTimestamp?: Date;
35
+ };
36
+
37
+ /**
38
+ * Records the four RocketMQ histograms around the SEND / RECEIVE / CONSUME hook
39
+ * points, mirroring org.apache.rocketmq.client.java.metrics.MessageMeterInterceptor.
40
+ *
41
+ * Unlike Java (which wires an AuthInterceptor + IpNameResolverFactory onto the
42
+ * export channel), the Node client signs each export request via a per-call
43
+ * metadata provider (see {@link ClientMeterManager}), so no auth plumbing is
44
+ * needed here.
45
+ */
46
+ export class MessageMeterInterceptor implements MessageInterceptor {
47
+ static readonly SEND_STOPWATCH_KEY = AttributeKey.create<number>('send_stopwatch');
48
+ static readonly CONSUME_STOPWATCH_KEY = AttributeKey.create<number>('consume_stopwatch');
49
+
50
+ constructor(
51
+ private readonly meterManager: ClientMeterManager,
52
+ private readonly clientId: string,
53
+ private readonly getConsumerGroup: () => string | undefined,
54
+ ) {
55
+ }
56
+
57
+ doBefore(context: MessageInterceptorContext, messages: GeneralMessage[]): void {
58
+ if (!this.meterManager.isEnabled()) {
59
+ return;
60
+ }
61
+ switch (context.getMessageHookPoints()) {
62
+ case MessageHookPoints.SEND:
63
+ context.putAttribute(MessageMeterInterceptor.SEND_STOPWATCH_KEY, Attribute.create(Date.now()));
64
+ break;
65
+ case MessageHookPoints.CONSUME: {
66
+ const consumerGroup = this.getConsumerGroup();
67
+ if (!consumerGroup) {
68
+ break;
69
+ }
70
+ const message = messages[0] as MetricMessage | undefined;
71
+ if (!message || !message.decodeTimestamp) {
72
+ break;
73
+ }
74
+ const latency = Date.now() - message.decodeTimestamp.getTime();
75
+ const attributes = this.#consumerAttributes(message.topic, consumerGroup);
76
+ this.meterManager.record(HistogramEnum.AWAIT_TIME, attributes, latency);
77
+ context.putAttribute(MessageMeterInterceptor.CONSUME_STOPWATCH_KEY, Attribute.create(Date.now()));
78
+ break;
79
+ }
80
+ default:
81
+ break;
82
+ }
83
+ }
84
+
85
+ doAfter(context: MessageInterceptorContext, messages: GeneralMessage[]): void {
86
+ if (!this.meterManager.isEnabled()) {
87
+ return;
88
+ }
89
+ const status = context.getStatus();
90
+ const invocationStatus = status === MessageHookPointsStatus.OK ? InvocationStatus.SUCCESS : InvocationStatus.FAILURE;
91
+ switch (context.getMessageHookPoints()) {
92
+ case MessageHookPoints.SEND: {
93
+ const attr = context.getAttribute(MessageMeterInterceptor.SEND_STOPWATCH_KEY);
94
+ if (!attr) {
95
+ break;
96
+ }
97
+ const message = messages[0] as MetricMessage | undefined;
98
+ if (!message) {
99
+ break;
100
+ }
101
+ const cost = Date.now() - attr.get();
102
+ const attributes: Attributes = {
103
+ [MetricLabels.TOPIC]: message.topic,
104
+ [MetricLabels.CLIENT_ID]: this.clientId,
105
+ [MetricLabels.INVOCATION_STATUS]: invocationStatus.name,
106
+ };
107
+ this.meterManager.record(HistogramEnum.SEND_COST_TIME, attributes, cost);
108
+ break;
109
+ }
110
+ case MessageHookPoints.RECEIVE: {
111
+ const consumerGroup = this.getConsumerGroup();
112
+ if (!consumerGroup) {
113
+ break;
114
+ }
115
+ const message = messages[0] as MetricMessage | undefined;
116
+ if (!message || !message.transportDeliveryTimestamp) {
117
+ break;
118
+ }
119
+ const latency = Date.now() - message.transportDeliveryTimestamp.getTime();
120
+ if (latency < 0) {
121
+ break;
122
+ }
123
+ const attributes = this.#consumerAttributes(message.topic, consumerGroup);
124
+ this.meterManager.record(HistogramEnum.DELIVERY_LATENCY, attributes, latency);
125
+ break;
126
+ }
127
+ case MessageHookPoints.CONSUME: {
128
+ const consumerGroup = this.getConsumerGroup();
129
+ if (!consumerGroup) {
130
+ break;
131
+ }
132
+ const attr = context.getAttribute(MessageMeterInterceptor.CONSUME_STOPWATCH_KEY);
133
+ if (!attr) {
134
+ break;
135
+ }
136
+ const message = messages[0] as MetricMessage | undefined;
137
+ if (!message) {
138
+ break;
139
+ }
140
+ const cost = Date.now() - attr.get();
141
+ const attributes: Attributes = {
142
+ [MetricLabels.TOPIC]: message.topic,
143
+ [MetricLabels.CLIENT_ID]: this.clientId,
144
+ [MetricLabels.CONSUMER_GROUP]: consumerGroup,
145
+ [MetricLabels.INVOCATION_STATUS]: invocationStatus.name,
146
+ };
147
+ this.meterManager.record(HistogramEnum.PROCESS_TIME, attributes, cost);
148
+ break;
149
+ }
150
+ default:
151
+ break;
152
+ }
153
+ }
154
+
155
+ #consumerAttributes(topic: string, consumerGroup: string): Attributes {
156
+ return {
157
+ [MetricLabels.TOPIC]: topic,
158
+ [MetricLabels.CLIENT_ID]: this.clientId,
159
+ [MetricLabels.CONSUMER_GROUP]: consumerGroup,
160
+ };
161
+ }
162
+ }
@@ -0,0 +1,27 @@
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
+ export * from './Attribute';
19
+ export * from './AttributeKey';
20
+ export * from './CompositedMessageInterceptor';
21
+ export * from './InflightRequestCountInterceptor';
22
+ export * from './MessageHookPoints';
23
+ export * from './MessageHookPointsStatus';
24
+ export * from './MessageInterceptor';
25
+ export * from './MessageInterceptorContext';
26
+ export * from './MessageInterceptorContextImpl';
27
+ export * from './MessageMeterInterceptor';
package/src/index.ts CHANGED
@@ -17,6 +17,7 @@
17
17
 
18
18
  export * from './consumer';
19
19
  export * from './exception';
20
+ export * from './hook';
20
21
  export * from './message';
21
22
  export * from './producer';
22
23
  export * from './retry';
@@ -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
  }
@@ -0,0 +1,81 @@
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, Histogram, Meter } from '@opentelemetry/api';
19
+ import { MeterProvider as SdkMeterProvider } from '@opentelemetry/sdk-metrics';
20
+ import { Endpoints } from '../route';
21
+ import { HistogramEnum } from './HistogramEnum';
22
+ import { Metric } from './Metric';
23
+
24
+ /**
25
+ * Wraps an OpenTelemetry {@link Meter} and records the four RocketMQ histograms.
26
+ * When metrics are disabled it is a no-op instance, mirroring
27
+ * org.apache.rocketmq.client.java.metrics.ClientMeter.
28
+ */
29
+ export class ClientMeter {
30
+ readonly enabled: boolean;
31
+ private readonly meter?: Meter;
32
+ private readonly endpoints?: Endpoints;
33
+ private readonly provider?: SdkMeterProvider;
34
+ private readonly histogramMap = new Map<HistogramEnum, Histogram>();
35
+
36
+ constructor(meter: Meter | null, endpoints: Endpoints | null, provider: SdkMeterProvider | null) {
37
+ this.enabled = meter != null && endpoints != null && provider != null;
38
+ this.meter = meter ?? undefined;
39
+ this.endpoints = endpoints ?? undefined;
40
+ this.provider = provider ?? undefined;
41
+ }
42
+
43
+ static disabledInstance(): ClientMeter {
44
+ return new ClientMeter(null, null, null);
45
+ }
46
+
47
+ record(histogramEnum: HistogramEnum, attributes: Attributes, value: number) {
48
+ if (!this.enabled || !this.meter) {
49
+ return;
50
+ }
51
+ let histogram = this.histogramMap.get(histogramEnum);
52
+ if (!histogram) {
53
+ histogram = this.meter.createHistogram(histogramEnum);
54
+ this.histogramMap.set(histogramEnum, histogram);
55
+ }
56
+ histogram.record(value, attributes);
57
+ }
58
+
59
+ async shutdown() {
60
+ if (!this.enabled || !this.provider) {
61
+ return;
62
+ }
63
+ try {
64
+ await this.provider.shutdown();
65
+ } catch (t) {
66
+ // best-effort shutdown, ignore
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Returns true if the supplied metric switch is already satisfied by this
72
+ * meter (so a rebuild is unnecessary), mirroring ClientMeter#satisfy.
73
+ */
74
+ satisfy(metric: Metric): boolean {
75
+ if (this.enabled && metric.on && this.endpoints != null && metric.endpoints != null
76
+ && this.endpoints.equals(metric.endpoints)) {
77
+ return true;
78
+ }
79
+ return !this.enabled && !metric.on;
80
+ }
81
+ }
@@ -0,0 +1,227 @@
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, Meter } from '@opentelemetry/api';
19
+ import {
20
+ MeterProvider as SdkMeterProvider,
21
+ PeriodicExportingMetricReader,
22
+ ResourceMetrics,
23
+ View,
24
+ } from '@opentelemetry/sdk-metrics';
25
+ import { Resource } from '@opentelemetry/resources';
26
+ import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-grpc';
27
+ import { ChannelCredentials, Metadata } from '@grpc/grpc-js';
28
+ import { isIPv6 } from 'node:net';
29
+ import { ILogger } from '../client/Logger';
30
+ import { ClientMeter } from './ClientMeter';
31
+ import { GaugeObserver } from './GaugeObserver';
32
+ import { EmptyGaugeObserver } from './EmptyGaugeObserver';
33
+ import { HistogramEnum, buildHistogramView } from './HistogramEnum';
34
+ import { Metric } from './Metric';
35
+
36
+ const METRIC_EXPORTER_RPC_TIMEOUT = 5000;
37
+ const METRIC_READER_INTERVAL = 60000;
38
+ const METRIC_INSTRUMENTATION_NAME = 'org.apache.rocketmq.message';
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
+
107
+ /**
108
+ * Owns the OpenTelemetry metric pipeline for a single client. On every settings
109
+ * command it lazily (re)builds an SdkMeterProvider that exports the four
110
+ * RocketMQ histograms plus the consumer gauges to the broker-supplied metric
111
+ * endpoints over OTLP/gRPC, mirroring
112
+ * org.apache.rocketmq.client.java.metrics.ClientMeterManager.
113
+ */
114
+ export class ClientMeterManager {
115
+ private readonly clientId: string;
116
+ private readonly metadataProvider: () => Metadata;
117
+ private readonly logger: ILogger;
118
+ private clientMeter: ClientMeter;
119
+ private gaugeObserver: GaugeObserver = EmptyGaugeObserver.EMPTY;
120
+ private pending: Promise<void> = Promise.resolve();
121
+ private shutdownPromise?: Promise<void>;
122
+
123
+ constructor(clientId: string, metadataProvider: () => Metadata, logger: ILogger) {
124
+ this.clientId = clientId;
125
+ this.metadataProvider = metadataProvider;
126
+ this.logger = logger;
127
+ this.clientMeter = ClientMeter.disabledInstance();
128
+ }
129
+
130
+ setGaugeObserver(gaugeObserver: GaugeObserver) {
131
+ this.gaugeObserver = gaugeObserver;
132
+ }
133
+
134
+ record(histogramEnum: HistogramEnum, attributes: Attributes, value: number) {
135
+ this.clientMeter.record(histogramEnum, attributes, value);
136
+ }
137
+
138
+ isEnabled(): boolean {
139
+ return this.clientMeter.enabled;
140
+ }
141
+
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;
149
+ }
150
+
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> {
166
+ try {
167
+ if (this.clientMeter.satisfy(metric)) {
168
+ this.logger.info('Metric settings is satisfied by the current message meter, metric=%j, clientId=%s',
169
+ metric, this.clientId);
170
+ return;
171
+ }
172
+ if (!metric.on || !metric.endpoints) {
173
+ this.logger.info('Metric is off, clientId=%s', this.clientId);
174
+ await this.clientMeter.shutdown();
175
+ this.clientMeter = ClientMeter.disabledInstance();
176
+ return;
177
+ }
178
+ const endpoints = metric.endpoints;
179
+ const urls = endpoints.addressesList.map(address => {
180
+ const host = isIPv6(address.host) ? `[${address.host}]` : address.host;
181
+ return `http://${host}:${address.port}`;
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);
187
+
188
+ const reader = new PeriodicExportingMetricReader({
189
+ exporter,
190
+ exportIntervalMillis: METRIC_READER_INTERVAL,
191
+ exportTimeoutMillis: METRIC_EXPORTER_RPC_TIMEOUT,
192
+ });
193
+
194
+ const views: View[] = [
195
+ new View(buildHistogramView(HistogramEnum.SEND_COST_TIME)),
196
+ new View(buildHistogramView(HistogramEnum.DELIVERY_LATENCY)),
197
+ new View(buildHistogramView(HistogramEnum.AWAIT_TIME)),
198
+ new View(buildHistogramView(HistogramEnum.PROCESS_TIME)),
199
+ ];
200
+
201
+ const provider: SdkMeterProvider = new SdkMeterProvider({
202
+ resource: Resource.empty(),
203
+ readers: [ reader ],
204
+ views,
205
+ });
206
+
207
+ const meter: Meter = provider.getMeter(METRIC_INSTRUMENTATION_NAME);
208
+
209
+ const existedClientMeter = this.clientMeter;
210
+ this.clientMeter = new ClientMeter(meter, endpoints, provider);
211
+ await existedClientMeter.shutdown();
212
+ this.logger.info('Metrics is on, endpoints=%s, clientId=%s', endpoints, this.clientId);
213
+
214
+ const gauges = this.gaugeObserver.getGauges();
215
+ for (const gauge of gauges) {
216
+ meter.createObservableGauge(gauge).addCallback(observableResult => {
217
+ const values = this.gaugeObserver.getValues(gauge);
218
+ for (const [ attributes, value ] of values) {
219
+ observableResult.observe(value, attributes);
220
+ }
221
+ });
222
+ }
223
+ } catch (t) {
224
+ this.logger.error('Exception raised when resetting message meter, clientId=%s, error=%s', this.clientId, t);
225
+ }
226
+ }
227
+ }
@@ -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
+ import { Attributes } from '@opentelemetry/api';
19
+ import { GaugeEnum } from './GaugeEnum';
20
+ import { GaugeObserver } from './GaugeObserver';
21
+
22
+ /**
23
+ * Default no-op gauge observer used before a consumer registers a real one,
24
+ * mirroring org.apache.rocketmq.client.java.metrics.EmptyGaugeObserver.
25
+ */
26
+ export class EmptyGaugeObserver implements GaugeObserver {
27
+ static readonly EMPTY: EmptyGaugeObserver = new EmptyGaugeObserver();
28
+
29
+ getGauges(): GaugeEnum[] {
30
+ return [];
31
+ }
32
+
33
+ getValues(): Map<Attributes, number> {
34
+ return new Map();
35
+ }
36
+ }