rocketmq-client-nodejs 1.0.3 → 1.0.6

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 (153) hide show
  1. package/README.md +84 -1
  2. package/dist/client/BaseClient.d.ts +24 -2
  3. package/dist/client/BaseClient.js +173 -28
  4. package/dist/client/ClientId.js +2 -2
  5. package/dist/client/Logger.d.ts +1 -0
  6. package/dist/client/Logger.js +1 -1
  7. package/dist/client/RpcClient.d.ts +3 -1
  8. package/dist/client/RpcClient.js +23 -1
  9. package/dist/client/RpcClientManager.d.ts +3 -1
  10. package/dist/client/RpcClientManager.js +23 -4
  11. package/dist/client/TelemetrySession.d.ts +1 -0
  12. package/dist/client/TelemetrySession.js +47 -9
  13. package/dist/consumer/Assignment.d.ts +24 -0
  14. package/dist/consumer/Assignment.js +40 -0
  15. package/dist/consumer/Assignments.d.ts +25 -0
  16. package/dist/consumer/Assignments.js +55 -0
  17. package/dist/consumer/ConsumeResult.d.ts +20 -0
  18. package/dist/consumer/ConsumeResult.js +25 -0
  19. package/dist/consumer/ConsumeService.d.ts +28 -0
  20. package/dist/consumer/ConsumeService.js +53 -0
  21. package/dist/consumer/ConsumeTask.d.ts +24 -0
  22. package/dist/consumer/ConsumeTask.js +39 -0
  23. package/dist/consumer/Consumer.d.ts +19 -1
  24. package/dist/consumer/Consumer.js +64 -21
  25. package/dist/consumer/FifoConsumeService.d.ts +25 -0
  26. package/dist/consumer/FifoConsumeService.js +130 -0
  27. package/dist/consumer/FilterExpression.d.ts +2 -0
  28. package/dist/consumer/FilterExpression.js +18 -1
  29. package/dist/consumer/LitePushConsumer.d.ts +161 -0
  30. package/dist/consumer/LitePushConsumer.js +172 -0
  31. package/dist/consumer/LitePushConsumerImpl.d.ts +167 -0
  32. package/dist/consumer/LitePushConsumerImpl.js +193 -0
  33. package/dist/consumer/LiteSubscriptionManager.d.ts +97 -0
  34. package/dist/consumer/LiteSubscriptionManager.js +238 -0
  35. package/dist/consumer/MessageListener.d.ts +21 -0
  36. package/dist/consumer/MessageListener.js +19 -0
  37. package/dist/consumer/OffsetOption.d.ts +109 -0
  38. package/dist/consumer/OffsetOption.js +191 -0
  39. package/dist/consumer/ProcessQueue.d.ts +39 -0
  40. package/dist/consumer/ProcessQueue.js +293 -0
  41. package/dist/consumer/PushConsumer.d.ts +88 -0
  42. package/dist/consumer/PushConsumer.js +449 -0
  43. package/dist/consumer/PushSubscriptionSettings.d.ts +31 -0
  44. package/dist/consumer/PushSubscriptionSettings.js +97 -0
  45. package/dist/consumer/SimpleConsumer.d.ts +12 -1
  46. package/dist/consumer/SimpleConsumer.js +54 -10
  47. package/dist/consumer/SimpleSubscriptionSettings.d.ts +2 -2
  48. package/dist/consumer/SimpleSubscriptionSettings.js +3 -3
  49. package/dist/consumer/StandardConsumeService.d.ts +25 -0
  50. package/dist/consumer/StandardConsumeService.js +50 -0
  51. package/dist/consumer/index.d.ts +15 -0
  52. package/dist/consumer/index.js +19 -1
  53. package/dist/exception/InternalErrorException.d.ts +5 -0
  54. package/dist/exception/InternalErrorException.js +10 -1
  55. package/dist/exception/LiteSubscriptionQuotaExceededException.d.ts +23 -0
  56. package/dist/exception/LiteSubscriptionQuotaExceededException.js +31 -0
  57. package/dist/exception/LiteTopicQuotaExceededException.d.ts +23 -0
  58. package/dist/exception/LiteTopicQuotaExceededException.js +31 -0
  59. package/dist/exception/StatusChecker.js +4 -1
  60. package/dist/exception/index.d.ts +2 -0
  61. package/dist/exception/index.js +3 -1
  62. package/dist/index.d.ts +1 -0
  63. package/dist/index.js +2 -1
  64. package/dist/message/Message.d.ts +8 -0
  65. package/dist/message/Message.js +39 -6
  66. package/dist/message/MessageId.d.ts +2 -0
  67. package/dist/message/MessageId.js +17 -1
  68. package/dist/message/MessageView.d.ts +86 -0
  69. package/dist/message/MessageView.js +115 -1
  70. package/dist/message/PublishingMessage.js +21 -5
  71. package/dist/producer/Producer.d.ts +21 -2
  72. package/dist/producer/Producer.js +120 -25
  73. package/dist/producer/PublishingLoadBalancer.d.ts +2 -0
  74. package/dist/producer/PublishingLoadBalancer.js +23 -1
  75. package/dist/producer/RecallReceipt.d.ts +25 -0
  76. package/dist/producer/RecallReceipt.js +34 -0
  77. package/dist/producer/SendReceipt.d.ts +2 -1
  78. package/dist/producer/SendReceipt.js +6 -3
  79. package/dist/producer/Transaction.js +7 -1
  80. package/dist/producer/index.d.ts +1 -0
  81. package/dist/producer/index.js +2 -1
  82. package/dist/route/Broker.d.ts +2 -0
  83. package/dist/route/Broker.js +21 -1
  84. package/dist/route/Endpoints.d.ts +2 -0
  85. package/dist/route/Endpoints.js +36 -1
  86. package/dist/route/MessageQueue.d.ts +2 -0
  87. package/dist/route/MessageQueue.js +23 -1
  88. package/dist/route/Resource.d.ts +54 -0
  89. package/dist/route/Resource.js +100 -0
  90. package/dist/route/TopicRouteData.d.ts +12 -0
  91. package/dist/route/TopicRouteData.js +37 -1
  92. package/dist/route/index.d.ts +1 -0
  93. package/dist/route/index.js +2 -1
  94. package/dist/util/index.d.ts +8 -0
  95. package/dist/util/index.js +20 -1
  96. package/package.json +2 -2
  97. package/proto/apache/rocketmq/v2/definition.proto +56 -0
  98. package/proto/apache/rocketmq/v2/definition_pb.d.ts +100 -0
  99. package/proto/apache/rocketmq/v2/definition_pb.js +570 -4
  100. package/proto/apache/rocketmq/v2/service.proto +65 -0
  101. package/proto/apache/rocketmq/v2/service_grpc_pb.d.ts +34 -0
  102. package/proto/apache/rocketmq/v2/service_grpc_pb.js +81 -4
  103. package/proto/apache/rocketmq/v2/service_pb.d.ts +211 -0
  104. package/proto/apache/rocketmq/v2/service_pb.js +1691 -25
  105. package/src/client/BaseClient.ts +196 -28
  106. package/src/client/ClientId.ts +1 -1
  107. package/src/client/Logger.ts +1 -0
  108. package/src/client/RpcClient.ts +26 -0
  109. package/src/client/RpcClientManager.ts +27 -3
  110. package/src/client/TelemetrySession.ts +54 -8
  111. package/src/consumer/Assignment.ts +40 -0
  112. package/src/consumer/Assignments.ts +55 -0
  113. package/src/consumer/ConsumeResult.ts +21 -0
  114. package/src/consumer/ConsumeService.ts +72 -0
  115. package/src/consumer/ConsumeTask.ts +39 -0
  116. package/src/consumer/Consumer.ts +76 -20
  117. package/src/consumer/FifoConsumeService.ts +146 -0
  118. package/src/consumer/FilterExpression.ts +17 -0
  119. package/src/consumer/LitePushConsumer.ts +256 -0
  120. package/src/consumer/LitePushConsumerImpl.ts +245 -0
  121. package/src/consumer/LiteSubscriptionManager.ts +354 -0
  122. package/src/consumer/MessageListener.ts +23 -0
  123. package/src/consumer/OffsetOption.ts +203 -0
  124. package/src/consumer/ProcessQueue.ts +339 -0
  125. package/src/consumer/PushConsumer.ts +563 -0
  126. package/src/consumer/PushSubscriptionSettings.ts +124 -0
  127. package/src/consumer/SimpleConsumer.ts +68 -11
  128. package/src/consumer/SimpleSubscriptionSettings.ts +2 -2
  129. package/src/consumer/StandardConsumeService.ts +57 -0
  130. package/src/consumer/index.ts +15 -0
  131. package/src/exception/InternalErrorException.ts +10 -0
  132. package/src/exception/LiteSubscriptionQuotaExceededException.ts +28 -0
  133. package/src/exception/LiteTopicQuotaExceededException.ts +28 -0
  134. package/src/exception/StatusChecker.ts +3 -0
  135. package/src/exception/index.ts +2 -0
  136. package/src/index.ts +1 -0
  137. package/src/message/Message.ts +46 -5
  138. package/src/message/MessageId.ts +16 -0
  139. package/src/message/MessageView.ts +127 -0
  140. package/src/message/PublishingMessage.ts +20 -4
  141. package/src/producer/Producer.ts +144 -24
  142. package/src/producer/PublishingLoadBalancer.ts +21 -0
  143. package/src/producer/RecallReceipt.ts +32 -0
  144. package/src/producer/SendReceipt.ts +5 -2
  145. package/src/producer/Transaction.ts +16 -0
  146. package/src/producer/index.ts +1 -0
  147. package/src/route/Broker.ts +20 -0
  148. package/src/route/Endpoints.ts +32 -0
  149. package/src/route/MessageQueue.ts +23 -1
  150. package/src/route/Resource.ts +104 -0
  151. package/src/route/TopicRouteData.ts +37 -0
  152. package/src/route/index.ts +1 -0
  153. package/src/util/index.ts +19 -0
