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,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
 
@@ -15,5 +15,6 @@
15
15
  * limitations under the License.
16
16
  */
17
17
 
18
+ export * from './CustomizedBackoffRetryPolicy';
18
19
  export * from './ExponentialBackoffRetryPolicy';
19
20
  export * from './RetryPolicy';
@@ -18,6 +18,9 @@
18
18
  import { isIPv4, isIPv6 } from 'node:net';
19
19
  import { hashCodeOfString } from '../util';
20
20
  import { Address, AddressScheme, Endpoints as EndpointsPB } from '../../proto/apache/rocketmq/v2/definition_pb';
21
+ // Side-effect import: registers the custom `ip` name resolver (shuffle + multi-address
22
+ // load balancing), mirroring the Java client's IpNameResolverFactory.
23
+ import './IpNameResolver';
21
24
 
22
25
  const DEFAULT_PORT = 80;
23
26
 
@@ -35,15 +38,49 @@ export class Endpoints {
35
38
  const splits = endpoints.split(';');
36
39
  this.addressesList = [];
37
40
  for (const endpoint of splits) {
38
- const [ host, port ] = endpoint.split(':');
39
- if (isIPv4(host)) {
40
- this.scheme = AddressScheme.IPV4;
41
- } else if (isIPv6(host)) {
42
- this.scheme = AddressScheme.IPV6;
41
+ // Strip the optional http:// or https:// prefix, mirroring the Java client.
42
+ const candidate = endpoint.trim().replace(/^https?:\/\//, '');
43
+ let host: string;
44
+ let port: number;
45
+ if (candidate.startsWith('[')) {
46
+ // Bracketed IPv6 address, e.g. [::1]:10911 or [fe80::1]
47
+ const match = candidate.match(/^\[([^\]]+)\](?::(\d+))?$/);
48
+ if (!match) {
49
+ throw new TypeError(`Invalid IPv6 endpoint: ${endpoint}`);
50
+ }
51
+ host = match[1];
52
+ if (!isIPv6(host)) throw new TypeError(`Invalid IPv6 endpoint: ${endpoint}`);
53
+ port = match[2] ? Number(match[2]) : DEFAULT_PORT;
54
+ } else if (isIPv6(candidate)) {
55
+ // Bare IPv6 address without brackets, e.g. ::1
56
+ host = candidate;
57
+ port = DEFAULT_PORT;
43
58
  } else {
44
- this.scheme = AddressScheme.DOMAIN_NAME;
59
+ // IPv4 address or domain name, e.g. 127.0.0.1:10911, example.com:80
60
+ const index = candidate.lastIndexOf(':');
61
+ if (index > 0) {
62
+ host = candidate.substring(0, index);
63
+ const portText = candidate.substring(index + 1);
64
+ if (!/^\d+$/.test(portText)) throw new TypeError(`Invalid endpoint port: ${endpoint}`);
65
+ port = Number(portText);
66
+ } else {
67
+ host = candidate;
68
+ port = DEFAULT_PORT;
69
+ }
45
70
  }
46
- this.addressesList.push({ host, port: parseInt(port) || DEFAULT_PORT });
71
+ if (!host || (host.includes(':') && !isIPv6(host))) {
72
+ throw new TypeError(`Invalid endpoint host: ${endpoint}`);
73
+ }
74
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
75
+ throw new TypeError(`Invalid endpoint port: ${endpoint}`);
76
+ }
77
+ const scheme = isIPv4(host) ? AddressScheme.IPV4
78
+ : isIPv6(host) ? AddressScheme.IPV6 : AddressScheme.DOMAIN_NAME;
79
+ if (this.addressesList.length > 0 && this.scheme !== scheme) {
80
+ throw new TypeError('Mixed address schemes are not supported');
81
+ }
82
+ this.scheme = scheme;
83
+ this.addressesList.push({ host, port });
47
84
  }
48
85
  } else {
49
86
  this.scheme = endpoints.scheme;
@@ -52,8 +89,28 @@ export class Endpoints {
52
89
  this.facade = this.addressesList.map(addr => `${addr.host}:${addr.port}`).join(',');
53
90
  }
54
91
 
92
+ /**
93
+ * gRPC target with resolver scheme prefix:
94
+ * - IP addresses: ip:127.0.0.1:10911,127.0.0.2:10912 (custom resolver, IPv6 hosts bracketed)
95
+ * - Domain names: dns:example.com:8080,example.org:8081
96
+ */
55
97
  getGrpcTarget() {
56
- return this.facade;
98
+ const targets = this.addressesList.map(addr => {
99
+ const host = this.scheme === AddressScheme.IPV6 ? `[${addr.host}]` : addr.host;
100
+ return `${host}:${addr.port}`;
101
+ }).join(',');
102
+ switch (this.scheme) {
103
+ case AddressScheme.IPV4:
104
+ case AddressScheme.IPV6:
105
+ // Route IP addresses through the custom `ip` resolver registered in
106
+ // IpNameResolver, which shuffles the address list for multi-proxy load
107
+ // balancing (equivalent to Java's IpNameResolverFactory).
108
+ return `ip:${targets}`;
109
+ case AddressScheme.DOMAIN_NAME:
110
+ return `dns:${targets}`;
111
+ default:
112
+ return targets;
113
+ }
57
114
  }
58
115
 
59
116
  toString() {
@@ -0,0 +1,119 @@
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 { experimental, Metadata, status as Status, ChannelOptions } from '@grpc/grpc-js';
19
+
20
+ /**
21
+ * Custom gRPC name resolver registered under the `ip` scheme, mirroring the Java
22
+ * client's `IpNameResolverFactory`.
23
+ *
24
+ * The Java resolver converts each socket address into its own
25
+ * `EquivalentAddressGroup` and then {@code Collections.shuffle}s the list, so the
26
+ * gRPC load balancer starts from a random address instead of always the first
27
+ * one. RocketMQ proxies are typically deployed as multiple endpoints behind one
28
+ * `Endpoints`, and shuffling spreads clients across them.
29
+ *
30
+ * grpc-js models an `EquivalentAddressGroup` as a single `Endpoint` carrying one
31
+ * or more equivalent `SubchannelAddress`es, so we emit one `Endpoint` per address
32
+ * and shuffle the array — exactly the Java semantics.
33
+ */
34
+ const DEFAULT_PORT = 80;
35
+
36
+ /**
37
+ * Fisher–Yates shuffle (pure, does not mutate the input array).
38
+ */
39
+ function shuffle<T>(input: readonly T[]): T[] {
40
+ const arr = input.slice();
41
+ for (let i = arr.length - 1; i > 0; i--) {
42
+ const j = Math.floor(Math.random() * (i + 1));
43
+ const tmp = arr[i];
44
+ arr[i] = arr[j];
45
+ arr[j] = tmp;
46
+ }
47
+ return arr;
48
+ }
49
+
50
+ class IpResolver {
51
+ private readonly listener: experimental.ResolverListener;
52
+ private endpoints: experimental.Endpoint[] = [];
53
+ private error: { code: Status; details: string; metadata: Metadata } | null = null;
54
+ private hasReturnedResult = false;
55
+
56
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
57
+ constructor(target: experimental.GrpcUri, listener: experimental.ResolverListener, _channelOptions: ChannelOptions) {
58
+ this.listener = listener;
59
+ const pathList = (target.path || '').split(',').map(s => s.trim()).filter(Boolean);
60
+ const addresses: experimental.SubchannelAddress[] = [];
61
+ for (const path of pathList) {
62
+ const hostPort = experimental.splitHostPort(path);
63
+ if (!hostPort) {
64
+ this.error = {
65
+ code: Status.UNAVAILABLE,
66
+ details: `Failed to parse ip address: ${path}`,
67
+ metadata: new Metadata(),
68
+ };
69
+ return;
70
+ }
71
+ addresses.push({
72
+ host: hostPort.host,
73
+ port: hostPort.port ?? DEFAULT_PORT,
74
+ });
75
+ }
76
+ this.endpoints = shuffle(addresses).map(address => ({ addresses: [ address ] }));
77
+ }
78
+
79
+ updateResolution(): void {
80
+ if (this.hasReturnedResult) {
81
+ return;
82
+ }
83
+ this.hasReturnedResult = true;
84
+ // Defer the callback to the next tick, mirroring the built-in ip resolver so
85
+ // listeners are never invoked synchronously from the constructor path.
86
+ process.nextTick(() => {
87
+ if (this.error) {
88
+ this.listener(
89
+ experimental.statusOrFromError(this.error),
90
+ {},
91
+ null,
92
+ '',
93
+ );
94
+ } else {
95
+ this.listener(
96
+ experimental.statusOrFromValue(this.endpoints),
97
+ {},
98
+ null,
99
+ '',
100
+ );
101
+ }
102
+ });
103
+ }
104
+
105
+ destroy(): void {
106
+ this.hasReturnedResult = false;
107
+ }
108
+
109
+ // eslint-disable-next-line @typescript-eslint/naming-convention
110
+ static getDefaultAuthority(target: experimental.GrpcUri): string {
111
+ return (target.path || '').split(',')[0] || 'localhost';
112
+ }
113
+ }
114
+
115
+ // Register the resolver so that gRPC targets prefixed with `ip:` are handled by
116
+ // this class. Registration is idempotent at module-load time.
117
+ experimental.registerResolver('ip', IpResolver);
118
+
119
+ export { IpResolver };
@@ -40,7 +40,7 @@ export class MessageQueue {
40
40
  toProtobuf() {
41
41
  const messageQueue = new MessageQueuePB();
42
42
  messageQueue.setId(this.queueId);
43
- messageQueue.setTopic(createResource(this.topic.name));
43
+ messageQueue.setTopic(createResource(this.topic.name).setResourceNamespace(this.topic.resourceNamespace));
44
44
  messageQueue.setBroker(this.broker.toProtobuf());
45
45
  messageQueue.setPermission(this.permission);
46
46
  messageQueue.setAcceptMessageTypesList(this.acceptMessageTypesList);
@@ -52,6 +52,7 @@ export class MessageQueue {
52
52
  if (!other) return false;
53
53
  return this.queueId === other.queueId &&
54
54
  this.topic.name === other.topic.name &&
55
+ this.topic.resourceNamespace === other.topic.resourceNamespace &&
55
56
  this.broker.equals(other.broker) &&
56
57
  this.permission === other.permission;
57
58
  }
@@ -62,6 +63,10 @@ export class MessageQueue {
62
63
  hash = (hash * 31 + this.queueId) | 0;
63
64
  // eslint-disable-next-line no-bitwise
64
65
  hash = (hash * 31 + hashCodeOfString(this.topic.name)) | 0;
66
+ if (this.topic.resourceNamespace) {
67
+ // eslint-disable-next-line no-bitwise
68
+ hash = (hash * 31 + hashCodeOfString(this.topic.resourceNamespace)) | 0;
69
+ }
65
70
  // eslint-disable-next-line no-bitwise
66
71
  hash = (hash * 31 + this.broker.hashCode()) | 0;
67
72
  // eslint-disable-next-line no-bitwise
@@ -15,12 +15,17 @@
15
15
  * limitations under the License.
16
16
  */
17
17
 
18
- import { MessageQueue as MessageQueuePB } from '../../proto/apache/rocketmq/v2/definition_pb';
18
+ import { randomInt } from 'node:crypto';
19
+ import { Code, MessageQueue as MessageQueuePB, Permission } from '../../proto/apache/rocketmq/v2/definition_pb';
20
+ import { NotFoundException } from '../exception/NotFoundException';
21
+ import { MASTER_BROKER_ID } from '../util';
19
22
  import { Endpoints } from './Endpoints';
20
23
  import { MessageQueue } from './MessageQueue';
21
24
 
22
25
  export class TopicRouteData {
23
26
  readonly messageQueues: MessageQueue[] = [];
27
+ // Randomize the round-robin starting point to spread initial assignment queries across clients.
28
+ #index = randomInt(0, 2 ** 31 - 1);
24
29
 
25
30
  constructor(messageQueues: MessageQueuePB[]) {
26
31
  for (const mq of messageQueues) {
@@ -36,6 +41,22 @@ export class TopicRouteData {
36
41
  return Array.from(endpointsMap.values());
37
42
  }
38
43
 
44
+ /**
45
+ * Rotate across master endpoints with non-NONE permissions, matching Java's selection rules.
46
+ */
47
+ pickEndpointsToQueryAssignments(): Endpoints {
48
+ const size = this.messageQueues.length;
49
+ for (let i = 0; i < size; i++) {
50
+ const mq = this.messageQueues[this.#index % size];
51
+ this.#index = (this.#index + 1) % size;
52
+ if (mq.broker.id !== MASTER_BROKER_ID || mq.permission === Permission.NONE) {
53
+ continue;
54
+ }
55
+ return mq.broker.endpoints;
56
+ }
57
+ throw new NotFoundException(Code.NOT_FOUND, 'Failed to pick endpoints to query assignment');
58
+ }
59
+
39
60
  /**
40
61
  * Get the count of message queues.
41
62
  * @return number of message queues
@@ -0,0 +1,82 @@
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
+ * A counting semaphore used to throttle the number of messages that can be
20
+ * in-flight (fetched but not yet settled) on a single {@link ProcessQueue}.
21
+ *
22
+ * This mirrors the permit model of the Java client's
23
+ * {@code ProcessQueueImpl#acquirePermit()}/{@code releasePermit()}, where the
24
+ * permit count is bounded by {@code consumeConcurrentlyMax} and exhaustion
25
+ * applies backpressure by stopping further message fetches until permits are
26
+ * released (i.e. messages are acked / nacked).
27
+ */
28
+ export class Semaphore {
29
+ #permits: number;
30
+ readonly #waiters: Array<() => void> = [];
31
+
32
+ constructor(permits: number) {
33
+ if (!Number.isInteger(permits) || permits < 0) {
34
+ throw new RangeError(`permits must be a non-negative integer, got ${permits}`);
35
+ }
36
+ this.#permits = permits;
37
+ }
38
+
39
+ /** Current number of available permits. */
40
+ get availablePermits(): number {
41
+ return this.#permits;
42
+ }
43
+
44
+ /**
45
+ * Non-blocking acquisition: takes one permit if available and returns true,
46
+ * otherwise leaves the semaphore unchanged and returns false.
47
+ */
48
+ tryAcquire(): boolean {
49
+ if (this.#permits > 0) {
50
+ this.#permits--;
51
+ return true;
52
+ }
53
+ return false;
54
+ }
55
+
56
+ /**
57
+ * Acquire a single permit. Resolves immediately when one is available;
58
+ * otherwise queues the caller until a permit is released.
59
+ */
60
+ acquire(): Promise<void> {
61
+ if (this.#permits > 0) {
62
+ this.#permits--;
63
+ return Promise.resolve();
64
+ }
65
+ return new Promise<void>(resolve => {
66
+ this.#waiters.push(resolve);
67
+ });
68
+ }
69
+
70
+ /**
71
+ * Release a single permit. Hands it to a pending acquirer if any, otherwise
72
+ * increments the available count.
73
+ */
74
+ release(): void {
75
+ const waiter = this.#waiters.shift();
76
+ if (waiter) {
77
+ waiter();
78
+ } else {
79
+ this.#permits++;
80
+ }
81
+ }
82
+ }
package/src/util/index.ts CHANGED
@@ -45,17 +45,20 @@ export function sign(accessSecret: string, dateTime: string) {
45
45
  }
46
46
 
47
47
  export function createDuration(ms: number) {
48
+ if (!Number.isFinite(ms) || Math.abs(ms) > 315576000000000) {
49
+ throw new RangeError('duration must be finite and within the protobuf Duration range');
50
+ }
48
51
  // Duration.seconds is a protobuf int64 field, so it must be an integer;
49
52
  // the remainder is carried by nanos. Non-integer seconds would fail
50
53
  // serialization with 'Assertion failed'.
51
- const nanos = Math.floor(ms % 1000 * 1000000);
54
+ const nanos = Math.sign(ms) * Math.floor(Math.abs(ms % 1000) * 1000000);
52
55
  return new Duration()
53
- .setSeconds(Math.floor(ms / 1000))
54
- .setNanos(nanos);
56
+ .setSeconds(Math.trunc(ms / 1000) || 0)
57
+ .setNanos(nanos || 0);
55
58
  }
56
59
 
57
- export function createResource(name: string) {
58
- return new Resource().setName(name);
60
+ export function createResource(name: string, namespace = '') {
61
+ return new Resource().setResourceNamespace(namespace).setName(name);
59
62
  }
60
63
 
61
64
  export function crc32CheckSum(bytes: Buffer) {
@@ -0,0 +1,34 @@
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 type { Metadata } from '@grpc/grpc-js';
19
+
20
+ // Associate request IDs with response objects to avoid mixing concurrent RPCs without changing protobufs or public return types.
21
+ const requestIds = new WeakMap<object, string>();
22
+
23
+ export function setRequestId<T extends object>(response: T, requestId?: string): T {
24
+ if (requestId !== undefined) requestIds.set(response, requestId);
25
+ return response;
26
+ }
27
+
28
+ export function withRequestId<T extends object>(response: T, metadata: Metadata): T {
29
+ return setRequestId(response, metadata.get('x-mq-request-id')[0]?.toString());
30
+ }
31
+
32
+ export function getRequestId(response?: object): string | undefined {
33
+ return response ? requestIds.get(response) : undefined;
34
+ }