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 48ab81ba fix(nodejs): align status handling and harden route utilities
(#1506)
48ab81ba is described below
commit 48ab81ba981f5a8046aaf45f3b3600a039ab4104
Author: Quan <[email protected]>
AuthorDate: Wed Nov 18 21:18:59 2026 +0800
fix(nodejs): align status handling and harden route utilities (#1506)
- Limit empty-message success to receive and retain per-request exception
IDs
- Validate endpoint strings and normalize protobuf durations
- Preserve queue namespaces and add table-driven regression tests
---
nodejs/src/client/BaseClient.ts | 7 +-
nodejs/src/client/RpcClientManager.ts | 21 +-
nodejs/src/client/TelemetrySession.ts | 2 +
nodejs/src/consumer/Consumer.ts | 8 +-
nodejs/src/consumer/PushConsumer.ts | 3 +-
nodejs/src/exception/InternalErrorException.ts | 4 +-
nodejs/src/exception/StatusChecker.ts | 5 +-
...{InternalErrorException.ts => receiveStatus.ts} | 22 +-
nodejs/src/producer/Producer.ts | 3 +-
nodejs/src/producer/SendReceipt.ts | 3 +-
nodejs/src/route/Endpoints.ts | 24 +-
nodejs/src/route/MessageQueue.ts | 7 +-
nodejs/src/util/index.ts | 9 +-
.../rpcContext.ts} | 29 ++-
nodejs/test/exception/RpcStatus.test.ts | 253 +++++++++++++++++++++
nodejs/test/exception/StatusChecker.test.ts | 137 +++++++++++
nodejs/test/fixes.test.ts | 5 +-
nodejs/test/retry/RetryPolicy.test.ts | 77 +++++++
nodejs/test/route/Endpoints.test.ts | 45 ++++
nodejs/test/route/RouteData.test.ts | 118 ++++++++++
nodejs/test/util/Semaphore.test.ts | 24 ++
nodejs/test/util/index.test.ts | 68 ++++++
22 files changed, 807 insertions(+), 67 deletions(-)
diff --git a/nodejs/src/client/BaseClient.ts b/nodejs/src/client/BaseClient.ts
index 73b80c81..d1f5931b 100644
--- a/nodejs/src/client/BaseClient.ts
+++ b/nodejs/src/client/BaseClient.ts
@@ -18,6 +18,7 @@
import { debuglog } from 'node:util';
import { randomUUID } from 'node:crypto';
import { Metadata } from '@grpc/grpc-js';
+import { getRequestId } from '../util/rpcContext';
import {
Settings as SettingsPB,
Status,
@@ -421,7 +422,7 @@ export abstract class BaseClient {
// gRPC responses; without this check the client stays blind to
// settings loss and never re-registers. Mirrors Java
// ClientImpl#doHeartbeat which checks the response status.
- StatusChecker.check(response.getStatus()?.toObject());
+ StatusChecker.check(response.getStatus()?.toObject(),
getRequestId(response));
// Heartbeat succeeded: the remote is reachable again, so rejoin any
// isolated endpoints (mirrors Java ClientImpl#doHeartbeat).
if (this.isolated.delete(endpoints.facade)) {
@@ -552,7 +553,7 @@ export abstract class BaseClient {
try {
const response = await this.rpcClientManager.queryRoute(this.endpoints,
req, this.requestTimeout);
- StatusChecker.check(response.getStatus()?.toObject());
+ StatusChecker.check(response.getStatus()?.toObject(),
getRequestId(response));
const topicRouteData = new
TopicRouteData(response.getMessageQueuesList());
const newEndpoints =
this.findNewRouteEndpoints(topicRouteData.getTotalEndpoints());
for (const endpoints of newEndpoints) {
@@ -699,7 +700,7 @@ export abstract class BaseClient {
onUnknownCommand(endpoints: Endpoints, status: Status.AsObject) {
try {
- StatusChecker.check(status);
+ StatusChecker.check(status, getRequestId(status));
} catch (err) {
this.logger.error('Get error status from telemetry session, status=%j,
endpoints=%j, clientId=%s',
status, endpoints, this.clientId);
diff --git a/nodejs/src/client/RpcClientManager.ts
b/nodejs/src/client/RpcClientManager.ts
index 6e455957..70bad526 100644
--- a/nodejs/src/client/RpcClientManager.ts
+++ b/nodejs/src/client/RpcClientManager.ts
@@ -29,6 +29,7 @@ import {
SyncLiteSubscriptionRequest,
} from '../../proto/apache/rocketmq/v2/service_pb';
import { Endpoints } from '../route';
+import { withRequestId } from '../util/rpcContext';
import { ILogger } from './Logger';
import { RpcClient } from './RpcClient';
import type { BaseClient } from './BaseClient';
@@ -128,37 +129,37 @@ export class RpcClientManager {
async queryRoute(endpoints: Endpoints, request: QueryRouteRequest, duration:
number) {
const rpcClient = this.#getRpcClient(endpoints);
const metadata = this.#baseClient.getRequestMetadata();
- return await rpcClient.queryRoute(request, metadata, duration);
+ return withRequestId(await rpcClient.queryRoute(request, metadata,
duration), metadata);
}
async heartbeat(endpoints: Endpoints, request: HeartbeatRequest, duration:
number) {
const rpcClient = this.#getRpcClient(endpoints);
const metadata = this.#baseClient.getRequestMetadata();
- return await rpcClient.heartbeat(request, metadata, duration);
+ return withRequestId(await rpcClient.heartbeat(request, metadata,
duration), metadata);
}
async sendMessage(endpoints: Endpoints, request: SendMessageRequest,
duration: number) {
const rpcClient = this.#getRpcClient(endpoints);
const metadata = this.#baseClient.getRequestMetadata();
- return await rpcClient.sendMessage(request, metadata, duration);
+ return withRequestId(await rpcClient.sendMessage(request, metadata,
duration), metadata);
}
async queryAssignment(endpoints: Endpoints, request: QueryAssignmentRequest,
duration: number) {
const rpcClient = this.#getRpcClient(endpoints);
const metadata = this.#baseClient.getRequestMetadata();
- return await rpcClient.queryAssignment(request, metadata, duration);
+ return withRequestId(await rpcClient.queryAssignment(request, metadata,
duration), metadata);
}
async receiveMessage(endpoints: Endpoints, request: ReceiveMessageRequest,
duration: number) {
const rpcClient = this.#getRpcClient(endpoints);
const metadata = this.#baseClient.getRequestMetadata();
- return await rpcClient.receiveMessage(request, metadata, duration);
+ return withRequestId(await rpcClient.receiveMessage(request, metadata,
duration), metadata);
}
async ackMessage(endpoints: Endpoints, request: AckMessageRequest, duration:
number) {
const rpcClient = this.#getRpcClient(endpoints);
const metadata = this.#baseClient.getRequestMetadata();
- return await rpcClient.ackMessage(request, metadata, duration);
+ return withRequestId(await rpcClient.ackMessage(request, metadata,
duration), metadata);
}
async forwardMessageToDeadLetterQueue(endpoints: Endpoints, request:
ForwardMessageToDeadLetterQueueRequest,
@@ -195,18 +196,18 @@ export class RpcClientManager {
async endTransaction(endpoints: Endpoints, request: EndTransactionRequest,
duration: number) {
const rpcClient = this.#getRpcClient(endpoints);
const metadata = this.#baseClient.getRequestMetadata();
- return await rpcClient.endTransaction(request, metadata, duration);
+ return withRequestId(await rpcClient.endTransaction(request, metadata,
duration), metadata);
}
telemetry(endpoints: Endpoints, metadata: Metadata) {
const rpcClient = this.#getRpcClient(endpoints);
- return rpcClient.telemetry(metadata);
+ return withRequestId(rpcClient.telemetry(metadata), metadata);
}
async changeInvisibleDuration(endpoints: Endpoints, request:
ChangeInvisibleDurationRequest, duration: number) {
const rpcClient = this.#getRpcClient(endpoints);
const metadata = this.#baseClient.getRequestMetadata();
- return await rpcClient.changeInvisibleDuration(request, metadata,
duration);
+ return withRequestId(await rpcClient.changeInvisibleDuration(request,
metadata, duration), metadata);
}
async notifyClientTermination(endpoints: Endpoints, request:
NotifyClientTerminationRequest, duration: number) {
@@ -218,7 +219,7 @@ export class RpcClientManager {
async recallMessage(endpoints: Endpoints, request: RecallMessageRequest,
duration: number) {
const rpcClient = this.#getRpcClient(endpoints);
const metadata = this.#baseClient.getRequestMetadata();
- return await rpcClient.recallMessage(request, metadata, duration);
+ return withRequestId(await rpcClient.recallMessage(request, metadata,
duration), metadata);
}
async syncLiteSubscription(endpoints: Endpoints, request:
SyncLiteSubscriptionRequest, duration: number) {
diff --git a/nodejs/src/client/TelemetrySession.ts
b/nodejs/src/client/TelemetrySession.ts
index e469907b..93db14f4 100644
--- a/nodejs/src/client/TelemetrySession.ts
+++ b/nodejs/src/client/TelemetrySession.ts
@@ -18,6 +18,7 @@
import { ClientDuplexStream } from '@grpc/grpc-js';
import { TelemetryCommand } from '../../proto/apache/rocketmq/v2/service_pb';
import { Endpoints } from '../route';
+import { getRequestId, setRequestId } from '../util/rpcContext';
import type { BaseClient } from './BaseClient';
import { ILogger } from './Logger';
@@ -204,6 +205,7 @@ export class TelemetrySession {
this.#logger.warn('Receive unrecognized command from remote,
endpoints=%s, commandCase=%j, command=%j, clientId=%s',
endpoints, commandCase, commandObj, clientId);
// should telemetry session start fail
+ if (commandObj.status) setRequestId(commandObj.status,
getRequestId(this.#stream));
this.#baseClient.onUnknownCommand(endpoints, commandObj.status!);
}
}
diff --git a/nodejs/src/consumer/Consumer.ts b/nodejs/src/consumer/Consumer.ts
index e5c94909..11f15e0d 100644
--- a/nodejs/src/consumer/Consumer.ts
+++ b/nodejs/src/consumer/Consumer.ts
@@ -25,6 +25,8 @@ import { ClientType } from
'../../proto/apache/rocketmq/v2/definition_pb';
import { MessageView } from '../message';
import { MessageQueue } from '../route';
import { StatusChecker } from '../exception';
+import { checkReceiveStatus } from '../exception/receiveStatus';
+import { getRequestId } from '../util/rpcContext';
import { BaseClient, BaseClientOptions } from '../client';
import { createDuration, createResource } from '../util';
import {
@@ -95,7 +97,7 @@ export abstract class Consumer extends BaseClient {
}
}
- StatusChecker.check(status);
+ checkReceiveStatus(status, getRequestId(responses));
if (messageList.length > 0) {
this.logger.debug?.('Received %d messages successfully, topic=%s,
endpoints=%s, clientId=%s',
@@ -133,7 +135,7 @@ export abstract class Consumer extends BaseClient {
const res = await this.rpcClientManager.ackMessage(endpoints, request,
this.requestTimeout);
const response = res.toObject();
hookStatus = response.status?.code === Code.OK ?
MessageHookPointsStatus.OK : MessageHookPointsStatus.ERROR;
- StatusChecker.check(response.status);
+ StatusChecker.check(response.status, getRequestId(res));
this.doAfter(MessageInterceptorContextImpl.withStatus(context,
hookStatus), generalMessages);
return response.entriesList;
} catch (err) {
@@ -162,7 +164,7 @@ export abstract class Consumer extends BaseClient {
const res = await
this.rpcClientManager.changeInvisibleDuration(messageView.endpoints, request,
this.requestTimeout);
const response = res.toObject();
hookStatus = response.status?.code === Code.OK ?
MessageHookPointsStatus.OK : MessageHookPointsStatus.ERROR;
- StatusChecker.check(response.status);
+ StatusChecker.check(response.status, getRequestId(res));
this.doAfter(MessageInterceptorContextImpl.withStatus(context,
hookStatus), generalMessages);
return response.receiptHandle;
} catch (err) {
diff --git a/nodejs/src/consumer/PushConsumer.ts
b/nodejs/src/consumer/PushConsumer.ts
index f6deb857..8fce40d0 100644
--- a/nodejs/src/consumer/PushConsumer.ts
+++ b/nodejs/src/consumer/PushConsumer.ts
@@ -29,6 +29,7 @@ import { MessageView } from '../message';
import { Broker, MessageQueue, TopicRouteData } from '../route';
import { MessageQueue as MessageQueuePB, Broker as BrokerPB } from
'../../proto/apache/rocketmq/v2/definition_pb';
import { StatusChecker } from '../exception';
+import { getRequestId } from '../util/rpcContext';
import { RetryPolicy } from '../retry';
import { createDuration, createResource } from '../util';
import { Consumer, ConsumerOptions } from './Consumer';
@@ -547,7 +548,7 @@ export class PushConsumer extends Consumer {
if (!status) {
throw new Error('Missing status in query assignment response');
}
- StatusChecker.check(status.toObject());
+ StatusChecker.check(status.toObject(), getRequestId(response));
const assignmentList = response.getAssignmentsList().map(assignment => {
const mqPb = assignment.getMessageQueue()!;
diff --git a/nodejs/src/exception/InternalErrorException.ts
b/nodejs/src/exception/InternalErrorException.ts
index 1f360734..62345c00 100644
--- a/nodejs/src/exception/InternalErrorException.ts
+++ b/nodejs/src/exception/InternalErrorException.ts
@@ -18,11 +18,13 @@
import { ClientException } from './ClientException';
export class InternalErrorException extends ClientException {
+ readonly retryable = true;
+
constructor(code: number, message: string, requestId?: string) {
super(code, message, requestId);
this.name = 'InternalErrorException';
// Mark this as a potentially retryable error (temporary server-side issue)
- (this as any).retryable = true;
+ // retryable 由类字段显式声明。
}
/**
diff --git a/nodejs/src/exception/StatusChecker.ts
b/nodejs/src/exception/StatusChecker.ts
index dfd68167..3b0eb01f 100644
--- a/nodejs/src/exception/StatusChecker.ts
+++ b/nodejs/src/exception/StatusChecker.ts
@@ -33,7 +33,9 @@ import { UnsupportedException } from './UnsupportedException';
export class StatusChecker {
static check(status?: Status.AsObject, requestId?: string) {
- if (!status) return;
+ if (!status) {
+ throw new InternalErrorException(Code.INTERNAL_SERVER_ERROR, 'status was
not set by server', requestId);
+ }
switch (status.code) {
case Code.OK:
case Code.MULTIPLE_RESULTS:
@@ -66,7 +68,6 @@ export class StatusChecker {
case Code.FORBIDDEN:
throw new ForbiddenException(status.code, status.message, requestId);
case Code.MESSAGE_NOT_FOUND:
- return;
case Code.NOT_FOUND:
case Code.TOPIC_NOT_FOUND:
case Code.CONSUMER_GROUP_NOT_FOUND:
diff --git a/nodejs/src/exception/InternalErrorException.ts
b/nodejs/src/exception/receiveStatus.ts
similarity index 59%
copy from nodejs/src/exception/InternalErrorException.ts
copy to nodejs/src/exception/receiveStatus.ts
index 1f360734..e6b64047 100644
--- a/nodejs/src/exception/InternalErrorException.ts
+++ b/nodejs/src/exception/receiveStatus.ts
@@ -15,21 +15,11 @@
* limitations under the License.
*/
-import { ClientException } from './ClientException';
+import { Code, Status } from '../../proto/apache/rocketmq/v2/definition_pb';
+import { StatusChecker } from './StatusChecker';
-export class InternalErrorException extends ClientException {
- constructor(code: number, message: string, requestId?: string) {
- super(code, message, requestId);
- this.name = 'InternalErrorException';
- // Mark this as a potentially retryable error (temporary server-side issue)
- (this as any).retryable = true;
- }
-
- /**
- * Check if this error is retryable.
- * Internal server errors are typically temporary and can be retried.
- */
- isRetryable(): boolean {
- return true;
- }
+// 仅拉取消息允许空结果;不改变已公开的 StatusChecker.check 签名。
+export function checkReceiveStatus(status?: Status.AsObject, requestId?:
string) {
+ if (status?.code === Code.MESSAGE_NOT_FOUND) return;
+ StatusChecker.check(status, requestId);
}
diff --git a/nodejs/src/producer/Producer.ts b/nodejs/src/producer/Producer.ts
index 90425d5f..7aeb3e86 100644
--- a/nodejs/src/producer/Producer.ts
+++ b/nodejs/src/producer/Producer.ts
@@ -48,6 +48,7 @@ import { PublishingLoadBalancer } from
'./PublishingLoadBalancer';
import { SendReceipt } from './SendReceipt';
import { Transaction } from './Transaction';
import { createResource } from '../util';
+import { getRequestId } from '../util/rpcContext';
import { RecallReceipt } from './RecallReceipt';
import { RecallMessageRequest } from
'../../proto/apache/rocketmq/v2/service_pb';
import {
@@ -133,7 +134,7 @@ export class Producer extends BaseClient {
const response = await this.rpcClientManager.endTransaction(endpoints,
request, this.requestTimeout);
const statusObj = response.getStatus()?.toObject();
const hookStatus = statusObj?.code === Code.OK ?
MessageHookPointsStatus.OK : MessageHookPointsStatus.ERROR;
- StatusChecker.check(statusObj);
+ StatusChecker.check(statusObj, getRequestId(response));
this.doAfter(MessageInterceptorContextImpl.withStatus(context,
hookStatus), generalMessages);
this.logger.debug?.('End transaction successfully, messageId=%s,
transactionId=%s, resolution=%s, source=%s, clientId=%s',
diff --git a/nodejs/src/producer/SendReceipt.ts
b/nodejs/src/producer/SendReceipt.ts
index f4084cdb..3100d454 100644
--- a/nodejs/src/producer/SendReceipt.ts
+++ b/nodejs/src/producer/SendReceipt.ts
@@ -19,6 +19,7 @@ import { Code } from
'../../proto/apache/rocketmq/v2/definition_pb';
import { SendMessageResponse } from
'../../proto/apache/rocketmq/v2/service_pb';
import { MessageQueue } from '../route';
import { StatusChecker } from '../exception';
+import { getRequestId } from '../util/rpcContext';
export class SendReceipt {
readonly messageId: string;
@@ -48,7 +49,7 @@ export class SendReceipt {
// Filter abnormal status.
const abnormalStatus = responseObj.entriesList.map(e => e.status).find(s
=> s?.code !== Code.OK);
const status = abnormalStatus ?? responseObj.status;
- StatusChecker.check(status);
+ StatusChecker.check(status, getRequestId(response));
const sendReceipts: SendReceipt[] = [];
for (const entry of responseObj.entriesList) {
const messageId = entry.messageId;
diff --git a/nodejs/src/route/Endpoints.ts b/nodejs/src/route/Endpoints.ts
index dff4fe03..b5dc66b2 100644
--- a/nodejs/src/route/Endpoints.ts
+++ b/nodejs/src/route/Endpoints.ts
@@ -49,7 +49,8 @@ export class Endpoints {
throw new TypeError(`Invalid IPv6 endpoint: ${endpoint}`);
}
host = match[1];
- port = match[2] ? parseInt(match[2], 10) : DEFAULT_PORT;
+ if (!isIPv6(host)) throw new TypeError(`Invalid IPv6 endpoint:
${endpoint}`);
+ port = match[2] ? Number(match[2]) : DEFAULT_PORT;
} else if (isIPv6(candidate)) {
// Bare IPv6 address without brackets, e.g. ::1
host = candidate;
@@ -59,19 +60,26 @@ export class Endpoints {
const index = candidate.lastIndexOf(':');
if (index > 0) {
host = candidate.substring(0, index);
- port = parseInt(candidate.substring(index + 1), 10) ||
DEFAULT_PORT;
+ const portText = candidate.substring(index + 1);
+ if (!/^\d+$/.test(portText)) throw new TypeError(`Invalid endpoint
port: ${endpoint}`);
+ port = Number(portText);
} else {
host = candidate;
port = DEFAULT_PORT;
}
}
- if (isIPv4(host)) {
- this.scheme = AddressScheme.IPV4;
- } else if (isIPv6(host)) {
- this.scheme = AddressScheme.IPV6;
- } else {
- this.scheme = AddressScheme.DOMAIN_NAME;
+ if (!host || (host.includes(':') && !isIPv6(host))) {
+ throw new TypeError(`Invalid endpoint host: ${endpoint}`);
+ }
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
+ throw new TypeError(`Invalid endpoint port: ${endpoint}`);
+ }
+ const scheme = isIPv4(host) ? AddressScheme.IPV4
+ : isIPv6(host) ? AddressScheme.IPV6 : AddressScheme.DOMAIN_NAME;
+ if (this.addressesList.length > 0 && this.scheme !== scheme) {
+ throw new TypeError('Mixed address schemes are not supported');
}
+ this.scheme = scheme;
this.addressesList.push({ host, port });
}
} else {
diff --git a/nodejs/src/route/MessageQueue.ts b/nodejs/src/route/MessageQueue.ts
index b6022644..8a231e1c 100644
--- a/nodejs/src/route/MessageQueue.ts
+++ b/nodejs/src/route/MessageQueue.ts
@@ -40,7 +40,7 @@ export class MessageQueue {
toProtobuf() {
const messageQueue = new MessageQueuePB();
messageQueue.setId(this.queueId);
- messageQueue.setTopic(createResource(this.topic.name));
+
messageQueue.setTopic(createResource(this.topic.name).setResourceNamespace(this.topic.resourceNamespace));
messageQueue.setBroker(this.broker.toProtobuf());
messageQueue.setPermission(this.permission);
messageQueue.setAcceptMessageTypesList(this.acceptMessageTypesList);
@@ -52,6 +52,7 @@ export class MessageQueue {
if (!other) return false;
return this.queueId === other.queueId &&
this.topic.name === other.topic.name &&
+ this.topic.resourceNamespace === other.topic.resourceNamespace &&
this.broker.equals(other.broker) &&
this.permission === other.permission;
}
@@ -62,6 +63,10 @@ export class MessageQueue {
hash = (hash * 31 + this.queueId) | 0;
// eslint-disable-next-line no-bitwise
hash = (hash * 31 + hashCodeOfString(this.topic.name)) | 0;
+ if (this.topic.resourceNamespace) {
+ // eslint-disable-next-line no-bitwise
+ hash = (hash * 31 + hashCodeOfString(this.topic.resourceNamespace)) | 0;
+ }
// eslint-disable-next-line no-bitwise
hash = (hash * 31 + this.broker.hashCode()) | 0;
// eslint-disable-next-line no-bitwise
diff --git a/nodejs/src/util/index.ts b/nodejs/src/util/index.ts
index df68c20f..c96662b4 100644
--- a/nodejs/src/util/index.ts
+++ b/nodejs/src/util/index.ts
@@ -45,13 +45,16 @@ export function sign(accessSecret: string, dateTime:
string) {
}
export function createDuration(ms: number) {
+ if (!Number.isFinite(ms) || Math.abs(ms) > 315576000000000) {
+ throw new RangeError('duration must be finite and within the protobuf
Duration range');
+ }
// Duration.seconds is a protobuf int64 field, so it must be an integer;
// the remainder is carried by nanos. Non-integer seconds would fail
// serialization with 'Assertion failed'.
- const nanos = Math.floor(ms % 1000 * 1000000);
+ const nanos = Math.sign(ms) * Math.floor(Math.abs(ms % 1000) * 1000000);
return new Duration()
- .setSeconds(Math.floor(ms / 1000))
- .setNanos(nanos);
+ .setSeconds(Math.trunc(ms / 1000) || 0)
+ .setNanos(nanos || 0);
}
export function createResource(name: string) {
diff --git a/nodejs/src/exception/InternalErrorException.ts
b/nodejs/src/util/rpcContext.ts
similarity index 54%
copy from nodejs/src/exception/InternalErrorException.ts
copy to nodejs/src/util/rpcContext.ts
index 1f360734..21fe3f9f 100644
--- a/nodejs/src/exception/InternalErrorException.ts
+++ b/nodejs/src/util/rpcContext.ts
@@ -15,21 +15,20 @@
* limitations under the License.
*/
-import { ClientException } from './ClientException';
+import type { Metadata } from '@grpc/grpc-js';
-export class InternalErrorException extends ClientException {
- constructor(code: number, message: string, requestId?: string) {
- super(code, message, requestId);
- this.name = 'InternalErrorException';
- // Mark this as a potentially retryable error (temporary server-side issue)
- (this as any).retryable = true;
- }
+// 按响应对象关联请求,避免并发 RPC 串号;不改写 protobuf 或公开返回类型。
+const requestIds = new WeakMap<object, string>();
- /**
- * Check if this error is retryable.
- * Internal server errors are typically temporary and can be retried.
- */
- isRetryable(): boolean {
- return true;
- }
+export function setRequestId<T extends object>(response: T, requestId?:
string): T {
+ if (requestId !== undefined) requestIds.set(response, requestId);
+ return response;
+}
+
+export function withRequestId<T extends object>(response: T, metadata:
Metadata): T {
+ return setRequestId(response,
metadata.get('x-mq-request-id')[0]?.toString());
+}
+
+export function getRequestId(response?: object): string | undefined {
+ return response ? requestIds.get(response) : undefined;
}
diff --git a/nodejs/test/exception/RpcStatus.test.ts
b/nodejs/test/exception/RpcStatus.test.ts
new file mode 100644
index 00000000..daf7eff4
--- /dev/null
+++ b/nodejs/test/exception/RpcStatus.test.ts
@@ -0,0 +1,253 @@
+/**
+ * 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 { Metadata } from '@grpc/grpc-js';
+import * as sinon from 'sinon';
+import { Code, TransactionResolution } from
'../../proto/apache/rocketmq/v2/definition_pb';
+import {
+ AckMessageResponse, ChangeInvisibleDurationResponse, EndTransactionResponse,
HeartbeatResponse,
+ QueryRouteResponse, QueryAssignmentResponse, ReceiveMessageRequest,
ReceiveMessageResponse,
+ SendMessageRequest, SendMessageResponse, TelemetryCommand,
+} from '../../proto/apache/rocketmq/v2/service_pb';
+import { BaseClient } from '../../src/client/BaseClient';
+import { RpcClient } from '../../src/client/RpcClient';
+import { TelemetrySession } from '../../src/client/TelemetrySession';
+import { SimpleConsumer } from '../../src/consumer/SimpleConsumer';
+import { PushConsumer } from '../../src/consumer/PushConsumer';
+import { ConsumeResult } from '../../src/consumer/ConsumeResult';
+import { ClientException, InternalErrorException, NotFoundException } from
'../../src/exception';
+import { Message, MessageView } from '../../src/message';
+import { Endpoints, MessageQueue } from '../../src/route';
+import { Producer } from '../../src/producer/Producer';
+import { SendReceipt } from '../../src/producer/SendReceipt';
+import { getRequestId } from '../../src/util/rpcContext';
+import { buildMessagePB, buildRoute, buildStatus } from '../support/protobuf';
+import { createSilentLogger, deferred, FakeTelemetryStream } from
'../support/fakes';
+
+const endpoints = new Endpoints('127.0.0.1:8081');
+const queue = buildRoute().messageQueues[0];
+const message = new MessageView(buildMessagePB(), queue);
+
+class TestConsumer extends SimpleConsumer {
+ receiveForTest(mq: MessageQueue = queue) { return this.receiveMessage(new
ReceiveMessageRequest(), mq, 1000); }
+ ackForTest() { return this.ackMessage(message); }
+ invisibleForTest() { return this.invisibleDuration(message, 10000); }
+ routeForTest() { return this.getRouteData('test-topic'); }
+ cacheRouteForTest() { this.topicRouteCache.set('test-topic', buildRoute()); }
+}
+
+class TestPushConsumer extends PushConsumer {
+ cacheRouteForTest() { this.topicRouteCache.set('test-topic', buildRoute()); }
+ scanForTest() { this.startAssignmentScanning(); }
+}
+
+function matchesRequest(error: unknown, requestId: string, code =
Code.UNAUTHORIZED) {
+ assert(error instanceof ClientException);
+ assert.equal(error.code, code);
+ assert.equal(error.message, `[request-id=${requestId},
response-code=${code}] server message`);
+ return true;
+}
+
+describe('RPC 异常 requestId 与 receive 限定', () => {
+ let consumer: TestConsumer;
+ let clients: BaseClient[];
+ let clock: sinon.SinonFakeTimers;
+ let logger: ReturnType<typeof createSilentLogger>;
+ beforeEach(() => {
+ clock = sinon.useFakeTimers({ toFake: [ 'setInterval', 'clearInterval',
'setTimeout', 'clearTimeout' ] });
+ logger = createSilentLogger();
+ consumer = new TestConsumer({ endpoints: endpoints.facade, namespace: '',
consumerGroup: 'test-group',
+ subscriptions: new Map([[ 'test-topic', '*' ]]), logger });
+ clients = [ consumer ];
+ });
+ afterEach(() => {
+ // 未启动客户端,meter 保持 disabled;关闭唯一创建的 RPC channel 与空闲定时器。
+ for (const client of clients) client.getRpcClientManager().close();
+ sinon.restore();
+ clock.restore();
+ });
+
+ [ 'ack', 'invisible', 'route' ].forEach(operation => {
+ it(`${operation} 异常 ID 等于本次真正发出的 metadata`, async () => {
+ let requestId = '';
+ const status = buildStatus(Code.UNAUTHORIZED, 'server message');
+ let invocation: () => Promise<unknown>;
+ if (operation === 'ack') {
+ sinon.stub(RpcClient.prototype, 'ackMessage').callsFake(async (_req,
metadata) => {
+ requestId = String(metadata.get('x-mq-request-id')[0]);
+ return new AckMessageResponse().setStatus(status);
+ });
+ invocation = () => consumer.ackForTest();
+ } else if (operation === 'invisible') {
+ sinon.stub(RpcClient.prototype,
'changeInvisibleDuration').callsFake(async (_req, metadata) => {
+ requestId = String(metadata.get('x-mq-request-id')[0]);
+ return new ChangeInvisibleDurationResponse().setStatus(status);
+ });
+ invocation = () => consumer.invisibleForTest();
+ } else {
+ sinon.stub(RpcClient.prototype, 'queryRoute').callsFake(async (_req,
metadata) => {
+ requestId = String(metadata.get('x-mq-request-id')[0]);
+ return new QueryRouteResponse().setStatus(status);
+ });
+ invocation = () => consumer.routeForTest();
+ }
+ await assert.rejects(invocation, error => matchesRequest(error,
requestId));
+ assert.match(requestId, /^[a-f0-9-]{36}$/);
+ });
+ });
+
+ [ Code.OK, Code.MESSAGE_NOT_FOUND, Code.UNAUTHORIZED ].forEach(code => {
+ it(`receive 状态 ${code} 保留空结果或错误 ID`, async () => {
+ let requestId = '';
+ sinon.stub(RpcClient.prototype, 'receiveMessage').callsFake(async (_req,
metadata) => {
+ requestId = String(metadata.get('x-mq-request-id')[0]);
+ return [ new ReceiveMessageResponse().setStatus(buildStatus(code,
'server message')) ];
+ });
+ if (code === Code.UNAUTHORIZED) {
+ await assert.rejects(() => consumer.receiveForTest(), error =>
matchesRequest(error, requestId));
+ } else {
+ assert.deepEqual(await consumer.receiveForTest(), []);
+ }
+ });
+ });
+
+ it('receive 流缺失 status 不被当作空结果成功', async () => {
+ let requestId = '';
+ sinon.stub(RpcClient.prototype, 'receiveMessage').callsFake(async (_req,
metadata) => {
+ requestId = String(metadata.get('x-mq-request-id')[0]);
+ return [];
+ });
+ await assert.rejects(() => consumer.receiveForTest(), error => {
+ assert(error instanceof InternalErrorException);
+ assert(error.message.includes(`request-id=${requestId}`));
+ return true;
+ });
+ });
+
+ it('ack 的 MESSAGE_NOT_FOUND 抛 NotFoundException', async () => {
+ sinon.stub(RpcClient.prototype, 'ackMessage').resolves(new
AckMessageResponse().setStatus(buildStatus(Code.MESSAGE_NOT_FOUND)));
+ await assert.rejects(() => consumer.ackForTest(), NotFoundException);
+ });
+
+ it('并发 RPC 逆序返回,响应身份和 requestId 不串号', async () => {
+ const first = deferred<AckMessageResponse>();
+ const second = deferred<AckMessageResponse>();
+ const ids: string[] = [];
+ sinon.stub(RpcClient.prototype, 'ackMessage').callsFake((_req, metadata)
=> {
+ ids.push(String(metadata.get('x-mq-request-id')[0]));
+ return ids.length === 1 ? first.promise : second.promise;
+ });
+ const a = consumer.ackForTest();
+ const b = consumer.ackForTest();
+ const failedA = assert.rejects(a, error => matchesRequest(error, ids[0]));
+ const failedB = assert.rejects(b, error => matchesRequest(error, ids[1]));
+ second.resolve(new
AckMessageResponse().setStatus(buildStatus(Code.UNAUTHORIZED, 'server
message')));
+ await failedB;
+ first.resolve(new
AckMessageResponse().setStatus(buildStatus(Code.UNAUTHORIZED, 'server
message')));
+ await failedA;
+ assert.notEqual(ids[0], ids[1]);
+ });
+
+ it('send 顶层和 entry 状态均读取响应所属请求 ID,返回类型不变', async () => {
+ for (const entryStatus of [ false, true ]) {
+ let requestId = '';
+ const response = new
SendMessageResponse().setStatus(buildStatus(entryStatus ? Code.OK :
Code.UNAUTHORIZED, 'server message'));
+ if (entryStatus)
response.addEntries().setStatus(buildStatus(Code.UNAUTHORIZED, 'server
message'));
+ const stub = sinon.stub(RpcClient.prototype,
'sendMessage').callsFake(async (_req, metadata) => {
+ requestId = String(metadata.get('x-mq-request-id')[0]);
+ return response;
+ });
+ const result = await
consumer.getRpcClientManager().sendMessage(endpoints, new SendMessageRequest(),
3000);
+ assert.equal(result, response);
+ assert.equal(getRequestId(result), requestId);
+ assert.throws(() => SendReceipt.processResponseInvocation(queue,
result), error => matchesRequest(error, requestId));
+ stub.restore();
+ }
+ });
+
+ it('endTransaction 的错误 ID 保留到调用方', async () => {
+ const producer = new Producer({ endpoints: endpoints.facade, namespace:
'', logger });
+ clients.push(producer);
+ let requestId = '';
+ sinon.stub(RpcClient.prototype, 'endTransaction').callsFake(async (_req,
metadata) => {
+ requestId = String(metadata.get('x-mq-request-id')[0]);
+ return new
EndTransactionResponse().setStatus(buildStatus(Code.UNAUTHORIZED, 'server
message'));
+ });
+ await assert.rejects(() => producer.endTransaction(endpoints, new
Message({ topic: 'test-topic', body: Buffer.from('body') }),
+ 'message-id', 'transaction-id', TransactionResolution.COMMIT), error =>
matchesRequest(error, requestId));
+ });
+
+ it('heartbeat 记录的错误带本次 ID', async () => {
+ consumer.cacheRouteForTest();
+ let requestId = '';
+ sinon.stub(RpcClient.prototype, 'heartbeat').callsFake(async (_req,
metadata) => {
+ requestId = String(metadata.get('x-mq-request-id')[0]);
+ return new HeartbeatResponse().setStatus(buildStatus(Code.UNAUTHORIZED,
'server message'));
+ });
+ await (consumer as unknown as { doHeartbeat(): Promise<void>
}).doHeartbeat();
+ assert(logger.warn.calledOnce);
+ assert(logger.warn.firstCall.args.some(arg => typeof arg === 'string' &&
arg.includes(`request-id=${requestId}`)));
+ });
+
+ it('queryAssignment 的错误带本次 ID', async () => {
+ const push = new TestPushConsumer({ endpoints: endpoints.facade,
namespace: '', logger, consumerGroup: 'test-group',
+ subscriptions: new Map([[ 'test-topic', '*' ]]), messageListener: {
consume: () => ConsumeResult.SUCCESS } });
+ clients.push(push);
+ push.cacheRouteForTest();
+ let requestId = '';
+ sinon.stub(RpcClient.prototype, 'queryAssignment').callsFake(async (_req,
metadata) => {
+ requestId = String(metadata.get('x-mq-request-id')[0]);
+ return new
QueryAssignmentResponse().setStatus(buildStatus(Code.UNAUTHORIZED, 'server
message'));
+ });
+ push.scanForTest();
+ await clock.tickAsync(1000);
+ const error = logger.error.firstCall.args.find(arg => arg instanceof
ClientException);
+ matchesRequest(error, requestId);
+ });
+
+ it('telemetry 未知命令关联当前建流 ID,刷新后 ID 更新', () => {
+ const streams: FakeTelemetryStream[] = [];
+ const ids: string[] = [];
+ sinon.stub(RpcClient.prototype, 'telemetry').callsFake(metadata => {
+ ids.push(String(metadata.get('x-mq-request-id')[0]));
+ const stream = new FakeTelemetryStream();
+ streams.push(stream);
+ return stream.asGrpcStream();
+ });
+ const check = sinon.spy(consumer, 'onUnknownCommand');
+ const session = new TelemetrySession(consumer, endpoints, logger);
+ try {
+ for (let i = 0; i < 2; i++) {
+ if (i > 0) session.refresh();
+ streams[i].receive(new
TelemetryCommand().setStatus(buildStatus(Code.UNAUTHORIZED, 'server message')));
+ const status = check.getCall(i).args[1];
+ assert.equal(getRequestId(status), ids[i]);
+ }
+ assert.notEqual(ids[0], ids[1]);
+ } finally {
+ session.release();
+ }
+ });
+
+ it('缺省 metadata ID 的辅助读取保持可选签名', () => {
+ const metadata = new Metadata();
+ assert.deepEqual(metadata.get('x-mq-request-id'), []);
+ assert.equal(getRequestId({}), undefined);
+ assert.equal(getRequestId(), undefined);
+ });
+});
diff --git a/nodejs/test/exception/StatusChecker.test.ts
b/nodejs/test/exception/StatusChecker.test.ts
new file mode 100644
index 00000000..12fcb6c3
--- /dev/null
+++ b/nodejs/test/exception/StatusChecker.test.ts
@@ -0,0 +1,137 @@
+/**
+ * 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 { Code } from '../../proto/apache/rocketmq/v2/definition_pb';
+import * as exceptions from '../../src/exception';
+import { checkReceiveStatus } from '../../src/exception/receiveStatus';
+import { buildStatus } from '../support/protobuf';
+
+// 每组与同基点 Java StatusChecker 的映射对应,未映射枚举显式进入 default。
+const groups = [
+ [ exceptions.BadRequestException, [
+ Code.BAD_REQUEST, Code.ILLEGAL_ACCESS_POINT, Code.ILLEGAL_TOPIC,
Code.ILLEGAL_CONSUMER_GROUP,
+ Code.ILLEGAL_MESSAGE_TAG, Code.ILLEGAL_MESSAGE_KEY,
Code.ILLEGAL_MESSAGE_GROUP,
+ Code.ILLEGAL_MESSAGE_PROPERTY_KEY, Code.ILLEGAL_LITE_TOPIC,
Code.INVALID_TRANSACTION_ID,
+ Code.ILLEGAL_MESSAGE_ID, Code.ILLEGAL_FILTER_EXPRESSION,
Code.ILLEGAL_INVISIBLE_TIME,
+ Code.ILLEGAL_DELIVERY_TIME, Code.INVALID_RECEIPT_HANDLE,
Code.MESSAGE_PROPERTY_CONFLICT_WITH_TYPE,
+ Code.UNRECOGNIZED_CLIENT_TYPE, Code.MESSAGE_CORRUPTED,
Code.CLIENT_ID_REQUIRED, Code.ILLEGAL_POLLING_TIME,
+ ]],
+ [ exceptions.UnauthorizedException, [ Code.UNAUTHORIZED ]],
+ [ exceptions.PaymentRequiredException, [ Code.PAYMENT_REQUIRED ]],
+ [ exceptions.ForbiddenException, [ Code.FORBIDDEN ]],
+ [ exceptions.NotFoundException, [ Code.MESSAGE_NOT_FOUND, Code.NOT_FOUND,
Code.TOPIC_NOT_FOUND, Code.CONSUMER_GROUP_NOT_FOUND ]],
+ [ exceptions.PayloadTooLargeException, [ Code.PAYLOAD_TOO_LARGE,
Code.MESSAGE_BODY_TOO_LARGE ]],
+ [ exceptions.PayloadEmptyException, [ Code.MESSAGE_BODY_EMPTY ]],
+ [ exceptions.TooManyRequestsException, [ Code.TOO_MANY_REQUESTS ]],
+ [ exceptions.RequestHeaderFieldsTooLargeException, [
Code.REQUEST_HEADER_FIELDS_TOO_LARGE, Code.MESSAGE_PROPERTIES_TOO_LARGE ]],
+ [ exceptions.InternalErrorException, [ Code.INTERNAL_ERROR,
Code.INTERNAL_SERVER_ERROR, Code.HA_NOT_AVAILABLE ]],
+ [ exceptions.ProxyTimeoutException, [ Code.PROXY_TIMEOUT,
Code.MASTER_PERSISTENCE_TIMEOUT, Code.SLAVE_PERSISTENCE_TIMEOUT ]],
+ [ exceptions.UnsupportedException, [
+ Code.UNSUPPORTED, Code.VERSION_UNSUPPORTED,
Code.VERIFY_FIFO_MESSAGE_UNSUPPORTED,
+ Code.CODE_UNSPECIFIED, Code.ILLEGAL_OFFSET, Code.OFFSET_NOT_FOUND,
Code.REQUEST_TIMEOUT,
+ Code.PRECONDITION_FAILED, Code.NOT_IMPLEMENTED,
Code.FAILED_TO_CONSUME_MESSAGE,
+ ]],
+ [ exceptions.LiteTopicQuotaExceededException, [
Code.LITE_TOPIC_QUOTA_EXCEEDED ]],
+ [ exceptions.LiteSubscriptionQuotaExceededException, [
Code.LITE_SUBSCRIPTION_QUOTA_EXCEEDED ]],
+] as const;
+
+function verifyException(error: unknown, name: string, code: number, requestId
= 'request-42', message = 'server message') {
+ assert(error instanceof exceptions.ClientException);
+ assert(error instanceof Error);
+ assert.equal(error.name, name);
+ assert.equal(error.code, code);
+ assert.equal(error.message, `[request-id=${requestId},
response-code=${code}] ${message}`);
+ return true;
+}
+
+describe('StatusChecker 与异常兼容性', () => {
+ it('枚举映射表覆盖 proto 的每个 Code', () => {
+ const covered = [ Code.OK, Code.MULTIPLE_RESULTS, ...groups.flatMap(([ ,
codes ]) => [ ...codes ]) ];
+ assert.equal(new Set(covered).size, covered.length);
+ assert.deepEqual(covered.sort((a, b) => a - b),
Object.values(Code).filter(v => typeof v === 'number').sort((a, b) => a - b));
+ });
+
+ for (const [ Exception, codes ] of groups) {
+ for (const code of codes) {
+ it(`状态 ${code} 映射为 ${Exception.name} 并保留 requestId`, () => {
+ assert.throws(() => exceptions.StatusChecker.check(buildStatus(code,
'server message').toObject(), 'request-42'), error => {
+ assert(error instanceof Exception);
+ return verifyException(error, Exception.name, code);
+ });
+ });
+ }
+ }
+
+ for (const code of [ Code.OK, Code.MULTIPLE_RESULTS ]) {
+ it(`状态 ${code} 在两种检查方式下均成功`, () => {
+ exceptions.StatusChecker.check(buildStatus(code).toObject());
+ checkReceiveStatus(buildStatus(code).toObject());
+ });
+ }
+
+ it('MESSAGE_NOT_FOUND 仅 receive 成功,普通 check 抛 NotFoundException', () => {
+ const status = buildStatus(Code.MESSAGE_NOT_FOUND).toObject();
+ checkReceiveStatus(status, 'receive-id');
+ assert.throws(() => exceptions.StatusChecker.check(status, 'ack-id'),
exceptions.NotFoundException);
+ });
+
+ it('receive 的其他错误保留类型和 ID', () => {
+ assert.throws(() => checkReceiveStatus(buildStatus(Code.UNAUTHORIZED,
'server message').toObject(), 'request-42'), error =>
+ verifyException(error, 'UnauthorizedException', Code.UNAUTHORIZED));
+ });
+
+ for (const check of [ exceptions.StatusChecker.check, checkReceiveStatus ]) {
+ it(`${check.name} 缺失 status 时抛内部错误`, () => {
+ assert.throws(() => check(undefined, 'request-42'), error =>
+ verifyException(error, 'InternalErrorException',
Code.INTERNAL_SERVER_ERROR, 'request-42', 'status was not set by server'));
+ });
+ }
+
+ it('未知 code 抛 UnsupportedException,保留原始 code', () => {
+ assert.throws(() => exceptions.StatusChecker.check({ code: 99999 as Code,
message: 'server message' }, 'request-42'), error =>
+ verifyException(error, 'UnsupportedException', 99999));
+ });
+
+ const standardExceptions = [
+ exceptions.ClientException, exceptions.BadRequestException,
exceptions.ForbiddenException,
+ exceptions.InternalErrorException,
exceptions.LiteTopicQuotaExceededException, exceptions.NotFoundException,
+ exceptions.PayloadEmptyException, exceptions.PayloadTooLargeException,
exceptions.PaymentRequiredException,
+ exceptions.ProxyTimeoutException,
exceptions.RequestHeaderFieldsTooLargeException,
+ exceptions.TooManyRequestsException, exceptions.UnauthorizedException,
exceptions.UnsupportedException,
+ ];
+ for (const Exception of standardExceptions) {
+ it(`${Exception.name} 保留现有构造参数顺序及可选 ID`, () => {
+ verifyException(new Exception(40100, 'server message', 'request-42'),
Exception.name, 40100);
+ assert.equal(new Exception(40100, 'server message').message,
'[request-id=undefined, response-code=40100] server message');
+ });
+ }
+
+ it('LiteSubscriptionQuotaExceededException 保留 (code, requestId, message)
顺序', () => {
+ verifyException(new
exceptions.LiteSubscriptionQuotaExceededException(42902, 'request-42', 'server
message'),
+ 'LiteSubscriptionQuotaExceededException', 42902);
+ assert.equal(new exceptions.LiteSubscriptionQuotaExceededException(42902,
null, '').message,
+ '[request-id=undefined, response-code=42902] ');
+ });
+
+ it('InternalErrorException 的 retryable 为有类型的 true', () => {
+ const error = new exceptions.InternalErrorException(50000, 'temporary');
+ const retryable: true = error.retryable;
+ assert.equal(retryable, true);
+ assert.equal(error.isRetryable(), true);
+ });
+});
diff --git a/nodejs/test/fixes.test.ts b/nodejs/test/fixes.test.ts
index a43d4b90..dc9bd636 100644
--- a/nodejs/test/fixes.test.ts
+++ b/nodejs/test/fixes.test.ts
@@ -131,10 +131,11 @@ describe('Endpoints parsing', () => {
});
it('should strip http(s) prefixes and parse multiple endpoints', () => {
- const endpoints = new
Endpoints('http://127.0.0.1:10911;https://example.com:8080');
+ const endpoints = new
Endpoints('http://127.0.0.1:10911;https://127.0.0.2:8080');
assert.strictEqual(endpoints.addressesList.length, 2);
assert.deepStrictEqual(endpoints.addressesList[0], { host: '127.0.0.1',
port: 10911 });
- assert.deepStrictEqual(endpoints.addressesList[1], { host: 'example.com',
port: 8080 });
+ assert.deepStrictEqual(endpoints.addressesList[1], { host: '127.0.0.2',
port: 8080 });
+ assert.throws(() => new
Endpoints('http://127.0.0.1:10911;https://example.com:8080'), TypeError);
});
});
diff --git a/nodejs/test/retry/RetryPolicy.test.ts
b/nodejs/test/retry/RetryPolicy.test.ts
new file mode 100644
index 00000000..ea8d09fa
--- /dev/null
+++ b/nodejs/test/retry/RetryPolicy.test.ts
@@ -0,0 +1,77 @@
+/**
+ * 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 { RetryPolicy as RetryPolicyPB, ExponentialBackoff } from
'../../proto/apache/rocketmq/v2/definition_pb';
+import { ExponentialBackoffRetryPolicy, CustomizedBackoffRetryPolicy } from
'../../src/retry';
+
+function wireCopy(policy: RetryPolicyPB) {
+ return RetryPolicyPB.deserializeBinary(policy.serializeBinary());
+}
+
+describe('RetryPolicy 对齐 Java 的毫秒行为', () => {
+ const exponential = new ExponentialBackoffRetryPolicy(7, 125.5, 1000.25, 2);
+ const customized = new CustomizedBackoffRetryPolicy([ 0, 125.5, 2500.25 ],
7);
+ for (const [ attempt, delay ] of [[ 1, 125.5 ], [ 2, 251 ], [ 3, 502 ], [ 4,
1000.25 ], [ 100000, 1000.25 ]]) {
+ it(`指数策略 attempt=${attempt} 延迟=${delay}`, () =>
assert.equal(exponential.getNextAttemptDelay(attempt), delay));
+ }
+ for (const [ attempt, delay ] of [[ 1, 0 ], [ 2, 125.5 ], [ 3, 2500.25 ], [
4, 2500.25 ], [ 100000, 2500.25 ]]) {
+ it(`自定义策略 attempt=${attempt} 延迟=${delay}`, () =>
assert.equal(customized.getNextAttemptDelay(attempt), delay));
+ }
+
+ for (const policy of [ exponential, customized ]) {
+ for (const attempt of [ 0, -1, NaN ]) {
+ it(`${policy.constructor.name} 拒绝非正 attempt ${attempt}`, () =>
assert.throws(() => policy.getNextAttemptDelay(attempt)));
+ }
+ it(`${policy.constructor.name} protobuf 往返保留亚秒精度,inherit 保留本地
maxAttempts`, () => {
+ const protobuf = wireCopy(policy.toProtobuf().setMaxAttempts(99));
+ const inherited = policy.inheritBackoff(protobuf);
+ assert.equal(inherited.getMaxAttempts(), 7);
+ assert.equal(policy.getMaxAttempts(), 7);
+ for (const attempt of [ 1, 2, 3, 4, 100000 ]) {
+ assert.equal(inherited.getNextAttemptDelay(attempt),
policy.getNextAttemptDelay(attempt));
+ }
+ assert.deepEqual(wireCopy(inherited.toProtobuf()).toObject(),
wireCopy(policy.toProtobuf()).toObject());
+ });
+ it(`${policy.constructor.name} 拒绝缺失 strategy`, () => assert.throws(() =>
policy.inheritBackoff(new RetryPolicyPB())));
+ }
+
+ it('两个策略拒绝继承另一种 strategy', () => {
+ assert.throws(() => exponential.inheritBackoff(customized.toProtobuf()));
+ assert.throws(() => customized.inheritBackoff(exponential.toProtobuf()));
+ });
+
+ it('立即重试及默认构造保持零延迟', () => {
+ for (const policy of [
ExponentialBackoffRetryPolicy.immediatelyRetryPolicy(3), new
ExponentialBackoffRetryPolicy(3) ]) {
+ assert.equal(policy.getMaxAttempts(), 3);
+ assert.equal(policy.getNextAttemptDelay(1), 0);
+ assert.equal(policy.getNextAttemptDelay(100000), 0);
+ assert.equal(wireCopy(policy.toProtobuf()).getMaxAttempts(), 3);
+ }
+ assert.equal(new ExponentialBackoffRetryPolicy(3, -1, 100,
2).getNextAttemptDelay(1), 0);
+ });
+
+ it('指数策略继承缺省 Duration 使用零值', () => {
+ const inherited = exponential.inheritBackoff(new
RetryPolicyPB().setExponentialBackoff(new
ExponentialBackoff().setMultiplier(1)));
+ assert.equal(inherited.getNextAttemptDelay(1), 0);
+ });
+
+ it('自定义策略拒绝空 durations,Duration 转换保留纳秒', () => {
+ assert.throws(() => new CustomizedBackoffRetryPolicy([], 3));
+
assert.deepEqual(CustomizedBackoffRetryPolicy.durationsToMillis(customized.toProtobuf().getCustomizedBackoff()!),
[ 0, 125.5, 2500.25 ]);
+ });
+});
diff --git a/nodejs/test/route/Endpoints.test.ts
b/nodejs/test/route/Endpoints.test.ts
index 79f3bc06..19276a82 100644
--- a/nodejs/test/route/Endpoints.test.ts
+++ b/nodejs/test/route/Endpoints.test.ts
@@ -36,6 +36,51 @@ function endpointsFromPb(scheme: AddressScheme, host:
string, port: number): End
return new Endpoints(pb.toObject());
}
+describe('Endpoints 表驱动解析与往返', () => {
+ const cases = [
+ [ '127.0.0.1', AddressScheme.IPV4, 'ip:127.0.0.1:80' ],
+ [ 'http://127.0.0.1:1', AddressScheme.IPV4, 'ip:127.0.0.1:1' ],
+ [ 'https://example.com', AddressScheme.DOMAIN_NAME, 'dns:example.com:80' ],
+ [ 'example.com:65535', AddressScheme.DOMAIN_NAME, 'dns:example.com:65535'
],
+ [ '::1', AddressScheme.IPV6, 'ip:[::1]:80' ],
+ [ '[::1]', AddressScheme.IPV6, 'ip:[::1]:80' ],
+ [ '[::1]:8081', AddressScheme.IPV6, 'ip:[::1]:8081' ],
+ [ '[::1]:8081;[::2]:8082', AddressScheme.IPV6, 'ip:[::1]:8081,[::2]:8082'
],
+ [ ' example.com:80 ; example.org:81 ', AddressScheme.DOMAIN_NAME,
'dns:example.com:80,example.org:81' ],
+ ] as const;
+ for (const [ input, scheme, target ] of cases) {
+ it(`${input} 保留合法解析和 protobuf 往返`, () => {
+ const endpoints = new Endpoints(input);
+ assert.strictEqual(endpoints.scheme, scheme);
+ assert.strictEqual(endpoints.getGrpcTarget(), target);
+ const copy = new
Endpoints(EndpointsPB.deserializeBinary(endpoints.toProtobuf().serializeBinary()).toObject());
+ assert.ok(endpoints.equals(copy));
+ assert.ok(endpoints.equals(endpoints));
+ assert.strictEqual(copy.hashCode(), endpoints.hashCode());
+ assert.strictEqual(copy.toString(), endpoints.facade);
+ assert.strictEqual(copy.getGrpcTarget(), target);
+ });
+ }
+
+ for (const input of [
+ '', 'host:', 'host:abc', 'host:80abc', 'host:0', 'host:-1', 'host:65536',
'host:1.5',
+ '[::1]:0', '[::1]:65536', '[::1', '[bad]:80', '::gg', '[::1]:abc',
+ '127.0.0.1;example.com', 'example.com;127.0.0.1', '127.0.0.1;::1',
'::1;127.0.0.1',
+ ]) {
+ it(`${input} 在构造时抛 TypeError`, () => {
+ assert.throws(() => new Endpoints(input), TypeError);
+ });
+ }
+
+ it('scheme、地址和顺序差异影响 equals', () => {
+ const endpoints = new Endpoints('127.0.0.1:80;127.0.0.2:81');
+ assert.strictEqual(endpoints.equals(undefined as unknown as Endpoints),
false);
+ assert.strictEqual(endpoints.equals(new Endpoints('127.0.0.1:80')), false);
+ assert.strictEqual(endpoints.equals(new
Endpoints('127.0.0.2:81;127.0.0.1:80')), false);
+ assert.strictEqual(endpoints.equals(new Endpoints({ scheme:
AddressScheme.DOMAIN_NAME, addressesList: endpoints.addressesList })), false);
+ });
+});
+
describe('Endpoints.getGrpcTarget with resolver scheme (custom ip resolver)',
() => {
it('should prefix ip: scheme for IPv4 addresses', () => {
assert.strictEqual(new Endpoints('127.0.0.1:10911').getGrpcTarget(),
'ip:127.0.0.1:10911');
diff --git a/nodejs/test/route/RouteData.test.ts
b/nodejs/test/route/RouteData.test.ts
new file mode 100644
index 00000000..ca238c2b
--- /dev/null
+++ b/nodejs/test/route/RouteData.test.ts
@@ -0,0 +1,118 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { strict as assert } from 'node:assert';
+import { MessageType, Permission, MessageQueue as MessageQueuePB } from
'../../proto/apache/rocketmq/v2/definition_pb';
+import { Broker, Endpoints, MessageQueue, Resource, TopicRouteData } from
'../../src/route';
+import { buildRoute } from '../support/protobuf';
+
+describe('Route 数据模型与 namespace', () => {
+ for (const namespace of [ '', 'tenant-a', '中文租户' ]) {
+ it(`Resource(${namespace}) 保留构造参数、namespace、相等与 protobuf 往返`, () => {
+ const resource = new Resource(namespace, 'topic');
+ const copy = Resource.fromProtobuf(resource.toProtobuf());
+ assert.equal(copy.getNamespace(), namespace);
+ assert.equal(copy.getName(), 'topic');
+ assert(resource.equals(resource));
+ assert(resource.equals(copy));
+ assert.equal(resource.hashCode(), copy.hashCode());
+ assert.equal(resource.equals(new Resource('other', 'topic')), false);
+ assert.equal(resource.equals(new Resource(namespace, 'other')), false);
+ assert.equal(resource.equals(undefined as unknown as Resource), false);
+ assert.equal(resource.toString(), namespace ? `Resource{name='topic',
namespace='${namespace}'}` : 'topic');
+ });
+ }
+ it('Resource 单参数构造保留默认 namespace', () => assert(new
Resource('topic').equals(new Resource('', 'topic'))));
+
+ for (const namespace of [ '', 'tenant-a' ]) {
+ it(`MessageQueue(${namespace}) protobuf 往返保留完整路由`, () => {
+ const queue = buildRoute({ namespace, queuesPerBroker: 3
}).messageQueues[2];
+ queue.acceptMessageTypesList = [ MessageType.NORMAL, MessageType.FIFO ];
+ const copy = new
MessageQueue(MessageQueuePB.deserializeBinary(queue.toProtobuf().serializeBinary()));
+ assert.deepEqual(copy.topic, queue.topic);
+ assert.equal(copy.topic.resourceNamespace, namespace);
+ assert.equal(copy.queueId, 2);
+ assert.equal(copy.permission, Permission.READ_WRITE);
+ assert.deepEqual(copy.acceptMessageTypesList,
queue.acceptMessageTypesList);
+ assert(queue.equals(queue));
+ assert(queue.equals(copy));
+ assert.equal(copy.hashCode(), queue.hashCode());
+ assert.deepEqual(copy.toProtobuf().toObject(),
queue.toProtobuf().toObject());
+ assert.equal(queue.equals(undefined as unknown as MessageQueue), false);
+ });
+ }
+
+ for (const field of [ 'namespace', 'queueId', 'permission', 'brokerId',
'topic' ]) {
+ it(`MessageQueue 的 ${field} 不同则不相等`, () => {
+ const queue = buildRoute({ namespace: 'tenant-a' }).messageQueues[0];
+ const other = new MessageQueue(queue.toProtobuf());
+ switch (field) {
+ case 'namespace': other.topic.resourceNamespace = 'tenant-b'; break;
+ case 'queueId': other.queueId++; break;
+ case 'permission': other.permission = Permission.READ; break;
+ case 'brokerId': other.broker.id++; break;
+ case 'topic': other.topic.name = 'other-topic'; break;
+ default: assert.fail(`未知字段 ${field}`);
+ }
+ assert.equal(queue.equals(other), false);
+ assert.notEqual(queue.hashCode(), other.hashCode());
+ });
+ }
+
+ it('空 namespace 保留基点的 MessageQueue hashCode 数值', () => {
+ assert.equal(buildRoute().messageQueues[0].hashCode(), -1085438236);
+ });
+
+ it('Broker 以 name、id、endpoints 比较并往返', () => {
+ const broker = buildRoute().messageQueues[0].broker;
+ const copy = new Broker(broker.toProtobuf().toObject());
+ assert(broker.equals(broker));
+ assert(broker.equals(copy));
+ assert.equal(broker.hashCode(), copy.hashCode());
+ assert.equal(broker.equals(undefined as unknown as Broker), false);
+ for (const change of [
+ (b: Broker) => { b.id++; }, (b: Broker) => { b.name = 'other'; },
+ (b: Broker) => { b.endpoints = new Endpoints('127.0.0.2:8081'); },
+ ]) {
+ const other = new Broker(broker.toProtobuf().toObject());
+ change(other);
+ assert.equal(broker.equals(other), false);
+ }
+ });
+
+ it('TopicRouteData 去重 endpoint、保留队列顺序和 equals/hashCode', () => {
+ const route = buildRoute({ queuesPerBroker: 2, brokers: [
+ { name: 'a', endpoints: '127.0.0.1:80' }, { name: 'b', endpoints:
'127.0.0.2:80' },
+ { name: 'c', endpoints: '127.0.0.1:80' },
+ ] });
+ const copy = new TopicRouteData(route.messageQueues.map(q =>
q.toProtobuf()));
+ assert.equal(route.getQueueCount(), 6);
+ assert.equal(route.isEmpty(), false);
+ assert.deepEqual(route.getTotalEndpoints().map(e => e.facade), [
'127.0.0.1:80', '127.0.0.2:80' ]);
+ assert(route.equals(route));
+ assert(route.equals(copy));
+ assert.equal(route.hashCode(), copy.hashCode());
+ assert.equal(route.equals(undefined as unknown as TopicRouteData), false);
+ assert.equal(route.equals(new TopicRouteData([])), false);
+ assert.equal(route.equals(new TopicRouteData(route.messageQueues.map(q =>
q.toProtobuf()).reverse())), false);
+ const empty = new TopicRouteData([]);
+ assert(empty.isEmpty());
+ assert.equal(empty.getQueueCount(), 0);
+ assert.deepEqual(empty.getTotalEndpoints(), []);
+ assert(empty.equals(new TopicRouteData([])));
+ });
+});
diff --git a/nodejs/test/util/Semaphore.test.ts
b/nodejs/test/util/Semaphore.test.ts
index ee897a9e..f207044f 100644
--- a/nodejs/test/util/Semaphore.test.ts
+++ b/nodejs/test/util/Semaphore.test.ts
@@ -69,6 +69,30 @@ describe('Semaphore (consumption permit primitive)', () => {
assert.strictEqual(s.availablePermits, 0);
});
+ it('release 可以超过初值,不设置隐含上限', async () => {
+ const s = new Semaphore(1);
+ s.release();
+ s.release();
+ assert.strictEqual(s.availablePermits, 3);
+ await s.acquire();
+ assert.strictEqual(s.availablePermits, 2);
+ });
+
+ it('逐次唤醒 FIFO 等待者,尚未分配的等待者不提前执行', async () => {
+ const s = new Semaphore(0);
+ const order: number[] = [];
+ const first = s.acquire().then(() => order.push(1));
+ const second = s.acquire().then(() => order.push(2));
+ s.release();
+ await first;
+ assert.deepStrictEqual(order, [ 1 ]);
+ assert.strictEqual(s.tryAcquire(), false);
+ s.release();
+ await second;
+ assert.deepStrictEqual(order, [ 1, 2 ]);
+ assert.strictEqual(s.availablePermits, 0);
+ });
+
it('release hands the permit to a waiter without incrementing the pool', ()
=> {
const s = new Semaphore(0);
const p = s.acquire();
diff --git a/nodejs/test/util/index.test.ts b/nodejs/test/util/index.test.ts
index 854969c3..dc5397d7 100644
--- a/nodejs/test/util/index.test.ts
+++ b/nodejs/test/util/index.test.ts
@@ -16,10 +16,13 @@
*/
import { strict as assert } from 'node:assert';
+import { Duration } from 'google-protobuf/google/protobuf/duration_pb';
+import * as sinon from 'sinon';
import {
createDuration,
getTimestamp,
calculateStringSipHash24,
+ crc32CheckSum, md5CheckSum, sha1CheckSum, hashCodeOfString,
getRequestDateTime, sign, createResource,
} from '../../src/util';
describe('test/util/index.test.ts', () => {
@@ -32,6 +35,24 @@ describe('test/util/index.test.ts', () => {
});
describe('createDuration()', () => {
+ const cases = [
+ [ 0, 0, 0 ], [ -0, 0, 0 ], [ 0.000001, 0, 1 ], [ 0.1234567, 0, 123456 ],
+ [ 999.999999, 0, 999999999 ], [ 1000, 1, 0 ], [ 1000.5, 1, 500000 ],
+ [ -0.5, 0, -500000 ], [ -999, 0, -999000000 ], [ -1000, -1, 0 ], [
-1000.5, -1, -500000 ],
+ [ -2173, -2, -173000000 ], [ 315576000000000, 315576000000, 0 ],
+ [ -315576000000000, -315576000000, 0 ],
+ ];
+ for (const [ ms, seconds, nanos ] of cases) {
+ it(`${ms}ms 序列化保留整数 seconds、nanos 与同号余数`, () => {
+ const duration = createDuration(ms);
+ assert.equal(duration.getSeconds(), seconds);
+ assert.equal(duration.getNanos(), nanos);
+
assert.deepEqual(Duration.deserializeBinary(duration.serializeBinary()).toObject(),
duration.toObject());
+ });
+ }
+ for (const ms of [ NaN, Infinity, -Infinity, 315576000000001,
-315576000000001 ]) {
+ it(`${ms} 在调用时抛 RangeError`, () => assert.throws(() =>
createDuration(ms), RangeError));
+ }
it('should split whole seconds correctly', () => {
const duration = createDuration(2000);
assert.equal(duration.getSeconds(), 2);
@@ -48,6 +69,53 @@ describe('test/util/index.test.ts', () => {
});
});
+ describe('Java 固定向量', () => {
+ // JShell 21 + Guava Hashing.sipHash24().hashBytes(UTF_8).asLong()。
+ const vectors = [
+ [ '', 0, 8246050544436514353n ], [ 'abc', 96354, 6754548778392356773n ],
+ [ 'RocketMQ', -453554280, -4355033068952641245n ], [ '你好', 652829,
-4706515592422728576n ],
+ [ '😄', 1772903, -3031427512150344328n ], [ 'a😄z', 57849842,
5994498846521405229n ],
+ [ 'foo哈哈😄2222哈哈', -1149599763, -705383726186849630n ],
+ ] as const;
+ for (const [ value, hashCode, javaSipHash ] of vectors) {
+ it(`${value} 的 UTF-16 hashCode 与 SipHash 字节对齐 Java`, () => {
+ assert.equal(hashCodeOfString(value), hashCode);
+ // Node 公开结果为摘要字节的无符号大端值;Java asLong 为小端有符号值。
+ const bytes = Buffer.alloc(8);
+ bytes.writeBigUInt64BE(calculateStringSipHash24(value));
+ assert.equal(bytes.readBigInt64LE(), javaSipHash);
+ });
+ }
+ });
+
+ describe('摘要、签名与请求时间', () => {
+ const vectors = [
+ [ '', '0', 'D41D8CD98F00B204E9800998ECF8427E',
'DA39A3EE5E6B4B0D3255BFEF95601890AFD80709' ],
+ [ '123456789', '3421780262', '25F9E794323B453885F5181F1B624D0B',
'F7C3BC1D808E04732ADF679965CCC34CA7AE3441' ],
+ [ 'abc', '891568578', '900150983CD24FB0D6963F7D28E17F72',
'A9993E364706816ABA3E25717850C26C9CD0D89D' ],
+ ];
+ for (const [ input, crc32, md5, sha1 ] of vectors) {
+ it(`${input} 的标准摘要向量`, () => {
+ const bytes = Buffer.from(input);
+ assert.equal(crc32CheckSum(bytes), crc32);
+ assert.equal(md5CheckSum(bytes), md5);
+ assert.equal(sha1CheckSum(bytes), sha1);
+ });
+ }
+ it('HMAC-SHA1 使用大写十六进制', () => {
+ assert.equal(sign('key', 'The quick brown fox jumps over the lazy dog'),
'DE7C9B85B8B78AA6BC8A7A36F70A90701C9DB4D9');
+ });
+ it('请求日期使用 UTC 格式且资源默认 namespace 为空', () => {
+ const clock = sinon.useFakeTimers({ now:
Date.parse('2026-11-18T12:34:56.789Z'), toFake: [ 'Date' ] });
+ try {
+ assert.equal(getRequestDateTime(), '20261118T123456Z');
+ assert.deepEqual(createResource('test-topic').toObject(), { name:
'test-topic', resourceNamespace: '' });
+ } finally {
+ clock.restore();
+ }
+ });
+ });
+
describe('calculateStringSipHash24()', () => {
it('should work', () => {
assert.equal(calculateStringSipHash24('foo哈哈😄2222哈哈'),
11716758754047899126n);