@@ -21,6 +21,8 @@ import {
21
21
  ClientType,
22
22
  MessageType,
23
23
  TransactionResolution,
24
+ TransactionSource,
25
+ Code,
24
26
  } from '../../proto/apache/rocketmq/v2/definition_pb';
25
27
  import {
26
28
  EndTransactionRequest,
@@ -46,6 +48,8 @@ import { PublishingLoadBalancer } from './PublishingLoadBalancer';
46
48
  import { SendReceipt } from './SendReceipt';
47
49
  import { Transaction } from './Transaction';
48
50
  import { createResource } from '../util';
51
+ import { RecallReceipt } from './RecallReceipt';
52
+ import { RecallMessageRequest } from '../../proto/apache/rocketmq/v2/service_pb';
49
53
 
50
54
  export interface ProducerOptions extends BaseClientOptions {
51
55
  topic?: string | string[];
@@ -71,24 +75,50 @@ export class Producer extends BaseClient {
71
75
  this.#checker = options.checker;
72
76
  }
73
77
 
78
+ async startup() {
79
+ this.logger.info('Begin to start the rocketmq producer, clientId=%s', this.clientId);
80
+ await super.startup();
81
+ this.logger.info('The rocketmq producer starts successfully, clientId=%s', this.clientId);
82
+ }
83
+
84
+ async shutdown() {
85
+ this.logger.info('Begin to shutdown the rocketmq producer, clientId=%s', this.clientId);
86
+ await super.shutdown();
87
+ this.logger.info('Shutdown the rocketmq producer successfully, clientId=%s', this.clientId);
88
+ }
89
+
74
90
  get publishingSettings() {
75
91
  return this.#publishingSettings;
76
92
  }
77
93
 
78
94
  beginTransaction() {
79
95
  assert(this.#checker, 'Transaction checker should not be null');
96
+ // Check producer status before beginning transaction
97
+ if (!this.isRunning()) {
98
+ this.logger.error('Unable to begin a transaction because producer is not running, clientId=%s', this.clientId);
99
+ throw new Error('Producer is not running now');
100
+ }
80
101
  return new Transaction(this);
81
102
  }
82
103
 
83
104
  async endTransaction(endpoints: Endpoints, message: Message, messageId: string,
84
- transactionId: string, resolution: TransactionResolution) {
105
+ transactionId: string, resolution: TransactionResolution, source: TransactionSource = TransactionSource.SOURCE_CLIENT) {
106
+ const resolutionStr = resolution === TransactionResolution.COMMIT ? 'COMMIT' : 'ROLLBACK';
107
+ const sourceStr = TransactionSource[source];
108
+ this.logger.debug?.('Begin to end transaction, messageId=%s, transactionId=%s, resolution=%s, source=%s, clientId=%s',
109
+ messageId, transactionId, resolutionStr, sourceStr, this.clientId);
110
+
85
111
  const request = new EndTransactionRequest()
86
112
  .setMessageId(messageId)
87
113
  .setTransactionId(transactionId)
88
114
  .setTopic(createResource(message.topic).setResourceNamespace(this.namespace))
89
- .setResolution(resolution);
115
+ .setResolution(resolution)
116
+ .setSource(source);
90
117
  const response = await this.rpcClientManager.endTransaction(endpoints, request, this.requestTimeout);
91
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);
92
122
  }
93
123
 
94
124
  async onRecoverOrphanedTransactionCommand(endpoints: Endpoints, command: RecoverOrphanedTransactionCommand) {
@@ -114,7 +144,9 @@ export class Producer extends BaseClient {
114
144
  if (resolution === null || resolution === TransactionResolution.TRANSACTION_RESOLUTION_UNSPECIFIED) {
115
145
  return;
116
146
  }
117
- await this.endTransaction(endpoints, messageView, messageId, transactionId, resolution);
147
+ // Use SOURCE_SERVER_CHECK for transaction recovery
148
+ await this.endTransaction(endpoints, messageView, messageId, transactionId, resolution,
149
+ TransactionSource.SOURCE_SERVER_CHECK);
118
150
  this.logger.info('Recover orphaned transaction message success, transactionId=%s, resolution=%s, messageId=%s, clientId=%s',
119
151
  transactionId, resolution, messageId, this.clientId);
120
152
  } catch (err) {
@@ -128,9 +160,18 @@ export class Producer extends BaseClient {
128
160
  return this.#publishingSettings;
129
161
  }
130
162
 
163
+ /**
164
+ * Get the client type.
165
+ *
166
+ * @return The client type identifier for producer
167
+ */
168
+ protected getClientType(): ClientType {
169
+ return ClientType.PRODUCER;
170
+ }
171
+
131
172
  protected wrapHeartbeatRequest(): HeartbeatRequest {
132
173
  return new HeartbeatRequest()
133
- .setClientType(ClientType.PRODUCER);
174
+ .setClientType(this.getClientType());
134
175
  }
135
176
 
136
177
  protected wrapNotifyClientTerminationRequest(): NotifyClientTerminationRequest {
@@ -143,14 +184,26 @@ export class Producer extends BaseClient {
143
184
  return sendReceipts[0];
144
185
  }
145
186
 
146
- const publishingMessage = transaction.tryAddMessage(message);
147
- const sendReceipts = await this.#send([ message ], true);
148
- const sendReceipt = sendReceipts[0];
149
- transaction.tryAddReceipt(publishingMessage, sendReceipt);
150
- return sendReceipt;
187
+ // Send transactional message
188
+ try {
189
+ const publishingMessage = transaction.tryAddMessage(message);
190
+ const sendReceipts = await this.#send([ message ], true);
191
+ const sendReceipt = sendReceipts[0];
192
+ transaction.tryAddReceipt(publishingMessage, sendReceipt);
193
+ return sendReceipt;
194
+ } catch (err) {
195
+ this.logger.error('Failed to send transactional message, clientId=%s, error=%s', this.clientId, err);
196
+ throw err;
197
+ }
151
198
  }
152
199
 
153
200
  async #send(messages: MessageOptions[], txEnabled: boolean) {
201
+ // Check producer status before message publishing
202
+ if (!this.isRunning()) {
203
+ this.logger.error('Unable to send message because producer is not running, clientId=%s', this.clientId);
204
+ throw new Error('Producer is not running now');
205
+ }
206
+
154
207
  const pubMessages: PublishingMessage[] = [];
155
208
  const topics = new Set<string>();
156
209
  for (const message of messages) {
@@ -158,21 +211,28 @@ export class Producer extends BaseClient {
158
211
  topics.add(message.topic);
159
212
  }
160
213
  if (topics.size > 1) {
161
- throw new TypeError(`Messages to send have different topics=${JSON.stringify(topics)}`);
214
+ throw new TypeError(`Messages to send have different topics=${JSON.stringify(Array.from(topics))}`);
162
215
  }
163
216
  const topic = pubMessages[0].topic;
164
217
  const messageType = pubMessages[0].messageType;
165
218
  const messageGroup = pubMessages[0].messageGroup;
219
+ const liteTopic = pubMessages[0].liteTopic;
166
220
  const messageTypes = new Set(pubMessages.map(m => m.messageType));
167
221
  if (messageTypes.size > 1) {
168
- throw new TypeError(`Messages to send have different types=${JSON.stringify(messageTypes)}`);
222
+ throw new TypeError(`Messages to send have different types=${JSON.stringify(Array.from(messageTypes))}`);
223
+ }
224
+
225
+ // Log Lite Topic message sending
226
+ if (liteTopic) {
227
+ this.logger.debug?.('Sending Lite Topic message, topic=%s, liteTopic=%s, messageType=%s, clientId=%s',
228
+ topic, liteTopic, MessageType[messageType], this.clientId);
169
229
  }
170
230
 
171
231
  // Message group must be same if message type is FIFO, or no need to proceed.
172
232
  if (messageType === MessageType.FIFO) {
173
233
  const messageGroups = new Set(pubMessages.map(m => m.messageGroup!));
174
234
  if (messageGroups.size > 1) {
175
- throw new TypeError(`FIFO messages to send have message groups, messageGroups=${JSON.stringify(messageGroups)}`);
235
+ throw new TypeError(`FIFO messages to send have message groups, messageGroups=${JSON.stringify(Array.from(messageGroups))}`);
176
236
  }
177
237
  }
178
238
 
@@ -223,42 +283,47 @@ export class Producer extends BaseClient {
223
283
  sendReceipts = SendReceipt.processResponseInvocation(mq, response);
224
284
  } catch (err) {
225
285
  const messageIds = messages.map(m => m.messageId);
226
- // Isolate endpoints because of sending failure.
286
+ // Isolate endpoints because of sending failure
227
287
  this.#isolate(endpoints);
228
288
  if (attempt >= maxAttempts) {
229
- // No need more attempts.
230
- 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',
289
+ // No more attempts
290
+ this.logger.error('Failed to send message(s) finally, run out of attempt times, maxAttempts=%d, attempt=%d, topic=%s, messageId(s)=%s, endpoints=%s, clientId=%s, error=%s',
231
291
  maxAttempts, attempt, topic, messageIds, endpoints, this.clientId, err);
232
292
  throw err;
233
293
  }
234
- // No need more attempts for transactional message.
294
+ // No more attempts for transactional message
235
295
  if (messageType === MessageType.TRANSACTION) {
236
- this.logger.error('Failed to send transactional message finally, maxAttempts=%s, attempt=%s, topic=%s, messageId(s)=%s, endpoints=%s, clientId=%s, error=%s',
296
+ this.logger.error('Failed to send transactional message finally, maxAttempts=%d, attempt=%d, topic=%s, messageId(s)=%s, endpoints=%s, clientId=%s, error=%s',
237
297
  maxAttempts, attempt, topic, messageIds, endpoints, this.clientId, err);
238
298
  throw err;
239
299
  }
240
- // Try to do more attempts.
300
+ // Try next attempt
241
301
  const nextAttempt = 1 + attempt;
242
- // Retry immediately if the request is not throttled.
302
+ // Retry immediately if the request is not throttled
243
303
  if (!(err instanceof TooManyRequestsException)) {
244
- 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',
304
+ this.logger.warn('Failed to send message, would attempt to resend right now, maxAttempts=%d, attempt=%d, topic=%s, messageId(s)=%s, endpoints=%s, clientId=%s, error=%s',
245
305
  maxAttempts, attempt, topic, messageIds, endpoints, this.clientId, err);
246
306
  return this.#send0(topic, messageType, candidates, messages, nextAttempt);
247
307
  }
248
308
  const delay = this.#getRetryPolicy().getNextAttemptDelay(nextAttempt);
249
- 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',
309
+ this.logger.warn('Failed to send message due to too many requests, would attempt to resend after %dms, maxAttempts=%d, attempt=%d, topic=%s, messageId(s)=%s, endpoints=%s, clientId=%s, error=%s',
250
310
  delay, maxAttempts, attempt, topic, messageIds, endpoints, this.clientId, err);
251
311
  await setTimeout(delay);
252
312
  return this.#send0(topic, messageType, candidates, messages, nextAttempt);
253
313
  }
254
314
 
255
- // Resend message(s) successfully.
315
+ // Resend message(s) successfully
256
316
  if (attempt > 1) {
257
317
  const messageIds = sendReceipts.map(r => r.messageId);
258
- this.logger.info('Resend message successfully, topic=%s, messageId(s)=%j, maxAttempts=%s, attempt=%s, endpoints=%s, clientId=%s',
318
+ this.logger.info('Resend message successfully, topic=%s, messageId(s)=%s, maxAttempts=%d, attempt=%d, endpoints=%s, clientId=%s',
259
319
  topic, messageIds, maxAttempts, attempt, endpoints, this.clientId);
260
320
  }
261
- // Send message(s) successfully on first attempt, return directly.
321
+ // Log Lite Topic message sent successfully
322
+ if (sendReceipts.length > 0 && messages[0].liteTopic) {
323
+ this.logger.debug?.('Lite Topic message sent successfully, topic=%s, liteTopic=%s, messageId=%s, clientId=%s',
324
+ topic, messages[0].liteTopic, sendReceipts[0].messageId, this.clientId);
325
+ }
326
+ // Send message(s) successfully on first attempt, return directly
262
327
  return sendReceipts;
263
328
  }
264
329
 
@@ -292,4 +357,59 @@ export class Producer extends BaseClient {
292
357
  #getRetryPolicy() {
293
358
  return this.#publishingSettings.getRetryPolicy()!;
294
359
  }
360
+
361
+ /**
362
+ * Recalls a scheduled/delayed message based on the topic and recall handle.
363
+ * This operation requires server support and can only be performed before the message is delivered.
364
+ *
365
+ * @param topic - The topic associated with the scheduled message to be canceled.
366
+ * @param recallHandle - A unique handle to identify the message to recall (obtained from SendReceipt).
367
+ * @return Promise resolving to RecallReceipt containing the recalled message ID.
368
+ * @throws Error if producer is not running or recall handle is invalid.
369
+ */
370
+ async recallMessage(topic: string, recallHandle: string): Promise<RecallReceipt> {
371
+ if (!this.isRunning()) {
372
+ this.logger.error('Unable to recall message because producer is not running, clientId=%s', this.clientId);
373
+ throw new Error('Producer is not running now');
374
+ }
375
+
376
+ // Validate topic
377
+ if (!topic || typeof topic !== 'string' || topic.trim().length === 0) {
378
+ this.logger.error('Topic is invalid for recall message, clientId=%s', this.clientId);
379
+ throw new Error('Topic is invalid');
380
+ }
381
+
382
+ if (!recallHandle) {
383
+ this.logger.error('Recall handle is invalid, clientId=%s', this.clientId);
384
+ throw new Error('Recall handle is invalid');
385
+ }
386
+
387
+ this.logger.info('Begin to recall message, topic=%s, recallHandle=%s, clientId=%s',
388
+ topic, recallHandle, this.clientId);
389
+
390
+ const request = new RecallMessageRequest()
391
+ .setTopic(createResource(topic).setResourceNamespace(this.namespace))
392
+ .setRecallHandle(recallHandle);
393
+
394
+ const response = await this.rpcClientManager.recallMessage(this.endpoints, request, this.requestTimeout);
395
+ const status = response.getStatus();
396
+ if (!status) {
397
+ throw new Error('Recall message response status is null');
398
+ }
399
+
400
+ // Check status code
401
+ const statusCode = status.getCode();
402
+ if (statusCode !== Code.OK) {
403
+ const errorMessage = status.getMessage() || 'Unknown error';
404
+ throw new Error(`Failed to recall message: ${errorMessage} (code: ${statusCode})`);
405
+ }
406
+
407
+ const messageId = response.getMessageId();
408
+ const receipt = new RecallReceipt(messageId);
409
+
410
+ this.logger.info('Recall message successfully, topic=%s, recallHandle=%s, messageId=%s, clientId=%s',
411
+ topic, recallHandle, messageId, this.clientId);
412
+
413
+ return receipt;
414
+ }
295
415
  }
@@ -82,4 +82,25 @@ export class PublishingLoadBalancer {
82
82
  const index = parseInt(`${hashCode % BigInt(this.#messageQueues.length)}`);
83
83
  return this.#messageQueues[index];
84
84
  }
85
+
86
+ equals(other: PublishingLoadBalancer): boolean {
87
+ if (this === other) return true;
88
+ if (!other) return false;
89
+ if (this.#messageQueues.length !== other.#messageQueues.length) return false;
90
+ for (let i = 0; i < this.#messageQueues.length; i++) {
91
+ if (!this.#messageQueues[i].equals(other.#messageQueues[i])) {
92
+ return false;
93
+ }
94
+ }
95
+ return true;
96
+ }
97
+
98
+ hashCode(): number {
99
+ let hash = 17;
100
+ for (const mq of this.#messageQueues) {
101
+ // eslint-disable-next-line no-bitwise
102
+ hash = (hash * 31 + mq.hashCode()) | 0;
103
+ }
104
+ return hash;
105
+ }
85
106
  }
@@ -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
+ /**
19
+ * Represents the receipt returned after successfully recalling a scheduled/delayed message.
20
+ * Contains the message ID of the recalled message.
21
+ */
22
+ export class RecallReceipt {
23
+ readonly messageId: string;
24
+
25
+ constructor(messageId: string) {
26
+ this.messageId = messageId;
27
+ }
28
+
29
+ toString(): string {
30
+ return `RecallReceipt{messageId='${this.messageId}'}`;
31
+ }
32
+ }
@@ -23,12 +23,14 @@ import { StatusChecker } from '../exception';
23
23
  export class SendReceipt {
24
24
  readonly messageId: string;
25
25
  readonly transactionId: string;
26
+ readonly recallHandle: string;
26
27
  readonly offset: number;
27
28
  readonly #messageQueue: MessageQueue;
28
29
 
29
- constructor(messageId: string, transactionId: string, messageQueue: MessageQueue, offset: number) {
30
+ constructor(messageId: string, transactionId: string, recallHandle: string, messageQueue: MessageQueue, offset: number) {
30
31
  this.messageId = messageId;
31
32
  this.transactionId = transactionId;
33
+ this.recallHandle = recallHandle;
32
34
  this.offset = offset;
33
35
  this.#messageQueue = messageQueue;
34
36
  }
@@ -51,8 +53,9 @@ export class SendReceipt {
51
53
  for (const entry of responseObj.entriesList) {
52
54
  const messageId = entry.messageId;
53
55
  const transactionId = entry.transactionId;
56
+ const recallHandle = entry.recallHandle;
54
57
  const offset = entry.offset;
55
- const sendReceipt = new SendReceipt(messageId, transactionId, mq, offset);
58
+ const sendReceipt = new SendReceipt(messageId, transactionId, recallHandle, mq, offset);
56
59
  sendReceipts.push(sendReceipt);
57
60
  }
58
61
  return sendReceipts;
@@ -50,21 +50,37 @@ export class Transaction {
50
50
  if (this.#messageSendReceiptMap.size === 0) {
51
51
  throw new TypeError('Transactional message has not been sent yet');
52
52
  }
53
+
54
+ const logger = (this.#producer as any).logger;
55
+ logger.info('Begin to commit transaction, messageCount=%d, clientId=%s',
56
+ this.#messageSendReceiptMap.size, (this.#producer as any).clientId);
57
+
53
58
  for (const [ messageId, sendReceipt ] of this.#messageSendReceiptMap.entries()) {
54
59
  const publishingMessage = this.#messageMap.get(messageId)!;
55
60
  await this.#producer.endTransaction(sendReceipt.endpoints, publishingMessage,
56
61
  sendReceipt.messageId, sendReceipt.transactionId, TransactionResolution.COMMIT);
57
62
  }
63
+
64
+ logger.debug('Commit transaction successfully, messageCount=%d, clientId=%s',
65
+ this.#messageSendReceiptMap.size, (this.#producer as any).clientId);
58
66
  }
59
67
 
60
68
  async rollback() {
61
69
  if (this.#messageSendReceiptMap.size === 0) {
62
70
  throw new TypeError('Transactional message has not been sent yet');
63
71
  }
72
+
73
+ const logger = (this.#producer as any).logger;
74
+ logger.debug('Begin to rollback transaction, messageCount=%d, clientId=%s',
75
+ this.#messageSendReceiptMap.size, (this.#producer as any).clientId);
76
+
64
77
  for (const [ messageId, sendReceipt ] of this.#messageSendReceiptMap.entries()) {
65
78
  const publishingMessage = this.#messageMap.get(messageId)!;
66
79
  await this.#producer.endTransaction(sendReceipt.endpoints, publishingMessage,
67
80
  sendReceipt.messageId, sendReceipt.transactionId, TransactionResolution.ROLLBACK);
68
81
  }
82
+
83
+ logger.debug('Rollback transaction successfully, messageCount=%d, clientId=%s',
84
+ this.#messageSendReceiptMap.size, (this.#producer as any).clientId);
69
85
  }
70
86
  }
@@ -18,6 +18,7 @@
18
18
  export * from './Producer';
19
19
  export * from './PublishingLoadBalancer';
20
20
  export * from './PublishingSettings';
21
+ export * from './RecallReceipt';
21
22
  export * from './SendReceipt';
22
23
  // export * from './Transaction';
23
24
  export * from './TransactionChecker';
@@ -16,6 +16,7 @@
16
16
  */
17
17
 
18
18
  import { Broker as BrokerPB } from '../../proto/apache/rocketmq/v2/definition_pb';
19
+ import { hashCodeOfString } from '../util';
19
20
  import { Endpoints } from './Endpoints';
20
21
 
21
22
  export class Broker implements BrokerPB.AsObject {
@@ -36,4 +37,23 @@ export class Broker implements BrokerPB.AsObject {
36
37
  broker.setEndpoints(this.endpoints.toProtobuf());
37
38
  return broker;
38
39
  }
40
+
41
+ equals(other: Broker): boolean {
42
+ if (this === other) return true;
43
+ if (!other) return false;
44
+ return this.id === other.id &&
45
+ this.name === other.name &&
46
+ this.endpoints.equals(other.endpoints);
47
+ }
48
+
49
+ hashCode(): number {
50
+ let hash = 17;
51
+ // eslint-disable-next-line no-bitwise
52
+ hash = (hash * 31 + this.id) | 0;
53
+ // eslint-disable-next-line no-bitwise
54
+ hash = (hash * 31 + hashCodeOfString(this.name)) | 0;
55
+ // eslint-disable-next-line no-bitwise
56
+ hash = (hash * 31 + this.endpoints.hashCode()) | 0;
57
+ return hash;
58
+ }
39
59
  }
@@ -16,6 +16,7 @@
16
16
  */
17
17
 
18
18
  import { isIPv4, isIPv6 } from 'node:net';
19
+ import { hashCodeOfString } from '../util';
19
20
  import { Address, AddressScheme, Endpoints as EndpointsPB } from '../../proto/apache/rocketmq/v2/definition_pb';
20
21
 
21
22
  const DEFAULT_PORT = 80;
@@ -67,4 +68,35 @@ export class Endpoints {
67
68
  }
68
69
  return endpoints;
69
70
  }
71
+
72
+ equals(other: Endpoints): boolean {
73
+ if (this === other) return true;
74
+ if (!other) return false;
75
+ if (this.scheme !== other.scheme) return false;
76
+ if (this.facade !== other.facade) return false;
77
+ if (this.addressesList.length !== other.addressesList.length) return false;
78
+ for (let i = 0; i < this.addressesList.length; i++) {
79
+ const addr1 = this.addressesList[i];
80
+ const addr2 = other.addressesList[i];
81
+ if (addr1.host !== addr2.host || addr1.port !== addr2.port) {
82
+ return false;
83
+ }
84
+ }
85
+ return true;
86
+ }
87
+
88
+ hashCode(): number {
89
+ let hash = 17;
90
+ // eslint-disable-next-line no-bitwise
91
+ hash = (hash * 31 + this.scheme) | 0;
92
+ // eslint-disable-next-line no-bitwise
93
+ hash = (hash * 31 + hashCodeOfString(this.facade)) | 0;
94
+ for (const addr of this.addressesList) {
95
+ // eslint-disable-next-line no-bitwise
96
+ hash = (hash * 31 + hashCodeOfString(addr.host)) | 0;
97
+ // eslint-disable-next-line no-bitwise
98
+ hash = (hash * 31 + addr.port) | 0;
99
+ }
100
+ return hash;
101
+ }
70
102
  }
@@ -19,7 +19,7 @@ import {
19
19
  MessageQueue as MessageQueuePB, MessageType, Permission,
20
20
  Resource,
21
21
  } from '../../proto/apache/rocketmq/v2/definition_pb';
22
- import { createResource } from '../util';
22
+ import { createResource, hashCodeOfString } from '../util';
23
23
  import { Broker } from './Broker';
24
24
 
25
25
  export class MessageQueue {
@@ -46,4 +46,26 @@ export class MessageQueue {
46
46
  messageQueue.setAcceptMessageTypesList(this.acceptMessageTypesList);
47
47
  return messageQueue;
48
48
  }
49
+
50
+ equals(other: MessageQueue): boolean {
51
+ if (this === other) return true;
52
+ if (!other) return false;
53
+ return this.queueId === other.queueId &&
54
+ this.topic.name === other.topic.name &&
55
+ this.broker.equals(other.broker) &&
56
+ this.permission === other.permission;
57
+ }
58
+
59
+ hashCode(): number {
60
+ let hash = 17;
61
+ // eslint-disable-next-line no-bitwise
62
+ hash = (hash * 31 + this.queueId) | 0;
63
+ // eslint-disable-next-line no-bitwise
64
+ hash = (hash * 31 + hashCodeOfString(this.topic.name)) | 0;
65
+ // eslint-disable-next-line no-bitwise
66
+ hash = (hash * 31 + this.broker.hashCode()) | 0;
67
+ // eslint-disable-next-line no-bitwise
68
+ hash = (hash * 31 + this.permission) | 0;
69
+ return hash;
70
+ }
49
71
  }
@@ -0,0 +1,104 @@
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 { Resource as ProtoResource } from '../../proto/apache/rocketmq/v2/definition_pb';
19
+ import { hashCodeOfString } from '../util';
20
+
21
+ /**
22
+ * Represents a resource with namespace and name.
23
+ */
24
+ export class Resource {
25
+ private readonly namespace: string;
26
+ private readonly name: string;
27
+
28
+ constructor(namespace: string, name: string);
29
+ constructor(name: string);
30
+ constructor(namespaceOrName: string, name?: string) {
31
+ if (name !== undefined) {
32
+ this.namespace = namespaceOrName;
33
+ this.name = name;
34
+ } else {
35
+ this.namespace = '';
36
+ this.name = namespaceOrName;
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Get the namespace.
42
+ */
43
+ getNamespace(): string {
44
+ return this.namespace;
45
+ }
46
+
47
+ /**
48
+ * Get the name.
49
+ */
50
+ getName(): string {
51
+ return this.name;
52
+ }
53
+
54
+ /**
55
+ * Convert to protobuf Resource.
56
+ */
57
+ toProtobuf(): ProtoResource {
58
+ const resource = new ProtoResource();
59
+ resource.setResourceNamespace(this.namespace);
60
+ resource.setName(this.name);
61
+ return resource;
62
+ }
63
+
64
+ /**
65
+ * Create from protobuf Resource.
66
+ */
67
+ static fromProtobuf(proto: ProtoResource): Resource {
68
+ const namespace = proto.getResourceNamespace();
69
+ const name = proto.getName();
70
+ return new Resource(namespace, name);
71
+ }
72
+
73
+ /**
74
+ * Returns a string representation of the resource.
75
+ */
76
+ toString(): string {
77
+ if (this.namespace && this.namespace.length > 0) {
78
+ return `Resource{name='${this.name}', namespace='${this.namespace}'}`;
79
+ }
80
+ return this.name;
81
+ }
82
+
83
+ /**
84
+ * Check equality with another Resource.
85
+ */
86
+ equals(other: Resource): boolean {
87
+ if (this === other) return true;
88
+ if (!other) return false;
89
+ return this.namespace === other.namespace &&
90
+ this.name === other.name;
91
+ }
92
+
93
+ /**
94
+ * Calculate hash code.
95
+ */
96
+ hashCode(): number {
97
+ let hash = 17;
98
+ // eslint-disable-next-line no-bitwise
99
+ hash = (hash * 31 + hashCodeOfString(this.namespace)) | 0;
100
+ // eslint-disable-next-line no-bitwise
101
+ hash = (hash * 31 + hashCodeOfString(this.name)) | 0;
102
+ return hash;
103
+ }
104
+ }
@@ -35,4 +35,41 @@ export class TopicRouteData {
35
35
  }
36
36
  return Array.from(endpointsMap.values());
37
37
  }
38
+
39
+ /**
40
+ * Get the count of message queues.
41
+ * @return number of message queues
42
+ */
43
+ getQueueCount(): number {
44
+ return this.messageQueues.length;
45
+ }
46
+
47
+ /**
48
+ * Check if the route data is empty.
49
+ * @return true if no message queues available
50
+ */
51
+ isEmpty(): boolean {
52
+ return this.messageQueues.length === 0;
53
+ }
54
+
55
+ equals(other: TopicRouteData): boolean {
56
+ if (this === other) return true;
57
+ if (!other) return false;
58
+ if (this.messageQueues.length !== other.messageQueues.length) return false;
59
+ for (let i = 0; i < this.messageQueues.length; i++) {
60
+ if (!this.messageQueues[i].equals(other.messageQueues[i])) {
61
+ return false;
62
+ }
63
+ }
64
+ return true;
65
+ }
66
+
67
+ hashCode(): number {
68
+ let hash = 17;
69
+ for (const mq of this.messageQueues) {
70
+ // eslint-disable-next-line no-bitwise
71
+ hash = (hash * 31 + mq.hashCode()) | 0;
72
+ }
73
+ return hash;
74
+ }
38
75
  }