rocketmq-client-remoting-nodejs 0.0.0-stage → 0.0.1

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 (137) hide show
  1. package/README.en.md +428 -0
  2. package/README.md +424 -2
  3. package/dist/client/admin.d.ts +229 -0
  4. package/dist/client/admin.js +2462 -0
  5. package/dist/client/allocate.d.ts +48 -0
  6. package/dist/client/allocate.js +365 -0
  7. package/dist/client/backpressure.d.ts +23 -0
  8. package/dist/client/backpressure.js +95 -0
  9. package/dist/client/consumer.d.ts +294 -0
  10. package/dist/client/consumer.js +3095 -0
  11. package/dist/client/consumer_result.d.ts +129 -0
  12. package/dist/client/consumer_result.js +138 -0
  13. package/dist/client/consumer_stats.d.ts +69 -0
  14. package/dist/client/consumer_stats.js +258 -0
  15. package/dist/client/exception.d.ts +39 -0
  16. package/dist/client/exception.js +36 -0
  17. package/dist/client/hook.d.ts +145 -0
  18. package/dist/client/hook.js +171 -0
  19. package/dist/client/latency.d.ts +61 -0
  20. package/dist/client/latency.js +239 -0
  21. package/dist/client/lite_pull_consumer.d.ts +151 -0
  22. package/dist/client/lite_pull_consumer.js +1096 -0
  23. package/dist/client/mq_client.d.ts +188 -0
  24. package/dist/client/mq_client.js +1678 -0
  25. package/dist/client/mq_client_manager.d.ts +21 -0
  26. package/dist/client/mq_client_manager.js +129 -0
  27. package/dist/client/offset_store.d.ts +45 -0
  28. package/dist/client/offset_store.js +389 -0
  29. package/dist/client/open_tracing_hook.d.ts +52 -0
  30. package/dist/client/open_tracing_hook.js +241 -0
  31. package/dist/client/pop_api.d.ts +28 -0
  32. package/dist/client/pop_api.js +224 -0
  33. package/dist/client/pop_consumer.d.ts +23 -0
  34. package/dist/client/pop_consumer.js +719 -0
  35. package/dist/client/pop_process_queue.d.ts +15 -0
  36. package/dist/client/pop_process_queue.js +51 -0
  37. package/dist/client/process_queue.d.ts +49 -0
  38. package/dist/client/process_queue.js +261 -0
  39. package/dist/client/produce_accumulator.d.ts +75 -0
  40. package/dist/client/produce_accumulator.js +288 -0
  41. package/dist/client/producer.d.ts +231 -0
  42. package/dist/client/producer.js +1774 -0
  43. package/dist/client/pull_api.d.ts +26 -0
  44. package/dist/client/pull_api.js +264 -0
  45. package/dist/client/pull_consumer.d.ts +119 -0
  46. package/dist/client/pull_consumer.js +876 -0
  47. package/dist/client/pull_schedule_service.d.ts +71 -0
  48. package/dist/client/pull_schedule_service.js +424 -0
  49. package/dist/client/request_reply.d.ts +61 -0
  50. package/dist/client/request_reply.js +232 -0
  51. package/dist/client/retry_message.d.ts +2 -0
  52. package/dist/client/retry_message.js +27 -0
  53. package/dist/client/send_result.d.ts +57 -0
  54. package/dist/client/send_result.js +70 -0
  55. package/dist/client/top_addressing.d.ts +20 -0
  56. package/dist/client/top_addressing.js +75 -0
  57. package/dist/client/trace_context.d.ts +61 -0
  58. package/dist/client/trace_context.js +373 -0
  59. package/dist/client/trace_dispatcher.d.ts +31 -0
  60. package/dist/client/trace_dispatcher.js +236 -0
  61. package/dist/client/trace_hook.d.ts +23 -0
  62. package/dist/client/trace_hook.js +228 -0
  63. package/dist/client/traceparent.d.ts +9 -0
  64. package/dist/client/traceparent.js +86 -0
  65. package/dist/common/boundary_type.d.ts +7 -0
  66. package/dist/common/boundary_type.js +16 -0
  67. package/dist/common/compress.d.ts +28 -0
  68. package/dist/common/compress.js +512 -0
  69. package/dist/common/message.d.ts +129 -0
  70. package/dist/common/message.js +214 -0
  71. package/dist/common/messageClientIdSetter.d.ts +7 -0
  72. package/dist/common/messageClientIdSetter.js +48 -0
  73. package/dist/common/messageConst.d.ts +68 -0
  74. package/dist/common/messageConst.js +68 -0
  75. package/dist/common/messageDecoder.d.ts +40 -0
  76. package/dist/common/messageDecoder.js +504 -0
  77. package/dist/common/messageType.d.ts +11 -0
  78. package/dist/common/messageType.js +11 -0
  79. package/dist/common/message_accessor.d.ts +39 -0
  80. package/dist/common/message_accessor.js +135 -0
  81. package/dist/common/mixAll.d.ts +106 -0
  82. package/dist/common/mixAll.js +247 -0
  83. package/dist/common/recall_message_handle.d.ts +25 -0
  84. package/dist/common/recall_message_handle.js +98 -0
  85. package/dist/common/subscriptionData.d.ts +36 -0
  86. package/dist/common/subscriptionData.js +64 -0
  87. package/dist/common/sysflag.d.ts +129 -0
  88. package/dist/common/sysflag.js +96 -0
  89. package/dist/common/topic_config.d.ts +66 -0
  90. package/dist/common/topic_config.js +106 -0
  91. package/dist/common/topic_validator.d.ts +49 -0
  92. package/dist/common/topic_validator.js +115 -0
  93. package/dist/common/utilAll.d.ts +39 -0
  94. package/dist/common/utilAll.js +154 -0
  95. package/dist/common/validators.d.ts +25 -0
  96. package/dist/common/validators.js +80 -0
  97. package/dist/index.d.ts +24 -0
  98. package/dist/index.js +36 -0
  99. package/dist/logging.d.ts +24 -0
  100. package/dist/logging.js +246 -0
  101. package/dist/remoting/acl.d.ts +16 -0
  102. package/dist/remoting/acl.js +39 -0
  103. package/dist/remoting/admin_body.d.ts +257 -0
  104. package/dist/remoting/admin_body.js +669 -0
  105. package/dist/remoting/bodies.d.ts +475 -0
  106. package/dist/remoting/bodies.js +1131 -0
  107. package/dist/remoting/client.d.ts +73 -0
  108. package/dist/remoting/client.js +591 -0
  109. package/dist/remoting/codes.d.ts +296 -0
  110. package/dist/remoting/codes.js +301 -0
  111. package/dist/remoting/exception.d.ts +45 -0
  112. package/dist/remoting/exception.js +58 -0
  113. package/dist/remoting/extra_info.d.ts +61 -0
  114. package/dist/remoting/extra_info.js +220 -0
  115. package/dist/remoting/headers.d.ts +758 -0
  116. package/dist/remoting/headers.js +1307 -0
  117. package/dist/remoting/heartbeat.d.ts +91 -0
  118. package/dist/remoting/heartbeat.js +227 -0
  119. package/dist/remoting/namespace.d.ts +14 -0
  120. package/dist/remoting/namespace.js +85 -0
  121. package/dist/remoting/pop_bodies.d.ts +58 -0
  122. package/dist/remoting/pop_bodies.js +214 -0
  123. package/dist/remoting/remotingCommand.d.ts +39 -0
  124. package/dist/remoting/remotingCommand.js +225 -0
  125. package/dist/remoting/route.d.ts +61 -0
  126. package/dist/remoting/route.js +288 -0
  127. package/dist/remoting/rpc_hooks.d.ts +31 -0
  128. package/dist/remoting/rpc_hooks.js +73 -0
  129. package/dist/remoting/serialize.d.ts +33 -0
  130. package/dist/remoting/serialize.js +372 -0
  131. package/dist/remoting/socks_proxy.d.ts +29 -0
  132. package/dist/remoting/socks_proxy.js +379 -0
  133. package/dist/remoting/static_topic.d.ts +49 -0
  134. package/dist/remoting/static_topic.js +244 -0
  135. package/dist/remoting/subscription.d.ts +65 -0
  136. package/dist/remoting/subscription.js +172 -0
  137. package/package.json +38 -4
