rocketmq-client-nodejs 0.0.0 → 1.0.0-beta.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 (165) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +69 -1
  3. package/dist/client/BaseClient.d.ts +92 -0
  4. package/dist/client/BaseClient.js +306 -0
  5. package/dist/client/ClientId.d.ts +24 -0
  6. package/dist/client/ClientId.js +33 -0
  7. package/dist/client/Logger.d.ts +24 -0
  8. package/dist/client/Logger.js +34 -0
  9. package/dist/client/RpcClient.d.ts +47 -0
  10. package/dist/client/RpcClient.js +208 -0
  11. package/dist/client/RpcClientManager.d.ts +41 -0
  12. package/dist/client/RpcClientManager.js +139 -0
  13. package/dist/client/SessionCredentials.d.ts +21 -0
  14. package/dist/client/SessionCredentials.js +19 -0
  15. package/dist/client/Settings.d.ts +30 -0
  16. package/dist/client/Settings.js +38 -0
  17. package/dist/client/TelemetrySession.d.ts +27 -0
  18. package/dist/client/TelemetrySession.js +101 -0
  19. package/dist/client/UserAgent.d.ts +25 -0
  20. package/dist/client/UserAgent.js +47 -0
  21. package/dist/client/index.d.ts +26 -0
  22. package/dist/client/index.js +43 -0
  23. package/dist/consumer/Consumer.d.ts +32 -0
  24. package/dist/consumer/Consumer.js +96 -0
  25. package/dist/consumer/FilterExpression.d.ts +25 -0
  26. package/dist/consumer/FilterExpression.js +40 -0
  27. package/dist/consumer/SimpleConsumer.d.ts +47 -8
  28. package/dist/consumer/SimpleConsumer.js +105 -27
  29. package/dist/consumer/SimpleSubscriptionSettings.d.ts +28 -0
  30. package/dist/consumer/SimpleSubscriptionSettings.js +57 -0
  31. package/dist/consumer/SubscriptionLoadBalancer.d.ts +23 -0
  32. package/dist/consumer/SubscriptionLoadBalancer.js +46 -0
  33. package/dist/consumer/index.d.ts +21 -0
  34. package/dist/consumer/index.js +38 -0
  35. package/dist/exception/BadRequestException.d.ts +20 -0
  36. package/dist/exception/BadRequestException.js +28 -0
  37. package/dist/exception/ClientException.d.ts +20 -0
  38. package/dist/exception/ClientException.js +31 -0
  39. package/dist/exception/ForbiddenException.d.ts +20 -0
  40. package/dist/exception/ForbiddenException.js +28 -0
  41. package/dist/exception/InternalErrorException.d.ts +20 -0
  42. package/dist/exception/InternalErrorException.js +28 -0
  43. package/dist/exception/NotFoundException.d.ts +20 -0
  44. package/dist/exception/NotFoundException.js +28 -0
  45. package/dist/exception/PayloadTooLargeException.d.ts +20 -0
  46. package/dist/exception/PayloadTooLargeException.js +28 -0
  47. package/dist/exception/PaymentRequiredException.d.ts +20 -0
  48. package/dist/exception/PaymentRequiredException.js +28 -0
  49. package/dist/exception/ProxyTimeoutException.d.ts +20 -0
  50. package/dist/exception/ProxyTimeoutException.js +28 -0
  51. package/dist/exception/RequestHeaderFieldsTooLargeException.d.ts +20 -0
  52. package/dist/exception/RequestHeaderFieldsTooLargeException.js +28 -0
  53. package/dist/exception/StatusChecker.d.ts +20 -0
  54. package/dist/exception/StatusChecker.js +98 -0
  55. package/dist/exception/TooManyRequestsException.d.ts +20 -0
  56. package/dist/exception/TooManyRequestsException.js +28 -0
  57. package/dist/exception/UnauthorizedException.d.ts +20 -0
  58. package/dist/exception/UnauthorizedException.js +28 -0
  59. package/dist/exception/UnsupportedException.d.ts +20 -0
  60. package/dist/exception/UnsupportedException.js +28 -0
  61. package/dist/exception/index.d.ts +29 -0
  62. package/dist/exception/index.js +46 -0
  63. package/dist/index.d.ts +22 -3
  64. package/dist/index.js +23 -4
  65. package/dist/message/Message.d.ts +37 -0
  66. package/dist/message/Message.js +43 -0
  67. package/dist/message/MessageId.d.ts +59 -0
  68. package/dist/message/MessageId.js +123 -0
  69. package/dist/message/MessageView.d.ts +39 -0
  70. package/dist/message/MessageView.js +90 -0
  71. package/dist/message/PublishingMessage.d.ts +30 -0
  72. package/dist/message/PublishingMessage.js +98 -0
  73. package/dist/message/index.d.ts +20 -0
  74. package/dist/message/index.js +37 -0
  75. package/dist/producer/Producer.d.ts +42 -0
  76. package/dist/producer/Producer.js +240 -1
  77. package/dist/producer/PublishingLoadBalancer.d.ts +24 -0
  78. package/dist/producer/PublishingLoadBalancer.js +82 -0
  79. package/dist/producer/PublishingSettings.d.ts +28 -0
  80. package/dist/producer/PublishingSettings.js +68 -0
  81. package/dist/producer/SendReceipt.d.ts +28 -0
  82. package/dist/producer/SendReceipt.js +57 -0
  83. package/dist/producer/Transaction.d.ts +28 -0
  84. package/dist/producer/Transaction.js +64 -0
  85. package/dist/producer/TransactionChecker.d.ts +21 -0
  86. package/dist/producer/TransactionChecker.js +19 -0
  87. package/dist/producer/index.d.ts +21 -0
  88. package/dist/producer/index.js +39 -0
  89. package/dist/retry/ExponentialBackoffRetryPolicy.d.ts +27 -0
  90. package/dist/retry/ExponentialBackoffRetryPolicy.js +67 -0
  91. package/dist/retry/RetryPolicy.d.ts +46 -0
  92. package/dist/retry/RetryPolicy.js +19 -0
  93. package/dist/retry/index.d.ts +18 -0
  94. package/dist/retry/index.js +35 -0
  95. package/dist/route/Broker.d.ts +25 -0
  96. package/dist/route/Broker.js +40 -0
  97. package/dist/route/Endpoints.d.ts +30 -0
  98. package/dist/route/Endpoints.js +71 -0
  99. package/dist/route/MessageQueue.d.ts +27 -0
  100. package/dist/route/MessageQueue.js +47 -0
  101. package/dist/route/TopicRouteData.d.ts +24 -0
  102. package/dist/route/TopicRouteData.js +37 -0
  103. package/dist/route/index.d.ts +20 -0
  104. package/dist/route/index.js +37 -0
  105. package/dist/util/index.d.ts +36 -0
  106. package/dist/util/index.js +88 -0
  107. package/package.json +12 -5
  108. package/src/client/BaseClient.ts +382 -0
  109. package/src/client/ClientId.ts +31 -0
  110. package/src/client/Logger.ts +35 -0
  111. package/src/client/RpcClient.ts +245 -0
  112. package/src/client/RpcClientManager.ts +173 -0
  113. package/src/client/SessionCredentials.ts +22 -0
  114. package/src/client/Settings.ts +45 -0
  115. package/src/client/TelemetrySession.ts +118 -0
  116. package/src/client/UserAgent.ts +45 -0
  117. package/src/client/index.ts +27 -0
  118. package/src/consumer/Consumer.ts +111 -0
  119. package/src/consumer/FilterExpression.ts +42 -0
  120. package/src/consumer/SimpleConsumer.ts +133 -20
  121. package/src/consumer/SimpleSubscriptionSettings.ts +65 -0
  122. package/src/consumer/SubscriptionLoadBalancer.ts +47 -0
  123. package/src/consumer/index.ts +22 -0
  124. package/src/exception/BadRequestException.ts +25 -0
  125. package/src/exception/ClientException.ts +29 -0
  126. package/src/exception/ForbiddenException.ts +25 -0
  127. package/src/exception/InternalErrorException.ts +25 -0
  128. package/src/exception/NotFoundException.ts +25 -0
  129. package/src/exception/PayloadTooLargeException.ts +25 -0
  130. package/src/exception/PaymentRequiredException.ts +25 -0
  131. package/src/exception/ProxyTimeoutException.ts +25 -0
  132. package/src/exception/RequestHeaderFieldsTooLargeException.ts +25 -0
  133. package/src/exception/StatusChecker.ts +94 -0
  134. package/src/exception/TooManyRequestsException.ts +25 -0
  135. package/src/exception/UnauthorizedException.ts +25 -0
  136. package/src/exception/UnsupportedException.ts +25 -0
  137. package/src/exception/index.ts +30 -0
  138. package/src/index.ts +23 -3
  139. package/src/message/Message.ts +51 -0
  140. package/src/message/MessageId.ts +123 -0
  141. package/src/message/MessageView.ts +94 -0
  142. package/src/message/PublishingMessage.ts +102 -0
  143. package/src/message/index.ts +21 -0
  144. package/src/producer/Producer.ts +289 -0
  145. package/src/producer/PublishingLoadBalancer.ts +85 -0
  146. package/src/producer/PublishingSettings.ts +77 -0
  147. package/src/producer/SendReceipt.ts +60 -0
  148. package/src/producer/Transaction.ts +70 -0
  149. package/src/producer/TransactionChecker.ts +23 -0
  150. package/src/producer/index.ts +23 -0
  151. package/src/retry/ExponentialBackoffRetryPolicy.ts +76 -0
  152. package/src/retry/RetryPolicy.ts +51 -0
  153. package/src/retry/index.ts +19 -0
  154. package/src/route/Broker.ts +39 -0
  155. package/src/route/Endpoints.ts +70 -0
  156. package/src/route/MessageQueue.ts +49 -0
  157. package/src/route/TopicRouteData.ts +38 -0
  158. package/src/route/index.ts +21 -0
  159. package/src/util/index.ts +83 -0
  160. package/dist/grpc/MessagingServiceClient.d.ts +0 -9
  161. package/dist/grpc/MessagingServiceClient.js +0 -13
  162. package/dist/model/SessionCredentials.d.ts +0 -5
  163. package/dist/model/SessionCredentials.js +0 -3
  164. package/src/grpc/MessagingServiceClient.ts +0 -17
  165. package/src/model/SessionCredentials.ts +0 -5
