@anycon/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +240 -0
  3. package/README.zh-CN.md +188 -0
  4. package/dist/async-queue.d.ts +20 -0
  5. package/dist/async-queue.d.ts.map +1 -0
  6. package/dist/async-queue.js +95 -0
  7. package/dist/async-queue.js.map +1 -0
  8. package/dist/attachments.d.ts +53 -0
  9. package/dist/attachments.d.ts.map +1 -0
  10. package/dist/attachments.js +228 -0
  11. package/dist/attachments.js.map +1 -0
  12. package/dist/client.d.ts +90 -0
  13. package/dist/client.d.ts.map +1 -0
  14. package/dist/client.js +280 -0
  15. package/dist/client.js.map +1 -0
  16. package/dist/connect.d.ts +16 -0
  17. package/dist/connect.d.ts.map +1 -0
  18. package/dist/connect.js +24 -0
  19. package/dist/connect.js.map +1 -0
  20. package/dist/default-storage.d.ts +4 -0
  21. package/dist/default-storage.d.ts.map +1 -0
  22. package/dist/default-storage.js +15 -0
  23. package/dist/default-storage.js.map +1 -0
  24. package/dist/emitter.d.ts +10 -0
  25. package/dist/emitter.d.ts.map +1 -0
  26. package/dist/emitter.js +38 -0
  27. package/dist/emitter.js.map +1 -0
  28. package/dist/errors.d.ts +112 -0
  29. package/dist/errors.d.ts.map +1 -0
  30. package/dist/errors.js +155 -0
  31. package/dist/errors.js.map +1 -0
  32. package/dist/hub.d.ts +85 -0
  33. package/dist/hub.d.ts.map +1 -0
  34. package/dist/hub.js +362 -0
  35. package/dist/hub.js.map +1 -0
  36. package/dist/index.d.ts +34 -0
  37. package/dist/index.d.ts.map +1 -0
  38. package/dist/index.js +32 -0
  39. package/dist/index.js.map +1 -0
  40. package/dist/link.d.ts +87 -0
  41. package/dist/link.d.ts.map +1 -0
  42. package/dist/link.js +628 -0
  43. package/dist/link.js.map +1 -0
  44. package/dist/node.d.ts +213 -0
  45. package/dist/node.d.ts.map +1 -0
  46. package/dist/node.js +474 -0
  47. package/dist/node.js.map +1 -0
  48. package/dist/pair.d.ts +75 -0
  49. package/dist/pair.d.ts.map +1 -0
  50. package/dist/pair.js +390 -0
  51. package/dist/pair.js.map +1 -0
  52. package/dist/permissions.d.ts +65 -0
  53. package/dist/permissions.d.ts.map +1 -0
  54. package/dist/permissions.js +74 -0
  55. package/dist/permissions.js.map +1 -0
  56. package/dist/runtime.d.ts +5 -0
  57. package/dist/runtime.d.ts.map +1 -0
  58. package/dist/runtime.js +15 -0
  59. package/dist/runtime.js.map +1 -0
  60. package/dist/session.d.ts +208 -0
  61. package/dist/session.d.ts.map +1 -0
  62. package/dist/session.js +504 -0
  63. package/dist/session.js.map +1 -0
  64. package/dist/storage-file.d.ts +21 -0
  65. package/dist/storage-file.d.ts.map +1 -0
  66. package/dist/storage-file.js +62 -0
  67. package/dist/storage-file.js.map +1 -0
  68. package/dist/storage-idb.d.ts +19 -0
  69. package/dist/storage-idb.d.ts.map +1 -0
  70. package/dist/storage-idb.js +64 -0
  71. package/dist/storage-idb.js.map +1 -0
  72. package/dist/storage.d.ts +78 -0
  73. package/dist/storage.d.ts.map +1 -0
  74. package/dist/storage.js +163 -0
  75. package/dist/storage.js.map +1 -0
  76. package/dist/version.d.ts +3 -0
  77. package/dist/version.d.ts.map +1 -0
  78. package/dist/version.js +3 -0
  79. package/dist/version.js.map +1 -0
  80. package/dist/ws.d.ts +41 -0
  81. package/dist/ws.d.ts.map +1 -0
  82. package/dist/ws.js +66 -0
  83. package/dist/ws.js.map +1 -0
  84. package/package.json +65 -0
  85. package/src/async-queue.ts +100 -0
  86. package/src/attachments.ts +301 -0
  87. package/src/client.ts +351 -0
  88. package/src/connect.ts +29 -0
  89. package/src/default-storage.ts +14 -0
  90. package/src/emitter.ts +40 -0
  91. package/src/errors.ts +218 -0
  92. package/src/hub.ts +456 -0
  93. package/src/index.ts +143 -0
  94. package/src/link.ts +699 -0
  95. package/src/node.ts +652 -0
  96. package/src/pair.ts +527 -0
  97. package/src/permissions.ts +134 -0
  98. package/src/runtime.ts +14 -0
  99. package/src/session.ts +697 -0
  100. package/src/storage-file.ts +78 -0
  101. package/src/storage-idb.ts +74 -0
  102. package/src/storage.ts +231 -0
  103. package/src/version.ts +2 -0
  104. package/src/ws.ts +94 -0
