rocketmq-client-nodejs 1.1.0 → 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.
- package/dist/client/BaseClient.d.ts +8 -0
- package/dist/client/BaseClient.js +197 -93
- package/dist/client/Logger.js +9 -6
- package/dist/client/RpcClient.js +29 -133
- package/dist/client/RpcClientManager.d.ts +17 -17
- package/dist/client/RpcClientManager.js +38 -50
- package/dist/client/TelemetrySession.js +68 -13
- package/dist/consumer/ConsumeService.js +6 -4
- package/dist/consumer/ConsumeTask.js +5 -5
- package/dist/consumer/Consumer.js +13 -13
- package/dist/consumer/FifoConsumeService.d.ts +2 -1
- package/dist/consumer/FifoConsumeService.js +3 -3
- package/dist/consumer/LiteConsumerSupport.d.ts +25 -0
- package/dist/consumer/LiteConsumerSupport.js +47 -0
- package/dist/consumer/LiteFifoConsumeService.d.ts +2 -1
- package/dist/consumer/LiteFifoConsumeService.js +4 -4
- package/dist/consumer/LitePushConsumerImpl.d.ts +3 -3
- package/dist/consumer/LitePushConsumerImpl.js +10 -29
- package/dist/consumer/LiteSimpleConsumerImpl.js +6 -14
- package/dist/consumer/LiteStandardConsumeService.d.ts +2 -1
- package/dist/consumer/LiteStandardConsumeService.js +3 -3
- package/dist/consumer/LiteSubscriptionManager.js +10 -9
- package/dist/consumer/OffsetOption.d.ts +1 -0
- package/dist/consumer/OffsetOption.js +10 -4
- package/dist/consumer/ProcessQueue.d.ts +7 -1
- package/dist/consumer/ProcessQueue.js +95 -90
- package/dist/consumer/PushConsumer.js +79 -27
- package/dist/consumer/PushSubscriptionSettings.js +3 -3
- package/dist/consumer/SimpleConsumer.d.ts +5 -0
- package/dist/consumer/SimpleConsumer.js +24 -20
- package/dist/consumer/SimpleSubscriptionSettings.js +3 -3
- package/dist/consumer/StandardConsumeService.d.ts +2 -1
- package/dist/consumer/StandardConsumeService.js +16 -7
- package/dist/consumer/SubscriptionLoadBalancer.js +3 -3
- package/dist/exception/InternalErrorException.d.ts +1 -0
- package/dist/exception/InternalErrorException.js +3 -2
- package/dist/exception/StatusChecker.js +4 -4
- package/dist/exception/receiveStatus.d.ts +18 -0
- package/dist/exception/receiveStatus.js +28 -0
- package/dist/hook/CompositedMessageInterceptor.d.ts +2 -1
- package/dist/hook/CompositedMessageInterceptor.js +8 -5
- package/dist/hook/MessageInterceptorContextImpl.d.ts +1 -0
- package/dist/hook/MessageInterceptorContextImpl.js +18 -4
- package/dist/message/Message.js +26 -4
- package/dist/message/MessageView.js +15 -5
- package/dist/message/PublishingMessage.js +4 -4
- package/dist/metrics/ClientMeterManager.d.ts +4 -0
- package/dist/metrics/ClientMeterManager.js +95 -19
- package/dist/producer/Producer.d.ts +8 -2
- package/dist/producer/Producer.js +66 -45
- package/dist/producer/PublishingLoadBalancer.js +3 -3
- package/dist/producer/PublishingSettings.js +1 -3
- package/dist/producer/SendReceipt.js +3 -2
- package/dist/producer/Transaction.d.ts +2 -1
- package/dist/producer/Transaction.js +9 -8
- package/dist/producer/index.d.ts +1 -0
- package/dist/producer/index.js +2 -2
- package/dist/route/Endpoints.js +17 -9
- package/dist/route/MessageQueue.js +7 -2
- package/dist/route/TopicRouteData.d.ts +5 -0
- package/dist/route/TopicRouteData.js +22 -1
- package/dist/util/index.d.ts +1 -1
- package/dist/util/index.js +9 -6
- package/dist/util/rpcContext.d.ts +20 -0
- package/dist/util/rpcContext.js +35 -0
- package/package.json +6 -3
- package/src/client/BaseClient.ts +211 -100
- package/src/client/Logger.ts +9 -5
- package/src/client/RpcClient.ts +48 -132
- package/src/client/RpcClientManager.ts +76 -52
- package/src/client/TelemetrySession.ts +70 -13
- package/src/consumer/ConsumeService.ts +7 -3
- package/src/consumer/ConsumeTask.ts +4 -4
- package/src/consumer/Consumer.ts +16 -15
- package/src/consumer/FifoConsumeService.ts +2 -2
- package/src/consumer/LiteConsumerSupport.ts +49 -0
- package/src/consumer/LiteFifoConsumeService.ts +3 -3
- package/src/consumer/LitePushConsumerImpl.ts +15 -22
- package/src/consumer/LiteSimpleConsumerImpl.ts +7 -14
- package/src/consumer/LiteStandardConsumeService.ts +2 -2
- package/src/consumer/LiteSubscriptionManager.ts +12 -14
- package/src/consumer/OffsetOption.ts +10 -3
- package/src/consumer/ProcessQueue.ts +123 -108
- package/src/consumer/PushConsumer.ts +83 -26
- package/src/consumer/PushSubscriptionSettings.ts +2 -2
- package/src/consumer/SimpleConsumer.ts +30 -23
- package/src/consumer/SimpleSubscriptionSettings.ts +2 -2
- package/src/consumer/StandardConsumeService.ts +15 -6
- package/src/consumer/SubscriptionLoadBalancer.ts +2 -2
- package/src/exception/InternalErrorException.ts +3 -1
- package/src/exception/StatusChecker.ts +3 -2
- package/src/exception/receiveStatus.ts +25 -0
- package/src/hook/CompositedMessageInterceptor.ts +8 -4
- package/src/hook/MessageInterceptorContextImpl.ts +18 -3
- package/src/message/Message.ts +25 -3
- package/src/message/MessageView.ts +13 -4
- package/src/message/PublishingMessage.ts +3 -3
- package/src/metrics/ClientMeterManager.ts +100 -18
- package/src/producer/Producer.ts +71 -46
- package/src/producer/PublishingLoadBalancer.ts +2 -2
- package/src/producer/PublishingSettings.ts +0 -2
- package/src/producer/SendReceipt.ts +2 -1
- package/src/producer/Transaction.ts +12 -11
- package/src/producer/index.ts +1 -1
- package/src/route/Endpoints.ts +16 -8
- package/src/route/MessageQueue.ts +6 -1
- package/src/route/TopicRouteData.ts +22 -1
- package/src/util/index.ts +8 -5
- package/src/util/rpcContext.ts +34 -0
package/src/producer/Producer.ts
CHANGED
|
@@ -39,7 +39,7 @@ import {
|
|
|
39
39
|
import {
|
|
40
40
|
ExponentialBackoffRetryPolicy,
|
|
41
41
|
} from '../retry';
|
|
42
|
-
import { StatusChecker, TooManyRequestsException } from '../exception';
|
|
42
|
+
import { InternalErrorException, StatusChecker, TooManyRequestsException } from '../exception';
|
|
43
43
|
import { BaseClient, BaseClientOptions, Settings } from '../client';
|
|
44
44
|
import { PublishingMessage, MessageOptions, MessageView, Message } from '../message';
|
|
45
45
|
import { PublishingSettings } from './PublishingSettings';
|
|
@@ -48,15 +48,23 @@ import { PublishingLoadBalancer } from './PublishingLoadBalancer';
|
|
|
48
48
|
import { SendReceipt } from './SendReceipt';
|
|
49
49
|
import { Transaction } from './Transaction';
|
|
50
50
|
import { createResource } from '../util';
|
|
51
|
+
import { getRequestId } from '../util/rpcContext';
|
|
51
52
|
import { RecallReceipt } from './RecallReceipt';
|
|
52
53
|
import { RecallMessageRequest } from '../../proto/apache/rocketmq/v2/service_pb';
|
|
53
54
|
import {
|
|
55
|
+
Attribute,
|
|
56
|
+
AttributeKey,
|
|
54
57
|
GeneralMessage,
|
|
55
58
|
MessageHookPoints,
|
|
56
59
|
MessageHookPointsStatus,
|
|
57
60
|
MessageInterceptorContextImpl,
|
|
58
61
|
} from '../hook';
|
|
59
62
|
|
|
63
|
+
// Context keys exposed to SEND interceptors, mirroring the Java ProducerImpl keys.
|
|
64
|
+
export const MESSAGE_TYPE_CONTEXT_KEY = AttributeKey.create<MessageType>('messageType');
|
|
65
|
+
export const SEND_RECEIPTS_CONTEXT_KEY = AttributeKey.create<SendReceipt[]>('sendReceipts');
|
|
66
|
+
export const SEND_EXCEPTION_CONTEXT_KEY = AttributeKey.create<unknown>('sendException');
|
|
67
|
+
|
|
60
68
|
export interface ProducerOptions extends BaseClientOptions {
|
|
61
69
|
topic?: string | string[];
|
|
62
70
|
maxAttempts?: number;
|
|
@@ -69,7 +77,10 @@ export class Producer extends BaseClient {
|
|
|
69
77
|
#publishingRouteDataCache = new Map<string, PublishingLoadBalancer>();
|
|
70
78
|
|
|
71
79
|
constructor(options: ProducerOptions) {
|
|
72
|
-
if (
|
|
80
|
+
if (options.maxAttempts !== undefined && (!Number.isInteger(options.maxAttempts) || options.maxAttempts <= 0)) {
|
|
81
|
+
throw new TypeError('maxAttempts should be a positive integer');
|
|
82
|
+
}
|
|
83
|
+
if (options.topics === undefined && options.topic !== undefined) {
|
|
73
84
|
options.topics = Array.isArray(options.topic) ? options.topic : [ options.topic ];
|
|
74
85
|
}
|
|
75
86
|
super(options);
|
|
@@ -104,7 +115,7 @@ export class Producer extends BaseClient {
|
|
|
104
115
|
this.logger.error('Unable to begin a transaction because producer is not running, clientId=%s', this.clientId);
|
|
105
116
|
throw new Error('Producer is not running now');
|
|
106
117
|
}
|
|
107
|
-
return new Transaction(this);
|
|
118
|
+
return new Transaction(this, this.logger);
|
|
108
119
|
}
|
|
109
120
|
|
|
110
121
|
async endTransaction(endpoints: Endpoints, message: Message, messageId: string,
|
|
@@ -130,7 +141,7 @@ export class Producer extends BaseClient {
|
|
|
130
141
|
const response = await this.rpcClientManager.endTransaction(endpoints, request, this.requestTimeout);
|
|
131
142
|
const statusObj = response.getStatus()?.toObject();
|
|
132
143
|
const hookStatus = statusObj?.code === Code.OK ? MessageHookPointsStatus.OK : MessageHookPointsStatus.ERROR;
|
|
133
|
-
StatusChecker.check(statusObj);
|
|
144
|
+
StatusChecker.check(statusObj, getRequestId(response));
|
|
134
145
|
this.doAfter(MessageInterceptorContextImpl.withStatus(context, hookStatus), generalMessages);
|
|
135
146
|
|
|
136
147
|
this.logger.debug?.('End transaction successfully, messageId=%s, transactionId=%s, resolution=%s, source=%s, clientId=%s',
|
|
@@ -143,8 +154,13 @@ export class Producer extends BaseClient {
|
|
|
143
154
|
|
|
144
155
|
async onRecoverOrphanedTransactionCommand(endpoints: Endpoints, command: RecoverOrphanedTransactionCommand) {
|
|
145
156
|
const transactionId = command.getTransactionId();
|
|
146
|
-
const messagePB = command.getMessage()
|
|
147
|
-
const messageId = messagePB
|
|
157
|
+
const messagePB = command.getMessage();
|
|
158
|
+
const messageId = messagePB?.getSystemProperties()?.getMessageId();
|
|
159
|
+
if (!messagePB) {
|
|
160
|
+
this.logger.error('[Bug] Orphaned transaction message is absent, ignore it, transactionId=%s, endpoints=%s, clientId=%s',
|
|
161
|
+
transactionId, endpoints, this.clientId);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
148
164
|
if (!this.#checker) {
|
|
149
165
|
this.logger.error('No transaction checker registered, ignore it, messageId=%s, transactionId=%s, endpoints=%s, clientId=%s',
|
|
150
166
|
messageId, transactionId, endpoints, this.clientId);
|
|
@@ -165,7 +181,7 @@ export class Producer extends BaseClient {
|
|
|
165
181
|
return;
|
|
166
182
|
}
|
|
167
183
|
// Use SOURCE_SERVER_CHECK for transaction recovery
|
|
168
|
-
await this.endTransaction(endpoints, messageView, messageId, transactionId, resolution,
|
|
184
|
+
await this.endTransaction(endpoints, messageView, messageView.messageId, transactionId, resolution,
|
|
169
185
|
TransactionSource.SOURCE_SERVER_CHECK);
|
|
170
186
|
this.logger.info('Recover orphaned transaction message success, transactionId=%s, resolution=%s, messageId=%s, clientId=%s',
|
|
171
187
|
transactionId, resolution, messageId, this.clientId);
|
|
@@ -200,14 +216,17 @@ export class Producer extends BaseClient {
|
|
|
200
216
|
|
|
201
217
|
async send(message: MessageOptions, transaction?: Transaction) {
|
|
202
218
|
if (!transaction) {
|
|
203
|
-
|
|
219
|
+
this.#checkRunning();
|
|
220
|
+
const sendReceipts = await this.#send([ new PublishingMessage(message, this.#publishingSettings, false) ]);
|
|
204
221
|
return sendReceipts[0];
|
|
205
222
|
}
|
|
206
223
|
|
|
207
224
|
// Send transactional message
|
|
208
225
|
try {
|
|
226
|
+
// Send the transaction's message instance so SEND and COMMIT/ROLLBACK hooks observe the same messageId.
|
|
209
227
|
const publishingMessage = transaction.tryAddMessage(message);
|
|
210
|
-
|
|
228
|
+
this.#checkRunning();
|
|
229
|
+
const sendReceipts = await this.#send([ publishingMessage ]);
|
|
211
230
|
const sendReceipt = sendReceipts[0];
|
|
212
231
|
transaction.tryAddReceipt(publishingMessage, sendReceipt);
|
|
213
232
|
return sendReceipt;
|
|
@@ -217,19 +236,16 @@ export class Producer extends BaseClient {
|
|
|
217
236
|
}
|
|
218
237
|
}
|
|
219
238
|
|
|
220
|
-
|
|
239
|
+
#checkRunning() {
|
|
221
240
|
// Check producer status before message publishing
|
|
222
241
|
if (!this.isRunning()) {
|
|
223
242
|
this.logger.error('Unable to send message because producer is not running, clientId=%s', this.clientId);
|
|
224
243
|
throw new Error('Producer is not running now');
|
|
225
244
|
}
|
|
245
|
+
}
|
|
226
246
|
|
|
227
|
-
|
|
228
|
-
const topics = new Set
|
|
229
|
-
for (const message of messages) {
|
|
230
|
-
pubMessages.push(new PublishingMessage(message, this.#publishingSettings, txEnabled));
|
|
231
|
-
topics.add(message.topic);
|
|
232
|
-
}
|
|
247
|
+
async #send(pubMessages: PublishingMessage[]) {
|
|
248
|
+
const topics = new Set(pubMessages.map(m => m.topic));
|
|
233
249
|
if (topics.size > 1) {
|
|
234
250
|
throw new TypeError(`Messages to send have different topics=${JSON.stringify(Array.from(topics))}`);
|
|
235
251
|
}
|
|
@@ -261,18 +277,7 @@ export class Producer extends BaseClient {
|
|
|
261
277
|
// Prepare the candidate message queue(s) for retry-sending in advance.
|
|
262
278
|
const candidates = messageGroup ? [ loadBalancer.takeMessageQueueByMessageGroup(messageGroup) ] :
|
|
263
279
|
this.#takeMessageQueues(loadBalancer);
|
|
264
|
-
|
|
265
|
-
const context = new MessageInterceptorContextImpl(MessageHookPoints.SEND);
|
|
266
|
-
const generalMessages = pubMessages as unknown as GeneralMessage[];
|
|
267
|
-
this.doBefore(context, generalMessages);
|
|
268
|
-
try {
|
|
269
|
-
const receipts = await this.#send0(topic, messageType, candidates, pubMessages, 1);
|
|
270
|
-
this.doAfter(MessageInterceptorContextImpl.withStatus(context, MessageHookPointsStatus.OK), generalMessages);
|
|
271
|
-
return receipts;
|
|
272
|
-
} catch (err) {
|
|
273
|
-
this.doAfter(MessageInterceptorContextImpl.withStatus(context, MessageHookPointsStatus.ERROR), generalMessages);
|
|
274
|
-
throw err;
|
|
275
|
-
}
|
|
280
|
+
return await this.#send0(topic, messageType, candidates, pubMessages, 1);
|
|
276
281
|
}
|
|
277
282
|
|
|
278
283
|
#wrapSendMessageRequest(pubMessages: PublishingMessage[], mq: MessageQueue) {
|
|
@@ -308,11 +313,19 @@ export class Producer extends BaseClient {
|
|
|
308
313
|
const endpoints = mq.broker.endpoints;
|
|
309
314
|
const maxAttempts = this.#getRetryPolicy().getMaxAttempts();
|
|
310
315
|
const request = this.#wrapSendMessageRequest(messages, mq);
|
|
316
|
+
// SEND hook point per attempt, mirroring Java ProducerImpl#send0.
|
|
317
|
+
const generalMessages = messages as unknown as GeneralMessage[];
|
|
318
|
+
const context = new MessageInterceptorContextImpl(MessageHookPoints.SEND);
|
|
319
|
+
context.putAttribute(MESSAGE_TYPE_CONTEXT_KEY, Attribute.create(messageType));
|
|
320
|
+
this.doBefore(context, generalMessages);
|
|
311
321
|
let sendReceipts: SendReceipt[] = [];
|
|
312
322
|
try {
|
|
313
323
|
const response = await this.rpcClientManager.sendMessage(endpoints, request, this.requestTimeout);
|
|
314
324
|
sendReceipts = SendReceipt.processResponseInvocation(mq, response);
|
|
315
325
|
} catch (err) {
|
|
326
|
+
const context0 = MessageInterceptorContextImpl.withStatus(context, MessageHookPointsStatus.ERROR);
|
|
327
|
+
context0.putAttribute(SEND_EXCEPTION_CONTEXT_KEY, Attribute.create(err));
|
|
328
|
+
this.doAfter(context0, generalMessages);
|
|
316
329
|
const messageIds = messages.map(m => m.messageId);
|
|
317
330
|
// Isolate endpoints because of sending failure
|
|
318
331
|
this.#isolate(endpoints);
|
|
@@ -322,12 +335,6 @@ export class Producer extends BaseClient {
|
|
|
322
335
|
maxAttempts, attempt, topic, messageIds, endpoints, this.clientId, err);
|
|
323
336
|
throw err;
|
|
324
337
|
}
|
|
325
|
-
// No more attempts for transactional message
|
|
326
|
-
if (messageType === MessageType.TRANSACTION) {
|
|
327
|
-
this.logger.error('Failed to send transactional message finally, maxAttempts=%d, attempt=%d, topic=%s, messageId(s)=%s, endpoints=%s, clientId=%s, error=%s',
|
|
328
|
-
maxAttempts, attempt, topic, messageIds, endpoints, this.clientId, err);
|
|
329
|
-
throw err;
|
|
330
|
-
}
|
|
331
338
|
// Try next attempt
|
|
332
339
|
const nextAttempt = 1 + attempt;
|
|
333
340
|
// Retry immediately if the request is not throttled
|
|
@@ -343,6 +350,18 @@ export class Producer extends BaseClient {
|
|
|
343
350
|
return this.#send0(topic, messageType, candidates, messages, nextAttempt);
|
|
344
351
|
}
|
|
345
352
|
|
|
353
|
+
// Should never reach here.
|
|
354
|
+
if (sendReceipts.length !== messages.length) {
|
|
355
|
+
const err = new InternalErrorException(Code.INTERNAL_ERROR, '[Bug] due to an unknown reason from remote, received ' +
|
|
356
|
+
`send receipt's quantity ${sendReceipts.length} is not equal to sent message's quantity ${messages.length}`);
|
|
357
|
+
const context0 = MessageInterceptorContextImpl.withStatus(context, MessageHookPointsStatus.ERROR);
|
|
358
|
+
context0.putAttribute(SEND_EXCEPTION_CONTEXT_KEY, Attribute.create(err));
|
|
359
|
+
this.doAfter(context0, generalMessages);
|
|
360
|
+
throw err;
|
|
361
|
+
}
|
|
362
|
+
const context0 = MessageInterceptorContextImpl.withStatus(context, MessageHookPointsStatus.OK);
|
|
363
|
+
context0.putAttribute(SEND_RECEIPTS_CONTEXT_KEY, Attribute.create(sendReceipts));
|
|
364
|
+
this.doAfter(context0, generalMessages);
|
|
346
365
|
// Resend message(s) successfully
|
|
347
366
|
if (attempt > 1) {
|
|
348
367
|
const messageIds = sendReceipts.map(r => r.messageId);
|
|
@@ -362,11 +381,24 @@ export class Producer extends BaseClient {
|
|
|
362
381
|
let loadBalancer = this.#publishingRouteDataCache.get(topic);
|
|
363
382
|
if (!loadBalancer) {
|
|
364
383
|
const topicRouteData = await this.getRouteData(topic);
|
|
365
|
-
|
|
384
|
+
// A fresh route fetch has already built the load balancer in onTopicRouteDataUpdate.
|
|
385
|
+
loadBalancer = this.#publishingRouteDataCache.get(topic) ??
|
|
386
|
+
this.#updatePublishingLoadBalancer(topic, topicRouteData);
|
|
366
387
|
}
|
|
367
388
|
return loadBalancer;
|
|
368
389
|
}
|
|
369
390
|
|
|
391
|
+
protected onTopicRouteDataUpdate(topic: string, topicRouteData: TopicRouteData) {
|
|
392
|
+
try {
|
|
393
|
+
this.#updatePublishingLoadBalancer(topic, topicRouteData);
|
|
394
|
+
} catch (err) {
|
|
395
|
+
// Keep the previous load balancer so that a route without writable queues fails neither the route refresh
|
|
396
|
+
// of other topics nor the startup; sending to such a topic still fails when no load balancer exists.
|
|
397
|
+
this.logger.error('Failed to update publishing load balancer, topic=%s, clientId=%s, error=%s',
|
|
398
|
+
topic, this.clientId, err);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
370
402
|
#updatePublishingLoadBalancer(topic: string, topicRouteData: TopicRouteData) {
|
|
371
403
|
let loadBalancer = this.#publishingRouteDataCache.get(topic);
|
|
372
404
|
if (loadBalancer) {
|
|
@@ -397,6 +429,7 @@ export class Producer extends BaseClient {
|
|
|
397
429
|
* @param recallHandle - A unique handle to identify the message to recall (obtained from SendReceipt).
|
|
398
430
|
* @return Promise resolving to RecallReceipt containing the recalled message ID.
|
|
399
431
|
* @throws Error if producer is not running or recall handle is invalid.
|
|
432
|
+
* @throws ClientException subclass mapped from the response status if the remote fails to recall the message.
|
|
400
433
|
*/
|
|
401
434
|
async recallMessage(topic: string, recallHandle: string): Promise<RecallReceipt> {
|
|
402
435
|
if (!this.isRunning()) {
|
|
@@ -423,17 +456,9 @@ export class Producer extends BaseClient {
|
|
|
423
456
|
.setRecallHandle(recallHandle);
|
|
424
457
|
|
|
425
458
|
const response = await this.rpcClientManager.recallMessage(this.endpoints, request, this.requestTimeout);
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
}
|
|
430
|
-
|
|
431
|
-
// Check status code
|
|
432
|
-
const statusCode = status.getCode();
|
|
433
|
-
if (statusCode !== Code.OK) {
|
|
434
|
-
const errorMessage = status.getMessage() || 'Unknown error';
|
|
435
|
-
throw new Error(`Failed to recall message: ${errorMessage} (code: ${statusCode})`);
|
|
436
|
-
}
|
|
459
|
+
// StatusChecker surfaces a missing status as InternalErrorException and MESSAGE_NOT_FOUND as
|
|
460
|
+
// NotFoundException, as Java does.
|
|
461
|
+
StatusChecker.check(response.getStatus()?.toObject(), getRequestId(response));
|
|
437
462
|
|
|
438
463
|
const messageId = response.getMessageId();
|
|
439
464
|
const receipt = new RecallReceipt(messageId);
|
|
@@ -26,12 +26,12 @@ export class PublishingLoadBalancer {
|
|
|
26
26
|
|
|
27
27
|
constructor(topicRouteData: TopicRouteData, index?: number) {
|
|
28
28
|
this.#messageQueues = topicRouteData.messageQueues.filter(mq => {
|
|
29
|
-
return mq.
|
|
29
|
+
return mq.broker.id === MASTER_BROKER_ID && (mq.permission === Permission.WRITE || mq.permission === Permission.READ_WRITE);
|
|
30
30
|
});
|
|
31
|
-
this.#index = index === undefined ? randomInt(this.#messageQueues.length) : index;
|
|
32
31
|
if (this.#messageQueues.length === 0) {
|
|
33
32
|
throw new Error(`No writable message queue found, topicRouteData=${JSON.stringify(topicRouteData)}`);
|
|
34
33
|
}
|
|
34
|
+
this.#index = index === undefined ? randomInt(this.#messageQueues.length) : index;
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
update(topicRouteData: TopicRouteData) {
|
|
@@ -64,8 +64,6 @@ export class PublishingSettings extends Settings {
|
|
|
64
64
|
|
|
65
65
|
sync(settings: SettingsPB): void {
|
|
66
66
|
if (settings.getPubSubCase() !== SettingsPB.PubSubCase.PUBLISHING) {
|
|
67
|
-
// log.error("[Bug] Issued settings not match with the client type, clientId={}, pubSubCase={}, "
|
|
68
|
-
// + "clientType={}", clientId, pubSubCase, clientType);
|
|
69
67
|
return;
|
|
70
68
|
}
|
|
71
69
|
const backoffPolicy = settings.getBackoffPolicy()!;
|
|
@@ -19,6 +19,7 @@ import { Code } from '../../proto/apache/rocketmq/v2/definition_pb';
|
|
|
19
19
|
import { SendMessageResponse } from '../../proto/apache/rocketmq/v2/service_pb';
|
|
20
20
|
import { MessageQueue } from '../route';
|
|
21
21
|
import { StatusChecker } from '../exception';
|
|
22
|
+
import { getRequestId } from '../util/rpcContext';
|
|
22
23
|
|
|
23
24
|
export class SendReceipt {
|
|
24
25
|
readonly messageId: string;
|
|
@@ -48,7 +49,7 @@ export class SendReceipt {
|
|
|
48
49
|
// Filter abnormal status.
|
|
49
50
|
const abnormalStatus = responseObj.entriesList.map(e => e.status).find(s => s?.code !== Code.OK);
|
|
50
51
|
const status = abnormalStatus ?? responseObj.status;
|
|
51
|
-
StatusChecker.check(status);
|
|
52
|
+
StatusChecker.check(status, getRequestId(response));
|
|
52
53
|
const sendReceipts: SendReceipt[] = [];
|
|
53
54
|
for (const entry of responseObj.entriesList) {
|
|
54
55
|
const messageId = entry.messageId;
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
18
|
import { TransactionResolution } from '../../proto/apache/rocketmq/v2/definition_pb';
|
|
19
|
+
import { getDefaultLogger, ILogger } from '../client';
|
|
19
20
|
import { MessageOptions, PublishingMessage } from '../message';
|
|
20
21
|
import type { Producer } from './Producer';
|
|
21
22
|
import { SendReceipt } from './SendReceipt';
|
|
@@ -23,11 +24,13 @@ import { SendReceipt } from './SendReceipt';
|
|
|
23
24
|
export class Transaction {
|
|
24
25
|
static readonly MAX_MESSAGE_NUM = 1;
|
|
25
26
|
readonly #producer: Producer;
|
|
27
|
+
readonly #logger: ILogger;
|
|
26
28
|
readonly #messageMap = new Map<string, PublishingMessage>();
|
|
27
29
|
readonly #messageSendReceiptMap = new Map<string, SendReceipt>();
|
|
28
30
|
|
|
29
|
-
constructor(producer: Producer) {
|
|
31
|
+
constructor(producer: Producer, logger: ILogger = getDefaultLogger()) {
|
|
30
32
|
this.#producer = producer;
|
|
33
|
+
this.#logger = logger;
|
|
31
34
|
}
|
|
32
35
|
|
|
33
36
|
tryAddMessage(message: MessageOptions) {
|
|
@@ -51,9 +54,8 @@ export class Transaction {
|
|
|
51
54
|
throw new TypeError('Transactional message has not been sent yet');
|
|
52
55
|
}
|
|
53
56
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
this.#messageSendReceiptMap.size, (this.#producer as any).clientId);
|
|
57
|
+
this.#logger.info('Begin to commit transaction, messageCount=%d, clientId=%s',
|
|
58
|
+
this.#messageSendReceiptMap.size, this.#producer.clientId);
|
|
57
59
|
|
|
58
60
|
for (const [ messageId, sendReceipt ] of this.#messageSendReceiptMap.entries()) {
|
|
59
61
|
const publishingMessage = this.#messageMap.get(messageId)!;
|
|
@@ -61,8 +63,8 @@ export class Transaction {
|
|
|
61
63
|
sendReceipt.messageId, sendReceipt.transactionId, TransactionResolution.COMMIT);
|
|
62
64
|
}
|
|
63
65
|
|
|
64
|
-
logger.debug('Commit transaction successfully, messageCount=%d, clientId=%s',
|
|
65
|
-
this.#messageSendReceiptMap.size,
|
|
66
|
+
this.#logger.debug?.('Commit transaction successfully, messageCount=%d, clientId=%s',
|
|
67
|
+
this.#messageSendReceiptMap.size, this.#producer.clientId);
|
|
66
68
|
}
|
|
67
69
|
|
|
68
70
|
async rollback() {
|
|
@@ -70,9 +72,8 @@ export class Transaction {
|
|
|
70
72
|
throw new TypeError('Transactional message has not been sent yet');
|
|
71
73
|
}
|
|
72
74
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
this.#messageSendReceiptMap.size, (this.#producer as any).clientId);
|
|
75
|
+
this.#logger.debug?.('Begin to rollback transaction, messageCount=%d, clientId=%s',
|
|
76
|
+
this.#messageSendReceiptMap.size, this.#producer.clientId);
|
|
76
77
|
|
|
77
78
|
for (const [ messageId, sendReceipt ] of this.#messageSendReceiptMap.entries()) {
|
|
78
79
|
const publishingMessage = this.#messageMap.get(messageId)!;
|
|
@@ -80,7 +81,7 @@ export class Transaction {
|
|
|
80
81
|
sendReceipt.messageId, sendReceipt.transactionId, TransactionResolution.ROLLBACK);
|
|
81
82
|
}
|
|
82
83
|
|
|
83
|
-
logger.debug('Rollback transaction successfully, messageCount=%d, clientId=%s',
|
|
84
|
-
this.#messageSendReceiptMap.size,
|
|
84
|
+
this.#logger.debug?.('Rollback transaction successfully, messageCount=%d, clientId=%s',
|
|
85
|
+
this.#messageSendReceiptMap.size, this.#producer.clientId);
|
|
85
86
|
}
|
|
86
87
|
}
|
package/src/producer/index.ts
CHANGED
package/src/route/Endpoints.ts
CHANGED
|
@@ -49,7 +49,8 @@ export class Endpoints {
|
|
|
49
49
|
throw new TypeError(`Invalid IPv6 endpoint: ${endpoint}`);
|
|
50
50
|
}
|
|
51
51
|
host = match[1];
|
|
52
|
-
|
|
52
|
+
if (!isIPv6(host)) throw new TypeError(`Invalid IPv6 endpoint: ${endpoint}`);
|
|
53
|
+
port = match[2] ? Number(match[2]) : DEFAULT_PORT;
|
|
53
54
|
} else if (isIPv6(candidate)) {
|
|
54
55
|
// Bare IPv6 address without brackets, e.g. ::1
|
|
55
56
|
host = candidate;
|
|
@@ -59,19 +60,26 @@ export class Endpoints {
|
|
|
59
60
|
const index = candidate.lastIndexOf(':');
|
|
60
61
|
if (index > 0) {
|
|
61
62
|
host = candidate.substring(0, index);
|
|
62
|
-
|
|
63
|
+
const portText = candidate.substring(index + 1);
|
|
64
|
+
if (!/^\d+$/.test(portText)) throw new TypeError(`Invalid endpoint port: ${endpoint}`);
|
|
65
|
+
port = Number(portText);
|
|
63
66
|
} else {
|
|
64
67
|
host = candidate;
|
|
65
68
|
port = DEFAULT_PORT;
|
|
66
69
|
}
|
|
67
70
|
}
|
|
68
|
-
if (
|
|
69
|
-
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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');
|
|
74
81
|
}
|
|
82
|
+
this.scheme = scheme;
|
|
75
83
|
this.addressesList.push({ host, port });
|
|
76
84
|
}
|
|
77
85
|
} else {
|
|
@@ -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 {
|
|
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
|
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.
|
|
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
|
+
}
|