libp2r2p 0.12.7 → 0.12.9

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.
@@ -7,6 +7,8 @@ import { drainableStream } from '../helpers/drainable-stream.js'
7
7
  import { maybeUnref } from '../helpers/timer.js'
8
8
  import { categorizeRelayError, relayTimeoutError } from '../helpers/error.js'
9
9
  import { ReadRetry, isRetryableReadFailure, needsConnectivityCheck, waitUntil } from '../helpers/read-retry.js'
10
+ import { DEFAULT_RATE_LIMIT_CAP_MS } from '../helpers/retry-advice.js'
11
+ import { debugRateLimitRetry } from '../helpers/retry-debug.js'
10
12
  import { normalizeRelayUrl } from '../../url/index.js'
11
13
  import { isValidEvent } from '../../event/index.js'
12
14
  import { RelayConnection } from './relay-connection.js'
@@ -101,6 +103,16 @@ function asError (error) {
101
103
  return error instanceof Error ? error : new Error(String(error))
102
104
  }
103
105
 
106
+ function validateRateLimitCapMs (value) {
107
+ if (!Number.isSafeInteger(value) || value < 1) throw new ValidationError('INVALID_RATE_LIMIT_CAP_MS')
108
+ return value
109
+ }
110
+
111
+ function validateRateLimitRetries (value) {
112
+ if (!Number.isSafeInteger(value) || value < 0) throw new ValidationError('INVALID_RATE_LIMIT_RETRIES')
113
+ return value
114
+ }
115
+
104
116
  function assertReadOptions (filter, timeouts) {
105
117
  if (!filter || typeof filter !== 'object' || Array.isArray(filter)) throw new ValidationError('INVALID_FILTER')
106
118
  for (const value of Object.values(timeouts)) {
@@ -153,14 +165,42 @@ export class RelayPool {
153
165
  #WebSocket
154
166
  #admission
155
167
  #readRetry
168
+ #options
156
169
 
157
- constructor ({ _createRelay, _isOnline, _onOnline, WebSocket: WebSocketImpl, ...capacity } = {}) {
170
+ constructor ({ _createRelay, _isOnline, _onOnline, WebSocket: WebSocketImpl, rateLimitCapMs = DEFAULT_RATE_LIMIT_CAP_MS, rateLimitRetries = 1, ...capacity } = {}) {
171
+ this.#options = {
172
+ rateLimitCapMs: validateRateLimitCapMs(rateLimitCapMs),
173
+ rateLimitRetries: validateRateLimitRetries(rateLimitRetries)
174
+ }
158
175
  this.#WebSocket = WebSocketImpl
159
- this.#createRelay = _createRelay ?? (url => new RelayConnection(url, this.#WebSocket ? { WebSocket: this.#WebSocket } : undefined))
176
+ this.#createRelay = _createRelay ?? (url => new RelayConnection(url, {
177
+ ...(this.#WebSocket ? { WebSocket: this.#WebSocket } : {}),
178
+ rateLimitCapMs: () => this.#options.rateLimitCapMs
179
+ }))
160
180
  this.#admission = new ReadAdmission(capacity)
161
181
  this.#readRetry = new ReadRetry({ checkOnline: _isOnline, watchOnline: _onOnline })
162
182
  }
163
183
 
184
+ getOptions () {
185
+ return Object.freeze({ ...this.#options })
186
+ }
187
+
188
+ setOptions (partial = {}) {
189
+ if (!partial || typeof partial !== 'object' || Array.isArray(partial)) throw new ValidationError('INVALID_RELAY_POOL_OPTIONS')
190
+ const unknown = Object.keys(partial).find(key => !['rateLimitCapMs', 'rateLimitRetries'].includes(key))
191
+ if (unknown) throw new ValidationError('UNKNOWN_RELAY_POOL_OPTION')
192
+ const next = { ...this.#options }
193
+ if (Object.hasOwn(partial, 'rateLimitCapMs')) next.rateLimitCapMs = validateRateLimitCapMs(partial.rateLimitCapMs)
194
+ if (Object.hasOwn(partial, 'rateLimitRetries')) next.rateLimitRetries = validateRateLimitRetries(partial.rateLimitRetries)
195
+ this.#options = next
196
+ for (const relay of this.#relays.values()) relay.setRateLimitCapMs?.(next.rateLimitCapMs)
197
+ return this.getOptions()
198
+ }
199
+
200
+ #retryCount (value) {
201
+ return validateRateLimitRetries(value === undefined ? this.#options.rateLimitRetries : value)
202
+ }
203
+
164
204
  // Injects the WebSocket implementation used by new pooled connections (e.g.
165
205
  // a launcher-owned relay multiplexer). Existing connections keep the
166
206
  // implementation they were created with.
@@ -250,21 +290,27 @@ export class RelayPool {
250
290
 
251
291
  // NIP-42 retries happen inside one relay attempt, so sendEvent still reports
252
292
  // exactly one terminal outcome for each relay URL.
253
- async #publishEvent (relay, event, getAuthEvent, signal) {
293
+ async #publishEvent (relay, event, getAuthEvent, signal, {
294
+ useBulkPacing,
295
+ rateLimitRetries,
296
+ retrySignal,
297
+ deadlineAt
298
+ }) {
254
299
  try {
255
- await relay.publish(event, { signal })
300
+ await relay.publish(event, { signal, useBulkPacing, rateLimitRetries, retrySignal, deadlineAt })
256
301
  return 'published'
257
302
  } catch (error) {
258
303
  const reason = error instanceof Error ? error : new Error(String(error))
259
304
  if (!getAuthEvent || !requiresNip42Auth(reason)) throw reason
260
305
 
261
306
  try {
262
- await relay.authenticate(getAuthEvent, { signal })
307
+ await relay.authenticate(getAuthEvent, { signal, rateLimitRetries, retrySignal, deadlineAt })
263
308
  } catch (error) {
264
309
  const authReason = error instanceof Error ? error : new Error(String(error))
310
+ if (retrySignal?.aborted && authReason.message?.startsWith('rate-limited:')) throw authReason
265
311
  throw new Nip42AuthenticationError(authReason)
266
312
  }
267
- await relay.publish(event, { signal })
313
+ await relay.publish(event, { signal, useBulkPacing, rateLimitRetries, retrySignal, deadlineAt })
268
314
  return 'published'
269
315
  }
270
316
  }
@@ -275,12 +321,14 @@ export class RelayPool {
275
321
  async countEvents (filter, relays, {
276
322
  timeout = COUNT_TIMEOUT_MS,
277
323
  timeoutAfterFirstCount = COUNT_TIMEOUT_AFTER_FIRST_COUNT_MS,
278
- signal
324
+ signal,
325
+ rateLimitRetries
279
326
  } = {}) {
280
327
  if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
281
328
  throw new ValidationError('COUNT_FILTER_REQUIRED')
282
329
  }
283
330
  if (signal?.aborted) throw new Error('Aborted')
331
+ const retries = this.#retryCount(rateLimitRetries)
284
332
 
285
333
  const urls = normalizedRelayUrls(relays)
286
334
  if (!urls.length) {
@@ -288,6 +336,10 @@ export class RelayPool {
288
336
  }
289
337
 
290
338
  const countController = new AbortController()
339
+ const retryControllers = new Map()
340
+ const retryCounts = new Map(urls.map(url => [url, 0]))
341
+ const retryErrors = new Map()
342
+ const deadline = timeout === null ? null : Date.now() + timeout
291
343
  const pending = new Set(urls)
292
344
  const errors = []
293
345
  let count = null
@@ -301,6 +353,8 @@ export class RelayPool {
301
353
  const cleanup = () => {
302
354
  clearTimeout(timeoutTimer)
303
355
  clearTimeout(graceTimer)
356
+ for (const controller of retryControllers.values()) controller.abort()
357
+ retryControllers.clear()
304
358
  signal?.removeEventListener('abort', onAbort)
305
359
  countController.abort()
306
360
  }
@@ -369,13 +423,48 @@ export class RelayPool {
369
423
  }
370
424
 
371
425
  const handleError = (relay, error) => {
372
- if (isResolved || !settleRelay(relay)) return
373
426
  const reason = error instanceof Error ? error : new Error(String(error))
427
+ if (isResolved || !pending.has(relay)) return
428
+ const retryAt = Number.isSafeInteger(reason.retryAt) ? reason.retryAt : 0
429
+ if (reason.message?.startsWith('rate-limited:') && retryAt &&
430
+ retryCounts.get(relay) < retries && (deadline === null || retryAt < deadline)) {
431
+ retryCounts.set(relay, retryCounts.get(relay) + 1)
432
+ retryErrors.set(relay, reason)
433
+ debugRateLimitRetry({
434
+ relay,
435
+ operation: 'COUNT',
436
+ retryAttempt: retryCounts.get(relay),
437
+ maxRetries: retries,
438
+ retryAt
439
+ })
440
+ const controller = new AbortController()
441
+ const combined = AbortSignal.any([countController.signal, controller.signal])
442
+ retryControllers.set(relay, controller)
443
+ waitUntil(retryAt, combined)
444
+ .then(() => {
445
+ if (retryControllers.get(relay) === controller) retryControllers.delete(relay)
446
+ if (isResolved || !pending.has(relay)) return
447
+ if (deadline !== null && Date.now() >= deadline) {
448
+ settleRelay(relay)
449
+ errors.push({ relay, reason: retryErrors.get(relay) ?? countTimeoutError() })
450
+ finishIfComplete()
451
+ return
452
+ }
453
+ startCount(relay)
454
+ })
455
+ .catch(cause => {
456
+ if (combined.aborted || isResolved || !pending.has(relay)) return
457
+ if (retryControllers.get(relay) === controller) retryControllers.delete(relay)
458
+ handleError(relay, asError(cause))
459
+ })
460
+ return
461
+ }
462
+ settleRelay(relay)
374
463
  errors.push({ relay, reason })
375
464
  finishIfComplete()
376
465
  }
377
466
 
378
- for (const relay of urls) {
467
+ const startCount = relay => {
379
468
  this.#getRelay(relay)
380
469
  .then(async connection => {
381
470
  if (isResolved) return null
@@ -386,6 +475,7 @@ export class RelayPool {
386
475
  error => handleError(relay, error)
387
476
  )
388
477
  }
478
+ for (const relay of urls) startCount(relay)
389
479
  })
390
480
  }
391
481
 
@@ -393,12 +483,31 @@ export class RelayPool {
393
483
  // grace window; null disables that window so callers wait for every relay or
394
484
  // the operation deadline. Disabling cross-relay deduplication still suppresses
395
485
  // repeated ids from the same relay; callbacks remain immediate in both modes.
396
- async getEvents (filter, relays, { timeout = 5000, timeoutAfterFirstEose = 500, callback, signal, deduplicateAcrossRelays = true, queueTimeout = 30000, _admissions } = {}) {
486
+ async getEvents (filter, relays, {
487
+ timeout = 5000,
488
+ timeoutAfterFirstEose = 500,
489
+ callback,
490
+ signal,
491
+ deduplicateAcrossRelays = true,
492
+ queueTimeout = 30000,
493
+ rateLimitRetries,
494
+ _admissions
495
+ } = {}) {
397
496
  assertReadOptions(filter, { timeout, timeoutAfterFirstEose, queueTimeout })
398
497
  if (typeof deduplicateAcrossRelays !== 'boolean') throw new ValidationError('INVALID_DEDUPLICATE_ACROSS_RELAYS')
399
498
  if (signal?.aborted) throw new Error('Aborted')
499
+ const retries = this.#retryCount(rateLimitRetries)
400
500
  const urls = normalizedRelayUrls(relays)
401
501
  const subscriptions = new Map()
502
+ const retryControllers = new Map()
503
+ const retryCounts = new Map(urls.map(url => [url, 0]))
504
+ const deadlines = new Map()
505
+ const remainingTimeout = url => {
506
+ if (timeout === null) return null
507
+ if (!deadlines.has(url)) deadlines.set(url, Date.now() + timeout)
508
+ return Math.max(0, deadlines.get(url) - Date.now())
509
+ }
510
+ const seenIdsByRelay = new Map()
402
511
  const outcomes = new Map()
403
512
  const errors = []
404
513
  const events = []
@@ -414,6 +523,8 @@ export class RelayPool {
414
523
  const cleanup = () => {
415
524
  admissionAbort.abort()
416
525
  for (const timer of timers.values()) clearTimeout(timer)
526
+ for (const controller of retryControllers.values()) controller.abort()
527
+ retryControllers.clear()
417
528
  clearTimeout(eoseTimer)
418
529
  signal?.removeEventListener('abort', onAbort)
419
530
  for (const sub of subscriptions.values()) sub.close()
@@ -466,18 +577,58 @@ export class RelayPool {
466
577
  signal?.addEventListener('abort', onAbort, { once: true })
467
578
  if (!urls.length) { finish(); return }
468
579
 
469
- for (const url of urls) {
470
- const seenIds = eventIds ?? new Set()
471
- const reservation = _admissions?.get(url) ?? this.#admission.acquire(normalizeRelayUrl(url), { history: true, signal: admissionSignal, queueTimeout })
580
+ const scheduleRetry = (url, error) => {
581
+ if (isResolved || outcomes.has(url) || retryControllers.has(url) ||
582
+ retryCounts.get(url) >= retries || !error?.message?.startsWith('rate-limited:')) return false
583
+ const retryAt = Number.isSafeInteger(error.retryAt) ? error.retryAt : 0
584
+ if (!retryAt || (deadlines.has(url) && retryAt >= deadlines.get(url))) return false
585
+ retryCounts.set(url, retryCounts.get(url) + 1)
586
+ debugRateLimitRetry({
587
+ relay: url,
588
+ operation: 'REQ',
589
+ retryAttempt: retryCounts.get(url),
590
+ maxRetries: retries,
591
+ retryAt
592
+ })
593
+ const controller = new AbortController()
594
+ const combined = AbortSignal.any([admissionSignal, controller.signal])
595
+ retryControllers.set(url, controller)
596
+ waitUntil(retryAt, combined)
597
+ .then(() => {
598
+ if (retryControllers.get(url) === controller) retryControllers.delete(url)
599
+ if (isResolved || outcomes.has(url)) return
600
+ if (deadlines.has(url) && Date.now() >= deadlines.get(url)) {
601
+ settleRelay(url, 'error', error)
602
+ finishIfComplete()
603
+ return
604
+ }
605
+ startRelay(url)
606
+ })
607
+ .catch(reason => {
608
+ if (combined.aborted) return
609
+ if (retryControllers.get(url) === controller) retryControllers.delete(url)
610
+ settleRelay(url, 'error', asError(reason))
611
+ finishIfComplete()
612
+ })
613
+ return true
614
+ }
615
+ const startRelay = url => {
616
+ const seenIds = eventIds ?? seenIdsByRelay.get(url) ?? new Set()
617
+ if (!eventIds) seenIdsByRelay.set(url, seenIds)
618
+ const existingLease = leases.get(url)
619
+ const reservation = existingLease
620
+ ? Promise.resolve({ history: existingLease })
621
+ : _admissions?.get(url) ?? this.#admission.acquire(normalizeRelayUrl(url), { history: true, signal: admissionSignal, queueTimeout })
472
622
  reservation.then(async slots => {
473
623
  const lease = slots.history
474
624
  if (isResolved || outcomes.has(url)) { lease.release(); return }
475
625
  leases.set(url, lease)
476
- if (timeout !== null) {
626
+ const relayTimeout = remainingTimeout(url)
627
+ if (relayTimeout !== null) {
477
628
  timers.set(url, maybeUnref(setTimeout(() => {
478
629
  settleRelay(url, 'timeout', getEventsTimeoutError())
479
630
  finishIfComplete()
480
- }, timeout)))
631
+ }, relayTimeout)))
481
632
  }
482
633
  const relay = await this.#getRelay(url)
483
634
  if (isResolved || outcomes.has(url)) return
@@ -513,6 +664,12 @@ export class RelayPool {
513
664
  onclose: error => {
514
665
  if (isResolved || outcomes.has(url)) return
515
666
  const reason = error === undefined ? undefined : asError(error)
667
+ if (reason && scheduleRetry(url, reason)) {
668
+ clearTimeout(timers.get(url))
669
+ timers.delete(url)
670
+ subscriptions.delete(url)
671
+ return
672
+ }
516
673
  settleRelay(url, reason ? 'error' : 'closed', reason)
517
674
  subscriptions.delete(url)
518
675
  finishIfComplete()
@@ -526,6 +683,7 @@ export class RelayPool {
526
683
  finishIfComplete()
527
684
  })
528
685
  }
686
+ for (const url of urls) startRelay(url)
529
687
  })
530
688
  }
531
689
 
@@ -860,6 +1018,7 @@ export class RelayPool {
860
1018
  queueTimeout,
861
1019
  timeout: timeoutForReconnectGap,
862
1020
  timeoutAfterFirstEose: timeoutAfterFirstReconnectGapEose,
1021
+ rateLimitRetries: 0,
863
1022
  signal,
864
1023
  _stopSignal: AbortSignal.any([gapAc.signal, attempt.stop.signal])
865
1024
  })
@@ -1083,7 +1242,10 @@ export class RelayPool {
1083
1242
  const options = { timeout, timeoutAfterFirstEose, queueTimeout, signal, _stopSignal }
1084
1243
  if (!live) {
1085
1244
  const bounds = { since: filter.since ?? 0, until: Math.min(filter.until ?? Infinity, Math.floor(Date.now() / 1000)) }
1086
- for await (const item of _eventsGenerator(snapshot ? { ...filter, ...bounds } : filter, relays, options)) {
1245
+ for await (const item of _eventsGenerator(snapshot ? { ...filter, ...bounds } : filter, relays, {
1246
+ ...options,
1247
+ rateLimitRetries: 0
1248
+ })) {
1087
1249
  if (signal.aborted) return
1088
1250
  yield snapshot && item.type === 'eose' ? { ...item, snapshot: bounds } : item
1089
1251
  }
@@ -1114,7 +1276,14 @@ export class RelayPool {
1114
1276
  reservation.catch(() => {})
1115
1277
  reservations.set(url, reservation)
1116
1278
  }
1117
- const readOptions = { ...options, signal: inputSignal, _admissions: reservations, maxBufferedLiveEvents, maxBufferedLiveBytes }
1279
+ const readOptions = {
1280
+ ...options,
1281
+ signal: inputSignal,
1282
+ _admissions: reservations,
1283
+ maxBufferedLiveEvents,
1284
+ maxBufferedLiveBytes,
1285
+ rateLimitRetries: 0
1286
+ }
1118
1287
  const liveFilter = { ...filter }
1119
1288
  if (snapshot) delete liveFilter.until
1120
1289
  const liveGen = _liveGenerator(liveFilter, urls, readOptions)
@@ -1221,10 +1390,14 @@ export class RelayPool {
1221
1390
  getAuthEvent,
1222
1391
  getRetryEvent,
1223
1392
  onRelayResult,
1224
- signal
1393
+ signal,
1394
+ useBulkPacing = false,
1395
+ rateLimitRetries
1225
1396
  } = {}) {
1226
1397
  if (signal != null && (typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function' || typeof signal.removeEventListener !== 'function')) throw new ValidationError('INVALID_RELAY_SIGNAL')
1227
1398
  if (getRetryEvent != null && typeof getRetryEvent !== 'function') throw new ValidationError('INVALID_RETRY_EVENT_CALLBACK')
1399
+ if (typeof useBulkPacing !== 'boolean') throw new ValidationError('INVALID_USE_BULK_PACING')
1400
+ const retries = this.#retryCount(rateLimitRetries)
1228
1401
  const urls = normalizedRelayUrls(relays)
1229
1402
  if (!urls.length) {
1230
1403
  const promise = Promise.resolve(publishSummary([], urls, {
@@ -1240,6 +1413,7 @@ export class RelayPool {
1240
1413
  const eventForAttempt = eventToSend.meta ? { ...eventToSend } : eventToSend
1241
1414
  if (eventForAttempt.meta) delete eventForAttempt.meta
1242
1415
  const sendControllers = urls.map(() => new AbortController())
1416
+ const retryControllers = urls.map(() => new AbortController())
1243
1417
  const sendDeferreds = urls.map(() => Promise.withResolvers())
1244
1418
  const sendPromises = sendDeferreds.map(({ promise }) => promise)
1245
1419
  const bufferedResults = []
@@ -1279,7 +1453,12 @@ export class RelayPool {
1279
1453
  if (operationSignal.aborted) throw operationSignal.reason
1280
1454
  const relay = await this.#getRelay(url)
1281
1455
  if (operationSignal.aborted) throw operationSignal.reason
1282
- return await this.#publishEvent(relay, eventForAttempt, getAuthEvent, operationSignal)
1456
+ return await this.#publishEvent(relay, eventForAttempt, getAuthEvent, operationSignal, {
1457
+ useBulkPacing,
1458
+ rateLimitRetries: retries,
1459
+ retrySignal: retryControllers[index].signal,
1460
+ deadlineAt: deadline
1461
+ })
1283
1462
  } catch (err) {
1284
1463
  const reason = err instanceof Error ? err : new Error(String(err))
1285
1464
  if (reason instanceof Nip42AuthenticationError) throw reason
@@ -1299,6 +1478,7 @@ export class RelayPool {
1299
1478
  const success = await firstFulfillment(sendPromises, earlyTimeout, {
1300
1479
  fallback: promise.then(report => report.success)
1301
1480
  })
1481
+ if (success) for (const controller of retryControllers) controller.abort()
1302
1482
  if (!success) settlement.timeout()
1303
1483
 
1304
1484
  const result = {