libp2r2p 0.12.8 → 0.12.10

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.
package/README.md CHANGED
@@ -1115,8 +1115,56 @@ Valid values produce both `retryAfterMs` and `retryAt`, capped by `capMs`.
1115
1115
  Missing or invalid params are ignored and do not instruct clients to retry
1116
1116
  immediately. RelayPool defaults `rateLimitCapMs` to five minutes. Its
1117
1117
  `getOptions()` returns a frozen runtime snapshot and `setOptions(partial)`
1118
- validates and applies allowlisted partial updates. Non-bulk schedulers retain
1119
- their existing max(local backoff deadline, retryAt) behavior.
1118
+ validates and applies allowlisted partial updates.
1119
+
1120
+ `RelayPool` also exposes `rateLimitRetries`, defaulting to one. The runtime option
1121
+ applies to `sendEvent`, `getEvents`, `getEventsGenerator` and `countEvents`, and
1122
+ each method accepts a per-call override. The budget is independent for each relay
1123
+ and message type; an AUTH retry does not consume the EVENT publication budget.
1124
+ `rateLimitRetries: 0` preserves the previous behavior. Relay advice replaces the
1125
+ local exponential backoff; without advice, retries use 1, 1.5, 2, 4, 8, 16 and
1126
+ 30 seconds and reset after success.
1127
+
1128
+ `maxRateLimitRetryWaitMs` defaults to 1500 and may be overridden per call or set
1129
+ to `null`. Before an automatic retry, the pool computes the effective remaining
1130
+ wait from relay advice and any active cooldown for the same relay/message type.
1131
+ Waits above the gate return the original bounded rate-limit error immediately.
1132
+ Success resets only the local backoff; an
1133
+ unexpired `retryAt` from a concurrent relay response remains authoritative.
1134
+ An existing operation deadline is never extended, so a retry whose next deadline
1135
+ would expire at or after the operation deadline returns the original bounded
1136
+ rate-limit error immediately.
1137
+
1138
+ For publication, the first accepted relay aborts retries that are still waiting
1139
+ on other relays; attempts already in flight may finish. Bulk retries retain the
1140
+ active queue position and do not allow later work to overtake them. Intermediate
1141
+ attempts do not reach callbacks, generators or aggregate reports. They may emit
1142
+ the sanitized `relay rate-limit retry` debug record with only relay URL,
1143
+ operation, attempt/count, numeric deadlines and the wait gate. Live and feed recovery keep
1144
+ their specialized reconnect behavior; their internal one-shot gap reads disable
1145
+ the generic retry budget.
1146
+
1147
+ Paged private-channel history and private-message fallback pass
1148
+ `rateLimitRetries: 0`; their range recovery and routing layers own rate-limit
1149
+ retry and fallback timing. Ephemeral one-shots without such recovery retain the
1150
+ guarded default.
1151
+
1152
+ Publication calls for the same event and relay share a physical job only when
1153
+ their pacing is compatible. Calls with the same pacing share one send. An
1154
+ interactive call joins an existing interactive job or a bulk job already removed
1155
+ from the queue and active; it never waits for a queued bulk job and instead may
1156
+ race it. A bulk call prefers an existing interactive job, otherwise it joins the
1157
+ bulk job. Each waiter keeps its own cancellation, operation deadline, timeout,
1158
+ `rateLimitRetries`, retry signal and observed rate-limit count.
1159
+
1160
+ A successful ACK on that relay settles every pending job for the event,
1161
+ including an unsent bulk sibling. Transmissions already started cannot be
1162
+ recalled, and their late responses are ignored. A rejection applies only to
1163
+ jobs whose bytes were transmitted and are awaiting that response, so a queued
1164
+ job remains pending. Success is never propagated across different relay
1165
+ connections. A waiter joining an already scheduled rate-limit retry may share
1166
+ that next attempt even with zero remaining retries; only later rate limits count
1167
+ against its budget.
1120
1168
 
1121
1169
  Rate limits apply only to the client message type that triggered the refusal:
1122
1170
  `EVENT`, `AUTH`, `REQ` and `COUNT` have independent connection cooldowns. Responses
@@ -1297,10 +1345,12 @@ responses are preserved as normalized `retryAt` and `retryAfterMs` on native rel
1297
1345
  errors. Only `rate-limited:`
1298
1346
  responses apply this advice; invalid values are ignored
1299
1347
  and delays are capped by the RelayPool runtime options, defaulting to five
1300
- minutes. New operations of the refused type wait
1348
+ minutes. One-shot operations retry the affected relay according to
1349
+ `rateLimitRetries`, defaulting to one additional attempt. New operations of the refused type wait
1301
1350
  within their existing deadlines; active subscriptions remain live and `CLOSE`
1302
1351
  never waits. Cancelled or timed-out operations cannot be sent later. A rejection
1303
- is still reported to the caller; this does not silently republish failed events.
1352
+ is still reported when retries are exhausted, disabled or cannot finish before
1353
+ the operation deadline; intermediate attempts are not reported as final failures.
1304
1354
 
1305
1355
  `createEventReplyPacker` and `createMissingMessageReplyPacker` accept
1306
1356
  `bytesPerChunk` (default 128 KiB of UTF-8 JSONL), in addition to the existing
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libp2r2p",
3
- "version": "0.12.8",
3
+ "version": "0.12.10",
4
4
  "description": "Peer-to-relay-to-peer",
