rocketmq-client-nodejs 1.0.7 → 1.1.0

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 (164) hide show
  1. package/README.md +61 -0
  2. package/dist/client/BaseClient.d.ts +36 -1
  3. package/dist/client/BaseClient.js +176 -12
  4. package/dist/client/RpcClient.js +14 -2
  5. package/dist/client/RpcClientManager.d.ts +5 -0
  6. package/dist/client/RpcClientManager.js +25 -8
  7. package/dist/client/TelemetrySession.js +45 -10
  8. package/dist/consumer/ConsumeResult.d.ts +2 -2
  9. package/dist/consumer/ConsumeResult.js +6 -3
  10. package/dist/consumer/ConsumeService.d.ts +2 -1
  11. package/dist/consumer/ConsumeService.js +7 -3
  12. package/dist/consumer/ConsumeTask.d.ts +6 -1
  13. package/dist/consumer/ConsumeTask.js +36 -5
  14. package/dist/consumer/Consumer.d.ts +13 -5
  15. package/dist/consumer/Consumer.js +85 -24
  16. package/dist/consumer/FifoConsumeService.d.ts +2 -1
  17. package/dist/consumer/FifoConsumeService.js +3 -3
  18. package/dist/consumer/LiteFifoConsumeService.d.ts +2 -1
  19. package/dist/consumer/LiteFifoConsumeService.js +3 -3
  20. package/dist/consumer/LitePushConsumerImpl.d.ts +12 -1
  21. package/dist/consumer/LitePushConsumerImpl.js +19 -4
  22. package/dist/consumer/LiteSimpleConsumer.d.ts +177 -0
  23. package/dist/consumer/LiteSimpleConsumer.js +126 -0
  24. package/dist/consumer/LiteSimpleConsumerImpl.d.ts +133 -0
  25. package/dist/consumer/LiteSimpleConsumerImpl.js +187 -0
  26. package/dist/consumer/LiteStandardConsumeService.d.ts +2 -1
  27. package/dist/consumer/LiteStandardConsumeService.js +3 -3
  28. package/dist/consumer/LiteSubscriptionManager.d.ts +27 -6
  29. package/dist/consumer/LiteSubscriptionManager.js +32 -24
  30. package/dist/consumer/ProcessQueue.d.ts +10 -0
  31. package/dist/consumer/ProcessQueue.js +47 -7
  32. package/dist/consumer/PushConsumer.d.ts +17 -0
  33. package/dist/consumer/PushConsumer.js +87 -7
  34. package/dist/consumer/PushConsumerGaugeObserver.d.ts +33 -0
  35. package/dist/consumer/PushConsumerGaugeObserver.js +60 -0
  36. package/dist/consumer/PushSubscriptionSettings.d.ts +8 -1
  37. package/dist/consumer/PushSubscriptionSettings.js +33 -6
  38. package/dist/consumer/SimpleConsumer.js +10 -1
  39. package/dist/consumer/StandardConsumeService.d.ts +2 -1
  40. package/dist/consumer/StandardConsumeService.js +3 -3
  41. package/dist/consumer/index.d.ts +1 -0
  42. package/dist/consumer/index.js +2 -1
  43. package/dist/exception/PayloadEmptyException.d.ts +20 -0
  44. package/dist/exception/PayloadEmptyException.js +28 -0
  45. package/dist/exception/StatusChecker.js +8 -1
  46. package/dist/exception/index.d.ts +1 -0
  47. package/dist/exception/index.js +2 -1
  48. package/dist/hook/Attribute.d.ts +26 -0
  49. package/dist/hook/Attribute.js +37 -0
  50. package/dist/hook/AttributeKey.d.ts +32 -0
  51. package/dist/hook/AttributeKey.js +43 -0
  52. package/dist/hook/CompositedMessageInterceptor.d.ts +31 -0
  53. package/dist/hook/CompositedMessageInterceptor.js +84 -0
  54. package/dist/hook/InflightRequestCountInterceptor.d.ts +28 -0
  55. package/dist/hook/InflightRequestCountInterceptor.js +44 -0
  56. package/dist/hook/MessageHookPoints.d.ts +54 -0
  57. package/dist/hook/MessageHookPoints.js +59 -0
  58. package/dist/hook/MessageHookPointsStatus.d.ts +24 -0
  59. package/dist/hook/MessageHookPointsStatus.js +29 -0
  60. package/dist/hook/MessageInterceptor.d.ts +34 -0
  61. package/dist/hook/MessageInterceptor.js +19 -0
  62. package/dist/hook/MessageInterceptorContext.d.ts +31 -0
  63. package/dist/hook/MessageInterceptorContext.js +19 -0
  64. package/dist/hook/MessageInterceptorContextImpl.d.ts +39 -0
  65. package/dist/hook/MessageInterceptorContextImpl.js +57 -0
  66. package/dist/hook/MessageMeterInterceptor.d.ts +39 -0
  67. package/dist/hook/MessageMeterInterceptor.js +149 -0
  68. package/dist/hook/index.d.ts +26 -0
  69. package/dist/hook/index.js +43 -0
  70. package/dist/index.d.ts +1 -0
  71. package/dist/index.js +2 -1
  72. package/dist/metrics/ClientMeter.d.ts +42 -0
  73. package/dist/metrics/ClientMeter.js +75 -0
  74. package/dist/metrics/ClientMeterManager.d.ts +42 -0
  75. package/dist/metrics/ClientMeterManager.js +127 -0
  76. package/dist/metrics/EmptyGaugeObserver.d.ts +28 -0
  77. package/dist/metrics/EmptyGaugeObserver.js +34 -0
  78. package/dist/metrics/GaugeEnum.d.ts +32 -0
  79. package/dist/metrics/GaugeEnum.js +37 -0
  80. package/dist/metrics/GaugeObserver.d.ts +29 -0
  81. package/dist/metrics/GaugeObserver.js +19 -0
  82. package/dist/metrics/HistogramEnum.d.ts +54 -0
  83. package/dist/metrics/HistogramEnum.js +71 -0
  84. package/dist/metrics/InvocationStatus.d.ts +26 -0
  85. package/dist/metrics/InvocationStatus.js +33 -0
  86. package/dist/metrics/Metric.d.ts +30 -0
  87. package/dist/metrics/Metric.js +44 -0
  88. package/dist/metrics/MetricLabels.d.ts +27 -0
  89. package/dist/metrics/MetricLabels.js +34 -0
  90. package/dist/metrics/index.d.ts +25 -0
  91. package/dist/metrics/index.js +42 -0
  92. package/dist/producer/Producer.js +33 -5
  93. package/dist/producer/PublishingLoadBalancer.js +9 -3
  94. package/dist/retry/CustomizedBackoffRetryPolicy.d.ts +37 -0
  95. package/dist/retry/CustomizedBackoffRetryPolicy.js +72 -0
  96. package/dist/retry/ExponentialBackoffRetryPolicy.js +10 -6
  97. package/dist/retry/RetryPolicy.d.ts +1 -1
  98. package/dist/retry/index.d.ts +1 -0
  99. package/dist/retry/index.js +2 -1
  100. package/dist/route/Endpoints.d.ts +6 -0
  101. package/dist/route/Endpoints.js +56 -4
  102. package/dist/route/IpNameResolver.d.ts +28 -0
  103. package/dist/route/IpNameResolver.js +104 -0
  104. package/dist/util/Semaphore.d.ts +47 -0
  105. package/dist/util/Semaphore.js +82 -0
  106. package/dist/util/index.js +6 -3
  107. package/package.json +6 -2
  108. package/src/client/BaseClient.ts +202 -12
  109. package/src/client/RpcClient.ts +14 -1
  110. package/src/client/RpcClientManager.ts +27 -8
  111. package/src/client/TelemetrySession.ts +47 -9
  112. package/src/consumer/ConsumeResult.ts +5 -2
  113. package/src/consumer/ConsumeService.ts +9 -2
  114. package/src/consumer/ConsumeTask.ts +43 -3
  115. package/src/consumer/Consumer.ts +103 -23
  116. package/src/consumer/FifoConsumeService.ts +4 -2
  117. package/src/consumer/LiteFifoConsumeService.ts +4 -2
  118. package/src/consumer/LitePushConsumerImpl.ts +21 -3
  119. package/src/consumer/LiteSimpleConsumer.ts +251 -0
  120. package/src/consumer/LiteSimpleConsumerImpl.ts +221 -0
  121. package/src/consumer/LiteStandardConsumeService.ts +4 -2
  122. package/src/consumer/LiteSubscriptionManager.ts +63 -36
  123. package/src/consumer/ProcessQueue.ts +54 -3
  124. package/src/consumer/PushConsumer.ts +98 -5
  125. package/src/consumer/PushConsumerGaugeObserver.ts +60 -0
  126. package/src/consumer/PushSubscriptionSettings.ts +38 -7
  127. package/src/consumer/SimpleConsumer.ts +9 -0
  128. package/src/consumer/StandardConsumeService.ts +4 -2
  129. package/src/consumer/index.ts +1 -0
  130. package/src/exception/PayloadEmptyException.ts +25 -0
  131. package/src/exception/StatusChecker.ts +7 -0
  132. package/src/exception/index.ts +1 -0
  133. package/src/hook/Attribute.ts +36 -0
  134. package/src/hook/AttributeKey.ts +42 -0
  135. package/src/hook/CompositedMessageInterceptor.ts +92 -0
  136. package/src/hook/InflightRequestCountInterceptor.ts +46 -0
  137. package/src/hook/MessageHookPoints.ts +55 -0
  138. package/src/hook/MessageHookPointsStatus.ts +25 -0
  139. package/src/hook/MessageInterceptor.ts +35 -0
  140. package/src/hook/MessageInterceptorContext.ts +33 -0
  141. package/src/hook/MessageInterceptorContextImpl.ts +68 -0
  142. package/src/hook/MessageMeterInterceptor.ts +162 -0
  143. package/src/hook/index.ts +27 -0
  144. package/src/index.ts +1 -0
  145. package/src/metrics/ClientMeter.ts +81 -0
  146. package/src/metrics/ClientMeterManager.ts +145 -0
  147. package/src/metrics/EmptyGaugeObserver.ts +36 -0
  148. package/src/metrics/GaugeEnum.ts +33 -0
  149. package/src/metrics/GaugeObserver.ts +32 -0
  150. package/src/metrics/HistogramEnum.ts +69 -0
  151. package/src/metrics/InvocationStatus.ts +28 -0
  152. package/src/metrics/Metric.ts +42 -0
  153. package/src/metrics/MetricLabels.ts +31 -0
  154. package/src/metrics/index.ts +26 -0
  155. package/src/producer/Producer.ts +37 -6
  156. package/src/producer/PublishingLoadBalancer.ts +8 -2
  157. package/src/retry/CustomizedBackoffRetryPolicy.ts +81 -0
  158. package/src/retry/ExponentialBackoffRetryPolicy.ts +11 -6
  159. package/src/retry/RetryPolicy.ts +1 -1
  160. package/src/retry/index.ts +1 -0
  161. package/src/route/Endpoints.ts +52 -3
  162. package/src/route/IpNameResolver.ts +119 -0
  163. package/src/util/Semaphore.ts +82 -0
  164. package/src/util/index.ts +5 -2
