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
@@ -29,6 +29,7 @@ import {
29
29
  RecoverOrphanedTransactionCommand,
30
30
  VerifyMessageCommand,
31
31
  PrintThreadStackTraceCommand,
32
+ ReconnectEndpointsCommand,
32
33
  TelemetryCommand,
33
34
  ThreadStackTrace,
34
35
  HeartbeatRequest,
@@ -74,7 +75,6 @@ export interface BaseClientOptions {
74
75
  */
75
76
  export abstract class BaseClient {
76
77
  readonly clientId = ClientId.create();
77
- readonly clientType = ClientType.CLIENT_TYPE_UNSPECIFIED;
78
78
  readonly sslEnabled: boolean;
79
79
  readonly #sessionCredentials?: SessionCredentials;
80
80
  readonly namespace: string;
@@ -83,18 +83,46 @@ export abstract class BaseClient {
83
83
  protected readonly requestTimeout: number;
84
84
  protected readonly topics = new Set<string>();
85
85
  protected readonly topicRouteCache = new Map<string, TopicRouteData>();
86
+ // In-flight route query futures to avoid duplicate queries for the same topic
87
+ protected readonly inflightRouteFutures = new Map<string, Promise<TopicRouteData>>();
86
88
  protected readonly logger: ILogger;
87
89
  protected readonly rpcClientManager: RpcClientManager;
88
90
  readonly #telemetrySessions = new Map<string, TelemetrySession>();
89
91
  #startupResolve?: () => void;
90
92
  #startupReject?: (err: Error) => void;
91
93
  #timers: NodeJS.Timeout[] = [];
94
+ #running = false;
95
+
96
+ /**
97
+ * Get the client type.
98
+ * Subclasses should override this method to return their specific client type.
99
+ *
100
+ * @return The client type identifier
101
+ */
102
+ protected getClientType(): ClientType {
103
+ return ClientType.CLIENT_TYPE_UNSPECIFIED;
104
+ }
92
105
 
93
106
  constructor(options: BaseClientOptions) {
107
+ // Validate required parameters
108
+ if (!options.endpoints) {
109
+ throw new TypeError('endpoints is required');
110
+ }
111
+ if (typeof options.endpoints !== 'string' || options.endpoints.trim().length === 0) {
112
+ throw new TypeError('endpoints must be a non-empty string');
113
+ }
114
+
115
+ // Validate optional parameters
116
+ if (options.requestTimeout !== undefined) {
117
+ if (typeof options.requestTimeout !== 'number' || options.requestTimeout < 1000) {
118
+ throw new RangeError('requestTimeout must be a number >= 1000ms');
119
+ }
120
+ }
121
+
94
122
  this.logger = options.logger ?? getDefaultLogger();
95
123
  this.sslEnabled = options.sslEnabled === true;
96
124
  this.endpoints = new Endpoints(options.endpoints);
97
- this.namespace = options.namespace;
125
+ this.namespace = options.namespace ?? '';
98
126
  this.#sessionCredentials = options.sessionCredentials;
99
127
  // https://rocketmq.apache.org/docs/introduction/03limits/
100
128
  // Default request timeout is 3000ms
@@ -102,7 +130,9 @@ export abstract class BaseClient {
102
130
  this.rpcClientManager = new RpcClientManager(this, this.logger);
103
131
  if (options.topics) {
104
132
  for (const topic of options.topics) {
105
- this.topics.add(topic);
133
+ if (topic && topic.trim().length > 0) {
134
+ this.topics.add(topic);
135
+ }
106
136
  }
107
137
  }
108
138
  }
@@ -125,16 +155,55 @@ export abstract class BaseClient {
125
155
  }
126
156
 
127
157
  async #startup() {
128
- // fetch topic route
129
- await this.updateRoutes();
158
+ this.logger.info('Begin to execute startup flow, clientId=%s, topics=%d',
159
+ this.clientId, this.topics.size);
160
+
161
+ // Fetch topic route with retry mechanism (align with Java client)
162
+ const maxAttempts = 3;
163
+ let lastError: Error | undefined;
164
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
165
+ try {
166
+ await this.updateRoutes();
167
+ this.logger.info('Fetch topic route successfully during startup, clientId=%s, attempt=%d',
168
+ this.clientId, attempt);
169
+ break;
170
+ } catch (e) {
171
+ lastError = e as Error;
172
+ if (attempt < maxAttempts) {
173
+ const backoffMs = 1000 * attempt; // Simple linear backoff: 1s, 2s, 3s
174
+ this.logger.warn('Fetch topic route failed during startup, will retry, clientId=%s, attempt=%d/%d, error=%s, backoff=%dms',
175
+ this.clientId, attempt, maxAttempts, e instanceof Error ? e.message : String(e), backoffMs);
176
+ await this.sleep(backoffMs);
177
+ } else {
178
+ this.logger.error('Fetch topic route failed after %d attempts, clientId=%s, error=%s',
179
+ maxAttempts, this.clientId, e instanceof Error ? e.message : String(e));
180
+ }
181
+ }
182
+ }
183
+
184
+ if (lastError && !this.topicRouteCache.size) {
185
+ throw new Error(`Failed to fetch topic routes after ${maxAttempts} attempts`, { cause: lastError });
186
+ }
187
+
188
+ this.logger.info('Topic routes updated, clientId=%s', this.clientId);
130
189
  // update topic route every 30s
131
190
  this.#timers.push(setInterval(async () => {
132
- this.updateRoutes();
191
+ try {
192
+ await this.updateRoutes();
193
+ } catch (e) {
194
+ this.logger.error('Failed to update routes periodically, clientId=%s, error=%s',
195
+ this.clientId, e instanceof Error ? e.message : String(e));
196
+ }
133
197
  }, 30000));
134
198
 
135
199
  // sync settings every 5m
136
200
  this.#timers.push(setInterval(async () => {
137
- this.#syncSettings();
201
+ try {
202
+ this.#syncSettings();
203
+ } catch (e) {
204
+ this.logger.error('Failed to sync settings, clientId=%s, error=%s',
205
+ this.clientId, e instanceof Error ? e.message : String(e));
206
+ }
138
207
  }, 5 * 60000));
