This is an automated email from the ASF dual-hosted git repository.
RongtongJin pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/rocketmq-clients.git
The following commit(s) were added to refs/heads/master by this push:
new 195d71ad fix(nodejs): align producer and message decoding with the
Java client (#1503)
195d71ad is described below
commit 195d71ad06e87530a9fba375a703ee83411fc4e2
Author: Quan <[email protected]>
AuthorDate: Wed Nov 18 21:18:37 2026 +0800
fix(nodejs): align producer and message decoding with the Java client
(#1503)
- Select publishing queues by master broker id and refresh them on route
updates
- Mark messages corrupted when gzip decoding fails instead of failing the
batch
- Map recall failures to typed exceptions and check send receipt counts
- Retry failed transactional messages and guard orphaned transaction
commands
- Pass the logger into Transaction, export it and cover producer paths with
unit tests
---
nodejs/src/message/Message.ts | 5 +-
nodejs/src/message/MessageView.ts | 12 +-
nodejs/src/producer/Producer.ts | 52 ++-
nodejs/src/producer/PublishingLoadBalancer.ts | 4 +-
nodejs/src/producer/Transaction.ts | 23 +-
nodejs/src/producer/index.ts | 2 +-
nodejs/test/message/MessageView.test.ts | 117 +++++++
nodejs/test/message/PublishingMessage.test.ts | 118 +++++++
nodejs/test/producer/Producer.test.ts | 370 +++++++++++++++++++++
.../test/producer/PublishingLoadBalancer.test.ts | 113 ++++++-
nodejs/test/producer/PublishingSettings.test.ts | 84 +++++
nodejs/test/producer/Transaction.test.ts | 154 +++++++++
nodejs/test/producer/harness.ts | 68 ++++
13 files changed, 1082 insertions(+), 40 deletions(-)
diff --git a/nodejs/src/message/Message.ts b/nodejs/src/message/Message.ts
index 55fe4018..b75edff8 100644
--- a/nodejs/src/message/Message.ts
+++ b/nodejs/src/message/Message.ts
@@ -68,13 +68,12 @@ export class Message {
finalDeliveryTimestamp = new Date(Date.now() + options.delay);
}
- const hasPriority = options.priority !== undefined;
const hasLiteTopic = options.liteTopic !== undefined;
const hasTimedDelivery = finalDeliveryTimestamp !== undefined;
const hasGroup = options.messageGroup !== undefined;
- if (hasPriority) {
- if (options.priority === undefined || options.priority < 0) {
+ if (options.priority !== undefined) {
+ if (options.priority < 0) {
throw new Error('priority must be greater than or equal to 0');
}
if (hasTimedDelivery || hasGroup || hasLiteTopic) {
diff --git a/nodejs/src/message/MessageView.ts
b/nodejs/src/message/MessageView.ts
index 0e17d233..2d4077ce 100644
--- a/nodejs/src/message/MessageView.ts
+++ b/nodejs/src/message/MessageView.ts
@@ -51,6 +51,7 @@ export class MessageView {
const digestType = bodyDigest.type;
const checksum = bodyDigest.checksum;
let expectedChecksum = '';
+ let corrupted = false;
let bodyBytes = Buffer.from(message.getBody_asU8());
switch (digestType) {
case DigestType.CRC32:
@@ -67,11 +68,18 @@ export class MessageView {
// digestType, topic, messageId);
}
if (expectedChecksum && expectedChecksum !== checksum) {
- this.corrupted = true;
+ corrupted = true;
}
if (systemProperties.getBodyEncoding() === Encoding.GZIP) {
- bodyBytes = gunzipSync(bodyBytes);
+ try {
+ bodyBytes = gunzipSync(bodyBytes);
+ } catch {
+ // Keep the raw body and let the consumer discard the message, as Java
MessageViewImpl#fromProtobuf does,
+ // instead of failing the whole received batch.
+ corrupted = true;
+ }
}
+ this.corrupted = corrupted;
for (const [ key, value ] of message.getUserPropertiesMap().entries()) {
this.properties.set(key, value);
diff --git a/nodejs/src/producer/Producer.ts b/nodejs/src/producer/Producer.ts
index c0554a22..90425d5f 100644
--- a/nodejs/src/producer/Producer.ts
+++ b/nodejs/src/producer/Producer.ts
@@ -39,7 +39,7 @@ import {
import {
ExponentialBackoffRetryPolicy,
} from '../retry';
-import { StatusChecker, TooManyRequestsException } from '../exception';
+import { InternalErrorException, NotFoundException, StatusChecker,
TooManyRequestsException } from '../exception';
import { BaseClient, BaseClientOptions, Settings } from '../client';
import { PublishingMessage, MessageOptions, MessageView, Message } from
'../message';
import { PublishingSettings } from './PublishingSettings';
@@ -107,7 +107,7 @@ export class Producer extends BaseClient {
this.logger.error('Unable to begin a transaction because producer is not
running, clientId=%s', this.clientId);
throw new Error('Producer is not running now');
}
- return new Transaction(this);
+ return new Transaction(this, this.logger);
}
async endTransaction(endpoints: Endpoints, message: Message, messageId:
string,
@@ -146,8 +146,13 @@ export class Producer extends BaseClient {
async onRecoverOrphanedTransactionCommand(endpoints: Endpoints, command:
RecoverOrphanedTransactionCommand) {
const transactionId = command.getTransactionId();
- const messagePB = command.getMessage()!;
- const messageId = messagePB.getSystemProperties()!.getMessageId();
+ const messagePB = command.getMessage();
+ const messageId = messagePB?.getSystemProperties()?.getMessageId();
+ if (!messagePB) {
+ this.logger.error('[Bug] Orphaned transaction message is absent, ignore
it, transactionId=%s, endpoints=%s, clientId=%s',
+ transactionId, endpoints, this.clientId);
+ return;
+ }
if (!this.#checker) {
this.logger.error('No transaction checker registered, ignore it,
messageId=%s, transactionId=%s, endpoints=%s, clientId=%s',
messageId, transactionId, endpoints, this.clientId);
@@ -168,7 +173,7 @@ export class Producer extends BaseClient {
return;
}
// Use SOURCE_SERVER_CHECK for transaction recovery
- await this.endTransaction(endpoints, messageView, messageId,
transactionId, resolution,
+ await this.endTransaction(endpoints, messageView, messageView.messageId,
transactionId, resolution,
TransactionSource.SOURCE_SERVER_CHECK);
this.logger.info('Recover orphaned transaction message success,
transactionId=%s, resolution=%s, messageId=%s, clientId=%s',
transactionId, resolution, messageId, this.clientId);
@@ -325,12 +330,6 @@ export class Producer extends BaseClient {
maxAttempts, attempt, topic, messageIds, endpoints, this.clientId,
err);
throw err;
}
- // No more attempts for transactional message
- if (messageType === MessageType.TRANSACTION) {
- this.logger.error('Failed to send transactional message finally,
maxAttempts=%d, attempt=%d, topic=%s, messageId(s)=%s, endpoints=%s,
clientId=%s, error=%s',
- maxAttempts, attempt, topic, messageIds, endpoints, this.clientId,
err);
- throw err;
- }
// Try next attempt
const nextAttempt = 1 + attempt;
// Retry immediately if the request is not throttled
@@ -346,6 +345,11 @@ export class Producer extends BaseClient {
return this.#send0(topic, messageType, candidates, messages,
nextAttempt);
}
+ // Should never reach here.
+ if (sendReceipts.length !== messages.length) {
+ throw new InternalErrorException(Code.INTERNAL_ERROR, '[Bug] due to an
unknown reason from remote, received ' +
+ `send receipt's quantity ${sendReceipts.length} is not equal to sent
message's quantity ${messages.length}`);
+ }
// Resend message(s) successfully
if (attempt > 1) {
const messageIds = sendReceipts.map(r => r.messageId);
@@ -365,11 +369,24 @@ export class Producer extends BaseClient {
let loadBalancer = this.#publishingRouteDataCache.get(topic);
if (!loadBalancer) {
const topicRouteData = await this.getRouteData(topic);
- loadBalancer = this.#updatePublishingLoadBalancer(topic, topicRouteData);
+ // A fresh route fetch has already built the load balancer in
onTopicRouteDataUpdate.
+ loadBalancer = this.#publishingRouteDataCache.get(topic) ??
+ this.#updatePublishingLoadBalancer(topic, topicRouteData);
}
return loadBalancer;
}
+ protected onTopicRouteDataUpdate(topic: string, topicRouteData:
TopicRouteData) {
+ try {
+ this.#updatePublishingLoadBalancer(topic, topicRouteData);
+ } catch (err) {
+ // Keep the previous load balancer so that a route without writable
queues fails neither the route refresh
+ // of other topics nor the startup; sending to such a topic still fails
when no load balancer exists.
+ this.logger.error('Failed to update publishing load balancer, topic=%s,
clientId=%s, error=%s',
+ topic, this.clientId, err);
+ }
+ }
+
#updatePublishingLoadBalancer(topic: string, topicRouteData: TopicRouteData)
{
let loadBalancer = this.#publishingRouteDataCache.get(topic);
if (loadBalancer) {
@@ -400,6 +417,7 @@ export class Producer extends BaseClient {
* @param recallHandle - A unique handle to identify the message to recall
(obtained from SendReceipt).
* @return Promise resolving to RecallReceipt containing the recalled
message ID.
* @throws Error if producer is not running or recall handle is invalid.
+ * @throws ClientException subclass mapped from the response status if the
remote fails to recall the message.
*/
async recallMessage(topic: string, recallHandle: string):
Promise<RecallReceipt> {
if (!this.isRunning()) {
@@ -430,13 +448,11 @@ export class Producer extends BaseClient {
if (!status) {
throw new Error('Recall message response status is null');
}
-
- // Check status code
- const statusCode = status.getCode();
- if (statusCode !== Code.OK) {
- const errorMessage = status.getMessage() || 'Unknown error';
- throw new Error(`Failed to recall message: ${errorMessage} (code:
${statusCode})`);
+ // StatusChecker treats MESSAGE_NOT_FOUND as success for receiving;
recalling surfaces it as Java does.
+ if (status.getCode() === Code.MESSAGE_NOT_FOUND) {
+ throw new NotFoundException(status.getCode(), status.getMessage());
}
+ StatusChecker.check(status.toObject());
const messageId = response.getMessageId();
const receipt = new RecallReceipt(messageId);
diff --git a/nodejs/src/producer/PublishingLoadBalancer.ts
b/nodejs/src/producer/PublishingLoadBalancer.ts
index 9039573f..1c23316c 100644
--- a/nodejs/src/producer/PublishingLoadBalancer.ts
+++ b/nodejs/src/producer/PublishingLoadBalancer.ts
@@ -26,12 +26,12 @@ export class PublishingLoadBalancer {
constructor(topicRouteData: TopicRouteData, index?: number) {
this.#messageQueues = topicRouteData.messageQueues.filter(mq => {
- return mq.queueId === MASTER_BROKER_ID && (mq.permission ===
Permission.WRITE || mq.permission === Permission.READ_WRITE);
+ return mq.broker.id === MASTER_BROKER_ID && (mq.permission ===
Permission.WRITE || mq.permission === Permission.READ_WRITE);
});
- this.#index = index === undefined ? randomInt(this.#messageQueues.length)
: index;
if (this.#messageQueues.length === 0) {
throw new Error(`No writable message queue found,
topicRouteData=${JSON.stringify(topicRouteData)}`);
}
+ this.#index = index === undefined ? randomInt(this.#messageQueues.length)
: index;
}
update(topicRouteData: TopicRouteData) {
diff --git a/nodejs/src/producer/Transaction.ts
b/nodejs/src/producer/Transaction.ts
index 529a878a..cb8dfc3a 100644
--- a/nodejs/src/producer/Transaction.ts
+++ b/nodejs/src/producer/Transaction.ts
@@ -16,6 +16,7 @@
*/
import { TransactionResolution } from
'../../proto/apache/rocketmq/v2/definition_pb';
+import { getDefaultLogger, ILogger } from '../client';
import { MessageOptions, PublishingMessage } from '../message';
import type { Producer } from './Producer';
import { SendReceipt } from './SendReceipt';
@@ -23,11 +24,13 @@ import { SendReceipt } from './SendReceipt';
export class Transaction {
static readonly MAX_MESSAGE_NUM = 1;
readonly #producer: Producer;
+ readonly #logger: ILogger;
readonly #messageMap = new Map<string, PublishingMessage>();
readonly #messageSendReceiptMap = new Map<string, SendReceipt>();
- constructor(producer: Producer) {
+ constructor(producer: Producer, logger: ILogger = getDefaultLogger()) {
this.#producer = producer;
+ this.#logger = logger;
}
tryAddMessage(message: MessageOptions) {
@@ -51,9 +54,8 @@ export class Transaction {
throw new TypeError('Transactional message has not been sent yet');
}
- const logger = (this.#producer as any).logger;
- logger.info('Begin to commit transaction, messageCount=%d, clientId=%s',
- this.#messageSendReceiptMap.size, (this.#producer as any).clientId);
+ this.#logger.info('Begin to commit transaction, messageCount=%d,
clientId=%s',
+ this.#messageSendReceiptMap.size, this.#producer.clientId);
for (const [ messageId, sendReceipt ] of
this.#messageSendReceiptMap.entries()) {
const publishingMessage = this.#messageMap.get(messageId)!;
@@ -61,8 +63,8 @@ export class Transaction {
sendReceipt.messageId, sendReceipt.transactionId,
TransactionResolution.COMMIT);
}
- logger.debug('Commit transaction successfully, messageCount=%d,
clientId=%s',
- this.#messageSendReceiptMap.size, (this.#producer as any).clientId);
+ this.#logger.debug?.('Commit transaction successfully, messageCount=%d,
clientId=%s',
+ this.#messageSendReceiptMap.size, this.#producer.clientId);
}
async rollback() {
@@ -70,9 +72,8 @@ export class Transaction {
throw new TypeError('Transactional message has not been sent yet');
}
- const logger = (this.#producer as any).logger;
- logger.debug('Begin to rollback transaction, messageCount=%d, clientId=%s',
- this.#messageSendReceiptMap.size, (this.#producer as any).clientId);
+ this.#logger.debug?.('Begin to rollback transaction, messageCount=%d,
clientId=%s',
+ this.#messageSendReceiptMap.size, this.#producer.clientId);
for (const [ messageId, sendReceipt ] of
this.#messageSendReceiptMap.entries()) {
const publishingMessage = this.#messageMap.get(messageId)!;
@@ -80,7 +81,7 @@ export class Transaction {
sendReceipt.messageId, sendReceipt.transactionId,
TransactionResolution.ROLLBACK);
}
- logger.debug('Rollback transaction successfully, messageCount=%d,
clientId=%s',
- this.#messageSendReceiptMap.size, (this.#producer as any).clientId);
+ this.#logger.debug?.('Rollback transaction successfully, messageCount=%d,
clientId=%s',
+ this.#messageSendReceiptMap.size, this.#producer.clientId);
}
}
diff --git a/nodejs/src/producer/index.ts b/nodejs/src/producer/index.ts
index 87af3eb4..57d19c69 100644
--- a/nodejs/src/producer/index.ts
+++ b/nodejs/src/producer/index.ts
@@ -20,5 +20,5 @@ export * from './PublishingLoadBalancer';
export * from './PublishingSettings';
export * from './RecallReceipt';
export * from './SendReceipt';
-// export * from './Transaction';
+export * from './Transaction';
export * from './TransactionChecker';
diff --git a/nodejs/test/message/MessageView.test.ts
b/nodejs/test/message/MessageView.test.ts
new file mode 100644
index 00000000..0c9361e6
--- /dev/null
+++ b/nodejs/test/message/MessageView.test.ts
@@ -0,0 +1,117 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { strict as assert } from 'node:assert';
+import { gzipSync } from 'node:zlib';
+import { Timestamp } from 'google-protobuf/google/protobuf/timestamp_pb';
+import { DigestType, Encoding } from
'../../proto/apache/rocketmq/v2/definition_pb';
+import { MessageView } from '../../src/message';
+import { crc32CheckSum } from '../../src/util';
+import { buildMessagePB, buildRoute } from '../support/protobuf';
+
+describe('MessageView', () => {
+ const mq = buildRoute({ brokers: [{ name: 'broker-a', endpoints:
'127.0.0.1:8081' }] }).messageQueues[0];
+
+ for (const [ name, digestType ] of [[ 'CRC32', DigestType.CRC32 ], [ 'MD5',
DigestType.MD5 ], [ 'SHA1', DigestType.SHA1 ]] as const) {
+ it(`marks the message corrupted when the ${name} checksum mismatches`, ()
=> {
+ const view = new MessageView(buildMessagePB({ digestType, checksum:
'mismatch' }), mq);
+ assert.equal(view.corrupted, true);
+ assert.deepEqual(view.body, Buffer.from('test-body'));
+ });
+
+ it(`accepts a matching ${name} checksum`, () => {
+ const view = new MessageView(buildMessagePB({ digestType }), mq);
+ assert.equal(view.corrupted, false);
+ });
+ }
+
+ it('decompresses a gzip body', () => {
+ const body = Buffer.from('compressed-body');
+ const view = new MessageView(buildMessagePB({ body, gzip: true }), mq);
+ assert.equal(view.corrupted, false);
+ assert.deepEqual(view.body, body);
+ });
+
+ it('marks the message corrupted and keeps the raw body when gzip decoding
fails', () => {
+ const raw = Buffer.from('not gzip data');
+ const message = buildMessagePB({ body: raw });
+ message.getSystemProperties()!.setBodyEncoding(Encoding.GZIP)
+ .getBodyDigest()!.setChecksum(crc32CheckSum(raw));
+ const view = new MessageView(message, mq);
+ assert.equal(view.corrupted, true);
+ assert.deepEqual(view.body, raw);
+ assert.equal(view.messageId, 'test-message-id');
+ });
+
+ it('decodes system properties, user properties and endpoints', () => {
+ const deliveryTimestamp = new Date('2026-01-01T00:00:00Z');
+ const bornTimestamp = new Date('2025-12-31T23:59:59Z');
+ const message = buildMessagePB({
+ tag: 'tag-a', keys: [ 'key-a', 'key-b' ], messageGroup: 'group-a',
liteTopic: 'lite-a', priority: 3,
+ deliveryAttempt: 2, receiptHandle: 'handle-a', properties: new Map([[
'k', 'v' ]]),
+ });
+ message.getSystemProperties()!
+ .setDeliveryTimestamp(Timestamp.fromDate(deliveryTimestamp))
+ .setBornTimestamp(Timestamp.fromDate(bornTimestamp))
+ .setBornHost('host-a')
+ .setQueueOffset(42);
+ const transportDeliveryTimestamp = new Date();
+ const view = new MessageView(message, mq, transportDeliveryTimestamp);
+
+ assert.equal(view.getMessageId(), 'test-message-id');
+ assert.equal(view.getTopic(), 'test-topic');
+ assert.equal(view.getTag(), 'tag-a');
+ assert.deepEqual(view.getKeys(), [ 'key-a', 'key-b' ]);
+ assert.equal(view.getMessageGroup(), 'group-a');
+ assert.equal(view.getLiteTopic(), 'lite-a');
+ assert.equal(view.getPriority(), 3);
+ assert.deepEqual(view.getDeliveryTimestamp(), deliveryTimestamp);
+ assert.deepEqual(view.getBornTimestamp(), bornTimestamp);
+ assert.equal(view.getBornHost(), 'host-a');
+ assert.equal(view.getDeliveryAttempt(), 2);
+ assert.equal(view.offset, 42);
+ assert.equal(view.receiptHandle, 'handle-a');
+ assert.equal(view.transportDeliveryTimestamp, transportDeliveryTimestamp);
+ assert.equal(view.getProperties().get('k'), 'v');
+ assert.equal(view.endpoints, mq.broker.endpoints);
+ assert.equal(view.incrementAndGetDeliveryAttempt(), 3);
+ });
+
+ it('returns copies of body, keys and properties', () => {
+ const view = new MessageView(buildMessagePB({ keys: [ 'key-a' ],
properties: new Map([[ 'k', 'v' ]]) }), mq);
+ view.getBody().fill(0);
+ view.getKeys().push('key-b');
+ view.getProperties().set('k', 'changed');
+ assert.deepEqual(view.body, Buffer.from('test-body'));
+ assert.deepEqual(view.keys, [ 'key-a' ]);
+ assert.equal(view.properties.get('k'), 'v');
+ });
+
+ it('skips the checksum for an unsupported digest type', () => {
+ const message = buildMessagePB({ checksum: 'ignored' });
+
message.getSystemProperties()!.getBodyDigest()!.setType(DigestType.DIGEST_TYPE_UNSPECIFIED);
+ assert.equal(new MessageView(message, mq).corrupted, false);
+ });
+
+ it('keeps a gzip body whose checksum covers the compressed bytes', () => {
+ const body = Buffer.from('payload');
+ const compressed = gzipSync(body);
+ const message = buildMessagePB({ body, gzip: true });
+
assert.equal(message.getSystemProperties()!.getBodyDigest()!.getChecksum(),
crc32CheckSum(compressed));
+ assert.deepEqual(new MessageView(message, mq).body, body);
+ });
+});
diff --git a/nodejs/test/message/PublishingMessage.test.ts
b/nodejs/test/message/PublishingMessage.test.ts
new file mode 100644
index 00000000..03503e3c
--- /dev/null
+++ b/nodejs/test/message/PublishingMessage.test.ts
@@ -0,0 +1,118 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { strict as assert } from 'node:assert';
+import { Encoding, MessageType, Publishing } from
'../../proto/apache/rocketmq/v2/definition_pb';
+import { MessageOptions, PublishingMessage } from '../../src/message';
+import { PublishingSettings } from '../../src/producer';
+import { ExponentialBackoffRetryPolicy } from '../../src/retry';
+import { Endpoints } from '../../src/route';
+import { buildRoute, buildSettings } from '../support/protobuf';
+
+describe('PublishingMessage', () => {
+ const settings = new PublishingSettings('', 'client-id', new
Endpoints('127.0.0.1:8080'),
+ ExponentialBackoffRetryPolicy.immediatelyRetryPolicy(3), 3000, new Set());
+ const base = { topic: 'test-topic', body: Buffer.from('body') };
+
+ const cases: Array<[ string, Partial<MessageOptions>, boolean, MessageType
]> = [
+ [ 'NORMAL', {}, false, MessageType.NORMAL ],
+ [ 'FIFO', { messageGroup: 'group-a' }, false, MessageType.FIFO ],
+ [ 'DELAY', { delay: 1000 }, false, MessageType.DELAY ],
+ [ 'DELAY by timestamp', { deliveryTimestamp: new Date(Date.now() + 1000)
}, false, MessageType.DELAY ],
+ [ 'TRANSACTION', {}, true, MessageType.TRANSACTION ],
+ [ 'PRIORITY', { priority: 0 }, false, MessageType.PRIORITY ],
+ [ 'LITE', { liteTopic: 'lite-a' }, false, MessageType.LITE ],
+ ];
+ for (const [ name, options, txEnabled, messageType ] of cases) {
+ it(`detects the ${name} message type`, () => {
+ const message = new PublishingMessage({ ...base, ...options }, settings,
txEnabled);
+ assert.equal(message.messageType, messageType);
+ assert.ok(message.messageId);
+ });
+ }
+
+ for (const extra of [{ messageGroup: 'g' }, { delay: 1000 }, { liteTopic:
'lite' }, { priority: 1 }]) {
+ it(`rejects a transactional message with ${Object.keys(extra)[0]}`, () => {
+ assert.throws(() => new PublishingMessage({ ...base, ...extra },
settings, true),
+ /Transactional message should not set messageGroup, liteTopic,
deliveryTimestamp or priority/);
+ });
+ }
+
+ const conflicts: Array<[ Partial<MessageOptions>, RegExp ]> = [
+ [{ priority: 1, messageGroup: 'g' }, /priority is mutually exclusive/ ],
+ [{ priority: 1, delay: 1000 }, /priority is mutually exclusive/ ],
+ [{ priority: 1, liteTopic: 'lite' }, /priority is mutually exclusive/ ],
+ [{ liteTopic: 'lite', messageGroup: 'g' }, /liteTopic is mutually
exclusive/ ],
+ [{ liteTopic: 'lite', delay: 1000 }, /liteTopic is mutually exclusive/ ],
+ [{ messageGroup: 'g', delay: 1000 }, /delay\/deliveryTimestamp is mutually
exclusive with messageGroup/ ],
+ [{ priority: -1 }, /priority must be greater than or equal to 0/ ],
+ ];
+ for (const [ options, error ] of conflicts) {
+ it(`rejects conflicting fields ${JSON.stringify(options)}`, () => {
+ assert.throws(() => new PublishingMessage({ ...base, ...options },
settings, false), error);
+ });
+ }
+
+ it('rejects a body larger than the max body size', () => {
+ const small = new PublishingSettings('', 'client-id', new
Endpoints('127.0.0.1:8080'),
+ ExponentialBackoffRetryPolicy.immediatelyRetryPolicy(3), 3000, new
Set());
+ small.sync(buildSettings({ publishing: new
Publishing().setMaxBodySize(4).setValidateMessageType(true) }));
+
+ assert.ok(new PublishingMessage({ ...base, body: Buffer.alloc(4) }, small,
false));
+ assert.throws(() => new PublishingMessage({ ...base, body: Buffer.alloc(5)
}, small, false),
+ /Message body size exceeds the threshold, max size=4 bytes/);
+ });
+
+ it('converts to protobuf with every field', () => {
+ const deliveryTimestamp = new Date(Date.now() + 1000);
+ const message = new PublishingMessage({
+ ...base, tag: 'tag-a', keys: [ 'key-a' ], deliveryTimestamp, properties:
new Map([[ 'k', 'v' ]]),
+ }, settings, false);
+ const mq = buildRoute({ queuesPerBroker: 3 }).messageQueues[2];
+
+ const pb = message.toProtobuf('ns', mq);
+
+ assert.equal(pb.getTopic()!.getName(), 'test-topic');
+ assert.equal(pb.getTopic()!.getResourceNamespace(), 'ns');
+ assert.deepEqual(Buffer.from(pb.getBody_asU8()), base.body);
+ assert.equal(pb.getUserPropertiesMap().get('k'), 'v');
+ const properties = pb.getSystemProperties()!;
+ assert.equal(properties.getMessageId(), message.messageId);
+ assert.equal(properties.getMessageType(), MessageType.DELAY);
+ assert.equal(properties.getTag(), 'tag-a');
+ assert.deepEqual(properties.getKeysList(), [ 'key-a' ]);
+ assert.equal(properties.getDeliveryTimestamp()!.toDate().getTime(),
deliveryTimestamp.getTime());
+ assert.equal(properties.getQueueId(), 2);
+ assert.equal(properties.getBodyEncoding(), Encoding.IDENTITY);
+ assert.ok(properties.getBornTimestamp());
+ assert.ok(properties.getBornHost());
+ assert.equal(properties.hasMessageGroup(), false);
+ assert.equal(properties.hasLiteTopic(), false);
+ assert.equal(properties.hasPriority(), false);
+ });
+
+ it('converts FIFO, lite and priority fields to protobuf', () => {
+ const mq = buildRoute().messageQueues[0];
+ const fifo = new PublishingMessage({ ...base, messageGroup: 'group-a' },
settings, false).toProtobuf('', mq);
+ assert.equal(fifo.getSystemProperties()!.getMessageGroup(), 'group-a');
+ const lite = new PublishingMessage({ ...base, liteTopic: 'lite-a' },
settings, false).toProtobuf('', mq);
+ assert.equal(lite.getSystemProperties()!.getLiteTopic(), 'lite-a');
+ const priority = new PublishingMessage({ ...base, priority: 0 }, settings,
false).toProtobuf('', mq);
+ assert.equal(priority.getSystemProperties()!.hasPriority(), true);
+ assert.equal(priority.getSystemProperties()!.getPriority(), 0);
+ });
+});
diff --git a/nodejs/test/producer/Producer.test.ts
b/nodejs/test/producer/Producer.test.ts
new file mode 100644
index 00000000..4e2f9631
--- /dev/null
+++ b/nodejs/test/producer/Producer.test.ts
@@ -0,0 +1,370 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { strict as assert } from 'node:assert';
+import * as sinon from 'sinon';
+import { Code, MessageType, Permission, TransactionResolution,
TransactionSource } from '../../proto/apache/rocketmq/v2/definition_pb';
+import {
+ EndTransactionResponse,
+ RecallMessageResponse,
+ RecoverOrphanedTransactionCommand,
+ SendMessageRequest,
+} from '../../proto/apache/rocketmq/v2/service_pb';
+import {
+ BadRequestException,
+ ForbiddenException,
+ InternalErrorException,
+ NotFoundException,
+ TooManyRequestsException,
+ UnsupportedException,
+} from '../../src/exception';
+import { Producer, RecallReceipt } from '../../src/producer';
+import { Endpoints } from '../../src/route';
+import { createSilentLogger } from '../support/fakes';
+import { buildMessagePB, buildRoute, buildSettings, buildStatus } from
'../support/protobuf';
+import { BROKERS, routeResponse, sendResponse, startProducer, TOPIC } from
'./harness';
+
+describe('Producer', () => {
+ let producer: Producer | undefined;
+
+ afterEach(async () => {
+ sinon.restore();
+ await producer?.shutdown();
+ producer = undefined;
+ });
+
+ async function start(options: Parameters<typeof startProducer>[0] = {}) {
+ const started = await startProducer(options);
+ producer = started.producer;
+ return started;
+ }
+
+ function message(options: Record<string, unknown> = {}) {
+ return { topic: TOPIC, body: Buffer.from('body'), ...options };
+ }
+
+ function sentTo(rpc: Awaited<ReturnType<typeof startProducer>>['rpc'], call:
number) {
+ return (rpc.sendMessage.getCall(call).args[0] as Endpoints).facade;
+ }
+
+ function isolatedOf(producer: Producer) {
+ return (producer as unknown as { isolated: Map<string, Endpoints>
}).isolated;
+ }
+
+ describe('send', () => {
+ it('rejects when the producer is not running', async () => {
+ producer = new Producer({ endpoints: '127.0.0.1:8080', namespace: '',
logger: createSilentLogger() });
+ await assert.rejects(producer.send(message()), /Producer is not running
now/);
+ });
+
+ it('returns the receipt without retrying after the first attempt
succeeds', async () => {
+ const { producer, rpc } = await start();
+ rpc.sendMessage.resolves(sendResponse([{ messageId: 'id-1' }]));
+
+ const receipt = await producer.send(message({ tag: 'tag-a', keys: [
'key-a' ] }));
+
+ sinon.assert.calledOnce(rpc.sendMessage);
+ assert.equal(receipt.messageId, 'id-1');
+ assert.equal(receipt.recallHandle, 'recall-handle-0');
+ assert.ok(BROKERS.some(b => b.endpoints === receipt.endpoints.facade));
+ const request = rpc.sendMessage.firstCall.args[1] as SendMessageRequest;
+ const sent = request.getMessagesList()[0];
+ assert.equal(sent.getTopic()!.getName(), TOPIC);
+ assert.equal(sent.getSystemProperties()!.getTag(), 'tag-a');
+ assert.equal(sent.getSystemProperties()!.getMessageType(),
MessageType.NORMAL);
+ assert.equal(sent.getSystemProperties()!.getQueueId(),
receipt.messageQueue.queueId);
+ });
+
+ it('retries immediately on another broker and isolates the failed
endpoints', async () => {
+ const { producer, rpc } = await start();
+ rpc.sendMessage.onFirstCall().rejects(new Error('network failure'));
+ rpc.sendMessage.onSecondCall().resolves(sendResponse());
+
+ await producer.send(message());
+
+ sinon.assert.calledTwice(rpc.sendMessage);
+ assert.notEqual(sentTo(rpc, 0), sentTo(rpc, 1));
+ assert.deepEqual([ ...isolatedOf(producer).keys() ], [ sentTo(rpc, 0) ]);
+ });
+
+ it('retries on a failure status returned by the remote', async () => {
+ const { producer, rpc } = await start();
+ rpc.sendMessage.onFirstCall().resolves(sendResponse([{}],
Code.INTERNAL_ERROR));
+ rpc.sendMessage.onSecondCall().resolves(sendResponse([{ messageId:
'id-2' }]));
+
+ const receipt = await producer.send(message());
+
+ sinon.assert.calledTwice(rpc.sendMessage);
+ assert.equal(receipt.messageId, 'id-2');
+ });
+
+ it('backs off before retrying a throttled request', async () => {
+ const { producer, rpc } = await start();
+ // initial=1s, multiplier=2: the delay before the 2nd attempt is 2s.
+ producer.publishingSettings.sync(buildSettings());
+ rpc.sendMessage.onFirstCall().resolves(sendResponse([{}],
Code.TOO_MANY_REQUESTS));
+ rpc.sendMessage.onSecondCall().resolves(sendResponse());
+ const clock = sinon.useFakeTimers({ toFake: [ 'setTimeout' ] });
+
+ const sending = producer.send(message());
+ await clock.tickAsync(1999);
+ sinon.assert.calledOnce(rpc.sendMessage);
+ await clock.tickAsync(1);
+ await sending;
+ sinon.assert.calledTwice(rpc.sendMessage);
+ });
+
+ it('throws the last error after running out of attempts', async () => {
+ const { producer, rpc } = await start({ maxAttempts: 2 });
+ rpc.sendMessage.onFirstCall().rejects(new Error('first failure'));
+ rpc.sendMessage.onSecondCall().rejects(new Error('second failure'));
+
+ await assert.rejects(producer.send(message()), /second failure/);
+ sinon.assert.calledTwice(rpc.sendMessage);
+ });
+
+ it('surfaces the typed exception of a throttled request after running out
of attempts', async () => {
+ const { producer, rpc } = await start({ maxAttempts: 1 });
+ rpc.sendMessage.resolves(sendResponse([{}], Code.TOO_MANY_REQUESTS));
+
+ await assert.rejects(producer.send(message()), TooManyRequestsException);
+ });
+
+ it('fails without retrying when the receipt count does not match the
message count', async () => {
+ const { producer, rpc } = await start();
+ rpc.sendMessage.resolves(sendResponse([]));
+
+ await assert.rejects(producer.send(message()), (err: Error) => {
+ assert.ok(err instanceof InternalErrorException);
+ assert.match(err.message, /received send receipt's quantity 0 is not
equal to sent message's quantity 1/);
+ return true;
+ });
+ sinon.assert.calledOnce(rpc.sendMessage);
+ assert.equal(isolatedOf(producer).size, 0);
+ });
+
+ it('sends a FIFO message to the queue selected by its message group',
async () => {
+ const { producer, rpc } = await start();
+ rpc.sendMessage.resolves(sendResponse());
+
+ const first = await producer.send(message({ messageGroup: 'order-1' }));
+ const second = await producer.send(message({ messageGroup: 'order-1' }));
+
+ assert.ok(first.messageQueue.equals(second.messageQueue));
+ const sent = (rpc.sendMessage.firstCall.args[1] as
SendMessageRequest).getMessagesList()[0];
+ assert.equal(sent.getSystemProperties()!.getMessageType(),
MessageType.FIFO);
+ assert.equal(sent.getSystemProperties()!.getMessageGroup(), 'order-1');
+ });
+
+ it('rejects a message type the topic does not accept', async () => {
+ const { producer, rpc } = await start();
+ rpc.queryRoute.resolves(routeResponse(undefined, [ MessageType.FIFO ]));
+
+ await assert.rejects(producer.send(message()), /Current message type not
match with topic accept message types/);
+ sinon.assert.notCalled(rpc.sendMessage);
+ });
+
+ it('sends to every master queue over successive sends', async () => {
+ const { producer, rpc } = await start();
+ rpc.queryRoute.resolves(routeResponse(buildRoute({ topic: TOPIC,
brokers: BROKERS, queuesPerBroker: 4 })));
+ rpc.sendMessage.resolves(sendResponse());
+
+ const picked = new Set<string>();
+ for (let i = 0; i < 12; i++) {
+ const receipt = await producer.send(message());
+
picked.add(`${receipt.messageQueue.broker.name}#${receipt.messageQueue.queueId}`);
+ }
+ assert.equal(picked.size, 12);
+ });
+ });
+
+ describe('route update', () => {
+ function refreshRoutes(producer: Producer) {
+ return (producer as unknown as { updateRoutes(): Promise<void>
}).updateRoutes();
+ }
+
+ it('sends to the queues of the refreshed route', async () => {
+ const { producer, rpc } = await start();
+ rpc.sendMessage.resolves(sendResponse());
+ await producer.send(message());
+
+ const moved = [{ name: 'broker-d', endpoints: '127.0.0.1:8084' }];
+ rpc.queryRoute.resolves(routeResponse(buildRoute({ topic: TOPIC,
brokers: moved })));
+ await refreshRoutes(producer);
+
+ for (let i = 0; i < 3; i++) {
+ const receipt = await producer.send(message());
+ assert.equal(receipt.endpoints.facade, '127.0.0.1:8084');
+ }
+ });
+
+ it('keeps the previous queues when the refreshed route has no writable
queue', async () => {
+ const { producer, rpc, logger } = await start();
+ rpc.sendMessage.resolves(sendResponse());
+ await producer.send(message());
+
+ rpc.queryRoute.resolves(routeResponse(buildRoute({ topic: TOPIC,
brokers: BROKERS, permission: Permission.READ })));
+ await refreshRoutes(producer);
+
+ sinon.assert.calledWithMatch(logger.error, /Failed to update publishing
load balancer/);
+ const receipt = await producer.send(message());
+ assert.ok(BROKERS.some(b => b.endpoints === receipt.endpoints.facade));
+ });
+
+ it('fails to send to a topic whose first route has no writable queue',
async () => {
+ const { producer, rpc } = await start();
+ rpc.queryRoute.resolves(routeResponse(buildRoute({ topic: TOPIC,
brokers: BROKERS, permission: Permission.READ })));
+
+ await assert.rejects(producer.send(message()), /No writable message
queue found/);
+ sinon.assert.notCalled(rpc.sendMessage);
+ });
+ });
+
+ describe('recallMessage', () => {
+ it('sends the recall request to the access point and returns the receipt',
async () => {
+ const { producer, rpc } = await start({ namespace: 'ns' });
+ rpc.recallMessage.resolves(new
RecallMessageResponse().setStatus(buildStatus()).setMessageId('id-1'));
+
+ const receipt = await producer.recallMessage(TOPIC, 'handle-1');
+
+ assert.ok(receipt instanceof RecallReceipt);
+ assert.equal(receipt.messageId, 'id-1');
+ const [ endpoints, request ] = rpc.recallMessage.firstCall.args;
+ assert.equal(endpoints.facade, '127.0.0.1:8080');
+ assert.equal(request.getTopic()!.getName(), TOPIC);
+ assert.equal(request.getTopic()!.getResourceNamespace(), 'ns');
+ assert.equal(request.getRecallHandle(), 'handle-1');
+ });
+
+ const cases = [
+ [ Code.BAD_REQUEST, BadRequestException ],
+ [ Code.INVALID_RECEIPT_HANDLE, BadRequestException ],
+ [ Code.FORBIDDEN, ForbiddenException ],
+ [ Code.NOT_FOUND, NotFoundException ],
+ [ Code.TOPIC_NOT_FOUND, NotFoundException ],
+ [ Code.MESSAGE_NOT_FOUND, NotFoundException ],
+ [ Code.TOO_MANY_REQUESTS, TooManyRequestsException ],
+ [ Code.INTERNAL_ERROR, InternalErrorException ],
+ [ Code.UNSUPPORTED, UnsupportedException ],
+ ] as const;
+ for (const [ code, exception ] of cases) {
+ it(`maps status code ${code} to ${exception.name}`, async () => {
+ const { producer, rpc } = await start();
+ rpc.recallMessage.resolves(new
RecallMessageResponse().setStatus(buildStatus(code, 'recall failed')));
+
+ await assert.rejects(producer.recallMessage(TOPIC, 'handle-1'), (err:
Error & { code: number }) => {
+ assert.ok(err instanceof exception, `expected ${exception.name}, got
${err.constructor.name}`);
+ assert.equal(err.code, code);
+ assert.match(err.message, /recall failed/);
+ return true;
+ });
+ });
+ }
+
+ it('rejects when the producer is not running', async () => {
+ producer = new Producer({ endpoints: '127.0.0.1:8080', namespace: '',
logger: createSilentLogger() });
+ await assert.rejects(producer.recallMessage(TOPIC, 'handle-1'),
/Producer is not running now/);
+ });
+
+ it('rejects a blank topic or an empty recall handle', async () => {
+ const { producer, rpc } = await start();
+ await assert.rejects(producer.recallMessage('', 'handle-1'), /Topic is
invalid/);
+ await assert.rejects(producer.recallMessage(' ', 'handle-1'), /Topic is
invalid/);
+ await assert.rejects(producer.recallMessage(TOPIC, ''), /Recall handle
is invalid/);
+ sinon.assert.notCalled(rpc.recallMessage);
+ });
+ });
+
+ describe('onRecoverOrphanedTransactionCommand', () => {
+ const endpoints = new Endpoints('127.0.0.1:8081');
+
+ function command(messagePB = buildMessagePB({ messageId: 'id-1',
messageType: MessageType.TRANSACTION })) {
+ return new
RecoverOrphanedTransactionCommand().setTransactionId('tx-1').setMessage(messagePB);
+ }
+
+ it('ignores the command when no checker is registered', async () => {
+ const { producer, rpc, logger } = await start();
+ await producer.onRecoverOrphanedTransactionCommand(endpoints, command());
+ sinon.assert.notCalled(rpc.endTransaction);
+ sinon.assert.calledWithMatch(logger.error, /No transaction checker
registered/);
+ });
+
+ it('ignores the command when the message cannot be decoded', async () => {
+ const check = sinon.stub().resolves(TransactionResolution.COMMIT);
+ const { producer, rpc, logger } = await start({ checker: { check } });
+ const messagePB = buildMessagePB({ messageId: 'id-1' });
+ messagePB.getSystemProperties()!.clearBodyDigest();
+
+ await producer.onRecoverOrphanedTransactionCommand(endpoints,
command(messagePB));
+
+ sinon.assert.notCalled(check);
+ sinon.assert.notCalled(rpc.endTransaction);
+ sinon.assert.calledWithMatch(logger.error, /Failed to decode message/);
+ });
+
+ it('ignores a command without a message instead of throwing', async () => {
+ const check = sinon.stub().resolves(TransactionResolution.COMMIT);
+ const { producer, rpc, logger } = await start({ checker: { check } });
+
+ await producer.onRecoverOrphanedTransactionCommand(endpoints,
+ new RecoverOrphanedTransactionCommand().setTransactionId('tx-1'));
+
+ sinon.assert.notCalled(check);
+ sinon.assert.notCalled(rpc.endTransaction);
+ sinon.assert.calledWithMatch(logger.error, /message is absent/);
+ });
+
+ for (const resolution of [
TransactionResolution.TRANSACTION_RESOLUTION_UNSPECIFIED, null ]) {
+ it(`does not end the transaction when the checker returns
${resolution}`, async () => {
+ const check = sinon.stub().resolves(resolution);
+ const { producer, rpc } = await start({ checker: { check } });
+
+ await producer.onRecoverOrphanedTransactionCommand(endpoints,
command());
+
+ sinon.assert.calledOnce(check);
+ sinon.assert.notCalled(rpc.endTransaction);
+ });
+ }
+
+ it('ends the transaction with the checker resolution as a server check',
async () => {
+ const check = sinon.stub().resolves(TransactionResolution.COMMIT);
+ const { producer, rpc } = await start({ checker: { check } });
+ rpc.endTransaction.resolves(new
EndTransactionResponse().setStatus(buildStatus()));
+
+ await producer.onRecoverOrphanedTransactionCommand(endpoints, command());
+
+ assert.equal(check.firstCall.args[0].messageId, 'id-1');
+ const [ target, request ] = rpc.endTransaction.firstCall.args;
+ assert.equal(target, endpoints);
+ assert.equal(request.getMessageId(), 'id-1');
+ assert.equal(request.getTransactionId(), 'tx-1');
+ assert.equal(request.getTopic()!.getName(), 'test-topic');
+ assert.equal(request.getResolution(), TransactionResolution.COMMIT);
+ assert.equal(request.getSource(), TransactionSource.SOURCE_SERVER_CHECK);
+ });
+
+ it('logs instead of throwing when the checker fails', async () => {
+ const check = sinon.stub().rejects(new Error('checker failure'));
+ const { producer, rpc, logger } = await start({ checker: { check } });
+
+ await producer.onRecoverOrphanedTransactionCommand(endpoints, command());
+
+ sinon.assert.notCalled(rpc.endTransaction);
+ sinon.assert.calledWithMatch(logger.error, /Exception raised while
checking the transaction/);
+ });
+ });
+});
diff --git a/nodejs/test/producer/PublishingLoadBalancer.test.ts
b/nodejs/test/producer/PublishingLoadBalancer.test.ts
index 6e2c0187..6871401a 100644
--- a/nodejs/test/producer/PublishingLoadBalancer.test.ts
+++ b/nodejs/test/producer/PublishingLoadBalancer.test.ts
@@ -24,7 +24,7 @@
import * as assert from 'node:assert';
import { PublishingLoadBalancer } from '../../src/producer';
-import { TopicRouteData } from '../../src/route';
+import { Endpoints, MessageQueue, TopicRouteData } from '../../src/route';
import { calculateStringSipHash24 } from '../../src/util';
import {
MessageQueue as MessageQueuePB,
@@ -34,10 +34,10 @@ import {
Permission,
AddressScheme,
} from '../../proto/apache/rocketmq/v2/definition_pb';
+import { buildRoute } from '../support/protobuf';
describe('takeMessageQueueByMessageGroup floorMod semantics (C-1)', () => {
- // One queue (queueId=0, the writable master queue) per broker across
queueCount brokers,
- // since PublishingLoadBalancer only keeps queues with queueId ===
MASTER_BROKER_ID (0).
+ // One writable master queue per broker across queueCount brokers.
// The returned queue is identified by its broker endpoints port (10911 +
expected index).
function buildLoadBalancer(queueCount: number): PublishingLoadBalancer {
const pbs: MessageQueuePB[] = [];
@@ -90,3 +90,110 @@ describe('takeMessageQueueByMessageGroup floorMod semantics
(C-1)', () => {
assert.strictEqual(mq.broker.endpoints.facade, '127.0.0.1:' + (10911 +
expectedIndex));
});
});
+
+describe('PublishingLoadBalancer queue selection', () => {
+ const TWO_BROKERS = [
+ { name: 'broker-a', endpoints: '127.0.0.1:8081' },
+ { name: 'broker-b', endpoints: '127.0.0.1:8082' },
+ ];
+
+ function queuePB(brokerName: string, brokerId: number, port: number,
queueId: number, permission: Permission) {
+ return new MessageQueuePB().setId(queueId)
+ .setTopic(new ResourcePB().setName('test-topic'))
+ .setBroker(new BrokerPB().setName(brokerName).setId(brokerId)
+ .setEndpoints(new Endpoints(`127.0.0.1:${port}`).toProtobuf()))
+ .setPermission(permission);
+ }
+
+ function key(mq: MessageQueue) {
+ return `${mq.broker.name}#${mq.broker.id}#${mq.queueId}`;
+ }
+
+ function rotate(loadBalancer: PublishingLoadBalancer, times: number) {
+ const picked = new Set<string>();
+ for (let i = 0; i < times; i++) {
+ picked.add(key(loadBalancer.takeMessageQueues(new Map(), 1)[0]));
+ }
+ return picked;
+ }
+
+ it('rotates over every writable queue of every master broker', () => {
+ const loadBalancer = new PublishingLoadBalancer(buildRoute({ brokers:
TWO_BROKERS, queuesPerBroker: 4 }), 0);
+ const picked = rotate(loadBalancer, 8);
+ assert.strictEqual(picked.size, 8, `only picked ${JSON.stringify([
...picked ])}`);
+ });
+
+ it('spreads FIFO message groups over every master queue', () => {
+ const loadBalancer = new PublishingLoadBalancer(buildRoute({ brokers:
TWO_BROKERS, queuesPerBroker: 4 }));
+ const picked = new Set<string>();
+ for (let i = 0; i < 200; i++) {
+
picked.add(key(loadBalancer.takeMessageQueueByMessageGroup(`group-${i}`)));
+ }
+ assert.strictEqual(picked.size, 8, `only picked ${JSON.stringify([
...picked ])}`);
+ });
+
+ it('excludes queues of slave brokers by broker id', () => {
+ const loadBalancer = new PublishingLoadBalancer(buildRoute({
+ queuesPerBroker: 2,
+ brokers: [
+ { name: 'broker-a', id: 0, endpoints: '127.0.0.1:8081' },
+ { name: 'broker-a', id: 1, endpoints: '127.0.0.1:8082' },
+ ],
+ }), 0);
+ assert.deepStrictEqual([ ...rotate(loadBalancer, 4) ].sort(), [
'broker-a#0#0', 'broker-a#0#1' ]);
+ });
+
+ it('keeps only writable queues', () => {
+ const loadBalancer = new PublishingLoadBalancer(new TopicRouteData([
+ queuePB('broker-a', 0, 8081, 0, Permission.READ),
+ queuePB('broker-a', 0, 8081, 1, Permission.WRITE),
+ queuePB('broker-a', 0, 8081, 2, Permission.READ_WRITE),
+ queuePB('broker-a', 0, 8081, 3, Permission.NONE),
+ ]), 0);
+ assert.deepStrictEqual([ ...rotate(loadBalancer, 4) ].sort(), [
'broker-a#0#1', 'broker-a#0#2' ]);
+ });
+
+ it('throws when no writable master queue exists', () => {
+ assert.throws(() => new PublishingLoadBalancer(buildRoute({ permission:
Permission.READ })), /No writable message queue found/);
+ assert.throws(() => new PublishingLoadBalancer(buildRoute({ brokerId: 1
})), /No writable message queue found/);
+ assert.throws(() => new PublishingLoadBalancer(buildRoute({ brokers: []
})), /No writable message queue found/);
+ });
+
+ it('takes one queue per broker and skips isolated endpoints', () => {
+ const brokers = [ ...TWO_BROKERS, { name: 'broker-c', endpoints:
'127.0.0.1:8083' }];
+ const loadBalancer = new PublishingLoadBalancer(buildRoute({ brokers,
queuesPerBroker: 2 }), 0);
+ const candidates = loadBalancer.takeMessageQueues(new Map(), 3);
+ assert.deepStrictEqual(candidates.map(mq => mq.broker.name).sort(), [
'broker-a', 'broker-b', 'broker-c' ]);
+
+ const isolated = new Map([[ '127.0.0.1:8082', new
Endpoints('127.0.0.1:8082') ]]);
+ const healthy = loadBalancer.takeMessageQueues(isolated, 3);
+ assert.deepStrictEqual(healthy.map(mq => mq.broker.name).sort(), [
'broker-a', 'broker-c' ]);
+ });
+
+ it('falls back to isolated endpoints when every endpoint is isolated', () =>
{
+ const loadBalancer = new PublishingLoadBalancer(buildRoute({ brokers:
TWO_BROKERS }), 0);
+ const isolated = new Map(TWO_BROKERS.map(b => [ b.endpoints, new
Endpoints(b.endpoints) ]));
+ const candidates = loadBalancer.takeMessageQueues(isolated, 2);
+ assert.deepStrictEqual(candidates.map(mq => mq.broker.name).sort(), [
'broker-a', 'broker-b' ]);
+ });
+
+ it('keeps the rotation position across route updates', () => {
+ const route = buildRoute({ brokers: TWO_BROKERS, queuesPerBroker: 2 });
+ const loadBalancer = new PublishingLoadBalancer(route, 0);
+ loadBalancer.takeMessageQueues(new Map(), 1);
+ const updated = loadBalancer.update(route);
+ const expected = new PublishingLoadBalancer(route,
1).takeMessageQueues(new Map(), 1)[0];
+ assert.ok(updated.takeMessageQueues(new Map(), 1)[0].equals(expected));
+ assert.ok(updated.equals(loadBalancer));
+ });
+
+ it('routes the same message group to the same queue', () => {
+ const route = buildRoute({ brokers: TWO_BROKERS, queuesPerBroker: 4 });
+ const loadBalancer = new PublishingLoadBalancer(route);
+ const first = loadBalancer.takeMessageQueueByMessageGroup('order-1');
+ for (let i = 0; i < 10; i++) {
+
assert.ok(loadBalancer.takeMessageQueueByMessageGroup('order-1').equals(first));
+ }
+
assert.ok(loadBalancer.update(route).takeMessageQueueByMessageGroup('order-1').equals(first));
+ });
+});
diff --git a/nodejs/test/producer/PublishingSettings.test.ts
b/nodejs/test/producer/PublishingSettings.test.ts
new file mode 100644
index 00000000..b28a5d1b
--- /dev/null
+++ b/nodejs/test/producer/PublishingSettings.test.ts
@@ -0,0 +1,84 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { strict as assert } from 'node:assert';
+import { ClientType, Publishing, Subscription } from
'../../proto/apache/rocketmq/v2/definition_pb';
+import { PublishingSettings } from '../../src/producer';
+import { ExponentialBackoffRetryPolicy } from '../../src/retry';
+import { Endpoints } from '../../src/route';
+import { buildSettings } from '../support/protobuf';
+
+describe('PublishingSettings', () => {
+ const accessPoint = new Endpoints('127.0.0.1:8080');
+
+ function create(topics = new Set([ 'topic-a', 'topic-b' ])) {
+ return new PublishingSettings('ns', 'client-id', accessPoint,
+ ExponentialBackoffRetryPolicy.immediatelyRetryPolicy(3), 3000, topics);
+ }
+
+ it('starts with the default publishing settings', () => {
+ const settings = create();
+ assert.equal(settings.maxBodySizeBytes, 4 * 1024 * 1024);
+ assert.equal(settings.isValidateMessageType(), true);
+ assert.equal(settings.getRetryPolicy()!.getNextAttemptDelay(2), 0);
+ });
+
+ it('syncs backoff, message type validation and max body size from the
remote', () => {
+ const settings = create();
+ settings.sync(buildSettings({
+ publishing: new
Publishing().setMaxBodySize(1024).setValidateMessageType(false),
+ }));
+
+ assert.equal(settings.maxBodySizeBytes, 1024);
+ assert.equal(settings.isValidateMessageType(), false);
+ const retryPolicy = settings.getRetryPolicy()!;
+ // Max attempts stay local; the backoff comes from the remote (initial=1s,
max=10s, multiplier=2).
+ assert.equal(retryPolicy.getMaxAttempts(), 3);
+ assert.equal(retryPolicy.getNextAttemptDelay(1), 1000);
+ assert.equal(retryPolicy.getNextAttemptDelay(2), 2000);
+ assert.equal(retryPolicy.getNextAttemptDelay(10), 10000);
+ });
+
+ it('ignores settings issued for another client type', () => {
+ const settings = create();
+ settings.sync(buildSettings({ clientType: ClientType.SIMPLE_CONSUMER,
subscription: new Subscription() }));
+
+ assert.equal(settings.maxBodySizeBytes, 4 * 1024 * 1024);
+ assert.equal(settings.isValidateMessageType(), true);
+ assert.equal(settings.getRetryPolicy()!.getNextAttemptDelay(2), 0);
+ });
+
+ it('converts to protobuf with every publishing field', () => {
+ const pb = create().toProtobuf();
+
+ assert.equal(pb.getClientType(), ClientType.PRODUCER);
+ assert.deepEqual(pb.getAccessPoint()!.toObject(),
accessPoint.toProtobuf().toObject());
+ assert.equal(pb.getRequestTimeout()!.getSeconds(), 3);
+ assert.ok(pb.getUserAgent());
+ const publishing = pb.getPublishing()!;
+ assert.equal(publishing.getValidateMessageType(), true);
+ assert.deepEqual(publishing.getTopicsList().map(t => [ t.getName(),
t.getResourceNamespace() ]),
+ [[ 'topic-a', 'ns' ], [ 'topic-b', 'ns' ]]);
+ });
+
+ it('includes topics added after construction', () => {
+ const topics = new Set<string>();
+ const settings = create(topics);
+ topics.add('topic-c');
+
assert.deepEqual(settings.toProtobuf().getPublishing()!.getTopicsList().map(t
=> t.getName()), [ 'topic-c' ]);
+ });
+});
diff --git a/nodejs/test/producer/Transaction.test.ts
b/nodejs/test/producer/Transaction.test.ts
new file mode 100644
index 00000000..fcd24218
--- /dev/null
+++ b/nodejs/test/producer/Transaction.test.ts
@@ -0,0 +1,154 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { strict as assert } from 'node:assert';
+import * as sinon from 'sinon';
+import { MessageType, TransactionResolution, TransactionSource } from
'../../proto/apache/rocketmq/v2/definition_pb';
+import { EndTransactionResponse, SendMessageRequest } from
'../../proto/apache/rocketmq/v2/service_pb';
+import { ILogger } from '../../src/client';
+import { Producer, Transaction } from '../../src/producer';
+import { buildStatus } from '../support/protobuf';
+import { sendResponse, startProducer, TOPIC } from './harness';
+
+describe('Transaction', () => {
+ let producer: Producer | undefined;
+ const checker = { check: async () => TransactionResolution.COMMIT };
+
+ afterEach(async () => {
+ sinon.restore();
+ await producer?.shutdown();
+ producer = undefined;
+ });
+
+ async function start(logger?: ILogger) {
+ const started = await startProducer({ checker, ...(logger ? { logger } :
{}) });
+ producer = started.producer;
+ started.rpc.sendMessage.resolves(sendResponse([{ messageId: 'id-1',
transactionId: 'tx-1' }]));
+ started.rpc.endTransaction.resolves(new
EndTransactionResponse().setStatus(buildStatus()));
+ return started;
+ }
+
+ function message() {
+ return { topic: TOPIC, body: Buffer.from('body') };
+ }
+
+ for (const [ name, resolution ] of [[ 'commit', TransactionResolution.COMMIT
], [ 'rollback', TransactionResolution.ROLLBACK ]] as const) {
+ it(`${name} ends the sent message with resolution ${resolution}`, async ()
=> {
+ const { producer, rpc } = await start();
+ const transaction = producer.beginTransaction();
+ const receipt = await producer.send(message(), transaction);
+
+ await transaction[name]();
+
+ const sent = (rpc.sendMessage.firstCall.args[1] as
SendMessageRequest).getMessagesList()[0];
+ assert.equal(sent.getSystemProperties()!.getMessageType(),
MessageType.TRANSACTION);
+ sinon.assert.calledOnce(rpc.endTransaction);
+ const [ endpoints, request ] = rpc.endTransaction.firstCall.args;
+ assert.equal(endpoints, receipt.endpoints);
+ assert.equal(request.getMessageId(), 'id-1');
+ assert.equal(request.getTransactionId(), 'tx-1');
+ assert.equal(request.getTopic()!.getName(), TOPIC);
+ assert.equal(request.getResolution(), resolution);
+ assert.equal(request.getSource(), TransactionSource.SOURCE_CLIENT);
+ });
+
+ it(`${name} rejects an empty transaction`, async () => {
+ const { producer, rpc } = await start();
+ await assert.rejects(producer.beginTransaction()[name](), /Transactional
message has not been sent yet/);
+ sinon.assert.notCalled(rpc.endTransaction);
+ });
+
+ it(`${name} works with a logger without debug`, async () => {
+ const logger = { info: sinon.stub(), warn: sinon.stub(), error:
sinon.stub() };
+ const { producer, rpc } = await start(logger);
+ const transaction = producer.beginTransaction();
+ await producer.send(message(), transaction);
+
+ await transaction[name]();
+
+ sinon.assert.calledOnce(rpc.endTransaction);
+ });
+ }
+
+ it('logs through the logger of the producer', async () => {
+ const { producer, logger } = await start();
+ const transaction = producer.beginTransaction();
+ await producer.send(message(), transaction);
+
+ await transaction.commit();
+
+ sinon.assert.calledWith(logger.info, 'Begin to commit transaction,
messageCount=%d, clientId=%s', 1, producer.clientId);
+ sinon.assert.calledWith(logger.debug, 'Commit transaction successfully,
messageCount=%d, clientId=%s', 1, producer.clientId);
+ });
+
+ it('rejects more messages than the threshold', async () => {
+ const { producer, rpc } = await start();
+ const transaction = producer.beginTransaction();
+ await producer.send(message(), transaction);
+
+ await assert.rejects(producer.send(message(), transaction), /Message in
transaction has exceeded the threshold=1/);
+ sinon.assert.calledOnce(rpc.sendMessage);
+ });
+
+ it('retries a failed transactional message and ends it on the broker that
accepted it', async () => {
+ const { producer, rpc } = await start();
+ rpc.sendMessage.onFirstCall().rejects(new Error('network failure'));
+ const transaction = producer.beginTransaction();
+
+ const receipt = await producer.send(message(), transaction);
+ await transaction.commit();
+
+ sinon.assert.calledTwice(rpc.sendMessage);
+ const [ failed, accepted ] = rpc.sendMessage.getCalls().map(call =>
call.args[0].facade);
+ assert.notEqual(failed, accepted);
+ assert.equal(receipt.endpoints.facade, accepted);
+ assert.equal(rpc.endTransaction.firstCall.args[0].facade, accepted);
+ });
+
+ it('throws the last error after running out of attempts for a transactional
message', async () => {
+ const { producer, rpc } = await start();
+ rpc.sendMessage.rejects(new Error('network failure'));
+
+ await assert.rejects(producer.send(message(),
producer.beginTransaction()), /network failure/);
+ sinon.assert.calledThrice(rpc.sendMessage);
+ });
+
+ it('rejects transactional messages with FIFO, delay, lite or priority
semantics', async () => {
+ const { producer, rpc } = await start();
+ for (const extra of [{ messageGroup: 'g' }, { delay: 1000 }, { liteTopic:
'lite' }, { priority: 1 }]) {
+ await assert.rejects(producer.send({ ...message(), ...extra },
producer.beginTransaction()),
+ /Transactional message should not set messageGroup, liteTopic,
deliveryTimestamp or priority/);
+ }
+ sinon.assert.notCalled(rpc.sendMessage);
+ });
+
+ it('cannot begin without a checker or before startup', async () => {
+ const started = await startProducer();
+ producer = started.producer;
+ assert.throws(() => started.producer.beginTransaction(), /Transaction
checker should not be null/);
+
+ const stopped = new Producer({ endpoints: '127.0.0.1:8080', namespace: '',
checker, logger: started.logger });
+ assert.throws(() => stopped.beginTransaction(), /Producer is not running
now/);
+ await stopped.shutdown();
+ });
+
+ it('keeps the single-argument constructor', async () => {
+ const { producer } = await start();
+ const transaction = new Transaction(producer);
+ assert.ok(transaction.tryAddMessage(message()).messageId);
+ });
+});
diff --git a/nodejs/test/producer/harness.ts b/nodejs/test/producer/harness.ts
new file mode 100644
index 00000000..d205aa94
--- /dev/null
+++ b/nodejs/test/producer/harness.ts
@@ -0,0 +1,68 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Code, MessageType } from
'../../proto/apache/rocketmq/v2/definition_pb';
+import {
+ NotifyClientTerminationResponse,
+ QueryRouteResponse,
+ SendMessageResponse,
+ SendResultEntry,
+} from '../../proto/apache/rocketmq/v2/service_pb';
+import { Producer, ProducerOptions } from '../../src/producer';
+import { TopicRouteData } from '../../src/route';
+import { createSilentLogger, FakeTelemetryStream, installFakeRpcClientManager
} from '../support/fakes';
+import { buildRoute, buildStatus } from '../support/protobuf';
+
+export const TOPIC = 'test-topic';
+export const BROKERS = [
+ { name: 'broker-a', endpoints: '127.0.0.1:8081' },
+ { name: 'broker-b', endpoints: '127.0.0.1:8082' },
+ { name: 'broker-c', endpoints: '127.0.0.1:8083' },
+];
+const ALL_MESSAGE_TYPES = [
+ MessageType.NORMAL, MessageType.FIFO, MessageType.DELAY,
MessageType.TRANSACTION,
+ MessageType.PRIORITY, MessageType.LITE,
+];
+
+export function routeResponse(route: TopicRouteData = buildRoute({ topic:
TOPIC, brokers: BROKERS }),
+ acceptMessageTypes = ALL_MESSAGE_TYPES) {
+ return new QueryRouteResponse().setStatus(buildStatus())
+ .setMessageQueuesList(route.messageQueues.map(mq =>
mq.toProtobuf().setAcceptMessageTypesList(acceptMessageTypes)));
+}
+
+export function sendResponse(entries: Array<{ messageId?: string;
transactionId?: string; code?: Code }> = [{}],
+ code = Code.OK) {
+ return new SendMessageResponse().setStatus(buildStatus(code, 'remote
status'))
+ .setEntriesList(entries.map((entry, i) => new SendResultEntry()
+ .setStatus(buildStatus(entry.code ?? code, 'remote status'))
+ .setMessageId(entry.messageId ?? `message-id-${i}`)
+ .setTransactionId(entry.transactionId ?? `transaction-id-${i}`)
+ .setRecallHandle(`recall-handle-${i}`)
+ .setOffset(i)));
+}
+
+// Without configured topics, startup() does not wait for server settings;
routes are queried on the first send.
+export async function startProducer(options: Partial<ProducerOptions> = {}) {
+ const logger = createSilentLogger();
+ const producer = new Producer({ endpoints: '127.0.0.1:8080', namespace: '',
logger, ...options });
+ const rpc = installFakeRpcClientManager(producer);
+ rpc.queryRoute.resolves(routeResponse());
+ rpc.telemetry.callsFake(() => new FakeTelemetryStream().asGrpcStream());
+ rpc.notifyClientTermination.resolves(new
NotifyClientTerminationResponse().setStatus(buildStatus()));
+ await producer.startup();
+ return { producer, rpc, logger };
+}