rocketmq-client-nodejs 1.0.8 → 1.1.0

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 (159) hide show
  1. package/README.md +61 -0
  2. package/dist/client/BaseClient.d.ts +36 -1
  3. package/dist/client/BaseClient.js +176 -12
  4. package/dist/client/RpcClient.js +14 -2
  5. package/dist/client/RpcClientManager.d.ts +5 -0
  6. package/dist/client/RpcClientManager.js +25 -8
  7. package/dist/client/TelemetrySession.js +45 -10
  8. package/dist/consumer/ConsumeService.d.ts +2 -1
  9. package/dist/consumer/ConsumeService.js +7 -3
  10. package/dist/consumer/ConsumeTask.d.ts +6 -1
  11. package/dist/consumer/ConsumeTask.js +36 -5
  12. package/dist/consumer/Consumer.d.ts +13 -5
  13. package/dist/consumer/Consumer.js +85 -24
  14. package/dist/consumer/FifoConsumeService.d.ts +2 -1
  15. package/dist/consumer/FifoConsumeService.js +3 -3
  16. package/dist/consumer/LiteFifoConsumeService.d.ts +2 -1
  17. package/dist/consumer/LiteFifoConsumeService.js +3 -3
  18. package/dist/consumer/LitePushConsumerImpl.d.ts +12 -1
  19. package/dist/consumer/LitePushConsumerImpl.js +19 -4
  20. package/dist/consumer/LiteSimpleConsumer.d.ts +177 -0
  21. package/dist/consumer/LiteSimpleConsumer.js +126 -0
  22. package/dist/consumer/LiteSimpleConsumerImpl.d.ts +133 -0
  23. package/dist/consumer/LiteSimpleConsumerImpl.js +187 -0
  24. package/dist/consumer/LiteStandardConsumeService.d.ts +2 -1
  25. package/dist/consumer/LiteStandardConsumeService.js +3 -3
  26. package/dist/consumer/LiteSubscriptionManager.d.ts +27 -6
  27. package/dist/consumer/LiteSubscriptionManager.js +32 -24
  28. package/dist/consumer/ProcessQueue.d.ts +10 -0
  29. package/dist/consumer/ProcessQueue.js +43 -5
  30. package/dist/consumer/PushConsumer.d.ts +17 -0
  31. package/dist/consumer/PushConsumer.js +43 -4
  32. package/dist/consumer/PushConsumerGaugeObserver.d.ts +33 -0
  33. package/dist/consumer/PushConsumerGaugeObserver.js +60 -0
  34. package/dist/consumer/PushSubscriptionSettings.d.ts +8 -1
  35. package/dist/consumer/PushSubscriptionSettings.js +33 -6
  36. package/dist/consumer/SimpleConsumer.js +10 -1
  37. package/dist/consumer/StandardConsumeService.d.ts +2 -1
  38. package/dist/consumer/StandardConsumeService.js +3 -3
  39. package/dist/consumer/index.d.ts +1 -0
  40. package/dist/consumer/index.js +2 -1
  41. package/dist/exception/PayloadEmptyException.d.ts +20 -0
  42. package/dist/exception/PayloadEmptyException.js +28 -0
  43. package/dist/exception/StatusChecker.js +8 -1
  44. package/dist/exception/index.d.ts +1 -0
  45. package/dist/exception/index.js +2 -1
  46. package/dist/hook/Attribute.d.ts +26 -0
  47. package/dist/hook/Attribute.js +37 -0
  48. package/dist/hook/AttributeKey.d.ts +32 -0
  49. package/dist/hook/AttributeKey.js +43 -0
  50. package/dist/hook/CompositedMessageInterceptor.d.ts +31 -0
  51. package/dist/hook/CompositedMessageInterceptor.js +84 -0
  52. package/dist/hook/InflightRequestCountInterceptor.d.ts +28 -0
  53. package/dist/hook/InflightRequestCountInterceptor.js +44 -0
  54. package/dist/hook/MessageHookPoints.d.ts +54 -0
  55. package/dist/hook/MessageHookPoints.js +59 -0
  56. package/dist/hook/MessageHookPointsStatus.d.ts +24 -0
  57. package/dist/hook/MessageHookPointsStatus.js +29 -0
  58. package/dist/hook/MessageInterceptor.d.ts +34 -0
  59. package/dist/hook/MessageInterceptor.js +19 -0
  60. package/dist/hook/MessageInterceptorContext.d.ts +31 -0
  61. package/dist/hook/MessageInterceptorContext.js +19 -0
  62. package/dist/hook/MessageInterceptorContextImpl.d.ts +39 -0
  63. package/dist/hook/MessageInterceptorContextImpl.js +57 -0
  64. package/dist/hook/MessageMeterInterceptor.d.ts +39 -0
  65. package/dist/hook/MessageMeterInterceptor.js +149 -0
  66. package/dist/hook/index.d.ts +26 -0
  67. package/dist/hook/index.js +43 -0
  68. package/dist/index.d.ts +1 -0
  69. package/dist/index.js +2 -1
  70. package/dist/metrics/ClientMeter.d.ts +42 -0
  71. package/dist/metrics/ClientMeter.js +75 -0
  72. package/dist/metrics/ClientMeterManager.d.ts +42 -0
  73. package/dist/metrics/ClientMeterManager.js +127 -0
  74. package/dist/metrics/EmptyGaugeObserver.d.ts +28 -0
  75. package/dist/metrics/EmptyGaugeObserver.js +34 -0
  76. package/dist/metrics/GaugeEnum.d.ts +32 -0
  77. package/dist/metrics/GaugeEnum.js +37 -0
  78. package/dist/metrics/GaugeObserver.d.ts +29 -0
  79. package/dist/metrics/GaugeObserver.js +19 -0
  80. package/dist/metrics/HistogramEnum.d.ts +54 -0
  81. package/dist/metrics/HistogramEnum.js +71 -0
  82. package/dist/metrics/InvocationStatus.d.ts +26 -0
  83. package/dist/metrics/InvocationStatus.js +33 -0
  84. package/dist/metrics/Metric.d.ts +30 -0
  85. package/dist/metrics/Metric.js +44 -0
  86. package/dist/metrics/MetricLabels.d.ts +27 -0
  87. package/dist/metrics/MetricLabels.js +34 -0
  88. package/dist/metrics/index.d.ts +25 -0
  89. package/dist/metrics/index.js +42 -0
  90. package/dist/producer/Producer.js +33 -5
  91. package/dist/producer/PublishingLoadBalancer.js +9 -3
  92. package/dist/retry/CustomizedBackoffRetryPolicy.d.ts +37 -0
  93. package/dist/retry/CustomizedBackoffRetryPolicy.js +72 -0
  94. package/dist/retry/ExponentialBackoffRetryPolicy.js +10 -6
  95. package/dist/retry/RetryPolicy.d.ts +1 -1
  96. package/dist/retry/index.d.ts +1 -0
  97. package/dist/retry/index.js +2 -1
  98. package/dist/route/Endpoints.d.ts +6 -0
  99. package/dist/route/Endpoints.js +56 -4
  100. package/dist/route/IpNameResolver.d.ts +28 -0
  101. package/dist/route/IpNameResolver.js +104 -0
  102. package/dist/util/Semaphore.d.ts +47 -0
  103. package/dist/util/Semaphore.js +82 -0
  104. package/package.json +6 -2
  105. package/src/client/BaseClient.ts +202 -12
  106. package/src/client/RpcClient.ts +14 -1
  107. package/src/client/RpcClientManager.ts +27 -8
  108. package/src/client/TelemetrySession.ts +47 -9
  109. package/src/consumer/ConsumeService.ts +9 -2
  110. package/src/consumer/ConsumeTask.ts +43 -3
  111. package/src/consumer/Consumer.ts +103 -23
  112. package/src/consumer/FifoConsumeService.ts +4 -2
  113. package/src/consumer/LiteFifoConsumeService.ts +4 -2
  114. package/src/consumer/LitePushConsumerImpl.ts +21 -3
  115. package/src/consumer/LiteSimpleConsumer.ts +251 -0
  116. package/src/consumer/LiteSimpleConsumerImpl.ts +221 -0
  117. package/src/consumer/LiteStandardConsumeService.ts +4 -2
  118. package/src/consumer/LiteSubscriptionManager.ts +63 -36
  119. package/src/consumer/ProcessQueue.ts +44 -1
  120. package/src/consumer/PushConsumer.ts +54 -2
  121. package/src/consumer/PushConsumerGaugeObserver.ts +60 -0
  122. package/src/consumer/PushSubscriptionSettings.ts +38 -7
  123. package/src/consumer/SimpleConsumer.ts +9 -0
  124. package/src/consumer/StandardConsumeService.ts +4 -2
  125. package/src/consumer/index.ts +1 -0
  126. package/src/exception/PayloadEmptyException.ts +25 -0
  127. package/src/exception/StatusChecker.ts +7 -0
  128. package/src/exception/index.ts +1 -0
  129. package/src/hook/Attribute.ts +36 -0
  130. package/src/hook/AttributeKey.ts +42 -0
  131. package/src/hook/CompositedMessageInterceptor.ts +92 -0
  132. package/src/hook/InflightRequestCountInterceptor.ts +46 -0
  133. package/src/hook/MessageHookPoints.ts +55 -0
  134. package/src/hook/MessageHookPointsStatus.ts +25 -0
  135. package/src/hook/MessageInterceptor.ts +35 -0
  136. package/src/hook/MessageInterceptorContext.ts +33 -0
  137. package/src/hook/MessageInterceptorContextImpl.ts +68 -0
  138. package/src/hook/MessageMeterInterceptor.ts +162 -0
  139. package/src/hook/index.ts +27 -0
  140. package/src/index.ts +1 -0
  141. package/src/metrics/ClientMeter.ts +81 -0
  142. package/src/metrics/ClientMeterManager.ts +145 -0
  143. package/src/metrics/EmptyGaugeObserver.ts +36 -0
  144. package/src/metrics/GaugeEnum.ts +33 -0
  145. package/src/metrics/GaugeObserver.ts +32 -0
  146. package/src/metrics/HistogramEnum.ts +69 -0
  147. package/src/metrics/InvocationStatus.ts +28 -0
  148. package/src/metrics/Metric.ts +42 -0
  149. package/src/metrics/MetricLabels.ts +31 -0
  150. package/src/metrics/index.ts +26 -0
  151. package/src/producer/Producer.ts +37 -6
  152. package/src/producer/PublishingLoadBalancer.ts +8 -2
  153. package/src/retry/CustomizedBackoffRetryPolicy.ts +81 -0
  154. package/src/retry/ExponentialBackoffRetryPolicy.ts +11 -6
  155. package/src/retry/RetryPolicy.ts +1 -1
  156. package/src/retry/index.ts +1 -0
  157. package/src/route/Endpoints.ts +52 -3
  158. package/src/route/IpNameResolver.ts +119 -0
  159. package/src/util/Semaphore.ts +82 -0