139
208
 
140
209
  // heartbeat every 10s
@@ -146,39 +215,80 @@ export abstract class BaseClient {
146
215
  // doStats()
147
216
 
148
217
  if (this.topics.size > 0) {
218
+ this.logger.info('Waiting for first onSettingsCommand, clientId=%s', this.clientId);
149
219
  // wait for this first onSettingsCommand call
150
220
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
151
221
  await new Promise<void>((resolve, reject) => {
152
222
  this.#startupReject = reject;
153
223
  this.#startupResolve = resolve;
154
224
  });
225
+ this.logger.info('Received first onSettingsCommand, clientId=%s', this.clientId);
155
226
  this.#startupReject = undefined;
156
227
  this.#startupResolve = undefined;
157
228
  }
229
+ this.#running = true;
230
+ }
231
+
232
+ isRunning(): boolean {
233
+ return this.#running;
234
+ }
235
+
236
+ protected sleep(ms: number): Promise<void> {
237
+ return new Promise(resolve => setTimeout(resolve, ms));
158
238
  }
159
239
 
160
240
  async shutdown() {
161
241
  this.logger.info('Begin to shutdown the rocketmq client, clientId=%s', this.clientId);
242
+ this.#running = false;
243
+
244
+ // 1. Clear all timers
162
245
  while (this.#timers.length > 0) {
163
246
  const timer = this.#timers.pop();
164
- clearInterval(timer);
247
+ if (timer) {
248
+ clearInterval(timer);
249
+ }
165
250
  }
166
251
 
252
+ // 2. Notify server termination
167
253
  await this.#notifyClientTermination();
168
254
 
255
+ // 3. Release all telemetry sessions
169
256
  this.logger.info('Begin to release all telemetry sessions, clientId=%s', this.clientId);
170
257
  this.#releaseTelemetrySessions();
171
258
  this.logger.info('Release all telemetry sessions successfully, clientId=%s', this.clientId);
172
259
 
260
+ // 4. Close RPC connections
173
261
  this.rpcClientManager.close();
262
+
263
+ // 5. Clear caches
264
+ this.topicRouteCache.clear();
265
+ this.inflightRouteFutures.clear();
266
+ this.isolated.clear();
267
+
174
268
  this.logger.info('Shutdown the rocketmq client successfully, clientId=%s', this.clientId);
175
269
  this.logger.close && this.logger.close();
176
270
  }
