rocketmq-client-nodejs 1.0.7 → 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 (164) 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/ConsumeResult.d.ts +2 -2
  9. package/dist/consumer/ConsumeResult.js +6 -3
  10. package/dist/consumer/ConsumeService.d.ts +2 -1
  11. package/dist/consumer/ConsumeService.js +7 -3
  12. package/dist/consumer/ConsumeTask.d.ts +6 -1
  13. package/dist/consumer/ConsumeTask.js +36 -5
  14. package/dist/consumer/Consumer.d.ts +13 -5
  15. package/dist/consumer/Consumer.js +85 -24
  16. package/dist/consumer/FifoConsumeService.d.ts +2 -1
  17. package/dist/consumer/FifoConsumeService.js +3 -3
  18. package/dist/consumer/LiteFifoConsumeService.d.ts +2 -1
  19. package/dist/consumer/LiteFifoConsumeService.js +3 -3
  20. package/dist/consumer/LitePushConsumerImpl.d.ts +12 -1
  21. package/dist/consumer/LitePushConsumerImpl.js +19 -4
  22. package/dist/consumer/LiteSimpleConsumer.d.ts +177 -0
  23. package/dist/consumer/LiteSimpleConsumer.js +126 -0
  24. package/dist/consumer/LiteSimpleConsumerImpl.d.ts +133 -0
  25. package/dist/consumer/LiteSimpleConsumerImpl.js +187 -0
  26. package/dist/consumer/LiteStandardConsumeService.d.ts +2 -1
  27. package/dist/consumer/LiteStandardConsumeService.js +3 -3
  28. package/dist/consumer/LiteSubscriptionManager.d.ts +27 -6
  29. package/dist/consumer/LiteSubscriptionManager.js +32 -24
  30. package/dist/consumer/ProcessQueue.d.ts +10 -0
  31. package/dist/consumer/ProcessQueue.js +47 -7
  32. package/dist/consumer/PushConsumer.d.ts +17 -0
  33. package/dist/consumer/PushConsumer.js +87 -7
  34. package/dist/consumer/PushConsumerGaugeObserver.d.ts +33 -0
  35. package/dist/consumer/PushConsumerGaugeObserver.js +60 -0
  36. package/dist/consumer/PushSubscriptionSettings.d.ts +8 -1
  37. package/dist/consumer/PushSubscriptionSettings.js +33 -6
  38. package/dist/consumer/SimpleConsumer.js +10 -1
  39. package/dist/consumer/StandardConsumeService.d.ts +2 -1
  40. package/dist/consumer/StandardConsumeService.js +3 -3
  41. package/dist/consumer/index.d.ts +1 -0
  42. package/dist/consumer/index.js +2 -1
  43. package/dist/exception/PayloadEmptyException.d.ts +20 -0
  44. package/dist/exception/PayloadEmptyException.js +28 -0
  45. package/dist/exception/StatusChecker.js +8 -1
  46. package/dist/exception/index.d.ts +1 -0
  47. package/dist/exception/index.js +2 -1
  48. package/dist/hook/Attribute.d.ts +26 -0
  49. package/dist/hook/Attribute.js +37 -0
  50. package/dist/hook/AttributeKey.d.ts +32 -0
  51. package/dist/hook/AttributeKey.js +43 -0
  52. package/dist/hook/CompositedMessageInterceptor.d.ts +31 -0
  53. package/dist/hook/CompositedMessageInterceptor.js +84 -0
  54. package/dist/hook/InflightRequestCountInterceptor.d.ts +28 -0
  55. package/dist/hook/InflightRequestCountInterceptor.js +44 -0
  56. package/dist/hook/MessageHookPoints.d.ts +54 -0
  57. package/dist/hook/MessageHookPoints.js +59 -0
  58. package/dist/hook/MessageHookPointsStatus.d.ts +24 -0
  59. package/dist/hook/MessageHookPointsStatus.js +29 -0
  60. package/dist/hook/MessageInterceptor.d.ts +34 -0
  61. package/dist/hook/MessageInterceptor.js +19 -0
  62. package/dist/hook/MessageInterceptorContext.d.ts +31 -0
  63. package/dist/hook/MessageInterceptorContext.js +19 -0
  64. package/dist/hook/MessageInterceptorContextImpl.d.ts +39 -0
  65. package/dist/hook/MessageInterceptorContextImpl.js +57 -0
  66. package/dist/hook/MessageMeterInterceptor.d.ts +39 -0
  67. package/dist/hook/MessageMeterInterceptor.js +149 -0
  68. package/dist/hook/index.d.ts +26 -0
  69. package/dist/hook/index.js +43 -0
  70. package/dist/index.d.ts +1 -0
  71. package/dist/index.js +2 -1
  72. package/dist/metrics/ClientMeter.d.ts +42 -0
  73. package/dist/metrics/ClientMeter.js +75 -0
  74. package/dist/metrics/ClientMeterManager.d.ts +42 -0
  75. package/dist/metrics/ClientMeterManager.js +127 -0
  76. package/dist/metrics/EmptyGaugeObserver.d.ts +28 -0
  77. package/dist/metrics/EmptyGaugeObserver.js +34 -0
  78. package/dist/metrics/GaugeEnum.d.ts +32 -0
  79. package/dist/metrics/GaugeEnum.js +37 -0
  80. package/dist/metrics/GaugeObserver.d.ts +29 -0
  81. package/dist/metrics/GaugeObserver.js +19 -0
  82. package/dist/metrics/HistogramEnum.d.ts +54 -0
  83. package/dist/metrics/HistogramEnum.js +71 -0
  84. package/dist/metrics/InvocationStatus.d.ts +26 -0
  85. package/dist/metrics/InvocationStatus.js +33 -0
  86. package/dist/metrics/Metric.d.ts +30 -0
  87. package/dist/metrics/Metric.js +44 -0
  88. package/dist/metrics/MetricLabels.d.ts +27 -0
  89. package/dist/metrics/MetricLabels.js +34 -0
  90. package/dist/metrics/index.d.ts +25 -0
  91. package/dist/metrics/index.js +42 -0
  92. package/dist/producer/Producer.js +33 -5
  93. package/dist/producer/PublishingLoadBalancer.js +9 -3
  94. package/dist/retry/CustomizedBackoffRetryPolicy.d.ts +37 -0
  95. package/dist/retry/CustomizedBackoffRetryPolicy.js +72 -0
  96. package/dist/retry/ExponentialBackoffRetryPolicy.js +10 -6
  97. package/dist/retry/RetryPolicy.d.ts +1 -1
  98. package/dist/retry/index.d.ts +1 -0
  99. package/dist/retry/index.js +2 -1
  100. package/dist/route/Endpoints.d.ts +6 -0
  101. package/dist/route/Endpoints.js +56 -4
  102. package/dist/route/IpNameResolver.d.ts +28 -0
  103. package/dist/route/IpNameResolver.js +104 -0
  104. package/dist/util/Semaphore.d.ts +47 -0
  105. package/dist/util/Semaphore.js +82 -0
  106. package/dist/util/index.js +6 -3
  107. package/package.json +6 -2
  108. package/src/client/BaseClient.ts +202 -12
  109. package/src/client/RpcClient.ts +14 -1
  110. package/src/client/RpcClientManager.ts +27 -8
  111. package/src/client/TelemetrySession.ts +47 -9
  112. package/src/consumer/ConsumeResult.ts +5 -2
  113. package/src/consumer/ConsumeService.ts +9 -2
  114. package/src/consumer/ConsumeTask.ts +43 -3
  115. package/src/consumer/Consumer.ts +103 -23
  116. package/src/consumer/FifoConsumeService.ts +4 -2
  117. package/src/consumer/LiteFifoConsumeService.ts +4 -2
  118. package/src/consumer/LitePushConsumerImpl.ts +21 -3
  119. package/src/consumer/LiteSimpleConsumer.ts +251 -0
  120. package/src/consumer/LiteSimpleConsumerImpl.ts +221 -0
  121. package/src/consumer/LiteStandardConsumeService.ts +4 -2
  122. package/src/consumer/LiteSubscriptionManager.ts +63 -36
  123. package/src/consumer/ProcessQueue.ts +54 -3
  124. package/src/consumer/PushConsumer.ts +98 -5
  125. package/src/consumer/PushConsumerGaugeObserver.ts +60 -0
  126. package/src/consumer/PushSubscriptionSettings.ts +38 -7
  127. package/src/consumer/SimpleConsumer.ts +9 -0
  128. package/src/consumer/StandardConsumeService.ts +4 -2
  129. package/src/consumer/index.ts +1 -0
  130. package/src/exception/PayloadEmptyException.ts +25 -0
  131. package/src/exception/StatusChecker.ts +7 -0
  132. package/src/exception/index.ts +1 -0
  133. package/src/hook/Attribute.ts +36 -0
  134. package/src/hook/AttributeKey.ts +42 -0
  135. package/src/hook/CompositedMessageInterceptor.ts +92 -0
  136. package/src/hook/InflightRequestCountInterceptor.ts +46 -0
  137. package/src/hook/MessageHookPoints.ts +55 -0
  138. package/src/hook/MessageHookPointsStatus.ts +25 -0
  139. package/src/hook/MessageInterceptor.ts +35 -0
  140. package/src/hook/MessageInterceptorContext.ts +33 -0
  141. package/src/hook/MessageInterceptorContextImpl.ts +68 -0
  142. package/src/hook/MessageMeterInterceptor.ts +162 -0
  143. package/src/hook/index.ts +27 -0
  144. package/src/index.ts +1 -0
  145. package/src/metrics/ClientMeter.ts +81 -0
  146. package/src/metrics/ClientMeterManager.ts +145 -0
  147. package/src/metrics/EmptyGaugeObserver.ts +36 -0
  148. package/src/metrics/GaugeEnum.ts +33 -0
  149. package/src/metrics/GaugeObserver.ts +32 -0
  150. package/src/metrics/HistogramEnum.ts +69 -0
  151. package/src/metrics/InvocationStatus.ts +28 -0
  152. package/src/metrics/Metric.ts +42 -0
  153. package/src/metrics/MetricLabels.ts +31 -0
  154. package/src/metrics/index.ts +26 -0
  155. package/src/producer/Producer.ts +37 -6
  156. package/src/producer/PublishingLoadBalancer.ts +8 -2
  157. package/src/retry/CustomizedBackoffRetryPolicy.ts +81 -0
  158. package/src/retry/ExponentialBackoffRetryPolicy.ts +11 -6
  159. package/src/retry/RetryPolicy.ts +1 -1
  160. package/src/retry/index.ts +1 -0
  161. package/src/route/Endpoints.ts +52 -3
  162. package/src/route/IpNameResolver.ts +119 -0
  163. package/src/util/Semaphore.ts +82 -0
  164. package/src/util/index.ts +5 -2