@@ -0,0 +1,145 @@
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
+ View,
23
+ } from '@opentelemetry/sdk-metrics';
24
+ import { Resource } from '@opentelemetry/resources';
25
+ import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-grpc';
26
+ import { ChannelCredentials, Metadata } from '@grpc/grpc-js';
27
+ import { ILogger } from '../client/Logger';
28
+ import { ClientMeter } from './ClientMeter';
29
+ import { GaugeObserver } from './GaugeObserver';
30
+ import { EmptyGaugeObserver } from './EmptyGaugeObserver';
31
+ import { HistogramEnum, buildHistogramView } from './HistogramEnum';
32
+ import { Metric } from './Metric';
33
+
34
+ const METRIC_EXPORTER_RPC_TIMEOUT = 5000;
35
+ const METRIC_READER_INTERVAL = 60000;
36
+ const METRIC_INSTRUMENTATION_NAME = 'org.apache.rocketmq.message';
37
+
38
+ /**
39
+ * Owns the OpenTelemetry metric pipeline for a single client. On every settings
40
+ * command it lazily (re)builds an SdkMeterProvider that exports the four
41
+ * RocketMQ histograms plus the consumer gauges to the broker-supplied metric
42
+ * endpoints over OTLP/gRPC, mirroring
43
+ * org.apache.rocketmq.client.java.metrics.ClientMeterManager.
44
+ */
45
+ export class ClientMeterManager {
46
+ private readonly clientId: string;
47
+ private readonly metadataProvider: () => Metadata;
48
+ private readonly logger: ILogger;
49
+ private clientMeter: ClientMeter;
50
+ private gaugeObserver: GaugeObserver = EmptyGaugeObserver.EMPTY;
51
+
52
+ constructor(clientId: string, metadataProvider: () => Metadata, logger: ILogger) {
53
+ this.clientId = clientId;
54
+ this.metadataProvider = metadataProvider;
55
+ this.logger = logger;
56
+ this.clientMeter = ClientMeter.disabledInstance();
57
+ }
58
+
59
+ setGaugeObserver(gaugeObserver: GaugeObserver) {
60
+ this.gaugeObserver = gaugeObserver;
61
+ }
62
+
63
+ record(histogramEnum: HistogramEnum, attributes: Attributes, value: number) {
64
+ this.clientMeter.record(histogramEnum, attributes, value);
65
+ }
66
+
67
+ isEnabled(): boolean {
68
+ return this.clientMeter.enabled;
69
+ }
70
+
71
+ async shutdown() {
72
+ await this.clientMeter.shutdown();
73
+ }
74
+
75
+ async reset(metric: Metric): Promise<void> {
76
+ try {
77
+ if (this.clientMeter.satisfy(metric)) {
78
+ this.logger.info('Metric settings is satisfied by the current message meter, metric=%j, clientId=%s',
79
+ metric, this.clientId);
80
+ return;
81
+ }
82
+ if (!metric.on || !metric.endpoints) {
83
+ this.logger.info('Metric is off, clientId=%s', this.clientId);
84
+ await this.clientMeter.shutdown();
85
+ this.clientMeter = ClientMeter.disabledInstance();
86
+ return;
87
+ }
88
+ 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,
104
+ });
105
+
106
+ const reader = new PeriodicExportingMetricReader({
107
+ exporter,
108
+ exportIntervalMillis: METRIC_READER_INTERVAL,
109
+ exportTimeoutMillis: METRIC_EXPORTER_RPC_TIMEOUT,
110
+ });
111
+
112
+ const views: View[] = [
113
+ new View(buildHistogramView(HistogramEnum.SEND_COST_TIME)),
114
+ new View(buildHistogramView(HistogramEnum.DELIVERY_LATENCY)),
115
+ new View(buildHistogramView(HistogramEnum.AWAIT_TIME)),
116
+ new View(buildHistogramView(HistogramEnum.PROCESS_TIME)),
117
+ ];
118
+
119
+ const provider: SdkMeterProvider = new SdkMeterProvider({
120
+ resource: Resource.empty(),
121
+ readers: [ reader ],
122
+ views,
123
+ });
124
+
125
+ const meter: Meter = provider.getMeter(METRIC_INSTRUMENTATION_NAME);
126
+
127
+ const existedClientMeter = this.clientMeter;
128
+ this.clientMeter = new ClientMeter(meter, endpoints, provider);
129
+ await existedClientMeter.shutdown();
130
+ this.logger.info('Metrics is on, endpoints=%s, clientId=%s', endpoints, this.clientId);
131
+
132
+ const gauges = this.gaugeObserver.getGauges();
133
+ for (const gauge of gauges) {
134
+ meter.createObservableGauge(gauge).addCallback(observableResult => {
135
+ const values = this.gaugeObserver.getValues(gauge);
136
+ for (const [ attributes, value ] of values) {
137
+ observableResult.observe(value, attributes);
138
+ }
139
+ });
140
+ }
141
+ } catch (t) {
142
+ this.logger.error('Exception raised when resetting message meter, clientId=%s, error=%s', this.clientId, t);
143
+ }
144
+ }
145
+ }
@@ -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
+ }
@@ -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';
@@ -50,6 +50,12 @@ import { Transaction } from './Transaction';
50
50
  import { createResource } from '../util';
