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 bc822ef6 fix(nodejs): stop push consumption from stranding cached 
messages (#1501)
bc822ef6 is described below

commit bc822ef6c2f4f0aa9479417d6dec9c7f166c9f35
Author: Quan <[email protected]>
AuthorDate: Wed Nov 18 21:18:25 2026 +0800

    fix(nodejs): stop push consumption from stranding cached messages (#1501)
    
    - Pass the consumer logger, client id and lite flag into ProcessQueue 
instead of reading protected members through any
    - Call the optional logger debug method safely so FIFO local redelivery no 
longer throws with a custom logger
    - Nack and evict a message whose settlement throws in standard consumption 
so its permit is released
    - Cover the receive loop, settlement, FIFO and standard consumption, 
assignment scanning, settings, assignments and gauges with unit tests
---
 nodejs/src/consumer/ProcessQueue.ts                |  50 +++-
 nodejs/src/consumer/PushConsumer.ts                |   8 +-
 nodejs/src/consumer/StandardConsumeService.ts      |  13 +-
 nodejs/test/consumer/FifoConsumeService.test.ts    |  73 +++++
 nodejs/test/consumer/ProcessQueue.test.ts          | 327 +++++++++++++++++++++
 .../test/consumer/PushConsumerAssignment.test.ts   | 173 +++++++++++
 .../consumer/PushConsumerGaugeObserver.test.ts     |  78 +++++
 .../test/consumer/PushSubscriptionSettings.test.ts | 101 +++++++
 .../test/consumer/StandardConsumeService.test.ts   |  88 ++++++
 nodejs/test/consumer/processQueueHarness.ts        | 112 +++++++
 10 files changed, 1005 insertions(+), 18 deletions(-)

diff --git a/nodejs/src/consumer/ProcessQueue.ts 
b/nodejs/src/consumer/ProcessQueue.ts
index 18f1f703..e689f0de 100644
--- a/nodejs/src/consumer/ProcessQueue.ts
+++ b/nodejs/src/consumer/ProcessQueue.ts
@@ -24,6 +24,7 @@ import { ConsumeResult, ConsumeResultSuspend } from 
'./ConsumeResult';
 import { FilterExpression } from './FilterExpression';
 import type { PushConsumer } from './PushConsumer';
 import { Semaphore } from '../util/Semaphore';
+import { ILogger, getDefaultLogger } from '../client/Logger';
 
 const ACK_MESSAGE_FAILURE_BACKOFF_DELAY = 1000;
 const CHANGE_INVISIBLE_DURATION_FAILURE_BACKOFF_DELAY = 1000;
@@ -36,6 +37,9 @@ const RECEIVING_BACKOFF_DELAY_WHEN_PERMITS_EXHAUSTED = 20;
 
 export class ProcessQueue {
   readonly #consumer: PushConsumer;
+  readonly #logger: ILogger;
+  readonly #clientId: string;
+  readonly #liteConsumer: boolean;
   #dropped = false;
   readonly #mq: MessageQueue;
   readonly #filterExpression: FilterExpression;
@@ -47,13 +51,31 @@ export class ProcessQueue {
   // Bounds in-flight messages per queue; mirrors Java ProcessQueueImpl 
permits.
   readonly #semaphore: Semaphore;
 
-  constructor(consumer: PushConsumer, mq: MessageQueue, filterExpression: 
FilterExpression) {
+  // `context` carries the logger and identity of the owning consumer. 
PushConsumer always passes it;
+  // when omitted they are read from the consumer so existing three-argument 
calls keep working.
+  constructor(consumer: PushConsumer, mq: MessageQueue, filterExpression: 
FilterExpression,
+    context?: { logger: ILogger; clientId: string; liteConsumer: boolean }) {
+    context = context ?? ProcessQueue.#contextOf(consumer);
     this.#consumer = consumer;
+    this.#logger = context.logger;
+    this.#clientId = context.clientId;
+    this.#liteConsumer = context.liteConsumer;
     this.#mq = mq;
     this.#filterExpression = filterExpression;
     this.#semaphore = new 
Semaphore(consumer.getPushConsumerSettings().getConsumeConcurrentlyMax());
   }
 
+  static #contextOf(consumer: PushConsumer) {
+    // logger and isLiteConsumer() are protected on the consumer; this is the 
only place
+    // that reads them, for callers constructing a process queue without a 
context.
+    const legacy = consumer as unknown as { logger?: ILogger; isLiteConsumer?: 
() => boolean };
+    return {
+      logger: legacy.logger ?? getDefaultLogger(),
+      clientId: consumer.clientId,
+      liteConsumer: legacy.isLiteConsumer?.() ?? false,
+    };
+  }
+
   getMessageQueue(): MessageQueue {
     return this.#mq;
   }
@@ -124,7 +146,7 @@ export class ProcessQueue {
     if (this.#dropped || this.#aborted) {
       return;
     }
-    (this.#consumer as any).logger?.info('ProcessQueue.fetchMessageImmediately 
called, mq=%s@%s@%d',
+    this.#logger.info('ProcessQueue.fetchMessageImmediately called, 
mq=%s@%s@%d',
       this.#mq.topic.name, this.#mq.broker.name, this.#mq.queueId);
     this.#receiveMessageImmediately();
   }
@@ -187,24 +209,24 @@ export class ProcessQueue {
       );
       this.#activityTime = Date.now();
 
-      (this.#consumer as any).logger?.debug?.('Start to receive message, 
mq=%s@%s@%d, batchSize=%d, attemptId=%s',
+      this.#logger.debug?.('Start to receive message, mq=%s@%s@%d, 
batchSize=%d, attemptId=%s',
         this.#mq.topic.name, this.#mq.broker.name, this.#mq.queueId, 
batchSize, attemptId);
 
       this.#consumer.receiveMessage(request, this.#mq, longPollingTimeout)
         .then(messages => {
           if (messages.length > 0) {
-            (this.#consumer as any).logger?.debug?.('Received messages, 
count=%d, mq=%s@%s@%d',
+            this.#logger.debug?.('Received messages, count=%d, mq=%s@%s@%d',
               messages.length, this.#mq.topic.name, this.#mq.broker.name, 
this.#mq.queueId);
           }
           this.#onReceiveMessageResult(messages);
         })
         .catch(err => {
-          (this.#consumer as any).logger?.error('Failed to receive message, 
mq=%s@%s@%d, error=%s',
+          this.#logger.error('Failed to receive message, mq=%s@%s@%d, 
error=%s',
             this.#mq.topic.name, this.#mq.broker.name, this.#mq.queueId, err);
           this.onReceiveMessageException(err, attemptId);
         });
     } catch (err) {
-      (this.#consumer as any).logger?.error('Exception in receiveMessage, 
mq=%s@%s@%d, error=%s',
+      this.#logger.error('Exception in receiveMessage, mq=%s@%s@%d, error=%s',
         this.#mq.topic.name, this.#mq.broker.name, this.#mq.queueId, err);
       this.onReceiveMessageException(err as Error, attemptId);
     }
@@ -266,7 +288,7 @@ export class ProcessQueue {
         await this.#ackMessageLater(messageView, attempt + 1);
       }
     } catch (err) {
-      (this.#consumer as any).logger?.warn(
+      this.#logger.warn(
         'Failed to ack message, attempt=%d, messageId=%s, error=%s',
         attempt, messageView.messageId, err,
       );
@@ -304,7 +326,7 @@ export class ProcessQueue {
         await this.#changeInvisibleDurationLater(messageView, duration, 
attempt + 1);
       }
     } catch (err) {
-      (this.#consumer as any).logger?.warn(
+      this.#logger.warn(
         'Failed to change invisible duration, attempt=%d, duration=%dms, 
messageId=%s, error=%s',
         attempt, duration, messageView.messageId, err,
       );
@@ -334,13 +356,13 @@ export class ProcessQueue {
     const maxAttempts = retryPolicy?.getMaxAttempts() ?? 1;
     const attempt = messageView.deliveryAttempt ?? 1;
     const messageId = messageView.messageId;
-    const clientId = (this.#consumer as any).clientId;
+    const clientId = this.#clientId;
 
     if (consumeResult === ConsumeResult.FAILURE && attempt < maxAttempts) {
       const nextAttemptDelay = retryPolicy?.getNextAttemptDelay(attempt) ?? 0;
       // Increment delivery attempt before redelivering
       messageView.incrementAndGetDeliveryAttempt();
-      (this.#consumer as any).logger?.debug(
+      this.#logger.debug?.(
         'Prepare to redeliver the fifo message because of the consumption 
failure, maxAttempts=%d, '
         + 'attempt=%d, mq=%s, messageId=%s, nextAttemptDelay=%d, clientId=%s',
         maxAttempts, messageView.deliveryAttempt, this.#mq, messageId, 
nextAttemptDelay, clientId,
@@ -355,14 +377,14 @@ export class ProcessQueue {
       await this.#ackMessage(messageView);
     } else if (consumeResult instanceof ConsumeResultSuspend) {
       const suspendTimeMs = consumeResult.suspendTimeMs;
-      (this.#consumer as any).logger?.info(
+      this.#logger.info(
         'Suspend consumption, consumerGroup=%s, topic=%s, liteTopic=%s, 
messageId=%s, result=%s',
         this.#consumer.getConsumerGroup(), messageView.topic, 
messageView.liteTopic ?? '',
         messageId, consumeResult,
       );
       await this.#changeInvisibleDuration(messageView, suspendTimeMs);
     } else {
-      (this.#consumer as any).logger?.info(
+      this.#logger.info(
         'Failed to consume fifo message finally, run out of attempt times, 
maxAttempts=%d, attempt=%d, '
         + 'mq=%s, messageId=%s, clientId=%s',
         maxAttempts, attempt, this.#mq, messageId, clientId,
@@ -429,8 +451,8 @@ export class ProcessQueue {
 
   #convertSuspendResultIfNeeded(consumeResult: ConsumeResult): ConsumeResult {
     if (consumeResult instanceof ConsumeResultSuspend) {
-      if (!(this.#consumer as any).isLiteConsumer?.()) {
-        (this.#consumer as any).logger?.warn(
+      if (!this.#liteConsumer) {
+        this.#logger.warn(
           'Only LitePushConsumer support ConsumeResultSuspend! Convert to 
ConsumeResult.FAILURE, '
           + 'consumerGroup=%s, consumerType=%s',
           this.#consumer.getConsumerGroup(), this.#consumer.constructor.name,
diff --git a/nodejs/src/consumer/PushConsumer.ts 
b/nodejs/src/consumer/PushConsumer.ts
index a723ed0c..f6deb857 100644
--- a/nodejs/src/consumer/PushConsumer.ts
+++ b/nodejs/src/consumer/PushConsumer.ts
@@ -627,11 +627,15 @@ export class PushConsumer extends Consumer {
     if (this.#processQueueTable.has(mqKey)) {
       return null;
     }
-    const processQueue = new ProcessQueue(this, mq, filterExpression);
+    const processQueue = new ProcessQueue(this, mq, filterExpression, 
this.#processQueueContext());
     this.#processQueueTable.set(mqKey, { mq, pq: processQueue });
     return processQueue;
   }
 
+  #processQueueContext() {
+    return { logger: this.logger, clientId: this.clientId, liteConsumer: 
this.isLiteConsumer() };
+  }
+
   /**
    * Create a virtual process queue for Lite consumer.
    * Lite consumers use a special message queue with queueId=-1 to receive 
messages.
@@ -678,7 +682,7 @@ export class PushConsumer extends Consumer {
       return;
     }
 
-    const processQueue = new ProcessQueue(this, virtualMq, filterExpression);
+    const processQueue = new ProcessQueue(this, virtualMq, filterExpression, 
this.#processQueueContext());
     this.#processQueueTable.set(mqKey, { mq: virtualMq, pq: processQueue });
 
     this.logger.info('Created virtual process queue for Lite consumer, mq=%s, 
clientId=%s',
diff --git a/nodejs/src/consumer/StandardConsumeService.ts 
b/nodejs/src/consumer/StandardConsumeService.ts
index 1a40a754..3195d97c 100644
--- a/nodejs/src/consumer/StandardConsumeService.ts
+++ b/nodejs/src/consumer/StandardConsumeService.ts
@@ -18,6 +18,7 @@
 import { MessageView } from '../message';
 import { MessageInterceptor } from '../hook';
 import { ConsumeService } from './ConsumeService';
+import { ConsumeResult } from './ConsumeResult';
 import { MessageListener } from './MessageListener';
 import type { ProcessQueue } from './ProcessQueue';
 import { getDefaultLogger } from '../client';
@@ -50,9 +51,17 @@ export class StandardConsumeService extends ConsumeService {
           pq.eraseMessage(messageView, result);
         })
         .catch(err => {
-          this.logger.error('Message consumption failed, messageId=%s, 
error=%s',
+          // consumeMessage never rejects, so this is a settlement that threw 
synchronously.
+          // Nack the message so it still leaves the cache and releases its 
permit; otherwise
+          // it would hold the permit until shutdown times out waiting for it.
+          this.logger.error('Failed to settle the consumed message, nack it 
instead, messageId=%s, error=%s',
             messageView.messageId, err);
-          // Should never reach here.
+          try {
+            pq.eraseMessage(messageView, ConsumeResult.FAILURE);
+          } catch (e) {
+            this.logger.error('Failed to nack the message after the settlement 
failure, messageId=%s, error=%s',
+              messageView.messageId, e);
+          }
         });
     }
   }
diff --git a/nodejs/test/consumer/FifoConsumeService.test.ts 
b/nodejs/test/consumer/FifoConsumeService.test.ts
index 40e3752e..25454349 100644
--- a/nodejs/test/consumer/FifoConsumeService.test.ts
+++ b/nodejs/test/consumer/FifoConsumeService.test.ts
@@ -20,12 +20,17 @@
  */
 
 import * as assert from 'node:assert';
+import * as sinon from 'sinon';
 import { FifoConsumeService } from '../../src/consumer/FifoConsumeService';
 import { MessageListener } from '../../src/consumer/MessageListener';
 import { ConsumeResult } from '../../src/consumer/ConsumeResult';
 import type { MessageView } from '../../src/message';
+import { deferred } from '../support/fakes';
+import { buildMessageView, createProcessQueueHarness, flushPromises } from 
'./processQueueHarness';
 
 describe('FifoConsumeService', () => {
+  afterEach(() => sinon.restore());
+
   it('should support enableFifoConsumeAccelerator option', () => {
     const messageListener: MessageListener = {
       // eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -46,4 +51,72 @@ describe('FifoConsumeService', () => {
     const serviceDefault = new FifoConsumeService('test-client', 
messageListener);
     assert.ok(serviceDefault, 'Should create service with default accelerator 
setting');
   });
+
+  it('redelivers a failed message locally until maxAttempts and then forwards 
it to the DLQ', async () => {
+    const h = createProcessQueueHarness({ maxAttempts: 3 });
+    const consume = sinon.stub().resolves(ConsumeResult.FAILURE);
+    const service = new FifoConsumeService('client-a', { consume });
+    h.setConsumeService(service);
+    const message = buildMessageView({ deliveryAttempt: 1 });
+    h.pq.cacheMessages([ message ]);
+
+    service.consume(h.pq, [ message ]);
+    await flushPromises();
+
+    sinon.assert.calledThrice(consume);
+    assert.strictEqual(message.deliveryAttempt, 3);
+    sinon.assert.calledOnce(h.consumer.forwardMessageToDeadLetterQueueViaRpc);
+    sinon.assert.notCalled(h.consumer.ackMessageViaRpc);
+    sinon.assert.notCalled(h.consumer.changeInvisibleDurationViaRpc);
+    assert.strictEqual(h.pq.cachedMessagesCount(), 0);
+  });
+
+  for (const accelerator of [ true, false ]) {
+    it(`consumes message groups ${accelerator ? 'in parallel' : 'serially'} 
when the accelerator is ${accelerator ? 'on' : 'off'}`, async () => {
+      const h = createProcessQueueHarness();
+      const started: string[] = [];
+      const results = new Map<string, ReturnType<typeof 
deferred<ConsumeResult>>>();
+      const service = new FifoConsumeService('client-a', {
+        consume(messageView) {
+          started.push(messageView.messageId);
+          const result = deferred<ConsumeResult>();
+          results.set(messageView.messageId, result);
+          return result.promise;
+        },
+      }, accelerator);
+      h.setConsumeService(service);
+      const messages = [
+        buildMessageView({ messageId: 'g1-a', messageGroup: 'g1' }),
+        buildMessageView({ messageId: 'g1-b', messageGroup: 'g1' }),
+        buildMessageView({ messageId: 'g2-a', messageGroup: 'g2' }),
+      ];
+      h.pq.cacheMessages(messages);
+
+      service.consume(h.pq, messages);
+      await flushPromises();
+      assert.deepStrictEqual(started, accelerator ? [ 'g1-a', 'g2-a' ] : [ 
'g1-a' ]);
+
+      results.get('g1-a')!.resolve(ConsumeResult.SUCCESS);
+      await flushPromises();
+      assert.deepStrictEqual(started, accelerator ? [ 'g1-a', 'g2-a', 'g1-b' ] 
: [ 'g1-a', 'g1-b' ]);
+    });
+  }
+
+  it('discards a corrupted message to the DLQ without blocking the next one', 
async () => {
+    const h = createProcessQueueHarness();
+    const consume = sinon.stub().resolves(ConsumeResult.SUCCESS);
+    const service = new FifoConsumeService('client-a', { consume });
+    h.setConsumeService(service);
+    const corrupted = buildMessageView({ messageId: 'corrupted', checksum: 
'invalid' });
+    const valid = buildMessageView({ messageId: 'valid' });
+    h.pq.cacheMessages([ corrupted, valid ]);
+
+    service.consume(h.pq, [ corrupted, valid ]);
+    await flushPromises();
+
+    sinon.assert.calledOnceWithExactly(consume, valid);
+    sinon.assert.calledOnce(h.consumer.forwardMessageToDeadLetterQueueViaRpc);
+    sinon.assert.calledOnce(h.consumer.ackMessageViaRpc);
+    assert.strictEqual(h.pq.cachedMessagesCount(), 0);
+  });
 });
diff --git a/nodejs/test/consumer/ProcessQueue.test.ts 
b/nodejs/test/consumer/ProcessQueue.test.ts
index 268f7611..e23689e6 100644
--- a/nodejs/test/consumer/ProcessQueue.test.ts
+++ b/nodejs/test/consumer/ProcessQueue.test.ts
@@ -16,9 +16,23 @@
  */
 
 import * as assert from 'node:assert';
+import * as sinon from 'sinon';
 import { ProcessQueue } from '../../src/consumer/ProcessQueue';
 import { FilterExpression } from '../../src/consumer/FilterExpression';
+import { ConsumeResult, ConsumeResultSuspend } from 
'../../src/consumer/ConsumeResult';
+import type { ConsumeService } from '../../src/consumer/ConsumeService';
+import { TooManyRequestsException } from '../../src/exception';
 import { Code } from '../../proto/apache/rocketmq/v2/definition_pb';
+import { deferred } from '../support/fakes';
+import { buildRoute } from '../support/protobuf';
+import {
+  ackResponse,
+  buildMessageView,
+  changeInvisibleDurationResponse,
+  createProcessQueueHarness,
+  flushPromises,
+  useFakeTimers,
+} from './processQueueHarness';
 
 function makeConsumer(consumeConcurrentlyMax: number): any {
   return {
@@ -85,3 +99,316 @@ describe('ProcessQueue consumption permit (backpressure)', 
() => {
     assert.strictEqual(pq.availablePermits(), 2);
   });
 });
+
+describe('ProcessQueue receive loop', () => {
+  let clock: sinon.SinonFakeTimers;
+  const never = () => new Promise<never>(() => undefined);
+
+  beforeEach(() => {
+    clock = useFakeTimers();
+  });
+
+  afterEach(() => {
+    clock.restore();
+    sinon.restore();
+  });
+
+  it('caches received messages, hands them to the consume service and receives 
again', async () => {
+    const h = createProcessQueueHarness();
+    const consume = sinon.stub();
+    h.setConsumeService({ consume } as unknown as ConsumeService);
+    const message = buildMessageView();
+    h.consumer.receiveMessage.onFirstCall().resolves([ message ]);
+    h.consumer.receiveMessage.returns(never());
+
+    h.pq.fetchMessageImmediately();
+    await flushPromises();
+
+    assert.strictEqual(h.pq.cachedMessagesCount(), 1);
+    assert.strictEqual(h.pq.cachedMessageBytes(), message.body.length);
+    sinon.assert.calledOnceWithExactly(consume, h.pq, [ message ]);
+    sinon.assert.calledTwice(h.consumer.receiveMessage);
+  });
+
+  it('bounds the batch size by the remaining permits', async () => {
+    const h = createProcessQueueHarness({ consumeConcurrentlyMax: 4 });
+    h.consumer.receiveMessage.returns(never());
+    h.pq.cacheMessages([ buildMessageView() ]);
+
+    h.pq.receiveMessage();
+
+    
assert.strictEqual(h.consumer.wrapPushReceiveMessageRequest.firstCall.args[0], 
3);
+  });
+
+  [
+    { name: 'message count', options: { cacheMessageCount: 1 } },
+    { name: 'message bytes', options: { cacheMessageBytes: 1 } },
+  ].forEach(({ name, options }) => {
+    it(`backs off while the cache is full by ${name}`, async () => {
+      const h = createProcessQueueHarness(options);
+      h.consumer.receiveMessage.returns(never());
+      const message = buildMessageView();
+      h.pq.cacheMessages([ message ]);
+
+      h.pq.receiveMessage();
+      await clock.tickAsync(2000);
+      sinon.assert.notCalled(h.consumer.receiveMessage);
+
+      h.pq.discardMessage(message);
+      await flushPromises();
+      await clock.tickAsync(1000);
+      sinon.assert.calledOnce(h.consumer.receiveMessage);
+    });
+  });
+
+  it('backs off while every permit is in use', async () => {
+    const h = createProcessQueueHarness({ consumeConcurrentlyMax: 1 });
+    h.consumer.receiveMessage.returns(never());
+    const message = buildMessageView();
+    h.pq.cacheMessages([ message ]);
+
+    h.pq.receiveMessage();
+    await clock.tickAsync(100);
+    sinon.assert.notCalled(h.consumer.receiveMessage);
+
+    h.pq.discardMessage(message);
+    await flushPromises();
+    await clock.tickAsync(20);
+    sinon.assert.calledOnce(h.consumer.receiveMessage);
+  });
+
+  [
+    { name: 'flow control', error: new 
TooManyRequestsException(Code.TOO_MANY_REQUESTS, 'throttled'), delay: 20 },
+    { name: 'failure', error: new Error('network'), delay: 1000 },
+  ].forEach(({ name, error, delay }) => {
+    it(`retries a failed receive after the ${name} backoff`, async () => {
+      const h = createProcessQueueHarness();
+      h.consumer.receiveMessage.onFirstCall().rejects(error);
+      h.consumer.receiveMessage.returns(never());
+
+      h.pq.fetchMessageImmediately();
+      await flushPromises();
+      await clock.tickAsync(delay - 1);
+      sinon.assert.calledOnce(h.consumer.receiveMessage);
+      await clock.tickAsync(1);
+      sinon.assert.calledTwice(h.consumer.receiveMessage);
+    });
+  });
+
+  it('reuses the attemptId after a failure and generates a new one after a 
success', async () => {
+    const h = createProcessQueueHarness();
+    h.consumer.receiveMessage.onFirstCall().rejects(new Error('network'));
+    h.consumer.receiveMessage.onSecondCall().resolves([]);
+    h.consumer.receiveMessage.returns(never());
+
+    h.pq.fetchMessageImmediately();
+    await flushPromises();
+    await clock.tickAsync(1000);
+    await flushPromises();
+
+    const attemptIds = 
h.consumer.wrapPushReceiveMessageRequest.getCalls().map(call => call.args[4]);
+    assert.strictEqual(attemptIds.length, 3);
+    assert.ok(attemptIds[0]);
+    assert.strictEqual(attemptIds[1], attemptIds[0]);
+    assert.notStrictEqual(attemptIds[2], attemptIds[1]);
+  });
+
+  ([ 'drop', 'abort' ] as const).forEach(stop => {
+    it(`schedules no retry for a receive failing after ${stop}`, async () => {
+      const h = createProcessQueueHarness();
+      const inflight = deferred<never>();
+      h.consumer.receiveMessage.onFirstCall().returns(inflight.promise);
+
+      h.pq.fetchMessageImmediately();
+      h.pq[stop]();
+      inflight.reject(new Error('network'));
+      await flushPromises();
+
+      assert.strictEqual(clock.countTimers(), 0);
+      h.pq.fetchMessageImmediately();
+      h.pq.receiveMessage();
+      sinon.assert.calledOnce(h.consumer.receiveMessage);
+    });
+
+    it(`ignores a retry timer that fires after ${stop}`, async () => {
+      const h = createProcessQueueHarness();
+      h.consumer.receiveMessage.onFirstCall().rejects(new Error('network'));
+
+      h.pq.fetchMessageImmediately();
+      await flushPromises();
+      h.pq[stop]();
+      await clock.tickAsync(1000);
+
+      sinon.assert.calledOnce(h.consumer.receiveMessage);
+    });
+  });
+});
+
+describe('ProcessQueue settlement', () => {
+  let clock: sinon.SinonFakeTimers;
+
+  beforeEach(() => {
+    clock = useFakeTimers();
+  });
+
+  afterEach(() => {
+    clock.restore();
+    sinon.restore();
+  });
+
+  it('acks a successfully consumed message and restores the cache and permit', 
async () => {
+    const h = createProcessQueueHarness({ consumeConcurrentlyMax: 2 });
+    const message = buildMessageView();
+    h.pq.cacheMessages([ message ]);
+
+    h.pq.eraseMessage(message, ConsumeResult.SUCCESS);
+    await flushPromises();
+
+    sinon.assert.calledOnce(h.consumer.ackMessageViaRpc);
+    sinon.assert.notCalled(h.consumer.changeInvisibleDurationViaRpc);
+    sinon.assert.calledOnce(h.consumer.incrementConsumptionOkQuantity);
+    assert.strictEqual(h.pq.cachedMessagesCount(), 0);
+    assert.strictEqual(h.pq.cachedMessageBytes(), 0);
+    assert.strictEqual(h.pq.availablePermits(), 2);
+  });
+
+  it('nacks a failed message with the retry policy delay', async () => {
+    const h = createProcessQueueHarness({ nextAttemptDelay: 5000 });
+    const message = buildMessageView({ deliveryAttempt: 2 });
+    h.pq.cacheMessages([ message ]);
+
+    h.pq.eraseMessage(message, ConsumeResult.FAILURE);
+    await flushPromises();
+
+    sinon.assert.calledOnceWithExactly(h.retryPolicy.getNextAttemptDelay, 2);
+    
sinon.assert.calledOnceWithExactly(h.consumer.wrapChangeInvisibleDurationRequest,
 message, 5000);
+    sinon.assert.calledOnce(h.consumer.incrementConsumptionErrorQuantity);
+    sinon.assert.notCalled(h.consumer.ackMessageViaRpc);
+    assert.strictEqual(h.pq.cachedMessagesCount(), 0);
+  });
+
+  it('retries a failed ack at a fixed interval until it succeeds', async () => 
{
+    const h = createProcessQueueHarness();
+    h.consumer.ackMessageViaRpc.onFirstCall().rejects(new Error('network'));
+    
h.consumer.ackMessageViaRpc.onSecondCall().resolves(ackResponse(Code.INTERNAL_SERVER_ERROR));
+    const message = buildMessageView();
+    h.pq.cacheMessages([ message ]);
+
+    h.pq.eraseMessage(message, ConsumeResult.SUCCESS);
+    await flushPromises();
+    sinon.assert.calledOnce(h.consumer.ackMessageViaRpc);
+    await clock.tickAsync(1000);
+    sinon.assert.calledTwice(h.consumer.ackMessageViaRpc);
+    assert.strictEqual(h.pq.cachedMessagesCount(), 1);
+    await clock.tickAsync(1000);
+    await flushPromises();
+
+    sinon.assert.calledThrice(h.consumer.ackMessageViaRpc);
+    assert.strictEqual(h.pq.cachedMessagesCount(), 0);
+  });
+
+  it('retries a failed nack until it succeeds', async () => {
+    const h = createProcessQueueHarness();
+    h.consumer.changeInvisibleDurationViaRpc.onFirstCall()
+      .resolves(changeInvisibleDurationResponse(Code.INTERNAL_SERVER_ERROR));
+    const message = buildMessageView();
+    h.pq.cacheMessages([ message ]);
+
+    h.pq.eraseMessage(message, ConsumeResult.FAILURE);
+    await flushPromises();
+    assert.strictEqual(h.pq.cachedMessagesCount(), 1);
+    await clock.tickAsync(1000);
+    await flushPromises();
+
+    sinon.assert.calledTwice(h.consumer.changeInvisibleDurationViaRpc);
+    assert.strictEqual(h.pq.cachedMessagesCount(), 0);
+  });
+
+  it('gives up the ack on INVALID_RECEIPT_HANDLE', async () => {
+    const h = createProcessQueueHarness();
+    
h.consumer.ackMessageViaRpc.resolves(ackResponse(Code.INVALID_RECEIPT_HANDLE));
+    const message = buildMessageView();
+    h.pq.cacheMessages([ message ]);
+
+    h.pq.eraseMessage(message, ConsumeResult.SUCCESS);
+    await flushPromises();
+    await clock.tickAsync(5000);
+
+    sinon.assert.calledOnce(h.consumer.ackMessageViaRpc);
+    assert.strictEqual(h.pq.cachedMessagesCount(), 0);
+  });
+
+  it('releases the permit only once when a message is settled twice', async () 
=> {
+    const h = createProcessQueueHarness({ consumeConcurrentlyMax: 2 });
+    const message = buildMessageView();
+    h.pq.cacheMessages([ message ]);
+
+    h.pq.eraseMessage(message, ConsumeResult.SUCCESS);
+    h.pq.discardMessage(message);
+    h.pq.discardFifoMessage(message);
+    await flushPromises();
+
+    assert.strictEqual(h.pq.availablePermits(), 2);
+    assert.strictEqual(h.pq.cachedMessagesCount(), 0);
+  });
+});
+
+describe('ProcessQueue consumer context', () => {
+  afterEach(() => sinon.restore());
+
+  it('converts a suspend result to FAILURE for a non-lite consumer', async () 
=> {
+    const h = createProcessQueueHarness({ nextAttemptDelay: 5000 });
+    const message = buildMessageView();
+    h.pq.cacheMessages([ message ]);
+
+    h.pq.eraseMessage(message, ConsumeResultSuspend.of(1000));
+    await flushPromises();
+
+    sinon.assert.calledWithMatch(h.logger.warn, /Only LitePushConsumer support 
ConsumeResultSuspend/);
+    
sinon.assert.calledOnceWithExactly(h.consumer.wrapChangeInvisibleDurationRequest,
 message, 5000);
+    sinon.assert.calledOnce(h.consumer.incrementConsumptionErrorQuantity);
+  });
+
+  it('suspends a lite message for the requested time', async () => {
+    const h = createProcessQueueHarness({ liteConsumer: true, 
nextAttemptDelay: 5000 });
+    const message = buildMessageView({ liteTopic: 'lite-a' });
+    h.pq.cacheMessages([ message ]);
+
+    await h.pq.eraseFifoMessage(message, ConsumeResultSuspend.of(1000));
+
+    sinon.assert.notCalled(h.logger.warn);
+    
sinon.assert.calledOnceWithExactly(h.consumer.wrapChangeInvisibleDurationRequest,
 message, 1000);
+    assert.strictEqual(h.pq.cachedMessagesCount(), 0);
+  });
+
+  it('keeps reading the logger and lite flag from the consumer for 
three-argument construction', async () => {
+    const h = createProcessQueueHarness();
+    const legacyConsumer = { ...h.consumer, logger: h.logger, clientId: 
'client-legacy', isLiteConsumer: () => true };
+    const pq = new ProcessQueue(legacyConsumer as any, 
buildRoute().messageQueues[0], new FilterExpression('*'));
+    const message = buildMessageView({ liteTopic: 'lite-a' });
+    pq.cacheMessages([ message ]);
+
+    await pq.eraseFifoMessage(message, ConsumeResultSuspend.of(1000));
+
+    sinon.assert.calledWithMatch(h.logger.info, /Suspend consumption/);
+    
sinon.assert.calledOnceWithExactly(h.consumer.wrapChangeInvisibleDurationRequest,
 message, 1000);
+  });
+
+  it('redelivers a FIFO message locally with a logger that has no debug 
method', async () => {
+    const h = createProcessQueueHarness();
+    const consumeMessage = sinon.stub().resolves(ConsumeResult.SUCCESS);
+    h.setConsumeService({ consumeMessage } as unknown as ConsumeService);
+    // debug is optional on ILogger, e.g. a custom logger passed to the 
consumer options.
+    const logger = { info: sinon.stub(), warn: sinon.stub(), error: 
sinon.stub() };
+    const pq = new ProcessQueue({ ...h.consumer, logger } as any, 
buildRoute().messageQueues[0],
+      new FilterExpression('*'), { logger, clientId: 'client-a', liteConsumer: 
false });
+    const message = buildMessageView();
+    pq.cacheMessages([ message ]);
+
+    await pq.eraseFifoMessage(message, ConsumeResult.FAILURE);
+
+    sinon.assert.calledOnce(consumeMessage);
+    sinon.assert.calledOnce(h.consumer.ackMessageViaRpc);
+    assert.strictEqual(pq.cachedMessagesCount(), 0);
+  });
+});
diff --git a/nodejs/test/consumer/PushConsumerAssignment.test.ts 
b/nodejs/test/consumer/PushConsumerAssignment.test.ts
new file mode 100644
index 00000000..d828ef26
--- /dev/null
+++ b/nodejs/test/consumer/PushConsumerAssignment.test.ts
@@ -0,0 +1,173 @@
+/**
+ * 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 * as assert from 'node:assert';
+import * as sinon from 'sinon';
+import { Assignment as AssignmentPB } from 
'../../proto/apache/rocketmq/v2/definition_pb';
+import {
+  NotifyClientTerminationResponse,
+  QueryAssignmentResponse,
+  QueryRouteResponse,
+  ReceiveMessageResponse,
+} from '../../proto/apache/rocketmq/v2/service_pb';
+import { ConsumeResult } from '../../src/consumer/ConsumeResult';
+import type { ConsumeService } from '../../src/consumer/ConsumeService';
+import { PushConsumer } from '../../src/consumer/PushConsumer';
+import { createSilentLogger, deferred, FakeTelemetryStream, 
installFakeRpcClientManager } from '../support/fakes';
+import { buildRoute, buildStatus } from '../support/protobuf';
+import { flushPromises, useFakeTimers } from './processQueueHarness';
+
+const route = buildRoute({ topic: 'topic-a', queuesPerBroker: 3 });
+
+function assignmentResponse(queueIds: number[]) {
+  const response = new QueryAssignmentResponse().setStatus(buildStatus());
+  for (const id of queueIds) {
+    response.addAssignments(new 
AssignmentPB().setMessageQueue(route.messageQueues[id].toProtobuf()));
+  }
+  return response;
+}
+
+const queueIdsOf = (consumer: PushConsumer) => consumer.processQueues().map(pq 
=> pq.getMessageQueue().queueId);
+
+describe('PushConsumer assignment scanning', () => {
+  let clock: sinon.SinonFakeTimers;
+  let consumer: PushConsumer;
+  let rpc: ReturnType<typeof installFakeRpcClientManager>;
+  let logger: ReturnType<typeof createSilentLogger>;
+  let receiveGate: ReturnType<typeof deferred<ReceiveMessageResponse[]>>;
+  let shutdown: boolean;
+
+  beforeEach(() => {
+    clock = useFakeTimers();
+    logger = createSilentLogger();
+    consumer = new PushConsumer({
+      endpoints: '127.0.0.1:8081',
+      namespace: '',
+      consumerGroup: 'group-a',
+      subscriptions: new Map([[ 'topic-a', '*' ]]),
+      messageListener: { consume: async () => ConsumeResult.SUCCESS },
+      logger,
+    });
+    rpc = installFakeRpcClientManager(consumer);
+    rpc.queryRoute.resolves(new QueryRouteResponse().setStatus(buildStatus())
+      .setMessageQueuesList(route.messageQueues.map(mq => mq.toProtobuf())));
+    rpc.telemetry.callsFake(() => new FakeTelemetryStream().asGrpcStream());
+    rpc.notifyClientTermination.resolves(new 
NotifyClientTerminationResponse().setStatus(buildStatus()));
+    rpc.queryAssignment.resolves(assignmentResponse([ 0, 1 ]));
+    // Receives stay in flight until the gate opens, so process queues never 
spin.
+    receiveGate = deferred<ReceiveMessageResponse[]>();
+    rpc.receiveMessage.callsFake(() => receiveGate.promise);
+    sinon.stub(consumer, 'getConsumeService').returns({ consume: sinon.stub() 
} as unknown as ConsumeService);
+    shutdown = false;
+  });
+
+  afterEach(async () => {
+    if (!shutdown) {
+      await shutdownConsumer();
+    }
+    clock.restore();
+    sinon.restore();
+  });
+
+  async function shutdownConsumer() {
+    shutdown = true;
+    const done = consumer.shutdown();
+    receiveGate.resolve([ new 
ReceiveMessageResponse().setStatus(buildStatus()) ]);
+    await clock.tickAsync(2000);
+    await done;
+  }
+
+  async function startScanning() {
+    (consumer as any).startAssignmentScanning();
+    await clock.tickAsync(1000);
+    await flushPromises();
+  }
+
+  it('creates a receiving process queue for every assignment on the first 
scan', async () => {
+    await startScanning();
+
+    assert.deepStrictEqual(queueIdsOf(consumer), [ 0, 1 ]);
+    sinon.assert.calledTwice(rpc.receiveMessage);
+  });
+
+  it('waits for the next scan when the first assignments are empty', async () 
=> {
+    rpc.queryAssignment.resolves(assignmentResponse([]));
+    await startScanning();
+    assert.deepStrictEqual(queueIdsOf(consumer), []);
+
+    rpc.queryAssignment.resolves(assignmentResponse([ 2 ]));
+    await clock.tickAsync(5000);
+    assert.deepStrictEqual(queueIdsOf(consumer), [ 2 ]);
+  });
+
+  it('drops the process queue of a removed assignment and creates one for an 
added assignment', async () => {
+    await startScanning();
+    const [ kept ] = consumer.processQueues();
+
+    rpc.queryAssignment.resolves(assignmentResponse([ 0, 2 ]));
+    await clock.tickAsync(5000);
+
+    assert.deepStrictEqual(queueIdsOf(consumer), [ 0, 2 ]);
+    assert.strictEqual(consumer.processQueues()[0], kept);
+  });
+
+  it('drops every process queue when the remote assignments become empty', 
async () => {
+    await startScanning();
+
+    rpc.queryAssignment.resolves(assignmentResponse([]));
+    await clock.tickAsync(5000);
+
+    assert.deepStrictEqual(queueIdsOf(consumer), []);
+    sinon.assert.calledWithMatch(logger.warn, /acquired empty assignments from 
remote, but existed assignments/);
+  });
+
+  it('recreates an expired process queue on the next scan', async () => {
+    await startScanning();
+    const before = consumer.processQueues();
+
+    // Expiry needs (longPollingTimeout + requestTimeout) * 3 = 99s without a 
new receive.
+    await clock.tickAsync(100_000);
+
+    const after = consumer.processQueues();
+    assert.deepStrictEqual(queueIdsOf(consumer), [ 0, 1 ]);
+    assert.ok(after.every(pq => !before.includes(pq)));
+    sinon.assert.callCount(rpc.receiveMessage, 4);
+  });
+
+  it('keeps the existing process queues when a scan fails', async () => {
+    await startScanning();
+    const before = consumer.processQueues();
+
+    rpc.queryAssignment.rejects(new Error('query assignment failed'));
+    await clock.tickAsync(5000);
+
+    assert.deepStrictEqual(consumer.processQueues(), before);
+    sinon.assert.calledWithMatch(logger.error, /Exception raised while 
scanning the assignments, topic=%s/);
+  });
+
+  it('stops scanning and creates no process queue after shutdown', async () => 
{
+    await startScanning();
+    const scans = rpc.queryAssignment.callCount;
+
+    await shutdownConsumer();
+    await clock.tickAsync(10_000);
+
+    assert.strictEqual(rpc.queryAssignment.callCount, scans);
+    assert.deepStrictEqual(consumer.processQueues(), []);
+    sinon.assert.calledTwice(rpc.receiveMessage);
+  });
+});
diff --git a/nodejs/test/consumer/PushConsumerGaugeObserver.test.ts 
b/nodejs/test/consumer/PushConsumerGaugeObserver.test.ts
new file mode 100644
index 00000000..b510ecf4
--- /dev/null
+++ b/nodejs/test/consumer/PushConsumerGaugeObserver.test.ts
@@ -0,0 +1,78 @@
+/**
+ * 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 * as assert from 'node:assert';
+import { Assignment } from '../../src/consumer/Assignment';
+import { Assignments } from '../../src/consumer/Assignments';
+import type { ProcessQueue } from '../../src/consumer/ProcessQueue';
+import { PushConsumerGaugeObserver } from 
'../../src/consumer/PushConsumerGaugeObserver';
+import { GaugeEnum } from '../../src/metrics/GaugeEnum';
+import { MetricLabels } from '../../src/metrics/MetricLabels';
+import { buildRoute } from '../support/protobuf';
+
+function assignments(queueIds: number[]) {
+  // A fresh route per call, so equality never relies on object identity.
+  const queues = buildRoute({ queuesPerBroker: 4 }).messageQueues;
+  return new Assignments(queueIds.map(id => new Assignment(queues[id])));
+}
+
+describe('Assignments', () => {
+  it('compares assignments by message queue in order', () => {
+    assert.ok(assignments([ 0, 1 ]).equals(assignments([ 0, 1 ])));
+    assert.strictEqual(assignments([ 0, 1 ]).hashCode(), assignments([ 0, 1 
]).hashCode());
+    assert.ok(!assignments([ 0, 1 ]).equals(assignments([ 1, 0 ])));
+    assert.ok(!assignments([ 0, 1 ]).equals(assignments([ 0 ])));
+    assert.ok(!assignments([ 0 ]).equals(undefined));
+    assert.ok(assignments([]).equals(assignments([])));
+  });
+
+  it('distinguishes queues of different topics', () => {
+    const other = new Assignments([ new Assignment(buildRoute({ topic: 
'topic-b' }).messageQueues[0]) ]);
+    assert.ok(!assignments([ 0 ]).equals(other));
+  });
+});
+
+describe('PushConsumerGaugeObserver', () => {
+  const queue = (topic: string, count: number, bytes: number) =>
+    ({ topic, cachedMessagesCount: () => count, cachedMessageBytes: () => 
bytes }) as unknown as ProcessQueue;
+  const observer = new PushConsumerGaugeObserver(
+    () => [ queue('topic-a', 1, 10), queue('topic-a', 2, 20), queue('topic-b', 
3, 30) ], 'client-a', 'group-a');
+
+  function valuesByTopic(gauge: GaugeEnum) {
+    const result = new Map<unknown, number>();
+    for (const [ attributes, value ] of observer.getValues(gauge)) {
+      assert.strictEqual(attributes[MetricLabels.CLIENT_ID], 'client-a');
+      assert.strictEqual(attributes[MetricLabels.CONSUMER_GROUP], 'group-a');
+      result.set(attributes[MetricLabels.TOPIC], value);
+    }
+    return result;
+  }
+
+  it('reports both consumer cache gauges', () => {
+    assert.deepStrictEqual(observer.getGauges(), [ 
GaugeEnum.CONSUMER_CACHED_MESSAGES, GaugeEnum.CONSUMER_CACHED_BYTES ]);
+  });
+
+  it('sums the cached message count and bytes of all queues per topic', () => {
+    assert.deepStrictEqual(valuesByTopic(GaugeEnum.CONSUMER_CACHED_MESSAGES), 
new Map([[ 'topic-a', 3 ], [ 'topic-b', 3 ]]));
+    assert.deepStrictEqual(valuesByTopic(GaugeEnum.CONSUMER_CACHED_BYTES), new 
Map([[ 'topic-a', 30 ], [ 'topic-b', 30 ]]));
+  });
+
+  it('reports nothing without process queues', () => {
+    const empty = new PushConsumerGaugeObserver(() => [], 'client-a', 
'group-a');
+    
assert.strictEqual(empty.getValues(GaugeEnum.CONSUMER_CACHED_MESSAGES).size, 0);
+  });
+});
diff --git a/nodejs/test/consumer/PushSubscriptionSettings.test.ts 
b/nodejs/test/consumer/PushSubscriptionSettings.test.ts
new file mode 100644
index 00000000..35b83209
--- /dev/null
+++ b/nodejs/test/consumer/PushSubscriptionSettings.test.ts
@@ -0,0 +1,101 @@
+/**
+ * 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 * as assert from 'node:assert';
+import {
+  ClientType,
+  CustomizedBackoff,
+  FilterType,
+  RetryPolicy as RetryPolicyPB,
+  Subscription,
+} from '../../proto/apache/rocketmq/v2/definition_pb';
+import { FilterExpression } from '../../src/consumer/FilterExpression';
+import { PushSubscriptionSettings } from 
'../../src/consumer/PushSubscriptionSettings';
+import { CustomizedBackoffRetryPolicy, ExponentialBackoffRetryPolicy } from 
'../../src/retry';
+import { Endpoints } from '../../src/route';
+import { createDuration } from '../../src/util';
+import { buildSettings } from '../support/protobuf';
+
+function createSettings(consumeConcurrentlyMax?: number) {
+  return new PushSubscriptionSettings('ns', 'client-a', 
ClientType.PUSH_CONSUMER, new Endpoints('127.0.0.1:8081'),
+    'group-a', 3000, new Map([[ 'topic-a', new FilterExpression('tag-a') ]]), 
undefined, consumeConcurrentlyMax);
+}
+
+describe('PushSubscriptionSettings', () => {
+  it('uses the defaults before the server settings arrive', () => {
+    const settings = createSettings();
+    assert.strictEqual(settings.isFifo(), false);
+    assert.strictEqual(settings.getReceiveBatchSize(), 32);
+    assert.strictEqual(settings.getLongPollingTimeout(), 30000);
+    assert.strictEqual(settings.getConsumeConcurrentlyMax(), 32);
+    assert.strictEqual(settings.getRetryPolicy(), undefined);
+  });
+
+  it('syncs fifo, batch size, long polling timeout and the exponential retry 
policy', () => {
+    const settings = createSettings(8);
+    const subscription = new 
Subscription().setFifo(true).setReceiveBatchSize(16)
+      .setLongPollingTimeout(createDuration(20500));
+
+    settings.sync(buildSettings({ clientType: ClientType.PUSH_CONSUMER, 
subscription }));
+
+    assert.strictEqual(settings.isFifo(), true);
+    assert.strictEqual(settings.getReceiveBatchSize(), 16);
+    assert.strictEqual(settings.getLongPollingTimeout(), 20500);
+    // The subscription settings carry no consumeConcurrentlyMax, so the local 
option is kept.
+    assert.strictEqual(settings.getConsumeConcurrentlyMax(), 8);
+    const retryPolicy = settings.getRetryPolicy();
+    assert.ok(retryPolicy instanceof ExponentialBackoffRetryPolicy);
+    assert.strictEqual(retryPolicy.getMaxAttempts(), 3);
+    assert.strictEqual(retryPolicy.getNextAttemptDelay(1), 1000);
+  });
+
+  it('syncs the customized retry policy', () => {
+    const settings = createSettings();
+    const retryPolicy = new 
RetryPolicyPB().setMaxAttempts(4).setCustomizedBackoff(
+      new CustomizedBackoff().setNextList([ createDuration(1000), 
createDuration(5000) ]));
+
+    settings.sync(buildSettings({ clientType: ClientType.PUSH_CONSUMER, 
subscription: new Subscription(), retryPolicy }));
+
+    const synced = settings.getRetryPolicy();
+    assert.ok(synced instanceof CustomizedBackoffRetryPolicy);
+    assert.strictEqual(synced.getMaxAttempts(), 4);
+    assert.strictEqual(synced.getNextAttemptDelay(2), 5000);
+  });
+
+  it('ignores settings without a subscription', () => {
+    const settings = createSettings();
+    settings.sync(buildSettings());
+    assert.strictEqual(settings.getRetryPolicy(), undefined);
+    assert.strictEqual(settings.getReceiveBatchSize(), 32);
+  });
+
+  it('writes the client type, access point, timeout, group and subscriptions 
to protobuf', () => {
+    const pb = createSettings().toProtobuf();
+
+    assert.strictEqual(pb.getClientType(), ClientType.PUSH_CONSUMER);
+    assert.strictEqual(pb.getAccessPoint()?.getAddressesList()[0].getHost(), 
'127.0.0.1');
+    assert.strictEqual(pb.getRequestTimeout()?.getSeconds(), 3);
+    assert.ok(pb.getUserAgent());
+    const subscription = pb.getSubscription()!;
+    assert.strictEqual(subscription.getGroup()?.getName(), 'group-a');
+    const entries = subscription.getSubscriptionsList();
+    assert.strictEqual(entries.length, 1);
+    assert.strictEqual(entries[0].getTopic()?.getName(), 'topic-a');
+    assert.strictEqual(entries[0].getExpression()?.getExpression(), 'tag-a');
+    assert.strictEqual(entries[0].getExpression()?.getType(), FilterType.TAG);
+  });
+});
diff --git a/nodejs/test/consumer/StandardConsumeService.test.ts 
b/nodejs/test/consumer/StandardConsumeService.test.ts
new file mode 100644
index 00000000..c9cc637d
--- /dev/null
+++ b/nodejs/test/consumer/StandardConsumeService.test.ts
@@ -0,0 +1,88 @@
+/**
+ * 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 * as assert from 'node:assert';
+import * as sinon from 'sinon';
+import { StandardConsumeService } from 
'../../src/consumer/StandardConsumeService';
+import { ConsumeResult } from '../../src/consumer/ConsumeResult';
+import { buildMessageView, createProcessQueueHarness, flushPromises } from 
'./processQueueHarness';
+
+describe('StandardConsumeService', () => {
+  afterEach(() => sinon.restore());
+
+  it('acks every successfully consumed message', async () => {
+    const h = createProcessQueueHarness();
+    const consume = sinon.stub().resolves(ConsumeResult.SUCCESS);
+    const service = new StandardConsumeService('client-a', { consume });
+    const messages = [ buildMessageView({ messageId: 'a' }), 
buildMessageView({ messageId: 'b' }) ];
+    h.pq.cacheMessages(messages);
+
+    service.consume(h.pq, messages);
+    await flushPromises();
+
+    sinon.assert.calledTwice(consume);
+    sinon.assert.calledTwice(h.consumer.ackMessageViaRpc);
+    assert.strictEqual(h.pq.cachedMessagesCount(), 0);
+  });
+
+  it('discards a corrupted message without calling the listener', async () => {
+    const h = createProcessQueueHarness();
+    const consume = sinon.stub().resolves(ConsumeResult.SUCCESS);
+    const service = new StandardConsumeService('client-a', { consume });
+    const corrupted = buildMessageView({ checksum: 'invalid' });
+    h.pq.cacheMessages([ corrupted ]);
+
+    service.consume(h.pq, [ corrupted ]);
+    await flushPromises();
+
+    sinon.assert.notCalled(consume);
+    sinon.assert.calledOnce(h.consumer.changeInvisibleDurationViaRpc);
+    sinon.assert.notCalled(h.consumer.ackMessageViaRpc);
+    assert.strictEqual(h.pq.cachedMessagesCount(), 0);
+  });
+
+  it('nacks a message whose listener throws', async () => {
+    const h = createProcessQueueHarness();
+    const service = new StandardConsumeService('client-a', { consume: 
sinon.stub().rejects(new Error('listener')) });
+    const message = buildMessageView();
+    h.pq.cacheMessages([ message ]);
+
+    service.consume(h.pq, [ message ]);
+    await flushPromises();
+
+    sinon.assert.calledOnce(h.consumer.incrementConsumptionErrorQuantity);
+    sinon.assert.calledOnce(h.consumer.changeInvisibleDurationViaRpc);
+    sinon.assert.notCalled(h.consumer.ackMessageViaRpc);
+    assert.strictEqual(h.pq.cachedMessagesCount(), 0);
+  });
+
+  it('nacks and evicts a message whose settlement throws', async () => {
+    const h = createProcessQueueHarness({ consumeConcurrentlyMax: 1 });
+    h.consumer.incrementConsumptionOkQuantity.throws(new Error('stats 
failed'));
+    const service = new StandardConsumeService('client-a', { consume: 
sinon.stub().resolves(ConsumeResult.SUCCESS) });
+    const message = buildMessageView();
+    h.pq.cacheMessages([ message ]);
+
+    service.consume(h.pq, [ message ]);
+    await flushPromises();
+
+    sinon.assert.notCalled(h.consumer.ackMessageViaRpc);
+    sinon.assert.calledOnce(h.consumer.changeInvisibleDurationViaRpc);
+    assert.strictEqual(h.pq.cachedMessagesCount(), 0);
+    assert.strictEqual(h.pq.availablePermits(), 1);
+  });
+});
diff --git a/nodejs/test/consumer/processQueueHarness.ts 
b/nodejs/test/consumer/processQueueHarness.ts
new file mode 100644
index 00000000..336f29c8
--- /dev/null
+++ b/nodejs/test/consumer/processQueueHarness.ts
@@ -0,0 +1,112 @@
+/**
+ * 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 * as sinon from 'sinon';
+import { Code } from '../../proto/apache/rocketmq/v2/definition_pb';
+import {
+  AckMessageResponse,
+  ChangeInvisibleDurationResponse,
+  ForwardMessageToDeadLetterQueueResponse,
+} from '../../proto/apache/rocketmq/v2/service_pb';
+import { ConsumeService } from '../../src/consumer/ConsumeService';
+import { FilterExpression } from '../../src/consumer/FilterExpression';
+import { ProcessQueue } from '../../src/consumer/ProcessQueue';
+import type { PushConsumer } from '../../src/consumer/PushConsumer';
+import { MessageView } from '../../src/message';
+import type { RetryPolicy } from '../../src/retry';
+import { createSilentLogger } from '../support/fakes';
+import { buildMessagePB, buildRoute, buildStatus } from '../support/protobuf';
+
+export const ackResponse = (code = Code.OK) => new 
AckMessageResponse().setStatus(buildStatus(code));
+export const changeInvisibleDurationResponse = (code = Code.OK) =>
+  new ChangeInvisibleDurationResponse().setStatus(buildStatus(code));
+export const forwardToDLQResponse = (code = Code.OK) =>
+  new ForwardMessageToDeadLetterQueueResponse().setStatus(buildStatus(code));
+
+export function buildMessageView(options: Parameters<typeof buildMessagePB>[0] 
= {}) {
+  return new MessageView(buildMessagePB(options), 
buildRoute().messageQueues[0]);
+}
+
+export interface HarnessOptions {
+  consumeConcurrentlyMax?: number;
+  cacheMessageCount?: number;
+  cacheMessageBytes?: number;
+  receiveBatchSize?: number;
+  maxAttempts?: number;
+  nextAttemptDelay?: number;
+  liteConsumer?: boolean;
+}
+
+/**
+ * A ProcessQueue backed by a stubbed PushConsumer: every RPC and settlement
+ * call is a sinon stub, so tests drive and observe the queue without a broker.
+ */
+export function createProcessQueueHarness(options: HarnessOptions = {}) {
+  const logger = createSilentLogger();
+  const retryPolicy = {
+    getMaxAttempts: sinon.stub().returns(options.maxAttempts ?? 3),
+    getNextAttemptDelay: sinon.stub().returns(options.nextAttemptDelay ?? 0),
+  };
+  let consumeService: ConsumeService | undefined;
+  const consumer = {
+    requestTimeoutValue: 3000,
+    getPushConsumerSettings: () => ({
+      getConsumeConcurrentlyMax: () => options.consumeConcurrentlyMax ?? 32,
+      getLongPollingTimeout: () => 30000,
+      getReceiveBatchSize: () => options.receiveBatchSize ?? 32,
+    }),
+    cacheMessageCountThresholdPerQueue: () => options.cacheMessageCount ?? 
1024,
+    cacheMessageBytesThresholdPerQueue: () => options.cacheMessageBytes ?? 64 
* 1024 * 1024,
+    getConsumeService: () => consumeService,
+    getRetryPolicy: () => retryPolicy as unknown as RetryPolicy,
+    getConsumerGroup: () => 'group-a',
+    wrapPushReceiveMessageRequest: sinon.stub().callsFake(
+      (batchSize: number, _mq: unknown, _filter: unknown, _timeout: number, 
attemptId?: string) =>
+        ({ batchSize, attemptId })),
+    receiveMessage: sinon.stub(),
+    wrapAckMessageRequest: sinon.stub().returns({}),
+    ackMessageViaRpc: sinon.stub().resolves(ackResponse()),
+    wrapChangeInvisibleDurationRequest: sinon.stub().callsFake(
+      (_messageView: MessageView, duration: number) => ({ duration })),
+    changeInvisibleDurationViaRpc: 
sinon.stub().resolves(changeInvisibleDurationResponse()),
+    wrapForwardMessageToDeadLetterQueueRequest: sinon.stub().returns({}),
+    forwardMessageToDeadLetterQueueViaRpc: 
sinon.stub().resolves(forwardToDLQResponse()),
+    incrementConsumptionOkQuantity: sinon.stub(),
+    incrementConsumptionErrorQuantity: sinon.stub(),
+  };
+  const pq = new ProcessQueue(consumer as unknown as PushConsumer, 
buildRoute().messageQueues[0],
+    new FilterExpression('*'), { logger, clientId: 'client-a', liteConsumer: 
options.liteConsumer ?? false });
+  return {
+    pq,
+    consumer,
+    logger,
+    retryPolicy,
+    setConsumeService(service: ConsumeService) {
+      consumeService = service;
+    },
+  };
+}
+
+// Fakes timers and Date only; setImmediate stays real so flushPromises() can 
drain promise chains.
+export function useFakeTimers() {
+  return sinon.useFakeTimers({ toFake: [ 'setTimeout', 'clearTimeout', 
'setInterval', 'clearInterval', 'Date' ] });
+}
+
+// Drains every pending promise callback that does not wait on a timer.
+export function flushPromises() {
+  return new Promise<void>(resolve => setImmediate(resolve));
+}

Reply via email to