@@ -0,0 +1,102 @@
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 { Timestamp } from 'google-protobuf/google/protobuf/timestamp_pb';
19
+ import {
20
+ MessageType, Message as MessagePB, SystemProperties, Encoding,
21
+ } from '../../proto/apache/rocketmq/v2/definition_pb';
22
+ import { PublishingSettings } from '../producer';
23
+ import { createResource } from '../util';
24
+ import { MessageQueue } from '../route';
25
+ import { UserAgent } from '../client';
26
+ import { Message, MessageOptions } from './Message';
27
+ import { MessageIdFactory } from './MessageId';
28
+
29
+ export class PublishingMessage extends Message {
30
+ readonly messageId: string;
31
+ readonly messageType: MessageType;
32
+
33
+ constructor(options: MessageOptions, publishingSettings: PublishingSettings, txEnabled: boolean) {
34
+ super(options);
35
+ const length = this.body.length;
36
+ const maxBodySizeBytes = publishingSettings.maxBodySizeBytes;
37
+ if (length > maxBodySizeBytes) {
38
+ throw new TypeError(`Message body size exceeds the threshold, max size=${maxBodySizeBytes} bytes`);
39
+ }
40
+ // Generate message id.
41
+ this.messageId = MessageIdFactory.create().toString();
42
+ // Normal message.
43
+ if (!this.messageGroup && !this.deliveryTimestamp && !txEnabled) {
44
+ this.messageType = MessageType.NORMAL;
45
+ return;
46
+ }
47
+ // Fifo message.
48
+ if (this.messageGroup && !txEnabled) {
49
+ this.messageType = MessageType.FIFO;
50
+ return;
51
+ }
52
+ // Delay message.
53
+ if (this.deliveryTimestamp && !txEnabled) {
54
+ this.messageType = MessageType.DELAY;
55
+ return;
56
+ }
57
+ // Transaction message.
58
+ if (!this.messageGroup &&
59
+ !this.deliveryTimestamp && txEnabled) {
60
+ this.messageType = MessageType.TRANSACTION;
61
+ return;
62
+ }
63
+ // Transaction semantics is conflicted with fifo/delay.
64
+ throw new TypeError('Transactional message should not set messageGroup or deliveryTimestamp');
65
+ }
66
+
67
+ /**
68
+ * This method should be invoked before each message sending, because the born time is reset before each
69
+ * invocation, which means that it should not be invoked ahead of time.
70
+ */
71
+ toProtobuf(mq: MessageQueue) {
72
+ const systemProperties = new SystemProperties()
73
+ .setKeysList(this.keys)
74
+ .setMessageId(this.messageId)
75
+ .setBornTimestamp(Timestamp.fromDate(new Date()))
76
+ .setBornHost(UserAgent.INSTANCE.hostname)
77
+ .setBodyEncoding(Encoding.IDENTITY)
78
+ .setQueueId(mq.queueId)
79
+ .setMessageType(this.messageType);
80
+ if (this.tag) {
81
+ systemProperties.setTag(this.tag);
82
+ }
83
+ if (this.deliveryTimestamp) {
84
+ systemProperties.setDeliveryTimestamp(Timestamp.fromDate(this.deliveryTimestamp));
85
+ }
86
+ if (this.messageGroup) {
87
+ systemProperties.setMessageGroup(this.messageGroup);
88
+ }
89
+
90
+ const message = new MessagePB()
91
+ .setTopic(createResource(this.topic))
92
+ .setBody(this.body)
93
+ .setSystemProperties(systemProperties);
94
+ if (this.properties) {
95
+ const userProperties = message.getUserPropertiesMap();
96
+ for (const [ key, value ] of this.properties.entries()) {
97
+ userProperties.set(key, value);
98
+ }
99
+ }
100
+ return message;
101
+ }
102
+ }
@@ -0,0 +1,21 @@
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 './Message';
19
+ export * from './MessageId';
20
+ export * from './MessageView';
21
+ export * from './PublishingMessage';
@@ -0,0 +1,289 @@
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 { setTimeout } from 'node:timers/promises';
20
+ import {
21
+ ClientType,
22
+ MessageType,
23
+ TransactionResolution,
24
+ } from '../../proto/apache/rocketmq/v2/definition_pb';
25
+ import {
26
+ EndTransactionRequest,
27
+ HeartbeatRequest,
28
+ NotifyClientTerminationRequest,
29
+ RecoverOrphanedTransactionCommand,
30
+ SendMessageRequest,
31
+ } from '../../proto/apache/rocketmq/v2/service_pb';
32
+ import {
33
+ Endpoints,
34
+ MessageQueue,
35
+ TopicRouteData,
36
+ } from '../route';
37
+ import {
38
+ ExponentialBackoffRetryPolicy,
39
+ } from '../retry';
40
+ import { StatusChecker, TooManyRequestsException } from '../exception';
41
+ import { BaseClient, BaseClientOptions, Settings } from '../client';
42
+ import { PublishingMessage, MessageOptions, MessageView, Message } from '../message';
43
+ import { PublishingSettings } from './PublishingSettings';
44
+ import { TransactionChecker } from './TransactionChecker';
45
+ import { PublishingLoadBalancer } from './PublishingLoadBalancer';
46
+ import { SendReceipt } from './SendReceipt';
47
+ import { Transaction } from './Transaction';
48
+ import { createResource } from '../util';
49
+
50
+ export interface ProducerOptions extends BaseClientOptions {
51
+ topic?: string | string[];
52
+ maxAttempts?: number;
53
+ checker?: TransactionChecker;
54
+ }
55
+
56
+ export class Producer extends BaseClient {
57
+ #publishingSettings: PublishingSettings;
58
+ #checker?: TransactionChecker;
59
+ #publishingRouteDataCache = new Map<string, PublishingLoadBalancer>();
60
+
61
+ constructor(options: ProducerOptions) {
62
+ if (!options.topics && options.topic) {
63
+ options.topics = Array.isArray(options.topic) ? options.topic : [ options.topic ];
64
+ }
65
+ super(options);
66
+ const retryPolicy = ExponentialBackoffRetryPolicy.immediatelyRetryPolicy(options.maxAttempts ?? 1);
67
+ this.#publishingSettings = new PublishingSettings(this.clientId, this.endpoints, retryPolicy,
68
+ this.requestTimeout, this.topics);
69
+ this.#checker = options.checker;
70
+ }
71
+
72
+ get publishingSettings() {
73
+ return this.#publishingSettings;
74
+ }
75
+
76
+ beginTransaction() {
77
+ assert(this.#checker, 'Transaction checker should not be null');
78
+ return new Transaction(this);
79
+ }
80
+
81
+ async endTransaction(endpoints: Endpoints, message: Message, messageId: string,
82
+ transactionId: string, resolution: TransactionResolution) {
83
+ const request = new EndTransactionRequest()
84
+ .setMessageId(messageId)
85
+ .setTransactionId(transactionId)
86
+ .setTopic(createResource(message.topic))
87
+ .setResolution(resolution);
88
+ const response = await this.rpcClientManager.endTransaction(endpoints, request, this.requestTimeout);
89
+ StatusChecker.check(response.getStatus()?.toObject());
90
+ }
91
+
92
+ async onRecoverOrphanedTransactionCommand(endpoints: Endpoints, command: RecoverOrphanedTransactionCommand) {
93
+ const transactionId = command.getTransactionId();
94
+ const messagePB = command.getMessage()!;
95
+ const messageId = messagePB.getSystemProperties()!.getMessageId();
96
+ if (!this.#checker) {
97
+ this.logger.error('No transaction checker registered, ignore it, messageId=%s, transactionId=%s, endpoints=%s, clientId=%s',
98
+ messageId, transactionId, endpoints, this.clientId);
99
+ return;
100
+ }
101
+ let messageView: MessageView;
102
+ try {
103
+ messageView = new MessageView(messagePB);
104
+ } catch (err) {
105
+ this.logger.error('[Bug] Failed to decode message during orphaned transaction message recovery, messageId=%s, transactionId=%s, endpoints=%s, clientId=%s, error=%s',
106
+ messageId, transactionId, endpoints, this.clientId, err);
107
+ return;
108
+ }
109
+
110
+ try {
111
+ const resolution = await this.#checker.check(messageView);
112
+ if (resolution === null || resolution === TransactionResolution.TRANSACTION_RESOLUTION_UNSPECIFIED) {
113
+ return;
114
+ }
115
+ await this.endTransaction(endpoints, messageView, messageId, transactionId, resolution);
116
+ this.logger.info('Recover orphaned transaction message success, transactionId=%s, resolution=%s, messageId=%s, clientId=%s',
117
+ transactionId, resolution, messageId, this.clientId);
118
+ } catch (err) {
119
+ this.logger.error('Exception raised while checking the transaction, messageId=%s, transactionId=%s, endpoints=%s, clientId=%s, error=%s',
120
+ messageId, transactionId, endpoints, this.clientId, err);
121
+ return;
122
+ }
123
+ }
124
+
125
+ protected getSettings(): Settings {
126
+ return this.#publishingSettings;
127
+ }
128
+
129
+ protected wrapHeartbeatRequest(): HeartbeatRequest {
130
+ return new HeartbeatRequest()
131
+ .setClientType(ClientType.PRODUCER);
132
+ }
133
+
134
+ protected wrapNotifyClientTerminationRequest(): NotifyClientTerminationRequest {
135
+ return new NotifyClientTerminationRequest();
136
+ }
137
+
138
+ async send(message: MessageOptions, transaction?: Transaction) {
139
+ if (!transaction) {
140
+ const sendReceipts = await this.#send([ message ], false);
141
+ return sendReceipts[0];
142
+ }
143
+
144
+ const publishingMessage = transaction.tryAddMessage(message);
145
+ const sendReceipts = await this.#send([ message ], true);
146
+ const sendReceipt = sendReceipts[0];
147
+ transaction.tryAddReceipt(publishingMessage, sendReceipt);
148
+ return sendReceipt;
149
+ }
150
+
151
+ async #send(messages: MessageOptions[], txEnabled: boolean) {
152
+ const pubMessages: PublishingMessage[] = [];
153
+ const topics = new Set<string>();
154
+ for (const message of messages) {
155
+ pubMessages.push(new PublishingMessage(message, this.#publishingSettings, txEnabled));
156
+ topics.add(message.topic);
157
+ }
158
+ if (topics.size > 1) {
159
+ throw new TypeError(`Messages to send have different topics=${JSON.stringify(topics)}`);
160
+ }
161
+ const topic = pubMessages[0].topic;
162
+ const messageType = pubMessages[0].messageType;
163
+ const messageGroup = pubMessages[0].messageGroup;
164
+ const messageTypes = new Set(pubMessages.map(m => m.messageType));
165
+ if (messageTypes.size > 1) {
166
+ throw new TypeError(`Messages to send have different types=${JSON.stringify(messageTypes)}`);
167
+ }
168
+
169
+ // Message group must be same if message type is FIFO, or no need to proceed.
170
+ if (messageType === MessageType.FIFO) {
171
+ const messageGroups = new Set(pubMessages.map(m => m.messageGroup!));
172
+ if (messageGroups.size > 1) {
173
+ throw new TypeError(`FIFO messages to send have message groups, messageGroups=${JSON.stringify(messageGroups)}`);
174
+ }
175
+ }
176
+
177
+ // Get publishing topic route.
178
+ const loadBalancer = await this.#getPublishingLoadBalancer(topic);
179
+ // Prepare the candidate message queue(s) for retry-sending in advance.
180
+ const candidates = messageGroup ? [ loadBalancer.takeMessageQueueByMessageGroup(messageGroup) ] :
181
+ this.#takeMessageQueues(loadBalancer);
182
+ return await this.#send0(topic, messageType, candidates, pubMessages, 1);
183
+ }
184
+
185
+ #wrapSendMessageRequest(pubMessages: PublishingMessage[], mq: MessageQueue) {
186
+ const request = new SendMessageRequest();
187
+ for (const pubMessage of pubMessages) {
188
+ request.addMessages(pubMessage.toProtobuf(mq));
189
+ }
190
+ return request;
191
+ }
192
+
193
+ /**
194
+ * Isolate specified Endpoints
195
+ */
196
+ #isolate(endpoints: Endpoints) {
197
+ this.isolated.set(endpoints.facade, endpoints);
198
+ }
199
+
200
+ async #send0(topic: string, messageType: MessageType, candidates: MessageQueue[],
201
+ messages: PublishingMessage[], attempt: number): Promise<SendReceipt[]> {
202
+ // Calculate the current message queue.
203
+ const index = (attempt - 1) % candidates.length;
204
+ const mq = candidates[index];
205
+ const acceptMessageTypes = mq.acceptMessageTypesList;
206
+ if (this.#publishingSettings.isValidateMessageType() && !acceptMessageTypes.includes(messageType)) {
207
+ throw new TypeError('Current message type not match with ' +
208
+ 'topic accept message types, topic=' + topic + ', actualMessageType=' + messageType + ', ' +
209
+ 'acceptMessageTypes=' + JSON.stringify(acceptMessageTypes));
210
+ }
211
+ const endpoints = mq.broker.endpoints;
212
+ const maxAttempts = this.#getRetryPolicy().getMaxAttempts();
213
+ const request = this.#wrapSendMessageRequest(messages, mq);
214
+ let sendReceipts: SendReceipt[] = [];
215
+ try {
216
+ const response = await this.rpcClientManager.sendMessage(endpoints, request, this.requestTimeout);
217
+ sendReceipts = SendReceipt.processResponseInvocation(mq, response);
218
+ } catch (err) {
219
+ const messageIds = messages.map(m => m.messageId);
220
+ // Isolate endpoints because of sending failure.
221
+ this.#isolate(endpoints);
222
+ if (attempt >= maxAttempts) {
223
+ // No need more attempts.
224
+ this.logger.error('Failed to send message(s) finally, run out of attempt times, maxAttempts=%s, attempt=%s, topic=%s, messageId(s)=%s, endpoints=%s, clientId=%s, error=%s',
225
+ maxAttempts, attempt, topic, messageIds, endpoints, this.clientId, err);
226
+ throw err;
227
+ }
228
+ // No need more attempts for transactional message.
229
+ if (messageType === MessageType.TRANSACTION) {
230
+ this.logger.error('Failed to send transactional message finally, maxAttempts=%s, attempt=%s, topic=%s, messageId(s)=%s, endpoints=%s, clientId=%s, error=%s',
231
+ maxAttempts, attempt, topic, messageIds, endpoints, this.clientId, err);
232
+ throw err;
233
+ }
234
+ // Try to do more attempts.
235
+ const nextAttempt = 1 + attempt;
236
+ // Retry immediately if the request is not throttled.
237
+ if (!(err instanceof TooManyRequestsException)) {
238
+ this.logger.warn('Failed to send message, would attempt to resend right now, maxAttempts=%s, attempt=%s, topic=%s, messageId(s)=%s, endpoints=%s, clientId=%s, error=%s',
239
+ maxAttempts, attempt, topic, messageIds, endpoints, this.clientId, err);
240
+ return this.#send0(topic, messageType, candidates, messages, nextAttempt);
241
+ }
242
+ const delay = this.#getRetryPolicy().getNextAttemptDelay(nextAttempt);
243
+ this.logger.warn('Failed to send message due to too many requests, would attempt to resend after %sms, maxAttempts=%s, attempt=%s, topic=%s, messageId(s)=%s, endpoints=%s, clientId=%s, error=%s',
244
+ delay, maxAttempts, attempt, topic, messageIds, endpoints, this.clientId, err);
245
+ await setTimeout(delay);
246
+ return this.#send0(topic, messageType, candidates, messages, nextAttempt);
247
+ }
248
+
249
+ // Resend message(s) successfully.
250
+ if (attempt > 1) {
251
+ const messageIds = sendReceipts.map(r => r.messageId);
252
+ this.logger.info('Resend message successfully, topic=%s, messageId(s)=%j, maxAttempts=%s, attempt=%s, endpoints=%s, clientId=%s',
253
+ topic, messageIds, maxAttempts, attempt, endpoints, this.clientId);
254
+ }
255
+ // Send message(s) successfully on first attempt, return directly.
256
+ return sendReceipts;
257
+ }
258
+
259
+ async #getPublishingLoadBalancer(topic: string) {
260
+ let loadBalancer = this.#publishingRouteDataCache.get(topic);
261
+ if (!loadBalancer) {
262
+ const topicRouteData = await this.getRouteData(topic);
263
+ loadBalancer = this.#updatePublishingLoadBalancer(topic, topicRouteData);
264
+ }
265
+ return loadBalancer;
266
+ }
267
+
268
+ #updatePublishingLoadBalancer(topic: string, topicRouteData: TopicRouteData) {
269
+ let loadBalancer = this.#publishingRouteDataCache.get(topic);
270
+ if (loadBalancer) {
271
+ loadBalancer = loadBalancer.update(topicRouteData);
272
+ } else {
273
+ loadBalancer = new PublishingLoadBalancer(topicRouteData);
274
+ }
275
+ this.#publishingRouteDataCache.set(topic, loadBalancer);
276
+ return loadBalancer;
277
+ }
278
+
279
+ /**
280
+ * Take message queue(s) from route for message publishing.
281
+ */
282
+ #takeMessageQueues(loadBalancer: PublishingLoadBalancer) {
283
+ return loadBalancer.takeMessageQueues(this.isolated, this.#getRetryPolicy().getMaxAttempts());
284
+ }
285
+
286
+ #getRetryPolicy() {
287
+ return this.#publishingSettings.getRetryPolicy()!;
288
+ }
289
+ }
@@ -0,0 +1,85 @@
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 { randomInt } from 'node:crypto';
19
+ import { Permission } from '../../proto/apache/rocketmq/v2/definition_pb';
20
+ import { Endpoints, MessageQueue, TopicRouteData } from '../route';
21
+ import { MASTER_BROKER_ID, calculateStringSipHash24 } from '../util';
22
+
23
+ export class PublishingLoadBalancer {
24
+ #index: number;
25
+ #messageQueues: MessageQueue[];
26
+
27
+ constructor(topicRouteData: TopicRouteData, index?: number) {
28
+ this.#messageQueues = topicRouteData.messageQueues.filter(mq => {
29
+ return mq.queueId === MASTER_BROKER_ID && (mq.permission === Permission.WRITE || mq.permission === Permission.READ_WRITE);
30
+ });
31
+ this.#index = index === undefined ? randomInt(this.#messageQueues.length) : index;
32
+ if (this.#messageQueues.length === 0) {
33
+ throw new Error(`No writable message queue found, topicRouteData=${JSON.stringify(topicRouteData)}`);
34
+ }
35
+ }
36
+
37
+ update(topicRouteData: TopicRouteData) {
38
+ return new PublishingLoadBalancer(topicRouteData, this.#index);
39
+ }
40
+
41
+ takeMessageQueues(excluded: Map<string, Endpoints>, count: number) {
42
+ if (this.#index >= this.#messageQueues.length) {
43
+ this.#index = 0;
44
+ }
45
+ let next = this.#index++;
46
+ const candidates: MessageQueue[] = [];
47
+ const candidateBrokerNames = new Set<string>();
48
+
49
+ const size = this.#messageQueues.length;
50
+ for (let i = 0; i < size; i++) {
51
+ const messageQueue = this.#messageQueues[next++ % size];
52
+ const broker = messageQueue.broker;
53
+ const brokerName = broker.name;
54
+ if (!excluded.has(broker.endpoints.facade) && !candidateBrokerNames.has(brokerName)) {
55
+ candidateBrokerNames.add(brokerName);
56
+ candidates.push(messageQueue);
57
+ }
58
+ if (candidates.length >= count) {
59
+ return candidates;
60
+ }
61
+ }
62
+ // If all endpoints are isolated.
63
+ if (candidates.length === 0) {
64
+ for (let i = 0; i < size; i++) {
65
+ const messageQueue = this.#messageQueues[next++ % size];
66
+ const broker = messageQueue.broker;
67
+ const brokerName = broker.name;
68
+ if (!candidateBrokerNames.has(brokerName)) {
69
+ candidateBrokerNames.add(brokerName);
70
+ candidates.push(messageQueue);
71
+ }
72
+ if (candidates.length >= count) {
73
+ return candidates;
74
+ }
75
+ }
76
+ }
77
+ return candidates;
78
+ }
79
+
80
+ takeMessageQueueByMessageGroup(messageGroup: string) {
81
+ const hashCode = calculateStringSipHash24(messageGroup);
82
+ const index = parseInt(`${hashCode % BigInt(this.#messageQueues.length)}`);
83
+ return this.#messageQueues[index];
84
+ }
85
+ }
@@ -0,0 +1,77 @@
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 {
19
+ Settings as SettingsPB,
20
+ ClientType,
21
+ Publishing,
22
+ } from '../../proto/apache/rocketmq/v2/definition_pb';
23
+ import { Endpoints } from '../route';
24
+ import { ExponentialBackoffRetryPolicy } from '../retry';
25
+ import { Settings, UserAgent } from '../client';
26
+ import { createDuration } from '../util';
27
+
28
+ export class PublishingSettings extends Settings {
29
+ readonly #topics: Set<string>;
30
+ /**
31
+ * If message body size exceeds the threshold, it would be compressed for convenience of transport.
32
+ */
33
+ #maxBodySizeBytes = 4 * 1024 * 1024;
34
+ #validateMessageType = true;
35
+
36
+ constructor(clientId: string, accessPoint: Endpoints, retryPolicy: ExponentialBackoffRetryPolicy,
37
+ requestTimeout: number, topics: Set<string>) {
38
+ super(clientId, ClientType.PRODUCER, accessPoint, requestTimeout, retryPolicy);
39
+ this.#topics = topics;
40
+ }
41
+
42
+ get maxBodySizeBytes() {
43
+ return this.#maxBodySizeBytes;
44
+ }
45
+
46
+ isValidateMessageType() {
47
+ return this.#validateMessageType;
48
+ }
49
+
50
+ toProtobuf(): SettingsPB {
51
+ const publishing = new Publishing()
52
+ .setValidateMessageType(this.#validateMessageType);
53
+ for (const topic of this.#topics) {
54
+ publishing.addTopics().setName(topic);
55
+ }
56
+ return new SettingsPB()
57
+ .setClientType(this.clientType)
58
+ .setAccessPoint(this.accessPoint.toProtobuf())
59
+ .setRequestTimeout(createDuration(this.requestTimeout))
60
+ .setPublishing(publishing)
61
+ .setUserAgent(UserAgent.INSTANCE.toProtobuf());
62
+ }
63
+
64
+ sync(settings: SettingsPB): void {
65
+ if (settings.getPubSubCase() !== SettingsPB.PubSubCase.PUBLISHING) {
66
+ // log.error("[Bug] Issued settings not match with the client type, clientId={}, pubSubCase={}, "
67
+ // + "clientType={}", clientId, pubSubCase, clientType);
68
+ return;
69
+ }
70
+ const backoffPolicy = settings.getBackoffPolicy()!;
71
+ const publishing = settings.getPublishing()!.toObject();
72
+ const exist = this.retryPolicy!;
73
+ this.retryPolicy = exist.inheritBackoff(backoffPolicy);
74
+ this.#validateMessageType = publishing.validateMessageType;
75
+ this.#maxBodySizeBytes = publishing.maxBodySize;
76
+ }
77
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Licensed to the Apache Software Foundation (ASF) under one or more
3
+ * contributor license agreements. See the NOTICE file distributed with
4
+ * this work for additional information regarding copyright ownership.
5
+ * The ASF licenses this file to You under the Apache License, Version 2.0
6
+ * (the "License"); you may not use this file except in compliance with
7
+ * the License. You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ import { Code } from '../../proto/apache/rocketmq/v2/definition_pb';
19
+ import { SendMessageResponse } from '../../proto/apache/rocketmq/v2/service_pb';
20
+ import { MessageQueue } from '../route';
21
+ import { StatusChecker } from '../exception';
22
+
23
+ export class SendReceipt {
24
+ readonly messageId: string;
25
+ readonly transactionId: string;
26
+ readonly offset: number;
27
+ readonly #messageQueue: MessageQueue;
28
+
29
+ constructor(messageId: string, transactionId: string, messageQueue: MessageQueue, offset: number) {
30
+ this.messageId = messageId;
31
+ this.transactionId = transactionId;
32
+ this.offset = offset;
33
+ this.#messageQueue = messageQueue;
34
+ }
35
+
36
+ get messageQueue() {
37
+ return this.#messageQueue;
38
+ }
39
+
40
+ get endpoints() {
41
+ return this.#messageQueue.broker.endpoints;
42
+ }
43
+
44
+ static processResponseInvocation(mq: MessageQueue, response: SendMessageResponse) {
45
+ const responseObj = response.toObject();
46
+ // Filter abnormal status.
47
+ const abnormalStatus = responseObj.entriesList.map(e => e.status).find(s => s?.code !== Code.OK);
48
+ const status = abnormalStatus ?? responseObj.status;
49
+ StatusChecker.check(status);
50
+ const sendReceipts: SendReceipt[] = [];
51
+ for (const entry of responseObj.entriesList) {
52
+ const messageId = entry.messageId;
53
+ const transactionId = entry.transactionId;
54
+ const offset = entry.offset;
55
+ const sendReceipt = new SendReceipt(messageId, transactionId, mq, offset);
56
+ sendReceipts.push(sendReceipt);
57
+ }
58
+ return sendReceipts;
59
+ }
60
+ }