177
271
 
178
272
  async #doHeartbeat() {
179
- const request = this.wrapHeartbeatRequest();
180
- for (const endpoints of this.getTotalRouteEndpoints()) {
181
- await this.rpcClientManager.heartbeat(endpoints, request, this.requestTimeout);
273
+ try {
274
+ const request = this.wrapHeartbeatRequest();
275
+ const endpointsList = this.getTotalRouteEndpoints();
276
+ if (endpointsList.length === 0) {
277
+ debug('No endpoints available for heartbeat, clientId=%s', this.clientId);
278
+ return;
279
+ }
280
+ for (const endpoints of endpointsList) {
281
+ try {
282
+ await this.rpcClientManager.heartbeat(endpoints, request, this.requestTimeout);
283
+ } catch (e) {
284
+ // Log but don't throw - heartbeat is best-effort
285
+ this.logger.warn('Heartbeat failed for endpoints=%s, clientId=%s, error=%s',
286
+ endpoints.facade, this.clientId, e instanceof Error ? e.message : String(e));
287
+ }
288
+ }
289
+ } catch (e) {
290
+ this.logger.error('Unexpected error in heartbeat, clientId=%s, error=%s',
291
+ this.clientId, e instanceof Error ? e.message : String(e));
182
292
  }
183
293
  }
184
294
 
@@ -214,31 +324,60 @@ export abstract class BaseClient {
214
324
  }
215
325
  }
216
326
 