@@ -0,0 +1,221 @@
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 { ClientType, Permission, Settings as SettingsPB } from '../../proto/apache/rocketmq/v2/definition_pb';
19
+ import { NotifyUnsubscribeLiteCommand } from '../../proto/apache/rocketmq/v2/service_pb';
20
+ import { Endpoints, TopicRouteData } from '../route';
21
+ import { Resource } from '../route/Resource';
22
+ import { MASTER_BROKER_ID } from '../util';
23
+ import { ILogger } from '../client/Logger';
24
+ import { RpcClientManager } from '../client/RpcClientManager';
25
+ import { SimpleConsumer, SimpleConsumerOptions } from './SimpleConsumer';
26
+ import { FilterExpression } from './FilterExpression';
27
+ import { LiteSubscriptionManager, LiteSubscriptionHost } from './LiteSubscriptionManager';
28
+ import { OffsetOption } from './OffsetOption';
29
+ import { LiteSimpleConsumer, LiteSimpleConsumerOptions } from './LiteSimpleConsumer';
30
+
31
+ /**
32
+ * Keep only the first readable master queue of the route. Lite consumers talk
33
+ * to brokers only through the bound parent topic, so a single queue is enough
34
+ * and it avoids useless route bookkeeping for the other queues.
35
+ */
36
+ export function firstReadableMasterQueue(topicRouteData: TopicRouteData): TopicRouteData {
37
+ const readable = topicRouteData.messageQueues.find(
38
+ mq => mq.broker.id === MASTER_BROKER_ID &&
39
+ (mq.permission === Permission.READ || mq.permission === Permission.READ_WRITE),
40
+ );
41
+ return new TopicRouteData(readable ? [ readable.toProtobuf() ] : []);
42
+ }
43
+
44
+ /**
45
+ * Implementation of LiteSimpleConsumer.
46
+ *
47
+ * <p>LiteSimpleConsumer extends SimpleConsumer to provide explicit receive/ack
48
+ * control over lite topics. It binds to a single parent topic and manages lite
49
+ * topic subscriptions dynamically via the lite subscription sync protocol.</p>
50
+ */
51
+ export class LiteSimpleConsumerImpl extends SimpleConsumer
52
+ implements LiteSimpleConsumer, LiteSubscriptionHost {
53
+ readonly #bindTopic: Resource;
54
+ readonly #liteSubscriptionManager: LiteSubscriptionManager;
55
+
56
+ constructor(options: LiteSimpleConsumerOptions) {
57
+ if (!options.bindTopic || options.bindTopic.trim().length === 0) {
58
+ throw new TypeError('bindTopic should not be blank');
59
+ }
60
+ // Default subscription: (bindTopic, *) for code reuse.
61
+ const subscriptions = new Map<string, FilterExpression | string>()
62
+ .set(options.bindTopic, FilterExpression.SUB_ALL);
63
+
64
+ super({
65
+ ...options,
66
+ subscriptions,
67
+ } as SimpleConsumerOptions);
68
+
69
+ this.#bindTopic = new Resource(options.namespace, options.bindTopic);
70
+ const groupResource = new Resource(options.namespace, options.consumerGroup);
71
+ this.#liteSubscriptionManager = new LiteSubscriptionManager(this, this.#bindTopic, groupResource);
72
+ }
73
+
74
+ /**
75
+ * Get the client type.
76
+ *
77
+ * @return The client type identifier for lite simple consumer
78
+ */
79
+ protected getClientType(): ClientType {
80
+ return ClientType.LITE_SIMPLE_CONSUMER;
81
+ }
82
+
83
+ protected onTopicRouteDataUpdate(topic: string, topicRouteData: TopicRouteData) {
84
+ super.onTopicRouteDataUpdate(topic, firstReadableMasterQueue(topicRouteData));
85
+ }
86
+
87
+ /**
88
+ * Start up the consumer.
89
+ *
90
+ * <p>This method initializes the consumer and starts the lite subscription
91
+ * manager. It must be called before the consumer can receive messages.</p>
92
+ */
93
+ async startup() {
94
+ await super.startup();
95
+ this.#liteSubscriptionManager.startUp();
96
+ }
97
+
98
+ /**
99
+ * Shutdown the consumer.
100
+ *
101
+ * <p>This method gracefully shuts down the consumer, releasing all resources
102
+ * and stopping the lite subscription manager.</p>
103
+ */
104
+ async shutdown() {
105
+ this.#liteSubscriptionManager.shutdown();
106
+ await super.shutdown();
107
+ }
108
+
109
+ async subscribeLite(liteTopic: string): Promise<void>;
110
+
111
+ /**
112
+ * Subscribe to a lite topic with an offset option to specify the consume
113
+ * from offset.
114
+ *
115
+ * @param liteTopic - The name of the lite topic to subscribe
116
+ * @param offsetOption - The consume from offset option
117
+ */
118
+ async subscribeLite(liteTopic: string, offsetOption: OffsetOption): Promise<void>;
119
+
120
+ async subscribeLite(liteTopic: string, offsetOption?: OffsetOption): Promise<void> {
121
+ if (!liteTopic || liteTopic.trim().length === 0) {
122
+ throw new Error('liteTopic should not be blank');
123
+ }
124
+ await this.#liteSubscriptionManager.subscribeLite(liteTopic, offsetOption ?? null);
125
+ }
126
+
127
+ /**
128
+ * Unsubscribe from a lite topic.
129
+ *
130
+ * @param liteTopic - The name of the lite topic to unsubscribe from
131
+ */
132
+ async unsubscribeLite(liteTopic: string): Promise<void> {
133
+ if (!liteTopic || liteTopic.trim().length === 0) {
134
+ throw new Error('liteTopic should not be blank');
135
+ }
136
+ await this.#liteSubscriptionManager.unsubscribeLite(liteTopic);
137
+ }
138
+
139
+ /**
140
+ * Get the lite topic set.
141
+ *
142
+ * @return Set of currently subscribed lite topic names
143
+ */
144
+ getLiteTopicSet(): Set<string> {
145
+ return this.#liteSubscriptionManager.getLiteTopicSet();
146
+ }
147
+
148
+ /**
149
+ * Get the load balancing group for the consumer.
150
+ *
151
+ * @return Consumer group name
152
+ */
153
+ getConsumerGroup(): string {
154
+ return this.#liteSubscriptionManager.getConsumerGroupName();
155
+ }
156
+
157
+ /**
158
+ * Handle notify unsubscribe lite command from server.
159
+ *
160
+ * @param _endpoints - The server endpoints
161
+ * @param command - The unsubscribe command from the server
162
+ */
163
+ onNotifyUnsubscribeLiteCommand(_endpoints: Endpoints, command: NotifyUnsubscribeLiteCommand) {
164
+ this.#liteSubscriptionManager.onNotifyUnsubscribeLiteCommand(command);
165
+ }
166
+
167
+ /**
168
+ * Handle settings command from server.
169
+ *
170
+ * @param endpoints - The server endpoints
171
+ * @param settings - The settings configuration
172
+ */
173
+ onSettingsCommand(endpoints: Endpoints, settings: SettingsPB) {
174
+ super.onSettingsCommand(endpoints, settings);
175
+ this.#liteSubscriptionManager.sync(settings);
176
+ }
177
+
178
+ /**
179
+ * Close the consumer.
180
+ */
181
+ async close(): Promise<void> {
182
+ await this.shutdown();
183
+ }
184
+
185
+ /**
186
+ * Get the logger.
187
+ *
188
+ * @internal
189
+ */
190
+ getLogger(): ILogger {
191
+ return this.logger;
192
+ }
193
+
194
+ /**
195
+ * Get the RPC client manager (protected access for internal use).
196
+ *
197
+ * @internal
198
+ */
199
+ getRpcClientManager(): RpcClientManager {
200
+ return this.rpcClientManager;
201
+ }
202
+
203
+ /**
204
+ * Get the request timeout (protected access for internal use).
205
+ *
206
+ * @internal
207
+ */
208
+ getRequestTimeout(): number {
209
+ return this.requestTimeout;
210
+ }
211
+
212
+ /**
213
+ * Endpoints the lite subscription manager should sync to: every endpoint
214
+ * present in the consumed routes.
215
+ *
216
+ * @internal
217
+ */
218
+ getSyncEndpoints(): Endpoints[] {
219
+ return this.getTotalRouteEndpoints();
220
+ }
221
+ }
@@ -16,6 +16,7 @@
16
16
  */
