rocketmq-client-nodejs 1.0.2 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/README.md +84 -1
  2. package/dist/client/BaseClient.d.ts +24 -2
  3. package/dist/client/BaseClient.js +173 -28
  4. package/dist/client/ClientId.js +2 -2
  5. package/dist/client/Logger.d.ts +1 -0
  6. package/dist/client/Logger.js +1 -1
  7. package/dist/client/RpcClient.d.ts +3 -1
  8. package/dist/client/RpcClient.js +23 -1
  9. package/dist/client/RpcClientManager.d.ts +3 -1
  10. package/dist/client/RpcClientManager.js +23 -4
  11. package/dist/client/TelemetrySession.d.ts +1 -0
  12. package/dist/client/TelemetrySession.js +47 -9
  13. package/dist/consumer/Assignment.d.ts +24 -0
  14. package/dist/consumer/Assignment.js +40 -0
  15. package/dist/consumer/Assignments.d.ts +25 -0
  16. package/dist/consumer/Assignments.js +55 -0
  17. package/dist/consumer/ConsumeResult.d.ts +20 -0
  18. package/dist/consumer/ConsumeResult.js +25 -0
  19. package/dist/consumer/ConsumeService.d.ts +28 -0
  20. package/dist/consumer/ConsumeService.js +53 -0
  21. package/dist/consumer/ConsumeTask.d.ts +24 -0
  22. package/dist/consumer/ConsumeTask.js +39 -0
  23. package/dist/consumer/Consumer.d.ts +19 -1
  24. package/dist/consumer/Consumer.js +64 -21
  25. package/dist/consumer/FifoConsumeService.d.ts +25 -0
  26. package/dist/consumer/FifoConsumeService.js +130 -0
  27. package/dist/consumer/FilterExpression.d.ts +2 -0
  28. package/dist/consumer/FilterExpression.js +18 -1
  29. package/dist/consumer/LitePushConsumer.d.ts +161 -0
  30. package/dist/consumer/LitePushConsumer.js +172 -0
  31. package/dist/consumer/LitePushConsumerImpl.d.ts +167 -0
  32. package/dist/consumer/LitePushConsumerImpl.js +193 -0
  33. package/dist/consumer/LiteSubscriptionManager.d.ts +97 -0
  34. package/dist/consumer/LiteSubscriptionManager.js +236 -0
  35. package/dist/consumer/MessageListener.d.ts +21 -0
  36. package/dist/consumer/MessageListener.js +19 -0
  37. package/dist/consumer/OffsetOption.d.ts +109 -0
  38. package/dist/consumer/OffsetOption.js +191 -0
  39. package/dist/consumer/ProcessQueue.d.ts +39 -0
  40. package/dist/consumer/ProcessQueue.js +293 -0
  41. package/dist/consumer/PushConsumer.d.ts +88 -0
  42. package/dist/consumer/PushConsumer.js +449 -0
  43. package/dist/consumer/PushSubscriptionSettings.d.ts +31 -0
  44. package/dist/consumer/PushSubscriptionSettings.js +97 -0
  45. package/dist/consumer/SimpleConsumer.d.ts +12 -1
  46. package/dist/consumer/SimpleConsumer.js +54 -10
  47. package/dist/consumer/SimpleSubscriptionSettings.d.ts +2 -2
  48. package/dist/consumer/SimpleSubscriptionSettings.js +3 -3
  49. package/dist/consumer/StandardConsumeService.d.ts +25 -0
  50. package/dist/consumer/StandardConsumeService.js +50 -0
  51. package/dist/consumer/index.d.ts +15 -0
  52. package/dist/consumer/index.js +19 -1
  53. package/dist/exception/InternalErrorException.d.ts +5 -0
  54. package/dist/exception/InternalErrorException.js +10 -1
  55. package/dist/exception/LiteSubscriptionQuotaExceededException.d.ts +23 -0
  56. package/dist/exception/LiteSubscriptionQuotaExceededException.js +31 -0
  57. package/dist/exception/LiteTopicQuotaExceededException.d.ts +23 -0
  58. package/dist/exception/LiteTopicQuotaExceededException.js +31 -0
  59. package/dist/exception/StatusChecker.js +4 -1
  60. package/dist/exception/index.d.ts +2 -0
  61. package/dist/exception/index.js +3 -1
  62. package/dist/index.d.ts +1 -0
  63. package/dist/index.js +2 -1
  64. package/dist/message/Message.d.ts +8 -0
  65. package/dist/message/Message.js +39 -6
  66. package/dist/message/MessageId.d.ts +2 -0
  67. package/dist/message/MessageId.js +17 -1
  68. package/dist/message/MessageView.d.ts +86 -0
  69. package/dist/message/MessageView.js +115 -1
  70. package/dist/message/PublishingMessage.js +21 -5
  71. package/dist/producer/Producer.d.ts +21 -2
  72. package/dist/producer/Producer.js +120 -25
  73. package/dist/producer/PublishingLoadBalancer.d.ts +2 -0
  74. package/dist/producer/PublishingLoadBalancer.js +23 -1
  75. package/dist/producer/RecallReceipt.d.ts +25 -0
  76. package/dist/producer/RecallReceipt.js +34 -0
  77. package/dist/producer/SendReceipt.d.ts +2 -1
  78. package/dist/producer/SendReceipt.js +6 -3
  79. package/dist/producer/Transaction.js +7 -1
  80. package/dist/producer/index.d.ts +1 -0
  81. package/dist/producer/index.js +2 -1
  82. package/dist/route/Broker.d.ts +2 -0
  83. package/dist/route/Broker.js +21 -1
  84. package/dist/route/Endpoints.d.ts +2 -0
  85. package/dist/route/Endpoints.js +36 -1
  86. package/dist/route/MessageQueue.d.ts +2 -0
  87. package/dist/route/MessageQueue.js +23 -1
  88. package/dist/route/Resource.d.ts +54 -0
  89. package/dist/route/Resource.js +100 -0
  90. package/dist/route/TopicRouteData.d.ts +12 -0
  91. package/dist/route/TopicRouteData.js +37 -1
  92. package/dist/route/index.d.ts +1 -0
  93. package/dist/route/index.js +2 -1
  94. package/dist/util/index.d.ts +8 -0
  95. package/dist/util/index.js +20 -1
  96. package/package.json +2 -3
  97. package/proto/apache/rocketmq/v2/definition.proto +56 -0
  98. package/proto/apache/rocketmq/v2/definition_pb.d.ts +100 -0
  99. package/proto/apache/rocketmq/v2/definition_pb.js +570 -4
  100. package/proto/apache/rocketmq/v2/service.proto +65 -0
  101. package/proto/apache/rocketmq/v2/service_grpc_pb.d.ts +34 -0
  102. package/proto/apache/rocketmq/v2/service_grpc_pb.js +81 -4
  103. package/proto/apache/rocketmq/v2/service_pb.d.ts +211 -0
  104. package/proto/apache/rocketmq/v2/service_pb.js +1691 -25
  105. package/src/client/BaseClient.ts +196 -28
  106. package/src/client/ClientId.ts +1 -1
  107. package/src/client/Logger.ts +1 -0
  108. package/src/client/RpcClient.ts +26 -0
  109. package/src/client/RpcClientManager.ts +27 -3
  110. package/src/client/TelemetrySession.ts +54 -8
  111. package/src/consumer/Assignment.ts +40 -0
  112. package/src/consumer/Assignments.ts +55 -0
  113. package/src/consumer/ConsumeResult.ts +21 -0
  114. package/src/consumer/ConsumeService.ts +72 -0
  115. package/src/consumer/ConsumeTask.ts +39 -0
  116. package/src/consumer/Consumer.ts +76 -20
  117. package/src/consumer/FifoConsumeService.ts +146 -0
  118. package/src/consumer/FilterExpression.ts +17 -0
  119. package/src/consumer/LitePushConsumer.ts +256 -0
  120. package/src/consumer/LitePushConsumerImpl.ts +245 -0
  121. package/src/consumer/LiteSubscriptionManager.ts +352 -0
  122. package/src/consumer/MessageListener.ts +23 -0
  123. package/src/consumer/OffsetOption.ts +203 -0
  124. package/src/consumer/ProcessQueue.ts +339 -0
  125. package/src/consumer/PushConsumer.ts +563 -0
  126. package/src/consumer/PushSubscriptionSettings.ts +124 -0
  127. package/src/consumer/SimpleConsumer.ts +68 -11
  128. package/src/consumer/SimpleSubscriptionSettings.ts +2 -2
  129. package/src/consumer/StandardConsumeService.ts +57 -0
  130. package/src/consumer/index.ts +15 -0
  131. package/src/exception/InternalErrorException.ts +10 -0
  132. package/src/exception/LiteSubscriptionQuotaExceededException.ts +28 -0
  133. package/src/exception/LiteTopicQuotaExceededException.ts +28 -0
  134. package/src/exception/StatusChecker.ts +3 -0
  135. package/src/exception/index.ts +2 -0
  136. package/src/index.ts +1 -0
  137. package/src/message/Message.ts +46 -5
  138. package/src/message/MessageId.ts +16 -0
  139. package/src/message/MessageView.ts +127 -0
  140. package/src/message/PublishingMessage.ts +20 -4
  141. package/src/producer/Producer.ts +144 -24
  142. package/src/producer/PublishingLoadBalancer.ts +21 -0
  143. package/src/producer/RecallReceipt.ts +32 -0
  144. package/src/producer/SendReceipt.ts +5 -2
  145. package/src/producer/Transaction.ts +16 -0
  146. package/src/producer/index.ts +1 -0
  147. package/src/route/Broker.ts +20 -0
  148. package/src/route/Endpoints.ts +32 -0
  149. package/src/route/MessageQueue.ts +23 -1
  150. package/src/route/Resource.ts +104 -0
  151. package/src/route/TopicRouteData.ts +37 -0
  152. package/src/route/index.ts +1 -0
  153. package/src/util/index.ts +19 -0
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Licensed to the Apache Software Foundation (ASF) under one or more
3
+ * contributor license agreements. See the NOTICE file distributed with
4
+ * this work for additional information regarding copyright ownership.
5
+ * The ASF licenses this file to You under the Apache License, Version 2.0
6
+ * (the "License"); you may not use this file except in compliance with
7
+ * the License. You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ /**
19
+ * OffsetOption type enum.
20
+ */
21
+ export enum OffsetType {
22
+ POLICY = 0,
23
+ OFFSET = 1,
24
+ TAIL_N = 2,
25
+ TIMESTAMP = 3,
26
+ }
27
+
28
+ /**
29
+ * ProtoBuf OffsetOption type.
30
+ */
31
+ import { OffsetOption as ProtoOffsetOption } from '../../proto/apache/rocketmq/v2/definition_pb';
32
+
33
+ /**
34
+ * OffsetOption for specifying consume from offset.
35
+ *
36
+ * <p>OffsetOption is used to specify the starting point for message consumption.
37
+ * It supports various policies and custom offsets.</p>
38
+ */
39
+ export class OffsetOption {
40
+ /** Policy constant: last offset */
41
+ static readonly POLICY_LAST_VALUE = BigInt(0);
42
+
43
+ /** Policy constant: min offset */
44
+ static readonly POLICY_MIN_VALUE = BigInt(1);
45
+
46
+ /** Policy constant: max offset */
47
+ static readonly POLICY_MAX_VALUE = BigInt(2);
48
+
49
+ /** Predefined option: LAST_OFFSET */
50
+ static readonly LAST_OFFSET = new OffsetOption(OffsetType.POLICY, OffsetOption.POLICY_LAST_VALUE);
51
+
52
+ /** Predefined option: MIN_OFFSET */
53
+ static readonly MIN_OFFSET = new OffsetOption(OffsetType.POLICY, OffsetOption.POLICY_MIN_VALUE);
54
+
55
+ /** Predefined option: MAX_OFFSET */
56
+ static readonly MAX_OFFSET = new OffsetOption(OffsetType.POLICY, OffsetOption.POLICY_MAX_VALUE);
57
+
58
+ private readonly type: OffsetType;
59
+ private readonly value: bigint;
60
+
61
+ private constructor(type: OffsetType, value: bigint) {
62
+ this.type = type;
63
+ this.value = value;
64
+ }
65
+
66
+ /**
67
+ * Create an OffsetOption from a specific offset.
68
+ *
69
+ * @param offset - The offset value (must be >= 0)
70
+ * @return OffsetOption instance
71
+ * @throws Error if offset is negative
72
+ */
73
+ static ofOffset(offset: number | bigint): OffsetOption {
74
+ const value = typeof offset === 'number' ? BigInt(offset) : offset;
75
+ if (value < BigInt(0)) {
76
+ throw new Error('offset must be greater than or equal to 0');
77
+ }
78
+ return new OffsetOption(OffsetType.OFFSET, value);
79
+ }
80
+
81
+ /**
82
+ * Create an OffsetOption from tail N messages.
83
+ *
84
+ * @param tailN - Number of messages from the tail (must be >= 0)
85
+ * @return OffsetOption instance
86
+ * @throws Error if tailN is negative
87
+ */
88
+ static ofTailN(tailN: number | bigint): OffsetOption {
89
+ const value = typeof tailN === 'number' ? BigInt(tailN) : tailN;
90
+ if (value < BigInt(0)) {
91
+ throw new Error('tailN must be greater than or equal to 0');
92
+ }
93
+ return new OffsetOption(OffsetType.TAIL_N, value);
94
+ }
95
+
96
+ /**
97
+ * Create an OffsetOption from a timestamp.
98
+ *
99
+ * @param timestamp - Unix timestamp in milliseconds (must be >= 0)
100
+ * @return OffsetOption instance
101
+ * @throws Error if timestamp is negative
102
+ */
103
+ static ofTimestamp(timestamp: number | bigint): OffsetOption {
104
+ const value = typeof timestamp === 'number' ? BigInt(timestamp) : timestamp;
105
+ if (value < BigInt(0)) {
106
+ throw new Error('timestamp must be greater than or equal to 0');
107
+ }
108
+ return new OffsetOption(OffsetType.TIMESTAMP, value);
109
+ }
110
+
111
+ /**
112
+ * Get the type of this OffsetOption.
113
+ *
114
+ * @return OffsetType
115
+ */
116
+ getType(): OffsetType {
117
+ return this.type;
118
+ }
119
+
120
+ /**
121
+ * Get the value of this OffsetOption.
122
+ *
123
+ * @return Value as bigint
124
+ */
125
+ getValue(): bigint {
126
+ return this.value;
127
+ }
128
+
129
+ /**
130
+ * Returns a string representation of this OffsetOption.
131
+ *
132
+ * @return String representation
133
+ */
134
+ toString(): string {
135
+ return `OffsetOption{type=${OffsetType[this.type]}, value=${this.value}}`;
136
+ }
137
+
138
+ /**
139
+ * Validate that a bigint value is within the safe number range.
140
+ *
141
+ * @param value - The bigint value to validate
142
+ * @throws Error if value is out of safe number range
143
+ */
144
+ private validateSafeNumberRange(value: bigint): void {
145
+ if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER)) {
146
+ throw new Error(`Value ${value} is out of safe number range`);
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Convert this OffsetOption to ProtoBuf OffsetOption.
152
+ *
153
+ * @return ProtoBuf OffsetOption instance
154
+ */
155
+ toProtobuf(): ProtoOffsetOption {
156
+ const proto = new ProtoOffsetOption();
157
+ switch (this.type) {
158
+ case OffsetType.POLICY: {
159
+ // Map our policy values to ProtoBuf Policy enum
160
+ // POLICY_LAST_VALUE (0) -> Policy.LAST (0)
161
+ // POLICY_MIN_VALUE (1) -> Policy.MIN (1)
162
+ // POLICY_MAX_VALUE (2) -> Policy.MAX (2)
163
+ this.validateSafeNumberRange(this.value);
164
+ proto.setPolicy(Number(this.value));
165
+ break;
166
+ }
167
+ case OffsetType.OFFSET: {
168
+ this.validateSafeNumberRange(this.value);
169
+ proto.setOffset(Number(this.value));
170
+ break;
171
+ }
172
+ case OffsetType.TAIL_N: {
173
+ this.validateSafeNumberRange(this.value);
174
+ proto.setTailN(Number(this.value));
175
+ break;
176
+ }
177
+ case OffsetType.TIMESTAMP: {
178
+ this.validateSafeNumberRange(this.value);
179
+ proto.setTimestamp(Number(this.value));
180
+ break;
181
+ }
182
+ default:
183
+ throw new Error(`Unknown OffsetType: ${this.type}`);
184
+ }
185
+ return proto;
186
+ }
187
+
188
+ equals(other: OffsetOption): boolean {
189
+ if (this === other) return true;
190
+ if (!other) return false;
191
+ return this.type === other.type && this.value === other.value;
192
+ }
193
+
194
+ hashCode(): number {
195
+ let hash = 17;
196
+ // eslint-disable-next-line no-bitwise
197
+ hash = (hash * 31 + this.type) | 0;
198
+ const valueNum = Number(this.value);
199
+ // eslint-disable-next-line no-bitwise
200
+ hash = (hash * 31 + valueNum) | 0;
201
+ return hash;
202
+ }
203
+ }
@@ -0,0 +1,339 @@
1
+ /**
2
+ * Licensed to the Apache Software Foundation (ASF) under one or more
3
+ * contributor license agreements. See the NOTICE file distributed with
4
+ * this work for additional information regarding copyright ownership.
5
+ * The ASF licenses this file to You under the Apache License, Version 2.0
6
+ * (the "License"); you may not use this file except in compliance with
7
+ * the License. You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ import { randomUUID } from 'node:crypto';
19
+ import { Code } from '../../proto/apache/rocketmq/v2/definition_pb';
20
+ import { MessageView } from '../message';
21
+ import { MessageQueue } from '../route';
22
+ import { TooManyRequestsException } from '../exception';
23
+ import { ConsumeResult } from './ConsumeResult';
24
+ import { FilterExpression } from './FilterExpression';
25
+ import type { PushConsumer } from './PushConsumer';
26
+
27
+ const ACK_MESSAGE_FAILURE_BACKOFF_DELAY = 1000;
28
+ const CHANGE_INVISIBLE_DURATION_FAILURE_BACKOFF_DELAY = 1000;
29
+ const FORWARD_MESSAGE_TO_DLQ_FAILURE_BACKOFF_DELAY = 1000;
30
+
31
+ const RECEIVING_FLOW_CONTROL_BACKOFF_DELAY = 20;
32
+ const RECEIVING_FAILURE_BACKOFF_DELAY = 1000;
33
+ const RECEIVING_BACKOFF_DELAY_WHEN_CACHE_IS_FULL = 1000;
34
+
35
+ export class ProcessQueue {
36
+ readonly #consumer: PushConsumer;
37
+ #dropped = false;
38
+ readonly #mq: MessageQueue;
39
+ readonly #filterExpression: FilterExpression;
40
+ readonly #cachedMessages: MessageView[] = [];
41
+ #cachedMessagesBytes = 0;
42
+ #activityTime = Date.now();
43
+ #cacheFullTime = 0;
44
+ #aborted = false;
45
+
46
+ constructor(consumer: PushConsumer, mq: MessageQueue, filterExpression: FilterExpression) {
47
+ this.#consumer = consumer;
48
+ this.#mq = mq;
49
+ this.#filterExpression = filterExpression;
50
+ }
51
+
52
+ getMessageQueue(): MessageQueue {
53
+ return this.#mq;
54
+ }
55
+
56
+ drop(): void {
57
+ this.#dropped = true;
58
+ }
59
+
60
+ expired(): boolean {
61
+ const longPollingTimeout = this.#consumer.getPushConsumerSettings().getLongPollingTimeout();
62
+ const requestTimeout = this.#consumer.requestTimeoutValue;
63
+ const maxIdleDuration = (longPollingTimeout + requestTimeout) * 3;
64
+ const idleDuration = Date.now() - this.#activityTime;
65
+ if (idleDuration < maxIdleDuration) {
66
+ return false;
67
+ }
68
+ const afterCacheFullDuration = Date.now() - this.#cacheFullTime;
69
+ if (afterCacheFullDuration < maxIdleDuration) {
70
+ return false;
71
+ }
72
+ return true;
73
+ }
74
+
75
+ cacheMessages(messageList: MessageView[]): void {
76
+ for (const messageView of messageList) {
77
+ this.#cachedMessages.push(messageView);
78
+ this.#cachedMessagesBytes += messageView.body.length;
79
+ }
80
+ }
81
+
82
+ #getReceptionBatchSize(): number {
83
+ const bufferSize = Math.max(
84
+ this.#consumer.cacheMessageCountThresholdPerQueue() - this.cachedMessagesCount(),
85
+ 1,
86
+ );
87
+ return Math.min(bufferSize, this.#consumer.getPushConsumerSettings().getReceiveBatchSize());
88
+ }
89
+
90
+ fetchMessageImmediately(): void {
91
+ (this.#consumer as any).logger?.info('ProcessQueue.fetchMessageImmediately called, mq=%s@%s@%d',
92
+ this.#mq.topic.name, this.#mq.broker.name, this.#mq.queueId);
93
+ this.#receiveMessageImmediately();
94
+ }
95
+
96
+ onReceiveMessageException(t: Error, attemptId?: string): void {
97
+ const delay = t instanceof TooManyRequestsException
98
+ ? RECEIVING_FLOW_CONTROL_BACKOFF_DELAY
99
+ : RECEIVING_FAILURE_BACKOFF_DELAY;
100
+ this.#receiveMessageLater(delay, attemptId);
101
+ }
102
+
103
+ #receiveMessageLater(delay: number, attemptId?: string): void {
104
+ if (this.#aborted) return;
105
+ setTimeout(() => {
106
+ if (this.#aborted) return;
107
+ this.#receiveMessage(attemptId);
108
+ }, delay);
109
+ }
110
+
111
+ #generateAttemptId(): string {
112
+ return randomUUID();
113
+ }
114
+
115
+ receiveMessage(attemptId?: string): void {
116
+ this.#receiveMessage(attemptId);
117
+ }
118
+
119
+ #receiveMessage(attemptId?: string): void {
120
+ if (this.#dropped) {
121
+ return;
122
+ }
123
+ if (this.#isCacheFull()) {
124
+ this.#receiveMessageLater(RECEIVING_BACKOFF_DELAY_WHEN_CACHE_IS_FULL, attemptId);
125
+ return;
126
+ }
127
+ this.#receiveMessageImmediately(attemptId);
128
+ }
129
+
130
+ #receiveMessageImmediately(attemptId?: string): void {
131
+ if (this.#aborted) return;
132
+ attemptId = attemptId ?? this.#generateAttemptId();
133
+ try {
134
+ const batchSize = this.#getReceptionBatchSize();
135
+ const longPollingTimeout = this.#consumer.getPushConsumerSettings().getLongPollingTimeout();
136
+ const request = this.#consumer.wrapPushReceiveMessageRequest(
137
+ batchSize, this.#mq, this.#filterExpression, longPollingTimeout, attemptId,
138
+ );
139
+ this.#activityTime = Date.now();
140
+
141
+ (this.#consumer as any).logger?.debug?.('Start to receive message, mq=%s@%s@%d, batchSize=%d, attemptId=%s',
142
+ this.#mq.topic.name, this.#mq.broker.name, this.#mq.queueId, batchSize, attemptId);
143
+
144
+ this.#consumer.receiveMessage(request, this.#mq, longPollingTimeout)
145
+ .then(messages => {
146
+ if (messages.length > 0) {
147
+ (this.#consumer as any).logger?.debug?.('Received messages, count=%d, mq=%s@%s@%d',
148
+ messages.length, this.#mq.topic.name, this.#mq.broker.name, this.#mq.queueId);
149
+ }
150
+ this.#onReceiveMessageResult(messages);
151
+ })
152
+ .catch(err => {
153
+ (this.#consumer as any).logger?.error('Failed to receive message, mq=%s@%s@%d, error=%s',
154
+ this.#mq.topic.name, this.#mq.broker.name, this.#mq.queueId, err);
155
+ this.onReceiveMessageException(err, attemptId);
156
+ });
157
+ } catch (err) {
158
+ (this.#consumer as any).logger?.error('Exception in receiveMessage, mq=%s@%s@%d, error=%s',
159
+ this.#mq.topic.name, this.#mq.broker.name, this.#mq.queueId, err);
160
+ this.onReceiveMessageException(err as Error, attemptId);
161
+ }
162
+ }
163
+
164
+ #onReceiveMessageResult(messages: MessageView[]): void {
165
+ if (messages.length > 0) {
166
+ this.cacheMessages(messages);
167
+ this.#consumer.getConsumeService().consume(this, messages);
168
+ }
169
+ this.#receiveMessage();
170
+ }
171
+
172
+ #isCacheFull(): boolean {
173
+ const cacheMessageCountThreshold = this.#consumer.cacheMessageCountThresholdPerQueue();
174
+ const actualCount = this.cachedMessagesCount();
175
+ if (cacheMessageCountThreshold <= actualCount) {
176
+ this.#cacheFullTime = Date.now();
177
+ return true;
178
+ }
179
+
180
+ const cacheMessageBytesThreshold = this.#consumer.cacheMessageBytesThresholdPerQueue();
181
+ if (cacheMessageBytesThreshold <= this.#cachedMessagesBytes) {
182
+ this.#cacheFullTime = Date.now();
183
+ return true;
184
+ }
185
+
186
+ return false;
187
+ }
188
+
189
+ eraseMessage(messageView: MessageView, consumeResult: ConsumeResult): void {
190
+ const task = consumeResult === ConsumeResult.SUCCESS
191
+ ? this.#ackMessage(messageView)
192
+ : this.#nackMessage(messageView);
193
+ task.finally(() => {
194
+ this.#evictCache(messageView);
195
+ });
196
+ }
197
+
198
+ async #ackMessage(messageView: MessageView, attempt = 1): Promise<void> {
199
+ try {
200
+ const endpoints = messageView.endpoints;
201
+ const response = await this.#consumer.ackMessageViaRpc(
202
+ endpoints,
203
+ this.#consumer.wrapAckMessageRequest(messageView),
204
+ this.#consumer.requestTimeoutValue,
205
+ );
206
+ const status = response.getStatus()?.toObject();
207
+ if (status?.code === Code.INVALID_RECEIPT_HANDLE) {
208
+ return; // Forgive to retry
209
+ }
210
+ if (status?.code !== Code.OK) {
211
+ await this.#ackMessageLater(messageView, attempt + 1);
212
+ }
213
+ } catch {
214
+ await this.#ackMessageLater(messageView, attempt + 1);
215
+ }
216
+ }
217
+
218
+ async #ackMessageLater(messageView: MessageView, attempt: number): Promise<void> {
219
+ if (this.#aborted) return;
220
+ await new Promise<void>(resolve => setTimeout(resolve, ACK_MESSAGE_FAILURE_BACKOFF_DELAY));
221
+ if (this.#aborted) return;
222
+ await this.#ackMessage(messageView, attempt);
223
+ }
224
+
225
+ async #nackMessage(messageView: MessageView): Promise<void> {
226
+ const retryPolicy = this.#consumer.getRetryPolicy();
227
+ const delay = retryPolicy?.getNextAttemptDelay(messageView.deliveryAttempt ?? 1) ?? 0;
228
+ await this.#changeInvisibleDuration(messageView, delay);
229
+ }
230
+
231
+ async #changeInvisibleDuration(messageView: MessageView, duration: number, attempt = 1): Promise<void> {
232
+ try {
233
+ const endpoints = messageView.endpoints;
234
+ const response = await this.#consumer.changeInvisibleDurationViaRpc(
235
+ endpoints,
236
+ this.#consumer.wrapChangeInvisibleDurationRequest(messageView, duration),
237
+ this.#consumer.requestTimeoutValue,
238
+ );
239
+ const status = response.getStatus()?.toObject();
240
+ if (status?.code === Code.INVALID_RECEIPT_HANDLE) {
241
+ return; // Forgive to retry
242
+ }
243
+ if (status?.code !== Code.OK) {
244
+ await this.#changeInvisibleDurationLater(messageView, duration, attempt + 1);
245
+ }
246
+ } catch {
247
+ await this.#changeInvisibleDurationLater(messageView, duration, attempt + 1);
248
+ }
249
+ }
250
+
251
+ async #changeInvisibleDurationLater(messageView: MessageView, duration: number, attempt: number): Promise<void> {
252
+ if (this.#aborted) return;
253
+ await new Promise<void>(resolve => setTimeout(resolve, CHANGE_INVISIBLE_DURATION_FAILURE_BACKOFF_DELAY));
254
+ if (this.#aborted) return;
255
+ await this.#changeInvisibleDuration(messageView, duration, attempt);
256
+ }
257
+
258
+ async eraseFifoMessage(messageView: MessageView, consumeResult: ConsumeResult): Promise<void> {
259
+ const retryPolicy = this.#consumer.getRetryPolicy();
260
+ const maxAttempts = retryPolicy?.getMaxAttempts() ?? 1;
261
+ const attempt = messageView.deliveryAttempt ?? 1;
262
+
263
+ if (consumeResult === ConsumeResult.FAILURE && attempt < maxAttempts) {
264
+ const nextAttemptDelay = retryPolicy?.getNextAttemptDelay(attempt) ?? 0;
265
+ // Redeliver the fifo message
266
+ const result = await this.#consumer.getConsumeService().consumeMessage(messageView, nextAttemptDelay);
267
+ await this.eraseFifoMessage(messageView, result);
268
+ } else {
269
+ const task = consumeResult === ConsumeResult.SUCCESS
270
+ ? this.#ackMessage(messageView)
271
+ : this.#forwardToDeadLetterQueue(messageView);
272
+ await task;
273
+ this.#evictCache(messageView);
274
+ }
275
+ }
276
+
277
+ async #forwardToDeadLetterQueue(messageView: MessageView, attempt = 1): Promise<void> {
278
+ try {
279
+ const endpoints = messageView.endpoints;
280
+ const response = await this.#consumer.forwardMessageToDeadLetterQueueViaRpc(
281
+ endpoints,
282
+ this.#consumer.wrapForwardMessageToDeadLetterQueueRequest(messageView),
283
+ this.#consumer.requestTimeoutValue,
284
+ );
285
+ const status = response.getStatus();
286
+ if (!status) {
287
+ throw new Error('Missing status in forward to dead letter queue response');
288
+ }
289
+ const statusObj = status.toObject();
290
+ if (statusObj.code !== Code.OK) {
291
+ await this.#forwardToDeadLetterQueueLater(messageView, attempt + 1);
292
+ }
293
+ } catch (err) {
294
+ if ((err as Error).message === 'Missing status in forward to dead letter queue response') {
295
+ throw err; // Re-throw critical error
296
+ }
297
+ await this.#forwardToDeadLetterQueueLater(messageView, attempt + 1);
298
+ }
299
+ }
300
+
301
+ async #forwardToDeadLetterQueueLater(messageView: MessageView, attempt: number): Promise<void> {
302
+ if (this.#aborted) return;
303
+ await new Promise<void>(resolve => setTimeout(resolve, FORWARD_MESSAGE_TO_DLQ_FAILURE_BACKOFF_DELAY));
304
+ if (this.#aborted) return;
305
+ await this.#forwardToDeadLetterQueue(messageView, attempt);
306
+ }
307
+
308
+ discardMessage(messageView: MessageView): void {
309
+ this.#nackMessage(messageView).finally(() => {
310
+ this.#evictCache(messageView);
311
+ });
312
+ }
313
+
314
+ discardFifoMessage(messageView: MessageView): void {
315
+ this.#forwardToDeadLetterQueue(messageView).finally(() => {
316
+ this.#evictCache(messageView);
317
+ });
318
+ }
319
+
320
+ #evictCache(messageView: MessageView): void {
321
+ const index = this.#cachedMessages.indexOf(messageView);
322
+ if (index !== -1) {
323
+ this.#cachedMessages.splice(index, 1);
324
+ this.#cachedMessagesBytes -= messageView.body.length;
325
+ }
326
+ }
327
+
328
+ cachedMessagesCount(): number {
329
+ return this.#cachedMessages.length;
330
+ }
331
+
332
+ cachedMessageBytes(): number {
333
+ return this.#cachedMessagesBytes;
334
+ }
335
+
336
+ abort(): void {
337
+ this.#aborted = true;
338
+ }
339
+ }