217
- protected async getRouteData(topic: string) {
218
- let topicRouteData = this.topicRouteCache.get(topic);
219
- if (!topicRouteData) {
220
- this.topics.add(topic);
221
- topicRouteData = await this.#fetchTopicRoute(topic);
327
+ protected async getRouteData(topic: string): Promise<TopicRouteData> {
328
+ // Check cache first
329
+ const cached = this.topicRouteCache.get(topic);
330
+ if (cached) {
331
+ return cached;
332
+ }
333
+
334
+ // Check if there's an in-flight request for this topic
335
+ const inFlight = this.inflightRouteFutures.get(topic);
336
+ if (inFlight) {
337
+ debug('Reusing in-flight route query for topic=%s', topic);
338
+ return inFlight;
339
+ }
340
+
341
+ // Add topic to topics set
342
+ this.topics.add(topic);
343
+
344
+ // Create new route query and cache the promise
345
+ const future = this.#fetchTopicRoute(topic);
346
+ this.inflightRouteFutures.set(topic, future);
347
+
348
+ try {
349
+ const result = await future;
350
+ return result;
351
+ } finally {
352
+ // Clean up in-flight cache after completion (success or failure)
353
+ this.inflightRouteFutures.delete(topic);
222
354
  }
223
- return topicRouteData;
224
355
  }
225
356
 
226
357
  async #fetchTopicRoute(topic: string) {
227
358
  const req = new QueryRouteRequest();
228
359
  req.setTopic(createResource(topic));
229
360
  req.setEndpoints(this.endpoints.toProtobuf());
230
- const response = await this.rpcClientManager.queryRoute(this.endpoints, req, this.requestTimeout);
231
- StatusChecker.check(response.getStatus()?.toObject());
232
- const topicRouteData = new TopicRouteData(response.getMessageQueuesList());
233
- const newEndpoints = this.findNewRouteEndpoints(topicRouteData.getTotalEndpoints());
234
- for (const endpoints of newEndpoints) {
235
- // sync current settings to new endpoints
236
- this.getTelemetrySession(endpoints).syncSettings();
361
+
362
+ try {
363
+ const response = await this.rpcClientManager.queryRoute(this.endpoints, req, this.requestTimeout);
364
+ StatusChecker.check(response.getStatus()?.toObject());
365
+ const topicRouteData = new TopicRouteData(response.getMessageQueuesList());
366
+ const newEndpoints = this.findNewRouteEndpoints(topicRouteData.getTotalEndpoints());
367
+ for (const endpoints of newEndpoints) {
368
+ // sync current settings to new endpoints
369
+ this.getTelemetrySession(endpoints).syncSettings();
370
+ }
371
+ this.topicRouteCache.set(topic, topicRouteData);
372
+ this.onTopicRouteDataUpdate(topic, topicRouteData);
373
+ debug('fetchTopicRoute topic=%o topicRouteData=%j', topic, topicRouteData);
374
+ return topicRouteData;
375
+ } catch (e) {
376
+ const error = e instanceof Error ? e : new Error(String(e));
377
+ this.logger.error('Failed to fetch topic route, clientId=%s, topic=%s, endpoints=%s, error=%s',
378
+ this.clientId, topic, this.endpoints.facade, error.message);
379
+ throw error;
237
380
  }
238
- this.topicRouteCache.set(topic, topicRouteData);
239
- this.onTopicRouteDataUpdate(topic, topicRouteData);
240
- debug('fetchTopicRoute topic=%o topicRouteData=%j', topic, topicRouteData);
241
- return topicRouteData;
242
381
  }
243
382
 
244
383
  #syncSettings() {
@@ -351,6 +490,8 @@ export abstract class BaseClient {
351
490
  }
352
491
 
353
492
  onSettingsCommand(_endpoints: Endpoints, settings: SettingsPB) {
493
+ this.logger.info('Received settings command, clientId=%s, settings=%j',
494
+ this.clientId, settings.toObject());
354
495
  // final Metric metric = new Metric(settings.getMetric());
355
496
  // clientMeterManager.reset(metric);
356
497
  this.getSettings().sync(settings);
@@ -387,4 +528,31 @@ export abstract class BaseClient {
387
528
  telemetryCommand.setStatus(new Status().setCode(Code.OK));
388
529
  this.telemetry(endpoints, telemetryCommand);
389
530
  }
531
+
532
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
533
+ onReconnectEndpointsCommand(endpoints: Endpoints, _command: ReconnectEndpointsCommand) {
534
+ this.logger.info('Received reconnect endpoints command from remote, will refresh telemetry session, endpoints=%s, clientId=%s',
535
+ endpoints, this.clientId);
536
+ // Refresh the telemetry session to use the latest endpoints
537
+ const session = this.getTelemetrySession(endpoints);
538
+ session.refresh();
539
+ }
540
+
541
+ /**
542
+ * Get the endpoints of this client.
543
+ *
544
+ * @return The endpoints
545
+ */
546
+ getEndpoints(): Endpoints {
547
+ return this.endpoints;
548
+ }
549
+
550
+ /**
551
+ * Get the RPC client manager.
552
+ *
553
+ * @return The RPC client manager
554
+ */
555
+ getRpcClientManager(): RpcClientManager {
556
+ return this.rpcClientManager;
557
+ }
390
558
  }
@@ -23,7 +23,7 @@ import { hostname } from 'node:os';
23
23
  */
24
24
  export class ClientId {
25
25
  static #hostname = hostname();
26
- static #index = 0n;
26
+ static #index = BigInt(0);
27
27
 
28
28
  static create() {
29
29
  return `${this.#hostname}@${process.pid}@${this.#index++}@${Date.now().toString(36)}`;
@@ -23,6 +23,7 @@ export interface ILogger {
23
23
  info(...args: any[]): void;
24
24
  warn(...args: any[]): void;
25
25
  error(...args: any[]): void;
26
+ debug?(...args: any[]): void;
26
27
  close?(...args: any[]): void;
27
28
  }
28
29
 
@@ -40,10 +40,14 @@ import {
40
40
  QueryOffsetResponse,
41
41
  QueryRouteRequest,
42
42
  QueryRouteResponse,
43
+ RecallMessageRequest,
44
+ RecallMessageResponse,
43
45
  ReceiveMessageRequest,
44
46
  ReceiveMessageResponse,
45
47
  SendMessageRequest,
46
48
  SendMessageResponse,
49
+ SyncLiteSubscriptionRequest,
50
+ SyncLiteSubscriptionResponse,
47
51
  UpdateOffsetRequest,
48
52
  UpdateOffsetResponse,
49
53
  } from '../../proto/apache/rocketmq/v2/service_pb';
@@ -242,4 +246,26 @@ export class RpcClient {
242
246
  });
243
247
  });
244
248
  }