51
51
  import { RecallReceipt } from './RecallReceipt';
52
52
  import { RecallMessageRequest } from '../../proto/apache/rocketmq/v2/service_pb';
53
+ import {
54
+ GeneralMessage,
55
+ MessageHookPoints,
56
+ MessageHookPointsStatus,
57
+ MessageInterceptorContextImpl,
58
+ } from '../hook';
53
59
 
54
60
  export interface ProducerOptions extends BaseClientOptions {
55
61
  topic?: string | string[];
@@ -114,11 +120,25 @@ export class Producer extends BaseClient {
114
120
  .setTopic(createResource(message.topic).setResourceNamespace(this.namespace))
115
121
  .setResolution(resolution)
116
122
  .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);
123
+ // COMMIT_TRANSACTION / ROLLBACK_TRANSACTION hook point, mirroring Java ProducerImpl#endTransaction.
124
+ const messageHookPoints = resolution === TransactionResolution.COMMIT ?
125
+ MessageHookPoints.COMMIT_TRANSACTION : MessageHookPoints.ROLLBACK_TRANSACTION;
126
+ const context = new MessageInterceptorContextImpl(messageHookPoints);
127
+ const generalMessages: GeneralMessage[] = [ message ];
128
+ this.doBefore(context, generalMessages);
129
+ try {
130
+ const response = await this.rpcClientManager.endTransaction(endpoints, request, this.requestTimeout);
131
+ const statusObj = response.getStatus()?.toObject();
132
+ const hookStatus = statusObj?.code === Code.OK ? MessageHookPointsStatus.OK : MessageHookPointsStatus.ERROR;
133
+ StatusChecker.check(statusObj);
134
+ this.doAfter(MessageInterceptorContextImpl.withStatus(context, hookStatus), generalMessages);
135
+
136
+ this.logger.debug?.('End transaction successfully, messageId=%s, transactionId=%s, resolution=%s, source=%s, clientId=%s',
137
+ messageId, transactionId, resolutionStr, sourceStr, this.clientId);
138
+ } catch (err) {
139
+ this.doAfter(MessageInterceptorContextImpl.withStatus(context, MessageHookPointsStatus.ERROR), generalMessages);
140
+ throw err;
141
+ }
122
142
  }
