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,33 @@
1
+ /**
2
+ * Licensed to the Apache Software Foundation (ASF) under one or more
3
+ * contributor license agreements. See the NOTICE file distributed with
4
+ * this work for additional information regarding copyright ownership.
5
+ * The ASF licenses this file to You under the Apache License, Version 2.0
6
+ * (the "License"); you may not use this file except in compliance with
7
+ * the License. You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ /**
19
+ * The two consumer gauges exported by the RocketMQ client, mirroring
20
+ * org.apache.rocketmq.client.java.metrics.GaugeEnum.
21
+ */
22
+ export enum GaugeEnum {
23
+ /**
24
+ * Cached message count of push consumer.
25
+ * Labels: topic, client_id, consumer_group.
26
+ */
27
+ CONSUMER_CACHED_MESSAGES = 'rocketmq_consumer_cached_messages',
28
+ /**
29
+ * Cached message bytes of push consumer.
30
+ * Labels: topic, client_id, consumer_group.
31
+ */
32
+ CONSUMER_CACHED_BYTES = 'rocketmq_consumer_cached_bytes',
33
+ }
@@ -0,0 +1,32 @@
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
+
21
+ /**
22
+ * Supplies the live values observed by the periodic metric reader for each
23
+ * consumer gauge, mirroring org.apache.rocketmq.client.java.metrics.GaugeObserver.
24
+ *
25
+ * The map key is the attribute set (topic / client_id / consumer_group) and the
26
+ * value is the observed gauge reading.
27
+ */
28
+ export interface GaugeObserver {
29
+ getGauges(): GaugeEnum[];
30
+
31
+ getValues(gauge: GaugeEnum): Map<Attributes, number>;
32
+ }
@@ -0,0 +1,69 @@
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 { ExplicitBucketHistogramAggregation, InstrumentType, ViewOptions } from '@opentelemetry/sdk-metrics';
19
+
20
+ /**
21
+ * The four histograms exported by the RocketMQ client, mirroring
22
+ * org.apache.rocketmq.client.java.metrics.HistogramEnum. The bucket
23
+ * boundaries (in milliseconds) are copied verbatim from the Java client.
24
+ */
25
+ export enum HistogramEnum {
26
+ /**
27
+ * Cost time of successful api calls of message publishing.
28
+ * Labels: topic, client_id, invocation_status.
29
+ */
30
+ SEND_COST_TIME = 'rocketmq_send_cost_time',
31
+ /**
32
+ * Latency of message delivery from remote.
33
+ * Labels: topic, client_id, consumer_group.
34
+ */
35
+ DELIVERY_LATENCY = 'rocketmq_delivery_latency',
36
+ /**
37
+ * Await time of message consumption.
38
+ * Labels: topic, client_id, consumer_group.
39
+ */
40
+ AWAIT_TIME = 'rocketmq_await_time',
41
+ /**
42
+ * Process time of message consumption.
43
+ * Labels: topic, client_id, consumer_group, invocation_status.
44
+ */
45
+ PROCESS_TIME = 'rocketmq_process_time',
46
+ }
47
+
48
+ /**
49
+ * Explicit bucket boundaries (milliseconds) for each histogram, identical to
50
+ * the Java client's Aggregation.explicitBucketHistogram(...) calls.
51
+ */
52
+ export const HISTOGRAM_BUCKETS: Record<HistogramEnum, number[]> = {
53
+ [HistogramEnum.SEND_COST_TIME]: [ 1.0, 5.0, 10.0, 20.0, 50.0, 200.0, 500.0 ],
54
+ [HistogramEnum.DELIVERY_LATENCY]: [ 1.0, 5.0, 10.0, 20.0, 50.0, 200.0, 500.0 ],
55
+ [HistogramEnum.AWAIT_TIME]: [ 1.0, 5.0, 20.0, 100.0, 1000.0, 5 * 1000.0, 10 * 1000.0 ],
56
+ [HistogramEnum.PROCESS_TIME]: [ 1.0, 5.0, 10.0, 100.0, 1000.0, 10 * 1000.0, 60 * 1000.0 ],
57
+ };
58
+
59
+ /**
60
+ * Build the OpenTelemetry view that forces the given histogram onto the exact
61
+ * explicit-bucket aggregation used by the Java client.
62
+ */
63
+ export function buildHistogramView(histogramEnum: HistogramEnum): ViewOptions {
64
+ return {
65
+ instrumentName: histogramEnum,
66
+ instrumentType: InstrumentType.HISTOGRAM,
67
+ aggregation: new ExplicitBucketHistogramAggregation(HISTOGRAM_BUCKETS[histogramEnum]),
68
+ };
69
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Licensed to the Apache Software Foundation (ASF) under one or more
3
+ * contributor license agreements. See the NOTICE file distributed with
4
+ * this work for additional information regarding copyright ownership.
5
+ * The ASF licenses this file to You under the Apache License, Version 2.0
6
+ * (the "License"); you may not use this file except in compliance with
7
+ * the License. You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ /**
19
+ * Outcome of an instrumented operation (send / consume), mirroring
20
+ * org.apache.rocketmq.client.java.metrics.InvocationStatus.
21
+ */
22
+ export class InvocationStatus {
23
+ static readonly SUCCESS = new InvocationStatus('success');
24
+ static readonly FAILURE = new InvocationStatus('failure');
25
+
26
+ private constructor(readonly name: string) {
27
+ }
28
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Licensed to the Apache Software Foundation (ASF) under one or more
3
+ * contributor license agreements. See the NOTICE file distributed with
4
+ * this work for additional information regarding copyright ownership.
5
+ * The ASF licenses this file to You under the Apache License, Version 2.0
6
+ * (the "License"); you may not use this file except in compliance with
7
+ * the License. You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ import { Endpoints } from '../route';
19
+ import { Metric as MetricPB } from '../../proto/apache/rocketmq/v2/definition_pb';
20
+
21
+ /**
22
+ * Local view of the metric switch received from the broker via the telemetry
23
+ * settings command, mirroring org.apache.rocketmq.client.java.metrics.Metric.
24
+ *
25
+ * Metrics are only considered enabled when both the `on` flag is set AND a
26
+ * valid endpoints is present.
27
+ */
28
+ export class Metric {
29
+ readonly endpoints: Endpoints | null;
30
+ readonly on: boolean;
31
+
32
+ constructor(metric: MetricPB | undefined | null) {
33
+ if (metric && metric.hasEndpoints() && metric.getOn()) {
34
+ // Endpoints expects the plain AsObject shape, so unwrap the proto message.
35
+ this.endpoints = new Endpoints(metric.getEndpoints()!.toObject());
36
+ this.on = true;
37
+ } else {
38
+ this.endpoints = null;
39
+ this.on = false;
40
+ }
41
+ }
42
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Licensed to the Apache Software Foundation (ASF) under one or more
3
+ * contributor license agreements. See the NOTICE file distributed with
4
+ * this work for additional information regarding copyright ownership.
5
+ * The ASF licenses this file to You under the Apache License, Version 2.0
6
+ * (the "License"); you may not use this file except in compliance with
7
+ * the License. You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ /**
19
+ * Canonical attribute (label) keys attached to every RocketMQ metric,
20
+ * mirroring org.apache.rocketmq.client.java.metrics.MetricLabels.
21
+ */
22
+ export class MetricLabels {
23
+ static readonly TOPIC = 'topic';
24
+ static readonly CLIENT_ID = 'client_id';
25
+ static readonly CONSUMER_GROUP = 'consumer_group';
26
+ static readonly INVOCATION_STATUS = 'invocation_status';
27
+
28
+ private constructor() {
29
+ // constant holder
30
+ }
31
+ }
@@ -0,0 +1,26 @@
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 './MetricLabels';
19
+ export * from './InvocationStatus';
20
+ export * from './HistogramEnum';
21
+ export * from './GaugeEnum';
22
+ export * from './GaugeObserver';
23
+ export * from './EmptyGaugeObserver';
24
+ export * from './Metric';
25
+ export * from './ClientMeter';
26
+ export * from './ClientMeterManager';
@@ -39,7 +39,7 @@ import {
39
39
  import {
40
40
  ExponentialBackoffRetryPolicy,
41
41
  } from '../retry';
42
- import { StatusChecker, TooManyRequestsException } from '../exception';
42
+ import { InternalErrorException, StatusChecker, TooManyRequestsException } from '../exception';
43
43
  import { BaseClient, BaseClientOptions, Settings } from '../client';
44
44
  import { PublishingMessage, MessageOptions, MessageView, Message } from '../message';
45
45
  import { PublishingSettings } from './PublishingSettings';
@@ -48,8 +48,22 @@ import { PublishingLoadBalancer } from './PublishingLoadBalancer';
48
48
  import { SendReceipt } from './SendReceipt';
49
49
  import { Transaction } from './Transaction';
50
50
  import { createResource } from '../util';
51
+ import { getRequestId } from '../util/rpcContext';
51
52
  import { RecallReceipt } from './RecallReceipt';
52
53
  import { RecallMessageRequest } from '../../proto/apache/rocketmq/v2/service_pb';
54
+ import {
55
+ Attribute,
56
+ AttributeKey,
57
+ GeneralMessage,
58
+ MessageHookPoints,
59
+ MessageHookPointsStatus,
60
+ MessageInterceptorContextImpl,
61
+ } from '../hook';
62
+
63
+ // Context keys exposed to SEND interceptors, mirroring the Java ProducerImpl keys.
64
+ export const MESSAGE_TYPE_CONTEXT_KEY = AttributeKey.create<MessageType>('messageType');
65
+ export const SEND_RECEIPTS_CONTEXT_KEY = AttributeKey.create<SendReceipt[]>('sendReceipts');
66
+ export const SEND_EXCEPTION_CONTEXT_KEY = AttributeKey.create<unknown>('sendException');
53
67
 
54
68
  export interface ProducerOptions extends BaseClientOptions {
55
69
  topic?: string | string[];
@@ -63,7 +77,10 @@ export class Producer extends BaseClient {
63
77
  #publishingRouteDataCache = new Map<string, PublishingLoadBalancer>();
64
78
 
65
79
  constructor(options: ProducerOptions) {
66
- if (!options.topics && options.topic) {
80
+ if (options.maxAttempts !== undefined && (!Number.isInteger(options.maxAttempts) || options.maxAttempts <= 0)) {
81
+ throw new TypeError('maxAttempts should be a positive integer');
82
+ }
83
+ if (options.topics === undefined && options.topic !== undefined) {
67
84
  options.topics = Array.isArray(options.topic) ? options.topic : [ options.topic ];
68
85
  }
69
86
  super(options);
@@ -98,7 +115,7 @@ export class Producer extends BaseClient {
98
115
  this.logger.error('Unable to begin a transaction because producer is not running, clientId=%s', this.clientId);
99
116
  throw new Error('Producer is not running now');
100
117
  }
101
- return new Transaction(this);
118
+ return new Transaction(this, this.logger);
102
119
  }
103
120
 
104
121
  async endTransaction(endpoints: Endpoints, message: Message, messageId: string,
@@ -114,17 +131,36 @@ export class Producer extends BaseClient {
114
131
  .setTopic(createResource(message.topic).setResourceNamespace(this.namespace))
115
132
  .setResolution(resolution)
116
133
  .setSource(source);
117
- const response = await this.rpcClientManager.endTransaction(endpoints, request, this.requestTimeout);
118
- StatusChecker.check(response.getStatus()?.toObject());
119
-
120
- this.logger.debug?.('End transaction successfully, messageId=%s, transactionId=%s, resolution=%s, source=%s, clientId=%s',
121
- messageId, transactionId, resolutionStr, sourceStr, this.clientId);
134
+ // COMMIT_TRANSACTION / ROLLBACK_TRANSACTION hook point, mirroring Java ProducerImpl#endTransaction.
135
+ const messageHookPoints = resolution === TransactionResolution.COMMIT ?
136
+ MessageHookPoints.COMMIT_TRANSACTION : MessageHookPoints.ROLLBACK_TRANSACTION;
137
+ const context = new MessageInterceptorContextImpl(messageHookPoints);
138
+ const generalMessages: GeneralMessage[] = [ message ];
139
+ this.doBefore(context, generalMessages);
140
+ try {
141
+ const response = await this.rpcClientManager.endTransaction(endpoints, request, this.requestTimeout);
142
+ const statusObj = response.getStatus()?.toObject();
143
+ const hookStatus = statusObj?.code === Code.OK ? MessageHookPointsStatus.OK : MessageHookPointsStatus.ERROR;
144
+ StatusChecker.check(statusObj, getRequestId(response));
145
+ this.doAfter(MessageInterceptorContextImpl.withStatus(context, hookStatus), generalMessages);
146
+
147
+ this.logger.debug?.('End transaction successfully, messageId=%s, transactionId=%s, resolution=%s, source=%s, clientId=%s',
148
+ messageId, transactionId, resolutionStr, sourceStr, this.clientId);
149
+ } catch (err) {
150
+ this.doAfter(MessageInterceptorContextImpl.withStatus(context, MessageHookPointsStatus.ERROR), generalMessages);
151
+ throw err;
152
+ }
122
153
  }
123
154
 
124
155
  async onRecoverOrphanedTransactionCommand(endpoints: Endpoints, command: RecoverOrphanedTransactionCommand) {
125
156
  const transactionId = command.getTransactionId();
126
- const messagePB = command.getMessage()!;
127
- const messageId = messagePB.getSystemProperties()!.getMessageId();
157
+ const messagePB = command.getMessage();
158
+ const messageId = messagePB?.getSystemProperties()?.getMessageId();
159
+ if (!messagePB) {
160
+ this.logger.error('[Bug] Orphaned transaction message is absent, ignore it, transactionId=%s, endpoints=%s, clientId=%s',
161
+ transactionId, endpoints, this.clientId);
162
+ return;
163
+ }
128
164
  if (!this.#checker) {
129
165
  this.logger.error('No transaction checker registered, ignore it, messageId=%s, transactionId=%s, endpoints=%s, clientId=%s',
130
166
  messageId, transactionId, endpoints, this.clientId);
@@ -145,7 +181,7 @@ export class Producer extends BaseClient {
145
181
  return;
146
182
  }
147
183
  // Use SOURCE_SERVER_CHECK for transaction recovery
148
- await this.endTransaction(endpoints, messageView, messageId, transactionId, resolution,
184
+ await this.endTransaction(endpoints, messageView, messageView.messageId, transactionId, resolution,
149
185
  TransactionSource.SOURCE_SERVER_CHECK);
150
186
  this.logger.info('Recover orphaned transaction message success, transactionId=%s, resolution=%s, messageId=%s, clientId=%s',
151
187
  transactionId, resolution, messageId, this.clientId);
@@ -180,14 +216,17 @@ export class Producer extends BaseClient {
180
216
 
181
217
  async send(message: MessageOptions, transaction?: Transaction) {
182
218
  if (!transaction) {
183
- const sendReceipts = await this.#send([ message ], false);
219
+ this.#checkRunning();
220
+ const sendReceipts = await this.#send([ new PublishingMessage(message, this.#publishingSettings, false) ]);
184
221
  return sendReceipts[0];
185
222
  }
186
223
 
187
224
  // Send transactional message
188
225
  try {
226
+ // Send the transaction's message instance so SEND and COMMIT/ROLLBACK hooks observe the same messageId.
189
227
  const publishingMessage = transaction.tryAddMessage(message);
190
- const sendReceipts = await this.#send([ message ], true);
228
+ this.#checkRunning();
229
+ const sendReceipts = await this.#send([ publishingMessage ]);
191
230
  const sendReceipt = sendReceipts[0];
192
231
  transaction.tryAddReceipt(publishingMessage, sendReceipt);
193
232
  return sendReceipt;
@@ -197,19 +236,16 @@ export class Producer extends BaseClient {
197
236
  }
198
237
  }
199
238
 
200
- async #send(messages: MessageOptions[], txEnabled: boolean) {
239
+ #checkRunning() {
201
240
  // Check producer status before message publishing
202
241
  if (!this.isRunning()) {
203
242
  this.logger.error('Unable to send message because producer is not running, clientId=%s', this.clientId);
204
243
  throw new Error('Producer is not running now');
205
244
  }
245
+ }
206
246
 
207
- const pubMessages: PublishingMessage[] = [];
208
- const topics = new Set<string>();
209
- for (const message of messages) {
210
- pubMessages.push(new PublishingMessage(message, this.#publishingSettings, txEnabled));
211
- topics.add(message.topic);
212
- }
247
+ async #send(pubMessages: PublishingMessage[]) {
248
+ const topics = new Set(pubMessages.map(m => m.topic));
213
249
  if (topics.size > 1) {
214
250
  throw new TypeError(`Messages to send have different topics=${JSON.stringify(Array.from(topics))}`);
215
251
  }
@@ -277,11 +313,19 @@ export class Producer extends BaseClient {
277
313
  const endpoints = mq.broker.endpoints;
278
314
  const maxAttempts = this.#getRetryPolicy().getMaxAttempts();
279
315
  const request = this.#wrapSendMessageRequest(messages, mq);
316
+ // SEND hook point per attempt, mirroring Java ProducerImpl#send0.
317
+ const generalMessages = messages as unknown as GeneralMessage[];
318
+ const context = new MessageInterceptorContextImpl(MessageHookPoints.SEND);
319
+ context.putAttribute(MESSAGE_TYPE_CONTEXT_KEY, Attribute.create(messageType));
320
+ this.doBefore(context, generalMessages);
280
321
  let sendReceipts: SendReceipt[] = [];
281
322
  try {
282
323
  const response = await this.rpcClientManager.sendMessage(endpoints, request, this.requestTimeout);
283
324
  sendReceipts = SendReceipt.processResponseInvocation(mq, response);
284
325
  } catch (err) {
326
+ const context0 = MessageInterceptorContextImpl.withStatus(context, MessageHookPointsStatus.ERROR);
327
+ context0.putAttribute(SEND_EXCEPTION_CONTEXT_KEY, Attribute.create(err));
328
+ this.doAfter(context0, generalMessages);
285
329
  const messageIds = messages.map(m => m.messageId);
286
330
  // Isolate endpoints because of sending failure
287
331
  this.#isolate(endpoints);
@@ -291,12 +335,6 @@ export class Producer extends BaseClient {
291
335
  maxAttempts, attempt, topic, messageIds, endpoints, this.clientId, err);
292
336
  throw err;
293
337
  }
294
- // No more attempts for transactional message
295
- if (messageType === MessageType.TRANSACTION) {
296
- this.logger.error('Failed to send transactional message finally, maxAttempts=%d, attempt=%d, topic=%s, messageId(s)=%s, endpoints=%s, clientId=%s, error=%s',
297
- maxAttempts, attempt, topic, messageIds, endpoints, this.clientId, err);
298
- throw err;
299
- }
300
338
  // Try next attempt
301
339
  const nextAttempt = 1 + attempt;
302
340
  // Retry immediately if the request is not throttled
@@ -312,6 +350,18 @@ export class Producer extends BaseClient {
312
350
  return this.#send0(topic, messageType, candidates, messages, nextAttempt);
313
351
  }
314
352
 
353
+ // Should never reach here.
354
+ if (sendReceipts.length !== messages.length) {
355
+ const err = new InternalErrorException(Code.INTERNAL_ERROR, '[Bug] due to an unknown reason from remote, received ' +
356
+ `send receipt's quantity ${sendReceipts.length} is not equal to sent message's quantity ${messages.length}`);
357
+ const context0 = MessageInterceptorContextImpl.withStatus(context, MessageHookPointsStatus.ERROR);
358
+ context0.putAttribute(SEND_EXCEPTION_CONTEXT_KEY, Attribute.create(err));
359
+ this.doAfter(context0, generalMessages);
360
+ throw err;
361
+ }
362
+ const context0 = MessageInterceptorContextImpl.withStatus(context, MessageHookPointsStatus.OK);
363
+ context0.putAttribute(SEND_RECEIPTS_CONTEXT_KEY, Attribute.create(sendReceipts));
364
+ this.doAfter(context0, generalMessages);
315
365
  // Resend message(s) successfully
316
366
  if (attempt > 1) {
317
367
  const messageIds = sendReceipts.map(r => r.messageId);
@@ -331,11 +381,24 @@ export class Producer extends BaseClient {
331
381
  let loadBalancer = this.#publishingRouteDataCache.get(topic);
332
382
  if (!loadBalancer) {
333
383
  const topicRouteData = await this.getRouteData(topic);
334
- loadBalancer = this.#updatePublishingLoadBalancer(topic, topicRouteData);
384
+ // A fresh route fetch has already built the load balancer in onTopicRouteDataUpdate.
385
+ loadBalancer = this.#publishingRouteDataCache.get(topic) ??
386
+ this.#updatePublishingLoadBalancer(topic, topicRouteData);
335
387
  }
336
388
  return loadBalancer;
337
389
  }
338
390
 
391
+ protected onTopicRouteDataUpdate(topic: string, topicRouteData: TopicRouteData) {
392
+ try {
393
+ this.#updatePublishingLoadBalancer(topic, topicRouteData);
394
+ } catch (err) {
395
+ // Keep the previous load balancer so that a route without writable queues fails neither the route refresh
396
+ // of other topics nor the startup; sending to such a topic still fails when no load balancer exists.
397
+ this.logger.error('Failed to update publishing load balancer, topic=%s, clientId=%s, error=%s',
398
+ topic, this.clientId, err);
399
+ }
400
+ }
401
+
339
402
  #updatePublishingLoadBalancer(topic: string, topicRouteData: TopicRouteData) {
340
403
  let loadBalancer = this.#publishingRouteDataCache.get(topic);
341
404
  if (loadBalancer) {
@@ -366,6 +429,7 @@ export class Producer extends BaseClient {
366
429
  * @param recallHandle - A unique handle to identify the message to recall (obtained from SendReceipt).
367
430
  * @return Promise resolving to RecallReceipt containing the recalled message ID.
368
431
  * @throws Error if producer is not running or recall handle is invalid.
432
+ * @throws ClientException subclass mapped from the response status if the remote fails to recall the message.
369
433
  */
370
434
  async recallMessage(topic: string, recallHandle: string): Promise<RecallReceipt> {
371
435
  if (!this.isRunning()) {
@@ -392,17 +456,9 @@ export class Producer extends BaseClient {
392
456
  .setRecallHandle(recallHandle);
393
457
 
394
458
  const response = await this.rpcClientManager.recallMessage(this.endpoints, request, this.requestTimeout);
395
- const status = response.getStatus();
396
- if (!status) {
397
- throw new Error('Recall message response status is null');
398
- }
399
-
400
- // Check status code
401
- const statusCode = status.getCode();
402
- if (statusCode !== Code.OK) {
403
- const errorMessage = status.getMessage() || 'Unknown error';
404
- throw new Error(`Failed to recall message: ${errorMessage} (code: ${statusCode})`);
405
- }
459
+ // StatusChecker surfaces a missing status as InternalErrorException and MESSAGE_NOT_FOUND as
460
+ // NotFoundException, as Java does.
461
+ StatusChecker.check(response.getStatus()?.toObject(), getRequestId(response));
406
462
 
407
463
  const messageId = response.getMessageId();
408
464
  const receipt = new RecallReceipt(messageId);
@@ -26,12 +26,12 @@ export class PublishingLoadBalancer {
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.WRITE || mq.permission === Permission.READ_WRITE);
29
+ return mq.broker.id === MASTER_BROKER_ID && (mq.permission === Permission.WRITE || 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 writable 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) {
@@ -78,8 +78,14 @@ export class PublishingLoadBalancer {
78
78
  }
79
79
 
80
80
  takeMessageQueueByMessageGroup(messageGroup: string) {
81
- const hashCode = calculateStringSipHash24(messageGroup);
82
- const index = parseInt(`${hashCode % BigInt(this.#messageQueues.length)}`);
81
+ // SipHash-2-4 returns an unsigned 64-bit value in JS (readBigUInt64BE), while
82
+ // Java's String.hashCode-style paths use signed semantics. Interpret the hash as
83
+ // a signed 64-bit integer and apply floorMod so the result is always non-negative,
84
+ // exactly matching Java LongMath.mod(hashCode, size) — otherwise FIFO messages
85
+ // with "negative" hashes route to different queues than the Java client.
86
+ const hashCode = BigInt.asIntN(64, calculateStringSipHash24(messageGroup));
87
+ const size = this.#messageQueues.length;
88
+ const index = Number(((hashCode % BigInt(size)) + BigInt(size)) % BigInt(size));
83
89
  return this.#messageQueues[index];
84
90
  }
85
91
 
@@ -64,8 +64,6 @@ export class PublishingSettings extends Settings {
64
64
 
65
65
  sync(settings: SettingsPB): void {
66
66
  if (settings.getPubSubCase() !== SettingsPB.PubSubCase.PUBLISHING) {
67
- // log.error("[Bug] Issued settings not match with the client type, clientId={}, pubSubCase={}, "
68
- // + "clientType={}", clientId, pubSubCase, clientType);
69
67
  return;
70
68
  }
71
69
  const backoffPolicy = settings.getBackoffPolicy()!;
@@ -19,6 +19,7 @@ import { Code } from '../../proto/apache/rocketmq/v2/definition_pb';
19
19
  import { SendMessageResponse } from '../../proto/apache/rocketmq/v2/service_pb';
20
20
  import { MessageQueue } from '../route';
21
21
  import { StatusChecker } from '../exception';
22
+ import { getRequestId } from '../util/rpcContext';
22
23
 
23
24
  export class SendReceipt {
24
25
  readonly messageId: string;
@@ -48,7 +49,7 @@ export class SendReceipt {
48
49
  // Filter abnormal status.
49
50
  const abnormalStatus = responseObj.entriesList.map(e => e.status).find(s => s?.code !== Code.OK);
50
51
  const status = abnormalStatus ?? responseObj.status;
51
- StatusChecker.check(status);
52
+ StatusChecker.check(status, getRequestId(response));
52
53
  const sendReceipts: SendReceipt[] = [];
53
54
  for (const entry of responseObj.entriesList) {
54
55
  const messageId = entry.messageId;
@@ -16,6 +16,7 @@
16
16
  */
17
17
 
18
18
  import { TransactionResolution } from '../../proto/apache/rocketmq/v2/definition_pb';
19
+ import { getDefaultLogger, ILogger } from '../client';
19
20
  import { MessageOptions, PublishingMessage } from '../message';
20
21
  import type { Producer } from './Producer';
21
22
  import { SendReceipt } from './SendReceipt';
@@ -23,11 +24,13 @@ import { SendReceipt } from './SendReceipt';
23
24
  export class Transaction {
24
25
  static readonly MAX_MESSAGE_NUM = 1;
25
26
  readonly #producer: Producer;
27
+ readonly #logger: ILogger;
26
28
  readonly #messageMap = new Map<string, PublishingMessage>();
27
29
  readonly #messageSendReceiptMap = new Map<string, SendReceipt>();
28
30
 
29
- constructor(producer: Producer) {
31
+ constructor(producer: Producer, logger: ILogger = getDefaultLogger()) {
30
32
  this.#producer = producer;
33
+ this.#logger = logger;
31
34
  }
32
35
 
33
36
  tryAddMessage(message: MessageOptions) {
@@ -51,9 +54,8 @@ export class Transaction {
51
54
  throw new TypeError('Transactional message has not been sent yet');
52
55
  }
53
56
 
54
- const logger = (this.#producer as any).logger;
55
- logger.info('Begin to commit transaction, messageCount=%d, clientId=%s',
56
- this.#messageSendReceiptMap.size, (this.#producer as any).clientId);
57
+ this.#logger.info('Begin to commit transaction, messageCount=%d, clientId=%s',
58
+ this.#messageSendReceiptMap.size, this.#producer.clientId);
57
59
 
58
60
  for (const [ messageId, sendReceipt ] of this.#messageSendReceiptMap.entries()) {
59
61
  const publishingMessage = this.#messageMap.get(messageId)!;
@@ -61,8 +63,8 @@ export class Transaction {
61
63
  sendReceipt.messageId, sendReceipt.transactionId, TransactionResolution.COMMIT);
62
64
  }
63
65
 
64
- logger.debug('Commit transaction successfully, messageCount=%d, clientId=%s',
65
- this.#messageSendReceiptMap.size, (this.#producer as any).clientId);
66
+ this.#logger.debug?.('Commit transaction successfully, messageCount=%d, clientId=%s',
67
+ this.#messageSendReceiptMap.size, this.#producer.clientId);
66
68
  }
67
69
 
68
70
  async rollback() {
@@ -70,9 +72,8 @@ export class Transaction {
70
72
  throw new TypeError('Transactional message has not been sent yet');
71
73
  }
72
74
 
73
- const logger = (this.#producer as any).logger;
74
- logger.debug('Begin to rollback transaction, messageCount=%d, clientId=%s',
75
- this.#messageSendReceiptMap.size, (this.#producer as any).clientId);
75
+ this.#logger.debug?.('Begin to rollback transaction, messageCount=%d, clientId=%s',
76
+ this.#messageSendReceiptMap.size, this.#producer.clientId);
76
77
 
77
78
  for (const [ messageId, sendReceipt ] of this.#messageSendReceiptMap.entries()) {
78
79
  const publishingMessage = this.#messageMap.get(messageId)!;
@@ -80,7 +81,7 @@ export class Transaction {
80
81
  sendReceipt.messageId, sendReceipt.transactionId, TransactionResolution.ROLLBACK);
81
82
  }
82
83
 
83
- logger.debug('Rollback transaction successfully, messageCount=%d, clientId=%s',
84
- this.#messageSendReceiptMap.size, (this.#producer as any).clientId);
84
+ this.#logger.debug?.('Rollback transaction successfully, messageCount=%d, clientId=%s',
85
+ this.#messageSendReceiptMap.size, this.#producer.clientId);
85
86
  }
86
87
  }
@@ -20,5 +20,5 @@ export * from './PublishingLoadBalancer';
20
20
  export * from './PublishingSettings';
21
21
  export * from './RecallReceipt';
22
22
  export * from './SendReceipt';
23
- // export * from './Transaction';
23
+ export * from './Transaction';
24
24
  export * from './TransactionChecker';