249
+
250
+ async recallMessage(request: RecallMessageRequest, metadata: Metadata, duration: number) {
251
+ const client = this.#getAndActivityRpcClient();
252
+ const deadline = this.#getDeadline(duration);
253
+ return new Promise<RecallMessageResponse>((resolve, reject) => {
254
+ client.recallMessage(request, metadata, { deadline }, (e, res) => {
255
+ if (e) return reject(e);
256
+ resolve(res);
257
+ });
258
+ });
259
+ }
260
+
261
+ async syncLiteSubscription(request: SyncLiteSubscriptionRequest, metadata: Metadata, duration: number) {
262
+ const client = this.#getAndActivityRpcClient();
263
+ const deadline = this.#getDeadline(duration);
264
+ return new Promise<SyncLiteSubscriptionResponse>((resolve, reject) => {
265
+ client.syncLiteSubscription(request, metadata, { deadline }, (e, res) => {
266
+ if (e) return reject(e);
267
+ resolve(res);
268
+ });
269
+ });
270
+ }
245
271
  }
@@ -25,6 +25,8 @@ import {
25
25
  HeartbeatRequest, NotifyClientTerminationRequest, PullMessageRequest,
26
26
  QueryAssignmentRequest, QueryOffsetRequest, QueryRouteRequest,
27
27
  ReceiveMessageRequest, SendMessageRequest, UpdateOffsetRequest,
28
+ RecallMessageRequest,
29
+ SyncLiteSubscriptionRequest,
28
30
  } from '../../proto/apache/rocketmq/v2/service_pb';
29
31
  import { Endpoints } from '../route';
30
32
  import { ILogger } from './Logger';
@@ -74,11 +76,21 @@ export class RpcClientManager {
74
76
  }
75
77
 
