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 45f27a31 fix(nodejs): harden simple consumers and add offline coverage 
(#1505)
45f27a31 is described below

commit 45f27a318ce10b25804095e16bb9bfcf56b0da46
Author: Quan <[email protected]>
AuthorDate: Wed Nov 18 21:18:54 2026 +0800

    fix(nodejs): harden simple consumers and add offline coverage (#1505)
    
    - Select readable master queues by broker id and report empty routes clearly
    - Clean up consumer casts, warn on unknown receive content, and refresh 
handles internally
    - Validate retry attempts and OffsetOption number inputs without changing 
public signatures
    - Add 75 offline tests covering requests, hooks, subscriptions, retries, 
settings, and offsets
---
 nodejs/src/consumer/Consumer.ts                    |  13 +-
 nodejs/src/consumer/OffsetOption.ts                |  13 +-
 nodejs/src/consumer/SimpleConsumer.ts              |  43 ++--
 nodejs/src/consumer/SubscriptionLoadBalancer.ts    |   4 +-
 nodejs/test/consumer/Consumer.test.ts              | 279 +++++++++++++++++++++
 nodejs/test/consumer/ConsumerSettings.test.ts      |  99 ++++++++
 nodejs/test/consumer/OffsetOption.test.ts          |  63 +++++
 nodejs/test/consumer/SimpleConsumer.test.ts        | 263 +++++++++++++++++++
 .../test/consumer/SubscriptionLoadBalancer.test.ts |  87 +++++++
 9 files changed, 831 insertions(+), 33 deletions(-)

diff --git a/nodejs/src/consumer/Consumer.ts b/nodejs/src/consumer/Consumer.ts
index 233db92c..e5c94909 100644
--- a/nodejs/src/consumer/Consumer.ts
+++ b/nodejs/src/consumer/Consumer.ts
@@ -72,7 +72,7 @@ export abstract class Consumer extends BaseClient {
 
     try {
       this.logger.debug?.('Receiving messages from broker, topic=%s, 
endpoints=%s, batchSize=%d, clientId=%s',
-        request.getMessageQueue()?.getTopic()?.getName(), endpoints, 
request.getBatchSize(), (this as any).clientId);
+        request.getMessageQueue()?.getTopic()?.getName(), endpoints, 
request.getBatchSize(), this.clientId);
 
       const responses = await this.rpcClientManager.receiveMessage(endpoints, 
request, timeout);
       const messageList: Message[] = [];
@@ -90,8 +90,8 @@ export abstract class Consumer extends BaseClient {
             transportDeliveryTimestamp = 
response.getDeliveryTimestamp()?.toDate();
             break;
           default:
-            // this.logger.warn("[Bug] Not recognized content for receive 
message response, mq={}, " +
-            //                 "clientId={}, response={}", mq, clientId, 
response);
+            this.logger.warn('Not recognized content for receive message 
response, mq=%s, clientId=%s, response=%j',
+              mq, this.clientId, response.toObject());
         }
       }
 
@@ -99,7 +99,7 @@ export abstract class Consumer extends BaseClient {
 
       if (messageList.length > 0) {
         this.logger.debug?.('Received %d messages successfully, topic=%s, 
endpoints=%s, clientId=%s',
-          messageList.length, 
request.getMessageQueue()?.getTopic()?.getName(), endpoints, (this as 
any).clientId);
+          messageList.length, 
request.getMessageQueue()?.getTopic()?.getName(), endpoints, this.clientId);
       }
 
       const messages = messageList.map(message => new MessageView(message, mq, 
transportDeliveryTimestamp));
@@ -107,7 +107,7 @@ export abstract class Consumer extends BaseClient {
       return messages;
     } catch (err) {
       this.logger.error('Failed to receive messages, topic=%s, endpoints=%s, 
clientId=%s, error=%s',
-        request.getMessageQueue()?.getTopic()?.getName(), endpoints, (this as 
any).clientId, err);
+        request.getMessageQueue()?.getTopic()?.getName(), endpoints, 
this.clientId, err);
       this.doAfter(MessageInterceptorContextImpl.withStatus(context, 
MessageHookPointsStatus.ERROR), []);
       throw err;
     }