@@ -0,0 +1,1678 @@
1
+ // -*- coding: utf-8 -*-
2
+ // MQClient — the central client manager. It owns: the name-server address list,
3
+ // the topic-route cache, the per-topic publish-info table (with the SHARED round-robin cursor),
4
+ // the broker-address table, and the low-level send / heartbeat / recall primitives.
5
+ //
6
+ // NOTE: this module is the single dependency of the producer; it must NOT import producer (the
7
+ // consumer/admin agents will import it too). Hooks/transaction policy live in the producer.
8
+ import os from 'node:os';
9
+ import { RemotingClient } from "../remoting/client.js";
10
+ import { RemotingCommand } from "../remoting/remotingCommand.js";
11
+ import { RequestCode, ResponseCode } from "../remoting/codes.js";
12
+ import { TopicRouteData, findBrokerAddressInPublish, } from "../remoting/route.js";
13
+ import { SendMessageRequestHeader, SendMessageRequestHeaderV2, SendMessageResponseHeader, RecallMessageRequestHeader, RecallMessageResponseHeader, EndTransactionRequestHeader, QueryConsumerOffsetRequestHeader, QueryConsumerOffsetResponseHeader, UpdateConsumerOffsetRequestHeader, GetMaxOffsetRequestHeader, GetMinOffsetRequestHeader, SearchOffsetRequestHeader, GetEarliestMsgStoretimeRequestHeader, PopMessageResponseHeader, ChangeInvisibleTimeResponseHeader, } from "../remoting/headers.js";
14
+ import { SetMessageRequestModeRequestBody } from "../remoting/pop_bodies.js";
15
+ import { CheckClientRequestBody, GetConsumerStatusBody } from "../remoting/bodies.js";
16
+ import { processPopResponse } from "./pop_api.js";
17
+ import { HeartbeatData, ProducerData, ConsumerData, ConsumeType, MessageModel, ConsumeFromWhere, decodeHeartbeatV2Flags, } from "../remoting/heartbeat.js";
18
+ import { MessageBatch, MessageExt, } from "../common/message.js";
19
+ import { MessageSysFlag } from "../common/sysflag.js";
20
+ import { MessageConst } from "../common/messageConst.js";
21
+ import { MessageAccessor } from "../common/message_accessor.js";
22
+ import { MessageType } from "../common/messageType.js";
23
+ import { ExpressionType } from "../common/subscriptionData.js";
24
+ import { MixAll } from "../common/mixAll.js";
25
+ import { messageProperties2String, decodeMessage, decodeMessageId, string2MessageProperties } from "../common/messageDecoder.js";
26
+ import { getLogger } from "../logging.js";
27
+ import { MQClientException, MQBrokerException, RemotingException, } from "../remoting/exception.js";
28
+ import { SendResult } from "./send_result.js";
29
+ import { EndTransactionContext, hookRegistry } from "./hook.js";
30
+ import { ConsumerStatsManager } from "./consumer_stats.js";
31
+ import { REQUEST_FUTURE_HOLDER } from "./request_reply.js";
32
+ import { decompressFor } from "../common/compress.js";
33
+ import { DefaultTopAddressing } from "./top_addressing.js";
34
+ import { QueryAssignmentRequestBody, QueryAssignmentResponseBody, } from "../remoting/pop_bodies.js";
35
+ const logger = getLogger('mqclient');
36
+ // Default size of the concurrent-heartbeat pool: the number of processors the
37
+ // runtime reports. Shared by the facades so their pre-start configuration
38
+ // carries the same default the instance would have used.
39
+ export const DEFAULT_CONCURRENT_HEARTBEAT_THREAD_POOL_SIZE = Math.max(1, os.availableParallelism());
40
+ // A minimal fixed-size task executor. It starts submitted tasks up to `size`
41
+ // at a time and queues the rest. `submit` returns a promise that settles when
42
+ // the task has run (or, for a task that never starts because the pool was shut
43
+ // down, rejects immediately). The heartbeat round waits on those promises, so
44
+ // a submission that is refused still settles the wait instead of hanging it.
45
+ class FixedTaskExecutor {
46
+ size;
47
+ active = 0;
48
+ queue = [];
49
+ closed = false;
50
+ constructor(size) {
51
+ this.size = Math.max(1, Math.floor(size));
52
+ }
53
+ submit(run) {
54
+ if (this.closed)
55
+ return Promise.reject(new Error('heartbeat executor is shut down'));
56
+ return new Promise((resolve, reject) => {
57
+ this.queue.push({ run, resolve, reject });
58
+ this._drain();
59
+ });
60
+ }
61
+ _drain() {
62
+ while (!this.closed && this.active < this.size && this.queue.length > 0) {
63
+ const item = this.queue.shift();
64
+ this.active++;
65
+ Promise.resolve()
66
+ .then(() => item.run())
67
+ .then(() => { this.active--; item.resolve(); this._drain(); }, () => { this.active--; item.resolve(); this._drain(); });
68
+ }
69
+ }
70
+ get pending() { return this.queue.length; }
71
+ shutdown() {
72
+ this.closed = true;
73
+ const dropped = this.queue.splice(0);
74
+ for (const item of dropped)
75
+ item.reject(new Error('heartbeat executor is shut down'));
76
+ }
77
+ }
78
+ export class TopicPublishInfo {
79
+ orderTopic;
80
+ msgQueueList;
81
+ _index; // shared round-robin cursor
82
+ haveTopicRouterInfo;
83
+ constructor() {
84
+ this.orderTopic = false;
85
+ this.msgQueueList = [];
86
+ this._index = 0;
87
+ this.haveTopicRouterInfo = false;
88
+ }
89
+ ok() {
90
+ return this.msgQueueList.length > 0;
91
+ }
92
+ // Round-robin selection. With no lastBrokerName, returns the next queue in rotation
93
+ // (distinct across consecutive calls). When lastBrokerName is given, tries to avoid it.
94
+ selectOneMessageQueue(lastBrokerName = null, resetIndex = false) {
95
+ const list = this.msgQueueList;
96
+ if (list.length === 0)
97
+ return null;
98
+ if (resetIndex)
99
+ this._index = 0;
100
+ if (lastBrokerName == null) {
101
+ const idx = this._index % list.length;
102
+ this._index = (this._index + 1) % list.length;
103
+ return list[idx];
104
+ }
105
+ for (let i = 0; i < list.length; i++) {
106
+ const idx = this._index % list.length;
107
+ this._index = (this._index + 1) % list.length;
108
+ const mq = list[idx];
109
+ if (mq.getBrokerName() !== lastBrokerName)
110
+ return mq;
111
+ }
112
+ // all queues belong to lastBrokerName: fall back to first
113
+ return list[this._index % list.length];
114
+ }
115
+ resetIndex() {
116
+ this._index = 0;
117
+ }
118
+ }
119
+ // ---------------------------------------------------------------------------
120
+ // MQClient
121
+ // ---------------------------------------------------------------------------
122
+ export class MQClient {
123
+ clientId;
124
+ nameServerAddrList;
125
+ nameServerAddress;
126
+ remotingClient;
127
+ topicRouteTable;
128
+ topicPublishInfoTable;
129
+ topicEndPointsTable;
130
+ brokerAddrTable;
131
+ consumerTable;
132
+ producerTable;
133
+ heartbeatIntervalMillis;
134
+ // Route-refresh period, mirrored from the admin facade's configuration at
135
+ // registration. The route timer and the heartbeat timer read these two
136
+ // instance-level values — the facades pass their config in ONCE, they do not
137
+ // each re-drive the timers.
138
+ pollNameServerIntervalMillis;
139
+ // Heartbeat V2. Off by default; a broker only answers the V2 flags when the
140
+ // beat carries a non-zero fingerprint, and a beat with fingerprint 0 makes it
141
+ // take its plain registration path, exactly as before.
142
+ useHeartbeatV2;
143
+ // Broker-side VIP channel. Off by default. When a facade enables it, the
144
+ // offset / queue-lock / consumer-list / subscription-check RPCs the broker
145
+ // answers go to the VIP port (listen port - 2). This mirrors the producer and
146
+ // admin VIP switches onto the shared instance where those requests are made;
147
+ // a name-server address never reaches it (the VIP port is broker-only).
148
+ vipChannelEnabled;
149
+ // Addresses whose HEART_BEAT response declared IS_SUPPORT_HEART_BEAT_V2.
150
+ _brokerSupportV2HeartbeatSet;
151
+ // Last fingerprint accepted per broker address; a beat whose fingerprint
152
+ // matches this cache may drop its subscription sets.
153
+ _brokerAddrHeartbeatFingerprintTable;
154
+ // Client-level API timeout (default 3000 ms): the timeout used by
155
+ // the instance-level admin calls, including CHECK_CLIENT_CONFIG(46), the
156
+ // name-server route fetches, unregister and the consumer-list RPC. An
157
+ // explicit per-call timeout passed by a caller still wins.
158
+ mqClientApiTimeout;
159
+ // Whether received message bodies are materialised during batch decode.
160
+ // On by default. Off: the stored-record frames are still walked (cursor and
161
+ // queue offsets advance), but body bytes are neither copied, CRC-checked nor
162
+ // decompressed — messages come back header-only with properties intact.
163
+ decodeReadBody;
164
+ // Concurrent heartbeat round. Off by default; when on (and heartbeat V2 is
165
+ // off — V2 always wins) one heartbeat per broker is fanned out over a
166
+ // fixed-size pool created when the instance starts.
167
+ enableConcurrentHeartbeat;
168
+ // Re-register the instance's consumer groups whenever a new connection to a
169
+ // known broker is established (see onChannelActive). On by default: the
170
+ // broker drops a group when its last channel closes, so a reconnect must
171
+ // restore the registration before the next periodic beat.
172
+ enableHeartbeatChannelEventListener;
173
+ concurrentHeartbeatThreadPoolSize;
174
+ _heartbeatExecutor;
175
+ // Page size of the paged metadata admin calls (GET_ALL_TOPIC_CONFIG /
176
+ // GET_ALL_SUBSCRIPTIONGROUP_CONFIG): maxTopicNum / maxGroupNum on the wire.
177
+ maxPageSizeInGetMetadata;
178
+ // Consumer stats manager — shared at the instance level; ONE sampler timer,
179
+ // 10s precision.
180
+ consumerStatsManager;
181
+ _heartbeatTimer;
182
+ _routeTimer;
183
+ _routeInitialTimer;
184
+ // Dynamic name-server addressing: fetchNameServerAddr via TopAddressing
185
+ // every 2min, initial delay 10s — ONLY when the name server address was not
186
+ // explicitly set.
187
+ _topAddressing;
188
+ _namesrvTimer;
189
+ _namesrvInitialTimer;
190
+ // adjustThreadPool task: every 1 minute every
191
+ // consumer of this instance is offered a pool-size adjustment decision.
192
+ _adjustThreadPoolTimer;
193
+ // persistAllConsumerOffset task (default 5000 ms): the
194
+ // INSTANCE-level offset flush. The push consumer keeps its
195
+ // own 5s loop, but the pull / lite-pull facades only flushed on shutdown --
196
+ // a crash lost every offset since the start. The first tick fires
197
+ // after a 10s initial delay, then every persistConsumerOffsetInterval.
198
+ persistConsumerOffsetInterval;
199
+ _persistOffsetTimer;
200
+ _persistOffsetInitialTimer;
201
+ // Nameserver sticky/round-robin semantics: reuse the last NS that answered.
202
+ // Prefer it; only fall back to the next one when it fails. Without this stickiness + rotation,
203
+ // when one of several NS is down every route fetch would pick randomly and fail on the dead one.
204
+ _namesrvChosen;
205
+ _running;
206
+ _facadeProcessors;
207
+ constructor(clientId, nameServerAddr = null, remotingClient = null) {
208
+ this.clientId = clientId;
209
+ this.nameServerAddrList = nameServerAddr ? nameServerAddr.split(';').filter((s) => s.length > 0) : [];
210
+ this.nameServerAddress = nameServerAddr;
211
+ this.remotingClient = remotingClient != null ? remotingClient : new RemotingClient({});
212
+ this.topicRouteTable = new Map();
213
+ this.topicPublishInfoTable = new Map();
214
+ this.topicEndPointsTable = new Map();
215
+ this.brokerAddrTable = new Map();
216
+ this.consumerTable = new Map();
217
+ this.producerTable = new Map();
218
+ this.heartbeatIntervalMillis = 30 * 1000;
219
+ this.pollNameServerIntervalMillis = 30 * 1000;
220
+ this.useHeartbeatV2 = false;
221
+ this.vipChannelEnabled = false;
222
+ this._brokerSupportV2HeartbeatSet = new Set();
223
+ this._brokerAddrHeartbeatFingerprintTable = new Map();
224
+ this.mqClientApiTimeout = 3000;
225
+ this.decodeReadBody = true;
226
+ this.enableConcurrentHeartbeat = false;
227
+ this.enableHeartbeatChannelEventListener = true;
228
+ this.concurrentHeartbeatThreadPoolSize = DEFAULT_CONCURRENT_HEARTBEAT_THREAD_POOL_SIZE;
229
+ this._heartbeatExecutor = null;
230
+ this.maxPageSizeInGetMetadata = 2000;
231
+ this.consumerStatsManager = new ConsumerStatsManager();
232
+ this._heartbeatTimer = null;
233
+ this._routeTimer = null;
234
+ this._routeInitialTimer = null;
235
+ this._topAddressing = null;
236
+ this._namesrvTimer = null;
237
+ this._namesrvInitialTimer = null;
238
+ this._adjustThreadPoolTimer = null;
239
+ this.persistConsumerOffsetInterval = 5000;
240
+ this._persistOffsetTimer = null;
241
+ this._persistOffsetInitialTimer = null;
242
+ this._namesrvChosen = null;
243
+ this._running = false;
244
+ this._facadeProcessors = new Map();
245
+ }
246
+ // ---- name server ----
247
+ updateNameServerAddressList(addrs) {
248
+ this.nameServerAddress = addrs;
249
+ this.nameServerAddrList = addrs.split(';').filter((s) => s.length > 0);
250
+ }
251
+ getNameServerAddressList() {
252
+ return this.nameServerAddrList;
253
+ }
254
+ // Apply a TopAddressing push of a new nameserver list.
255
+ // Returns the accepted address (null/unchanged -> no-op).
256
+ onNameServerAddressChange(namesrvAddress) {
257
+ if (namesrvAddress != null && namesrvAddress !== this.nameServerAddress) {
258
+ logger.info('name server address changed, old=%s, new=%s', this.nameServerAddress, namesrvAddress);
259
+ this.updateNameServerAddressList(namesrvAddress);
260
+ return this.nameServerAddress;
261
+ }
262
+ return this.nameServerAddress;
263
+ }
264
+ // Poll the TopAddressing HTTP endpoint for the current nameserver list;
265
+ // a changed answer is pushed through the change callback.
266
+ async fetchNameServerAddr() {
267
+ if (this._topAddressing == null)
268
+ return this.nameServerAddress;
269
+ try {
270
+ return await this._topAddressing.fetchNsAddr();
271
+ }
272
+ catch (e) {
273
+ logger.debug('fetchNameServerAddr exception: %s', e.message);
274
+ return this.nameServerAddress;
275
+ }
276
+ }
277
+ _randomNameServer() {
278
+ const list = this.nameServerAddrList;
279
+ if (list.length === 0)
280
+ return null;
281
+ return list[Math.floor(Math.random() * list.length)];
282
+ }
283
+ // Nameserver call stickiness/rotation: the last NS that answered (_namesrvChosen) is preferred;
284
+ // if it was never configured or has failed, start from a random position and
285
+ // walk the **entire list**, electing the first one to answer and sticking to it. When one of several
286
+ // NS is down, the old implementation (a single random pick) hit the dead one and the whole route
287
+ // fetch failed — with 3 up and 1 down that was ~33% of calls dead, and a fresh process hitting the dead
288
+ // one on its first route fetch showed up as "no route info" / zero-consumption timeouts.
289
+ async _invokeSyncNameServer(request, timeoutMillis) {
290
+ const list = this.nameServerAddrList;
291
+ if (list.length === 0)
292
+ throw new MQClientException('No name server address, please set it first.');
293
+ const chosenIdx = this._namesrvChosen != null ? list.indexOf(this._namesrvChosen) : -1;
294
+ const begin = chosenIdx >= 0 ? chosenIdx : Math.floor(Math.random() * list.length);
295
+ let lastErr = null;
296
+ for (let i = 0; i < list.length; i++) {
297
+ const ns = list[(begin + i) % list.length];
298
+ try {
299
+ const resp = await this.remotingClient.invokeSync(ns, request, timeoutMillis);
300
+ this._namesrvChosen = ns;
301
+ return resp;
302
+ }
303
+ catch (e) {
304
+ lastErr = e instanceof Error ? e : new Error(String(e));
305
+ // The elected one died: drop stickiness so the next round restarts from the next server in the list.
306
+ if (this._namesrvChosen === ns)
307
+ this._namesrvChosen = null;
308
+ logger.warn('name server %s unreachable (%s), trying next', ns, lastErr.message);
309
+ }
310
+ }
311
+ throw lastErr != null ? lastErr : new MQClientException('all name servers failed');
312
+ }
313
+ topicRouteData2TopicPublishInfo(topic, routeData) {
314
+ const info = new TopicPublishInfo();
315
+ info.orderTopic = false;
316
+ info.msgQueueList = routeData.getAllMessageQueue(topic);
317
+ info.haveTopicRouterInfo = true;
318
+ this.topicRouteTable.set(topic, routeData);
319
+ const endpoints = routeData.getStaticTopicEndPoints(topic);
320
+ if (endpoints != null) {
321
+ const byKey = new Map();
322
+ for (const [mq, real] of endpoints.entries()) {
323
+ byKey.set(`${mq.topic}@${mq.brokerName}@${mq.queueId}`, real);
324
+ }
325
+ this.topicEndPointsTable.set(topic, byKey);
326
+ }
327
+ else {
328
+ this.topicEndPointsTable.delete(topic);
329
+ }
330
+ this._refreshBrokerAddrTable(routeData);
331
+ return info;
332
+ }
333
+ _refreshBrokerAddrTable(routeData) {
334
+ for (const bd of routeData.brokerDatas) {
335
+ this.brokerAddrTable.set(bd.brokerName, Object.assign({}, bd.brokerAddrs));
336
+ }
337
+ }
338
+ // Register a route directly (used by the producer's pre-warmed cache / tests).
339
+ updateTopicPublishInfo(topic, info) {
340
+ this.topicPublishInfoTable.set(topic, info);
341
+ }
342
+ getTopicRouteData(topic) {
343
+ return this.topicRouteTable.get(topic) != null ? this.topicRouteTable.get(topic) : null;
344
+ }
345
+ getTopicPublishInfo(topic) {
346
+ return this.topicPublishInfoTable.get(topic) != null ? this.topicPublishInfoTable.get(topic) : null;
347
+ }
348
+ // Resolve route from the name server (network). Contract: isDefault
349
+ // only changes WHICH topic's route is fetched (TBW102 instead of `topic`);
350
+ // the TBW102 fallback for a missing topic is the PRODUCER's
351
+ // tryToFindTopicPublishInfo second step — never an automatic behaviour of
352
+ // this method. A fallback-derived publish info is TAGGED (`fromDefaultTopic`):
353
+ // its queue list is TBW102's, not the real topic's — the send path uses the
354
+ // tag to refetch the exact route before sending (a stale fallback yields
355
+ // "request queueId[N] is illegal" on every attempt otherwise).
356
+ async updateTopicRouteInfoFromNameServer(topic, isDefault = false) {
357
+ const realTopic = isDefault ? MixAll.DEFAULT_TOPIC : topic;
358
+ const request = RemotingCommand.createRequestCommand(RequestCode.GET_ROUTEINFO_BY_TOPIC, null);
359
+ request.addExtField('topic', realTopic);
360
+ // NS failover happens inside _invokeSyncNameServer (it rotates through all
361
+ // NS, see its comment); here we only distinguish "a reachable NS explicitly
362
+ // says the topic does not exist" from "no NS is reachable": the former
363
+ // returns false (no automatic TBW102 fallback), the latter rethrows to the
364
+ // caller — the thrown exception carries the last NS's failure reason
365
+ // (connection refused / TLS handshake failure...), and producers/consumers
366
+ // attach it to their own route error instead of black-boxing it as
367
+ // "No route info".
368
+ const response = await this._invokeSyncNameServer(request, this.mqClientApiTimeout);
369
+ const code = response.code;
370
+ if (code === ResponseCode.SUCCESS) {
371
+ const routeData = TopicRouteData.decode(response.body);
372
+ const info = this.topicRouteData2TopicPublishInfo(topic, routeData);
373
+ if (isDefault && topic !== MixAll.DEFAULT_TOPIC)
374
+ info.fromDefaultTopic = true;
375
+ else
376
+ info.fromDefaultTopic = false;
377
+ this.topicPublishInfoTable.set(topic, info);
378
+ return true;
379
+ }
380
+ // TOPIC_NOT_EXIST (or anything else): NO automatic fallback to TBW102 —
381
+ // return false. A silent fallback would poison the consumer's
382
+ // rebalance with TBW102's 8-queue layout ("queueId[N] is illegal").
383
+ return false;
384
+ }
385
+ // ---- broker address lookup (publish side = master only) ----
386
+ findBrokerAddrByTopic(topic) {
387
+ const info = this.topicPublishInfoTable.get(topic);
388
+ if (info != null && info.ok()) {
389
+ const mq = info.selectOneMessageQueue(null, true);
390
+ if (mq != null)
391
+ return this.findBrokerAddressInPublish(this.getBrokerNameFromMessageQueue(mq));
392
+ }
393
+ const route = this.topicRouteTable.get(topic);
394
+ if (route != null) {
395
+ for (const bd of route.brokerDatas) {
396
+ const master = bd.brokerAddrs[MixAll.MASTER_ID];
397
+ if (master != null)
398
+ return master;
399
+ }
400
+ }
401
+ return null;
402
+ }
403
+ getBrokerNameFromMessageQueue(mq) {
404
+ const endpoints = this.topicEndPointsTable.get(mq.topic);
405
+ if (endpoints != null && endpoints.size > 0) {
406
+ const real = endpoints.get(`${mq.topic}@${mq.brokerName}@${mq.queueId}`);
407
+ if (real != null)
408
+ return real;
409
+ }
410
+ return mq.brokerName;
411
+ }
412
+ findBrokerAddressInPublish(brokerName) {
413
+ const map = this.brokerAddrTable.get(brokerName);
414
+ if (map && map[MixAll.MASTER_ID] != null)
415
+ return map[MixAll.MASTER_ID];
416
+ // fall back to route table
417
+ const route = this._routeForBroker(brokerName);
418
+ if (route != null)
419
+ return findBrokerAddressInPublish(brokerName, route);
420
+ return null;
421
+ }
422
+ _routeForBroker(brokerName) {
423
+ for (const route of this.topicRouteTable.values()) {
424
+ for (const bd of route.brokerDatas) {
425
+ if (bd.brokerName === brokerName)
426
+ return route;
427
+ }
428
+ }
429
+ return null;
430
+ }
431
+ publishAddrFor(mq) {
432
+ return this.findBrokerAddressInPublish(this.getBrokerNameFromMessageQueue(mq));
433
+ }
434
+ getBrokerAddrTable() { return this.brokerAddrTable; }
435
+ // Every (id, addr) pair of every broker we know — masters AND slaves.
436
+ // Heartbeat and unregister iterate the whole brokerAddrTable; restricting
437
+ // to masters breaks slave-only topologies
438
+ // (a slave that never received a heartbeat answers pulls with
439
+ // "subscription not exist").
440
+ getAllBrokerAddrEntries() {
441
+ const out = [];
442
+ for (const [name, addrs] of this.brokerAddrTable.entries()) {
443
+ for (const [idStr, addr] of Object.entries(addrs)) {
444
+ out.push({ brokerName: name, id: parseInt(idStr, 10), addr });
445
+ }
446
+ }
447
+ return out;
448
+ }
449
+ getRouteOfAllBrokers() {
450
+ return Array.from(this.topicRouteTable.values());
451
+ }
452
+ getAllBrokerAddrs() {
453
+ const out = {};
454
+ for (const [name, addrs] of this.brokerAddrTable.entries()) {
455
+ if (addrs[MixAll.MASTER_ID] != null)
456
+ out[name] = addrs[MixAll.MASTER_ID];
457
+ }
458
+ return out;
459
+ }
460
+ // ---- CHECK_CLIENT_CONFIG(46) ----
461
+ // Pre-flight broker-side subscription validation. Only non-TAG
462
+ // subscriptions go on the wire: a broker that does not know 46 answers with
463
+ // a remoting error, and a silently-broken SQL92 filter would otherwise
464
+ // degrade into "subscribe to everything" (ExpressionMessageFilter admits all
465
+ // messages when the expression does not compile). Sending 46 turns that into
466
+ // a start-up failure.
467
+ async checkClientInBroker() {
468
+ for (const [group, consumer] of this.consumerTable.entries()) {
469
+ const subs = consumer.subscription;
470
+ if (subs == null || subs.size === 0) {
471
+ // Return (do not `continue`) on a subscription-less consumer — the
472
+ // whole instance is not ready yet.
473
+ return;
474
+ }
475
+ await this.checkSubscriptionsInBroker(group, subs, this.mqClientApiTimeout);
476
+ }
477
+ }
478
+ // The inner loop, exposed for callers that keep consumers out of the table.
479
+ async checkSubscriptionsInBroker(group, subs, timeoutMillis) {
480
+ for (const sub of subs.values()) {
481
+ // TAG classification: null / "" / "TAG" all count as TAG.
482
+ const exprType = sub.expressionType;
483
+ if (exprType == null || exprType === '' || exprType === ExpressionType.TAG)
484
+ continue;
485
+ // One broker per cluster is checked; the rest are assumed identical.
486
+ const addr = this.findBrokerAddrByTopic(sub.topic);
487
+ if (addr == null)
488
+ continue;
489
+ try {
490
+ await this.checkClientConfig(addr, group, sub, timeoutMillis);
491
+ }
492
+ catch (e) {
493
+ if (e instanceof MQClientException)
494
+ throw e;
495
+ // Transport-class failure (a broker too old to know 46) uses the fixed
496
+ // wording below — callers match on it. The failure also takes the
497
+ // consumer start down.
498
+ throw new MQClientException(`Check client in broker error, maybe because you use ${exprType} to filter message, `
499
+ + 'but server has not been upgraded to support!'
500
+ + 'This error would not affect the launch of consumer, but may has impact on message '
501
+ + 'receiving if you have use the new features which are not supported by server, '
502
+ + 'please check the log!', e);
503
+ }
504
+ }
505
+ }
506
+ // One CHECK_CLIENT_CONFIG(46) round trip. The custom header is null and the
507
+ // body carries CheckClientRequestBody; any non-SUCCESS code becomes an
508
+ // MQClientException carrying the broker's own response code.
509
+ async checkClientConfig(addr, consumerGroup, sub, timeoutMillis) {
510
+ const request = RemotingCommand.createRequestCommand(RequestCode.CHECK_CLIENT_CONFIG, null);
511
+ const body = new CheckClientRequestBody();
512
+ body.clientId = this.clientId;
513
+ body.group = consumerGroup;
514
+ body.subscriptionData = sub.toDict ? sub.toDict() : sub;
515
+ request.body = body.encode();
516
+ const response = await this.remotingClient.invokeSync(this.vipChannel(addr), request, timeoutMillis);
517
+ if (response.code !== ResponseCode.SUCCESS) {
518
+ throw new MQClientException(`CODE: ${response.code} exception message: ${response.remark ?? ''}`);
519
+ }
520
+ }
521
+ // ---- low-level send primitives ----
522
+ // Build the on-wire request command for a message. The UNIQ_KEY must
523
+ // already be set on the message by the caller.
524
+ buildSendRequest(msg, mq, producerGroup) {
525
+ const topic = msg.getTopic();
526
+ const isBatch = msg instanceof MessageBatch;
527
+ // Wire rule: only a REPLY (MSG_TYPE == "reply") goes out as
528
+ // SEND_REPLY_MESSAGE_V2. A REQUEST carries MSG_TYPE=Request_Reply_Msg and
529
+ // CORRELATION_ID but must go as a NORMAL send — the reply processor does
530
+ // not stamp CLUSTER and would push the "reply" straight back to the
531
+ // client named by REPLY_TO_CLIENT (i.e. the requestor itself).
532
+ const isReply = MessageAccessor.getMessageType(msg) === MessageType.REPLY;
533
+ const properties = msg.getProperties();
534
+ const propsStr = messageProperties2String(properties);
535
+ const sysFlag = msg._sysFlag != null ? msg._sysFlag : 0;
536
+ const header = new SendMessageRequestHeader();
537
+ header.producerGroup = producerGroup;
538
+ header.topic = topic;
539
+ header.defaultTopic = MixAll.DEFAULT_TOPIC;
540
+ header.defaultTopicQueueNums = MixAll.DEFAULT_TOPIC_QUEUE_NUMS;
541
+ header.queueId = mq.getQueueId();
542
+ header.sysFlag = sysFlag;
543
+ header.bornTimestamp = Date.now();
544
+ header.flag = msg.getFlag();
545
+ header.properties = propsStr;
546
+ header.reconsumeTimes = null;
547
+ header.unitMode = false;
548
+ header.maxReconsumeTimes = null;
549
+ header.brokerName = mq.getBrokerName();
550
+ // The broker only takes the batch path when the header says so: requestCode
551
+ // alone leaves the packed body stored as ONE ordinary message, which no
552
+ // consumer can read back as its individual members.
553
+ header.batch = isBatch;
554
+ if (MixAll.isRetryTopic(topic)) {
555
+ const rt = msg.getProperty(MessageConst.PROPERTY_RECONSUME_TIME);
556
+ const mt = msg.getProperty(MessageConst.PROPERTY_MAX_RECONSUME_TIMES);
557
+ header.reconsumeTimes = rt != null ? parseInt(rt, 10) : 0;
558
+ header.maxReconsumeTimes = mt != null ? parseInt(mt, 10) : 0;
559
+ }
560
+ let code;
561
+ if (isReply)
562
+ code = RequestCode.SEND_REPLY_MESSAGE_V2;
563
+ else if (isBatch)
564
+ code = RequestCode.SEND_BATCH_MESSAGE;
565
+ else
566
+ code = RequestCode.SEND_MESSAGE_V2;
567
+ const v2 = SendMessageRequestHeaderV2.createV2(header);
568
+ const request = RemotingCommand.createRequestCommand(code, v2);
569
+ request.body = isBatch ? msg.encode() : (msg.getBody() || Buffer.alloc(0));
570
+ return request;
571
+ }
572
+ // Parse a send response into a SendResult. Wire rule: for a single
573
+ // (non-batch) message the SendResult.msgId is the UNIQ_KEY client id
574
+ // (offsetMsgId keeps the physical broker id). The trace Pub record and the
575
+ // console join on this.
576
+ parseSendResponse(response, mq, brokerAddr, msg = null) {
577
+ const code = response.code;
578
+ const remark = response.remark;
579
+ const ext = response.extFields || {};
580
+ switch (code) {
581
+ case ResponseCode.SUCCESS:
582
+ case ResponseCode.FLUSH_DISK_TIMEOUT:
583
+ case ResponseCode.FLUSH_SLAVE_TIMEOUT:
584
+ case ResponseCode.SLAVE_NOT_AVAILABLE: {
585
+ const header = new SendMessageResponseHeader();
586
+ header.fromExtFields(ext);
587
+ let status;
588
+ if (code === ResponseCode.SUCCESS)
589
+ status = 0;
590
+ else if (code === ResponseCode.FLUSH_DISK_TIMEOUT)
591
+ status = 1;
592
+ else if (code === ResponseCode.FLUSH_SLAVE_TIMEOUT)
593
+ status = 2;
594
+ else
595
+ status = 3;
596
+ const offsetMsgId = header.msgId != null ? header.msgId : '';
597
+ const uniqKey = msg != null
598
+ ? msg.getProperty(MessageConst.PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX)
599
+ : null;
600
+ const msgId = uniqKey != null && String(uniqKey).length > 0 ? String(uniqKey) : offsetMsgId;
601
+ const regionId = ext['MSG_REGION'] != null ? ext['MSG_REGION'] : MixAll.DEFAULT_TRACE_REGION_ID;
602
+ const traceOn = ext['TRACE_ON'] != null ? ext['TRACE_ON'] !== 'false' : true;
603
+ return new SendResult(status, msgId, mq, header.queueOffset != null ? header.queueOffset : 0, header.transactionId, offsetMsgId, regionId, traceOn, header.recallHandle);
604
+ }
605
+ default:
606
+ throw new MQBrokerException(code, remark || `CODE: ${code}`, brokerAddr);
607
+ }
608
+ }
609
+ // Synchronous send to a broker address.
610
+ // NOTE: invokeSync is async — this MUST await it, otherwise parseSendResponse
611
+ // receives a Promise and `response.code` is undefined (surfaced as
612
+ // "CODE: undefined" on every real send).
613
+ async sendMessage(addr, request, mq, timeoutMillis, msg = null) {
614
+ const response = await this.remotingClient.invokeSync(addr, request, timeoutMillis);
615
+ return this.parseSendResponse(response, mq, addr, msg);
616
+ }
617
+ // Asynchronous send. sendCallback = (sendResult: SendResult|null, err: Error|null) => void.
618
+ sendMessageAsync(addr, request, mq, timeoutMillis, sendCallback, msg = null) {
619
+ this.remotingClient.invokeAsync(addr, request, (response, err) => {
620
+ if (err != null || response == null) {
621
+ sendCallback(null, err != null ? err : new RemotingException('null response'));
622
+ return;
623
+ }
624
+ try {
625
+ sendCallback(this.parseSendResponse(response, mq, addr, msg), null);
626
+ }
627
+ catch (e) {
628
+ sendCallback(null, e);
629
+ }
630
+ }, timeoutMillis);
631
+ }
632
+ sendMessageOneway(addr, request) {
633
+ // Returned, not dropped: a connection failure here must reach the awaiting
634
+ // producer.sendOneway caller instead of surfacing as an unhandled rejection.
635
+ return this.remotingClient.invokeOneway(addr, request);
636
+ }
637
+ // ---- recall ----
638
+ // RECALL_MESSAGE answers with RecallMessageResponseHeader#msgId — the id of
639
+ // the message the broker withdrew — NOT a SendResult: a recall parses no
640
+ // send response fields and must not be pushed through parseSendResponse.
641
+ async recallMessage(brokerAddr, producerGroup, topic, recallHandle, bname, timeoutMillis) {
642
+ const header = new RecallMessageRequestHeader();
643
+ header.producerGroup = producerGroup;
644
+ header.topic = topic;
645
+ header.recallHandle = recallHandle;
646
+ header.bname = bname;
647
+ const request = RemotingCommand.createRequestCommand(RequestCode.RECALL_MESSAGE, header);
648
+ const response = await this.remotingClient.invokeSync(brokerAddr, request, timeoutMillis);
649
+ if (response.code !== ResponseCode.SUCCESS) {
650
+ throw new MQBrokerException(response.code, response.remark || '', brokerAddr);
651
+ }
652
+ const respHeader = new RecallMessageResponseHeader();
653
+ respHeader.fromExtFields(response.extFields || {});
654
+ return respHeader.msgId != null ? respHeader.msgId : '';
655
+ }
656
+ // ---- heartbeat ----
657
+ // buildHeartbeatData(withoutSub) renders the two heartbeat
658
+ // shapes the V2 protocol knows: withoutSub keeps every consumer's identity but empties its
659
+ // subscription set, which is what lets a V2 broker skip registration work it
660
+ // already did.
661
+ buildHeartbeatData(withoutSub = false) {
662
+ const hb = new HeartbeatData(this.clientId);
663
+ for (const [group, producer] of this.producerTable.entries()) {
664
+ const pd = new ProducerData(group);
665
+ pd.enable = true;
666
+ hb.producerDataSet.push(pd);
667
+ void producer;
668
+ }
669
+ for (const [group, consumer] of this.consumerTable.entries()) {
670
+ const cd = new ConsumerData(group, consumer.consumeType != null ? consumer.consumeType : ConsumeType.CONSUME_PASSIVELY, consumer.messageModel != null ? consumer.messageModel : MessageModel.CLUSTERING, consumer.consumeFromWhere != null ? consumer.consumeFromWhere : ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
671
+ if (!withoutSub)
672
+ cd.subscriptionDataSet = consumer.subscriptionDataSet || [];
673
+ cd.unitMode = consumer.unitMode === true;
674
+ hb.consumerDataSet.push(cd);
675
+ }
676
+ hb.withoutSub = withoutSub;
677
+ return hb;
678
+ }
679
+ setUseHeartbeatV2(enable) {
680
+ if (this.useHeartbeatV2 === (enable === true))
681
+ return this;
682
+ this.useHeartbeatV2 = enable === true;
683
+ // Turning the switch either way invalidates what the caches mean, so start the
684
+ // conversation with every broker over again.
685
+ this._brokerSupportV2HeartbeatSet.clear();
686
+ this._brokerAddrHeartbeatFingerprintTable.clear();
687
+ return this;
688
+ }
689
+ // Broker-side VIP channel switch (mirrors the facade VIP config). Off by
690
+ // default; on makes the offset / lock / consumer-list / subscription-check
691
+ // RPCs target the broker VIP port (listen port - 2).
692
+ setVipChannelEnabled(enable) {
693
+ this.vipChannelEnabled = enable === true;
694
+ return this;
695
+ }
696
+ // Internal-API timeout for the broker / name-server RPCs this instance
697
+ // issues. Callers that pass an explicit timeout still use that value.
698
+ setMqClientApiTimeout(ms) {
699
+ if (!Number.isFinite(ms) || ms <= 0) {
700
+ throw new Error(`mqClientApiTimeout must be > 0, got ${ms}`);
701
+ }
702
+ this.mqClientApiTimeout = Math.floor(ms);
703
+ return this;
704
+ }
705
+ // Whether batch decode materialises received message bodies.
706
+ setDecodeReadBody(enable) {
707
+ this.decodeReadBody = enable === true;
708
+ return this;
709
+ }
710
+ // Dispatch the periodic heartbeat round over a pool instead of serially.
711
+ // Heartbeat V2 always wins over this switch (see sendHeartbeatToAllBrokers).
712
+ setEnableConcurrentHeartbeat(enable) {
713
+ this.enableConcurrentHeartbeat = enable === true;
714
+ return this;
715
+ }
716
+ // Channel-active re-registration switch (default on; see onChannelActive).
717
+ setEnableHeartbeatChannelEventListener(enable) {
718
+ this.enableHeartbeatChannelEventListener = enable === true;
719
+ return this;
720
+ }
721
+ getEnableHeartbeatChannelEventListener() {
722
+ return this.enableHeartbeatChannelEventListener;
723
+ }
724
+ // A connection to addr has just been established. A broker drops a consumer
725
+ // group when its last channel closes, so after a reconnect the group is
726
+ // unknown there until the next periodic beat; beat the broker right away,
727
+ // then wake every consumer's rebalance. Nothing happens for an address that
728
+ // is not a known broker, when no consumer is registered, or with the switch
729
+ // off.
730
+ async onChannelActive(addr) {
731
+ if (!this.enableHeartbeatChannelEventListener)
732
+ return;
733
+ if (!this.getAllBrokerAddrEntries().some((entry) => entry.addr === addr))
734
+ return;
735
+ if (this.consumerTable.size === 0)
736
+ return;
737
+ try {
738
+ await this.sendHeartbeat(addr);
739
+ }
740
+ catch (e) {
741
+ logger.debug('channel-active heartbeat to %s failed: %s', addr, e.message);
742
+ }
743
+ for (const consumer of this.consumerTable.values()) {
744
+ if (consumer != null && typeof consumer.rebalanceImmediately === 'function') {
745
+ try {
746
+ consumer.rebalanceImmediately();
747
+ }
748
+ catch (e) { /* best effort per consumer */ }
749
+ }
750
+ }
751
+ }
752
+ // Pool size of the concurrent heartbeat round. Rebuilds the pool when one is
753
+ // already alive (a round in flight settles; its queued submissions are
754
+ // refused and counted as unsuccessful waits).
755
+ setConcurrentHeartbeatThreadPoolSize(size) {
756
+ if (!Number.isInteger(size) || size <= 0) {
757
+ throw new Error(`concurrentHeartbeatThreadPoolSize must be a positive integer, got ${size}`);
758
+ }
759
+ this.concurrentHeartbeatThreadPoolSize = size;
760
+ if (this._heartbeatExecutor != null) {
761
+ this._heartbeatExecutor.shutdown();
762
+ this._heartbeatExecutor = null;
763
+ }
764
+ return this;
765
+ }
766
+ // Page size used as maxTopicNum / maxGroupNum by the paged metadata calls.
767
+ setMaxPageSizeInGetMetadata(size) {
768
+ if (!Number.isInteger(size) || size <= 0) {
769
+ throw new Error(`maxPageSizeInGetMetadata must be a positive integer, got ${size}`);
770
+ }
771
+ this.maxPageSizeInGetMetadata = size;
772
+ return this;
773
+ }
774
+ // Per-request VIP translation of a BROKER address at the invoke boundary. Off
775
+ // (or an unparseable port) returns the address untouched, so a disabled switch
776
+ // changes nothing and a name-server address must never be passed here.
777
+ vipChannel(addr) {
778
+ return MixAll.brokerVipChannel(this.vipChannelEnabled, addr);
779
+ }
780
+ // Send one heartbeat to one broker (HEART_BEAT=34, body = heartbeat JSON).
781
+ //
782
+ // V1 (the default): the body carries subscriptions and fingerprint 0, so a broker
783
+ // takes its plain registration path and never answers the V2 flags.
784
+ //
785
+ // V2: the fingerprint of this client's subscription snapshot rides on the body —
786
+ // a non-zero fingerprint is exactly what makes the broker answer
787
+ // IS_SUPPORT_HEART_BEAT_V2 / IS_SUB_CHANGE. Once THIS address has declared
788
+ // support and the fingerprint it last accepted is unchanged, the beat goes out
789
+ // without subscription sets; a response saying the subscriptions changed drops
790
+ // the cached fingerprint so the next beat reports them again.
791
+ async sendHeartbeat(brokerAddr) {
792
+ const hb = this.buildHeartbeatData(false);
793
+ if (!this.useHeartbeatV2)
794
+ return this._sendHeartbeatBody(brokerAddr, hb);
795
+ const fingerprint = hb.computeHeartbeatFingerprint();
796
+ hb.heartbeatFingerprint = fingerprint;
797
+ const withoutSub = this.buildHeartbeatData(true);
798
+ withoutSub.heartbeatFingerprint = fingerprint;
799
+ const skipSub = this._brokerSupportV2HeartbeatSet.has(brokerAddr) &&
800
+ this._brokerAddrHeartbeatFingerprintTable.get(brokerAddr) === fingerprint;
801
+ const response = await this._sendHeartbeatBody(brokerAddr, skipSub ? withoutSub : hb);
802
+ const flags = decodeHeartbeatV2Flags(response);
803
+ if (flags.supportV2) {
804
+ this._brokerSupportV2HeartbeatSet.add(brokerAddr);
805
+ if (flags.subChange)
806
+ this._brokerAddrHeartbeatFingerprintTable.delete(brokerAddr);
807
+ else
808
+ this._brokerAddrHeartbeatFingerprintTable.set(brokerAddr, fingerprint);
809
+ }
810
+ return response;
811
+ }
812
+ async _sendHeartbeatBody(brokerAddr, hb) {
813
+ const request = RemotingCommand.createRequestCommand(RequestCode.HEART_BEAT, null);
814
+ request.body = hb.encode();
815
+ // The beat is sent with the client-level API timeout, not a fixed
816
+ // one, so setMqClientApiTimeout governs the heartbeat too.
817
+ return this.remotingClient.invokeSync(brokerAddr, request, this.mqClientApiTimeout);
818
+ }
819
+ async unregisterClient(brokerAddr, producerGroup, consumerGroup) {
820
+ const request = RemotingCommand.createRequestCommand(RequestCode.UNREGISTER_CLIENT, null);
821
+ request.addExtField('clientID', this.clientId);
822
+ request.addExtField('producerGroup', producerGroup);
823
+ request.addExtField('consumerGroup', consumerGroup);
824
+ return this.remotingClient.invokeSync(brokerAddr, request, this.mqClientApiTimeout);
825
+ }
826
+ async unregisterClientAllBrokers(producerGroup, consumerGroup) {
827
+ // Unregister goes to every broker entry (incl. slaves).
828
+ for (const { addr } of this.getAllBrokerAddrEntries()) {
829
+ try {
830
+ await this.unregisterClient(addr, producerGroup, consumerGroup);
831
+ }
832
+ catch (e) { /* best effort */ }
833
+ }
834
+ }
835
+ // ---- create topic ----
836
+ // UPDATE_AND_CREATE_TOPIC(17) extFields:
837
+ // topic / defaultTopic / readQueueNums / writeQueueNums / perm /
838
+ // topicFilterType / attributes. NOTE: `defaultTopicQueueNums` is a SEND-path
839
+ // field — it is NOT part of this request, and omitting read/writeQueueNums
840
+ // makes the broker decode -1 queues and silently fail to create anything.
841
+ async createTopicInBroker(brokerAddr, topic, queueNums, defaultTopic = MixAll.DEFAULT_TOPIC) {
842
+ const request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_AND_CREATE_TOPIC, null);
843
+ request.addExtField('topic', topic);
844
+ request.addExtField('defaultTopic', defaultTopic);
845
+ request.addExtField('readQueueNums', String(queueNums));
846
+ request.addExtField('writeQueueNums', String(queueNums));
847
+ request.addExtField('perm', '6');
848
+ request.addExtField('topicFilterType', 'SINGLE_TAG');
849
+ request.addExtField('order', 'false');
850
+ return this.remotingClient.invokeSync(brokerAddr, request, 3000);
851
+ }
852
+ async getConsumerListByGroup(brokerAddr, consumerGroup) {
853
+ const request = RemotingCommand.createRequestCommand(RequestCode.GET_CONSUMER_LIST_BY_GROUP, null);
854
+ request.addExtField('consumerGroup', consumerGroup);
855
+ return this.remotingClient.invokeSync(this.vipChannel(brokerAddr), request, this.mqClientApiTimeout);
856
+ }
857
+ // ---- offset helpers (used by offset store / consumers / admin) ----
858
+ // Master publish addr first, then any addr for this broker in a cached route
859
+ // (persistAll's findBrokerAddrByTopic fallback). Static-topic logical queues
860
+ // resolve their real broker name first (endpoints table).
861
+ findBrokerAddrForQueue(mq) {
862
+ const master = this.findBrokerAddressInPublish(this.getBrokerNameFromMessageQueue(mq));
863
+ if (master)
864
+ return master;
865
+ const realName = this.getBrokerNameFromMessageQueue(mq);
866
+ const route = this.getTopicRouteData(mq.getTopic());
867
+ if (route) {
868
+ for (const bd of route.brokerDatas || []) {
869
+ if (bd.brokerName === realName) {
870
+ const addrs = Object.values(bd.brokerAddrs || {});
871
+ if (addrs.length)
872
+ return addrs[0];
873
+ }
874
+ }
875
+ }
876
+ return null;
877
+ }
878
+ async queryConsumerOffset(brokerAddr, consumerGroup, mq, setZeroIfNotFound = false, timeoutMillis = 5000) {
879
+ const h = new QueryConsumerOffsetRequestHeader();
880
+ h.consumerGroup = consumerGroup;
881
+ h.topic = mq.getTopic();
882
+ h.queueId = mq.getQueueId();
883
+ h.setZeroIfNotFound = setZeroIfNotFound;
884
+ const request = RemotingCommand.createRequestCommand(RequestCode.QUERY_CONSUMER_OFFSET, h);
885
+ const response = await this.remotingClient.invokeSync(this.vipChannel(brokerAddr), request, timeoutMillis);
886
+ if (response.code === ResponseCode.QUERY_NOT_FOUND)
887
+ return { found: false, offset: -1 };
888
+ if (response.code !== ResponseCode.SUCCESS) {
889
+ throw new MQBrokerException(response.code, response.remark || '', brokerAddr);
890
+ }
891
+ const rh = new QueryConsumerOffsetResponseHeader();
892
+ rh.fromExtFields(response.extFields || {});
893
+ return { found: true, offset: rh.offset == null ? -1 : rh.offset };
894
+ }
895
+ async updateConsumerOffset(brokerAddr, consumerGroup, mq, offset, timeoutMillis = 5000) {
896
+ const h = new UpdateConsumerOffsetRequestHeader();
897
+ h.consumerGroup = consumerGroup;
898
+ h.topic = mq.getTopic();
899
+ h.queueId = mq.getQueueId();
900
+ h.commitOffset = offset;
901
+ const request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_CONSUMER_OFFSET, h);
902
+ const response = await this.remotingClient.invokeSync(this.vipChannel(brokerAddr), request, timeoutMillis);
903
+ if (response.code !== ResponseCode.SUCCESS) {
904
+ throw new MQBrokerException(response.code, response.remark || '', brokerAddr);
905
+ }
906
+ }
907
+ async getMaxOffset(brokerAddr, topic, queueId, timeoutMillis = 5000) {
908
+ const h = new GetMaxOffsetRequestHeader();
909
+ h.topic = topic;
910
+ h.queueId = queueId;
911
+ const request = RemotingCommand.createRequestCommand(RequestCode.GET_MAX_OFFSET, h);
912
+ const response = await this.remotingClient.invokeSync(this.vipChannel(brokerAddr), request, timeoutMillis);
913
+ if (response.code !== ResponseCode.SUCCESS) {
914
+ throw new MQBrokerException(response.code, response.remark || '', brokerAddr);
915
+ }
916
+ return (response.extFields && response.extFields['offset'] != null)
917
+ ? parseInt(response.extFields['offset'], 10) : -1;
918
+ }
919
+ async getMinOffset(brokerAddr, topic, queueId, timeoutMillis = 5000) {
920
+ const h = new GetMinOffsetRequestHeader();
921
+ h.topic = topic;
922
+ h.queueId = queueId;
923
+ const request = RemotingCommand.createRequestCommand(RequestCode.GET_MIN_OFFSET, h);
924
+ const response = await this.remotingClient.invokeSync(this.vipChannel(brokerAddr), request, timeoutMillis);
925
+ if (response.code !== ResponseCode.SUCCESS) {
926
+ throw new MQBrokerException(response.code, response.remark || '', brokerAddr);
927
+ }
928
+ return (response.extFields && response.extFields['offset'] != null)
929
+ ? parseInt(response.extFields['offset'], 10) : -1;
930
+ }
931
+ async searchOffsetByTimestamp(brokerAddr, topic, queueId, timestamp, timeoutMillis = 5000) {
932
+ const h = new SearchOffsetRequestHeader();
933
+ h.topic = topic;
934
+ h.queueId = queueId;
935
+ h.timestamp = timestamp;
936
+ const request = RemotingCommand.createRequestCommand(RequestCode.SEARCH_OFFSET_BY_TIMESTAMP, h);
937
+ const response = await this.remotingClient.invokeSync(this.vipChannel(brokerAddr), request, timeoutMillis);
938
+ if (response.code !== ResponseCode.SUCCESS) {
939
+ throw new MQBrokerException(response.code, response.remark || '', brokerAddr);
940
+ }
941
+ return (response.extFields && response.extFields['offset'] != null)
942
+ ? parseInt(response.extFields['offset'], 10) : -1;
943
+ }
944
+ async getEarliestMsgStoretime(brokerAddr, topic, queueId, timeoutMillis = 5000) {
945
+ const h = new GetEarliestMsgStoretimeRequestHeader();
946
+ h.topic = topic;
947
+ h.queueId = queueId;
948
+ const request = RemotingCommand.createRequestCommand(RequestCode.GET_EARLIEST_MSG_STORETIME, h);
949
+ const response = await this.remotingClient.invokeSync(this.vipChannel(brokerAddr), request, timeoutMillis);
950
+ if (response.code !== ResponseCode.SUCCESS) {
951
+ throw new MQBrokerException(response.code, response.remark || '', brokerAddr);
952
+ }
953
+ return (response.extFields && response.extFields['timestamp'] != null)
954
+ ? parseInt(response.extFields['timestamp'], 10) : -1;
955
+ }
956
+ // viewMessage is the Java MQAdminImpl#viewMessage(topic, msgId) core
957
+ // (MQAdminImpl.java:267): a single leg — decode the offset msgId and ask
958
+ // the broker that stamped it VIEW_MESSAGE_BY_ID(33) straight away. Decode
959
+ // failure maps to the NO_MESSAGE client error Java raises there; every
960
+ // other leg failure surfaces as-is. The uniq-key fallback is NOT part of
961
+ // this layer — it belongs to the admin facade only
962
+ // (DefaultMQAdminExtImpl#viewMessage), while the producer / push / pull
963
+ // facades ride this single-leg path in Java.
964
+ //
965
+ // defaultViewMessageTimeoutMillis mirrors Java MQAdminImpl's own RPC budget
966
+ // (MQAdminImpl.java:67, `timeoutMillis = 6000`): the viewMessage facades
967
+ // run on it, not on the send timeout or the admin budget.
968
+ async viewMessage(topic, msgId, timeoutMillis = 6000) {
969
+ let addr = '';
970
+ let offset = BigInt(0);
971
+ let decodeError = null;
972
+ try {
973
+ const parsed = decodeMessageId(msgId);
974
+ if (parsed.port <= 0 || parsed.port > 65535) {
975
+ throw new MQClientException(`not a valid offset msgId: ${msgId}`);
976
+ }
977
+ addr = `${parsed.ip}:${parsed.port}`;
978
+ offset = BigInt(parsed.offset);
979
+ }
980
+ catch (e) {
981
+ decodeError = e;
982
+ }
983
+ if (addr === '') {
984
+ throw new MQClientException('query message by id finished, but no message.', decodeError);
985
+ }
986
+ // The address is the store host:port the broker stamped into the offset
987
+ // msgId — a broker address, so the VIP-channel rewrite applies to it like
988
+ // to any other query request.
989
+ const target = this.vipChannel(addr);
990
+ const request = RemotingCommand.createRequestCommand(RequestCode.VIEW_MESSAGE_BY_ID, null);
991
+ request.addExtField('topic', topic);
992
+ request.addExtField('offset', offset.toString());
993
+ const response = await this.remotingClient.invokeSync(target, request, timeoutMillis);
994
+ if (response.code !== ResponseCode.SUCCESS) {
995
+ throw new MQBrokerException(response.code, response.remark || `CODE: ${response.code}`, target);
996
+ }
997
+ if (response.body == null || response.body.length === 0) {
998
+ throw new MQClientException(`message not found: ${msgId}`);
999
+ }
1000
+ const msg = decodeMessage(response.body, true, true);
1001
+ if (msg == null)
1002
+ throw new MQClientException(`message not found: ${msgId}`);
1003
+ return msg;
1004
+ }
1005
+ // ---------------------------------------------------------------- POP path
1006
+ // POP/ACK/CHANGE_INVISIBLE/BATCH_ACK/SET_MESSAGE_REQUEST_MODE primitives.
1007
+ // popMessage sends POP_MESSAGE(200050) to one broker and turns the reply into
1008
+ // a PopResult with a POP_CK stamped on every message.
1009
+ //
1010
+ // brokerName is the LOGICAL name the checkpoint must carry (segment 5) and
1011
+ // must be the same name the ACK later addresses — sending the physical broker
1012
+ // name here makes every ACK unresolvable.
1013
+ async popMessage(brokerName, addr, header, namespace, timeoutMillis) {
1014
+ const request = RemotingCommand.createRequestCommand(RequestCode.POP_MESSAGE, header);
1015
+ const response = await this.remotingClient.invokeSync(addr, request, timeoutMillis);
1016
+ const respHeader = new PopMessageResponseHeader();
1017
+ respHeader.fromExtFields(response.extFields || {});
1018
+ return processPopResponse(brokerName, response.code, response.remark || '', response.body || null, respHeader, header.topic || '', namespace, header.order === true, this.decodeReadBody);
1019
+ }
1020
+ // ackMessage sends ACK_MESSAGE(200051) synchronously and returns the broker's
1021
+ // response code. `offset` must be the checkpoint's segment 7 (the message's
1022
+ // own queue offset).
1023
+ //
1024
+ // Java parity (MQClientAPIImpl#ackMessageAsync:987-993): ANY non-SUCCESS code
1025
+ // means the broker could not find the checkpoint (AckStatus.NO_EXIST on the
1026
+ // wire) — a RESULT, not an error; only transport failures reject. The push
1027
+ // consumer warns on non-SUCCESS and moves on (DefaultMQPushConsumerImpl:842).
1028
+ async ackMessage(addr, header, timeoutMillis) {
1029
+ const request = RemotingCommand.createRequestCommand(RequestCode.ACK_MESSAGE, header);
1030
+ const response = await this.remotingClient.invokeSync(addr, request, timeoutMillis);
1031
+ return response.code;
1032
+ }
1033
+ // batchAckMessage sends BATCH_ACK_MESSAGE(200151) with a pre-built body.
1034
+ //
1035
+ // NOTE: the classic remoting POP path acks ONE message at a time via
1036
+ // ACK_MESSAGE(200051). This primitive is exported because the broker-side
1037
+ // capability is real and next-gen/proxy clients use it. Do NOT "finish" the
1038
+ // POP consumer by routing its acks through this — that would be inventing
1039
+ // client behaviour.
1040
+ async batchAckMessage(addr, body, timeoutMillis) {
1041
+ // No custom header — the request rides the body only.
1042
+ const request = RemotingCommand.createRequestCommand(RequestCode.BATCH_ACK_MESSAGE, null);
1043
+ request.body = body.encode();
1044
+ const response = await this.remotingClient.invokeSync(addr, request, timeoutMillis);
1045
+ if (response.code !== ResponseCode.SUCCESS) {
1046
+ throw new MQBrokerException(response.code, response.remark || '', addr);
1047
+ }
1048
+ }
1049
+ // changeInvisibleTime sends CHANGE_MESSAGE_INVISIBLETIME(200053) and reports
1050
+ // the broker's verdict as a RESULT (Java parity:
1051
+ // MQClientAPIImpl#changeInvisibleTimeAsync:1018-1036 — SUCCESS is
1052
+ // AckStatus.OK with the NEW popTime / invisibleTime; ANY non-SUCCESS code is
1053
+ // AckStatus.NO_EXIST, a result rather than an error; only transport failures
1054
+ // reject). The returned values are not cosmetic: the caller rebuilds the
1055
+ // checkpoint from `header` so a later ACK still matches the (now longer)
1056
+ // invisibility window. `header` is null unless code === SUCCESS.
1057
+ async changeInvisibleTime(addr, header, timeoutMillis) {
1058
+ const request = RemotingCommand.createRequestCommand(RequestCode.CHANGE_MESSAGE_INVISIBLETIME, header);
1059
+ const response = await this.remotingClient.invokeSync(addr, request, timeoutMillis);
1060
+ if (response.code !== ResponseCode.SUCCESS) {
1061
+ return { code: response.code, remark: response.remark || '', header: null };
1062
+ }
1063
+ const rh = new ChangeInvisibleTimeResponseHeader();
1064
+ rh.fromExtFields(response.extFields || {});
1065
+ return { code: response.code, remark: '', header: rh };
1066
+ }
1067
+ // setMessageRequestMode sends SET_MESSAGE_REQUEST_MODE(401) — the
1068
+ // broker-side switch that decides whether a (group, topic) pair is served in
1069
+ // POP or PULL mode.
1070
+ async setMessageRequestMode(addr, topic, consumerGroup, mode, popShareQueueNum, timeoutMillis) {
1071
+ const body = new SetMessageRequestModeRequestBody();
1072
+ body.topic = topic;
1073
+ body.consumerGroup = consumerGroup;
1074
+ body.mode = mode;
1075
+ body.popShareQueueNum = popShareQueueNum;
1076
+ const request = RemotingCommand.createRequestCommand(RequestCode.SET_MESSAGE_REQUEST_MODE, null);
1077
+ request.body = body.encode();
1078
+ const response = await this.remotingClient.invokeSync(addr, request, timeoutMillis);
1079
+ if (response.code !== ResponseCode.SUCCESS) {
1080
+ throw new MQClientException(`setMessageRequestMode failed, code=${response.code} remark=${response.remark || ''}`);
1081
+ }
1082
+ }
1083
+ // ---- QUERY_ASSIGNMENT(400) — broker-side queue assignment. Used by the
1084
+ // push consumer's rebalance when clientRebalance is OFF: the broker decides
1085
+ // which queues (and in which MessageRequestMode) this client consumes.
1086
+ // Returns null when the broker answered with an invalid/empty result — the
1087
+ // caller treats null as "skip the update", never "I own nothing".
1088
+ async queryAssignment(addr, topic, consumerGroup, clientId, strategyName, messageModel, timeoutMillis = 3000) {
1089
+ const body = new QueryAssignmentRequestBody();
1090
+ body.topic = topic;
1091
+ body.consumerGroup = consumerGroup;
1092
+ body.clientId = clientId;
1093
+ body.messageModel = messageModel;
1094
+ body.strategyName = strategyName;
1095
+ const request = RemotingCommand.createRequestCommand(RequestCode.QUERY_ASSIGNMENT, null);
1096
+ request.body = body.encode();
1097
+ const response = await this.remotingClient.invokeSync(addr, request, timeoutMillis);
1098
+ if (response.code !== ResponseCode.SUCCESS) {
1099
+ throw new MQBrokerException(response.code, response.remark || 'queryAssignment failed', addr);
1100
+ }
1101
+ return QueryAssignmentResponseBody.decode(response.body);
1102
+ }
1103
+ // ---- producer / consumer registration (for the eventual consumer/admin agents) ----
1104
+ registerProducer(group, producer) {
1105
+ this.producerTable.set(group, producer);
1106
+ }
1107
+ unregisterProducer(group) {
1108
+ this.producerTable.delete(group);
1109
+ }
1110
+ registerConsumer(group, consumer) {
1111
+ this.consumerTable.set(group, consumer);
1112
+ }
1113
+ unregisterConsumer(group) {
1114
+ this.consumerTable.delete(group);
1115
+ }
1116
+ getRegisteredConsumers() { return this.consumerTable; }
1117
+ getRegisteredProducers() { return this.producerTable; }
1118
+ // ---- facade-level reverse-request processors (shared-instance multicast) ----
1119
+ // Facades register reverse-request processors on the instance (under a shared
1120
+ // instance they fan out by registration count and never overwrite each other).
1121
+ // Note: do NOT mix remotingClient.registerProcessor direct slots under the
1122
+ // same code — a direct slot would displace the dispatcher here. The
1123
+ // instance's built-in 39/326 processors are registered through here as well.
1124
+ registerFacadeProcessor(requestCode, handler) {
1125
+ let list = this._facadeProcessors.get(requestCode);
1126
+ if (list == null) {
1127
+ list = [];
1128
+ this._facadeProcessors.set(requestCode, list);
1129
+ this.remotingClient.registerProcessor(requestCode, (cmd, addr) => this.dispatchFacadeProcessor(cmd, addr));
1130
+ }
1131
+ list.push(handler);
1132
+ }
1133
+ // Remove your own processors when a facade exits; the last remover unloads the transport-layer slot.
1134
+ unregisterFacadeProcessor(requestCode, handler) {
1135
+ const list = this._facadeProcessors.get(requestCode);
1136
+ if (list == null)
1137
+ return;
1138
+ const idx = list.indexOf(handler);
1139
+ if (idx >= 0)
1140
+ list.splice(idx, 1);
1141
+ if (list.length === 0) {
1142
+ this._facadeProcessors.delete(requestCode);
1143
+ this.remotingClient.unregisterProcessor(requestCode);
1144
+ }
1145
+ }
1146
+ dispatchFacadeProcessor(cmd, addr) {
1147
+ const list = this._facadeProcessors.get(cmd.code);
1148
+ if (list == null || list.length === 0)
1149
+ return this.unclaimedFacadeResponse(cmd);
1150
+ let first = null;
1151
+ for (const handler of list.slice()) {
1152
+ try {
1153
+ const resp = handler(cmd, addr);
1154
+ if (resp != null && first == null)
1155
+ first = resp;
1156
+ }
1157
+ catch (e) {
1158
+ logger.warning('facade processor for code %s failed: %s', cmd.code, e.message);
1159
+ }
1160
+ }
1161
+ return first ?? this.unclaimedFacadeResponse(cmd);
1162
+ }
1163
+ // Two different tails, each one shaped for what the asking side can act on:
1164
+ // 221 always answers SUCCESS with a body, because the asking side decodes it
1165
+ // unconditionally -- an error code makes it drop the reply instead of reading
1166
+ // "this group consumed nothing", and silence reads as unreachable.
1167
+ // 307 and 309 answer the fixed "group is not hosted here" error, because the
1168
+ // initiating admin reports whichever client it probed; only a real reply
1169
+ // carries that. A oneway push (220) and every other unclaimed code send nothing.
1170
+ unclaimedFacadeResponse(cmd) {
1171
+ if (cmd.code === RequestCode.GET_CONSUMER_STATUS_FROM_CLIENT) {
1172
+ const response = RemotingCommand.createResponseCommand(ResponseCode.SUCCESS, null);
1173
+ response.body = new GetConsumerStatusBody().encode();
1174
+ return response;
1175
+ }
1176
+ if (cmd.code === RequestCode.GET_CONSUMER_RUNNING_INFO
1177
+ || cmd.code === RequestCode.CONSUME_MESSAGE_DIRECTLY) {
1178
+ const ext = cmd.extFields || {};
1179
+ const group = String(ext['consumerGroup'] != null ? ext['consumerGroup'] : '');
1180
+ return RemotingCommand.createResponseCommand(ResponseCode.SYSTEM_ERROR, `The Consumer Group <${group}> not exist in this consumer`);
1181
+ }
1182
+ return null;
1183
+ }
1184
+ // How many facade processors a given code currently has (test observability: the non-overwriting landing spots under a shared instance).
1185
+ facadeProcessorCount(requestCode) {
1186
+ const list = this._facadeProcessors.get(requestCode);
1187
+ return list != null ? list.length : 0;
1188
+ }
1189
+ start() {
1190
+ if (this._running)
1191
+ return;
1192
+ this._running = true;
1193
+ this._registerChannelListener();
1194
+ this._ensureHeartbeatExecutor();
1195
+ this._registerTransactionCheckProcessor();
1196
+ this._registerReplyMessageProcessor();
1197
+ this._startHeartbeatLoop();
1198
+ this._startRouteRefreshLoop();
1199
+ this._startNamesrvAddressingLoop();
1200
+ this._startAdjustThreadPoolLoop();
1201
+ this._startPersistConsumerOffsetLoop();
1202
+ // The stats manager's own start() is empty (sampling hangs off each
1203
+ // StatsItem's scheduler); the unified sampler timer starts here.
1204
+ this.consumerStatsManager.start();
1205
+ }
1206
+ _registerChannelListener() {
1207
+ // A transport that does not report connection events (a plain invoker)
1208
+ // never triggers re-registration; a real RemotingClient always reports.
1209
+ const remoting = this.remotingClient;
1210
+ if (typeof remoting.registerChannelListener !== 'function')
1211
+ return;
1212
+ remoting.registerChannelListener((addr) => {
1213
+ void this.onChannelActive(addr);
1214
+ });
1215
+ }
1216
+ // The TopAddressing branch runs ONLY when no name server address was
1217
+ // explicitly configured: fetchNameServerAddr fires at +10s, then every 2min.
1218
+ _startNamesrvAddressingLoop() {
1219
+ if (this.nameServerAddress != null)
1220
+ return; // explicitly set — skip the task
1221
+ this._topAddressing = new DefaultTopAddressing(null, null);
1222
+ this._topAddressing.registerChangeCallBack((addrs) => this.onNameServerAddressChange(addrs));
1223
+ const beat = () => { void this.fetchNameServerAddr(); };
1224
+ const initial = setTimeout(beat, 10_000);
1225
+ if (typeof initial.unref === 'function')
1226
+ initial.unref();
1227
+ this._namesrvTimer = setInterval(beat, 2 * 60_000);
1228
+ if (typeof this._namesrvTimer.unref === 'function')
1229
+ this._namesrvTimer.unref();
1230
+ this._namesrvInitialTimer = initial;
1231
+ }
1232
+ // Periodic adjustThreadPool sweep every 1 minute (initial delay 1 min).
1233
+ // The consumer-side inc/dec is a deliberate no-op (see DefaultMQPushConsumer
1234
+ // .adjustThreadPool), so this only measures.
1235
+ _startAdjustThreadPoolLoop() {
1236
+ this._adjustThreadPoolTimer = setInterval(() => { this.adjustThreadPool(); }, 60_000);
1237
+ if (typeof this._adjustThreadPoolTimer.unref === 'function')
1238
+ this._adjustThreadPoolTimer.unref();
1239
+ }
1240
+ adjustThreadPool() {
1241
+ for (const consumer of this.consumerTable.values()) {
1242
+ if (consumer != null && typeof consumer.adjustThreadPool === 'function') {
1243
+ try {
1244
+ consumer.adjustThreadPool();
1245
+ }
1246
+ catch (e) { /* best effort — never let one consumer break the sweep */ }
1247
+ }
1248
+ }
1249
+ }
1250
+ // Periodic offset flush: persistAllConsumerOffset runs 10s after start and
1251
+ // then every persistConsumerOffsetInterval (default 5s). The
1252
+ // interval timer alone would fire at +5s already, so the 10s initial tick
1253
+ // only matters for a configured interval LONGER than 10s -- kept anyway,
1254
+ // because it also bounds the very first flush after start().
1255
+ _startPersistConsumerOffsetLoop() {
1256
+ if (this._persistOffsetTimer != null)
1257
+ return;
1258
+ const beat = () => { this.persistAllConsumerOffset(); };
1259
+ const initial = setTimeout(beat, 10_000);
1260
+ if (typeof initial.unref === 'function')
1261
+ initial.unref();
1262
+ this._persistOffsetInitialTimer = initial;
1263
+ this._persistOffsetTimer = setInterval(beat, this.persistConsumerOffsetInterval);
1264
+ if (typeof this._persistOffsetTimer.unref === 'function')
1265
+ this._persistOffsetTimer.unref();
1266
+ }
1267
+ // Instance-level flush sweep: walk EVERY consumer
1268
+ // registered on this instance. Best effort per consumer -- one failing flush
1269
+ // must never starve the others (same isolation rule as adjustThreadPool).
1270
+ persistAllConsumerOffset() {
1271
+ for (const consumer of this.consumerTable.values()) {
1272
+ if (consumer == null || typeof consumer.persistConsumerOffset !== 'function')
1273
+ continue;
1274
+ try {
1275
+ const r = consumer.persistConsumerOffset();
1276
+ if (r != null && typeof r.then === 'function') {
1277
+ r.catch((e) => logger.debug('persistConsumerOffset failed: %s', e.message));
1278
+ }
1279
+ }
1280
+ catch (e) {
1281
+ logger.debug('persistConsumerOffset raised: %s', e.message);
1282
+ }
1283
+ }
1284
+ }
1285
+ // Runtime knob for the flush period, in milliseconds (must be > 0).
1286
+ // When the loop is already running the interval timer is rebuilt so the new
1287
+ // period takes effect from the next tick; the 10s initial tick is left alone.
1288
+ setPersistConsumerOffsetInterval(ms) {
1289
+ if (!Number.isFinite(ms) || ms <= 0) {
1290
+ throw new Error(`persistConsumerOffsetInterval must be > 0, got ${ms}`);
1291
+ }
1292
+ this.persistConsumerOffsetInterval = Math.floor(ms);
1293
+ if (this._persistOffsetTimer != null) {
1294
+ clearInterval(this._persistOffsetTimer);
1295
+ this._persistOffsetTimer = setInterval(() => { this.persistAllConsumerOffset(); }, this.persistConsumerOffsetInterval);
1296
+ if (typeof this._persistOffsetTimer.unref === 'function')
1297
+ this._persistOffsetTimer.unref();
1298
+ }
1299
+ }
1300
+ // Runtime knob for the beat period of the instance-level heartbeat loop, in
1301
+ // milliseconds (must be > 0). The facades pass their configured value in at
1302
+ // registration; when the loop is already running the interval timer is
1303
+ // rebuilt so the new period takes effect from the next tick.
1304
+ setHeartbeatIntervalMillis(ms) {
1305
+ if (!Number.isFinite(ms) || ms <= 0) {
1306
+ throw new Error(`heartbeatIntervalMillis must be > 0, got ${ms}`);
1307
+ }
1308
+ this.heartbeatIntervalMillis = Math.floor(ms);
1309
+ if (this._heartbeatTimer != null) {
1310
+ clearInterval(this._heartbeatTimer);
1311
+ this._heartbeatTimer = setInterval(() => { void this.sendHeartbeatToAllBrokers(); }, this.heartbeatIntervalMillis);
1312
+ if (typeof this._heartbeatTimer.unref === 'function')
1313
+ this._heartbeatTimer.unref();
1314
+ }
1315
+ }
1316
+ // Runtime knob for the route-refresh period, in milliseconds (must be > 0).
1317
+ // The 10s initial delay of the refresh loop is a documented constant and is
1318
+ // left alone; only the interval timer is rebuilt.
1319
+ setPollNameServerIntervalMillis(ms) {
1320
+ if (!Number.isFinite(ms) || ms <= 0) {
1321
+ throw new Error(`pollNameServerIntervalMillis must be > 0, got ${ms}`);
1322
+ }
1323
+ this.pollNameServerIntervalMillis = Math.floor(ms);
1324
+ if (this._routeTimer != null) {
1325
+ clearInterval(this._routeTimer);
1326
+ this._routeTimer = setInterval(() => { void this.updateAllTopicRoutesFromNameServer(); }, this.pollNameServerIntervalMillis);
1327
+ if (typeof this._routeTimer.unref === 'function')
1328
+ this._routeTimer.unref();
1329
+ }
1330
+ }
1331
+ // Route refresh every pollNameServerInterval (default 30s), initial delay 10s.
1332
+ // Refreshes the route
1333
+ // of EVERY topic the consumers subscribe to and the producers publish to —
1334
+ // without this, a route registered at the nameserver AFTER the client cached
1335
+ // it (e.g. topic created 3s before consumer start; broker registers its
1336
+ // topic config on its own cycle) never replaces the stale cache and the
1337
+ // rebalance keeps assigning phantom queues.
1338
+ _startRouteRefreshLoop() {
1339
+ if (this._routeTimer != null)
1340
+ return;
1341
+ const beat = () => { void this.updateAllTopicRoutesFromNameServer(); };
1342
+ const initial = setTimeout(beat, 10_000);
1343
+ if (typeof initial.unref === 'function')
1344
+ initial.unref();
1345
+ this._routeTimer = setInterval(beat, this.pollNameServerIntervalMillis);
1346
+ if (typeof this._routeTimer.unref === 'function')
1347
+ this._routeTimer.unref();
1348
+ this._routeInitialTimer = initial;
1349
+ }
1350
+ async updateAllTopicRoutesFromNameServer() {
1351
+ const topics = new Set();
1352
+ // Consumer subscriptions (includes the implicit %RETRY%<group>).
1353
+ for (const consumer of this.consumerTable.values()) {
1354
+ const subs = consumer.subscription;
1355
+ if (subs != null && typeof subs.keys === 'function') {
1356
+ for (const topic of subs.keys())
1357
+ topics.add(topic);
1358
+ }
1359
+ }
1360
+ // Producer publish topics (everything we ever fetched a publish info for).
1361
+ for (const topic of this.topicPublishInfoTable.keys())
1362
+ topics.add(topic);
1363
+ let refreshed = false;
1364
+ for (const topic of topics) {
1365
+ try {
1366
+ if (await this.updateTopicRouteInfoFromNameServer(topic, false))
1367
+ refreshed = true;
1368
+ }
1369
+ catch (e) { /* best effort */ }
1370
+ }
1371
+ // The first heartbeats of a fresh client go nowhere: brokerAddrTable is
1372
+ // only populated by route fetches, and until the broker registers a new
1373
+ // topic (up to its 30s cycle) the consumer group is unknown to the broker
1374
+ // either. As soon as the first route lands, send the heartbeat at once so
1375
+ // the consumer group registers without waiting a full 30s cadence.
1376
+ if (refreshed)
1377
+ void this.sendHeartbeatToAllBrokers();
1378
+ }
1379
+ // Client-level heartbeat beat every heartbeatIntervalMillis (default 30s;
1380
+ // configurable — the facades pass their value in at registration) + an early
1381
+ // beat at start. Without
1382
+ // it the broker's ProducerManager has no channel for the producer group and
1383
+ // can never send CHECK_TRANSACTION_STATE back — the transaction check-back
1384
+ // path silently dies ("Check transaction failed, channel table is empty").
1385
+ // Consumers keep their own loop too; duplicate beats are idempotent.
1386
+ _startHeartbeatLoop() {
1387
+ if (this._heartbeatTimer != null)
1388
+ return;
1389
+ void this.sendHeartbeatToAllBrokers();
1390
+ this._heartbeatTimer = setInterval(() => { void this.sendHeartbeatToAllBrokers(); }, this.heartbeatIntervalMillis);
1391
+ if (typeof this._heartbeatTimer.unref === 'function')
1392
+ this._heartbeatTimer.unref();
1393
+ }
1394
+ // Public: facade start() (pull / lite-pull consumer), route refresh and the
1395
+ // push consumer's rebalance all call this directly. `isRebalance` is the push
1396
+ // consumer's assignment-changed signal: it drops every cached fingerprint so
1397
+ // the next beat re-reports subscriptions -- after a rebalance moved the queue
1398
+ // set the broker has to be told what this client now subscribes to.
1399
+ //
1400
+ // Dispatch order: heartbeat V2 wins when enabled; otherwise the concurrent
1401
+ // round when enableConcurrentHeartbeat is on; otherwise the serial loop. The
1402
+ // return value is the number of brokers a beat was successfully delivered to.
1403
+ async sendHeartbeatToAllBrokers(isRebalance = false) {
1404
+ const entries = this.getAllBrokerAddrEntries();
1405
+ // Two guards apply before walking the broker table: a
1406
+ // client that registers nothing has nothing to report, and a producer-only
1407
+ // client beats the MASTER only -- heartbeating a slave with no consumer data
1408
+ // would leave the slave holding a producer registration it can never use.
1409
+ const beat = this.buildHeartbeatData(false);
1410
+ const producerEmpty = beat.producerDataSet.length === 0;
1411
+ const consumerEmpty = beat.consumerDataSet.length === 0;
1412
+ if (producerEmpty && consumerEmpty) {
1413
+ logger.warning('heartbeat skipped: no producer and no consumer registered');
1414
+ return 0;
1415
+ }
1416
+ if (isRebalance)
1417
+ this._brokerAddrHeartbeatFingerprintTable.clear();
1418
+ logger.debug('heartbeat beat to %d broker(s)', entries.length);
1419
+ if (this.useHeartbeatV2) {
1420
+ // V2 keeps the serial path: its per-address fingerprint cache is updated
1421
+ // from each response and is read by the next beat.
1422
+ return this._sendHeartbeatsSerially(entries, consumerEmpty);
1423
+ }
1424
+ if (this.enableConcurrentHeartbeat) {
1425
+ return this._sendHeartbeatsConcurrently(entries, consumerEmpty);
1426
+ }
1427
+ return this._sendHeartbeatsSerially(entries, consumerEmpty);
1428
+ }
1429
+ async _sendHeartbeatsSerially(entries, consumerEmpty) {
1430
+ let success = 0;
1431
+ for (const { addr, id } of entries) {
1432
+ if (consumerEmpty && id !== MixAll.MASTER_ID)
1433
+ continue;
1434
+ try {
1435
+ await this.sendHeartbeat(addr);
1436
+ success++;
1437
+ }
1438
+ catch (e) { /* best effort */ }
1439
+ }
1440
+ return success;
1441
+ }
1442
+ // One heartbeat per eligible broker, fanned out over the instance's fixed
1443
+ // pool, then wait for every task. A submission refused by a shut-down pool
1444
+ // still settles its wait (and is not counted as a success).
1445
+ async _sendHeartbeatsConcurrently(entries, consumerEmpty) {
1446
+ const targets = [];
1447
+ for (const entry of entries) {
1448
+ if (consumerEmpty && entry.id !== MixAll.MASTER_ID)
1449
+ continue;
1450
+ targets.push(entry);
1451
+ }
1452
+ if (targets.length === 0)
1453
+ return 0;
1454
+ const executor = this._ensureHeartbeatExecutor();
1455
+ let success = 0;
1456
+ const waits = [];
1457
+ for (const { addr } of targets) {
1458
+ let submitted;
1459
+ try {
1460
+ submitted = executor.submit(async () => {
1461
+ try {
1462
+ await this.sendHeartbeat(addr);
1463
+ success++;
1464
+ }
1465
+ catch (e) { /* best effort: one broker must not sink the round */ }
1466
+ });
1467
+ }
1468
+ catch (e) {
1469
+ // A synchronous refusal still contributes a completed wait.
1470
+ waits.push(Promise.resolve());
1471
+ continue;
1472
+ }
1473
+ waits.push(submitted.catch(() => { }));
1474
+ }
1475
+ await Promise.all(waits);
1476
+ return success;
1477
+ }
1478
+ _ensureHeartbeatExecutor() {
1479
+ if (this._heartbeatExecutor == null) {
1480
+ this._heartbeatExecutor = new FixedTaskExecutor(this.concurrentHeartbeatThreadPoolSize);
1481
+ }
1482
+ return this._heartbeatExecutor;
1483
+ }
1484
+ _registerTransactionCheckProcessor() {
1485
+ this.registerFacadeProcessor(RequestCode.CHECK_TRANSACTION_STATE, (cmd, addr) => {
1486
+ const response = RemotingCommand.createResponseCommand(ResponseCode.SUCCESS, '');
1487
+ let msg = null;
1488
+ try {
1489
+ msg = (cmd.body != null && cmd.body.length > 0) ? decodeMessage(cmd.body, true, false) : null;
1490
+ }
1491
+ catch (e) {
1492
+ msg = null;
1493
+ }
1494
+ if (msg == null) {
1495
+ response.code = ResponseCode.SYSTEM_ERROR;
1496
+ response.remark = 'decode message failed';
1497
+ return response;
1498
+ }
1499
+ // transactionId = UNIQ_KEY user property (broker-side check contract).
1500
+ const uniqKey = msg.getProperty(MessageConst.PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX);
1501
+ if (uniqKey != null)
1502
+ msg.transactionId = uniqKey;
1503
+ const group = msg.getProperty(MessageConst.PROPERTY_PRODUCER_GROUP);
1504
+ const producer = group != null ? this.producerTable.get(group) : null;
1505
+ if (producer == null || typeof producer.transactionListener?.checkLocalTransaction !== 'function') {
1506
+ logger.warning('transaction check: no producer registered for group %s', group);
1507
+ return response;
1508
+ }
1509
+ setImmediate(() => {
1510
+ try {
1511
+ const state = producer.transactionListener.checkLocalTransaction(msg) | 0;
1512
+ const header = new EndTransactionRequestHeader();
1513
+ header.producerGroup = group;
1514
+ header.tranStateTableOffset = cmd.extFields['tranStateTableOffset'] != null ? parseInt(cmd.extFields['tranStateTableOffset'], 10) : 0;
1515
+ header.commitLogOffset = cmd.extFields['commitLogOffset'] != null ? parseInt(cmd.extFields['commitLogOffset'], 10) : 0;
1516
+ header.fromTransactionCheck = true;
1517
+ header.msgId = uniqKey != null ? String(uniqKey)
1518
+ : (msg.msgId != null ? msg.msgId : cmd.extFields['msgId']);
1519
+ header.transactionId = msg.transactionId != null ? msg.transactionId
1520
+ : (cmd.extFields['transactionId'] != null ? cmd.extFields['transactionId'] : null);
1521
+ // LocalTransactionState: COMMIT_MESSAGE=0 / ROLLBACK_MESSAGE=1 / UNKNOW=2
1522
+ // (constants live in producer.ts; importing it here would be a cycle).
1523
+ if (state === 0)
1524
+ header.commitOrRollback = MessageSysFlag.TRANSACTION_COMMIT_TYPE;
1525
+ else if (state === 1)
1526
+ header.commitOrRollback = MessageSysFlag.TRANSACTION_ROLLBACK_TYPE;
1527
+ else
1528
+ header.commitOrRollback = MessageSysFlag.TRANSACTION_NOT_TYPE;
1529
+ const request = RemotingCommand.createRequestCommand(RequestCode.END_TRANSACTION, header);
1530
+ // EndTransactionHook wraps the check-back commit/rollback dispatch
1531
+ // with the same before/after discipline the send path applies to
1532
+ // SendMessageHook.
1533
+ const endCtx = new EndTransactionContext(group, msg, addr);
1534
+ endCtx.msgId = header.msgId != null ? String(header.msgId) : null;
1535
+ endCtx.transactionId = header.transactionId;
1536
+ endCtx.transactionState = state;
1537
+ endCtx.fromTransactionCheck = true;
1538
+ const endHooks = hookRegistry.endTransactionHooks;
1539
+ for (const hook of endHooks)
1540
+ hook.endTransactionBefore(endCtx);
1541
+ try {
1542
+ this.remotingClient.invokeOneway(addr, request).catch((e) => {
1543
+ logger.warning('transaction check END_TRANSACTION oneway failed: %s', e.message);
1544
+ });
1545
+ }
1546
+ catch (e) {
1547
+ for (const hook of endHooks)
1548
+ hook.endTransactionAfter(endCtx);
1549
+ throw e;
1550
+ }
1551
+ for (const hook of endHooks)
1552
+ hook.endTransactionAfter(endCtx);
1553
+ }
1554
+ catch (e) {
1555
+ logger.warning('transaction check listener raised: %s', e.message);
1556
+ }
1557
+ });
1558
+ return response;
1559
+ });
1560
+ }
1561
+ // Broker-initiated reply delivery (PUSH_REPLY_MESSAGE_TO_CLIENT, 326): the
1562
+ // broker pushes the REPLY
1563
+ // message of a request to the requesting client. The wire is NOT the 17
1564
+ // segment stored format — the message fields ride in the
1565
+ // ReplyMessageRequestHeader extFields and only the body is binary. The
1566
+ // handler rebuilds the MessageExt, extracts the CORRELATION_ID and resolves
1567
+ // the in-flight request future (atomically removed so the timeout-scan path
1568
+ // cannot double-resolve).
1569
+ _registerReplyMessageProcessor() {
1570
+ this.registerFacadeProcessor(RequestCode.PUSH_REPLY_MESSAGE_TO_CLIENT, (cmd, _addr) => {
1571
+ const response = RemotingCommand.createResponseCommand(ResponseCode.SUCCESS, '');
1572
+ try {
1573
+ const ext = cmd.extFields || {};
1574
+ const msg = new MessageExt();
1575
+ if (ext['topic'] != null)
1576
+ msg.setTopic(String(ext['topic']));
1577
+ msg.setProperties(string2MessageProperties(ext['properties'] != null ? String(ext['properties']) : null));
1578
+ msg.setFlag(ext['flag'] != null ? parseInt(ext['flag'], 10) : 0);
1579
+ msg.setSysFlag(ext['sysFlag'] != null ? parseInt(ext['sysFlag'], 10) : 0);
1580
+ msg.setBornTimestamp(ext['bornTimestamp'] != null ? parseInt(ext['bornTimestamp'], 10) : 0);
1581
+ msg.setReconsumeTimes(ext['reconsumeTimes'] != null ? parseInt(ext['reconsumeTimes'], 10) : 0);
1582
+ if (ext['bornHost'] != null) {
1583
+ msg.setBornHost(String(ext['bornHost']));
1584
+ }
1585
+ if (ext['storeHost'] != null) {
1586
+ msg.setStoreHost(String(ext['storeHost']));
1587
+ }
1588
+ msg.putProperty(MessageConst.PROPERTY_REPLY_MESSAGE_ARRIVE_TIME, String(Date.now()));
1589
+ // The broker compresses a reply body exactly like a send: sysFlag says
1590
+ // which algorithm — don't assume ZLIB (an LZ4-flagged reply would
1591
+ // otherwise crash the inflate).
1592
+ let body = cmd.body != null ? cmd.body : Buffer.alloc(0);
1593
+ if (MessageSysFlag.isCompressed(msg.getSysFlag()) && body.length > 0) {
1594
+ body = decompressFor(body, MessageSysFlag.getCompressionType(msg.getSysFlag()));
1595
+ }
1596
+ msg.setBody(body);
1597
+ const correlationId = msg.getProperty(MessageConst.PROPERTY_CORRELATION_ID);
1598
+ if (correlationId == null) {
1599
+ response.code = ResponseCode.SYSTEM_ERROR;
1600
+ response.remark = 'reply message has no correlation id';
1601
+ return response;
1602
+ }
1603
+ // Atomically remove so only one of the reply-arrival path and the
1604
+ // timeout-scan path can take ownership.
1605
+ const future = REQUEST_FUTURE_HOLDER.removeRequest(correlationId);
1606
+ if (future == null) {
1607
+ logger.warning('receive reply message, but not matched any request, CorrelationId: %s', correlationId);
1608
+ return response;
1609
+ }
1610
+ // Wake the sync caller off the read thread — same hard rule as the
1611
+ // transaction-check processor: never run user code inline.
1612
+ setImmediate(() => future.complete(msg));
1613
+ }
1614
+ catch (e) {
1615
+ logger.warning('process reply message failed: %s', e.message);
1616
+ response.code = ResponseCode.SYSTEM_ERROR;
1617
+ response.remark = 'process reply message fail';
1618
+ }
1619
+ return response;
1620
+ });
1621
+ }
1622
+ shutdown() {
1623
+ this._running = false;
1624
+ if (this._heartbeatTimer != null) {
1625
+ clearInterval(this._heartbeatTimer);
1626
+ this._heartbeatTimer = null;
1627
+ }
1628
+ if (this._routeTimer != null) {
1629
+ clearInterval(this._routeTimer);
1630
+ this._routeTimer = null;
1631
+ }
1632
+ if (this._routeInitialTimer != null) {
1633
+ clearTimeout(this._routeInitialTimer);
1634
+ this._routeInitialTimer = null;
1635
+ }
1636
+ if (this._namesrvTimer != null) {
1637
+ clearInterval(this._namesrvTimer);
1638
+ this._namesrvTimer = null;
1639
+ }
1640
+ if (this._namesrvInitialTimer != null) {
1641
+ clearTimeout(this._namesrvInitialTimer);
1642
+ this._namesrvInitialTimer = null;
1643
+ }
1644
+ if (this._topAddressing != null) {
1645
+ this._topAddressing.clearChangeCallBack();
1646
+ this._topAddressing = null;
1647
+ }
1648
+ if (this._adjustThreadPoolTimer != null) {
1649
+ clearInterval(this._adjustThreadPoolTimer);
1650
+ this._adjustThreadPoolTimer = null;
1651
+ }
1652
+ if (this._persistOffsetTimer != null) {
1653
+ clearInterval(this._persistOffsetTimer);
1654
+ this._persistOffsetTimer = null;
1655
+ }
1656
+ if (this._persistOffsetInitialTimer != null) {
1657
+ clearTimeout(this._persistOffsetInitialTimer);
1658
+ this._persistOffsetInitialTimer = null;
1659
+ }
1660
+ if (this._heartbeatExecutor != null) {
1661
+ this._heartbeatExecutor.shutdown();
1662
+ this._heartbeatExecutor = null;
1663
+ }
1664
+ this.consumerStatsManager.shutdown();
1665
+ try {
1666
+ this.remotingClient.shutdown();
1667
+ }
1668
+ catch (e) { /* ignore */ }
1669
+ for (const acc of this._accumulators || []) {
1670
+ try {
1671
+ acc.stop();
1672
+ }
1673
+ catch (e) { }
1674
+ }
1675
+ }
1676
+ isRunning() { return this._running; }
1677
+ }
1678
+ export default { MQClient, TopicPublishInfo };