5
5
  "keywords": [
6
6
  "p2r2p",
@@ -65,7 +65,10 @@ export async function readHistory ({ filter, relays, receiverPubkey, signal, get
65
65
  releasePage = await acquirePage?.(signal)
66
66
  signal?.throwIfAborted()
67
67
  page = await getEvents({ ...filter, ...interval }, [relay], {
68
- signal, timeout: TIMEOUT_MS, timeoutAfterFirstEose: null,
68
+ signal,
69
+ timeout: TIMEOUT_MS,
70
+ timeoutAfterFirstEose: null,
71
+ rateLimitRetries: 0,
69
72
  callback: item => {
70
73
  if (item.type !== 'event') return
71
74
  bytes += encoder.encode(JSON.stringify(item.event)).byteLength
@@ -66,7 +66,13 @@ export function publishWithEarlyFallback ({ event, receivers, first, mirrors, tr
66
66
  const slot = Promise.withResolvers()
67
67
  summaries.push(slot.promise)
68
68
  let result
69
- try { result = await sendEvent(event, relays, { signal: transportSignal, getRetryEvent }) } catch (reason) {
69
+ try {
70
+ result = await sendEvent(event, relays, {
71
+ signal: transportSignal,
72
+ getRetryEvent,
73
+ rateLimitRetries: 0
74
+ })
75
+ } catch (reason) {
70
76
  if (reason?.code === 'RETRY_EVENT_PREPARATION_FAILED') {
71
77
  fail(reason)
72
78
  return
@@ -159,7 +159,11 @@ export function createSendRelayRouting ({ peer, peers = [peer], relaysByPubkey,
159
159
  for (const relay of relays) tried.add(normalized(relay))
160
160
  // Every relay in this batch serves the same pending recipient subset.
161
161
  // One ACK covers that subset, never unrelated members of the ciphertext.
162
- result = await sendEvent(event, relays, { signal: transportSignal, getRetryEvent: context.getRetryEvent })
162
+ result = await sendEvent(event, relays, {
163
+ signal: transportSignal,
164
+ getRetryEvent: context.getRetryEvent,
165
+ rateLimitRetries: 0
166
+ })
163
167
  const settled = Promise.resolve(result.promise)
164
168
  summaries.push(settled)
165
169
  settled.then(report => rememberSuccess(report?.succeededRelays || [])).catch(() => {})
@@ -259,6 +259,14 @@ It returns the existing result/report envelopes with the original abort reason
259
259
  for unfinished relays, preserving partial acceptance and avoiding synthetic
260
260
  timeouts. Cancellation releases publication waiters and deferred sends without
261
261
  closing shared sockets or cancelling another subscriber for the same event ID.
262
+ Rate-limited relay attempts are retried by the pool once by default, within the
263
+ same operation deadline and using the relay's `retryAt` when supplied. A relay
264
+ result reaches the session only after its retry budget is terminal; a first ACK
265
+ from another relay cancels scheduled retries but does not recall work already
266
+ transmitted. Calls sharing an event and relay keep independent cancellation,
267
+ deadline and retry state even when they reuse the same physical publication.
268
+ Success from that relay is shared locally, but never treated as success on a
269
+ different relay.
262
270
  Operations already transmitted cannot be recalled from relays. A messenger pause
263
271
  cancels its outstanding publication work and leaves the outbox pending; resume
264
272
  creates a fresh publication lifetime, without treating the pause as a user abort.
@@ -0,0 +1,24 @@
1
+ // Intermediate automatic retries are intentionally visible only as structured
2
+ // debug data. Never include relay messages, filters, event IDs or payloads.
3
+ export function debugRateLimitRetry ({
4
+ relay,
5
+ operation,
6
+ retryAttempt,
7
+ maxRetries,
8
+ retryAt,
9
+ effectiveWaitMs,
10
+ maxWaitMs
11
+ }) {
12
+ try {
13
+ console.debug('relay rate-limit retry', {
14
+ relay,
15
+ operation,
16
+ retryAttempt,
17
+ maxRetries,
18
+ retryAt,
19
+ delayMs: Math.max(0, retryAt - Date.now()),
20
+ effectiveWaitMs,
21
+ maxWaitMs
22
+ })
23
+ } catch {}
24
+ }
@@ -2,12 +2,15 @@ import { isValidEvent } from '../../event/index.js'
2
2
  import { ValidationError } from '../../error/index.js'
3
3
  import { maybeUnref } from '../helpers/timer.js'
4
4
  import { categorizeRelayError, relayCloseError, relayTimeoutError, relayRejectionError } from '../helpers/error.js'
5
+ import { debugRateLimitRetry } from '../helpers/retry-debug.js'
5
6
  import { DEFAULT_RATE_LIMIT_CAP_MS } from '../helpers/retry-advice.js'
6
7
 
7
8
  const DEFAULT_CONNECT_TIMEOUT = 3000
8
9
  const DEFAULT_OPERATION_TIMEOUT = 30000
9
10
  const BULK_PACING_MS = 1000
10
- const BULK_BACKOFF_MAX_MS = 30000
11
+ const RATE_LIMIT_BACKOFF_MAX_MS = 30000
12
+ const DEFAULT_MAX_RATE_LIMIT_RETRY_WAIT_MS = 1500
13
+ const OPERATION_TYPES = ['EVENT', 'AUTH', 'REQ', 'COUNT']
11
14
 
12
15
  function errorFrom (reason, fallback) {
13
16
  return reason instanceof Error ? reason : new Error(String(reason || fallback))
@@ -30,6 +33,33 @@ function retryAtFrom (value) {
30
33
  return retryAt
31
34
  }
32
35
 
36
+ function nextRateLimitBackoff (delay) {
37
+ if (delay === BULK_PACING_MS) return 1500
38
+ if (delay === 1500) return 2000
39
+ return Math.min(RATE_LIMIT_BACKOFF_MAX_MS, delay * 2)
40
+ }
41
+
42
+ function retryWaitAllowed (retryAt, maxWaitMs, now = Date.now()) {
43
+ return maxWaitMs === null || Math.max(0, retryAt - now) <= maxWaitMs
44
+ }
45
+
46
+ function waitForRetry (deadline, signal, retrySignal) {
47
+ const combined = AbortSignal.any([signal, retrySignal].filter(Boolean))
48
+ if (combined.aborted) return Promise.reject(combined.reason)
49
+ return new Promise((resolve, reject) => {
50
+ const timer = maybeUnref(setTimeout(() => {
51
+ combined.removeEventListener('abort', onAbort)
52
+ resolve()
53
+ }, Math.max(0, deadline - Date.now())))
54
+ const onAbort = () => {
55
+ clearTimeout(timer)
56
+ combined.removeEventListener('abort', onAbort)
57
+ reject(combined.reason)
58
+ }
59
+ combined.addEventListener('abort', onAbort, { once: true })
60
+ })
61
+ }
62
+
33
63
  function hasMatchingPrefix (values, candidate) {
34
64
  return !values || values.some(value => typeof value === 'string' && candidate.startsWith(value))
35
65
  }
@@ -75,13 +105,15 @@ export class RelayConnection {
75
105
  #bulkQueue = []
76
106
  #bulkActive = null
77
107
  #bulkTimer = null
78
- #bulkBackoffMs = BULK_PACING_MS
79
108
  #bulkNextAt = 0
109
+ #rateLimitBackoffMs = new Map(OPERATION_TYPES.map(type => [type, BULK_PACING_MS]))
80
110
  #getRateLimitCapMs
111
+ #defaultMaxRateLimitRetryWaitMs
81
112
 
82
113
  constructor (url, {
83
114
  WebSocket: WebSocketImpl = globalThis.WebSocket,
84
- rateLimitCapMs = () => DEFAULT_RATE_LIMIT_CAP_MS
115
+ rateLimitCapMs = () => DEFAULT_RATE_LIMIT_CAP_MS,
116
+ maxRateLimitRetryWaitMs = DEFAULT_MAX_RATE_LIMIT_RETRY_WAIT_MS
85
117
  } = {}) {
86
118
  this.url = url
87
119
  this.#WebSocket = WebSocketImpl
@@ -91,6 +123,11 @@ export class RelayConnection {
91
123
  this.#getRateLimitCapMs = typeof rateLimitCapMs === 'function'
92
124
  ? rateLimitCapMs
93
125
  : () => rateLimitCapMs
126
+ if (maxRateLimitRetryWaitMs !== null &&
127
+ (!Number.isSafeInteger(maxRateLimitRetryWaitMs) || maxRateLimitRetryWaitMs < 0)) {
128
+ throw new ValidationError('INVALID_MAX_RATE_LIMIT_RETRY_WAIT_MS')
129
+ }
130
+ this.#defaultMaxRateLimitRetryWaitMs = maxRateLimitRetryWaitMs
94
131
  this.ws = null
95
132
  this.publishTimeout = DEFAULT_OPERATION_TIMEOUT
96
133
  this.onnotice = null
@@ -173,7 +210,7 @@ export class RelayConnection {
173
210
 
174
211
  // New work respects relay cooldowns; cleanup uses send() directly. These
175
212
  // waits stay within the caller's existing deadline and are cancellable.
176
- #dispatchWork (type, send, fail) {
213
+ #dispatchWork (type, send, fail, onDispatch) {
177
214
  let timer = null
178
215
  let cancelled = false
179
216
  const wake = () => {
@@ -189,6 +226,7 @@ export class RelayConnection {
189
226
  return
190
227
  }
191
228
  this.#cooldownWaiters.delete(wake)
229
+ onDispatch?.()
192
230
  try { send() } catch (error) { fail(error) }
193
231
  }
194
232
  const dispatch = () => {
@@ -205,10 +243,30 @@ export class RelayConnection {
205
243
 
206
244
  #rejection (type, reason, params, fallback) {
207
245
  const error = relayRejectionError(reason, params, fallback, { rateLimitCapMs: this.#getRateLimitCapMs() })
208
- if (error.retryAt !== undefined) this.#retryAtByType.set(type, Math.max(this.#retryAtByType.get(type) ?? 0, error.retryAt))
246
+ if (error.message?.startsWith('rate-limited:')) {
247
+ const now = Date.now()
248
+ const hasAdvice = Number.isSafeInteger(error.retryAt)
249
+ if (!hasAdvice) {
250
+ const delay = this.#rateLimitBackoffMs.get(type) ?? BULK_PACING_MS
251
+ error.retryAt = now + delay
252
+ error.retryAfterMs = delay
253
+ }
254
+ const delay = this.#rateLimitBackoffMs.get(type) ?? BULK_PACING_MS
255
+ this.#rateLimitBackoffMs.set(type, nextRateLimitBackoff(delay))
256
+ this.#retryAtByType.set(type, Math.max(this.#retryAtByType.get(type) ?? 0, error.retryAt))
257
+ Object.defineProperty(error, 'effectiveRetryAt', {
258
+ value: Math.max(error.retryAt, this.#retryAtByType.get(type) ?? 0),
259
+ enumerable: false,
260
+ configurable: true
261
+ })
262
+ }
209
263
  return error
210
264
  }
211
265
 
266
+ #recordSuccess (type) {
267
+ this.#rateLimitBackoffMs.set(type, BULK_PACING_MS)
268
+ }
269
+
212
270
  subscribe (filters, handlers = {}) {
213
271
  if (!Array.isArray(filters) || !filters.length) throw new ValidationError('SUBSCRIPTION_FILTERS_REQUIRED')
214
272
  const id = `p2r2p-sub:${++this.#serial}`
@@ -236,28 +294,247 @@ export class RelayConnection {
236
294
  return { id, close }
237
295
  }
238
296
 
239
- publish (event, { signal, useBulkPacing = false } = {}) {
297
+ publish (event, {
298
+ signal,
299
+ useBulkPacing = false,
300
+ rateLimitRetries = 0,
301
+ maxRateLimitRetryWaitMs = this.#defaultMaxRateLimitRetryWaitMs,
302
+ retrySignal,
303
+ deadlineAt = null
304
+ } = {}) {
240
305
  if (!isValidEvent(event)) return Promise.reject(new Error('INVALID_EVENT'))
241
306
  if (typeof useBulkPacing !== 'boolean') return Promise.reject(new ValidationError('INVALID_USE_BULK_PACING'))
242
- return this.#sendEventOperation('EVENT', event, this.#publishes, 'PUBLISH_TIMEOUT', signal, { useBulkPacing })
307
+ if (!Number.isSafeInteger(rateLimitRetries) || rateLimitRetries < 0) return Promise.reject(new ValidationError('INVALID_RATE_LIMIT_RETRIES'))
308
+ if (maxRateLimitRetryWaitMs !== null &&
309
+ (!Number.isSafeInteger(maxRateLimitRetryWaitMs) || maxRateLimitRetryWaitMs < 0)) {
310
+ return Promise.reject(new ValidationError('INVALID_MAX_RATE_LIMIT_RETRY_WAIT_MS'))
311
+ }
312
+ return this.#sendEventOperation('EVENT', event, this.#publishes, 'PUBLISH_TIMEOUT', signal, {
313
+ useBulkPacing,
314
+ rateLimitRetries,
315
+ maxRateLimitRetryWaitMs,
316
+ retrySignal,
317
+ deadlineAt
318
+ })
243
319
  }
244
320
 
245
- async authenticate (getAuthEvent, { signal } = {}) {
321
+ async authenticate (getAuthEvent, {
322
+ signal,
323
+ rateLimitRetries = 0,
324
+ maxRateLimitRetryWaitMs = this.#defaultMaxRateLimitRetryWaitMs,
325
+ deadlineAt = null,
326
+ retrySignal
327
+ } = {}) {
246
328
  if (!this.#challenge) throw new Error('AUTH_CHALLENGE_MISSING')
247
- const event = await getAuthEvent({ relay: this.url, challenge: this.#challenge })
248
- if (!isValidEvent(event)) throw new ValidationError('INVALID_AUTH_EVENT')
249
- return await this.#sendEventOperation('AUTH', event, this.#authentications, 'AUTH_TIMEOUT', signal)
329
+ if (!Number.isSafeInteger(rateLimitRetries) || rateLimitRetries < 0) throw new ValidationError('INVALID_RATE_LIMIT_RETRIES')
330
+ if (maxRateLimitRetryWaitMs !== null &&
331
+ (!Number.isSafeInteger(maxRateLimitRetryWaitMs) || maxRateLimitRetryWaitMs < 0)) {
332
+ throw new ValidationError('INVALID_MAX_RATE_LIMIT_RETRY_WAIT_MS')
333
+ }
334
+ let lastRateLimitError = null
335
+ for (let attempt = 0; ; attempt++) {
336
+ if (signal?.aborted) throw signal.reason
337
+ if (deadlineAt !== null && Date.now() >= deadlineAt) {
338
+ throw lastRateLimitError ?? relayTimeoutError('AUTH_TIMEOUT', this.#lastTransportError)
339
+ }
340
+ const event = await getAuthEvent({ relay: this.url, challenge: this.#challenge })
341
+ if (!isValidEvent(event)) throw new ValidationError('INVALID_AUTH_EVENT')
342
+ try {
343
+ return await this.#sendEventOperation('AUTH', event, this.#authentications, 'AUTH_TIMEOUT', signal, { deadlineAt })
344
+ } catch (error) {
345
+ if (!error?.message?.startsWith('rate-limited:') || attempt >= rateLimitRetries) throw error
346
+ const retryAt = Math.max(
347
+ retryAtFrom(error),
348
+ this.#retryAtByType.get('AUTH') ?? 0
349
+ )
350
+ if (!retryAt || (deadlineAt !== null && retryAt >= deadlineAt)) throw error
351
+ if (!retryWaitAllowed(retryAt, maxRateLimitRetryWaitMs)) throw error
352
+ debugRateLimitRetry({
353
+ relay: this.url,
354
+ operation: 'AUTH',
355
+ retryAttempt: attempt + 1,
356
+ maxRetries: rateLimitRetries,
357
+ retryAt,
358
+ effectiveWaitMs: Math.max(0, retryAt - Date.now()),
359
+ maxWaitMs: maxRateLimitRetryWaitMs
360
+ })
361
+ lastRateLimitError = error
362
+ try {
363
+ await waitForRetry(retryAt, signal, retrySignal)
364
+ } catch (cause) {
365
+ if (retrySignal?.aborted) throw error
366
+ throw cause
367
+ }
368
+ }
369
+ }
370
+ }
371
+
372
+ // A job owns physical transmission and scheduling. Its waiters retain
373
+ // per-call cancellation, timeout, deadline and retry policy.
374
+ #mapForType (type) {
375
+ return type === 'EVENT' ? this.#publishes : this.#authentications
376
+ }
377
+
378
+ #hasJob (job) {
379
+ return this.#mapForType(job.type).get(job.event.id)?.has(job) === true
380
+ }
381
+
382
+ #findJob (map, id, pacing) {
383
+ for (const job of map.get(id) ?? []) {
384
+ if (job.pacing === pacing) return job
385
+ }
386
+ return null
387
+ }
388
+
389
+ #selectJob (map, event, useBulkPacing) {
390
+ const interactive = this.#findJob(map, event.id, 'interactive')
391
+ if (!useBulkPacing) {
392
+ if (interactive) return interactive
393
+ // Interactive work may benefit from a bulk send already in progress,
394
+ // but must never wait behind a bulk job that is still queued.
395
+ const activeBulk = this.#findJob(map, event.id, 'bulk')
396
+ return activeBulk?.state === 'active' ? activeBulk : null
397
+ }
398
+ if (interactive) return interactive
399
+ return this.#findJob(map, event.id, 'bulk')
400
+ }
401
+
402
+ #addJob (job) {
403
+ const map = this.#mapForType(job.type)
404
+ let jobs = map.get(job.event.id)
405
+ if (!jobs) {
406
+ jobs = new Set()
407
+ map.set(job.event.id, jobs)
408
+ }
409
+ jobs.add(job)
410
+ }
411
+
412
+ #allJobs (map) {
413
+ const jobs = []
414
+ for (const set of map.values()) jobs.push(...set)
415
+ return jobs
416
+ }
417
+
418
+ #cleanupWaiter (job, waiter) {
419
+ clearTimeout(waiter.timer)
420
+ waiter.signal?.removeEventListener('abort', waiter.onAbort)
421
+ waiter.retrySignal?.removeEventListener('abort', waiter.onRetryAbort)
422
+ job.waiters.delete(waiter)
250
423
  }
251
424
 
252
- #removeBulkPublish (pending) {
253
- const index = this.#bulkQueue.indexOf(pending)
425
+ #detachJob (job) {
426
+ if (job.detached) return
427
+ job.detached = true
428
+ job.awaitingAck = false
429
+ job.retryScheduled = false
430
+ const map = this.#mapForType(job.type)
431
+ const jobs = map.get(job.event.id)
432
+ if (jobs) {
433
+ jobs.delete(job)
434
+ if (!jobs.size) map.delete(job.event.id)
435
+ }
436
+ job.cancelSend?.()
437
+ job.cancelSend = null
438
+ const index = this.#bulkQueue.indexOf(job)
254
439
  if (index >= 0) this.#bulkQueue.splice(index, 1)
255
- if (this.#bulkActive === pending) {
440
+ const wasActive = this.#bulkActive === job
441
+ if (wasActive) {
256
442
  this.#bulkActive = null
257
- pending.onSettled = null
258
- this.#bulkNextAt = Math.max(this.#bulkNextAt, Date.now() + BULK_PACING_MS)
443
+ this.#bulkNextAt = Math.max(this.#bulkNextAt, Date.now(), job.startedAt + BULK_PACING_MS)
259
444
  }
260
- this.#pumpBulkPublishes()
445
+ if (!this.#bulkActive) this.#pumpBulkPublishes()
446
+ }
447
+
448
+ #settleJob (job, reason, value) {
449
+ if (job.settled) return
450
+ job.settled = true
451
+ const waiters = [...job.waiters]
452
+ for (const waiter of waiters) this.#cleanupWaiter(job, waiter)
453
+ this.#detachJob(job)
454
+ for (const waiter of waiters) {
455
+ if (reason) waiter.reject(errorFrom(reason, 'OPERATION_REJECTED'))
456
+ else waiter.resolve(value)
457
+ }
458
+ }
459
+
460
+ #removeWaiter (job, waiter, reason) {
461
+ if (!job.waiters.has(waiter)) return
462
+ this.#cleanupWaiter(job, waiter)
463
+ waiter.reject(errorFrom(reason, 'OPERATION_REJECTED'))
464
+ if (!job.waiters.size) {
465
+ job.settled = true
466
+ this.#detachJob(job)
467
+ }
468
+ }
469
+
470
+ #canShareScheduledRetry (waiter, retryAt) {
471
+ return !waiter.retrySignal?.aborted &&
472
+ (waiter.deadlineAt === null || retryAt < waiter.deadlineAt)
473
+ }
474
+
475
+ #canRetryAfterLimit (waiter, retryAt) {
476
+ return waiter.observedRateLimitFailures <= waiter.rateLimitRetries &&
477
+ retryWaitAllowed(retryAt, waiter.maxRateLimitRetryWaitMs) &&
478
+ this.#canShareScheduledRetry(waiter, retryAt)
479
+ }
480
+
481
+ #pruneScheduledRetryWaiters (job) {
482
+ if (!job.retryScheduled || !job.lastRateLimitError) return
483
+ for (const waiter of [...job.waiters]) {
484
+ if (!this.#canShareScheduledRetry(waiter, job.retryAt)) {
485
+ this.#removeWaiter(job, waiter, job.lastRateLimitError)
486
+ }
487
+ }
488
+ }
489
+
490
+ #expireWaiter (job, waiter) {
491
+ const reason = job.retryScheduled && job.lastRateLimitError
492
+ ? job.lastRateLimitError
493
+ : relayTimeoutError(job.timeoutCode, this.#lastTransportError)
494
+ this.#removeWaiter(job, waiter, reason)
495
+ this.#pruneScheduledRetryWaiters(job)
496
+ }
497
+
498
+ #abortWaiterRetry (job, waiter) {
499
+ if (!job.retryScheduled || !job.lastRateLimitError) return
500
+ this.#removeWaiter(job, waiter, job.lastRateLimitError)
501
+ this.#pruneScheduledRetryWaiters(job)
502
+ }
503
+
504
+ #addWaiter (job, {
505
+ signal,
506
+ retrySignal,
507
+ deadlineAt,
508
+ rateLimitRetries,
509
+ maxRateLimitRetryWaitMs
510
+ }) {
511
+ const deferred = Promise.withResolvers()
512
+ const waiter = {
513
+ ...deferred,
514
+ signal,
515
+ retrySignal,
516
+ deadlineAt,
517
+ rateLimitRetries,
518
+ maxRateLimitRetryWaitMs,
519
+ observedRateLimitFailures: 0,
520
+ timer: null,
521
+ onAbort: null,
522
+ onRetryAbort: null
523
+ }
524
+ job.waiters.add(waiter)
525
+ waiter.onAbort = () => this.#removeWaiter(job, waiter, signal.reason)
526
+ waiter.onRetryAbort = () => this.#abortWaiterRetry(job, waiter)
527
+ signal?.addEventListener('abort', waiter.onAbort, { once: true })
528
+ retrySignal?.addEventListener('abort', waiter.onRetryAbort, { once: true })
529
+ let timeout = this.publishTimeout
530
+ if (!signal && deadlineAt !== null) timeout = Math.min(timeout, Math.max(0, deadlineAt - Date.now()))
531
+ waiter.timer = maybeUnref(setTimeout(() => this.#expireWaiter(job, waiter), timeout))
532
+
533
+ if (signal?.aborted) this.#removeWaiter(job, waiter, signal.reason)
534
+ else if (job.retryScheduled && !this.#canShareScheduledRetry(waiter, job.retryAt)) {
535
+ this.#removeWaiter(job, waiter, job.lastRateLimitError)
536
+ }
537
+ return deferred.promise
261
538
  }
262
539
 
263
540
  #clearBulkScheduler () {
@@ -266,7 +543,6 @@ export class RelayConnection {
266
543
  this.#bulkQueue.length = 0
267
544
  this.#bulkActive = null
268
545
  this.#bulkNextAt = 0
269
- this.#bulkBackoffMs = BULK_PACING_MS
270
546
  }
271
547
 
272
548
  #pumpBulkPublishes () {
@@ -274,8 +550,8 @@ export class RelayConnection {
274
550
  clearTimeout(this.#bulkTimer)
275
551
  this.#bulkTimer = null
276
552
  while (this.#bulkQueue.length) {
277
- const pending = this.#bulkQueue[0]
278
- if (this.#publishes.get(pending.event.id) === pending && pending.waiters.size > 0) break
553
+ const job = this.#bulkQueue[0]
554
+ if (this.#hasJob(job) && job.waiters.size > 0) break
279
555
  this.#bulkQueue.shift()
280
556
  }
281
557
  if (!this.#bulkQueue.length) return
@@ -287,72 +563,115 @@ export class RelayConnection {
287
563
  return
288
564
  }
289
565
 
290
- const pending = this.#bulkQueue.shift()
566
+ const job = this.#bulkQueue.shift()
291
567
  const startedAt = now
292
- this.#bulkActive = pending
293
- pending.onSettled = (success, reason) => {
294
- if (this.#bulkActive !== pending) return
295
- this.#bulkActive = null
296
- pending.onSettled = null
297
- const completedAt = Date.now()
298
- const hintedRetryAt = retryAtFrom(reason)
299
- if (success) {
300
- this.#bulkBackoffMs = BULK_PACING_MS
301
- this.#bulkNextAt = Math.max(completedAt, startedAt + BULK_PACING_MS)
302
- } else if (hintedRetryAt) {
303
- // The relay advice overrides the local backoff for this retry.
304
- this.#bulkNextAt = Math.max(completedAt, startedAt + BULK_PACING_MS)
305
- this.#bulkBackoffMs = Math.min(BULK_BACKOFF_MAX_MS, this.#bulkBackoffMs * 2)
306
- } else {
307
- this.#bulkNextAt = Math.max(completedAt + this.#bulkBackoffMs, startedAt + BULK_PACING_MS)
308
- this.#bulkBackoffMs = Math.min(BULK_BACKOFF_MAX_MS, this.#bulkBackoffMs * 2)
568
+ job.state = 'active'
569
+ job.startedAt = startedAt
570
+ this.#bulkActive = job
571
+ this.#dispatchEventAttempt(job)
572
+ }
573
+
574
+ #dispatchEventAttempt (job) {
575
+ const cancel = this.#dispatchWork(job.type, () => {
576
+ if (!this.#hasJob(job)) return
577
+ const retrying = job.retryScheduled
578
+ for (const waiter of [...job.waiters]) {
579
+ if (waiter.deadlineAt !== null && Date.now() >= waiter.deadlineAt) {
580
+ this.#removeWaiter(job, waiter, retrying && job.lastRateLimitError
581
+ ? job.lastRateLimitError
582
+ : relayTimeoutError(job.timeoutCode, this.#lastTransportError))
583
+ }
584
+ }
585
+ if (!job.waiters.size) return
586
+ job.retryScheduled = false
587
+ job.awaitingAck = true
588
+ try {
589
+ this.send(JSON.stringify([job.type, job.event]))
590
+ } catch (error) {
591
+ job.awaitingAck = false
592
+ throw error
593
+ }
594
+ }, error => {
595
+ job.awaitingAck = false
596
+ this.#settleJob(job, error)
597
+ })
598
+ job.cancelSend = cancel
599
+ if (!this.#hasJob(job)) cancel()
600
+ }
601
+
602
+ #applyRateLimit (job, reason) {
603
+ job.awaitingAck = false
604
+ job.lastRateLimitError = reason
605
+ const retryAt = Math.max(
606
+ retryAtFrom(reason),
607
+ this.#retryAtByType.get(job.type) ?? 0
608
+ )
609
+ for (const waiter of [...job.waiters]) {
610
+ waiter.observedRateLimitFailures++
611
+ if (!retryAt || !this.#canRetryAfterLimit(waiter, retryAt)) {
612
+ this.#removeWaiter(job, waiter, reason)
309
613
  }
310
- this.#pumpBulkPublishes()
311
614
  }
312
- pending.cancelSend = this.#dispatchWork('EVENT', () => {
313
- this.send(JSON.stringify(['EVENT', pending.event]))
314
- }, error => this.#settleEvent(this.#publishes, pending.event.id, error))
615
+ if (!job.waiters.size) return
616
+ job.retryAt = retryAt
617
+ job.retryScheduled = true
618
+ job.retryAttempts++
619
+ const waitLimits = [...job.waiters].map(waiter => waiter.maxRateLimitRetryWaitMs)
620
+ debugRateLimitRetry({
621
+ relay: this.url,
622
+ operation: job.type,
623
+ retryAttempt: job.retryAttempts,
624
+ maxRetries: Math.max(...[...job.waiters].map(waiter => waiter.rateLimitRetries)),
625
+ retryAt,
626
+ effectiveWaitMs: Math.max(0, retryAt - Date.now()),
627
+ maxWaitMs: waitLimits.includes(null) ? null : Math.max(...waitLimits)
628
+ })
629
+ this.#dispatchEventAttempt(job)
315
630
  }
316
631
 
317
- #sendEventOperation (type, event, map, timeoutCode, signal, { useBulkPacing = false } = {}) {
632
+ #sendEventOperation (type, event, map, timeoutCode, signal, {
633
+ useBulkPacing = false,
634
+ rateLimitRetries = 0,
635
+ maxRateLimitRetryWaitMs = this.#defaultMaxRateLimitRetryWaitMs,
636
+ retrySignal,
637
+ deadlineAt = null
638
+ } = {}) {
318
639
  if (signal?.aborted) return Promise.reject(signal.reason)
319
- let pending = map.get(event.id)
320
- const created = !pending
640
+ let job = this.#selectJob(map, event, useBulkPacing && type === 'EVENT')
641
+ const created = !job
321
642
  if (created) {
322
- const timer = maybeUnref(setTimeout(() => this.#settleEvent(map, event.id, relayTimeoutError(timeoutCode, this.#lastTransportError)), this.publishTimeout))
323
- pending = { timer, waiters: new Set(), cancelSend: null, event, type, timeoutCode, useBulkPacing, onSettled: null }
324
- map.set(event.id, pending)
325
- }
326
- const deferred = Promise.withResolvers()
327
- const onAbort = () => {
328
- pending.waiters.delete(waiter)
329
- signal.removeEventListener('abort', onAbort)
330
- deferred.reject(signal.reason)
331
- if (!pending.waiters.size && map.get(event.id) === pending) {
332
- map.delete(event.id)
333
- pending.cancelSend?.()
334
- clearTimeout(pending.timer)
335
- if (this.#bulkActive === pending) {
336
- this.#bulkActive = null
337
- pending.onSettled = null
338
- this.#bulkNextAt = Math.max(this.#bulkNextAt, Date.now() + BULK_PACING_MS)
339
- this.#pumpBulkPublishes()
340
- }
643
+ job = {
644
+ waiters: new Set(),
645
+ cancelSend: null,
646
+ event,
647
+ type,
648
+ timeoutCode,
649
+ pacing: useBulkPacing && type === 'EVENT' ? 'bulk' : 'interactive',
650
+ state: useBulkPacing && type === 'EVENT' ? 'queued' : 'active',
651
+ startedAt: 0,
652
+ retryAttempts: 0,
653
+ lastRateLimitError: null,
654
+ retryAt: 0,
655
+ retryScheduled: false,
656
+ awaitingAck: false,
657
+ detached: false,
658
+ settled: false
341
659
  }
660
+ this.#addJob(job)
342
661
  }
343
- const waiter = { ...deferred, stopAbort: () => signal?.removeEventListener('abort', onAbort) }
344
- pending.waiters.add(waiter)
345
- signal?.addEventListener('abort', onAbort, { once: true })
346
- if (created && useBulkPacing && type === 'EVENT') {
347
- pending.cancelSend = () => this.#removeBulkPublish(pending)
348
- this.#bulkQueue.push(pending)
662
+ const promise = this.#addWaiter(job, {
663
+ signal,
664
+ retrySignal,
665
+ deadlineAt,
666
+ rateLimitRetries,
667
+ maxRateLimitRetryWaitMs
668
+ })
669
+ if (!created || !this.#hasJob(job)) return promise
670
+ if (job.pacing === 'bulk') {
671
+ this.#bulkQueue.push(job)
349
672
  this.#pumpBulkPublishes()
350
- } else if (created) {
351
- pending.cancelSend = this.#dispatchWork(type, () => {
352
- this.send(JSON.stringify([type, event]))
353
- }, error => this.#settleEvent(map, event.id, error))
354
- }
355
- return deferred.promise
673
+ } else this.#dispatchEventAttempt(job)
674
+ return promise
356
675
  }
357
676
 
358
677
  countWithHll (filters, { signal } = {}) {
@@ -369,25 +688,26 @@ export class RelayConnection {
369
688
  return deferred.promise
370
689
  }
371
690
 
372
- #settleEvent (map, id, reason, value) {
373
- const pending = map.get(id)
374
- if (!pending) return
375
- map.delete(id)
376
- pending.cancelSend?.()
377
- clearTimeout(pending.timer)
378
- pending.onSettled?.(!reason, reason)
379
- for (const waiter of pending.waiters) {
380
- waiter.stopAbort()
381
- if (reason) waiter.reject(errorFrom(reason, 'OPERATION_REJECTED'))
382
- else waiter.resolve(value)
691
+ #settleJobsSuccess (jobs, value) {
692
+ for (const job of [...jobs]) this.#settleJob(job, null, value)
693
+ }
694
+
695
+ #handleOkFailure (jobs, type, message, params) {
696
+ const awaiting = [...jobs].filter(job => job.awaitingAck)
697
+ if (!awaiting.length) return
698
+ const reason = this.#rejection(type, message, params, 'EVENT_REJECTED')
699
+ for (const job of awaiting) {
700
+ job.awaitingAck = false
701
+ if (reason.message?.startsWith('rate-limited:')) this.#applyRateLimit(job, reason)
702
+ else this.#settleJob(job, reason)
383
703
  }
384
- pending.waiters.clear()
385
704
  }
386
705
 
387
706
  #settleCount (id, payload, reason) {
388
707
  const pending = this.#counts.get(id)
389
708
  if (!pending) return
390
709
  this.#counts.delete(id)
710
+ if (!reason) this.#recordSuccess('COUNT')
391
711
  pending.cancelSend?.()
392
712
  pending.signal?.removeEventListener('abort', pending.onAbort)
393
713
  if (reason) pending.reject(errorFrom(reason, 'COUNT_REJECTED'))
@@ -411,7 +731,11 @@ export class RelayConnection {
411
731
  return
412
732
  }
413
733
  if (data[0] === 'EOSE') {
414
- this.#subscriptions.get(data[1])?.handlers.oneose?.()
734
+ const subscription = this.#subscriptions.get(data[1])
735
+ if (subscription) {
736
+ this.#recordSuccess('REQ')
737
+ subscription.handlers.oneose?.()
738
+ }
415
739
  return
416
740
  }
417
741
  if (data[0] === 'CLOSED') {
@@ -427,10 +751,17 @@ export class RelayConnection {
427
751
  return
428
752
  }
429
753
  if (data[0] === 'OK') {
430
- for (const [type, pending] of [['EVENT', this.#publishes], ['AUTH', this.#authentications]]) {
431
- if (!pending.has(data[1])) continue
432
- const reason = data[2] === true ? null : this.#rejection(type, data[3], data[4], 'EVENT_REJECTED')
433
- this.#settleEvent(pending, data[1], reason, data[3])
754
+ for (const [type, map] of [['EVENT', this.#publishes], ['AUTH', this.#authentications]]) {
755
+ const jobs = map.get(data[1])
756
+ if (!jobs || ![...jobs].some(job => job.awaitingAck)) continue
757
+ if (data[2] === true) {
758
+ this.#recordSuccess(type)
759
+ // The same relay accepted this exact event. Settle every pacing job
760
+ // locally, including copies that have not started transmission.
761
+ this.#settleJobsSuccess(jobs, data[3])
762
+ } else {
763
+ this.#handleOkFailure(jobs, type, data[3], data[4])
764
+ }
434
765
  }
435
766
  return
436
767
  }
@@ -454,10 +785,10 @@ export class RelayConnection {
454
785
  subscription.cancelSend?.()
455
786
  subscription.handlers.onclose?.(reason)
456
787
  }
457
- for (const id of [...this.#publishes.keys()]) this.#settleEvent(this.#publishes, id, reason)
458
- for (const id of [...this.#authentications.keys()]) this.#settleEvent(this.#authentications, id, reason)
459
- for (const id of [...this.#counts.keys()]) this.#settleCount(id, null, reason)
788
+ const jobs = [...this.#allJobs(this.#publishes), ...this.#allJobs(this.#authentications)]
460
789
  this.#clearBulkScheduler()
790
+ for (const job of jobs) this.#settleJob(job, reason)
791
+ for (const id of [...this.#counts.keys()]) this.#settleCount(id, null, reason)
461
792
  this.onclose?.(reason)
462
793
  }
463
794
 
@@ -471,10 +802,10 @@ export class RelayConnection {
471
802
  subscription.cancelSend?.()
472
803
  subscription.handlers.onclose?.()
473
804
  }
474
- for (const id of [...this.#publishes.keys()]) this.#settleEvent(this.#publishes, id, reason)
475
- for (const id of [...this.#authentications.keys()]) this.#settleEvent(this.#authentications, id, reason)
476
- for (const id of [...this.#counts.keys()]) this.#settleCount(id, null, reason)
805
+ const jobs = [...this.#allJobs(this.#publishes), ...this.#allJobs(this.#authentications)]
477
806
  this.#clearBulkScheduler()
807
+ for (const job of jobs) this.#settleJob(job, reason)
808
+ for (const id of [...this.#counts.keys()]) this.#settleCount(id, null, reason)
478
809
  if (socket && socket.readyState < 2) socket.close()
479
810
  }
480
811
  }
@@ -8,6 +8,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
10
  import { DEFAULT_RATE_LIMIT_CAP_MS } from '../helpers/retry-advice.js'
11
+ import { debugRateLimitRetry } from '../helpers/retry-debug.js'
11
12
  import { normalizeRelayUrl } from '../../url/index.js'
12
13
  import { isValidEvent } from '../../event/index.js'
13
14
  import { RelayConnection } from './relay-connection.js'
@@ -18,6 +19,7 @@ const COUNT_TIMEOUT_AFTER_FIRST_COUNT_MS = 500
18
19
  const SEND_TIMEOUT_MS = 30000
19
20
  const LIVE_OVERLAP_SECONDS = 600
20
21
  const LIVE_PROGRESS_INTERVAL_MS = 60000
22
+ const DEFAULT_MAX_RATE_LIMIT_RETRY_WAIT_MS = 1500
21
23
 
22
24
  // Returns a function that should be called for each received event (valid or invalid).
23
25
  // Calls onSatisfied() and stops counting once the filter is fully satisfied per relay:
@@ -107,6 +109,41 @@ function validateRateLimitCapMs (value) {
107
109
  return value
108
110
  }
109
111
 
112
+ function validateRateLimitRetries (value) {
113
+ if (!Number.isSafeInteger(value) || value < 0) throw new ValidationError('INVALID_RATE_LIMIT_RETRIES')
114
+ return value
115
+ }
116
+
117
+ function validateMaxRateLimitRetryWaitMs (value) {
118
+ if (value !== null && (!Number.isSafeInteger(value) || value < 0)) {
119
+ throw new ValidationError('INVALID_MAX_RATE_LIMIT_RETRY_WAIT_MS')
120
+ }
121
+ return value
122
+ }
123
+
124
+ function effectiveRetryAt (value) {
125
+ const pending = [value]
126
+ const seen = new Set()
127
+ let retryAt = 0
128
+ while (pending.length) {
129
+ const current = pending.pop()
130
+ if (!current || typeof current !== 'object' || seen.has(current)) continue
131
+ seen.add(current)
132
+ for (const key of ['retryAt', 'effectiveRetryAt']) {
133
+ if (Number.isSafeInteger(current[key])) retryAt = Math.max(retryAt, current[key])
134
+ }
135
+ for (const key of ['cause', 'reason', 'error']) pending.push(current[key])
136
+ for (const key of ['errors', 'reports', 'relays']) {
137
+ if (Array.isArray(current[key])) pending.push(...current[key])
138
+ }
139
+ }
140
+ return retryAt
141
+ }
142
+
143
+ function retryWaitAllowed (retryAt, maxWaitMs, now = Date.now()) {
144
+ return maxWaitMs === null || Math.max(0, retryAt - now) <= maxWaitMs
145
+ }
146
+
110
147
  function assertReadOptions (filter, timeouts) {
111
148
  if (!filter || typeof filter !== 'object' || Array.isArray(filter)) throw new ValidationError('INVALID_FILTER')
112
149
  for (const value of Object.values(timeouts)) {
@@ -161,8 +198,21 @@ export class RelayPool {
161
198
  #readRetry
162
199
  #options
163
200
 
164
- constructor ({ _createRelay, _isOnline, _onOnline, WebSocket: WebSocketImpl, rateLimitCapMs = DEFAULT_RATE_LIMIT_CAP_MS, ...capacity } = {}) {
165
- this.#options = { rateLimitCapMs: validateRateLimitCapMs(rateLimitCapMs) }
201
+ constructor ({
202
+ _createRelay,
203
+ _isOnline,
204
+ _onOnline,
205
+ WebSocket: WebSocketImpl,
206
+ rateLimitCapMs = DEFAULT_RATE_LIMIT_CAP_MS,
207
+ rateLimitRetries = 1,
208
+ maxRateLimitRetryWaitMs = DEFAULT_MAX_RATE_LIMIT_RETRY_WAIT_MS,
209
+ ...capacity
210
+ } = {}) {
211
+ this.#options = {
212
+ rateLimitCapMs: validateRateLimitCapMs(rateLimitCapMs),
213
+ rateLimitRetries: validateRateLimitRetries(rateLimitRetries),
214
+ maxRateLimitRetryWaitMs: validateMaxRateLimitRetryWaitMs(maxRateLimitRetryWaitMs)
215
+ }
166
216
  this.#WebSocket = WebSocketImpl
167
217
  this.#createRelay = _createRelay ?? (url => new RelayConnection(url, {
168
218
  ...(this.#WebSocket ? { WebSocket: this.#WebSocket } : {}),
@@ -178,15 +228,29 @@ export class RelayPool {
178
228
 
179
229
  setOptions (partial = {}) {
180
230
  if (!partial || typeof partial !== 'object' || Array.isArray(partial)) throw new ValidationError('INVALID_RELAY_POOL_OPTIONS')
181
- const unknown = Object.keys(partial).find(key => key !== 'rateLimitCapMs')
231
+ const unknown = Object.keys(partial).find(key => !['rateLimitCapMs', 'rateLimitRetries', 'maxRateLimitRetryWaitMs'].includes(key))
182
232
  if (unknown) throw new ValidationError('UNKNOWN_RELAY_POOL_OPTION')
183
233
  const next = { ...this.#options }
184
234
  if (Object.hasOwn(partial, 'rateLimitCapMs')) next.rateLimitCapMs = validateRateLimitCapMs(partial.rateLimitCapMs)
235
+ if (Object.hasOwn(partial, 'rateLimitRetries')) next.rateLimitRetries = validateRateLimitRetries(partial.rateLimitRetries)
236
+ if (Object.hasOwn(partial, 'maxRateLimitRetryWaitMs')) {
237
+ next.maxRateLimitRetryWaitMs = validateMaxRateLimitRetryWaitMs(partial.maxRateLimitRetryWaitMs)
238
+ }
185
239
  this.#options = next
186
240
  for (const relay of this.#relays.values()) relay.setRateLimitCapMs?.(next.rateLimitCapMs)
187
241
  return this.getOptions()
188
242
  }
189
243
 
244
+ #retryCount (value) {
245
+ return validateRateLimitRetries(value === undefined ? this.#options.rateLimitRetries : value)
246
+ }
247
+
248
+ #maxRetryWait (value) {
249
+ return validateMaxRateLimitRetryWaitMs(
250
+ value === undefined ? this.#options.maxRateLimitRetryWaitMs : value
251
+ )
252
+ }
253
+
190
254
  // Injects the WebSocket implementation used by new pooled connections (e.g.
191
255
  // a launcher-owned relay multiplexer). Existing connections keep the
192
256
  // implementation they were created with.
@@ -276,21 +340,48 @@ export class RelayPool {
276
340
 
277
341
  // NIP-42 retries happen inside one relay attempt, so sendEvent still reports
278
342
  // exactly one terminal outcome for each relay URL.
279
- async #publishEvent (relay, event, getAuthEvent, signal, useBulkPacing) {
343
+ async #publishEvent (relay, event, getAuthEvent, signal, {
344
+ useBulkPacing,
345
+ rateLimitRetries,
346
+ maxRateLimitRetryWaitMs,
347
+ retrySignal,
348
+ deadlineAt
349
+ }) {
280
350
  try {
281
- await relay.publish(event, { signal, useBulkPacing })
351
+ await relay.publish(event, {
352
+ signal,
353
+ useBulkPacing,
354
+ rateLimitRetries,
355
+ maxRateLimitRetryWaitMs,
356
+ retrySignal,
357
+ deadlineAt
358
+ })
282
359
  return 'published'
283
360
  } catch (error) {
284
361
  const reason = error instanceof Error ? error : new Error(String(error))
285
362
  if (!getAuthEvent || !requiresNip42Auth(reason)) throw reason
286
363
 
287
364
  try {
288
- await relay.authenticate(getAuthEvent, { signal })
365
+ await relay.authenticate(getAuthEvent, {
366
+ signal,
367
+ rateLimitRetries,
368
+ maxRateLimitRetryWaitMs,
369
+ retrySignal,
370
+ deadlineAt
371
+ })
289
372
  } catch (error) {
290
373
  const authReason = error instanceof Error ? error : new Error(String(error))
374
+ if (retrySignal?.aborted && authReason.message?.startsWith('rate-limited:')) throw authReason
291
375
  throw new Nip42AuthenticationError(authReason)
292
376
  }
293
- await relay.publish(event, { signal, useBulkPacing })
377
+ await relay.publish(event, {
378
+ signal,
379
+ useBulkPacing,
380
+ rateLimitRetries,
381
+ maxRateLimitRetryWaitMs,
382
+ retrySignal,
383
+ deadlineAt
384
+ })
294
385
  return 'published'
295
386
  }
296
387
  }
@@ -301,12 +392,16 @@ export class RelayPool {
301
392
  async countEvents (filter, relays, {
302
393
  timeout = COUNT_TIMEOUT_MS,
303
394
  timeoutAfterFirstCount = COUNT_TIMEOUT_AFTER_FIRST_COUNT_MS,
304
- signal
395
+ signal,
396
+ rateLimitRetries,
397
+ maxRateLimitRetryWaitMs
305
398
  } = {}) {
306
399
  if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
307
400
  throw new ValidationError('COUNT_FILTER_REQUIRED')
308
401
  }
309
402
  if (signal?.aborted) throw new Error('Aborted')
403
+ const retries = this.#retryCount(rateLimitRetries)
404
+ const maxRetryWait = this.#maxRetryWait(maxRateLimitRetryWaitMs)
310
405
 
311
406
  const urls = normalizedRelayUrls(relays)
312
407
  if (!urls.length) {
@@ -314,6 +409,10 @@ export class RelayPool {
314
409
  }
315
410
 
316
411
  const countController = new AbortController()
412
+ const retryControllers = new Map()
413
+ const retryCounts = new Map(urls.map(url => [url, 0]))
414
+ const retryErrors = new Map()
415
+ const deadline = timeout === null ? null : Date.now() + timeout
317
416
  const pending = new Set(urls)
318
417
  const errors = []
319
418
  let count = null
@@ -327,6 +426,8 @@ export class RelayPool {
327
426
  const cleanup = () => {
328
427
  clearTimeout(timeoutTimer)
329
428
  clearTimeout(graceTimer)
429
+ for (const controller of retryControllers.values()) controller.abort()
430
+ retryControllers.clear()
330
431
  signal?.removeEventListener('abort', onAbort)
331
432
  countController.abort()
332
433
  }
@@ -395,13 +496,51 @@ export class RelayPool {
395
496
  }
396
497
 
397
498
  const handleError = (relay, error) => {
398
- if (isResolved || !settleRelay(relay)) return
399
499
  const reason = error instanceof Error ? error : new Error(String(error))
500
+ if (isResolved || !pending.has(relay)) return
501
+ const retryAt = effectiveRetryAt(reason)
502
+ if (reason.message?.startsWith('rate-limited:') && retryAt &&
503
+ retryCounts.get(relay) < retries && (deadline === null || retryAt < deadline) &&
504
+ retryWaitAllowed(retryAt, maxRetryWait)) {
505
+ retryCounts.set(relay, retryCounts.get(relay) + 1)
506
+ retryErrors.set(relay, reason)
507
+ debugRateLimitRetry({
508
+ relay,
509
+ operation: 'COUNT',
510
+ retryAttempt: retryCounts.get(relay),
511
+ maxRetries: retries,
512
+ retryAt,
513
+ effectiveWaitMs: Math.max(0, retryAt - Date.now()),
514
+ maxWaitMs: maxRetryWait
515
+ })
516
+ const controller = new AbortController()
517
+ const combined = AbortSignal.any([countController.signal, controller.signal])
518
+ retryControllers.set(relay, controller)
519
+ waitUntil(retryAt, combined)
520
+ .then(() => {
521
+ if (retryControllers.get(relay) === controller) retryControllers.delete(relay)
522
+ if (isResolved || !pending.has(relay)) return
523
+ if (deadline !== null && Date.now() >= deadline) {
524
+ settleRelay(relay)
525
+ errors.push({ relay, reason: retryErrors.get(relay) ?? countTimeoutError() })
526
+ finishIfComplete()
527
+ return
528
+ }
529
+ startCount(relay)
530
+ })
531
+ .catch(cause => {
532
+ if (combined.aborted || isResolved || !pending.has(relay)) return
533
+ if (retryControllers.get(relay) === controller) retryControllers.delete(relay)
534
+ handleError(relay, asError(cause))
535
+ })
536
+ return
537
+ }
538
+ settleRelay(relay)
400
539
  errors.push({ relay, reason })
401
540
  finishIfComplete()
402
541
  }
403
542
 
404
- for (const relay of urls) {
543
+ const startCount = relay => {
405
544
  this.#getRelay(relay)
406
545
  .then(async connection => {
407
546
  if (isResolved) return null
@@ -412,6 +551,7 @@ export class RelayPool {
412
551
  error => handleError(relay, error)
413
552
  )
414
553
  }
554
+ for (const relay of urls) startCount(relay)
415
555
  })
416
556
  }
417
557
 
@@ -419,12 +559,33 @@ export class RelayPool {
419
559
  // grace window; null disables that window so callers wait for every relay or
420
560
  // the operation deadline. Disabling cross-relay deduplication still suppresses
421
561
  // repeated ids from the same relay; callbacks remain immediate in both modes.
422
- async getEvents (filter, relays, { timeout = 5000, timeoutAfterFirstEose = 500, callback, signal, deduplicateAcrossRelays = true, queueTimeout = 30000, _admissions } = {}) {
562
+ async getEvents (filter, relays, {
563
+ timeout = 5000,
564
+ timeoutAfterFirstEose = 500,
565
+ callback,
566
+ signal,
567
+ deduplicateAcrossRelays = true,
568
+ queueTimeout = 30000,
569
+ rateLimitRetries,
570
+ maxRateLimitRetryWaitMs,
571
+ _admissions
572
+ } = {}) {
423
573
  assertReadOptions(filter, { timeout, timeoutAfterFirstEose, queueTimeout })
424
574
  if (typeof deduplicateAcrossRelays !== 'boolean') throw new ValidationError('INVALID_DEDUPLICATE_ACROSS_RELAYS')
425
575
  if (signal?.aborted) throw new Error('Aborted')
576
+ const retries = this.#retryCount(rateLimitRetries)
577
+ const maxRetryWait = this.#maxRetryWait(maxRateLimitRetryWaitMs)
426
578
  const urls = normalizedRelayUrls(relays)
427
579
  const subscriptions = new Map()
580
+ const retryControllers = new Map()
581
+ const retryCounts = new Map(urls.map(url => [url, 0]))
582
+ const deadlines = new Map()
583
+ const remainingTimeout = url => {
584
+ if (timeout === null) return null
585
+ if (!deadlines.has(url)) deadlines.set(url, Date.now() + timeout)
586
+ return Math.max(0, deadlines.get(url) - Date.now())
587
+ }
588
+ const seenIdsByRelay = new Map()
428
589
  const outcomes = new Map()
429
590
  const errors = []
430
591
  const events = []
@@ -440,6 +601,8 @@ export class RelayPool {
440
601
  const cleanup = () => {
441
602
  admissionAbort.abort()
442
603
  for (const timer of timers.values()) clearTimeout(timer)
604
+ for (const controller of retryControllers.values()) controller.abort()
605
+ retryControllers.clear()
443
606
  clearTimeout(eoseTimer)
444
607
  signal?.removeEventListener('abort', onAbort)
445
608
  for (const sub of subscriptions.values()) sub.close()
@@ -492,18 +655,61 @@ export class RelayPool {
492
655
  signal?.addEventListener('abort', onAbort, { once: true })
493
656
  if (!urls.length) { finish(); return }
494
657
 
495
- for (const url of urls) {
496
- const seenIds = eventIds ?? new Set()
497
- const reservation = _admissions?.get(url) ?? this.#admission.acquire(normalizeRelayUrl(url), { history: true, signal: admissionSignal, queueTimeout })
658
+ const scheduleRetry = (url, error) => {
659
+ if (isResolved || outcomes.has(url) || retryControllers.has(url) ||
660
+ retryCounts.get(url) >= retries || !error?.message?.startsWith('rate-limited:')) return false
661
+ const retryAt = effectiveRetryAt(error)
662
+ if (!retryAt || (deadlines.has(url) && retryAt >= deadlines.get(url)) ||
663
+ !retryWaitAllowed(retryAt, maxRetryWait)) return false
664
+ retryCounts.set(url, retryCounts.get(url) + 1)
665
+ debugRateLimitRetry({
666
+ relay: url,
667
+ operation: 'REQ',
668
+ retryAttempt: retryCounts.get(url),
669
+ maxRetries: retries,
670
+ retryAt,
671
+ effectiveWaitMs: Math.max(0, retryAt - Date.now()),
672
+ maxWaitMs: maxRetryWait
673
+ })
674
+ const controller = new AbortController()
675
+ const combined = AbortSignal.any([admissionSignal, controller.signal])
676
+ retryControllers.set(url, controller)
677
+ waitUntil(retryAt, combined)
678
+ .then(() => {
679
+ if (retryControllers.get(url) === controller) retryControllers.delete(url)
680
+ if (isResolved || outcomes.has(url)) return
681
+ if (deadlines.has(url) && Date.now() >= deadlines.get(url)) {
682
+ settleRelay(url, 'error', error)
683
+ finishIfComplete()
684
+ return
685
+ }
686
+ startRelay(url)
687
+ })
688
+ .catch(reason => {
689
+ if (combined.aborted) return
690
+ if (retryControllers.get(url) === controller) retryControllers.delete(url)
691
+ settleRelay(url, 'error', asError(reason))
692
+ finishIfComplete()
693
+ })
694
+ return true
695
+ }
696
+ const startRelay = url => {
697
+ const seenIds = eventIds ?? seenIdsByRelay.get(url) ?? new Set()
698
+ if (!eventIds) seenIdsByRelay.set(url, seenIds)
699
+ const existingLease = leases.get(url)
700
+ const reservation = existingLease
701
+ ? Promise.resolve({ history: existingLease })
702
+ : _admissions?.get(url) ?? this.#admission.acquire(normalizeRelayUrl(url), { history: true, signal: admissionSignal, queueTimeout })
498
703
  reservation.then(async slots => {
499
704
  const lease = slots.history
500
705
  if (isResolved || outcomes.has(url)) { lease.release(); return }
501
706
  leases.set(url, lease)
502
- if (timeout !== null) {
707
+ const relayTimeout = remainingTimeout(url)
708
+ if (relayTimeout !== null) {
503
709
  timers.set(url, maybeUnref(setTimeout(() => {
504
710
  settleRelay(url, 'timeout', getEventsTimeoutError())
505
711
  finishIfComplete()
506
- }, timeout)))
712
+ }, relayTimeout)))
507
713
  }
508
714
  const relay = await this.#getRelay(url)
509
715
  if (isResolved || outcomes.has(url)) return
@@ -539,6 +745,12 @@ export class RelayPool {
539
745
  onclose: error => {
540
746
  if (isResolved || outcomes.has(url)) return
541
747
  const reason = error === undefined ? undefined : asError(error)
748
+ if (reason && scheduleRetry(url, reason)) {
749
+ clearTimeout(timers.get(url))
750
+ timers.delete(url)
751
+ subscriptions.delete(url)
752
+ return
753
+ }
542
754
  settleRelay(url, reason ? 'error' : 'closed', reason)
543
755
  subscriptions.delete(url)
544
756
  finishIfComplete()
@@ -552,6 +764,7 @@ export class RelayPool {
552
764
  finishIfComplete()
553
765
  })
554
766
  }
767
+ for (const url of urls) startRelay(url)
555
768
  })
556
769
  }
557
770
 
@@ -886,6 +1099,7 @@ export class RelayPool {
886
1099
  queueTimeout,
887
1100
  timeout: timeoutForReconnectGap,
888
1101
  timeoutAfterFirstEose: timeoutAfterFirstReconnectGapEose,
1102
+ rateLimitRetries: 0,
889
1103
  signal,
890
1104
  _stopSignal: AbortSignal.any([gapAc.signal, attempt.stop.signal])
891
1105
  })
@@ -1109,7 +1323,10 @@ export class RelayPool {
1109
1323
  const options = { timeout, timeoutAfterFirstEose, queueTimeout, signal, _stopSignal }
1110
1324
  if (!live) {
1111
1325
  const bounds = { since: filter.since ?? 0, until: Math.min(filter.until ?? Infinity, Math.floor(Date.now() / 1000)) }
1112
- for await (const item of _eventsGenerator(snapshot ? { ...filter, ...bounds } : filter, relays, options)) {
1326
+ for await (const item of _eventsGenerator(snapshot ? { ...filter, ...bounds } : filter, relays, {
1327
+ ...options,
1328
+ rateLimitRetries: 0
1329
+ })) {
1113
1330
  if (signal.aborted) return
1114
1331
  yield snapshot && item.type === 'eose' ? { ...item, snapshot: bounds } : item
1115
1332
  }
@@ -1140,7 +1357,14 @@ export class RelayPool {
1140
1357
  reservation.catch(() => {})
1141
1358
  reservations.set(url, reservation)
1142
1359
  }
1143
- const readOptions = { ...options, signal: inputSignal, _admissions: reservations, maxBufferedLiveEvents, maxBufferedLiveBytes }
1360
+ const readOptions = {
1361
+ ...options,
1362
+ signal: inputSignal,
1363
+ _admissions: reservations,
1364
+ maxBufferedLiveEvents,
1365
+ maxBufferedLiveBytes,
1366
+ rateLimitRetries: 0
1367
+ }
1144
1368
  const liveFilter = { ...filter }
1145
1369
  if (snapshot) delete liveFilter.until
1146
1370
  const liveGen = _liveGenerator(liveFilter, urls, readOptions)
@@ -1248,11 +1472,15 @@ export class RelayPool {
1248
1472
  getRetryEvent,
1249
1473
  onRelayResult,
1250
1474
  signal,
1251
- useBulkPacing = false
1475
+ useBulkPacing = false,
1476
+ rateLimitRetries,
1477
+ maxRateLimitRetryWaitMs
1252
1478
  } = {}) {
1253
1479
  if (signal != null && (typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function' || typeof signal.removeEventListener !== 'function')) throw new ValidationError('INVALID_RELAY_SIGNAL')
1254
1480
  if (getRetryEvent != null && typeof getRetryEvent !== 'function') throw new ValidationError('INVALID_RETRY_EVENT_CALLBACK')
1255
1481
  if (typeof useBulkPacing !== 'boolean') throw new ValidationError('INVALID_USE_BULK_PACING')
1482
+ const retries = this.#retryCount(rateLimitRetries)
1483
+ const maxRetryWait = this.#maxRetryWait(maxRateLimitRetryWaitMs)
1256
1484
  const urls = normalizedRelayUrls(relays)
1257
1485
  if (!urls.length) {
1258
1486
  const promise = Promise.resolve(publishSummary([], urls, {
@@ -1268,6 +1496,7 @@ export class RelayPool {
1268
1496
  const eventForAttempt = eventToSend.meta ? { ...eventToSend } : eventToSend
1269
1497
  if (eventForAttempt.meta) delete eventForAttempt.meta
1270
1498
  const sendControllers = urls.map(() => new AbortController())
1499
+ const retryControllers = urls.map(() => new AbortController())
1271
1500
  const sendDeferreds = urls.map(() => Promise.withResolvers())
1272
1501
  const sendPromises = sendDeferreds.map(({ promise }) => promise)
1273
1502
  const bufferedResults = []
@@ -1307,7 +1536,13 @@ export class RelayPool {
1307
1536
  if (operationSignal.aborted) throw operationSignal.reason
1308
1537
  const relay = await this.#getRelay(url)
1309
1538
  if (operationSignal.aborted) throw operationSignal.reason
1310
- return await this.#publishEvent(relay, eventForAttempt, getAuthEvent, operationSignal, useBulkPacing)
1539
+ return await this.#publishEvent(relay, eventForAttempt, getAuthEvent, operationSignal, {
1540
+ useBulkPacing,
1541
+ rateLimitRetries: retries,
1542
+ maxRateLimitRetryWaitMs: maxRetryWait,
1543
+ retrySignal: retryControllers[index].signal,
1544
+ deadlineAt: deadline
1545
+ })
1311
1546
  } catch (err) {
1312
1547
  const reason = err instanceof Error ? err : new Error(String(err))
1313
1548
  if (reason instanceof Nip42AuthenticationError) throw reason
@@ -1327,6 +1562,7 @@ export class RelayPool {
1327
1562
  const success = await firstFulfillment(sendPromises, earlyTimeout, {
1328
1563
  fallback: promise.then(report => report.success)
1329
1564
  })
1565
+ if (success) for (const controller of retryControllers) controller.abort()
1330
1566
  if (!success) settlement.timeout()
1331
1567
 
1332
1568
  const result = {