@@ -16,24 +16,64 @@
16
16
  */
17
17
 
18
18
  import { MessageView } from '../message';
19
+ import {
20
+ Attribute,
21
+ AttributeKey,
22
+ MessageHookPoints,
23
+ MessageHookPointsStatus,
24
+ MessageInterceptor,
25
+ MessageInterceptorContextImpl,
26
+ } from '../hook';
19
27
  import { ConsumeResult } from './ConsumeResult';
20
28
  import { MessageListener } from './MessageListener';
21
29
 
30
+ // Context keys exposed to interceptors, mirroring the Java ConsumeTask keys.
31
+ export const REMOTE_ADDR_CONTEXT_KEY = AttributeKey.create<string>('remote_address');
32
+ export const MESSAGE_VIEW_CONTEXT_KEY = AttributeKey.create<MessageView>('message_view');
33
+ export const CONSUMER_GROUP_CONTEXT_KEY = AttributeKey.create<string>('consumer_group');
34
+ export const CONSUME_ERROR_CONTEXT_KEY = AttributeKey.create<unknown>('consume_error');
35
+
22
36
  export class ConsumeTask {
23
37
  readonly #messageListener: MessageListener;
24
38
  readonly #messageView: MessageView;
39
+ readonly #consumerGroup?: string;
40
+ readonly #messageInterceptor?: MessageInterceptor;
25
41
 
26
- constructor(_clientId: string, messageListener: MessageListener, messageView: MessageView) {
42
+ constructor(_clientId: string, messageListener: MessageListener, messageView: MessageView,
43
+ messageInterceptor?: MessageInterceptor, consumerGroup?: string) {
27
44
  this.#messageListener = messageListener;
28
45
  this.#messageView = messageView;
46
+ this.#messageInterceptor = messageInterceptor;
47
+ this.#consumerGroup = consumerGroup;
29
48
  }
30
49
 
31
50
  async call(): Promise<ConsumeResult> {
51
+ const generalMessages = [ this.#messageView ];
52
+ let context = new MessageInterceptorContextImpl(MessageHookPoints.CONSUME);
53
+ context.putAttribute(MESSAGE_VIEW_CONTEXT_KEY, Attribute.create(this.#messageView));
54
+ if (this.#consumerGroup) {
55
+ context.putAttribute(CONSUMER_GROUP_CONTEXT_KEY, Attribute.create(this.#consumerGroup));
56
+ }
57
+ let throwable: unknown;
58
+ let consumeResult: ConsumeResult;
59
+ if (this.#messageInterceptor) {
60
+ this.#messageInterceptor.doBefore(context, generalMessages);
61
+ }
32
62
  try {
33
- return await this.#messageListener.consume(this.#messageView);
63
+ consumeResult = await this.#messageListener.consume(this.#messageView);
34
64
  } catch (e) {
35
65
  // Message listener raised an exception while consuming messages
36
- return ConsumeResult.FAILURE;
66
+ throwable = e;
67
+ consumeResult = ConsumeResult.FAILURE;
68
+ }
69
+ const status = consumeResult === ConsumeResult.SUCCESS ? MessageHookPointsStatus.OK : MessageHookPointsStatus.ERROR;
70
+ context = MessageInterceptorContextImpl.withStatus(context, status);
71
+ if (throwable) {
72
+ context.putAttribute(CONSUME_ERROR_CONTEXT_KEY, Attribute.create(throwable));
73
+ }
74
+ if (this.#messageInterceptor) {
75
+ this.#messageInterceptor.doAfter(context, generalMessages);
37
76
  }
77
+ return consumeResult;
38
78
  }
39
79
  }
@@ -15,7 +15,7 @@
15
15
  * limitations under the License.
16
16
  */
17
17
 
18
- import { Message, Status } from '../../proto/apache/rocketmq/v2/definition_pb';
18
+ import { Code, Message, Status } from '../../proto/apache/rocketmq/v2/definition_pb';
19
19
  import {
20
20
  AckMessageRequest,
21
21
  ChangeInvisibleDurationRequest,
@@ -27,6 +27,12 @@ import { MessageQueue } from '../route';
27
27
  import { StatusChecker } from '../exception';
28
28
  import { BaseClient, BaseClientOptions } from '../client';
29
29
  import { createDuration, createResource } from '../util';
30
+ import {
31
+ GeneralMessage,
32
+ MessageHookPoints,
33
+ MessageHookPointsStatus,
34
+ MessageInterceptorContextImpl,
35
+ } from '../hook';
30
36
  import { FilterExpression } from './FilterExpression';
31
37
 
32
38
  export interface ConsumerOptions extends BaseClientOptions {
@@ -58,6 +64,12 @@ export abstract class Consumer extends BaseClient {
58
64
  const timeout = this.requestTimeout + awaitDuration;
59
65
  let status: Status.AsObject | undefined;
60
66
 
67
+ // RECEIVE hook point, mirroring Java ProcessQueueImpl: intercept before the
68
+ // RPC so that interceptors which count in-flight requests observe the real
69
+ // request, and carry this same context into doAfter.
70
+ const context = new MessageInterceptorContextImpl(MessageHookPoints.RECEIVE);
71
+ this.doBefore(context, []);
72
+
61
73
  try {
62
74
  this.logger.debug?.('Receiving messages from broker, topic=%s, endpoints=%s, batchSize=%d, clientId=%s',
63
75
  request.getMessageQueue()?.getTopic()?.getName(), endpoints, request.getBatchSize(), (this as any).clientId);
@@ -91,10 +103,12 @@ export abstract class Consumer extends BaseClient {
91
103
  }
92
104
 
93
105
  const messages = messageList.map(message => new MessageView(message, mq, transportDeliveryTimestamp));
106
+ this.doAfter(MessageInterceptorContextImpl.withStatus(context, MessageHookPointsStatus.OK), messages);
94
107
  return messages;
95
108
  } catch (err) {
96
109
  this.logger.error('Failed to receive messages, topic=%s, endpoints=%s, clientId=%s, error=%s',
97
110
  request.getMessageQueue()?.getTopic()?.getName(), endpoints, (this as any).clientId, err);
111
+ this.doAfter(MessageInterceptorContextImpl.withStatus(context, MessageHookPointsStatus.ERROR), []);
98
112
  throw err;
99
113
  }
100
114
  }
@@ -104,14 +118,29 @@ export abstract class Consumer extends BaseClient {
104
118
  const request = new AckMessageRequest()
105
119
  .setGroup(createResource(this.consumerGroup))
106
120
  .setTopic(createResource(messageView.topic));
107
- request.addEntries()
121
+ const entry = request.addEntries()
108
122
  .setMessageId(messageView.messageId)
109
123
  .setReceiptHandle(messageView.receiptHandle);
110
- const res = await this.rpcClientManager.ackMessage(endpoints, request, this.requestTimeout);
111
- // FIXME: handle fail ack
112
- const response = res.toObject();
113
- StatusChecker.check(response.status);
114
- return response.entriesList;
124
+ if (this.isLiteConsumer() && messageView.liteTopic) {
125
+ entry.setLiteTopic(messageView.liteTopic);
126
+ }
127
+ // ACK hook point, mirroring Java ConsumerImpl#ackMessage.
128
+ const context = new MessageInterceptorContextImpl(MessageHookPoints.ACK);
129
+ const generalMessages = [ messageView ];
130
+ this.doBefore(context, generalMessages);
131
+ let hookStatus = MessageHookPointsStatus.OK;
132
+ try {
133
+ const res = await this.rpcClientManager.ackMessage(endpoints, request, this.requestTimeout);
134
+ // FIXME: handle fail ack
135
+ const response = res.toObject();
136
+ hookStatus = response.status?.code === Code.OK ? MessageHookPointsStatus.OK : MessageHookPointsStatus.ERROR;
137
+ StatusChecker.check(response.status);
138
+ this.doAfter(MessageInterceptorContextImpl.withStatus(context, hookStatus), generalMessages);
139
+ return response.entriesList;
140
+ } catch (err) {
141
+ this.doAfter(MessageInterceptorContextImpl.withStatus(context, MessageHookPointsStatus.ERROR), generalMessages);
142
+ throw err;
143
+ }
115
144
  }
116
145
 
117
146
  protected async invisibleDuration(messageView: MessageView, invisibleDuration: number) {
@@ -121,29 +150,80 @@ export abstract class Consumer extends BaseClient {
121
150
  .setReceiptHandle(messageView.receiptHandle)
122
151
  .setInvisibleDuration(createDuration(invisibleDuration))
123
152
  .setMessageId(messageView.messageId);
153
+ if (this.isLiteConsumer() && messageView.liteTopic) {
154
+ request.setLiteTopic(messageView.liteTopic);
155
+ }
124
156
 
125
- const res = await this.rpcClientManager.changeInvisibleDuration(messageView.endpoints, request, this.requestTimeout);
126
- const response = res.toObject();
127
- StatusChecker.check(response.status);
128
- return response.receiptHandle;
157
+ // CHANGE_INVISIBLE_DURATION hook point, mirroring Java ConsumerImpl#changeInvisibleDuration.
158
+ const context = new MessageInterceptorContextImpl(MessageHookPoints.CHANGE_INVISIBLE_DURATION);
159
+ const generalMessages = [ messageView ];
160
+ this.doBefore(context, generalMessages);
161
+ let hookStatus = MessageHookPointsStatus.OK;
162
+ try {
163
+ const res = await this.rpcClientManager.changeInvisibleDuration(messageView.endpoints, request, this.requestTimeout);
164
+ const response = res.toObject();
165
+ hookStatus = response.status?.code === Code.OK ? MessageHookPointsStatus.OK : MessageHookPointsStatus.ERROR;
166
+ StatusChecker.check(response.status);
167
+ this.doAfter(MessageInterceptorContextImpl.withStatus(context, hookStatus), generalMessages);
168
+ return response.receiptHandle;
169
+ } catch (err) {
170
+ this.doAfter(MessageInterceptorContextImpl.withStatus(context, MessageHookPointsStatus.ERROR), generalMessages);
171
+ throw err;
172
+ }
129
173
  }
130
174
 
131
175
  /**
132
- * Expose public methods for ProcessQueue to access RPC operations
176
+ * Expose public methods for ProcessQueue to access RPC operations. Each attempt
177
+ * — including retries driven by ProcessQueue — triggers the matching hook point,
178
+ * so PushConsumer and SimpleConsumer observability stays consistent.
133
179
  */
134
- async ackMessageViaRpc(endpoints: any, request: AckMessageRequest, timeout: number) {
135
- const res = await this.rpcClientManager.ackMessage(endpoints, request, timeout);
136
- return res;
180
+ async ackMessageViaRpc(endpoints: any, request: AckMessageRequest, timeout: number, messageView: MessageView) {
181
+ return this.#invokeWithHook(
182
+ MessageHookPoints.ACK,
183
+ messageView,
184
+ () => this.rpcClientManager.ackMessage(endpoints, request, timeout),
185
+ );
137
186
  }
138
187
 
139
- async changeInvisibleDurationViaRpc(endpoints: any, request: ChangeInvisibleDurationRequest, timeout: number) {
140
- const res = await this.rpcClientManager.changeInvisibleDuration(endpoints, request, timeout);
141
- return res;
188
+ async changeInvisibleDurationViaRpc(endpoints: any, request: ChangeInvisibleDurationRequest, timeout: number,
189
+ messageView: MessageView) {
190
+ return this.#invokeWithHook(
191
+ MessageHookPoints.CHANGE_INVISIBLE_DURATION,
192
+ messageView,
193
+ () => this.rpcClientManager.changeInvisibleDuration(endpoints, request, timeout),
194
+ );
195
+ }
196
+
197
+ async #invokeWithHook<T extends { getStatus(): Status | undefined }>(hookPoint: MessageHookPoints,
198
+ messageView: MessageView,
199
+ rpc: () => Promise<T>): Promise<T> {
200
+ const context = new MessageInterceptorContextImpl(hookPoint);
201
+ const generalMessages: GeneralMessage[] = [ messageView ];
202
+ this.doBefore(context, generalMessages);
203
+ try {
204
+ const response = await rpc();
205
+ const hookStatus = response.getStatus()?.getCode() === Code.OK
206
+ ? MessageHookPointsStatus.OK : MessageHookPointsStatus.ERROR;
207
+ this.doAfter(MessageInterceptorContextImpl.withStatus(context, hookStatus), generalMessages);
208
+ return response;
209
+ } catch (err) {
210
+ this.doAfter(MessageInterceptorContextImpl.withStatus(context, MessageHookPointsStatus.ERROR), generalMessages);
211
+ throw err;
212
+ }
142
213
  }
143
214
 
144
- async forwardMessageToDeadLetterQueueViaRpc(endpoints: any, request: any, timeout: number) {
145
- const res = await this.rpcClientManager.forwardMessageToDeadLetterQueue(endpoints, request, timeout);
146
- return res;
215
+ /**
216
+ * Forward the message to the dead letter queue, mirroring Java
217
+ * PushConsumerImpl#forwardMessageToDeadLetterQueue. The FORWARD_TO_DLQ hook
218
+ * point is triggered around every RPC attempt.
219
+ */
220
+ async forwardMessageToDeadLetterQueueViaRpc(endpoints: any, request: any, timeout: number,
221
+ messageView: MessageView) {
222
+ return this.#invokeWithHook(
223
+ MessageHookPoints.FORWARD_TO_DLQ,
224
+ messageView,
225
+ () => this.rpcClientManager.forwardMessageToDeadLetterQueue(endpoints, request, timeout),
226
+ );
147
227
  }
148
228
 
149
229
  /**
@@ -158,10 +238,10 @@ export abstract class Consumer extends BaseClient {
158
238
  /**
159
239
  * Check if this is a lite consumer.
160
240
  *
161
- * @return true if this is a LITE_PUSH_CONSUMER
241
+ * @return true if this is a LITE_PUSH_CONSUMER or LITE_SIMPLE_CONSUMER
162
242
  */
163
243
  protected isLiteConsumer(): boolean {
164
244
  const clientType = (this as any).getClientType?.();
165
- return clientType === ClientType.LITE_PUSH_CONSUMER;
245
+ return clientType === ClientType.LITE_PUSH_CONSUMER || clientType === ClientType.LITE_SIMPLE_CONSUMER;
166
246
  }
167
247
  }
@@ -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';
@@ -25,8 +26,9 @@ export class FifoConsumeService extends ConsumeService {
25
26
  readonly #enableFifoConsumeAccelerator: boolean;
26
27
  readonly #logger: ILogger;
27
28
 
28
- constructor(clientId: string, messageListener: MessageListener, enableFifoConsumeAccelerator?: boolean) {
29
- super(clientId, messageListener);
29
+ constructor(clientId: string, messageListener: MessageListener, enableFifoConsumeAccelerator?: boolean,
30
+ messageInterceptor?: MessageInterceptor, consumerGroup?: string) {
31
+ super(clientId, messageListener, messageInterceptor, consumerGroup);
30
32
  this.#enableFifoConsumeAccelerator = enableFifoConsumeAccelerator ?? false;
31
33
  this.#logger = getDefaultLogger();
32
34
  }
@@ -16,6 +16,7 @@
16
16
  */
17
17
 
18
18
  import { MessageView } from '../message';
19
+ import { MessageInterceptor } from '../hook';
19
20
  import { ConsumeResultSuspend } from './ConsumeResult';
20
21
  import { FifoConsumeService } from './FifoConsumeService';
21
22
  import { MessageListener } from './MessageListener';
@@ -37,8 +38,9 @@ import { ILogger, getDefaultLogger } from '../client/Logger';
37
38
  export class LiteFifoConsumeService extends FifoConsumeService {
38
39
  readonly #logger: ILogger;
39
40
 
40
- constructor(clientId: string, messageListener: MessageListener, enableFifoConsumeAccelerator?: boolean) {
41
- super(clientId, messageListener, enableFifoConsumeAccelerator);
41
+ constructor(clientId: string, messageListener: MessageListener, enableFifoConsumeAccelerator?: boolean,
42
+ messageInterceptor?: MessageInterceptor, consumerGroup?: string) {
43
+ super(clientId, messageListener, enableFifoConsumeAccelerator, messageInterceptor, consumerGroup);
42
44
  this.#logger = getDefaultLogger();
43
45
  }
44
46
 
@@ -95,10 +95,11 @@ export class LitePushConsumerImpl extends PushConsumer implements LitePushConsum
95
95
  'Create lite FIFO consume service, consumerGroup=%s, clientId=%s, enableFifoConsumeAccelerator=%s',
96
96
  this.consumerGroup, this.clientId, this.#enableFifoConsumeAccelerator,
97
97
  );
98
- return new LiteFifoConsumeService(this.clientId, this.#messageListener, this.#enableFifoConsumeAccelerator);
98
+ return new LiteFifoConsumeService(this.clientId, this.#messageListener, this.#enableFifoConsumeAccelerator,
99
+ this, this.consumerGroup);
99
100
  }
100
101
  this.logger.info('Create lite standard consume service, consumerGroup=%s, clientId=%s', this.consumerGroup, this.clientId);
101
- return new LiteStandardConsumeService(this.clientId, this.#messageListener);
102
+ return new LiteStandardConsumeService(this.clientId, this.#messageListener, this, this.consumerGroup);
102
103
  }
103
104
 
104
105
  /**
@@ -218,9 +219,12 @@ export class LitePushConsumerImpl extends PushConsumer implements LitePushConsum
218
219
  * <p>This method is called when the server sends a notification to unsubscribe
219
220
  * from a lite topic, typically due to quota violations or administrative actions.</p>
220
221
  *
222
+ * @param endpoints - The remote endpoints which sent the command
221
223
  * @param command - The unsubscribe command from the server
222
224
  */
223
- onNotifyUnsubscribeLiteCommand(command: NotifyUnsubscribeLiteCommand) {
225
+ onNotifyUnsubscribeLiteCommand(endpoints: Endpoints, command: NotifyUnsubscribeLiteCommand) {
226
+ this.logger.info('Received notify unsubscribe lite command, liteTopic=%s, endpoints=%s, clientId=%s',
227
+ command.getLiteTopic(), endpoints.facade, this.clientId);
224
228
  this.liteSubscriptionManager.onNotifyUnsubscribeLiteCommand(command);
225
229
  }
226
230
 
@@ -278,4 +282,18 @@ export class LitePushConsumerImpl extends PushConsumer implements LitePushConsum
278
282
  getRequestTimeout(): number {
279
283
  return this.requestTimeout;
280
284
  }
285
+
286
+ /**
287
+ * Endpoints the lite subscription manager should sync to.
288
+ *
289
+ * Lite subscriptions must reach every proxy serving the topic route, not only
290
+ * the endpoint the client was configured with, so the route cache is used and
291
+ * the configured endpoints act as the fallback before any route is known.
292
+ *
293
+ * @internal
294
+ */
295
+ getSyncEndpoints(): Endpoints[] {
296
+ const endpointsList = this.getTotalRouteEndpoints();
297
+ return endpointsList.length > 0 ? endpointsList : [ this.endpoints ];
298
+ }
281
299
  }
@@ -0,0 +1,251 @@
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 { BaseClientOptions } from '../client';
19
+ import { MessageView } from '../message';
20
+ import { OffsetOption } from './OffsetOption';
21
+ import { LiteSimpleConsumerImpl } from './LiteSimpleConsumerImpl';
22
+
23
+ /**
24
+ * LiteSimpleConsumer interface for consuming messages from lite topics with
25
+ * explicit receive/ack control.
26
+ *
27
+ * <p>Similar to SimpleConsumer, but bound to a single parent topic and able to
28
+ * (un)subscribe lite topics dynamically through the lite subscription sync
29
+ * protocol.</p>
30
+ */
31
+ export interface LiteSimpleConsumer {
32
+ /**
33
+ * Get the load balancing group for the lite simple consumer.
34
+ *
35
+ * @return Consumer load balancing group
36
+ */
37
+ getConsumerGroup(): string;
38
+
39
+ /**
40
+ * Subscribe to a lite topic.
41
+ *
42
+ * <p>The subscribeLite() method initiates network requests and performs quota
43
+ * verification, so it may fail. It's important to check the result of this
44
+ * call to ensure that the subscription was successfully added. Possible
45
+ * failure scenarios include:</p>
46
+ * <ul>
47
+ * <li>Network request errors, which can be retried.</li>
48
+ * <li>Quota verification failures, indicated by LiteSubscriptionQuotaExceededException.
49
+ * In this case, evaluate whether the quota is insufficient and promptly
50
+ * unsubscribe from unused subscriptions using unsubscribeLite() to free
51
+ * up resources.</li>
52
+ * </ul>
53
+ *
54
+ * @param liteTopic - The name of the lite topic to subscribe
55
+ * @throws ClientException if an error occurs during subscription
56
+ */
57
+ subscribeLite(liteTopic: string): Promise<void>;
58
+
59
+ /**
60
+ * Subscribe to a lite topic with an offset option to specify the consume from
61
+ * offset.
62
+ *
63
+ * @param liteTopic - The name of the lite topic to subscribe
64
+ * @param offsetOption - The consume from offset option
65
+ * @throws ClientException if an error occurs during subscription
66
+ */
67
+ subscribeLite(liteTopic: string, offsetOption: OffsetOption): Promise<void>;
68
+
69
+ /**
70
+ * Unsubscribe from a lite topic.
71
+ *
72
+ * @param liteTopic - The name of the lite topic to unsubscribe from
73
+ * @throws ClientException if an error occurs during unsubscription
74
+ */
75
+ unsubscribeLite(liteTopic: string): Promise<void>;
76
+
77
+ /**
78
+ * Get the lite topic immutable set.
79
+ *
80
+ * @return Lite topic immutable set
81
+ */
82
+ getLiteTopicSet(): Set<string>;
83
+
84
+ /**
85
+ * Fetch messages from the server synchronously.
86
+ *
87
+ * <p>This method returns immediately if there are messages available.
88
+ * Otherwise, it will await the passed timeout. If the timeout expires, an
89
+ * empty list will be returned.</p>
90
+ *
91
+ * @param maxMessageNum - Max message num of server returned
92
+ * @param invisibleDuration - Set the invisibleDuration of messages to return
93
+ * @return List of message views
94
+ */
95
+ receive(maxMessageNum?: number, invisibleDuration?: number): Promise<MessageView[]>;
96
+
97
+ /**
98
+ * Ack the consumption of the message which is returned by receive().
99
+ *
100
+ * @param messageView - Message view with the receipt handle to ack
101
+ * @throws ClientException if an error occurs during ack
102
+ */
103
+ ack(messageView: MessageView): Promise<void>;
104
+
105
+ /**
106
+ * Change the invisible duration of a received message.
107
+ *
108
+ * @param messageView - Message view to change invisible duration
109
+ * @param invisibleDuration - New invisible duration
110
+ * @throws ClientException if an error occurs
111
+ */
112
+ changeInvisibleDuration(messageView: MessageView, invisibleDuration: number): Promise<void>;
113
+
114
+ /**
115
+ * Close the consumer and release all related resources.
116
+ *
117
+ * <p>Once the consumer is closed, <strong>it could not be started once
118
+ * again.</strong></p>
119
+ */
120
+ close(): Promise<void>;
121
+ }
122
+
123
+ export interface LiteSimpleConsumerOptions extends BaseClientOptions {
124
+ consumerGroup: string;
125
+ /**
126
+ * The parent topic the lite consumer binds to. All lite topics subscribed by
127
+ * this consumer must belong to this parent topic.
128
+ */
129
+ bindTopic: string;
130
+ /**
131
+ * set await duration for long-polling, default is 30000ms
132
+ */
133
+ awaitDuration?: number;
134
+ /**
135
+ * max retry attempts for temporary errors (e.g., internal server error), default is 3
136
+ */
137
+ maxRetryAttempts?: number;
138
+ }
139
+
140
+ const CONSUMER_GROUP_PATTERN = /^[a-zA-Z0-9_-]+$/;
141
+
142
+ /**
143
+ * LiteSimpleConsumer builder class.
144
+ *
145
+ * <p>This class provides a fluent API for configuring and creating lite simple
146
+ * consumers with explicit receive/ack control over lite topics.</p>
147
+ */
148
+ export class LiteSimpleConsumerBuilder {
149
+ private options: Partial<LiteSimpleConsumerOptions> = {};
150
+
151
+ /**
152
+ * Set the bind topic for the lite simple consumer.
153
+ *
154
+ * @param bindTopic - The parent topic to bind
155
+ * @return This builder instance
156
+ * @throws Error if bindTopic is blank
157
+ */
158
+ bindTopic(bindTopic: string): LiteSimpleConsumerBuilder {
159
+ if (!bindTopic || bindTopic.trim().length === 0) {
160
+ throw new Error('bindTopic should not be blank');
161
+ }
162
+ this.options.bindTopic = bindTopic;
163
+ return this;
164
+ }
165
+
166
+ /**
167
+ * Set the client configuration.
168
+ *
169
+ * @param options - Client configuration options
170
+ * @return This builder instance
171
+ * @throws Error if options is null/undefined
172
+ */
173
+ setClientConfiguration(options: BaseClientOptions): LiteSimpleConsumerBuilder {
174
+ if (!options) {
175
+ throw new Error('clientConfiguration should not be null');
176
+ }
177
+ Object.assign(this.options, options);
178
+ return this;
179
+ }
180
+
181
+ /**
182
+ * Set the consumer group.
183
+ *
184
+ * @param consumerGroup - Consumer group name
185
+ * @return This builder instance
186
+ * @throws Error if consumerGroup is null or doesn't match the pattern
187
+ */
188
+ setConsumerGroup(consumerGroup: string): LiteSimpleConsumerBuilder {
189
+ if (!consumerGroup) {
190
+ throw new Error('consumerGroup should not be null');
191
+ }
192
+ if (!CONSUMER_GROUP_PATTERN.test(consumerGroup)) {
193
+ throw new Error(`consumerGroup does not match the pattern ${CONSUMER_GROUP_PATTERN.source}`);
194
+ }
195
+ this.options.consumerGroup = consumerGroup;
196
+ return this;
197
+ }
198
+
199
+ /**
200
+ * Set the await duration for long-polling receive requests.
201
+ *
202
+ * @param awaitDuration - Maximum time to block when no message is available
203
+ * @return This builder instance
204
+ * @throws Error if awaitDuration is not positive
205
+ */
206
+ setAwaitDuration(awaitDuration: number): LiteSimpleConsumerBuilder {
207
+ if (awaitDuration <= 0) {
208
+ throw new Error('awaitDuration should be positive');
209
+ }
210
+ this.options.awaitDuration = awaitDuration;
211
+ return this;
212
+ }
213
+
214
+ /**
215
+ * Finalize the build of LiteSimpleConsumer and start.
216
+ *
217
+ * <p>This method will block until the lite simple consumer starts
218
+ * successfully.</p>
219
+ *
220
+ * @return Promise resolving to started LiteSimpleConsumer instance
221
+ * @throws Error if required parameters are not set
222
+ */
223
+ async build(): Promise<LiteSimpleConsumer> {
224
+ if (!this.options.endpoints) {
225
+ throw new Error('clientConfiguration has not been set yet');
226
+ }
227
+ if (!this.options.consumerGroup) {
228
+ throw new Error('consumerGroup has not been set yet');
229
+ }
230
+ if (!this.options.bindTopic) {
231
+ throw new Error('bindTopic has not been set yet');
232
+ }
233
+
234
+ const options: LiteSimpleConsumerOptions = {
235
+ endpoints: this.options.endpoints,
236
+ namespace: this.options.namespace ?? '',
237
+ consumerGroup: this.options.consumerGroup!,
238
+ bindTopic: this.options.bindTopic,
239
+ awaitDuration: this.options.awaitDuration,
240
+ maxRetryAttempts: this.options.maxRetryAttempts,
241
+ sslEnabled: this.options.sslEnabled,
242
+ sessionCredentials: this.options.sessionCredentials,
243
+ requestTimeout: this.options.requestTimeout,
244
+ logger: this.options.logger,
245
+ };
246
+
247
+ const liteSimpleConsumer = new LiteSimpleConsumerImpl(options);
248
+ await liteSimpleConsumer.startup();
249
+ return liteSimpleConsumer;
250
+ }
251
+ }