@@ -131,7 +131,6 @@ export abstract class Consumer extends BaseClient {
     let hookStatus = MessageHookPointsStatus.OK;
     try {
       const res = await this.rpcClientManager.ackMessage(endpoints, request, 
this.requestTimeout);
-      // FIXME: handle fail ack
       const response = res.toObject();
       hookStatus = response.status?.code === Code.OK ? 
MessageHookPointsStatus.OK : MessageHookPointsStatus.ERROR;
       StatusChecker.check(response.status);
@@ -241,7 +240,7 @@ export abstract class Consumer extends BaseClient {
    * @return true if this is a LITE_PUSH_CONSUMER or LITE_SIMPLE_CONSUMER
    */
   protected isLiteConsumer(): boolean {
-    const clientType = (this as any).getClientType?.();
+    const clientType = this.getClientType();
     return clientType === ClientType.LITE_PUSH_CONSUMER || clientType === 
ClientType.LITE_SIMPLE_CONSUMER;
   }
 }
diff --git a/nodejs/src/consumer/OffsetOption.ts 
b/nodejs/src/consumer/OffsetOption.ts
index 275c8fc5..5b4aca63 100644
--- a/nodejs/src/consumer/OffsetOption.ts
+++ b/nodejs/src/consumer/OffsetOption.ts
@@ -63,6 +63,13 @@ export class OffsetOption {
     this.value = value;
   }
 
+  private static toBigInt(value: number | bigint, name: string): bigint {
+    if (typeof value === 'number' && !Number.isSafeInteger(value)) {
+      throw new RangeError(`${name} must be a safe integer when provided as 
number`);
+    }
+    return typeof value === 'number' ? BigInt(value) : value;
+  }
+
   /**
    * Create an OffsetOption from a specific offset.
    *
@@ -71,7 +78,7 @@ export class OffsetOption {
    * @throws Error if offset is negative
    */
   static ofOffset(offset: number | bigint): OffsetOption {
-    const value = typeof offset === 'number' ? BigInt(offset) : offset;
+    const value = OffsetOption.toBigInt(offset, 'offset');
     if (value < BigInt(0)) {
       throw new Error('offset must be greater than or equal to 0');
     }
@@ -86,7 +93,7 @@ export class OffsetOption {
    * @throws Error if tailN is negative
    */
   static ofTailN(tailN: number | bigint): OffsetOption {
-    const value = typeof tailN === 'number' ? BigInt(tailN) : tailN;
+    const value = OffsetOption.toBigInt(tailN, 'tailN');
     if (value < BigInt(0)) {
       throw new Error('tailN must be greater than or equal to 0');
     }
@@ -101,7 +108,7 @@ export class OffsetOption {
    * @throws Error if timestamp is negative
    */
   static ofTimestamp(timestamp: number | bigint): OffsetOption {
-    const value = typeof timestamp === 'number' ? BigInt(timestamp) : 
timestamp;
+    const value = OffsetOption.toBigInt(timestamp, 'timestamp');
     if (value < BigInt(0)) {
       throw new Error('timestamp must be greater than or equal to 0');
     }
diff --git a/nodejs/src/consumer/SimpleConsumer.ts 
b/nodejs/src/consumer/SimpleConsumer.ts
index 7efe816c..be657828 100644
--- a/nodejs/src/consumer/SimpleConsumer.ts
+++ b/nodejs/src/consumer/SimpleConsumer.ts
@@ -46,6 +46,11 @@ export interface SimpleConsumerOptions extends 
ConsumerOptions {
   awaitDuration?: number;
   /**
    * max retry attempts for temporary errors (e.g., internal server error), 
default is 3
+   * 包含首次请求,必须为正安全整数;设为 1 时不重试。
+   * 与 Java 的单次 receive 不同,Node 保留已有重试配置。
+   * 路由就绪后的 RPC 等待及退避预算最多为
+   * maxRetryAttempts * (requestTimeout + awaitDuration) + (maxRetryAttempts - 
1) * 1000ms,
+   * 不包含路由查询、消息解码、hook 和事件循环调度耗时。
    */
   maxRetryAttempts?: number;
 }
@@ -65,6 +70,10 @@ export class SimpleConsumer extends Consumer {
     if (!(options.subscriptions instanceof Map) || options.subscriptions.size 
=== 0) {
       throw new TypeError('subscriptions must be a non-empty Map');
     }
+    if (options.maxRetryAttempts !== undefined &&
+      (!Number.isSafeInteger(options.maxRetryAttempts) || 
options.maxRetryAttempts <= 0)) {
+      throw new TypeError('maxRetryAttempts must be a positive safe integer');
+    }
     options.topics = Array.from(options.subscriptions.keys());
     super(options);
     for (const [ topic, filter ] of options.subscriptions.entries()) {
@@ -158,31 +167,18 @@ export class SimpleConsumer extends Consumer {
     const request = this.wrapReceiveMessageRequest(maxMessageNum, mq, 
filterExpression,
       invisibleDuration, this.#awaitDuration);
 
-    // Retry logic for temporary errors
-    let lastError: Error | undefined;
-    for (let attempt = 1; attempt <= this.#maxRetryAttempts; attempt++) {
+    for (let attempt = 1; ; attempt++) {
       try {
         return await this.receiveMessage(request, mq, this.#awaitDuration);
       } catch (err) {
-        lastError = err as Error;
-
-        // Only retry on internal server errors (temporary errors)
-        if (err instanceof InternalErrorException) {
-          if (attempt < this.#maxRetryAttempts) {
-            this.logger.warn('Received temporary error from server, will retry 
after %dms, attempt=%d/%d, topic=%s, clientId=%s, error=%s',
-              RETRY_DELAY_MS, attempt, this.#maxRetryAttempts, topic, 
this.clientId, err.message);
-            await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));
-            continue;
-          }
+        if (!(err instanceof InternalErrorException) || attempt >= 
this.#maxRetryAttempts) {
+          throw err;
         }
-
-        // For non-retryable errors or max attempts reached, throw immediately
-        throw err;
+        this.logger.warn('Received temporary error from server, will retry 
after %dms, attempt=%d/%d, topic=%s, clientId=%s, error=%s',
+          RETRY_DELAY_MS, attempt, this.#maxRetryAttempts, topic, 
this.clientId, err.message);
+        await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));
       }
     }
-
-    // This should never be reached, but just in case
-    throw lastError;
   }
 
   async ack(message: MessageView) {
@@ -197,8 +193,13 @@ export class SimpleConsumer extends Consumer {
       throw new Error('Simple consumer is not running, cannot change invisible 
duration');
     }
     const response = await this.invisibleDuration(message, invisibleDuration);
-    // Refresh receipt handle manually
-    (message as any).receiptHandle = response;
+    this.#refreshReceiptHandle(message, response);
+  }
+
+  #refreshReceiptHandle(message: MessageView, receiptHandle: string) {
+    // receiptHandle 对调用方只读,SDK 在成功续期后内部更新;保留 MessageView 的公开签名。
+    const mutableMessage = message as { receiptHandle: string };
+    mutableMessage.receiptHandle = receiptHandle;
   }
 
   #nextTopic() {
diff --git a/nodejs/src/consumer/SubscriptionLoadBalancer.ts 
b/nodejs/src/consumer/SubscriptionLoadBalancer.ts
index f191f24a..e208b597 100644
--- a/nodejs/src/consumer/SubscriptionLoadBalancer.ts
+++ b/nodejs/src/consumer/SubscriptionLoadBalancer.ts
@@ -26,12 +26,12 @@ export class SubscriptionLoadBalancer {
 
   constructor(topicRouteData: TopicRouteData, index?: number) {
     this.#messageQueues = topicRouteData.messageQueues.filter(mq => {
-      return mq.queueId === MASTER_BROKER_ID && (mq.permission === 
Permission.READ || mq.permission === Permission.READ_WRITE);
+      return mq.broker.id === MASTER_BROKER_ID && (mq.permission === 
Permission.READ || mq.permission === Permission.READ_WRITE);
     });
-    this.#index = index === undefined ? randomInt(this.#messageQueues.length) 
: index;
     if (this.#messageQueues.length === 0) {
       throw new Error(`No readable message queue found, 
topicRouteData=${JSON.stringify(topicRouteData)}`);
     }
+    this.#index = index === undefined ? randomInt(this.#messageQueues.length) 
: index;
   }
 
   update(topicRouteData: TopicRouteData) {
diff --git a/nodejs/test/consumer/Consumer.test.ts 
b/nodejs/test/consumer/Consumer.test.ts
new file mode 100644
index 00000000..70653915
--- /dev/null
+++ b/nodejs/test/consumer/Consumer.test.ts
@@ -0,0 +1,279 @@
+/**
+ * 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 { Timestamp } from 'google-protobuf/google/protobuf/timestamp_pb';
+import { ClientType, Code } from 
'../../proto/apache/rocketmq/v2/definition_pb';
+import {
+  AckMessageRequest, AckMessageResponse, ChangeInvisibleDurationRequest, 
ChangeInvisibleDurationResponse,
+  ForwardMessageToDeadLetterQueueRequest, 
ForwardMessageToDeadLetterQueueResponse,
+  ReceiveMessageRequest, ReceiveMessageResponse,
+} from '../../proto/apache/rocketmq/v2/service_pb';
+import { FilterExpression } from '../../src/consumer/FilterExpression';
+import { SimpleConsumer } from '../../src/consumer/SimpleConsumer';
+import { BadRequestException, ForbiddenException, InternalErrorException } 
from '../../src/exception';
+import { GeneralMessage, MessageHookPoints, MessageHookPointsStatus, 
MessageInterceptorContext } from '../../src/hook';
+import { MessageView } from '../../src/message';
+import { MessageQueue } from '../../src/route';
+import { createResource } from '../../src/util';
+import { createFakeRpcClientManager, createSilentLogger, 
installFakeRpcClientManager } from '../support/fakes';
+import { buildMessagePB, buildRoute, buildStatus } from '../support/protobuf';
+
+class ConsumerHarness extends SimpleConsumer {
+  testClientType = ClientType.SIMPLE_CONSUMER;
+
+  protected getClientType() {
+    return this.testClientType ?? ClientType.SIMPLE_CONSUMER;
+  }
+
+  buildRequest(mq: MessageQueue) {
+    return this.wrapReceiveMessageRequest(5, mq, new FilterExpression('tag'), 
15000, 30000);
+  }
+
+  receiveRpc(request: ReceiveMessageRequest, mq: MessageQueue) {
+    return this.receiveMessage(request, mq, 30000);
+  }
+
+  ackRpc(message: MessageView) {
+    return this.ackMessage(message);
+  }
+
+  invisibleRpc(message: MessageView) {
+    return this.invisibleDuration(message, 15000);
+  }
+}
+
+describe('Consumer', () => {
+  let consumer: ConsumerHarness;
+  let rpc: ReturnType<typeof createFakeRpcClientManager>;
+  let logger: ReturnType<typeof createSilentLogger>;
+  const interceptor = {
+    doBefore: sinon.stub<[MessageInterceptorContext, GeneralMessage[]], 
void>(),
+    doAfter: sinon.stub<[MessageInterceptorContext, GeneralMessage[]], void>(),
+  };
+  const mq = buildRoute().messageQueues[0];
+
+  beforeEach(() => {
+    interceptor.doBefore.resetHistory();
+    interceptor.doAfter.resetHistory();
+    logger = createSilentLogger();
+    consumer = new ConsumerHarness({ endpoints: '127.0.0.1:8081', namespace: 
'', consumerGroup: 'group',
+      requestTimeout: 3000, subscriptions: new Map([[ 'test-topic', 
FilterExpression.SUB_ALL ]]),
+      logger, messageInterceptor: [ interceptor ] });
+    rpc = installFakeRpcClientManager(consumer);
+  });
+
+  afterEach(async () => {
+    await consumer.shutdown();
+    sinon.restore();
+  });
+
+  function checkHook(point: MessageHookPoints, status: 
MessageHookPointsStatus, messages: GeneralMessage[]) {
+    sinon.assert.calledOnce(interceptor.doBefore);
+    sinon.assert.calledOnce(interceptor.doAfter);
+    
assert.strictEqual(interceptor.doBefore.firstCall.args[0].getMessageHookPoints(),
 point);
+    
assert.strictEqual(interceptor.doAfter.firstCall.args[0].getMessageHookPoints(),
 point);
+    assert.strictEqual(interceptor.doAfter.firstCall.args[0].getStatus(), 
status);
+    assert.deepStrictEqual(interceptor.doAfter.firstCall.args[1], messages);
+    sinon.assert.callOrder(interceptor.doBefore, interceptor.doAfter);
+  }
+
+  it('receive 构造完整请求并按 requestTimeout + awaitDuration 设置 RPC 超时', async () => {
+    const request = consumer.buildRequest(mq);
+    assert.strictEqual(request.getGroup()?.getName(), 'group');
+    assert.deepStrictEqual(request.getMessageQueue()?.toObject(), 
mq.toProtobuf().toObject());
+    assert.strictEqual(request.getFilterExpression()?.getExpression(), 'tag');
+    assert.strictEqual(request.getBatchSize(), 5);
+    assert.strictEqual(request.getAutoRenew(), false);
+    assert.strictEqual(request.getInvisibleDuration()?.getSeconds(), 15);
+    assert.strictEqual(request.getLongPollingTimeout()?.getSeconds(), 30);
+    rpc.receiveMessage.resolves([ new 
ReceiveMessageResponse().setStatus(buildStatus()) ]);
+    assert.deepStrictEqual(await consumer.receiveRpc(request, mq), []);
+    sinon.assert.calledWithExactly(rpc.receiveMessage, mq.broker.endpoints, 
request, 33000);
+    checkHook(MessageHookPoints.RECEIVE, MessageHookPointsStatus.OK, []);
+    assert.deepStrictEqual(interceptor.doBefore.firstCall.args[1], []);
+  });
+
+  [ false, true ].forEach(timestampFirst => {
+    it(`解析 STATUS、MESSAGE 和 DELIVERY_TIMESTAMP 
组合(timestampFirst=${timestampFirst})`, async () => {
+      const time = new Date(1700000000123);
+      const timestamp = new 
ReceiveMessageResponse().setDeliveryTimestamp(Timestamp.fromDate(time));
+      const messages = [
+        new ReceiveMessageResponse().setMessage(buildMessagePB({ messageId: 
'a' })),
+        new ReceiveMessageResponse().setMessage(buildMessagePB({ messageId: 
'b' })),
+      ];
+      rpc.receiveMessage.resolves([
+        ...(timestampFirst ? [ timestamp ] : []), ...messages,
+        new ReceiveMessageResponse().setStatus(buildStatus()), 
...(timestampFirst ? [] : [ timestamp ]),
+      ]);
+      const result = await consumer.receiveRpc(consumer.buildRequest(mq), mq);
+      assert.deepStrictEqual(result.map(message => message.messageId), [ 'a', 
'b' ]);
+      assert.ok(result.every(message => 
message.transportDeliveryTimestamp?.getTime() === time.getTime()));
+      assert.ok(result.every(message => message.endpoints === 
mq.broker.endpoints));
+      checkHook(MessageHookPoints.RECEIVE, MessageHookPointsStatus.OK, result);
+    });
+  });
+
+  it('MESSAGE_NOT_FOUND 返回空列表并记录 OK hook', async () => {
+    rpc.receiveMessage.resolves([ new 
ReceiveMessageResponse().setStatus(buildStatus(Code.MESSAGE_NOT_FOUND)) ]);
+    assert.deepStrictEqual(await 
consumer.receiveRpc(consumer.buildRequest(mq), mq), []);
+    checkHook(MessageHookPoints.RECEIVE, MessageHookPointsStatus.OK, []);
+  });
+
+  ([
+    [ Code.BAD_REQUEST, BadRequestException ], [ Code.FORBIDDEN, 
ForbiddenException ],
+    [ Code.INTERNAL_SERVER_ERROR, InternalErrorException ],
+  ] as const).forEach(([ code, exception ]) => {
+    it(`receive 失败状态 ${code} 映射异常并记录一次 ERROR hook`, async () => {
+      rpc.receiveMessage.resolves([ new 
ReceiveMessageResponse().setStatus(buildStatus(code)) ]);
+      await assert.rejects(consumer.receiveRpc(consumer.buildRequest(mq), mq), 
exception);
+      checkHook(MessageHookPoints.RECEIVE, MessageHookPointsStatus.ERROR, []);
+    });
+  });
+
+  it('receive 传输失败保留异常对象并记录 ERROR hook', async () => {
+    const error = new Error('deadline exceeded');
+    rpc.receiveMessage.rejects(error);
+    await assert.rejects(consumer.receiveRpc(consumer.buildRequest(mq), mq), 
reason => reason === error);
+    checkHook(MessageHookPoints.RECEIVE, MessageHookPointsStatus.ERROR, []);
+  });
+
+  it('未知 receive content 发出 warn 并继续处理有效响应', async () => {
+    rpc.receiveMessage.resolves([ new ReceiveMessageResponse(), new 
ReceiveMessageResponse().setStatus(buildStatus()) ]);
+    assert.deepStrictEqual(await 
consumer.receiveRpc(consumer.buildRequest(mq), mq), []);
+    sinon.assert.calledOnce(logger.warn);
+    assert.ok(logger.warn.firstCall.args.includes(consumer.clientId));
+    checkHook(MessageHookPoints.RECEIVE, MessageHookPointsStatus.OK, []);
+  });
+
+  [ ClientType.SIMPLE_CONSUMER, ClientType.PUSH_CONSUMER,
+    ClientType.LITE_SIMPLE_CONSUMER, ClientType.LITE_PUSH_CONSUMER 
].forEach(type => {
+    ([ 'ack', 'invisible' ] as const).forEach(operation => {
+      it(`${operation} 构造完整字段并按 clientType=${type} 传递 liteTopic`, async () => {
+        consumer.testClientType = type;
+        const message = new MessageView(buildMessagePB({ liteTopic: 'lite' }), 
mq);
+        const isLite = type === ClientType.LITE_SIMPLE_CONSUMER || type === 
ClientType.LITE_PUSH_CONSUMER;
+        if (operation === 'ack') {
+          rpc.ackMessage.resolves(new 
AckMessageResponse().setStatus(buildStatus()));
+          await consumer.ackRpc(message);
+          const [ endpoints, request, timeout ] = 
rpc.ackMessage.firstCall.args;
+          assert.strictEqual(endpoints, message.endpoints);
+          assert.strictEqual(timeout, 3000);
+          assert.strictEqual(request.getGroup()?.getName(), 'group');
+          assert.strictEqual(request.getTopic()?.getName(), message.topic);
+          assert.strictEqual(request.getEntriesList()[0].getMessageId(), 
message.messageId);
+          assert.strictEqual(request.getEntriesList()[0].getReceiptHandle(), 
message.receiptHandle);
+          assert.strictEqual(request.getEntriesList()[0].getLiteTopic(), 
isLite ? 'lite' : '');
+          checkHook(MessageHookPoints.ACK, MessageHookPointsStatus.OK, [ 
message ]);
+        } else {
+          rpc.changeInvisibleDuration.resolves(new 
ChangeInvisibleDurationResponse()
+            .setStatus(buildStatus()).setReceiptHandle('new-handle'));
+          assert.strictEqual(await consumer.invisibleRpc(message), 
'new-handle');
+          const [ endpoints, request, timeout ] = 
rpc.changeInvisibleDuration.firstCall.args;
+          assert.strictEqual(endpoints, message.endpoints);
+          assert.strictEqual(timeout, 3000);
+          assert.strictEqual(request.getGroup()?.getName(), 'group');
+          assert.strictEqual(request.getTopic()?.getName(), message.topic);
+          assert.strictEqual(request.getMessageId(), message.messageId);
+          assert.strictEqual(request.getReceiptHandle(), 
message.receiptHandle);
+          assert.strictEqual(request.getInvisibleDuration()?.getSeconds(), 15);
+          assert.strictEqual(request.getLiteTopic(), isLite ? 'lite' : '');
+          checkHook(MessageHookPoints.CHANGE_INVISIBLE_DURATION, 
MessageHookPointsStatus.OK, [ message ]);
+        }
+        assert.deepStrictEqual(interceptor.doBefore.firstCall.args[1], [ 
message ]);
+      });
+    });
+  });
+
+  ([ 'ack', 'invisible' ] as const).forEach(operation => {
+    [ false, true ].forEach(transportFailure => {
+      it(`${operation} 失败时抛出异常并记录 ERROR 
hook(transportFailure=${transportFailure})`, async () => {
+        const message = new MessageView(buildMessagePB(), mq);
+        if (operation === 'ack') {
+          rpc.ackMessage.resolves(new 
AckMessageResponse().setStatus(buildStatus(Code.FORBIDDEN)));
+          if (transportFailure) rpc.ackMessage.rejects(new Error('transport'));
+          await assert.rejects(consumer.ackRpc(message), transportFailure ? 
/transport/ : ForbiddenException);
+          checkHook(MessageHookPoints.ACK, MessageHookPointsStatus.ERROR, [ 
message ]);
+        } else {
+          rpc.changeInvisibleDuration.resolves(new 
ChangeInvisibleDurationResponse().setStatus(buildStatus(Code.FORBIDDEN)));
+          if (transportFailure) rpc.changeInvisibleDuration.rejects(new 
Error('transport'));
+          await assert.rejects(consumer.invisibleRpc(message), 
transportFailure ? /transport/ : ForbiddenException);
+          checkHook(MessageHookPoints.CHANGE_INVISIBLE_DURATION, 
MessageHookPointsStatus.ERROR, [ message ]);
+        }
+      });
+    });
+  });
+
+  ([ 'ack', 'invisible', 'dlq' ] as const).forEach(operation => {
+    [ Code.OK, Code.FORBIDDEN ].forEach(code => {
+      it(`ViaRpc ${operation} 保留响应对象与调用参数,状态 ${code} 由调用方处理`, async () => {
+        const message = new MessageView(buildMessagePB(), mq);
+        let result: unknown;
+        let response: unknown;
+        let point: MessageHookPoints;
+        if (operation === 'ack') {
+          const request = new 
AckMessageRequest().setGroup(createResource('group')).setTopic(createResource(message.topic));
+          
request.addEntries().setMessageId(message.messageId).setReceiptHandle(message.receiptHandle);
+          response = new AckMessageResponse().setStatus(buildStatus(code));
+          rpc.ackMessage.resolves(response as AckMessageResponse);
+          result = await consumer.ackMessageViaRpc(message.endpoints, request, 
1234, message);
+          sinon.assert.calledWithExactly(rpc.ackMessage, message.endpoints, 
request, 1234);
+          point = MessageHookPoints.ACK;
+        } else if (operation === 'invisible') {
+          const request = new 
ChangeInvisibleDurationRequest().setMessageId(message.messageId);
+          response = new 
ChangeInvisibleDurationResponse().setStatus(buildStatus(code));
+          rpc.changeInvisibleDuration.resolves(response as 
ChangeInvisibleDurationResponse);
+          result = await 
consumer.changeInvisibleDurationViaRpc(message.endpoints, request, 1234, 
message);
+          sinon.assert.calledWithExactly(rpc.changeInvisibleDuration, 
message.endpoints, request, 1234);
+          point = MessageHookPoints.CHANGE_INVISIBLE_DURATION;
+        } else {
+          const request = new 
ForwardMessageToDeadLetterQueueRequest().setGroup(createResource('group'))
+            .setTopic(createResource(message.topic))
+            .setMessageId(message.messageId)
+            .setReceiptHandle(message.receiptHandle)
+            .setDeliveryAttempt(3)
+            .setMaxDeliveryAttempts(3);
+          response = new 
ForwardMessageToDeadLetterQueueResponse().setStatus(buildStatus(code));
+          rpc.forwardMessageToDeadLetterQueue.resolves(response as 
ForwardMessageToDeadLetterQueueResponse);
+          result = await 
consumer.forwardMessageToDeadLetterQueueViaRpc(message.endpoints, request, 
1234, message);
+          sinon.assert.calledWithExactly(rpc.forwardMessageToDeadLetterQueue, 
message.endpoints, request, 1234);
+          point = MessageHookPoints.FORWARD_TO_DLQ;
+        }
+        assert.strictEqual(result, response);
+        checkHook(point, code === Code.OK ? MessageHookPointsStatus.OK : 
MessageHookPointsStatus.ERROR, [ message ]);
+      });
+    });
+
+    it(`ViaRpc ${operation} 传输异常仍抛出且记录一次 ERROR hook`, async () => {
+      const message = new MessageView(buildMessagePB(), mq);
+      const error = new Error('transport failure');
+      rpc.ackMessage.rejects(error);
+      rpc.changeInvisibleDuration.rejects(error);
+      rpc.forwardMessageToDeadLetterQueue.rejects(error);
+      const [ pending, point ] = operation === 'ack'
+        ? [ consumer.ackMessageViaRpc(message.endpoints, new 
AckMessageRequest(), 3000, message), MessageHookPoints.ACK ]
+        : operation === 'invisible'
+          ? [ consumer.changeInvisibleDurationViaRpc(message.endpoints, new 
ChangeInvisibleDurationRequest(), 3000, message),
+            MessageHookPoints.CHANGE_INVISIBLE_DURATION ]
+          : [ consumer.forwardMessageToDeadLetterQueueViaRpc(message.endpoints,
+            new ForwardMessageToDeadLetterQueueRequest(), 3000, message), 
MessageHookPoints.FORWARD_TO_DLQ ];
+      await assert.rejects(pending, reason => reason === error);
+      checkHook(point, MessageHookPointsStatus.ERROR, [ message ]);
+    });
+  });
+});
diff --git a/nodejs/test/consumer/ConsumerSettings.test.ts 
b/nodejs/test/consumer/ConsumerSettings.test.ts
new file mode 100644
index 00000000..f3c97935
--- /dev/null
+++ b/nodejs/test/consumer/ConsumerSettings.test.ts
@@ -0,0 +1,99 @@
+/**
+ * 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, FilterType, Settings as SettingsPB, Subscription } from 
'../../proto/apache/rocketmq/v2/definition_pb';
+import { FilterExpression } from '../../src/consumer/FilterExpression';
+import { SimpleSubscriptionSettings } from 
'../../src/consumer/SimpleSubscriptionSettings';
+import { Endpoints } from '../../src/route';
+import { createDuration } from '../../src/util';
+import { buildSettings } from '../support/protobuf';
+
+describe('FilterExpression', () => {
+  it('SUB_ALL 默认使用 TAG 和 *,普通表达式默认 TAG', () => {
+    assert.strictEqual(FilterExpression.SUB_ALL.expression, '*');
+    assert.strictEqual(FilterExpression.SUB_ALL.filterType, FilterType.TAG);
+    const proto = FilterExpression.SUB_ALL.toProtobuf();
+    assert.strictEqual(proto.getExpression(), '*');
+    assert.strictEqual(proto.getType(), FilterType.TAG);
+    assert.strictEqual(new FilterExpression('tag').toProtobuf().getType(), 
FilterType.TAG);
+  });
+
+  it('SQL92 表达式按 SQL 类型写入协议', () => {
+    const expression = new FilterExpression('a > 1', FilterType.SQL);
+    assert.strictEqual(expression.toProtobuf().getType(), FilterType.SQL);
+    assert.strictEqual(expression.toProtobuf().getExpression(), 'a > 1');
+  });
+
+  it('保留 equals、hashCode、toString 公开行为', () => {
+    const expression = new FilterExpression('tag');
+    assert.ok(expression.equals(expression));
+    assert.ok(expression.equals(new FilterExpression('tag')));
+    assert.ok(!expression.equals(new FilterExpression('another')));
+    assert.ok(!expression.equals(new FilterExpression('tag', FilterType.SQL)));
+    assert.ok(!expression.equals(null as unknown as FilterExpression));
+    assert.strictEqual(expression.hashCode(), new 
FilterExpression('tag').hashCode());
+    assert.strictEqual(expression.toString(), 
`FilterExpression(${FilterType.TAG},tag)`);
+  });
+});
+
+describe('SimpleSubscriptionSettings', () => {
+  function createSettings() {
+    const expressions = new Map([
+      [ 'topic-a', FilterExpression.SUB_ALL ], [ 'topic-b', new 
FilterExpression('a > 1', FilterType.SQL) ],
+    ]);
+    const endpoints = new Endpoints('127.0.0.1:8081');
+    const settings = new SimpleSubscriptionSettings('ns', 'client', 
ClientType.SIMPLE_CONSUMER,
+      endpoints, 'group', 3000, 30000, expressions);
+    return { settings, expressions, endpoints };
+  }
+
+  it('toProtobuf 
包含类型、accessPoint、requestTimeout、group、longPollingTimeout、过滤表达式和 userAgent', () 
=> {
+    const { settings, endpoints } = createSettings();
+    const proto = settings.toProtobuf();
+    assert.strictEqual(proto.getClientType(), ClientType.SIMPLE_CONSUMER);
+    assert.deepStrictEqual(proto.getAccessPoint()?.toObject(), 
endpoints.toProtobuf().toObject());
+    assert.deepStrictEqual(proto.getRequestTimeout()?.toObject(), 
createDuration(3000).toObject());
+    const subscription = proto.getSubscription()!;
+    assert.strictEqual(subscription.getGroup()?.getName(), 'group');
+    assert.deepStrictEqual(subscription.getLongPollingTimeout()?.toObject(), 
createDuration(30000).toObject());
+    assert.deepStrictEqual(subscription.getSubscriptionsList().map(entry => [
+      entry.getTopic()?.getName(), entry.getExpression()?.getType(), 
entry.getExpression()?.getExpression(),
+    ]), [[ 'topic-a', FilterType.TAG, '*' ], [ 'topic-b', FilterType.SQL, 'a > 
1' ]]);
+    assert.ok(proto.getUserAgent()?.getVersion());
+  });
+
+  it('toProtobuf 反映同一个订阅 Map 的追加与删除', () => {
+    const { settings, expressions } = createSettings();
+    expressions.delete('topic-a');
+    expressions.set('topic-c', new FilterExpression('tag'));
+    
assert.deepStrictEqual(settings.toProtobuf().getSubscription()?.getSubscriptionsList()
+      .map(entry => entry.getTopic()?.getName()), [ 'topic-b', 'topic-c' ]);
+  });
+
+  it('sync 不覆盖客户端配置,接受 subscription 与其他类型 settings', () => {
+    const { settings } = createSettings();
+    const snapshot = settings.toProtobuf().toObject();
+    const issued = buildSettings({ clientType: ClientType.SIMPLE_CONSUMER,
+      subscription: new 
Subscription().setLongPollingTimeout(createDuration(1000)) });
+    for (const proto of [ issued, buildSettings(), new SettingsPB() ]) {
+      assert.doesNotThrow(() => settings.sync(proto));
+      assert.deepStrictEqual(settings.toProtobuf().toObject(), snapshot);
+    }
+    assert.strictEqual(settings.longPollingTimeout, 30000);
+  });
+});
diff --git a/nodejs/test/consumer/OffsetOption.test.ts 
b/nodejs/test/consumer/OffsetOption.test.ts
index 96cd8056..163899c3 100644
--- a/nodejs/test/consumer/OffsetOption.test.ts
+++ b/nodejs/test/consumer/OffsetOption.test.ts
@@ -21,6 +21,7 @@
 
 import * as assert from 'node:assert';
 import { OffsetOption, OffsetType } from '../../src/consumer/OffsetOption';
+import { OffsetOption as ProtoOffsetOption } from 
'../../proto/apache/rocketmq/v2/definition_pb';
 
 describe('OffsetOption', () => {
   describe('Predefined constants', () => {
@@ -102,6 +103,68 @@ describe('OffsetOption', () => {
     });
   });
 
+  describe('协议与数值边界', () => {
+    it('三种 policy 都使用对应的 oneof 字段', () => {
+      for (const [ option, value ] of [
+        [ OffsetOption.LAST_OFFSET, 0 ], [ OffsetOption.MIN_OFFSET, 1 ], [ 
OffsetOption.MAX_OFFSET, 2 ],
+      ] as const) {
+        const proto = option.toProtobuf();
+        assert.strictEqual(proto.getOffsetTypeCase(), 
ProtoOffsetOption.OffsetTypeCase.POLICY);
+        assert.strictEqual(proto.getPolicy(), value);
+      }
+    });
+
+    const factories = [
+      { name: 'offset', create: OffsetOption.ofOffset, type: OffsetType.OFFSET,
+        protoCase: ProtoOffsetOption.OffsetTypeCase.OFFSET, read: (p: 
ProtoOffsetOption) => p.getOffset() },
+      { name: 'tailN', create: OffsetOption.ofTailN, type: OffsetType.TAIL_N,
+        protoCase: ProtoOffsetOption.OffsetTypeCase.TAIL_N, read: (p: 
ProtoOffsetOption) => p.getTailN() },
+      { name: 'timestamp', create: OffsetOption.ofTimestamp, type: 
OffsetType.TIMESTAMP,
+        protoCase: ProtoOffsetOption.OffsetTypeCase.TIMESTAMP, read: (p: 
ProtoOffsetOption) => p.getTimestamp() },
+    ];
+    for (const { name, create, type, protoCase, read } of factories) {
+      it(`${name} 接受非负安全整数 number 和 bigint 并保留协议字段`, () => {
+        for (const value of [ 0, 1, Number.MAX_SAFE_INTEGER - 1, 
Number.MAX_SAFE_INTEGER ]) {
+          for (const input of [ value, BigInt(value) ]) {
+            const option = create(input);
+            assert.strictEqual(option.getType(), type);
+            assert.strictEqual(option.getValue(), BigInt(value));
+            const proto = option.toProtobuf();
+            assert.strictEqual(proto.getOffsetTypeCase(), protoCase);
+            assert.strictEqual(read(proto), value);
+          }
+        }
+      });
+
+      it(`${name} 在工厂调用时拒绝不安全 number、NaN、无限值和小数`, () => {
+        for (const value of [ Number.MAX_SAFE_INTEGER + 1, 
Number.MAX_SAFE_INTEGER + 2,
+          Number.MIN_SAFE_INTEGER - 1, NaN, Infinity, -Infinity, 0.5 ]) {
+          assert.throws(() => create(value), RangeError);
+        }
+      });
+
+      it(`${name} 保留负数校验和超大 bigint 的延迟序列化校验`, () => {
+        for (const value of [ -1, BigInt(-1) ]) {
+          assert.throws(() => create(value), new RegExp(`${name} must be 
greater than or equal to 0`));
+        }
+        const value = BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1);
+        const option = create(value);
+        assert.strictEqual(option.getValue(), value);
+        assert.throws(() => option.toProtobuf(), /out of safe number range/);
+      });
+    }
+
+    it('equals 比较类型和值;hashCode 对相等对象稳定', () => {
+      const option = OffsetOption.ofOffset(1);
+      assert.ok(option.equals(option));
+      assert.ok(option.equals(OffsetOption.ofOffset(BigInt(1))));
+      assert.ok(!option.equals(OffsetOption.ofOffset(2)));
+      assert.ok(!option.equals(OffsetOption.ofTailN(1)));
+      assert.ok(!option.equals(null as unknown as OffsetOption));
+      assert.strictEqual(option.hashCode(), 
OffsetOption.ofOffset(BigInt(1)).hashCode());
+    });
+  });
+
   describe('toString()', () => {
     it('should return string representation', () => {
       const option = OffsetOption.ofOffset(100);
diff --git a/nodejs/test/consumer/SimpleConsumer.test.ts 
b/nodejs/test/consumer/SimpleConsumer.test.ts
new file mode 100644
index 00000000..222b83b7
--- /dev/null
+++ b/nodejs/test/consumer/SimpleConsumer.test.ts
@@ -0,0 +1,263 @@
+/**
+ * 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 { ClientType, Code, FilterType } from 
'../../proto/apache/rocketmq/v2/definition_pb';
+import { AckMessageResponse, ChangeInvisibleDurationResponse, 
ReceiveMessageResponse } from '../../proto/apache/rocketmq/v2/service_pb';
+import { FilterExpression } from '../../src/consumer/FilterExpression';
+import { SimpleConsumer, SimpleConsumerOptions } from 
'../../src/consumer/SimpleConsumer';
+import { BadRequestException, InternalErrorException } from 
'../../src/exception';
+import { MessageView } from '../../src/message';
+import { TopicRouteData } from '../../src/route';
+import { createSilentLogger, installFakeRpcClientManager } from 
'../support/fakes';
+import { buildMessagePB, buildRoute, buildStatus } from '../support/protobuf';
+
+class SimpleConsumerHarness extends SimpleConsumer {
+  getRouteData(topic: string) {
+    return super.getRouteData(topic);
+  }
+
+  settingsSnapshot() {
+    return this.getSettings().toProtobuf();
+  }
+
+  updateRoute(topic: string, route: TopicRouteData) {
+    this.onTopicRouteDataUpdate(topic, route);
+  }
+
+  heartbeatRequest() {
+    return this.wrapHeartbeatRequest();
+  }
+
+  terminationRequest() {
+    return this.wrapNotifyClientTerminationRequest();
+  }
+}
+
+describe('SimpleConsumer', () => {
+  const clients: SimpleConsumerHarness[] = [];
+
+  function createConsumer(options: Partial<SimpleConsumerOptions> = {}) {
+    const logger = createSilentLogger();
+    const consumer = new SimpleConsumerHarness({ endpoints: '127.0.0.1:8081', 
namespace: '', consumerGroup: 'group',
+      requestTimeout: 3000, subscriptions: new Map([[ 'topic-a', 
FilterExpression.SUB_ALL ]]), logger, ...options });
+    clients.push(consumer);
+    const rpc = installFakeRpcClientManager(consumer);
+    rpc.receiveMessage.resolves([ new 
ReceiveMessageResponse().setStatus(buildStatus()) ]);
+    const running = sinon.stub(consumer, 'isRunning').returns(true);
+    const route = sinon.stub(consumer, 'getRouteData').callsFake(async topic 
=> buildRoute({ topic, queuesPerBroker: 3 }));
+    return { consumer, rpc, running, route, logger };
+  }
+
+  afterEach(async () => {
+    for (const consumer of clients.splice(0)) {
+      await consumer.shutdown();
+    }
+    sinon.restore();
+  });
+
+  it('现有 string 与 FilterExpression 订阅、默认参数及组查询保持可用', async () => {
+    const { consumer, rpc } = createConsumer({ subscriptions: new Map<string, 
FilterExpression | string>([
+      [ 'topic-a', 'tag' ], [ 'topic-b', new FilterExpression('a > 1', 
FilterType.SQL) ],
+    ]) });
+    assert.strictEqual(consumer.getConsumerGroup(), 'group');
+    await consumer.receive();
+    await consumer.receive();
+    const requests = rpc.receiveMessage.getCalls().map(call => call.args[1]);
+    assert.strictEqual(new Set(requests.map(request => 
request.getMessageQueue()?.getTopic()?.getName())).size, 2);
+    for (const request of requests) {
+      assert.strictEqual(request.getBatchSize(), 10);
+      assert.strictEqual(request.getInvisibleDuration()?.getSeconds(), 15);
+      assert.strictEqual(request.getLongPollingTimeout()?.getSeconds(), 30);
+    }
+    assert.strictEqual(consumer.heartbeatRequest().getClientType(), 
ClientType.SIMPLE_CONSUMER);
+    assert.strictEqual(consumer.heartbeatRequest().getGroup()?.getName(), 
'group');
+    assert.strictEqual(consumer.terminationRequest().getGroup()?.getName(), 
'group');
+  });
+
+  it('多 topic 连续轮询,缓存路由并只发送 master 的各个队列', async () => {
+    const { consumer, rpc, route } = createConsumer({ subscriptions: new Map([
+      [ 'topic-a', FilterExpression.SUB_ALL ], [ 'topic-b', 
FilterExpression.SUB_ALL ],
+    ]) });
+    route.callsFake(async topic => buildRoute({ topic, queuesPerBroker: 3, 
brokers: [
+      { name: 'master', id: 0, endpoints: '127.0.0.1:8081' },
+      { name: 'slave', id: 1, endpoints: '127.0.0.1:8082' },
+    ] }));
+    for (let i = 0; i < 6; i++) await consumer.receive();
+    const queues = rpc.receiveMessage.getCalls().map(call => 
call.args[1].getMessageQueue()!);
+    assert.ok(queues.every(queue => queue.getBroker()?.getId() === 0));
+    assert.notStrictEqual(queues[0].getTopic()?.getName(), 
queues[1].getTopic()?.getName());
+    assert.strictEqual(queues[0].getTopic()?.getName(), 
queues[2].getTopic()?.getName());
+    for (const topic of [ 'topic-a', 'topic-b' ]) {
+      assert.deepStrictEqual(queues.filter(queue => 
queue.getTopic()?.getName() === topic).map(queue => queue.getId()).sort(), [ 0, 
1, 2 ]);
+    }
+    sinon.assert.calledTwice(route);
+  });
+
+  it('路由更新保留轮询位置,后续 receive 使用更新后的端点', async () => {
+    const { consumer, rpc } = createConsumer();
+    await consumer.receive();
+    const firstId = 
rpc.receiveMessage.firstCall.args[1].getMessageQueue()!.getId();
+    consumer.updateRoute('topic-a', buildRoute({ topic: 'topic-a', 
queuesPerBroker: 3,
+      brokers: [{ name: 'updated', endpoints: '127.0.0.1:8083' }] }));
+    await consumer.receive();
+    
assert.strictEqual(rpc.receiveMessage.secondCall.args[1].getMessageQueue()?.getId(),
 (firstId + 1) % 3);
+    assert.strictEqual(rpc.receiveMessage.secondCall.args[0].facade, 
'127.0.0.1:8083');
+  });
+
+  it('subscribe 查询成功后写入订阅,失败时保留原订阅', async () => {
+    const { consumer, route, rpc } = createConsumer();
+    const filter = new FilterExpression('tag');
+    route.withArgs('topic-b').rejects(new Error('route unavailable'));
+    await assert.rejects(consumer.subscribe('topic-b', filter), /route 
unavailable/);
+    
assert.deepStrictEqual(consumer.settingsSnapshot().getSubscription()?.getSubscriptionsList()
+      .map(entry => entry.getTopic()?.getName()), [ 'topic-a' ]);
+    route.withArgs('topic-b').resolves(buildRoute({ topic: 'topic-b' }));
+    assert.strictEqual(await consumer.subscribe('topic-b', filter), undefined);
+    consumer.unsubscribe('topic-a');
+    await consumer.receive();
+    
assert.strictEqual(rpc.receiveMessage.firstCall.args[1].getMessageQueue()?.getTopic()?.getName(),
 'topic-b');
+    
assert.strictEqual(rpc.receiveMessage.firstCall.args[1].getFilterExpression()?.getExpression(),
 'tag');
+  });
+
+  it('unsubscribe 只更新本地订阅,删除后不再选择该 topic', async () => {
+    const { consumer, route, rpc } = createConsumer({ subscriptions: new Map([
+      [ 'topic-a', FilterExpression.SUB_ALL ], [ 'topic-b', 
FilterExpression.SUB_ALL ],
+    ]) });
+    assert.strictEqual(consumer.unsubscribe('topic-a'), undefined);
+    consumer.unsubscribe('unknown-topic');
+    for (let i = 0; i < 3; i++) await consumer.receive();
+    assert.ok(rpc.receiveMessage.getCalls().every(call => 
call.args[1].getMessageQueue()?.getTopic()?.getName() === 'topic-b'));
+    sinon.assert.calledOnce(route);
+    consumer.unsubscribe('topic-b');
+    await assert.rejects(consumer.receive(), /No subscriptions available/);
+    sinon.assert.calledThrice(rpc.receiveMessage);
+  });
+
+  it('保留 startup 前的订阅调整能力及 subscribe/unsubscribe 返回类型', async () => {
+    const { consumer, running } = createConsumer();
+    running.returns(false);
+    assert.strictEqual(await consumer.subscribe('topic-b', 
FilterExpression.SUB_ALL), undefined);
+    assert.strictEqual(consumer.unsubscribe('topic-a'), undefined);
+    
assert.deepStrictEqual(consumer.settingsSnapshot().getSubscription()?.getSubscriptionsList()
+      .map(entry => entry.getTopic()?.getName()), [ 'topic-b' ]);
+  });
+
+  it('未运行时 receive、ack、changeInvisibleDuration 均拒绝且不发 RPC', async () => {
+    const { consumer, running, rpc } = createConsumer();
+    running.returns(false);
+    const message = new MessageView(buildMessagePB(), 
buildRoute().messageQueues[0]);
+    await assert.rejects(consumer.receive(), /not running/);
+    await assert.rejects(consumer.ack(message), /not running/);
+    await assert.rejects(consumer.changeInvisibleDuration(message, 15000), 
/not running/);
+    sinon.assert.notCalled(rpc.receiveMessage);
+    sinon.assert.notCalled(rpc.ackMessage);
+    sinon.assert.notCalled(rpc.changeInvisibleDuration);
+  });
+
+  it('receive 拒绝非正批量大小且不发 RPC', async () => {
+    const { consumer, rpc } = createConsumer();
+    for (const count of [ 0, -1 ]) await 
assert.rejects(consumer.receive(count), /maxMessageNum must be greater than 0/);
+    sinon.assert.notCalled(rpc.receiveMessage);
+  });
+
+  it('成功更新 receiptHandle,后续 ack 使用新句柄并保留 void 返回值', async () => {
+    const { consumer, rpc } = createConsumer();
+    const message = new MessageView(buildMessagePB(), 
buildRoute().messageQueues[0]);
+    rpc.changeInvisibleDuration.resolves(new 
ChangeInvisibleDurationResponse().setStatus(buildStatus()).setReceiptHandle('new'));
+    assert.strictEqual(await consumer.changeInvisibleDuration(message, 15000), 
undefined);
+    assert.strictEqual(message.receiptHandle, 'new');
+    rpc.ackMessage.resolves(new AckMessageResponse().setStatus(buildStatus()));
+    assert.strictEqual(await consumer.ack(message), undefined);
+    
assert.strictEqual(rpc.ackMessage.firstCall.args[1].getEntriesList()[0].getReceiptHandle(),
 'new');
+  });
+
+  it('续期失败时保留旧 receiptHandle', async () => {
+    const { consumer, rpc } = createConsumer();
+    const message = new MessageView(buildMessagePB(), 
buildRoute().messageQueues[0]);
+    const old = message.receiptHandle;
+    rpc.changeInvisibleDuration.resolves(new ChangeInvisibleDurationResponse()
+      
.setStatus(buildStatus(Code.INVALID_RECEIPT_HANDLE)).setReceiptHandle('invalid-new'));
+    await assert.rejects(consumer.changeInvisibleDuration(message, 15000), 
BadRequestException);
+    assert.strictEqual(message.receiptHandle, old);
+  });
+
+  it('仅 InternalErrorException 重试,复用 request 和队列并按 1000ms 退避', async () => {
+    const clock = sinon.useFakeTimers();
+    const { consumer, rpc } = createConsumer();
+    rpc.receiveMessage.onFirstCall().resolves([ new 
ReceiveMessageResponse().setStatus(buildStatus(Code.INTERNAL_SERVER_ERROR)) ]);
+    rpc.receiveMessage.onSecondCall().resolves([ new 
ReceiveMessageResponse().setStatus(buildStatus()) ]);
+    const pending = consumer.receive();
+    await clock.tickAsync(0);
+    sinon.assert.calledOnce(rpc.receiveMessage);
+    await clock.tickAsync(999);
+    sinon.assert.calledOnce(rpc.receiveMessage);
+    await clock.tickAsync(1);
+    assert.deepStrictEqual(await pending, []);
+    sinon.assert.calledTwice(rpc.receiveMessage);
+    assert.strictEqual(rpc.receiveMessage.firstCall.args[1], 
rpc.receiveMessage.secondCall.args[1]);
+    assert.strictEqual(rpc.receiveMessage.firstCall.args[0], 
rpc.receiveMessage.secondCall.args[0]);
+  });
+
+  for (const attempts of [ undefined, 1, 2, 4 ]) {
+    it(`重试耗尽在 RPC 等待与退避预算内结束(maxRetryAttempts=${attempts ?? '默认3'})`, async () 
=> {
+      const clock = sinon.useFakeTimers();
+      const { consumer, rpc } = createConsumer({ maxRetryAttempts: attempts });
+      rpc.receiveMessage.callsFake(async (_endpoints, _request, timeout) => {
+        await new Promise(resolve => setTimeout(resolve, timeout));
+        return [ new 
ReceiveMessageResponse().setStatus(buildStatus(Code.INTERNAL_SERVER_ERROR)) ];
+      });
+      let settled = false;
+      const pending = assert.rejects(consumer.receive(), 
InternalErrorException).then(() => { settled = true; });
+      const count = attempts ?? 3;
+      const budget = count * 33000 + (count - 1) * 1000;
+      await clock.tickAsync(budget - 1);
+      assert.strictEqual(settled, false);
+      await clock.tickAsync(1);
+      await pending;
+      assert.strictEqual(settled, true);
+      assert.strictEqual(rpc.receiveMessage.callCount, count);
+      assert.strictEqual(clock.now, budget);
+    });
+  }
+
+  for (const code of [ Code.BAD_REQUEST, Code.PROXY_TIMEOUT ]) {
+    it(`非内部错误 ${code} 不重试`, async () => {
+      const { consumer, rpc } = createConsumer();
+      rpc.receiveMessage.resolves([ new 
ReceiveMessageResponse().setStatus(buildStatus(code)) ]);
+      await assert.rejects(consumer.receive());
+      sinon.assert.calledOnce(rpc.receiveMessage);
+    });
+  }
+
+  it('传输异常不重试并保留原异常对象', async () => {
+    const { consumer, rpc } = createConsumer();
+    const error = new Error('transport');
+    rpc.receiveMessage.rejects(error);
+    await assert.rejects(consumer.receive(), reason => reason === error);
+    sinon.assert.calledOnce(rpc.receiveMessage);
+  });
+
+  it('构造时拒绝非法 maxRetryAttempts,在创建客户端资源前报 TypeError', () => {
+    for (const maxRetryAttempts of [ 0, -1, NaN, Infinity, -Infinity, 1.5, 
Number.MAX_SAFE_INTEGER + 1 ]) {
+      assert.throws(() => new SimpleConsumer({ endpoints: '127.0.0.1:8081', 
namespace: '', consumerGroup: 'group',
+        subscriptions: new Map([[ 'topic-a', FilterExpression.SUB_ALL ]]), 
maxRetryAttempts }),
+      { name: 'TypeError', message: 'maxRetryAttempts must be a positive safe 
integer' });
+    }
+  });
+});
diff --git a/nodejs/test/consumer/SubscriptionLoadBalancer.test.ts 
b/nodejs/test/consumer/SubscriptionLoadBalancer.test.ts
new file mode 100644
index 00000000..ca308099
--- /dev/null
+++ b/nodejs/test/consumer/SubscriptionLoadBalancer.test.ts
@@ -0,0 +1,87 @@
+/**
+ * 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 { Permission } from '../../proto/apache/rocketmq/v2/definition_pb';
+import { SubscriptionLoadBalancer } from 
'../../src/consumer/SubscriptionLoadBalancer';
+import { buildRoute } from '../support/protobuf';
+
+const brokers = [
+  { name: 'a', id: 0, endpoints: '127.0.0.1:8081' },
+  { name: 'a', id: 1, endpoints: '127.0.0.1:8082' },
+  { name: 'b', id: 0, endpoints: '127.0.0.1:8083' },
+];
+
+describe('SubscriptionLoadBalancer', () => {
+  it('轮询所有 master 可读队列,排除 slave 的 0 号队列', () => {
+    const route = buildRoute({ brokers, queuesPerBroker: 3 });
+    const balancer = new SubscriptionLoadBalancer(route, 0);
+    const selected = Array.from({ length: 6 }, () => 
balancer.takeMessageQueue());
+    assert.deepStrictEqual(selected.map(mq => [ mq.broker.name, mq.broker.id, 
mq.queueId ]), [
+      [ 'a', 0, 0 ], [ 'a', 0, 1 ], [ 'a', 0, 2 ],
+      [ 'b', 0, 0 ], [ 'b', 0, 1 ], [ 'b', 0, 2 ],
+    ]);
+    assert.strictEqual(balancer.takeMessageQueue(), selected[0]);
+  });
+
+  it('接受 READ 和 READ_WRITE,排除 WRITE 和 NONE', () => {
+    const route = buildRoute({ queuesPerBroker: 4 });
+    [ Permission.READ, Permission.WRITE, Permission.READ_WRITE, 
Permission.NONE ].forEach((permission, i) => {
+      route.messageQueues[i] = buildRoute({ permission }).messageQueues[0];
+    });
+    const balancer = new SubscriptionLoadBalancer(route, 0);
+    assert.strictEqual(balancer.takeMessageQueue(), route.messageQueues[0]);
+    assert.strictEqual(balancer.takeMessageQueue(), route.messageQueues[2]);
+    assert.strictEqual(balancer.takeMessageQueue(), route.messageQueues[0]);
+  });
+
+  for (const route of [
+    buildRoute({ brokers: [] }),
+    buildRoute({ brokerId: 1 }),
+    buildRoute({ permission: Permission.WRITE }),
+    buildRoute({ permission: Permission.NONE }),
+  ]) {
+    it('无可读 master 队列时抛出明确错误(含默认随机起点)', () => {
+      assert.throws(() => new SubscriptionLoadBalancer(route), /No readable 
message queue found/);
+      assert.throws(() => new SubscriptionLoadBalancer(route, 0), /No readable 
message queue found/);
+    });
+  }
+
+  it('默认随机起点只产生可读 master 队列', () => {
+    const route = buildRoute({ brokers, queuesPerBroker: 3 });
+    const balancer = new SubscriptionLoadBalancer(route);
+    const selected = Array.from({ length: 6 }, () => 
balancer.takeMessageQueue());
+    assert.strictEqual(new Set(selected).size, 6);
+    assert.ok(selected.every(mq => mq.broker.id === 0));
+  });
+
+  it('update 保留轮询位置,并使用新路由', () => {
+    const balancer = new SubscriptionLoadBalancer(buildRoute({ 
queuesPerBroker: 3 }), 0);
+    assert.strictEqual(balancer.takeMessageQueue().queueId, 0);
+    const route = buildRoute({ topic: 'updated', queuesPerBroker: 3 });
+    const updated = balancer.update(route);
+    assert.strictEqual(updated.takeMessageQueue(), route.messageQueues[1]);
+    assert.strictEqual(updated.takeMessageQueue(), route.messageQueues[2]);
+    assert.strictEqual(updated.takeMessageQueue(), route.messageQueues[0]);
+  });
+
+  it('update 后位置超出缩短的路由时回到起点', () => {
+    const balancer = new SubscriptionLoadBalancer(buildRoute({ 
queuesPerBroker: 3 }), 2);
+    const route = buildRoute();
+    assert.strictEqual(balancer.update(route).takeMessageQueue(), 
route.messageQueues[0]);
+  });
+});

Reply via email to