package/src/link.ts ADDED
@@ -0,0 +1,699 @@
1
+ /**
2
+ * 到一个节点(daemon)的端到端通道:IK 握手(initiator)、Noise Transport、JSON-RPC。
3
+ *
4
+ * 状态机(对应 docs/spec/web.md § 6.4):
5
+ * hub_disconnected → peer_offline → handshaking → ready
6
+ * └→ noise_failed(daemon 不认识我们的公钥:被吊销或 daemon 重装)
7
+ * 每次 `peer_online`(或 `auth_ok.peers_online` 含该节点)都重新握手;`peer_offline` / hub 断线丢弃 Transport。
8
+ *
9
+ * 一条 JSON-RPC 消息 = 一次 `Transport.encrypt` = 一个 `msg_id`;密文按 `frame`(ADR-30)切成一个 `WHOLE` 或
10
+ * 若干 `FRAGMENT`,每片一个 `data` 信封(hub 对单个信封有上限,默认 256 KiB)。Noise 的 nonce 是顺序的,
11
+ * 所以任何一片丢失或乱序都意味着传输失步。hub 对已配对的 `(from, to)` 只会「转发」或「退回 `backpressure`」,
12
+ * 从不静默丢弃,并且「粘住」:一个 `seq` 被退回后,后续信封一律退回,直到被退回的那些 `seq` 按序重发被转发
13
+ * (docs/protocol.md § 3.1)。发送方要配合:
14
+ * - 保留最近发出的信封**原文**(按字节封顶,`RESEND_BUFFER_BYTES`)。凡是可能还在路上、hub 还没来得及回执的
15
+ * 信封都不能丢:发出不满 `RESEND_RETAIN_MS`(10 s)的、以及被退回等着重发的,永不逐出。保留量超过上限时
16
+ * **暂停发新的**(把上限当作在途窗口),等最老的那批过了 10 s 再继续,而不是逐出;
17
+ * - 收到 `backpressure { to, seq }`:暂停向该节点发新东西,攒齐被退回的 `seq`,等 `retry_after_ms`(最近一条
18
+ * `rate_limited` 给的,封顶 30 s;没有就 100–300 ms + 抖动,连续被退回时翻倍,封顶 ×8,最长约 2.4 s),
19
+ * 然后把所有被退回的 `seq` **按升序原样重发**(不重新加密),再发排队的新东西。重发期间又被退回就再来一轮;
20
+ * - 被退回的 `seq` 不在保留缓冲里(hub 报了我们没发过的 `seq`)→ 无法保证顺序,丢弃 Transport、重新 IK 握手;
21
+ * - `handshake` 信封被退回(目标缓冲满或超速):这一封节点没收到。按 `retry_after_ms` 延后再重新发起握手
22
+ * (没有就 300–1000 ms + 抖动,连续被退回时翻倍,封顶 30 s),不立即重发、也不重置,也不占用握手的重试次数;
23
+ * - `rate_limited { retry_after_ms }` 是**整条 hub 连接**(所有节点、含重发)暂停多久的提示,不对应某一封信
24
+ * (伴随 `backpressure` 出现,不再意味着有信封被丢):记在 `HubConnection.rateUntil`,各节点共用;到点之前新的
25
+ * 信封排队,不失败请求、不重新握手;
26
+ * - `dropped { seq, reason }` 每连接每秒至多一条,是「发错东西」的信号(`too_large` = 分片后仍超限,`not_paired` = 配对
27
+ * 关系不对),**不据此重发**:作为 `error` 事件报出,进行中的请求失败,并重新握手;
28
+ * - 接收方解密失败 / 分片乱序 / 收到 `RESET` 时,丢弃 Transport、直接重新 IK 握手。
29
+ */
30
+ import {
31
+ FrameError,
32
+ MAX_MESSAGE,
33
+ Reassembler,
34
+ RpcPeer,
35
+ bytesOfHex,
36
+ decodeFrame,
37
+ encodeFrames,
38
+ type Control,
39
+ type Crypto,
40
+ type DropReason,
41
+ type Envelope,
42
+ type Handshake,
43
+ type Keypair,
44
+ type Transport,
45
+ } from '@anycon/protocol'
46
+
47
+ import { Emitter } from './emitter.js'
48
+ import { AnyconError, ConnectionError, NodeOffline, NodeRejected } from './errors.js'
49
+ import { RATE_WAIT_MAX_MS, type HubConnection } from './hub.js'
50
+ import type { StoredNode } from './storage.js'
51
+
52
+ export type LinkState =
53
+ | 'hub_disconnected'
54
+ | 'peer_offline'
55
+ | 'handshaking'
56
+ | 'ready'
57
+ | 'noise_failed'
58
+ | 'closed'
59
+
60
+ export interface LinkEvents {
61
+ state: [state: LinkState, previous: LinkState]
62
+ /** 握手完成(含每次重连后的重新握手)。 */
63
+ ready: []
64
+ /** 从 ready 掉线(peer_offline / hub 断线 / 重新握手开始)。 */
65
+ offline: []
66
+ /**
67
+ * 非致命的协议问题:hub 丢弃了我们的信封(`dropped`:`too_large` / `not_paired`)。进行中的请求已经失败,
68
+ * 通道会重新握手;这里让调用方有机会记录。限速(`rate_limited`)和背压(`backpressure`)不走这里:
69
+ * hub 不丢信封,SDK 暂停、等、按序重发,请求照常完成。
70
+ */
71
+ error: [error: Error]
72
+ }
73
+
74
+ export interface LinkOptions {
75
+ requestTimeoutMs?: number
76
+ /** 等握手回复的时间,毫秒。默认 5000。 */
77
+ handshakeTimeoutMs?: number
78
+ /** 握手回复超时后的重试次数(含首次)。默认 3。 */
79
+ handshakeAttempts?: number
80
+ /**
81
+ * 保留最近发出的信封原文的字节上限(被退回时按原样重发)。默认 16 MiB;协议要求不低于 8 MiB。
82
+ * 超过上限时**暂停发送新的信封**(当作在途窗口),直到最老的一批过了 `resendRetainMs`,而不是逐出。
83
+ * 调小只会让大消息发得更慢。主要给测试用。
84
+ */
85
+ resendBufferBytes?: number
86
+ /**
87
+ * 发出不满这么久的信封永不逐出(它们可能还在路上,hub 的退回回执可能还没到),毫秒。默认 10000。
88
+ * 主要给测试用。
89
+ */
90
+ resendRetainMs?: number
91
+ }
92
+
93
+ /** 默认的重发缓冲:16 MiB(= `MAX_MESSAGE`,一整条最大的分片消息)。协议下限 8 MiB。 */
94
+ export const RESEND_BUFFER_BYTES = MAX_MESSAGE
95
+ /** 发出不满这么久的信封永不逐出:它们可能还在路上,hub 的退回回执可能还没到(docs/protocol.md § 3.1)。 */
96
+ export const RESEND_RETAIN_MS = 10_000
97
+ /** 被退回之后重发前默认等多久:100–300 ms 随机(抖动),连续被退回时翻倍,最多 ×8(约 2.4 s)。 */
98
+ const RESEND_DELAY_MIN_MS = 100
99
+ const RESEND_DELAY_SPREAD_MS = 200
100
+ const RESEND_BACKOFF_MAX = 8
101
+ /** 距上一轮重发不到这么久又被退回,算「连续被退回」。 */
102
+ const RESEND_BACKOFF_WINDOW_MS = 5000
103
+ /** `handshake` 被退回、又没有 `rate_limited` 给时间时,重新握手前等多久:300–1000 ms(含抖动),连续被退回时翻倍。 */
104
+ const HS_RETRY_MIN_MS = 300
105
+ const HS_RETRY_SPREAD_MS = 700
106
+ /** 握手重试等待的上限(与 `rate_limited` 的封顶一致)。 */
107
+ const HS_RETRY_MAX_MS = RATE_WAIT_MAX_MS
108
+
109
+ export class NodeLink extends Emitter<LinkEvents> {
110
+ readonly rpc: RpcPeer
111
+ readonly node: StoredNode
112
+ readonly #hub: HubConnection
113
+ readonly #crypto: Crypto
114
+ readonly #keypair: Keypair
115
+ readonly #nodePublic: Uint8Array
116
+ readonly #hsTimeoutMs: number
117
+ readonly #hsAttempts: number
118
+ #state: LinkState = 'hub_disconnected'
119
+ #peerOnline = false
120
+ #transport: Transport | undefined
121
+ #handshake: Handshake | undefined
122
+ #hsTimer: ReturnType<typeof setTimeout> | undefined
123
+ #hsTry = 0
124
+ /** 当前这一次握手信封的 seq(被退回时据此认出来);没有在握手时是 0。 */
125
+ #hsSeq = 0
126
+ /** 握手被 hub 退回后,重新握手的定时器。 */
127
+ #hsRetryTimer: ReturnType<typeof setTimeout> | undefined
128
+ /** 重新握手最早在什么时候做(绝对时间,毫秒);`rate_limited` 更晚就等它。 */
129
+ #hsRetryAt = 0
130
+ /** 连续被退回的握手次数(退避用,握手有回复或重新开始时清零)。 */
131
+ #hsBounces = 0
132
+ /**
133
+ * 最近发出的 data 信封的原文(seq → 整帧 + 发出时间,按发送顺序),被退回时按原样重发。
134
+ * 按字节封顶,但**不逐出发出不满 `#retainMs` 的**:超过上限就暂停发新的(`#flushQueued`)。
135
+ */
136
+ readonly #sent = new Map<number, { frame: Uint8Array; at: number }>()
137
+ #sentBytes = 0
138
+ readonly #sentCap: number
139
+ readonly #retainMs: number
140
+ /** hub 退回、还没重发的 seq(`backpressure`)。 */
141
+ readonly #rejected = new Set<number>()
142
+ /** 暂停向该节点发新信封:有被退回的 seq 在等重发,`rate_limited` 的等待还没到点,或在途窗口(保留缓冲)满了。 */
143
+ #paused = false
144
+ /** 这一轮重发最早在什么时候做(绝对时间,毫秒)。 */
145
+ #resendAt = 0
146
+ /** 在途窗口满了的话,最早什么时候有信封过了保留期、腾得出位置(绝对时间,毫秒)。 */
147
+ #windowUntil = 0
148
+ /** 唤醒定时器:到点重发被退回的 seq、再发排队的新信封。 */
149
+ #wakeTimer: ReturnType<typeof setTimeout> | undefined
150
+ /** 连续被退回时的退避倍数(1, 2, 4, 8)。 */
151
+ #backoff = 1
152
+ #lastRoundAt = 0
153
+ /** 这个传输会话开始前(握手期间)发出的 seq 都已过期:迟到的 `backpressure` 不理。 */
154
+ #staleBelow = 0
155
+ /** 暂停期间排队的 data body(已加密、已成帧),恢复后按序发。 */
156
+ #queued: Uint8Array[] = []
157
+ /** 下一条消息的 `msg_id`(u32,本地递增)。 */
158
+ #msgId = 0
159
+ #reassembler = new Reassembler()
160
+ #failure: Error | undefined
161
+
162
+ constructor(
163
+ hub: HubConnection,
164
+ crypto: Crypto,
165
+ keypair: Keypair,
166
+ node: StoredNode,
167
+ options: LinkOptions = {},
168
+ ) {
169
+ super()
170
+ this.#hub = hub
171
+ this.#crypto = crypto
172
+ this.#keypair = keypair
173
+ this.node = node
174
+ this.#nodePublic = bytesOfHex(node.publicKey)
175
+ this.#sentCap = options.resendBufferBytes ?? RESEND_BUFFER_BYTES
176
+ this.#retainMs = options.resendRetainMs ?? RESEND_RETAIN_MS
177
+ this.#hsTimeoutMs = options.handshakeTimeoutMs ?? 5000
178
+ this.#hsAttempts = options.handshakeAttempts ?? 3
179
+ this.rpc = new RpcPeer({
180
+ send: (bytes) => this.#sendData(bytes),
181
+ ...(options.requestTimeoutMs !== undefined ? { timeoutMs: options.requestTimeoutMs } : {}),
182
+ })
183
+ }
184
+
185
+ get state(): LinkState {
186
+ return this.#state
187
+ }
188
+
189
+ get ready(): boolean {
190
+ return this.#state === 'ready'
191
+ }
192
+
193
+ /** 握手失败的原因(`noise_failed` 时)。 */
194
+ get failure(): Error | undefined {
195
+ return this.#failure
196
+ }
197
+
198
+ // ---------- 来自 Client 的事件 ----------
199
+
200
+ /** hub 认证成功(含重连后)。`peersOnline` 是此刻在线的已配对设备。 */
201
+ onHubAuthed(peersOnline: readonly string[]): void {
202
+ if (this.#state === 'closed') return
203
+ this.#peerOnline = peersOnline.includes(this.node.id)
204
+ // 节点在线就直接进入 handshaking,不经过 peer_offline(否则等待方会把中间态当成「已落定」)。
205
+ if (this.#peerOnline) this.#startHandshake()
206
+ else this.#setState('peer_offline')
207
+ }
208
+
209
+ onHubDown(): void {
210
+ if (this.#state === 'closed') return
211
+ this.#peerOnline = false
212
+ this.#dropSession(
213
+ new NodeOffline(this.node.name ?? this.node.id, 'the hub connection was lost'),
214
+ )
215
+ this.#setState('hub_disconnected')
216
+ }
217
+
218
+ onControl(ctrl: Control): void {
219
+ switch (ctrl.type) {
220
+ case 'peer_online':
221
+ if (ctrl.device !== this.node.id) return
222
+ this.#peerOnline = true
223
+ // 每次 online 都重新握手:对端可能重启过,旧 Transport 的计数器已经对不上。
224
+ this.#dropSession(new NodeOffline(this.node.name ?? this.node.id, 'the node reconnected'))
225
+ this.#startHandshake()
226
+ return
227
+ case 'peer_offline':
228
+ if (ctrl.device !== this.node.id) return
229
+ this.#peerOnline = false
230
+ this.#dropSession(new NodeOffline(this.node.name ?? this.node.id))
231
+ this.#setState('peer_offline')
232
+ return
233
+ case 'undeliverable':
234
+ if (ctrl.to !== this.node.id) return
235
+ // 对端已无活跃连接,那一封(以及之后的)都没送到。peer_offline 通常随后到达。
236
+ this.rpc.failAll(
237
+ new NodeOffline(this.node.name ?? this.node.id, 'the node is not reachable'),
238
+ )
239
+ return
240
+ case 'backpressure':
241
+ if (ctrl.to !== this.node.id) return
242
+ this.#onBackpressure(ctrl.seq)
243
+ return
244
+ case 'dropped':
245
+ this.#onDropped(ctrl.seq, ctrl.reason)
246
+ return
247
+ case 'rate_limited':
248
+ // 限速是整条 hub 连接的,不分节点;只是「暂停多久」的提示。时间点已经由 HubConnection 记在 `rateUntil` 上。
249
+ this.#onRateLimited()
250
+ return
251
+ default:
252
+ return
253
+ }
254
+ }
255
+
256
+ onEnvelope(env: Envelope): void {
257
+ if (env.from !== this.node.id) return
258
+ if (env.kind === 'handshake') this.#onHandshake(env.body)
259
+ else if (env.kind === 'data') this.#onData(env.body)
260
+ }
261
+
262
+ /** 释放资源,之后所有请求立刻失败。 */
263
+ close(): void {
264
+ this.#dropSession(new NodeOffline(this.node.name ?? this.node.id, 'the client was closed'))
265
+ this.#setState('closed')
266
+ }
267
+
268
+ // ---------- 握手 ----------
269
+
270
+ #startHandshake(): void {
271
+ this.#clearHsTimer()
272
+ this.#freeHandshake()
273
+ this.#failure = undefined
274
+ this.#hsTry = 0
275
+ this.#hsBounces = 0
276
+ this.#attemptHandshake()
277
+ }
278
+
279
+ #attemptHandshake(): void {
280
+ this.#hsTry += 1
281
+ this.#freeHandshake()
282
+ try {
283
+ const hs = this.#crypto.reconnect('initiator', this.#keypair, this.#nodePublic)
284
+ this.#handshake = hs
285
+ this.#setState('handshaking')
286
+ this.#hsSeq = this.#hub.sendEnvelope(this.node.id, 'handshake', hs.write())
287
+ } catch (cause) {
288
+ this.#freeHandshake()
289
+ if (cause instanceof ConnectionError) {
290
+ // hub 连接不可用:等 onHubAuthed 再来,这不是节点的问题。
291
+ this.#setState('hub_disconnected')
292
+ return
293
+ }
294
+ this.#fail(new NodeRejected(`cannot start the Noise handshake: ${errorMessage(cause)}`))
295
+ return
296
+ }
297
+ this.#hsTimer = setTimeout(() => {
298
+ this.#hsTimer = undefined
299
+ if (this.#state !== 'handshaking') return
300
+ if (this.#hsTry < this.#hsAttempts) this.#attemptHandshake()
301
+ else {
302
+ this.#fail(
303
+ new NodeRejected(
304
+ 'the node did not answer the Noise handshake: this device may have been revoked or the node reinstalled; re-pair it',
305
+ ),
306
+ )
307
+ }
308
+ }, this.#hsTimeoutMs)
309
+ }
310
+
311
+ #onHandshake(body: Uint8Array): void {
312
+ const hs = this.#handshake
313
+ if (this.#state !== 'handshaking' || !hs) return
314
+ try {
315
+ hs.read(body)
316
+ if (!hs.isFinished()) {
317
+ throw new Error('handshake not finished after the reply')
318
+ }
319
+ const transport = hs.intoTransport()
320
+ this.#handshake = undefined
321
+ this.#clearHsTimer()
322
+ if (!sameBytes(transport.remotePublic, this.#nodePublic)) {
323
+ transport.free()
324
+ throw new Error('the node presented a different static key than the one paired')
325
+ }
326
+ this.#transport = transport
327
+ this.#reassembler.clear()
328
+ this.#hsSeq = 0
329
+ this.#hsBounces = 0
330
+ // 握手期间(含更早)发出的 seq 到此为止;之后的 data 信封 seq 都更大。
331
+ this.#staleBelow = this.#hub.lastSeq
332
+ } catch (cause) {
333
+ this.#clearHsTimer()
334
+ // 可能是上一轮握手迟到的回复被新握手读到了:还有次数就重来,用完才判定被拒。
335
+ if (this.#hsTry < this.#hsAttempts) {
336
+ this.#attemptHandshake()
337
+ return
338
+ }
339
+ this.#fail(new NodeRejected(`Noise handshake with the node failed: ${errorMessage(cause)}`))
340
+ return
341
+ }
342
+ this.#setState('ready')
343
+ this.emit('ready')
344
+ }
345
+
346
+ /**
347
+ * hub 退回了我们的 `handshake`(目标缓冲满或这条连接超速):这一封节点没收到,等回复没有意义。
348
+ * 按 `retry_after_ms` 延后再重新握手;没有 `rate_limited` 给时间就 300–1000 ms + 抖动,连续被退回时翻倍,封顶 30 s。
349
+ * 不立即重发(那只会再被退回,形成「握手 → 退回 → 再握手」的循环),也不重置、不占用握手的重试次数。
350
+ */
351
+ #onHandshakeBounced(): void {
352
+ this.#clearHsTimer()
353
+ this.#freeHandshake()
354
+ this.#hsTry = Math.max(0, this.#hsTry - 1) // 没送到节点,不算一次失败的尝试
355
+ const now = Date.now()
356
+ const hinted = this.#hub.rateUntil > now
357
+ const backoff = Math.min(
358
+ HS_RETRY_MAX_MS,
359
+ (HS_RETRY_MIN_MS + jitter(HS_RETRY_SPREAD_MS)) * 2 ** Math.min(this.#hsBounces, 16),
360
+ )
361
+ this.#hsBounces += 1
362
+ this.#hsRetryAt = now + (hinted ? this.#hub.rateUntil - now : backoff)
363
+ this.#armHandshakeRetry()
364
+ }
365
+
366
+ /** (重)装重新握手的定时器:到 `#hsRetryAt`,且不早于 `rate_limited` 给的时间点。 */
367
+ #armHandshakeRetry(): void {
368
+ if (this.#hsRetryTimer !== undefined) clearTimeout(this.#hsRetryTimer)
369
+ const due = Math.max(this.#hsRetryAt, this.#hub.rateUntil)
370
+ this.#hsRetryTimer = setTimeout(
371
+ () => {
372
+ this.#hsRetryTimer = undefined
373
+ if (this.#state !== 'handshaking') return
374
+ if (Math.max(this.#hsRetryAt, this.#hub.rateUntil) - Date.now() > 2) {
375
+ this.#armHandshakeRetry() // 等待期间又收到了更晚的 rate_limited
376
+ return
377
+ }
378
+ this.#attemptHandshake()
379
+ },
380
+ Math.max(0, due - Date.now()),
381
+ )
382
+ }
383
+
384
+ #fail(error: Error): void {
385
+ this.#freeHandshake()
386
+ this.#failure = error
387
+ this.rpc.failAll(error)
388
+ this.#setState('noise_failed')
389
+ }
390
+
391
+ // ---------- 数据 ----------
392
+
393
+ #onData(body: Uint8Array): void {
394
+ const transport = this.#transport
395
+ if (this.#state !== 'ready' || !transport) return
396
+ let ciphertext: Uint8Array | undefined
397
+ try {
398
+ const frame = decodeFrame(body)
399
+ if (frame.kind === 'reset') {
400
+ // 对端发现传输失步,请求我们重新握手。
401
+ this.#resync('the node asked for a new handshake')
402
+ return
403
+ }
404
+ ciphertext = this.#reassembler.push(frame)
405
+ } catch (err) {
406
+ // 分片乱序 / 超限 / 格式坏:传输已经失步。
407
+ this.#resync(err instanceof FrameError ? `bad data frame (${err.code})` : 'bad data frame')
408
+ return
409
+ }
410
+ if (!ciphertext) return // 还在等后续分片
411
+ let plain: Uint8Array
412
+ try {
413
+ plain = transport.decrypt(ciphertext)
414
+ } catch {
415
+ // 计数器对不上或被篡改:丢弃 Transport,重新握手最稳妥(docs/protocol.md § 3.1、crates/crypto/README.md)。
416
+ this.#resync('decryption failed')
417
+ return
418
+ }
419
+ try {
420
+ this.rpc.handle(plain)
421
+ } catch {
422
+ // 对端发来不合法的 JSON-RPC:忽略这一条。
423
+ }
424
+ }
425
+
426
+ /** 传输失步:丢掉 Transport(进行中的请求以 NodeOffline 失败),节点还在线就重新 IK 握手。 */
427
+ #resync(why: string): void {
428
+ this.#dropSession(new NodeOffline(this.node.name ?? this.node.id, `${why}; re-handshaking`))
429
+ if (this.#peerOnline) this.#startHandshake()
430
+ }
431
+
432
+ #sendData(bytes: Uint8Array): void {
433
+ if (this.#state === 'noise_failed') throw this.#failure ?? new NodeRejected()
434
+ const transport = this.#transport
435
+ if (this.#state !== 'ready' || !transport) {
436
+ throw new NodeOffline(this.node.name ?? this.node.id)
437
+ }
438
+ const ciphertext = transport.encrypt(bytes)
439
+ const msgId = this.#msgId
440
+ this.#msgId = (this.#msgId + 1) >>> 0
441
+ // 同一条消息的各片连续发出,不与别的消息交错(接收方的重组器只跟踪一条)。
442
+ this.#queued.push(...encodeFrames(ciphertext, msgId))
443
+ if (this.#paused) return // 暂停中(等重发 / 等 rate_limited 到点 / 在途窗口满):恢复后按序发
444
+ if (Date.now() < this.#hub.rateUntil) {
445
+ // 之前的 rate_limited 还没到点(节点刚连上、或唤醒定时器还没装):也走排队,到点再发。
446
+ this.#paused = true
447
+ this.#arm()
448
+ return
449
+ }
450
+ this.#flushQueued()
451
+ }
452
+
453
+ #emitData(body: Uint8Array): void {
454
+ const sent = this.#hub.sendEncoded(this.node.id, 'data', body)
455
+ this.#sent.set(sent.seq, { frame: sent.frame, at: Date.now() })
456
+ this.#sentBytes += sent.frame.length
457
+ }
458
+
459
+ /**
460
+ * 在途窗口(保留缓冲)满了吗?满了先试着腾位置:只逐出发出已满 `#retainMs`、且不在待重发集合里的信封,
461
+ * 从最老的开始,腾到上限以下为止。凡是更新的一律不动(它们可能还在路上,被退回时要原样重发)。
462
+ * 腾不出来就是满,调用方暂停发新的;`#windowUntil` 记下最早什么时候有信封过期。
463
+ */
464
+ #windowFull(now: number): boolean {
465
+ if (this.#sentBytes < this.#sentCap) return false
466
+ for (const [seq, entry] of this.#sent) {
467
+ if (this.#sentBytes < this.#sentCap || now - entry.at < this.#retainMs) break
468
+ if (this.#rejected.has(seq)) continue // 等着重发的不能丢
469
+ this.#sentBytes -= entry.frame.length
470
+ this.#sent.delete(seq)
471
+ }
472
+ if (this.#sentBytes < this.#sentCap) return false
473
+ let free = now + 50 // 全是等着重发的:重发之后它们才可能过期,稍后再看
474
+ for (const [seq, entry] of this.#sent) {
475
+ if (this.#rejected.has(seq)) continue
476
+ free = entry.at + this.#retainMs
477
+ break
478
+ }
479
+ this.#windowUntil = Math.max(free, now + 1)
480
+ return true
481
+ }
482
+
483
+ /**
484
+ * hub 退回了我们的一封 `data`(目标发送缓冲满,或我们超过速率预算),并从此刻起退回同一 `(from, to)` 的所有
485
+ * 后续信封,直到被退回的这些重发成功。这里攒齐被退回的 `seq`(hub 会为每一封各回一条),暂停发新东西,
486
+ * 过一会儿按升序原样重发。重复的一片对端解不开,所以每个 `seq` 一轮只发一次。
487
+ * 被退回的若是我们的 `handshake`,走 `#onHandshakeBounced`:延后再握手。
488
+ */
489
+ #onBackpressure(seq: number): void {
490
+ if (this.#state === 'handshaking' && seq !== 0 && seq === this.#hsSeq) {
491
+ this.#onHandshakeBounced()
492
+ return
493
+ }
494
+ if (this.#state !== 'ready' || !this.#transport) return // 没有传输,也没什么可重发
495
+ if (seq <= this.#staleBelow) return // 上一个会话 / 握手期间的尾巴
496
+ if (!this.#sent.has(seq)) {
497
+ // hub 说了一封我们没留的信封(我们没发过,或不属于这个会话):无法再保证顺序,丢弃传输重新握手。
498
+ this.#resync('a rejected envelope is no longer buffered for resending')
499
+ return
500
+ }
501
+ const firstOfRound = this.#rejected.size === 0
502
+ this.#rejected.add(seq)
503
+ if (!firstOfRound) return // 并入这一轮,重发时间已经定了
504
+ const now = Date.now()
505
+ const rateUntil = this.#hub.rateUntil
506
+ this.#resendAt = now + (rateUntil > now ? rateUntil - now + jitter(50) : this.#nextDelay(now))
507
+ this.#paused = true
508
+ this.#arm()
509
+ }
510
+
511
+ /** 没有 `rate_limited` 给的时间时的重发等待:100–300 ms + 抖动;连续被退回就翻倍,安静 5 秒后重来。 */
512
+ #nextDelay(now: number): number {
513
+ this.#backoff =
514
+ this.#lastRoundAt > 0 && now - this.#lastRoundAt < RESEND_BACKOFF_WINDOW_MS
515
+ ? Math.min(this.#backoff * 2, RESEND_BACKOFF_MAX)
516
+ : 1
517
+ return (RESEND_DELAY_MIN_MS + jitter(RESEND_DELAY_SPREAD_MS)) * this.#backoff
518
+ }
519
+
520
+ /**
521
+ * hub 对这条连接限速:只是「暂停多久」的提示(`retry_after_ms`),通常伴随 `backpressure`;时间点由
522
+ * `HubConnection` 记在 `rateUntil` 上(整条连接共享,所有节点同时暂停)。
523
+ * 暂停到点之前新的信封排队;被退回的 seq 也等到这个时间点之后再重发;握手被退回后等待重握手的,也顺延。
524
+ * 不会失败进行中的请求,也不重新握手——hub 不再因为限速丢信封,退回的信封都会按序重发。
525
+ */
526
+ #onRateLimited(): void {
527
+ if (this.#state === 'closed') return
528
+ if (this.#hsRetryTimer !== undefined) this.#armHandshakeRetry()
529
+ if (this.#state !== 'ready' || !this.#transport) return // 之后发的时候再按 `rateUntil` 排队
530
+ this.#paused = true
531
+ this.#arm()
532
+ }
533
+
534
+ /** 下一次该醒的时间点:有被退回的 seq 就是重发时间,否则是窗口腾出位置的时间;都不早于 `rate_limited` 给的。 */
535
+ #nextWake(): number {
536
+ const rate = this.#hub.rateUntil
537
+ return this.#rejected.size > 0
538
+ ? Math.max(rate, this.#resendAt)
539
+ : Math.max(rate, this.#windowUntil)
540
+ }
541
+
542
+ /** (重)装唤醒定时器。 */
543
+ #arm(): void {
544
+ if (this.#wakeTimer !== undefined) clearTimeout(this.#wakeTimer)
545
+ this.#wakeTimer = setTimeout(() => this.#wake(), Math.max(0, this.#nextWake() - Date.now()))
546
+ }
547
+
548
+ #wake(): void {
549
+ this.#wakeTimer = undefined
550
+ if (this.#state !== 'ready' || !this.#transport) {
551
+ this.#paused = false
552
+ return
553
+ }
554
+ if (this.#nextWake() - Date.now() > 2) {
555
+ this.#arm() // 等待期间又收到了更晚的 rate_limited
556
+ return
557
+ }
558
+ try {
559
+ if (this.#rejected.size > 0 && !this.#resendRejected()) return
560
+ this.#flushQueued()
561
+ } catch {
562
+ // hub 断线:state 会变,由 onHubDown 清理。
563
+ this.#paused = false
564
+ }
565
+ }
566
+
567
+ /** 把被退回的 seq 按升序原样重发。缓冲里找不到其中任何一个 → 重置传输,返回 false。 */
568
+ #resendRejected(): boolean {
569
+ const seqs = [...this.#rejected].toSorted((a, b) => a - b)
570
+ this.#rejected.clear()
571
+ const entries: Array<{ frame: Uint8Array; at: number }> = []
572
+ for (const seq of seqs) {
573
+ const entry = this.#sent.get(seq)
574
+ if (!entry) {
575
+ this.#resync('a rejected envelope is no longer buffered for resending')
576
+ return false
577
+ }
578
+ entries.push(entry)
579
+ }
580
+ const now = Date.now()
581
+ this.#lastRoundAt = now
582
+ // 原样重发(seq 不变):hub 靠 seq 判断这是不是它在等的那一封。重发之后它们又在路上了,保留期重新算。
583
+ for (const entry of entries) {
584
+ entry.at = now
585
+ this.#hub.sendRaw(entry.frame)
586
+ }
587
+ return true
588
+ }
589
+
590
+ /** 把排队的 body 按序发出去;在途窗口满了就暂停,等腾出位置再继续。 */
591
+ #flushQueued(): void {
592
+ const queued = this.#queued
593
+ let next = 0
594
+ try {
595
+ while (next < queued.length) {
596
+ if (this.#windowFull(Date.now())) {
597
+ this.#paused = true
598
+ this.#arm()
599
+ return
600
+ }
601
+ this.#emitData(queued[next++]!)
602
+ }
603
+ this.#windowUntil = 0
604
+ this.#paused = false
605
+ } finally {
606
+ this.#queued = queued.slice(next)
607
+ }
608
+ }
609
+
610
+ /**
611
+ * hub 丢弃了我们发出的一封 `data`(不是因为对端离线)。hub 对 `dropped` 每连接每秒至多回一条,所以它不是
612
+ * 「每个被丢的 seq 都有」,也不能据此逐条重发——它是「发错东西」的信号。只处理缓冲里有的 `seq`(seq 在整条
613
+ * hub 连接上唯一,其他节点的丢弃与我们无关):
614
+ * - `not_paired`:hub 认为我们和节点没配对(被吊销)→ 通道失败(`NodeRejected`);
615
+ * - `too_large`:分片之后仍超限(hub 的 `ANYCON_MAX_ENVELOPE_BYTES` 比一片还小);
616
+ * - `rate_limited`:(协议里保留,hub 不再发——限速走 `backpressure`)有信封被限速丢了。
617
+ * 后两种都意味着至少丢了一片,Noise 传输已经失步:报 `error` 事件,进行中的请求失败,重新握手。
618
+ */
619
+ #onDropped(seq: number, reason: DropReason): void {
620
+ if (!this.#sent.has(seq)) return
621
+ if (reason === 'not_paired') {
622
+ const err = new NodeRejected('the hub says this device is no longer paired with the node')
623
+ this.emit('error', err)
624
+ this.#fail(err)
625
+ return
626
+ }
627
+ const err =
628
+ reason === 'too_large'
629
+ ? new AnyconError(
630
+ 'envelope_too_large',
631
+ 'the hub dropped a data envelope as too large: its ANYCON_MAX_ENVELOPE_BYTES is below the fragment size',
632
+ )
633
+ : new AnyconError('envelope_dropped', `the hub dropped a data envelope (${reason})`)
634
+ this.emit('error', err)
635
+ this.#dropSession(err)
636
+ if (this.#peerOnline) this.#startHandshake()
637
+ }
638
+
639
+ // ---------- 内部 ----------
640
+
641
+ #dropSession(reason: Error): void {
642
+ this.#clearHsTimer()
643
+ this.#freeHandshake()
644
+ this.#transport?.free()
645
+ this.#transport = undefined
646
+ this.#sent.clear()
647
+ this.#sentBytes = 0
648
+ this.#rejected.clear()
649
+ this.#queued = []
650
+ this.#paused = false
651
+ this.#windowUntil = 0
652
+ this.#backoff = 1
653
+ this.#lastRoundAt = 0
654
+ if (this.#wakeTimer !== undefined) clearTimeout(this.#wakeTimer)
655
+ this.#wakeTimer = undefined
656
+ this.#reassembler.clear()
657
+ this.rpc.failAll(reason)
658
+ }
659
+
660
+ #freeHandshake(): void {
661
+ try {
662
+ this.#handshake?.free()
663
+ } catch {
664
+ // 已被消费
665
+ }
666
+ this.#handshake = undefined
667
+ this.#hsSeq = 0
668
+ }
669
+
670
+ #clearHsTimer(): void {
671
+ if (this.#hsTimer !== undefined) clearTimeout(this.#hsTimer)
672
+ this.#hsTimer = undefined
673
+ if (this.#hsRetryTimer !== undefined) clearTimeout(this.#hsRetryTimer)
674
+ this.#hsRetryTimer = undefined
675
+ }
676
+
677
+ #setState(next: LinkState): void {
678
+ const prev = this.#state
679
+ if (prev === next) return
680
+ this.#state = next
681
+ this.emit('state', next, prev)
682
+ if (prev === 'ready') this.emit('offline')
683
+ }
684
+ }
685
+
686
+ /** `[0, max)` 的随机毫秒数(重发等待的抖动)。 */
687
+ function jitter(max: number): number {
688
+ return Math.random() * max
689
+ }
690
+
691
+ function sameBytes(a: Uint8Array, b: Uint8Array): boolean {
692
+ if (a.length !== b.length) return false
693
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false
694
+ return true
695
+ }
696
+
697
+ function errorMessage(err: unknown): string {
698
+ return err instanceof Error ? err.message : String(err)
699
+ }