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,379 @@
1
+ // -*- coding: utf-8 -*-
2
+ // SOCKS proxy support for the remoting transport layer.
3
+ import net from 'node:net';
4
+ import { Buffer } from 'node:buffer';
5
+ export const SOCKS5_METHOD_NO_AUTH = 0x00;
6
+ export const SOCKS5_METHOD_GSSAPI = 0x01;
7
+ export const SOCKS5_METHOD_USER_PASS = 0x02;
8
+ export const SOCKS5_METHOD_NO_ACCEPTABLE = 0xff;
9
+ export const SOCKS4_GRANTED = 0x5a; // 90
10
+ export const SOCKS5_REPLY_NAMES = {
11
+ 0x01: 'general SOCKS server failure',
12
+ 0x02: 'connection not allowed by ruleset',
13
+ 0x03: 'network unreachable',
14
+ 0x04: 'host unreachable',
15
+ 0x05: 'connection refused',
16
+ 0x06: 'TTL expired',
17
+ 0x07: 'command not supported',
18
+ 0x08: 'address type not supported',
19
+ };
20
+ export function socks5ReplyName(code) {
21
+ return SOCKS5_REPLY_NAMES[code] != null ? SOCKS5_REPLY_NAMES[code] : `unknown reply code`;
22
+ }
23
+ // Normalize the `version` field to 4 | 5. Default 5.
24
+ export function proxyVersion(proxy) {
25
+ const v = proxy.version;
26
+ if (v == null || v === '')
27
+ return 5;
28
+ const s = String(v).trim().toUpperCase();
29
+ if (s === '5' || s === 'SOCKS5')
30
+ return 5;
31
+ if (s === '4' || s === 'SOCKS4' || s === 'SOCKS4A')
32
+ return 4;
33
+ throw new Error(`socks proxy: unsupported version '${String(v)}' (use 4/5 or 'SOCKS4'/'SOCKS5')`);
34
+ }
35
+ // 'host:port' -> [host, port] (IPv6 literal needs brackets, like _parseAddr in client.ts).
36
+ export function parseProxyAddr(addr) {
37
+ if (addr == null || addr === '')
38
+ throw new Error('socks proxy addr is empty (expected host:port)');
39
+ let host;
40
+ let portStr;
41
+ if (addr.startsWith('[')) {
42
+ const idx = addr.indexOf(']');
43
+ if (idx < 0)
44
+ throw new Error(`socks proxy addr must be host:port, got '${addr}'`);
45
+ host = addr.slice(1, idx);
46
+ portStr = addr.slice(idx + 2);
47
+ }
48
+ else {
49
+ const idx = addr.lastIndexOf(':');
50
+ if (idx <= 0)
51
+ throw new Error(`socks proxy addr must be host:port, got '${addr}'`);
52
+ host = addr.slice(0, idx);
53
+ portStr = addr.slice(idx + 1);
54
+ }
55
+ const port = Number(portStr);
56
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
57
+ throw new Error(`socks proxy addr has an invalid port: '${addr}'`);
58
+ }
59
+ if (!host)
60
+ throw new Error(`socks proxy addr has an empty host: '${addr}'`);
61
+ return [host, port];
62
+ }
63
+ function checkPort(port) {
64
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
65
+ throw new Error(`socks proxy: invalid target port ${port}`);
66
+ }
67
+ }
68
+ // ---------------- SOCKS5 (RFC 1928) ----------------
69
+ // Method selection greeting. We offer no-auth always and user/pass when
70
+ // credentials are configured — the same offer space netty's Socks5ProxyHandler has.
71
+ export function buildSocks5Greeting(withUserPass) {
72
+ return withUserPass ? Buffer.from([0x05, 0x02, SOCKS5_METHOD_NO_AUTH, SOCKS5_METHOD_USER_PASS])
73
+ : Buffer.from([0x05, 0x01, SOCKS5_METHOD_NO_AUTH]);
74
+ }
75
+ // Server's method choice: VER METHOD. Returns the chosen method byte.
76
+ export function parseSocks5MethodSelection(buf) {
77
+ if (buf.length < 2 || buf[0] !== 0x05)
78
+ throw new Error('socks5: malformed method selection reply');
79
+ return buf[1];
80
+ }
81
+ // RFC 1929 username/password subnegotiation request: VER(1) ULEN UNAME PLEN PASSWD.
82
+ export function buildSocks5UserPassAuth(username, password) {
83
+ const u = Buffer.from(username, 'utf8');
84
+ const p = Buffer.from(password, 'utf8');
85
+ if (u.length > 255 || p.length > 255)
86
+ throw new Error('socks5: username/password longer than 255 bytes');
87
+ return Buffer.concat([Buffer.from([0x01, u.length]), u, Buffer.from([p.length]), p]);
88
+ }
89
+ // RFC 1929 reply: VER(1) STATUS(1); 0x00 = success.
90
+ export function parseSocks5UserPassReply(buf) {
91
+ if (buf.length < 2 || buf[0] !== 0x01)
92
+ throw new Error('socks5: malformed username/password auth reply');
93
+ if (buf[1] !== 0x00) {
94
+ throw new Error(`socks5: username/password authentication failed (status 0x${buf[1].toString(16).padStart(2, '0')})`);
95
+ }
96
+ }
97
+ // CONNECT request: VER CMD RSV ATYP ADDR PORT. Host may be IPv4/IPv6 literal or
98
+ // a domain name (ATYP 3). SOCKS4a-style: domains stay unresolved on the wire.
99
+ export function buildSocks5Connect(host, port) {
100
+ checkPort(port);
101
+ const head = Buffer.from([0x05, 0x01, 0x00]);
102
+ const tail = Buffer.from([(port >> 8) & 0xff, port & 0xff]);
103
+ if (net.isIPv4(host)) {
104
+ return Buffer.concat([head, Buffer.from([0x01]), Buffer.from(host.split('.').map((x) => parseInt(x, 10))), tail]);
105
+ }
106
+ if (net.isIPv6(host)) {
107
+ return Buffer.concat([head, Buffer.from([0x04]), Buffer.from(new Uint8Array(ip6Bytes(host))), tail]);
108
+ }
109
+ const d = Buffer.from(host, 'utf8');
110
+ if (d.length > 255)
111
+ throw new Error(`socks5: target host longer than 255 bytes: '${host}'`);
112
+ return Buffer.concat([head, Buffer.from([0x03, d.length]), d, tail]);
113
+ }
114
+ function ip6Bytes(host) {
115
+ const bytes = [];
116
+ // net.isIPv6 checked by the caller; node parses via `net.isIPv6`, but there is
117
+ // no public API for the byte form — use URL-ish split on ':' groups.
118
+ const groups = host.replace(/^\[|\]$/g, '').split('::');
119
+ const left = groups[0] === '' ? [] : groups[0].split(':');
120
+ const right = groups.length > 1 ? (groups[1] === '' ? [] : groups[1].split(':')) : [];
121
+ const mid = 8 - left.length - right.length;
122
+ const all = [...left, ...Array.from({ length: Math.max(0, mid) }, () => '0'), ...right];
123
+ for (const g of all) {
124
+ const v = parseInt(g, 16);
125
+ bytes.push((v >> 8) & 0xff, v & 0xff);
126
+ }
127
+ return bytes;
128
+ }
129
+ // Full success reply parse (used by tests and the handshake driver's tail):
130
+ // returns the BND.ADDR/BND.PORT the proxy reports.
131
+ export function parseSocks5ConnectReply(buf) {
132
+ if (buf.length < 8)
133
+ throw new Error('socks5: truncated CONNECT reply');
134
+ if (buf[0] !== 0x05)
135
+ throw new Error(`socks5: bad CONNECT reply version ${buf[0]}`);
136
+ if (buf[1] !== 0x00) {
137
+ throw new Error(`socks5 CONNECT refused (0x${buf[1].toString(16).padStart(2, '0')}): ${socks5ReplyName(buf[1])}`);
138
+ }
139
+ const atyp = buf[3];
140
+ let boundAddr;
141
+ let portOff;
142
+ if (atyp === 0x01) {
143
+ boundAddr = `${buf[4]}.${buf[5]}.${buf[6]}.${buf[7]}`;
144
+ portOff = 8;
145
+ }
146
+ else if (atyp === 0x03) {
147
+ const len = buf[4];
148
+ if (buf.length < 5 + len + 2)
149
+ throw new Error('socks5: truncated CONNECT reply (domain)');
150
+ boundAddr = buf.subarray(5, 5 + len).toString('utf8');
151
+ portOff = 5 + len;
152
+ }
153
+ else if (atyp === 0x04) {
154
+ if (buf.length < 22)
155
+ throw new Error('socks5: truncated CONNECT reply (IPv6)');
156
+ const parts = [];
157
+ for (let i = 0; i < 16; i += 2)
158
+ parts.push(((buf[4 + i] << 8) | buf[5 + i]).toString(16));
159
+ boundAddr = parts.join(':');
160
+ portOff = 20;
161
+ }
162
+ else {
163
+ throw new Error(`socks5: unsupported reply address type 0x${atyp.toString(16)}`);
164
+ }
165
+ return { boundAddr, boundPort: (buf[portOff] << 8) | buf[portOff + 1] };
166
+ }
167
+ // ---------------- SOCKS4 / SOCKS4a ----------------
168
+ // SOCKS4 request: VER CMD DSTPORT DSTIP USERID NULL. A domain name target is
169
+ // sent as SOCKS4a: DSTIP 0.0.0.x (x != 0) sentinel + USERID NULL + DOMAIN NULL.
170
+ export function buildSocks4Connect(host, port, userid = '') {
171
+ checkPort(port);
172
+ const head = Buffer.from([0x04, 0x01, (port >> 8) & 0xff, port & 0xff]);
173
+ const user = Buffer.from(userid, 'utf8');
174
+ if (net.isIPv4(host)) {
175
+ const ip = Buffer.from(host.split('.').map((x) => parseInt(x, 10)));
176
+ return Buffer.concat([head, ip, user, Buffer.from([0x00])]);
177
+ }
178
+ const d = Buffer.from(host, 'utf8');
179
+ if (d.length > 255)
180
+ throw new Error(`socks4a: target host longer than 255 bytes: '${host}'`);
181
+ return Buffer.concat([head, Buffer.from([0x00, 0x00, 0x00, 0x01]), user, Buffer.from([0x00]), d, Buffer.from([0x00])]);
182
+ }
183
+ // SOCKS4 reply: 8 bytes, VN(0) CD; 0x5A (90) = granted.
184
+ export function parseSocks4ConnectReply(buf) {
185
+ if (buf.length < 8 || buf[0] !== 0x00)
186
+ throw new Error('socks4: malformed CONNECT reply');
187
+ const cd = buf[1];
188
+ if (cd === SOCKS4_GRANTED)
189
+ return;
190
+ const names = {
191
+ 0x5b: 'request rejected or failed',
192
+ 0x5c: 'request rejected: identd not reachable',
193
+ 0x5d: 'request rejected: identd user mismatch',
194
+ };
195
+ const why = names[cd] != null ? names[cd] : 'unknown reply code';
196
+ throw new Error(`socks4 CONNECT refused (0x${cd.toString(16)}): ${why}`);
197
+ }
198
+ // ---------------- config parsing (env surface) ----------------
199
+ export function parseSocksProxyConfig(json) {
200
+ if (json == null)
201
+ return null;
202
+ const s = String(json).trim();
203
+ if (s === '' || s === '{}')
204
+ return null;
205
+ let obj;
206
+ try {
207
+ obj = JSON.parse(s);
208
+ }
209
+ catch (e) {
210
+ throw new Error(`socks proxy config is not valid JSON: ${e.message}`);
211
+ }
212
+ if (obj == null || typeof obj !== 'object' || Array.isArray(obj))
213
+ return null;
214
+ if (typeof obj['addr'] === 'string')
215
+ return obj;
216
+ for (const v of Object.values(obj)) {
217
+ if (v != null && typeof v === 'object' && typeof v['addr'] === 'string') {
218
+ return v;
219
+ }
220
+ }
221
+ return null;
222
+ }
223
+ // ---------------- handshake driver ----------------
224
+ // Streaming reader over the proxy socket: buffers inbound bytes across reads so
225
+ // no data is lost between handshake steps, and pushes unconsumed bytes back via
226
+ // socket.unshift() on release (the tunnel may carry the first remoting frame in
227
+ // the same TCP segment as the handshake reply).
228
+ class _SocksStreamReader {
229
+ buf = Buffer.alloc(0);
230
+ failed = null;
231
+ closed = false;
232
+ waiter = null;
233
+ sock;
234
+ onData;
235
+ onErr;
236
+ onClose;
237
+ constructor(sock) {
238
+ this.sock = sock;
239
+ this.onData = (c) => {
240
+ this.buf = this.buf.length ? Buffer.concat([this.buf, Buffer.from(c)]) : Buffer.from(c);
241
+ this._maybe();
242
+ };
243
+ this.onErr = (e) => {
244
+ this.failed = new Error(`socks proxy socket error: ${e.message}`);
245
+ this._fail(this.failed);
246
+ };
247
+ this.onClose = () => {
248
+ this.closed = true;
249
+ this._fail(new Error('socks proxy closed the connection during handshake'));
250
+ };
251
+ sock.on('data', this.onData);
252
+ sock.on('error', this.onErr);
253
+ sock.on('close', this.onClose);
254
+ }
255
+ _fail(e) {
256
+ if (this.waiter) {
257
+ clearTimeout(this.waiter.timer);
258
+ const w = this.waiter;
259
+ this.waiter = null;
260
+ w.reject(e);
261
+ }
262
+ }
263
+ _maybe() {
264
+ if (!this.waiter || this.buf.length < this.waiter.n)
265
+ return;
266
+ const w = this.waiter;
267
+ this.waiter = null;
268
+ clearTimeout(w.timer);
269
+ const out = Buffer.from(this.buf.subarray(0, w.n));
270
+ this.buf = this.buf.subarray(w.n);
271
+ w.resolve(out);
272
+ }
273
+ read(n, budgetMs) {
274
+ if (this.failed)
275
+ return Promise.reject(this.failed);
276
+ if (this.closed)
277
+ return Promise.reject(new Error('socks proxy closed the connection during handshake'));
278
+ if (this.buf.length >= n) {
279
+ const out = Buffer.from(this.buf.subarray(0, n));
280
+ this.buf = this.buf.subarray(n);
281
+ return Promise.resolve(out);
282
+ }
283
+ return new Promise((resolve, reject) => {
284
+ const timer = setTimeout(() => {
285
+ this.waiter = null;
286
+ reject(new Error(`socks handshake timed out after ${budgetMs}ms`));
287
+ }, budgetMs);
288
+ this.waiter = { n, resolve, reject, timer };
289
+ });
290
+ }
291
+ // Detach our listeners and push unconsumed bytes back into the socket so the
292
+ // caller's own 'data' handler (frame parser) sees them.
293
+ release() {
294
+ this.sock.removeListener('data', this.onData);
295
+ this.sock.removeListener('error', this.onErr);
296
+ this.sock.removeListener('close', this.onClose);
297
+ if (this.waiter) {
298
+ clearTimeout(this.waiter.timer);
299
+ this.waiter = null;
300
+ }
301
+ if (this.buf.length) {
302
+ try {
303
+ this.sock.unshift(this.buf);
304
+ }
305
+ catch (e) { /* stream already gone */ }
306
+ this.buf = Buffer.alloc(0);
307
+ }
308
+ }
309
+ }
310
+ function writeAll(sock, buf) {
311
+ return new Promise((resolve, reject) => {
312
+ sock.write(buf, (err) => (err ? reject(err) : resolve()));
313
+ });
314
+ }
315
+ function assertOk(verByte, what) {
316
+ if (verByte !== 0x05)
317
+ throw new Error(`socks5: bad ${what} reply version ${verByte}`);
318
+ }
319
+ async function _socks5Handshake(reader, proxy, host, port, left) {
320
+ const hasAuth = (proxy.username != null && proxy.username !== '')
321
+ || (proxy.password != null && proxy.password !== '');
322
+ await writeAll(reader.sock, buildSocks5Greeting(hasAuth));
323
+ const method = parseSocks5MethodSelection(await reader.read(2, left()));
324
+ if (method === SOCKS5_METHOD_NO_ACCEPTABLE) {
325
+ throw new Error(hasAuth
326
+ ? 'socks5: proxy accepts none of the offered auth methods'
327
+ : 'socks5: proxy requires an auth method but no username/password is configured');
328
+ }
329
+ if (method === SOCKS5_METHOD_USER_PASS) {
330
+ if (!hasAuth)
331
+ throw new Error('socks5: proxy demands username/password auth but none is configured');
332
+ await writeAll(reader.sock, buildSocks5UserPassAuth(proxy.username ?? '', proxy.password ?? ''));
333
+ parseSocks5UserPassReply(await reader.read(2, left()));
334
+ }
335
+ else if (method !== SOCKS5_METHOD_NO_AUTH) {
336
+ throw new Error(`socks5: proxy chose unsupported auth method 0x${method.toString(16).padStart(2, '0')}`);
337
+ }
338
+ await writeAll(reader.sock, buildSocks5Connect(host, port));
339
+ const head = await reader.read(4, left());
340
+ assertOk(head[0], 'CONNECT');
341
+ if (head[1] !== 0x00) {
342
+ throw new Error(`socks5 CONNECT refused (0x${head[1].toString(16).padStart(2, '0')}): ${socks5ReplyName(head[1])}`);
343
+ }
344
+ // Drain the BND.ADDR/BND.PORT tail (length depends on ATYP; domain needs its
345
+ // length byte first).
346
+ if (head[3] === 0x03) {
347
+ const len = (await reader.read(1, left()))[0];
348
+ if (len > 0)
349
+ await reader.read(len + 2, left());
350
+ else
351
+ await reader.read(2, left());
352
+ }
353
+ else if (head[3] === 0x01) {
354
+ await reader.read(6, left());
355
+ }
356
+ else if (head[3] === 0x04) {
357
+ await reader.read(18, left());
358
+ }
359
+ }
360
+ async function _socks4Handshake(reader, proxy, host, port, left) {
361
+ await writeAll(reader.sock, buildSocks4Connect(host, port, proxy.username ?? ''));
362
+ parseSocks4ConnectReply(await reader.read(8, left()));
363
+ }
364
+ export async function socksHandshake(socket, proxy, targetHost, targetPort, timeoutMillis = 10000) {
365
+ const version = proxyVersion(proxy); // validates addr too
366
+ parseProxyAddr(proxy.addr);
367
+ const reader = new _SocksStreamReader(socket);
368
+ const deadline = Date.now() + Math.max(1, timeoutMillis);
369
+ const left = () => Math.max(1, deadline - Date.now());
370
+ try {
371
+ if (version === 5)
372
+ await _socks5Handshake(reader, proxy, targetHost, targetPort, left);
373
+ else
374
+ await _socks4Handshake(reader, proxy, targetHost, targetPort, left);
375
+ }
376
+ finally {
377
+ reader.release();
378
+ }
379
+ }
@@ -0,0 +1,49 @@
1
+ import { MessageQueue } from '../common/message.js';
2
+ import type { TopicRouteData } from './route.js';
3
+ export declare const METADATA_SCOPE_GLOBAL = "__global__";
4
+ export declare const LOGICAL_QUEUE_MOCK_BROKER_PREFIX = "__syslo__";
5
+ export declare const LOGICAL_QUEUE_MOCK_BROKER_NAME_NOT_EXIST = "__syslo__none__";
6
+ export declare function isLogicalQueueMockBrokerName(brokerName: string): boolean;
7
+ export declare function getMockBrokerName(scope: string): string;
8
+ export declare class LogicQueueMappingItem {
9
+ gen: number;
10
+ queueId: number;
11
+ bname: string;
12
+ logicOffset: number;
13
+ startOffset: number;
14
+ endOffset: number;
15
+ timeOfStart: number;
16
+ timeOfEnd: number;
17
+ constructor(gen?: number, queueId?: number, bname?: string, logicOffset?: number, startOffset?: number, endOffset?: number, timeOfStart?: number, timeOfEnd?: number);
18
+ isBrokered(): boolean;
19
+ toDict(): Record<string, any>;
20
+ static fromDict(d: Record<string, any> | null | undefined): LogicQueueMappingItem;
21
+ }
22
+ export declare class TopicQueueMappingInfo {
23
+ topic: string;
24
+ scope: string;
25
+ totalQueues: number;
26
+ bname: string;
27
+ epoch: number;
28
+ dirty: boolean;
29
+ currIdMap: Record<string, number>;
30
+ constructor(topic?: string, totalQueues?: number, bname?: string, epoch?: number, scope?: string, dirty?: boolean, currIdMap?: Record<string, number> | null);
31
+ toDict(): Record<string, any>;
32
+ static fromDict(d: Record<string, any> | null | undefined): TopicQueueMappingInfo;
33
+ }
34
+ export declare class TopicQueueMappingDetail {
35
+ topic: string;
36
+ scope: string;
37
+ totalQueues: number;
38
+ bname: string;
39
+ epoch: number;
40
+ dirty: boolean;
41
+ currIdMap: Record<string, number>;
42
+ hostedQueues: Record<string, LogicQueueMappingItem[]>;
43
+ constructor(topic?: string, totalQueues?: number, bname?: string, epoch?: number, scope?: string, dirty?: boolean, currIdMap?: Record<string, number> | null, hostedQueues?: Record<string, LogicQueueMappingItem[]> | null);
44
+ toDict(): Record<string, any>;
45
+ encode(): Buffer;
46
+ static fromDict(d: Record<string, any> | null | undefined): TopicQueueMappingDetail;
47
+ }
48
+ export declare function topicRouteData2EndpointsForStaticTopic(topic: string, route: TopicRouteData): Map<MessageQueue, string>;
49
+ export declare function endpointsToKeyStrings(endpoints: Map<MessageQueue, string>): Map<string, string>;
@@ -0,0 +1,244 @@
1
+ // -*- coding: utf-8 -*-
2
+ // Static topic (unitized topic) mapping support.
3
+ import { MessageQueue } from "../common/message.js";
4
+ import { RemotingSerializable } from "./serialize.js";
5
+ // MixAll.METADATA_SCOPE_GLOBAL — the scope every route-side mapping info uses
6
+ // unless a migration explicitly scoped it otherwise.
7
+ export const METADATA_SCOPE_GLOBAL = '__global__';
8
+ // MixAll.LOGICAL_QUEUE_MOCK_BROKER_PREFIX — logical MessageQueues carry a
9
+ // broker name of this prefix + scope; the real broker is resolved through the
10
+ // topicEndPointsTable.
11
+ export const LOGICAL_QUEUE_MOCK_BROKER_PREFIX = '__syslo__';
12
+ // MixAll.LOGICAL_QUEUE_MOCK_BROKER_NAME_NOT_EXIST — a logical queue whose
13
+ // mapping info lists no hosting broker maps to this sentinel.
14
+ export const LOGICAL_QUEUE_MOCK_BROKER_NAME_NOT_EXIST = '__syslo__none__';
15
+ export function isLogicalQueueMockBrokerName(brokerName) {
16
+ return typeof brokerName === 'string' && brokerName.startsWith(LOGICAL_QUEUE_MOCK_BROKER_PREFIX);
17
+ }
18
+ // TopicQueueMappingUtils.getMockBrokerName: "__global__" (the scope) loses its
19
+ // first two chars, every other scope is prefixed verbatim.
20
+ export function getMockBrokerName(scope) {
21
+ if (scope === METADATA_SCOPE_GLOBAL) {
22
+ return LOGICAL_QUEUE_MOCK_BROKER_PREFIX + scope.substring(2);
23
+ }
24
+ return LOGICAL_QUEUE_MOCK_BROKER_PREFIX + scope;
25
+ }
26
+ // ---------------------------------------------------------------------------
27
+ // LogicQueueMappingItem — one generation of a logical queue on one broker.
28
+ // ---------------------------------------------------------------------------
29
+ export class LogicQueueMappingItem {
30
+ gen = 0; // immutable generation
31
+ queueId = 0; // immutable physical queue id on bname
32
+ bname = ''; // immutable hosting broker name
33
+ logicOffset = 0; // start of the logic offset; changed by command once
34
+ startOffset = 0; // start of the physical offset, always 0, immutable
35
+ endOffset = -1; // end of the physical offset, excluded, -1 = open
36
+ timeOfStart = -1; // mutable, reserved
37
+ timeOfEnd = -1; // mutable, reserved
38
+ constructor(gen = 0, queueId = 0, bname = '', logicOffset = 0, startOffset = 0, endOffset = -1, timeOfStart = -1, timeOfEnd = -1) {
39
+ this.gen = gen;
40
+ this.queueId = queueId;
41
+ this.bname = bname;
42
+ this.logicOffset = logicOffset;
43
+ this.startOffset = startOffset;
44
+ this.endOffset = endOffset;
45
+ this.timeOfStart = timeOfStart;
46
+ this.timeOfEnd = timeOfEnd;
47
+ }
48
+ // The last item of a hostedQueues list is the CURRENT generation.
49
+ isBrokered() {
50
+ return this.bname !== '';
51
+ }
52
+ toDict() {
53
+ return {
54
+ gen: this.gen,
55
+ queueId: this.queueId,
56
+ bname: this.bname,
57
+ logicOffset: this.logicOffset,
58
+ startOffset: this.startOffset,
59
+ endOffset: this.endOffset,
60
+ timeOfStart: this.timeOfStart,
61
+ timeOfEnd: this.timeOfEnd,
62
+ };
63
+ }
64
+ static fromDict(d) {
65
+ d = d || {};
66
+ return new LogicQueueMappingItem(d['gen'] != null ? d['gen'] : 0, d['queueId'] != null ? d['queueId'] : 0, d['bname'] != null ? d['bname'] : '', d['logicOffset'] != null ? d['logicOffset'] : 0, d['startOffset'] != null ? d['startOffset'] : 0, d['endOffset'] != null ? d['endOffset'] : -1, d['timeOfStart'] != null ? d['timeOfStart'] : -1, d['timeOfEnd'] != null ? d['timeOfEnd'] : -1);
67
+ }
68
+ }
69
+ // ---------------------------------------------------------------------------
70
+ // TopicQueueMappingInfo — the per-broker view carried INSIDE the route.
71
+ // ---------------------------------------------------------------------------
72
+ export class TopicQueueMappingInfo {
73
+ topic = '';
74
+ scope = METADATA_SCOPE_GLOBAL;
75
+ totalQueues = 0;
76
+ bname = '';
77
+ epoch = 0;
78
+ dirty = false;
79
+ // logicId -> physicalId, JSON keys are stringified ints.
80
+ currIdMap = {};
81
+ constructor(topic = '', totalQueues = 0, bname = '', epoch = 0, scope = METADATA_SCOPE_GLOBAL, dirty = false, currIdMap = null) {
82
+ this.topic = topic;
83
+ this.totalQueues = totalQueues;
84
+ this.bname = bname;
85
+ this.epoch = epoch;
86
+ this.scope = scope;
87
+ this.dirty = dirty;
88
+ this.currIdMap = currIdMap != null ? currIdMap : {};
89
+ }
90
+ toDict() {
91
+ const curr = {};
92
+ for (const [k, v] of Object.entries(this.currIdMap))
93
+ curr[String(k)] = v;
94
+ return {
95
+ topic: this.topic,
96
+ scope: this.scope,
97
+ totalQueues: this.totalQueues,
98
+ bname: this.bname,
99
+ epoch: this.epoch,
100
+ dirty: this.dirty,
101
+ currIdMap: curr,
102
+ };
103
+ }
104
+ static fromDict(d) {
105
+ d = d || {};
106
+ const curr = {};
107
+ const rawCurr = d['currIdMap'] || {};
108
+ for (const [k, v] of Object.entries(rawCurr))
109
+ curr[String(k)] = Number(v);
110
+ return new TopicQueueMappingInfo(d['topic'] != null ? d['topic'] : '', d['totalQueues'] != null ? d['totalQueues'] : 0, d['bname'] != null ? d['bname'] : '', d['epoch'] != null ? d['epoch'] : 0, d['scope'] != null ? d['scope'] : METADATA_SCOPE_GLOBAL, d['dirty'] === true, curr);
111
+ }
112
+ }
113
+ // ---------------------------------------------------------------------------
114
+ // TopicQueueMappingDetail — the full mapping document a static-topic CREATE
115
+ // carries in its body (one broker's shard of it).
116
+ // ---------------------------------------------------------------------------
117
+ export class TopicQueueMappingDetail {
118
+ topic = '';
119
+ scope = METADATA_SCOPE_GLOBAL;
120
+ totalQueues = 0;
121
+ bname = '';
122
+ epoch = 0;
123
+ dirty = false;
124
+ // globalId -> physicalId on THIS broker, JSON keys are stringified ints.
125
+ currIdMap = {};
126
+ // globalId -> generation list; JSON keys are stringified ints.
127
+ hostedQueues = {};
128
+ constructor(topic = '', totalQueues = 0, bname = '', epoch = 0, scope = METADATA_SCOPE_GLOBAL, dirty = false, currIdMap = null, hostedQueues = null) {
129
+ this.topic = topic;
130
+ this.totalQueues = totalQueues;
131
+ this.bname = bname;
132
+ this.epoch = epoch;
133
+ this.scope = scope;
134
+ this.dirty = dirty;
135
+ this.currIdMap = currIdMap != null ? currIdMap : {};
136
+ this.hostedQueues = hostedQueues != null ? hostedQueues : {};
137
+ }
138
+ toDict() {
139
+ const curr = {};
140
+ for (const [k, v] of Object.entries(this.currIdMap))
141
+ curr[String(k)] = v;
142
+ const hosted = {};
143
+ for (const [globalId, items] of Object.entries(this.hostedQueues)) {
144
+ hosted[String(globalId)] = items.map((it) => it.toDict());
145
+ }
146
+ return {
147
+ topic: this.topic,
148
+ scope: this.scope,
149
+ totalQueues: this.totalQueues,
150
+ bname: this.bname,
151
+ epoch: this.epoch,
152
+ dirty: this.dirty,
153
+ currIdMap: curr,
154
+ hostedQueues: hosted,
155
+ };
156
+ }
157
+ encode() {
158
+ const data = RemotingSerializable.encode(this.toDict());
159
+ return data != null ? data : Buffer.alloc(0);
160
+ }
161
+ static fromDict(d) {
162
+ d = d || {};
163
+ const curr = {};
164
+ for (const [k, v] of Object.entries(d['currIdMap'] || {}))
165
+ curr[String(k)] = Number(v);
166
+ const hosted = {};
167
+ for (const [globalId, items] of Object.entries(d['hostedQueues'] || {})) {
168
+ hosted[String(globalId)] = items.map((it) => LogicQueueMappingItem.fromDict(it));
169
+ }
170
+ return new TopicQueueMappingDetail(d['topic'] != null ? d['topic'] : '', d['totalQueues'] != null ? d['totalQueues'] : 0, d['bname'] != null ? d['bname'] : '', d['epoch'] != null ? d['epoch'] : 0, d['scope'] != null ? d['scope'] : METADATA_SCOPE_GLOBAL, d['dirty'] === true, curr, hosted);
171
+ }
172
+ }
173
+ // ---------------------------------------------------------------------------
174
+ // topicRouteData2EndpointsForStaticTopic — the pure routing core.
175
+ // ---------------------------------------------------------------------------
176
+ // Port of ClientMetadata.topicRouteData2EndpointsForStaticTopic: from the
177
+ // route's topicQueueMappingByBroker (brokerName -> TopicQueueMappingInfo JSON)
178
+ // build the LOGICAL queue set — MessageQueue(topic, mockBrokerName(scope),
179
+ // globalId) -> the REAL broker name hosting it ("__syslo__none__" when the
180
+ // logical queue exists in the totals but no broker hosts it yet).
181
+ export function topicRouteData2EndpointsForStaticTopic(topic, route) {
182
+ const endpointsOfBroker = new Map();
183
+ const mappingByBroker = route.topicQueueMappingByBroker;
184
+ if (mappingByBroker == null || Object.keys(mappingByBroker).length === 0) {
185
+ return endpointsOfBroker;
186
+ }
187
+ const infosByScope = new Map();
188
+ for (const [brokerName, raw] of Object.entries(mappingByBroker)) {
189
+ const info = TopicQueueMappingInfo.fromDict(raw);
190
+ if (info.scope != null) {
191
+ let byScope = infosByScope.get(info.scope);
192
+ if (byScope == null) {
193
+ byScope = new Map();
194
+ infosByScope.set(info.scope, byScope);
195
+ }
196
+ byScope.set(brokerName, info);
197
+ }
198
+ }
199
+ for (const [scope, infoMap] of infosByScope.entries()) {
200
+ // epoch-desc; Array.prototype.sort is stable (spec), matching
201
+ // Collections.sort's tie behaviour.
202
+ const mappingInfos = Array.from(infoMap.entries())
203
+ .sort(([, a], [, b]) => b.epoch - a.epoch);
204
+ let maxTotalNums = 0;
205
+ const maxTotalNumOfEpoch = -1;
206
+ const mqKey = (mq) => `${mq.topic}@${mq.brokerName}@${mq.queueId}`;
207
+ const mqEndPoints = new Map();
208
+ for (const [, info] of mappingInfos) {
209
+ if (info.epoch >= maxTotalNumOfEpoch && info.totalQueues > maxTotalNums) {
210
+ maxTotalNums = info.totalQueues;
211
+ }
212
+ for (const [logicIdStr, physicalId] of Object.entries(info.currIdMap)) {
213
+ const globalId = parseInt(logicIdStr, 10);
214
+ const mq = new MessageQueue(topic, getMockBrokerName(scope), globalId);
215
+ const oldInfo = mqEndPoints.get(mqKey(mq));
216
+ if (oldInfo == null || oldInfo.epoch <= info.epoch) {
217
+ mqEndPoints.set(mqKey(mq), info);
218
+ }
219
+ }
220
+ }
221
+ // Accomplish the static logic queues: every id below the total exists;
222
+ // unhosted ones point at the NOT_EXIST sentinel.
223
+ for (let i = 0; i < maxTotalNums; i++) {
224
+ const mq = new MessageQueue(topic, getMockBrokerName(scope), i);
225
+ const holder = mqEndPoints.get(mqKey(mq));
226
+ if (holder == null) {
227
+ endpointsOfBroker.set(mq, LOGICAL_QUEUE_MOCK_BROKER_NAME_NOT_EXIST);
228
+ }
229
+ else {
230
+ endpointsOfBroker.set(mq, holder.bname);
231
+ }
232
+ }
233
+ }
234
+ return endpointsOfBroker;
235
+ }
236
+ // Map<MessageQueue, string> keyed by MessageQueue OBJECT — expose a plain
237
+ // [key-string -> realBrokerName] view for tests and logging.
238
+ export function endpointsToKeyStrings(endpoints) {
239
+ const out = new Map();
240
+ for (const [mq, real] of endpoints.entries()) {
241
+ out.set(`${mq.topic}@${mq.brokerName}@${mq.queueId}`, real);
242
+ }
243
+ return out;
244
+ }