76
78
  close() {
79
+ // Clear idle check timer first
80
+ if (this.#clearIdleRpcClientsTimer) {
81
+ clearInterval(this.#clearIdleRpcClientsTimer);
82
+ }
83
+
84
+ // Close all RPC clients and clear the map
77
85
  for (const [ endpoints, rpcClient ] of this.#rpcClients.entries()) {
78
- rpcClient.close();
79
- this.#rpcClients.delete(endpoints);
86
+ try {
87
+ rpcClient.close();
88
+ } catch (e) {
89
+ this.#logger.warn('Failed to close RPC client for endpoints=%s, clientId=%s, error=%s',
90
+ endpoints.facade, this.#baseClient.clientId, e instanceof Error ? e.message : String(e));
91
+ }
80
92
  }
81
- clearInterval(this.#clearIdleRpcClientsTimer);
93
+ this.#rpcClients.clear();
82
94
  }
83
95
 
84
96
  async queryRoute(endpoints: Endpoints, request: QueryRouteRequest, duration: number) {
@@ -170,4 +182,16 @@ export class RpcClientManager {
170
182
  const metadata = this.#baseClient.getRequestMetadata();
171
183
  return await rpcClient.notifyClientTermination(request, metadata, duration);
172
184
  }
185
+
186
+ async recallMessage(endpoints: Endpoints, request: RecallMessageRequest, duration: number) {
187
+ const rpcClient = this.#getRpcClient(endpoints);
188
+ const metadata = this.#baseClient.getRequestMetadata();
189
+ return await rpcClient.recallMessage(request, metadata, duration);
190
+ }
191
+
192
+ async syncLiteSubscription(endpoints: Endpoints, request: SyncLiteSubscriptionRequest, duration: number) {
193
+ const rpcClient = this.#getRpcClient(endpoints);
194
+ const metadata = this.#baseClient.getRequestMetadata();
195
+ return await rpcClient.syncLiteSubscription(request, metadata, duration);
196
+ }
173
197
  }
@@ -26,19 +26,27 @@ export class TelemetrySession {
26
26
  #baseClient: BaseClient;
27
27
  #logger: ILogger;
28
28
  #stream: ClientDuplexStream<TelemetryCommand, TelemetryCommand>;
29
+ #isRefreshing = false;
29
30
 
30
31
  constructor(baseClient: BaseClient, endpoints: Endpoints, logger: ILogger) {
31
32
  this.#endpoints = endpoints;
32
33
  this.#baseClient = baseClient;
33
34
  this.#logger = logger;
35
+ this.#logger.info('Creating telemetry session, endpoints=%s, clientId=%s',
36
+ endpoints, baseClient.clientId);
34
37
  this.#renewStream(true);
35
38
  }
36
39
 
37
40
  release() {
38
41
  this.#logger.info('Begin to release telemetry session, endpoints=%s, clientId=%s',
39
42
  this.#endpoints, this.#baseClient.clientId);
40
- this.#stream.end();
41
- this.#stream.removeAllListeners();
43
+ try {
44
+ this.#stream.end();
45
+ this.#stream.removeAllListeners();
46
+ } catch (e) {
47
+ this.#logger.warn('Failed to release telemetry session gracefully, endpoints=%s, clientId=%s, error=%s',
48
+ this.#endpoints, this.#baseClient.clientId, e instanceof Error ? e.message : String(e));
49
+ }
42
50
  }
43
51
 
44
52
  write(command: TelemetryCommand) {
@@ -50,13 +58,45 @@ export class TelemetrySession {
50
58
  this.write(command);
51
59
  }
52
60
 
61
+ refresh() {
62
+ if (this.#isRefreshing) {
63
+ this.#logger.warn('Telemetry session is already refreshing, skip this request, endpoints=%s, clientId=%s',
64
+ this.#endpoints, this.#baseClient.clientId);
65
+ return;
66
+ }
67
+
68
+ this.#isRefreshing = true;
69
+ this.#logger.info('Refreshing telemetry session, endpoints=%s, clientId=%s',
70
+ this.#endpoints, this.#baseClient.clientId);
71
+
72
+ try {
73
+ this.release();
74
+ this.#renewStream(false);
75
+ } catch (err) {
76
+ this.#logger.error('Failed to refresh telemetry session, endpoints=%s, clientId=%s, error=%s',
77
+ this.#endpoints, this.#baseClient.clientId, err);
78
+ } finally {
79
+ this.#isRefreshing = false;
80
+ }
81
+ }
82
+
53
83
  #renewStream(inited: boolean) {
54
- this.#stream = this.#baseClient.createTelemetryStream(this.#endpoints);
55
- this.#stream.on('data', this.#onData.bind(this));
56
- this.#stream.once('error', this.#onError.bind(this));
57
- this.#stream.once('end', this.#onEnd.bind(this));
58
- if (!inited) {
59
- this.syncSettings();
84
+ try {
85
+ this.#logger.debug?.('Creating telemetry stream, endpoints=%s, clientId=%s, inited=%s',
86
+ this.#endpoints, this.#baseClient.clientId, inited);
87
+ this.#stream = this.#baseClient.createTelemetryStream(this.#endpoints);
88
+ this.#stream.on('data', this.#onData.bind(this));
89
+ this.#stream.once('error', this.#onError.bind(this));
90
+ this.#stream.once('end', this.#onEnd.bind(this));
91
+ if (!inited) {
92
+ this.#logger.info('Syncing settings to new stream, endpoints=%s, clientId=%s',
93
+ this.#endpoints, this.#baseClient.clientId);
94
+ this.syncSettings();
95
+ }
96
+ } catch (err) {
97
+ this.#logger.error('Failed to create telemetry stream, endpoints=%s, clientId=%s, error=%s',
98
+ this.#endpoints, this.#baseClient.clientId, err);
99
+ throw err;
60
100
  }
61
101
  }
62
102
 
@@ -88,6 +128,12 @@ export class TelemetrySession {
88
128
  this.#baseClient.onPrintThreadStackTraceCommand(endpoints, command.getPrintThreadStackTraceCommand()!);
89
129
  break;
90
130
  }
131
+ case TelemetryCommand.CommandCase.RECONNECT_ENDPOINTS_COMMAND: {
132
+ this.#logger.info('Receive reconnect endpoints command from remote, endpoints=%s, clientId=%s',
133
+ endpoints, clientId);
134
+ this.#baseClient.onReconnectEndpointsCommand(endpoints, command.getReconnectEndpointsCommand()!);
135
+ break;
136
+ }
91
137
  default: {
92
138
  const commandObj = command.toObject();
93
139
  this.#logger.warn('Receive unrecognized command from remote, endpoints=%s, commandCase=%j, command=%j, clientId=%s',
@@ -0,0 +1,40 @@
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 { MessageQueue } from '../route';
19
+
20
+ export class Assignment {
21
+ readonly messageQueue: MessageQueue;
22
+
23
+ constructor(messageQueue: MessageQueue) {
24
+ this.messageQueue = messageQueue;
25
+ }
26
+
27
+ equals(other: Assignment): boolean {
28
+ if (this === other) return true;
29
+ if (!other) return false;
30
+ return this.messageQueue.equals(other.messageQueue);
31
+ }
32
+
33
+ hashCode(): number {
34
+ return this.messageQueue.hashCode();
35
+ }
36
+
37
+ toString(): string {
38
+ return `Assignment{messageQueue=${JSON.stringify(this.messageQueue)}}`;
39
+ }
40
+ }
@@ -0,0 +1,55 @@
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 { Assignment } from './Assignment';
19
+
20
+ export class Assignments {
21
+ readonly #assignmentList: Assignment[];
22
+
23
+ constructor(assignmentList: Assignment[]) {
24
+ this.#assignmentList = assignmentList;
25
+ }
26
+
27
+ getAssignmentList(): Assignment[] {
28
+ return this.#assignmentList;
29
+ }
30
+
31
+ equals(other?: Assignments): boolean {
32
+ if (this === other) return true;
33
+ if (!other) return false;
34
+ if (this.#assignmentList.length !== other.#assignmentList.length) return false;
35
+ for (let i = 0; i < this.#assignmentList.length; i++) {
36
+ if (!this.#assignmentList[i].equals(other.#assignmentList[i])) {
37
+ return false;
38
+ }
39
+ }
40
+ return true;
41
+ }
42
+
43
+ hashCode(): number {
44
+ let hash = 17;
45
+ for (const assignment of this.#assignmentList) {
46
+ // eslint-disable-next-line no-bitwise
47
+ hash = (hash * 31 + assignment.hashCode()) | 0;
48
+ }
49
+ return hash;
50
+ }
51
+
52
+ toString(): string {
53
+ return `Assignments{assignmentList=[${this.#assignmentList.map(a => a.toString()).join(', ')}]}`;
54
+ }
55
+ }
@@ -0,0 +1,21 @@
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
+ export enum ConsumeResult {
19
+ SUCCESS = 'SUCCESS',
20
+ FAILURE = 'FAILURE',
21
+ }