@w3lib/solana-batch-call 0.0.0-stage → 0.2.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 (49) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/LICENSE +21 -0
  3. package/README.md +270 -2
  4. package/dist/address.d.ts +20 -0
  5. package/dist/address.d.ts.map +1 -0
  6. package/dist/address.js +120 -0
  7. package/dist/address.js.map +1 -0
  8. package/dist/client.d.ts +190 -0
  9. package/dist/client.d.ts.map +1 -0
  10. package/dist/client.js +971 -0
  11. package/dist/client.js.map +1 -0
  12. package/dist/constants.d.ts +21 -0
  13. package/dist/constants.d.ts.map +1 -0
  14. package/dist/constants.js +35 -0
  15. package/dist/constants.js.map +1 -0
  16. package/dist/index.d.ts +9 -0
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/index.js +9 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/layout.d.ts +84 -0
  21. package/dist/layout.d.ts.map +1 -0
  22. package/dist/layout.js +237 -0
  23. package/dist/layout.js.map +1 -0
  24. package/dist/rpc.d.ts +115 -0
  25. package/dist/rpc.d.ts.map +1 -0
  26. package/dist/rpc.js +458 -0
  27. package/dist/rpc.js.map +1 -0
  28. package/dist/shortcuts.d.ts +93 -0
  29. package/dist/shortcuts.d.ts.map +1 -0
  30. package/dist/shortcuts.js +281 -0
  31. package/dist/shortcuts.js.map +1 -0
  32. package/dist/source.d.ts +35 -0
  33. package/dist/source.d.ts.map +1 -0
  34. package/dist/source.js +124 -0
  35. package/dist/source.js.map +1 -0
  36. package/dist/types.d.ts +155 -0
  37. package/dist/types.d.ts.map +1 -0
  38. package/dist/types.js +2 -0
  39. package/dist/types.js.map +1 -0
  40. package/package.json +60 -4
  41. package/src/address.ts +134 -0
  42. package/src/client.ts +1298 -0
  43. package/src/constants.ts +41 -0
  44. package/src/index.ts +98 -0
  45. package/src/layout.ts +320 -0
  46. package/src/rpc.ts +549 -0
  47. package/src/shortcuts.ts +367 -0
  48. package/src/source.ts +149 -0
  49. package/src/types.ts +164 -0