123
143
 
124
144
  async onRecoverOrphanedTransactionCommand(endpoints: Endpoints, command: RecoverOrphanedTransactionCommand) {
@@ -241,7 +261,18 @@ export class Producer extends BaseClient {
241
261
  // Prepare the candidate message queue(s) for retry-sending in advance.
242
262
  const candidates = messageGroup ? [ loadBalancer.takeMessageQueueByMessageGroup(messageGroup) ] :
243
263
  this.#takeMessageQueues(loadBalancer);
244
- return await this.#send0(topic, messageType, candidates, pubMessages, 1);
264
+ // SEND hook point, mirroring Java ProducerImpl#send.
265
+ const context = new MessageInterceptorContextImpl(MessageHookPoints.SEND);
266
+ const generalMessages = pubMessages as unknown as GeneralMessage[];
267
+ this.doBefore(context, generalMessages);
268
+ try {
269
+ const receipts = await this.#send0(topic, messageType, candidates, pubMessages, 1);
270
+ this.doAfter(MessageInterceptorContextImpl.withStatus(context, MessageHookPointsStatus.OK), generalMessages);
271
+ return receipts;
272
+ } catch (err) {
273
+ this.doAfter(MessageInterceptorContextImpl.withStatus(context, MessageHookPointsStatus.ERROR), generalMessages);
274
+ throw err;
275
+ }
245
276
  }
246
277
 
247
278
  #wrapSendMessageRequest(pubMessages: PublishingMessage[], mq: MessageQueue) {
@@ -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
 
@@ -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 assert from 'node:assert';
19
+ import { Duration } from 'google-protobuf/google/protobuf/duration_pb';
20
+ import {
21
+ RetryPolicy as RetryPolicyPB,
22
+ CustomizedBackoff,
23
+ } from '../../proto/apache/rocketmq/v2/definition_pb';
24
+ import { createDuration } from '../util';
25
+ import { RetryPolicy } from './RetryPolicy';
26
+
27
+ /**
28
+ * Backoff policy whose durations are customized by the server side,
29
+ * mirroring Java's CustomizedBackoffRetryPolicy: the Nth attempt waits
30
+ * durations[N - 1], and once attempts run past the list, the last
31
+ * duration applies.
32
+ */
33
+ export class CustomizedBackoffRetryPolicy implements RetryPolicy {
34
+ #maxAttempts: number;
35
+ // Backoff durations in milliseconds.
36
+ #durations: number[];
37
+
38
+ constructor(durations: number[], maxAttempts: number) {
39
+ assert(Array.isArray(durations) && durations.length > 0, 'durations must not be empty');
40
+ this.#durations = durations;
41
+ this.#maxAttempts = maxAttempts;
42
+ }
43
+
44
+ getMaxAttempts(): number {
45
+ return this.#maxAttempts;
46
+ }
47
+
48
+ getNextAttemptDelay(attempt: number): number {
49
+ assert(attempt > 0, 'attempt must be positive');
50
+ return attempt > this.#durations.length
51
+ ? this.#durations[this.#durations.length - 1]
52
+ : this.#durations[attempt - 1];
53
+ }
54
+
55
+ inheritBackoff(retryPolicy: RetryPolicyPB): RetryPolicy {
56
+ assert(retryPolicy.getStrategyCase() === RetryPolicyPB.StrategyCase.CUSTOMIZED_BACKOFF,
57
+ 'strategy must be customized backoff');
58
+ return new CustomizedBackoffRetryPolicy(
59
+ CustomizedBackoffRetryPolicy.durationsToMillis(retryPolicy.getCustomizedBackoff()!),
60
+ this.#maxAttempts);
61
+ }
62
+
63
+ toProtobuf(): RetryPolicyPB {
64
+ const customizedBackoff = new CustomizedBackoff();
65
+ for (const duration of this.#durations) {
66
+ customizedBackoff.addNext(createDuration(duration));
67
+ }
68
+ return new RetryPolicyPB()
69
+ .setMaxAttempts(this.#maxAttempts)
70
+ .setCustomizedBackoff(customizedBackoff);
71
+ }
72
+
73
+ /**
74
+ * Convert the protobuf CustomizedBackoff durations (seconds + nanos) to
75
+ * milliseconds without losing sub-second precision.
76
+ */
77
+ static durationsToMillis(customizedBackoff: CustomizedBackoff): number[] {
78
+ return customizedBackoff.getNextList().map((duration: Duration) =>
79
+ duration.getSeconds() * 1000 + duration.getNanos() / 1e6);
80
+ }
81
+ }
@@ -16,16 +16,16 @@
16
16
  */
17
17
 
18
18
  import assert from 'node:assert';
19
- import { Duration } from 'google-protobuf/google/protobuf/duration_pb';
20
19
  import {
21
20
  RetryPolicy as RetryPolicyPB,
22
21
  ExponentialBackoff,
23
22
  } from '../../proto/apache/rocketmq/v2/definition_pb';
23
+ import { createDuration } from '../util';
24
24
  import { RetryPolicy } from './RetryPolicy';
25
25
 
26
26
  export class ExponentialBackoffRetryPolicy implements RetryPolicy {
27
27
  #maxAttempts: number;
28
- // seconds
28
+ // milliseconds
29
29
  #initialBackoff: number;
30
30
  #maxBackoff: number;
31
31
  #backoffMultiplier: number;
@@ -58,9 +58,14 @@ export class ExponentialBackoffRetryPolicy implements RetryPolicy {
58
58
  assert(retryPolicy.getStrategyCase() === RetryPolicyPB.StrategyCase.EXPONENTIAL_BACKOFF,
59
59
  'strategy must be exponential backoff');
60
60
  const backoff = retryPolicy.getExponentialBackoff()!.toObject();
61
+ // Convert protobuf Duration (seconds + nanos) to milliseconds without
62
+ // losing sub-second precision (e.g. an initial backoff of 0.5s used to
63
+ // be truncated to plain 0, causing immediate retries).
64
+ const toMillis = (duration?: { seconds?: number; nanos?: number }) =>
65
+ (duration ? (duration.seconds ?? 0) * 1000 + (duration.nanos ?? 0) / 1e6 : 0);
61
66
  return new ExponentialBackoffRetryPolicy(this.#maxAttempts,
62
- backoff.initial?.seconds,
63
- backoff.max?.seconds,
67
+ toMillis(backoff.initial),
68
+ toMillis(backoff.max),
64
69
  backoff.multiplier);
65
70
  }
66
71
 
@@ -69,8 +74,8 @@ export class ExponentialBackoffRetryPolicy implements RetryPolicy {
69
74
  .setMaxAttempts(this.#maxAttempts)
70
75
  .setExponentialBackoff(
71
76
  new ExponentialBackoff()
72
- .setInitial(new Duration().setSeconds(this.#initialBackoff))
73
- .setMax(new Duration().setSeconds(this.#maxBackoff))
77
+ .setInitial(createDuration(this.#initialBackoff))
78
+ .setMax(createDuration(this.#maxBackoff))
74
79
  .setMultiplier(this.#backoffMultiplier));
75
80
  }
76
81
  }
@@ -32,7 +32,7 @@ export interface RetryPolicy {
32
32
  * Get await time after current attempts, the attempt index starts at 1.
33
33
  *
34
34
  * @param attempt current attempt.
35
- * @return await time in seconds.
35
+ * @return await time in milliseconds.
36
36
  */
37
37
  getNextAttemptDelay(attempt: number): number;
38
38