17
17
 
18
18
  import { MessageView } from '../message';
19
+ import { MessageInterceptor } from '../hook';
19
20
  import { ConsumeService } from './ConsumeService';
20
21
  import { MessageListener } from './MessageListener';
21
22
  import type { ProcessQueue } from './ProcessQueue';
@@ -31,8 +32,9 @@ import { ILogger, getDefaultLogger } from '../client/Logger';
31
32
  export class LiteStandardConsumeService extends ConsumeService {
32
33
  readonly #logger: ILogger;
33
34
 
34
- constructor(clientId: string, messageListener: MessageListener) {
35
- super(clientId, messageListener);
35
+ constructor(clientId: string, messageListener: MessageListener,
36
+ messageInterceptor?: MessageInterceptor, consumerGroup?: string) {
37
+ super(clientId, messageListener, messageInterceptor, consumerGroup);
36
38
  this.#logger = getDefaultLogger();
37
39
  }
38
40
 
@@ -21,15 +21,37 @@ import {
21
21
  SyncLiteSubscriptionRequest,
22
22
  SyncLiteSubscriptionResponse,
23
23
  } from '../../proto/apache/rocketmq/v2/service_pb';
24
+ import { Endpoints } from '../route';
25
+ import { ILogger } from '../client/Logger';
26
+ import { RpcClientManager } from '../client/RpcClientManager';
24
27
  import { ClientException } from '../exception';
25
- import { Resource } from '../route';
26
- import { LitePushConsumerImpl } from './LitePushConsumerImpl';
28
+ import { Resource } from '../route/Resource';
27
29
  import { OffsetOption } from './OffsetOption';
28
30
 
29
31
  const SYNC_LITE_SUBSCRIPTION_INTERVAL = 30000; // 30 seconds
30
32
 
31
33
  /**
32
- * Manages lite topic subscriptions for LitePushConsumer.
34
+ * Minimal host contract required by LiteSubscriptionManager.
35
+ *
36
+ * Implemented by LitePushConsumerImpl and LiteSimpleConsumerImpl so the same
37
+ * manager can keep lite subscriptions in sync for both consumer flavors.
38
+ */
39
+ export interface LiteSubscriptionHost {
40
+ clientId: string;
41
+ isRunning(): boolean;
42
+ getLogger(): ILogger;
43
+ getRpcClientManager(): RpcClientManager;
44
+ getRequestTimeout(): number;
45
+ /**
46
+ * Endpoints the lite subscription should be synced to. Lite subscriptions
47
+ * must reach every route endpoint, not only the endpoint the client was
48
+ * configured with.
49
+ */
50
+ getSyncEndpoints(): Endpoints[];
51
+ }
52
+
53
+ /**
54
+ * Manages lite topic subscriptions for lite consumers.
33
55
  *
34
56
  * <p>LiteSubscriptionManager handles:
35
57
  * - Maintaining the set of subscribed lite topics
@@ -38,7 +60,7 @@ const SYNC_LITE_SUBSCRIPTION_INTERVAL = 30000; // 30 seconds
38
60
  * - Handling unsubscribe commands from server</p>
39
61
  */
40
62
  export class LiteSubscriptionManager {
41
- private readonly consumerImpl: LitePushConsumerImpl;
63
+ private readonly host: LiteSubscriptionHost;
42
64
  private readonly bindTopic: Resource;
43
65
  private readonly group: Resource;
44
66
  private readonly liteTopicSet = new Set<string>();
@@ -47,11 +69,11 @@ export class LiteSubscriptionManager {
47
69
  private syncTimer?: NodeJS.Timeout;
48
70
 
49
71
  constructor(
50
- consumerImpl: LitePushConsumerImpl,
72
+ host: LiteSubscriptionHost,
51
73
  bindTopic: Resource,
52
74
  group: Resource,
53
75
  ) {
54
- this.consumerImpl = consumerImpl;
76
+ this.host = host;
55
77
  this.bindTopic = bindTopic;
56
78
  this.group = group;
57
79
  this.liteSubscriptionQuota = 100; // Default quota
@@ -129,7 +151,7 @@ export class LiteSubscriptionManager {
129
151
  offsetOption?: OffsetOption | null,
130
152
  ): Promise<void> {
131
153
  // Check if consumer is running
132
- if (!this.consumerImpl.isRunning()) {
154
+ if (!this.host.isRunning()) {
133
155
  throw new ClientException(500, 'Consumer is not running');
134
156
  }
135
157
 
@@ -152,15 +174,15 @@ export class LiteSubscriptionManager {
152
174
  );
153
175
 
154
176
  this.liteTopicSet.add(liteTopic);
155
- this.consumerImpl.getLogger().info(
177
+ this.host.getLogger().info(
156
178
  'SubscribeLite %s, topic=%s, group=%s, clientId=%s',
157
179
  liteTopic,
158
180
  this.getBindTopicName(),
159
181
  this.getConsumerGroupName(),
160
- this.consumerImpl.clientId,
182
+ this.host.clientId,
161
183
  );
162
184
  } catch (error) {
163
- this.consumerImpl.getLogger().error(
185
+ this.host.getLogger().error(
164
186
  'Failed to subscribeLite %s, error=%s',
165
187
  liteTopic,
166
188
  error,
@@ -174,7 +196,7 @@ export class LiteSubscriptionManager {
174
196
  */
175
197
  public async unsubscribeLite(liteTopic: string): Promise<void> {
176
198
  // Check if consumer is running
177
- if (!this.consumerImpl.isRunning()) {
199
+ if (!this.host.isRunning()) {
178
200
  throw new ClientException(500, 'Consumer is not running');
179
201
  }
180
202
 
@@ -191,15 +213,15 @@ export class LiteSubscriptionManager {
191
213
  );
192
214
 
193
215
  this.liteTopicSet.delete(liteTopic);
194
- this.consumerImpl.getLogger().info(
216
+ this.host.getLogger().info(
195
217
  'UnsubscribeLite %s, topic=%s, group=%s, clientId=%s',
196
218
  liteTopic,
197
219
  this.getBindTopicName(),
198
220
  this.getConsumerGroupName(),
199
- this.consumerImpl.clientId,
221
+ this.host.clientId,
200
222
  );
201
223
  } catch (error) {
202
- this.consumerImpl.getLogger().error(
224
+ this.host.getLogger().error(
203
225
  'Failed to unsubscribeLite %s, error=%s',
204
226
  liteTopic,
205
227
  error,
@@ -220,23 +242,23 @@ export class LiteSubscriptionManager {
220
242
  null,
221
243
  );
222
244
  } catch (error) {
223
- this.consumerImpl.getLogger().error(
245
+ this.host.getLogger().error(
224
246
  'Schedule syncAllLiteSubscription error, clientId=%s, error=%s',
225
- this.consumerImpl.clientId,
247
+ this.host.clientId,
226
248
  error,
227
249
  );
228
250
  }
229
251
  }
230
252
 
231
253
  /**
232
- * Sync lite subscription with server.
254
+ * Sync lite subscription with every route endpoint.
233
255
  */
234
256
  private async syncLiteSubscription(
235
257
  action: LiteSubscriptionAction,
236
258
  liteTopics: string[],
237
259
  offsetOption: OffsetOption | null,
238
260
  ): Promise<void> {
239
- const logger = this.consumerImpl.getLogger();
261
+ const logger = this.host.getLogger();
240
262
  if (logger.debug) {
241
263
  logger.debug(
242
264
  'SyncLiteSubscription: action=%s, liteTopics=[%s], offsetOption=%s',
@@ -258,29 +280,34 @@ export class LiteSubscriptionManager {
258
280
  request.setOffsetOption(offsetOption.toProtobuf());
259
281
  }
260
282
 
261
- try {
262
- // Call RPC client using public methods from LitePushConsumerImpl
263
- const response: SyncLiteSubscriptionResponse = await this.consumerImpl.getRpcClientManager().syncLiteSubscription(
264
- this.consumerImpl.getEndpoints(),
265
- request,
266
- this.consumerImpl.getRequestTimeout(),
267
- );
283
+ const endpointsList = this.host.getSyncEndpoints();
284
+ if (endpointsList.length === 0) {
285
+ throw new ClientException(500, 'No endpoints available to sync lite subscription');
286
+ }
268
287
 
269
- // Handle response status
270
- const status = response.getStatus();
271
- if (status && status.getCode() !== Code.OK) {
272
- throw new ClientException(
273
- status.getCode(),
274
- `Failed to sync lite subscription: ${status.getMessage()}`,
275
- );
276
- }
288
+ try {
289
+ // The lite subscription must reach every route endpoint; the sync fails
290
+ // if any endpoint rejects it.
291
+ await Promise.all(endpointsList.map(async endpoints => {
292
+ const response: SyncLiteSubscriptionResponse = await this.host.getRpcClientManager()
293
+ .syncLiteSubscription(endpoints, request, this.host.getRequestTimeout());
294
+
295
+ // Handle response status
296
+ const status = response.getStatus();
297
+ if (status && status.getCode() !== Code.OK) {
298
+ throw new ClientException(
299
+ status.getCode(),
300
+ `Failed to sync lite subscription to endpoints=${endpoints.facade}: ${status.getMessage()}`,
301
+ );
302
+ }
303
+ }));
277
304
 
278
305
  if (logger.info) {
279
306
  logger.info(
280
307
  'SyncLiteSubscription success: action=%s, liteTopics=[%s], clientId=%s',
281
308
  LiteSubscriptionAction[action],
282
309
  liteTopics.join(', '),
283
- this.consumerImpl.clientId,
310
+ this.host.clientId,
284
311
  );
285
312
  }
286
313
  } catch (error) {
@@ -289,7 +316,7 @@ export class LiteSubscriptionManager {
289
316
  'SyncLiteSubscription failed: action=%s, liteTopics=[%s], clientId=%s, error=%s',
290
317
  LiteSubscriptionAction[action],
291
318
  liteTopics.join(', '),
292
- this.consumerImpl.clientId,
319
+ this.host.clientId,
293
320
  error,
294
321
  );
295
322
  }
@@ -302,7 +329,7 @@ export class LiteSubscriptionManager {
302
329
  */
303
330
  public onNotifyUnsubscribeLiteCommand(command: NotifyUnsubscribeLiteCommand) {
304
331
  const liteTopic = command.getLiteTopic();
305
- this.consumerImpl.getLogger().info(
332
+ this.host.getLogger().info(
306
333
  'Notify unsubscribe lite: liteTopic=%s, group=%s, bindTopic=%s',
307
334
  liteTopic,
308
335
  this.getConsumerGroupName(),
@@ -23,6 +23,7 @@ import { TooManyRequestsException } from '../exception';
23
23
  import { ConsumeResult, ConsumeResultSuspend } from './ConsumeResult';
24
24
  import { FilterExpression } from './FilterExpression';
25
25
  import type { PushConsumer } from './PushConsumer';
26
+ import { Semaphore } from '../util/Semaphore';
26
27
 
27
28
  const ACK_MESSAGE_FAILURE_BACKOFF_DELAY = 1000;
28
29
  const CHANGE_INVISIBLE_DURATION_FAILURE_BACKOFF_DELAY = 1000;
@@ -31,6 +32,7 @@ const FORWARD_MESSAGE_TO_DLQ_FAILURE_BACKOFF_DELAY = 1000;
31
32
  const RECEIVING_FLOW_CONTROL_BACKOFF_DELAY = 20;
32
33
  const RECEIVING_FAILURE_BACKOFF_DELAY = 1000;
33
34
  const RECEIVING_BACKOFF_DELAY_WHEN_CACHE_IS_FULL = 1000;
35
+ const RECEIVING_BACKOFF_DELAY_WHEN_PERMITS_EXHAUSTED = 20;
34
36
 
35
37
  export class ProcessQueue {
36
38
  readonly #consumer: PushConsumer;
@@ -42,17 +44,28 @@ export class ProcessQueue {
42
44
  #activityTime = Date.now();
43
45
  #cacheFullTime = 0;
44
46
  #aborted = false;
47
+ // Bounds in-flight messages per queue; mirrors Java ProcessQueueImpl permits.
48
+ readonly #semaphore: Semaphore;
45
49
 
46
50
  constructor(consumer: PushConsumer, mq: MessageQueue, filterExpression: FilterExpression) {
47
51
  this.#consumer = consumer;
48
52
  this.#mq = mq;
49
53
  this.#filterExpression = filterExpression;
54
+ this.#semaphore = new Semaphore(consumer.getPushConsumerSettings().getConsumeConcurrentlyMax());
50
55
  }
51
56
 
52
57
  getMessageQueue(): MessageQueue {
53
58
  return this.#mq;
54
59
  }
55
60
 
61
+ /**
62
+ * Topic of the underlying message queue, used as a metric attribute when
63
+ * aggregating the consumer gauges.
64
+ */
65
+ get topic(): string {
66
+ return this.#mq.topic.name;
67
+ }
68
+
56
69
  drop(): void {
57
70
  this.#dropped = true;
58
71
  }
@@ -77,17 +90,34 @@ export class ProcessQueue {
77
90
  return;
78
91
  }
79
92
  for (const messageView of messageList) {
93
+ // Each in-flight message consumes one permit. The reception batch size is
94
+ // already bounded by availablePermits, so tryAcquire should always succeed;
95
+ // if it does not (defensive), stop caching to avoid over-committing.
96
+ if (!this.#semaphore.tryAcquire()) {
97
+ break;
98
+ }
80
99
  this.#cachedMessages.push(messageView);
81
100
  this.#cachedMessagesBytes += messageView.body.length;
82
101
  }
83
102
  }
84
103
 
104
+ /**
105
+ * Number of consumption permits still available on this process queue. When it
106
+ * reaches zero the receive loop applies backpressure (see #receiveMessageImmediately).
107
+ */
108
+ availablePermits(): number {
109
+ return this.#semaphore.availablePermits;
110
+ }
111
+
85
112
  #getReceptionBatchSize(): number {
86
113
  const bufferSize = Math.max(
87
114
  this.#consumer.cacheMessageCountThresholdPerQueue() - this.cachedMessagesCount(),
88
115
  1,
89
116
  );
90
- return Math.min(bufferSize, this.#consumer.getPushConsumerSettings().getReceiveBatchSize());
117
+ // Bound the batch by the remaining consumption permits, mirroring Java's
118
+ // Math.max(consumeConcurrentlyMax - inflight, 1).
119
+ const permitSize = Math.max(this.#semaphore.availablePermits, 1);
120
+ return Math.min(bufferSize, permitSize, this.#consumer.getPushConsumerSettings().getReceiveBatchSize());
91
121
  }
92
122
 
93
123
  fetchMessageImmediately(): void {
@@ -132,6 +162,13 @@ export class ProcessQueue {
132
162
 
133
163
  #receiveMessageImmediately(attemptId?: string): void {
134
164
  if (this.#aborted) return;
165
+ // Apply backpressure: when every consumption permit is in use (i.e. the
166
+ // maximum number of messages is in-flight), stop fetching until messages are
167
+ // settled and permits are released. Mirrors Java's tryAcquirePermit gate.
168
+ if (this.#semaphore.availablePermits <= 0) {
169
+ this.#receiveMessageLater(RECEIVING_BACKOFF_DELAY_WHEN_PERMITS_EXHAUSTED, attemptId);
170
+ return;
171
+ }
135
172
  attemptId = attemptId ?? this.#generateAttemptId();
136
173
  try {
137
174
  const batchSize = this.#getReceptionBatchSize();
@@ -210,6 +247,7 @@ export class ProcessQueue {
210
247
  endpoints,
211
248
  this.#consumer.wrapAckMessageRequest(messageView),
212
249
  this.#consumer.requestTimeoutValue,
250
+ messageView,
213
251
  );
214
252
  const status = response.getStatus()?.toObject();
215
253
  if (status?.code === Code.INVALID_RECEIPT_HANDLE) {
@@ -247,6 +285,7 @@ export class ProcessQueue {
247
285
  endpoints,
248
286
  this.#consumer.wrapChangeInvisibleDurationRequest(messageView, duration),
249
287
  this.#consumer.requestTimeoutValue,
288
+ messageView,
250
289
  );
251
290
  const status = response.getStatus()?.toObject();
252
291
  if (status?.code === Code.INVALID_RECEIPT_HANDLE) {
@@ -326,6 +365,7 @@ export class ProcessQueue {
326
365
  endpoints,
327
366
  this.#consumer.wrapForwardMessageToDeadLetterQueueRequest(messageView),
328
367
  this.#consumer.requestTimeoutValue,
368
+ messageView,
329
369
  );
330
370
  const status = response.getStatus();
331
371
  if (!status) {
@@ -367,6 +407,9 @@ export class ProcessQueue {
367
407
  if (index !== -1) {
368
408
  this.#cachedMessages.splice(index, 1);
369
409
  this.#cachedMessagesBytes -= messageView.body.length;
410
+ // Return the consumption permit held by this now-settled message, so the
411
+ // receive loop can fetch again (backpressure release).
412
+ this.#semaphore.release();
370
413
  }
371
414
  }
372
415