package/src/rpc.ts ADDED
@@ -0,0 +1,549 @@
1
+ /** 最小的 JSON-RPC 传输接口:可以传入自己的实现(如包一层 @solana/kit 的 rpc) */
2
+ export interface RpcTransport {
3
+ request<T = unknown>(method: string, params?: readonly unknown[]): Promise<T>
4
+ /** 节点名称,用于 AllNodesFailedError / onRequest 里标识节点;不传时自定义传输显示为 'custom' */
5
+ readonly label?: string
6
+ }
7
+
8
+ /** 节点返回的 JSON-RPC 错误 */
9
+ export class RpcError extends Error {
10
+ readonly code: number | undefined
11
+ readonly data: unknown
12
+ /** 是否是节点自身的限制(限频、需要 API Key、禁止访问等),换节点可能成功 */
13
+ readonly nodeFault: boolean
14
+
15
+ constructor(message: string, code?: number, data?: unknown) {
16
+ super(message)
17
+ this.name = 'RpcError'
18
+ this.code = code
19
+ this.data = data
20
+ this.nodeFault =
21
+ code === 403 ||
22
+ code === 429 ||
23
+ code === -32005 ||
24
+ // 节点高度没到 minContextSlot:换节点可能成功
25
+ code === MIN_CONTEXT_SLOT_NOT_REACHED ||
26
+ /minimum context slot/i.test(message) ||
27
+ /forbidden|blocked|personal token|api.?key|rate.?limit|too many|not allowed|unauthori[sz]ed|limit exceeded|disabled|not available|not supported/i.test(message)
28
+ }
29
+ }
30
+
31
+ /** HTTP 层错误(非 2xx、网络错误、超时) */
32
+ export class HttpError extends Error {
33
+ readonly status: number | undefined
34
+ /** 请求超时(HttpRpcOptions.timeout) */
35
+ readonly timeout: boolean
36
+
37
+ constructor(message: string, status?: number, timeout = false) {
38
+ super(message)
39
+ this.name = 'HttpError'
40
+ this.status = status
41
+ this.timeout = timeout
42
+ }
43
+ }
44
+
45
+ /** JSON-RPC 错误码:节点高度还没到请求的 minContextSlot */
46
+ export const MIN_CONTEXT_SLOT_NOT_REACHED = -32016
47
+
48
+ /** 是否是请求超时(HttpRpc 的超时,或自定义传输抛出的 TimeoutError) */
49
+ export function isTimeout(err: unknown): boolean {
50
+ return (err instanceof HttpError && err.timeout) || (err as { name?: unknown } | null)?.name === 'TimeoutError'
51
+ }
52
+
53
+ /** 是否是“节点高度没到 minContextSlot”(所有节点都落后时也算) */
54
+ export function isBehind(err: unknown): boolean {
55
+ if (err instanceof AllNodesFailedError) {
56
+ return err.errors.length > 0 && err.errors.every((e) => isBehind(e.error))
57
+ }
58
+ return err instanceof RpcError && (err.code === MIN_CONTEXT_SLOT_NOT_REACHED || /minimum context slot/i.test(err.message))
59
+ }
60
+
61
+ /**
62
+ * 多节点时所有节点都失败(都是节点问题)。errors 是各节点的错误,按尝试顺序;
63
+ * node 是节点名称(URL 只保留 host,不会带出 path / query 里的 API Key)
64
+ */
65
+ export class AllNodesFailedError extends Error {
66
+ readonly errors: ReadonlyArray<{ node: string; error: unknown }>
67
+
68
+ constructor(errors: ReadonlyArray<{ node: string; error: unknown }>) {
69
+ super(`All RPC nodes failed: ${errors.map((e) => `${e.node}: ${errorMessage(e.error)}`).join(' | ')}`, { cause: errors[errors.length - 1]?.error })
70
+ this.name = 'AllNodesFailedError'
71
+ this.errors = errors
72
+ }
73
+ }
74
+
75
+ function errorMessage(err: unknown): string {
76
+ return err instanceof Error ? err.message : String(err)
77
+ }
78
+
79
+ /** 是否是节点问题(应换节点重试):除了确定性的 JSON-RPC 错误(如参数错误),其余都算(包括 AllNodesFailedError) */
80
+ export function isNodeFault(err: unknown): boolean {
81
+ if (err instanceof RpcError) {
82
+ return err.nodeFault
83
+ }
84
+ return true
85
+ }
86
+
87
+ export interface HttpRpcOptions {
88
+ /** 单次 HTTP 请求超时(毫秒),<= 0 不限制。默认 10000 */
89
+ timeout?: number
90
+ headers?: Record<string, string>
91
+ /** 一个 HTTP 批量请求最多包含的调用数。默认 20 */
92
+ maxBatchSize?: number
93
+ /** 是否合并成 JSON-RPC 批量请求。默认 true;节点不支持时会自动关闭 */
94
+ batch?: boolean
95
+ /** 收集窗口(毫秒),窗口内的调用合并成一个 HTTP 请求。默认 0(同一 tick) */
96
+ batchWait?: number
97
+ /** 遇到 HTTP 429 时的重试次数(指数退避,从 500ms 开始)。默认 2 */
98
+ retries?: number
99
+ /** 自定义 fetch(如需要代理时) */
100
+ fetch?: typeof fetch
101
+ }
102
+
103
+ interface Pending {
104
+ method: string
105
+ params: readonly unknown[]
106
+ resolve: (value: unknown) => void
107
+ reject: (reason: unknown) => void
108
+ }
109
+
110
+ interface RpcResponse {
111
+ id?: number | string | null
112
+ result?: unknown
113
+ error?: { code?: number; message?: string; data?: unknown }
114
+ }
115
+
116
+ let nextId = 1
117
+
118
+ /** 批量请求被拒绝、可以降级为逐条请求的 HTTP 状态 */
119
+ const BATCH_REJECTED_STATUS = new Set([400, 404, 405, 415, 422])
120
+
121
+ function isBatchLimitError(message: string | undefined): boolean {
122
+ return !!message && /batch/i.test(message) && /more than \d+|too (large|many|big)|not (allowed|supported)|exceed/i.test(message)
123
+ }
124
+
125
+ /**
126
+ * 基于 fetch 的 JSON-RPC 传输:同一收集窗口内的调用合并成一个 JSON-RPC 批量请求。
127
+ * 节点不支持批量(返回非数组)或限制批量大小(如 drpc 免费档最多 3 条)时自动降级。
128
+ */
129
+ export class HttpRpc implements RpcTransport {
130
+ readonly url: string
131
+ /** 报错信息里用的地址:只保留 origin,不带 path / query(常含 API Key) */
132
+ readonly #safeUrl: string
133
+ readonly #timeout: number
134
+ readonly #headers: Record<string, string>
135
+ readonly #batchWait: number
136
+ readonly #retries: number
137
+ readonly #fetch: typeof fetch
138
+ #maxBatchSize: number
139
+ #batch: boolean
140
+ #queue: Pending[] = []
141
+ #timer: ReturnType<typeof setTimeout> | null = null
142
+
143
+ constructor(url: string, options: HttpRpcOptions = {}) {
144
+ this.url = url
145
+ this.#safeUrl = safeOrigin(url)
146
+ this.#timeout = options.timeout ?? 10_000
147
+ this.#headers = { 'content-type': 'application/json', ...options.headers }
148
+ this.#maxBatchSize = Math.max(1, options.maxBatchSize ?? 20)
149
+ this.#batch = options.batch ?? true
150
+ this.#batchWait = options.batchWait ?? 0
151
+ this.#retries = Math.max(0, options.retries ?? 2)
152
+ this.#fetch = options.fetch ?? ((...args) => fetch(...args))
153
+ }
154
+
155
+ request<T = unknown>(method: string, params: readonly unknown[] = []): Promise<T> {
156
+ return new Promise<T>((resolve, reject) => {
157
+ this.#queue.push({ method, params, resolve: resolve as (value: unknown) => void, reject })
158
+ if (!this.#batch || this.#queue.length >= this.#maxBatchSize) {
159
+ this.#flush()
160
+ } else if (!this.#timer) {
161
+ this.#timer = setTimeout(() => this.#flush(), this.#batchWait)
162
+ }
163
+ })
164
+ }
165
+
166
+ #flush(): void {
167
+ if (this.#timer) {
168
+ clearTimeout(this.#timer)
169
+ this.#timer = null
170
+ }
171
+ const queue = this.#queue
172
+ this.#queue = []
173
+ for (let i = 0; i < queue.length; i += this.#maxBatchSize) {
174
+ void this.#dispatch(queue.slice(i, i + this.#maxBatchSize))
175
+ }
176
+ }
177
+
178
+ async #dispatch(items: Pending[]): Promise<void> {
179
+ if (items.length === 1 || !this.#batch) {
180
+ await Promise.all(items.map((item) => this.#single(item)))
181
+ return
182
+ }
183
+ const ids = items.map(() => nextId++)
184
+ let body: unknown
185
+ try {
186
+ body = await this.#post(items.map((item, i) => ({ jsonrpc: '2.0', id: ids[i], method: item.method, params: item.params })))
187
+ } catch (err) {
188
+ if (err instanceof HttpError && err.status === 413 && items.length > 1) {
189
+ // 请求体太大:批量减半后重发
190
+ this.#maxBatchSize = Math.max(1, Math.floor(items.length / 2))
191
+ await this.#redispatch(items)
192
+ return
193
+ }
194
+ // 400 / 404 / 405 / 415 / 422 等:节点多半不接受批量请求,降级为逐条请求
195
+ // (401 / 403 / 429 / 5xx 是鉴权、限频或节点本身的问题,降级没有用,原样报错)
196
+ if (err instanceof HttpError && err.status !== undefined && BATCH_REJECTED_STATUS.has(err.status)) {
197
+ this.#disableBatch()
198
+ await Promise.all(items.map((item) => this.#single(item)))
199
+ return
200
+ }
201
+ items.forEach((item) => item.reject(err))
202
+ return
203
+ }
204
+ if (!Array.isArray(body)) {
205
+ const error = (body as RpcResponse)?.error
206
+ const rpcError = new RpcError(error?.message ?? 'Invalid JSON-RPC batch response', error?.code, error?.data)
207
+ // 限频 / 鉴权等节点问题:原样报错,不降级(降级成逐条请求只会让限频更严重)
208
+ if (rpcError.nodeFault) {
209
+ items.forEach((item) => item.reject(rpcError))
210
+ return
211
+ }
212
+ // 其他(如 -32600 invalid request):节点不支持批量,降级为逐条请求
213
+ this.#disableBatch()
214
+ await Promise.all(items.map((item) => this.#single(item)))
215
+ return
216
+ }
217
+ const byId = new Map((body as RpcResponse[]).map((res) => [res.id, res]))
218
+ const limited = (body as RpcResponse[]).find((res) => isBatchLimitError(res.error?.message))
219
+ if (limited) {
220
+ // 如 “Batch of more than 3 requests are not allowed”:按限制缩小批量后重发;
221
+ // 限制不小于当前批量(节点的上限判断有偏差)或解析不出数字时,降级为逐条请求,避免无限重发
222
+ const max = Number(/more than (\d+)/i.exec(limited.error?.message ?? '')?.[1])
223
+ if (Number.isFinite(max) && max > 1 && max < items.length) {
224
+ this.#maxBatchSize = max
225
+ await this.#redispatch(items)
226
+ } else {
227
+ this.#disableBatch()
228
+ await Promise.all(items.map((item) => this.#single(item)))
229
+ }
230
+ return
231
+ }
232
+ // 批量里个别调用被限频(JSON-RPC 429):只把这些调用退避后单独重试
233
+ const limitedItems: Pending[] = []
234
+ items.forEach((item, i) => {
235
+ const response = byId.get(ids[i])
236
+ if (response?.error?.code === 429 && this.#retries > 0) {
237
+ limitedItems.push(item)
238
+ } else {
239
+ settle(item, response)
240
+ }
241
+ })
242
+ if (limitedItems.length) {
243
+ await new Promise((r) => setTimeout(r, 500))
244
+ await Promise.all(limitedItems.map((item) => this.#single(item)))
245
+ }
246
+ }
247
+
248
+ /** 按当前的 maxBatchSize 重新分批发送(每批都比原来小,不会无限循环) */
249
+ async #redispatch(items: Pending[]): Promise<void> {
250
+ const size = this.#maxBatchSize
251
+ const chunks: Pending[][] = []
252
+ for (let i = 0; i < items.length; i += size) {
253
+ chunks.push(items.slice(i, i + size))
254
+ }
255
+ await Promise.all(chunks.map((chunk) => this.#dispatch(chunk)))
256
+ }
257
+
258
+ async #single(item: Pending): Promise<void> {
259
+ try {
260
+ const body = (await this.#post({ jsonrpc: '2.0', id: nextId++, method: item.method, params: item.params })) as RpcResponse
261
+ settle(item, body)
262
+ } catch (err) {
263
+ item.reject(err)
264
+ }
265
+ }
266
+
267
+ #disableBatch(): void {
268
+ this.#batch = false
269
+ }
270
+
271
+ async #post(payload: unknown): Promise<unknown> {
272
+ for (let attempt = 0; ; attempt++) {
273
+ let response: Response
274
+ try {
275
+ response = await this.#fetch(this.url, {
276
+ method: 'POST',
277
+ headers: this.#headers,
278
+ body: JSON.stringify(payload),
279
+ signal: this.#timeout > 0 && Number.isFinite(this.#timeout) ? AbortSignal.timeout(this.#timeout) : undefined,
280
+ })
281
+ } catch (err) {
282
+ // AbortSignal.timeout 触发时是 TimeoutError(DOMException)
283
+ const timeout = (err as { name?: unknown } | null)?.name === 'TimeoutError'
284
+ throw new HttpError(`Request to ${this.#safeUrl} failed: ${(err as Error)?.message ?? err}`, undefined, timeout)
285
+ }
286
+ if (response.status === 429 && attempt < this.#retries) {
287
+ await new Promise((r) => setTimeout(r, 500 * 2 ** attempt))
288
+ continue
289
+ }
290
+ const text = await response.text()
291
+ let body: unknown
292
+ try {
293
+ body = parseJson(text)
294
+ } catch {
295
+ throw new HttpError(`Invalid JSON from ${this.#safeUrl} (HTTP ${response.status})`, response.status)
296
+ }
297
+ // 非 2xx 但返回了 JSON-RPC 结构(如 403 Access forbidden、drpc 的 500 + 批量错误数组):交给上层解析
298
+ if (!response.ok && !Array.isArray(body) && !(body as RpcResponse)?.error) {
299
+ throw new HttpError(`HTTP ${response.status} from ${this.#safeUrl}`, response.status)
300
+ }
301
+ // 有的节点限频时返回 HTTP 200 + JSON-RPC 错误码 429:同样退避重试
302
+ if (attempt < this.#retries && isRateLimited(body)) {
303
+ await new Promise((r) => setTimeout(r, 500 * 2 ** attempt))
304
+ continue
305
+ }
306
+ return body
307
+ }
308
+ }
309
+ }
310
+
311
+ // lamports 等 u64 以 JSON 数字返回,超过 2^53(约 900 万 SOL)时 JSON.parse 会丢精度:
312
+ // 支持 JSON.parse source text access 的环境(Node 21+、新版浏览器)直接取原文;否则先把超长整数改成字符串再解析
313
+ let sourceAccess: boolean | undefined
314
+
315
+ function parseJson(text: string): unknown {
316
+ sourceAccess ??= (() => {
317
+ let supported = false
318
+ JSON.parse('1', (_key, value, context?: { source?: string }) => {
319
+ supported = typeof context?.source === 'string'
320
+ return value
321
+ })
322
+ return supported
323
+ })()
324
+ if (sourceAccess) {
325
+ return JSON.parse(text, (_key, value: unknown, context?: { source?: string }) =>
326
+ typeof value === 'number' && !Number.isSafeInteger(value) && Number.isInteger(value) && context?.source ? context.source : value,
327
+ )
328
+ }
329
+ return JSON.parse(text.replace(/([:[,]\s*)(-?\d{16,})(?=\s*[,}\]])/g, '$1"$2"'))
330
+ }
331
+
332
+ function safeOrigin(url: string): string {
333
+ try {
334
+ return new URL(url).origin
335
+ } catch {
336
+ return 'invalid URL'
337
+ }
338
+ }
339
+
340
+ function isRateLimited(body: unknown): boolean {
341
+ const responses = (Array.isArray(body) ? body : [body]) as RpcResponse[]
342
+ return responses.length > 0 && responses.every((res) => res?.error?.code === 429)
343
+ }
344
+
345
+ function settle(item: Pending, response: RpcResponse | undefined): void {
346
+ if (!response) {
347
+ item.reject(new HttpError('Missing response in JSON-RPC batch'))
348
+ } else if (response.error) {
349
+ item.reject(new RpcError(response.error.message ?? 'JSON-RPC error', response.error.code, response.error.data))
350
+ } else {
351
+ item.resolve(response.result)
352
+ }
353
+ }
354
+
355
+ /**
356
+ * onRequest 的事件:每个 JSON-RPC 调用对每个节点的每次尝试一条(合并成批量 HTTP 请求时,批里每个调用各一条,
357
+ * ms 是该调用从发出到返回的时间;HttpRpc 内部的 429 退避重试算在同一条里)
358
+ */
359
+ export interface RequestEvent {
360
+ /** 节点名称:URL 的 host,自定义传输的 label(没有时为 'custom') */
361
+ node: string
362
+ method: string
363
+ ms: number
364
+ ok: boolean
365
+ /** 失败时的错误 */
366
+ error?: unknown
367
+ /** 本次调用按故障切换顺序尝试的第几个节点(0 起);大于 0 说明换过节点 */
368
+ attempt: number
369
+ }
370
+
371
+ const requestListeners = new Set<(event: RequestEvent) => void>()
372
+
373
+ /**
374
+ * 监听所有客户端发出的 JSON-RPC 调用(节点、方法、耗时、成功与否、第几次尝试),用于统计和排查。返回取消监听的函数。
375
+ *
376
+ * ```ts
377
+ * const stop = onRequest((e) => console.log(e.node, e.method, e.ms, e.ok, e.attempt))
378
+ * ```
379
+ */
380
+ export function onRequest(listener: (event: RequestEvent) => void): () => void {
381
+ requestListeners.add(listener)
382
+ return () => {
383
+ requestListeners.delete(listener)
384
+ }
385
+ }
386
+
387
+ function emit(event: RequestEvent): void {
388
+ for (const listener of requestListeners) {
389
+ try {
390
+ listener(event)
391
+ } catch {
392
+ // 监听函数出错不影响请求
393
+ }
394
+ }
395
+ }
396
+
397
+ /** 节点名称:优先用传输自带的 label;HttpRpc 取 URL 的 host(不带 path / query,避免泄露 API Key) */
398
+ export function nodeLabel(node: RpcTransport): string {
399
+ if (typeof node.label === 'string') {
400
+ return node.label
401
+ }
402
+ const base = unwrap(node)
403
+ if (base !== node && typeof base.label === 'string') {
404
+ return base.label
405
+ }
406
+ if (base instanceof HttpRpc) {
407
+ try {
408
+ return new URL(base.url).host || 'custom'
409
+ } catch {
410
+ return 'custom'
411
+ }
412
+ }
413
+ return 'custom'
414
+ }
415
+
416
+ /** 去掉校验层等包装(有 inner 属性的传输),取底层节点 */
417
+ function unwrap(node: RpcTransport): RpcTransport {
418
+ let current = node
419
+ for (let inner = (current as { inner?: RpcTransport }).inner; inner && typeof inner.request === 'function'; inner = (current as { inner?: RpcTransport }).inner) {
420
+ current = inner
421
+ }
422
+ return current
423
+ }
424
+
425
+ interface NodeHealth {
426
+ /** 上次出错(进入冷却)的时间,0 表示健康 */
427
+ failedAt: number
428
+ /** 连续超时次数 */
429
+ timeouts: number
430
+ }
431
+
432
+ // 节点健康状态按节点共享(模块级):客户端重建后,刚出过错的节点仍排在后面。URL 节点按完整 URL,其他按对象
433
+ const healthByUrl = new Map<string, NodeHealth>()
434
+ let healthByObject = new WeakMap<object, NodeHealth>()
435
+ const MAX_TRACKED_URLS = 1000
436
+ /** 连续超时这么多次才冷却(单次超时多半只是这次请求慢) */
437
+ const TIMEOUTS_BEFORE_COOLDOWN = 3
438
+
439
+ /** 健康状态的 key:HttpRpc 按完整 URL(不同连接对象共享),其他节点按对象(去掉校验层) */
440
+ function healthKeyOf(node: RpcTransport): string | object {
441
+ const base = unwrap(node)
442
+ return base instanceof HttpRpc ? base.url : base
443
+ }
444
+
445
+ /** 每次用时按 key 从全局表里取:表淘汰条目后,各实例仍取到同一个对象 */
446
+ function healthOf(key: string | object): NodeHealth {
447
+ if (typeof key === 'string') {
448
+ let health = healthByUrl.get(key)
449
+ if (!health) {
450
+ health = { failedAt: 0, timeouts: 0 }
451
+ healthByUrl.set(key, health)
452
+ if (healthByUrl.size > MAX_TRACKED_URLS) {
453
+ healthByUrl.delete(healthByUrl.keys().next().value as string)
454
+ }
455
+ }
456
+ return health
457
+ }
458
+ let health = healthByObject.get(key)
459
+ if (!health) {
460
+ health = { failedAt: 0, timeouts: 0 }
461
+ healthByObject.set(key, health)
462
+ }
463
+ return health
464
+ }
465
+
466
+ /** 测试用:清空节点健康状态 */
467
+ export function resetNodeHealth(): void {
468
+ healthByUrl.clear()
469
+ healthByObject = new WeakMap()
470
+ }
471
+
472
+ export interface FallbackOptions {
473
+ /** 出错节点的冷却时间(毫秒),期间排到最后。默认 30000 */
474
+ cooldown?: number
475
+ }
476
+
477
+ /**
478
+ * 多节点故障切换:按顺序使用,节点问题(网络、超时、限频、需要 Key、403、高度不够等)换下一个;
479
+ * 参数错误等确定性错误直接抛出。单个节点也用它包一层(统一 onRequest 事件),此时失败抛原始错误。
480
+ *
481
+ * - 出错的节点在冷却期内排到最后;健康状态按节点全局共享(URL 相同即同一节点),客户端重建后仍然有效
482
+ * - 超时只换节点、不冷却(大批量查询慢一点很正常),同一节点连续 3 次超时才冷却
483
+ * - 节点高度没到 minContextSlot 只换节点、不冷却(只是这次请求要求的 slot 太新)
484
+ * - 多个节点都失败时抛 AllNodesFailedError,带上每个节点的错误
485
+ */
486
+ export class FallbackRpc implements RpcTransport {
487
+ readonly nodes: readonly RpcTransport[]
488
+ readonly #cooldown: number
489
+ /** 节点标识和健康状态的 key 不会变,构造时算好(每次请求只做一次 Map 查找) */
490
+ readonly #labels: readonly string[]
491
+ readonly #healthKeys: ReadonlyArray<string | object>
492
+
493
+ constructor(nodes: readonly RpcTransport[], options: FallbackOptions = {}) {
494
+ if (!nodes.length) {
495
+ throw new Error('FallbackRpc requires at least one node')
496
+ }
497
+ this.nodes = nodes
498
+ this.#cooldown = options.cooldown ?? 30_000
499
+ this.#labels = nodes.map(nodeLabel)
500
+ this.#healthKeys = nodes.map(healthKeyOf)
501
+ }
502
+
503
+ async request<T = unknown>(method: string, params?: readonly unknown[]): Promise<T> {
504
+ const errors: Array<{ node: string; error: unknown }> = []
505
+ const order = this.#order()
506
+ for (let attempt = 0; attempt < order.length; attempt++) {
507
+ const index = order[attempt] as number
508
+ const node = this.nodes[index] as RpcTransport
509
+ const label = this.#labels[index] as string
510
+ const health = healthOf(this.#healthKeys[index] as string | object)
511
+ const started = Date.now()
512
+ try {
513
+ const result = await node.request<T>(method, params)
514
+ health.failedAt = 0
515
+ health.timeouts = 0
516
+ emit({ node: label, method, ms: Date.now() - started, ok: true, attempt })
517
+ return result
518
+ } catch (err) {
519
+ emit({ node: label, method, ms: Date.now() - started, ok: false, error: err, attempt })
520
+ if (!isNodeFault(err)) {
521
+ throw err
522
+ }
523
+ if (isTimeout(err)) {
524
+ if (++health.timeouts >= TIMEOUTS_BEFORE_COOLDOWN) {
525
+ health.failedAt = Date.now()
526
+ health.timeouts = 0
527
+ }
528
+ } else if (!isBehind(err)) {
529
+ health.failedAt = Date.now()
530
+ }
531
+ errors.push({ node: label, error: err })
532
+ }
533
+ }
534
+ if (this.nodes.length === 1) {
535
+ throw errors[0]?.error
536
+ }
537
+ throw new AllNodesFailedError(errors)
538
+ }
539
+
540
+ #order(): number[] {
541
+ const now = Date.now()
542
+ const failedAt = this.#healthKeys.map((key) => healthOf(key).failedAt)
543
+ const healthy: number[] = []
544
+ const cooling: number[] = []
545
+ failedAt.forEach((at, i) => (at && now - at < this.#cooldown ? cooling : healthy).push(i))
546
+ cooling.sort((a, b) => (failedAt[a] as number) - (failedAt[b] as number))
547
+ return [...healthy, ...cooling]
548
+ }
549
+ }