libp2r2p 0.12.8 → 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.
package/README.md CHANGED
@@ -1115,8 +1115,45 @@ 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, 2, 4... up to 30
1126
+ seconds and reset after success. Success resets only the local backoff; an
1127
+ unexpired `retryAt` from a concurrent relay response remains authoritative.
1128
+ An existing operation deadline is never extended, so a retry whose next deadline
1129
+ would expire at or after the operation deadline returns the original bounded
1130
+ rate-limit error immediately.
1131
+
1132
+ For publication, the first accepted relay aborts retries that are still waiting
1133
+ on other relays; attempts already in flight may finish. Bulk retries retain the
1134
+ active queue position and do not allow later work to overtake them. Intermediate
1135
+ attempts do not reach callbacks, generators or aggregate reports. They may emit
1136
+ the sanitized `relay rate-limit retry` debug record with only relay URL,
1137
+ operation, attempt/count and numeric deadlines. Live and feed recovery keep
1138
+ their specialized reconnect behavior; their internal one-shot gap reads disable
1139
+ the generic retry budget.
1140
+
1141
+ Publication calls for the same event and relay share a physical job only when
1142
+ their pacing is compatible. Calls with the same pacing share one send. An
1143
+ interactive call joins an existing interactive job or a bulk job already removed
1144
+ from the queue and active; it never waits for a queued bulk job and instead may
1145
+ race it. A bulk call prefers an existing interactive job, otherwise it joins the
1146
+ bulk job. Each waiter keeps its own cancellation, operation deadline, timeout,
1147
+ `rateLimitRetries`, retry signal and observed rate-limit count.
1148
+
1149
+ A successful ACK on that relay settles every pending job for the event,
1150
+ including an unsent bulk sibling. Transmissions already started cannot be
1151
+ recalled, and their late responses are ignored. A rejection applies only to
1152
+ jobs whose bytes were transmitted and are awaiting that response, so a queued
1153
+ job remains pending. Success is never propagated across different relay
1154
+ connections. A waiter joining an already scheduled rate-limit retry may share
1155
+ that next attempt even with zero remaining retries; only later rate limits count
1156
+ against its budget.
1120
1157
 
1121
1158
  Rate limits apply only to the client message type that triggered the refusal:
1122
1159
  `EVENT`, `AUTH`, `REQ` and `COUNT` have independent connection cooldowns. Responses
@@ -1297,10 +1334,12 @@ responses are preserved as normalized `retryAt` and `retryAfterMs` on native rel
1297
1334
  errors. Only `rate-limited:`
1298
1335
  responses apply this advice; invalid values are ignored
1299
1336
  and delays are capped by the RelayPool runtime options, defaulting to five
1300
- minutes. New operations of the refused type wait
1337
+ minutes. One-shot operations retry the affected relay according to
1338
+ `rateLimitRetries`, defaulting to one additional attempt. New operations of the refused type wait
1301
1339
  within their existing deadlines; active subscriptions remain live and `CLOSE`
1302
1340
  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.
1341
+ is still reported when retries are exhausted, disabled or cannot finish before
1342
+ the operation deadline; intermediate attempts are not reported as final failures.
1304
1343
 
1305
1344
  `createEventReplyPacker` and `createMissingMessageReplyPacker` accept
1306
1345
  `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.9",
4
4
  "description": "Peer-to-relay-to-peer",
5
5
  "keywords": [
6
6
  "p2r2p",
@@ -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,20 @@
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
+ }) {
10
+ try {
11
+ console.debug('relay rate-limit retry', {
12
+ relay,
13
+ operation,
14
+ retryAttempt,
15
+ maxRetries,
16
+ retryAt,
17
+ delayMs: Math.max(0, retryAt - Date.now())
18
+ })
19
+ } catch {}
20
+ }
@@ -2,12 +2,14 @@ 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 OPERATION_TYPES = ['EVENT', 'AUTH', 'REQ', 'COUNT']
11
13
 
12
14
  function errorFrom (reason, fallback) {
13
15
  return reason instanceof Error ? reason : new Error(String(reason || fallback))
@@ -30,6 +32,23 @@ function retryAtFrom (value) {
30
32
  return retryAt
31
33
  }
32
34
 
35
+ function waitForRetry (deadline, signal, retrySignal) {
36
+ const combined = AbortSignal.any([signal, retrySignal].filter(Boolean))
37
+ if (combined.aborted) return Promise.reject(combined.reason)
38
+ return new Promise((resolve, reject) => {
39
+ const timer = maybeUnref(setTimeout(() => {
40
+ combined.removeEventListener('abort', onAbort)
41
+ resolve()
42
+ }, Math.max(0, deadline - Date.now())))
43
+ const onAbort = () => {
44
+ clearTimeout(timer)
45
+ combined.removeEventListener('abort', onAbort)
46
+ reject(combined.reason)
47
+ }
48
+ combined.addEventListener('abort', onAbort, { once: true })
49
+ })
50
+ }
51
+
33
52
  function hasMatchingPrefix (values, candidate) {
34
53
  return !values || values.some(value => typeof value === 'string' && candidate.startsWith(value))
35
54
  }
@@ -75,8 +94,8 @@ export class RelayConnection {
75
94
  #bulkQueue = []
76
95
  #bulkActive = null
77
96
  #bulkTimer = null
78
- #bulkBackoffMs = BULK_PACING_MS
79
97
  #bulkNextAt = 0
98
+ #rateLimitBackoffMs = new Map(OPERATION_TYPES.map(type => [type, BULK_PACING_MS]))
80
99
  #getRateLimitCapMs
81
100
 
82
101
  constructor (url, {
@@ -173,7 +192,7 @@ export class RelayConnection {
173
192
 
174
193
  // New work respects relay cooldowns; cleanup uses send() directly. These
175
194
  // waits stay within the caller's existing deadline and are cancellable.
176
- #dispatchWork (type, send, fail) {
195
+ #dispatchWork (type, send, fail, onDispatch) {
177
196
  let timer = null
178
197
  let cancelled = false
179
198
  const wake = () => {
@@ -189,6 +208,7 @@ export class RelayConnection {
189
208
  return
190
209
  }
191
210
  this.#cooldownWaiters.delete(wake)
211
+ onDispatch?.()
192
212
  try { send() } catch (error) { fail(error) }
193
213
  }
194
214
  const dispatch = () => {
@@ -205,10 +225,25 @@ export class RelayConnection {
205
225
 
206
226
  #rejection (type, reason, params, fallback) {
207
227
  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))
228
+ if (error.message?.startsWith('rate-limited:')) {
229
+ const now = Date.now()
230
+ const hasAdvice = Number.isSafeInteger(error.retryAt)
231
+ if (!hasAdvice) {
232
+ const delay = this.#rateLimitBackoffMs.get(type) ?? BULK_PACING_MS
233
+ error.retryAt = now + delay
234
+ error.retryAfterMs = delay
235
+ }
236
+ const delay = this.#rateLimitBackoffMs.get(type) ?? BULK_PACING_MS
237
+ this.#rateLimitBackoffMs.set(type, Math.min(RATE_LIMIT_BACKOFF_MAX_MS, delay * 2))
238
+ this.#retryAtByType.set(type, Math.max(this.#retryAtByType.get(type) ?? 0, error.retryAt))
239
+ }
209
240
  return error
210
241
  }
211
242
 
243
+ #recordSuccess (type) {
244
+ this.#rateLimitBackoffMs.set(type, BULK_PACING_MS)
245
+ }
246
+
212
247
  subscribe (filters, handlers = {}) {
213
248
  if (!Array.isArray(filters) || !filters.length) throw new ValidationError('SUBSCRIPTION_FILTERS_REQUIRED')
214
249
  const id = `p2r2p-sub:${++this.#serial}`
@@ -236,28 +271,227 @@ export class RelayConnection {
236
271
  return { id, close }
237
272
  }
238
273
 
239
- publish (event, { signal, useBulkPacing = false } = {}) {
274
+ publish (event, {
275
+ signal,
276
+ useBulkPacing = false,
277
+ rateLimitRetries = 0,
278
+ retrySignal,
279
+ deadlineAt = null
280
+ } = {}) {
240
281
  if (!isValidEvent(event)) return Promise.reject(new Error('INVALID_EVENT'))
241
282
  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 })
283
+ if (!Number.isSafeInteger(rateLimitRetries) || rateLimitRetries < 0) return Promise.reject(new ValidationError('INVALID_RATE_LIMIT_RETRIES'))
284
+ return this.#sendEventOperation('EVENT', event, this.#publishes, 'PUBLISH_TIMEOUT', signal, {
285
+ useBulkPacing,
286
+ rateLimitRetries,
287
+ retrySignal,
288
+ deadlineAt
289
+ })
243
290
  }
244
291
 
245
- async authenticate (getAuthEvent, { signal } = {}) {
292
+ async authenticate (getAuthEvent, {
293
+ signal,
294
+ rateLimitRetries = 0,
295
+ deadlineAt = null,
296
+ retrySignal
297
+ } = {}) {
246
298
  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)
299
+ if (!Number.isSafeInteger(rateLimitRetries) || rateLimitRetries < 0) throw new ValidationError('INVALID_RATE_LIMIT_RETRIES')
300
+ let lastRateLimitError = null
301
+ for (let attempt = 0; ; attempt++) {
302
+ if (signal?.aborted) throw signal.reason
303
+ if (deadlineAt !== null && Date.now() >= deadlineAt) {
304
+ throw lastRateLimitError ?? relayTimeoutError('AUTH_TIMEOUT', this.#lastTransportError)
305
+ }
306
+ const event = await getAuthEvent({ relay: this.url, challenge: this.#challenge })
307
+ if (!isValidEvent(event)) throw new ValidationError('INVALID_AUTH_EVENT')
308
+ try {
309
+ return await this.#sendEventOperation('AUTH', event, this.#authentications, 'AUTH_TIMEOUT', signal, { deadlineAt })
310
+ } catch (error) {
311
+ if (!error?.message?.startsWith('rate-limited:') || attempt >= rateLimitRetries) throw error
312
+ const retryAt = retryAtFrom(error)
313
+ if (!retryAt || (deadlineAt !== null && retryAt >= deadlineAt)) throw error
314
+ debugRateLimitRetry({
315
+ relay: this.url,
316
+ operation: 'AUTH',
317
+ retryAttempt: attempt + 1,
318
+ maxRetries: rateLimitRetries,
319
+ retryAt
320
+ })
321
+ lastRateLimitError = error
322
+ try {
323
+ await waitForRetry(retryAt, signal, retrySignal)
324
+ } catch (cause) {
325
+ if (retrySignal?.aborted) throw error
326
+ throw cause
327
+ }
328
+ }
329
+ }
330
+ }
331
+
332
+ // A job owns physical transmission and scheduling. Its waiters retain
333
+ // per-call cancellation, timeout, deadline and retry policy.
334
+ #mapForType (type) {
335
+ return type === 'EVENT' ? this.#publishes : this.#authentications
336
+ }
337
+
338
+ #hasJob (job) {
339
+ return this.#mapForType(job.type).get(job.event.id)?.has(job) === true
340
+ }
341
+
342
+ #findJob (map, id, pacing) {
343
+ for (const job of map.get(id) ?? []) {
344
+ if (job.pacing === pacing) return job
345
+ }
346
+ return null
347
+ }
348
+
349
+ #selectJob (map, event, useBulkPacing) {
350
+ const interactive = this.#findJob(map, event.id, 'interactive')
351
+ if (!useBulkPacing) {
352
+ if (interactive) return interactive
353
+ // Interactive work may benefit from a bulk send already in progress,
354
+ // but must never wait behind a bulk job that is still queued.
355
+ const activeBulk = this.#findJob(map, event.id, 'bulk')
356
+ return activeBulk?.state === 'active' ? activeBulk : null
357
+ }
358
+ if (interactive) return interactive
359
+ return this.#findJob(map, event.id, 'bulk')
360
+ }
361
+
362
+ #addJob (job) {
363
+ const map = this.#mapForType(job.type)
364
+ let jobs = map.get(job.event.id)
365
+ if (!jobs) {
366
+ jobs = new Set()
367
+ map.set(job.event.id, jobs)
368
+ }
369
+ jobs.add(job)
370
+ }
371
+
372
+ #allJobs (map) {
373
+ const jobs = []
374
+ for (const set of map.values()) jobs.push(...set)
375
+ return jobs
376
+ }
377
+
378
+ #cleanupWaiter (job, waiter) {
379
+ clearTimeout(waiter.timer)
380
+ waiter.signal?.removeEventListener('abort', waiter.onAbort)
381
+ waiter.retrySignal?.removeEventListener('abort', waiter.onRetryAbort)
382
+ job.waiters.delete(waiter)
250
383
  }
251
384
 
252
- #removeBulkPublish (pending) {
253
- const index = this.#bulkQueue.indexOf(pending)
385
+ #detachJob (job) {
386
+ if (job.detached) return
387
+ job.detached = true
388
+ job.awaitingAck = false
389
+ job.retryScheduled = false
390
+ const map = this.#mapForType(job.type)
391
+ const jobs = map.get(job.event.id)
392
+ if (jobs) {
393
+ jobs.delete(job)
394
+ if (!jobs.size) map.delete(job.event.id)
395
+ }
396
+ job.cancelSend?.()
397
+ job.cancelSend = null
398
+ const index = this.#bulkQueue.indexOf(job)
254
399
  if (index >= 0) this.#bulkQueue.splice(index, 1)
255
- if (this.#bulkActive === pending) {
400
+ const wasActive = this.#bulkActive === job
401
+ if (wasActive) {
256
402
  this.#bulkActive = null
257
- pending.onSettled = null
258
- this.#bulkNextAt = Math.max(this.#bulkNextAt, Date.now() + BULK_PACING_MS)
403
+ this.#bulkNextAt = Math.max(this.#bulkNextAt, Date.now(), job.startedAt + BULK_PACING_MS)
259
404
  }
260
- this.#pumpBulkPublishes()
405
+ if (!this.#bulkActive) this.#pumpBulkPublishes()
406
+ }
407
+
408
+ #settleJob (job, reason, value) {
409
+ if (job.settled) return
410
+ job.settled = true
411
+ const waiters = [...job.waiters]
412
+ for (const waiter of waiters) this.#cleanupWaiter(job, waiter)
413
+ this.#detachJob(job)
414
+ for (const waiter of waiters) {
415
+ if (reason) waiter.reject(errorFrom(reason, 'OPERATION_REJECTED'))
416
+ else waiter.resolve(value)
417
+ }
418
+ }
419
+
420
+ #removeWaiter (job, waiter, reason) {
421
+ if (!job.waiters.has(waiter)) return
422
+ this.#cleanupWaiter(job, waiter)
423
+ waiter.reject(errorFrom(reason, 'OPERATION_REJECTED'))
424
+ if (!job.waiters.size) {
425
+ job.settled = true
426
+ this.#detachJob(job)
427
+ }
428
+ }
429
+
430
+ #canShareScheduledRetry (waiter, retryAt) {
431
+ return !waiter.retrySignal?.aborted &&
432
+ (waiter.deadlineAt === null || retryAt < waiter.deadlineAt)
433
+ }
434
+
435
+ #canRetryAfterLimit (waiter, retryAt) {
436
+ return waiter.observedRateLimitFailures <= waiter.rateLimitRetries &&
437
+ this.#canShareScheduledRetry(waiter, retryAt)
438
+ }
439
+
440
+ #pruneScheduledRetryWaiters (job) {
441
+ if (!job.retryScheduled || !job.lastRateLimitError) return
442
+ for (const waiter of [...job.waiters]) {
443
+ if (!this.#canShareScheduledRetry(waiter, job.retryAt)) {
444
+ this.#removeWaiter(job, waiter, job.lastRateLimitError)
445
+ }
446
+ }
447
+ }
448
+
449
+ #expireWaiter (job, waiter) {
450
+ const reason = job.retryScheduled && job.lastRateLimitError
451
+ ? job.lastRateLimitError
452
+ : relayTimeoutError(job.timeoutCode, this.#lastTransportError)
453
+ this.#removeWaiter(job, waiter, reason)
454
+ this.#pruneScheduledRetryWaiters(job)
455
+ }
456
+
457
+ #abortWaiterRetry (job, waiter) {
458
+ if (!job.retryScheduled || !job.lastRateLimitError) return
459
+ this.#removeWaiter(job, waiter, job.lastRateLimitError)
460
+ this.#pruneScheduledRetryWaiters(job)
461
+ }
462
+
463
+ #addWaiter (job, {
464
+ signal,
465
+ retrySignal,
466
+ deadlineAt,
467
+ rateLimitRetries
468
+ }) {
469
+ const deferred = Promise.withResolvers()
470
+ const waiter = {
471
+ ...deferred,
472
+ signal,
473
+ retrySignal,
474
+ deadlineAt,
475
+ rateLimitRetries,
476
+ observedRateLimitFailures: 0,
477
+ timer: null,
478
+ onAbort: null,
479
+ onRetryAbort: null
480
+ }
481
+ job.waiters.add(waiter)
482
+ waiter.onAbort = () => this.#removeWaiter(job, waiter, signal.reason)
483
+ waiter.onRetryAbort = () => this.#abortWaiterRetry(job, waiter)
484
+ signal?.addEventListener('abort', waiter.onAbort, { once: true })
485
+ retrySignal?.addEventListener('abort', waiter.onRetryAbort, { once: true })
486
+ let timeout = this.publishTimeout
487
+ if (!signal && deadlineAt !== null) timeout = Math.min(timeout, Math.max(0, deadlineAt - Date.now()))
488
+ waiter.timer = maybeUnref(setTimeout(() => this.#expireWaiter(job, waiter), timeout))
489
+
490
+ if (signal?.aborted) this.#removeWaiter(job, waiter, signal.reason)
491
+ else if (job.retryScheduled && !this.#canShareScheduledRetry(waiter, job.retryAt)) {
492
+ this.#removeWaiter(job, waiter, job.lastRateLimitError)
493
+ }
494
+ return deferred.promise
261
495
  }
262
496
 
263
497
  #clearBulkScheduler () {
@@ -266,7 +500,6 @@ export class RelayConnection {
266
500
  this.#bulkQueue.length = 0
267
501
  this.#bulkActive = null
268
502
  this.#bulkNextAt = 0
269
- this.#bulkBackoffMs = BULK_PACING_MS
270
503
  }
271
504
 
272
505
  #pumpBulkPublishes () {
@@ -274,8 +507,8 @@ export class RelayConnection {
274
507
  clearTimeout(this.#bulkTimer)
275
508
  this.#bulkTimer = null
276
509
  while (this.#bulkQueue.length) {
277
- const pending = this.#bulkQueue[0]
278
- if (this.#publishes.get(pending.event.id) === pending && pending.waiters.size > 0) break
510
+ const job = this.#bulkQueue[0]
511
+ if (this.#hasJob(job) && job.waiters.size > 0) break
279
512
  this.#bulkQueue.shift()
280
513
  }
281
514
  if (!this.#bulkQueue.length) return
@@ -287,72 +520,110 @@ export class RelayConnection {
287
520
  return
288
521
  }
289
522
 
290
- const pending = this.#bulkQueue.shift()
523
+ const job = this.#bulkQueue.shift()
291
524
  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)
525
+ job.state = 'active'
526
+ job.startedAt = startedAt
527
+ this.#bulkActive = job
528
+ this.#dispatchEventAttempt(job)
529
+ }
530
+
531
+ #dispatchEventAttempt (job) {
532
+ const cancel = this.#dispatchWork(job.type, () => {
533
+ if (!this.#hasJob(job)) return
534
+ const retrying = job.retryScheduled
535
+ for (const waiter of [...job.waiters]) {
536
+ if (waiter.deadlineAt !== null && Date.now() >= waiter.deadlineAt) {
537
+ this.#removeWaiter(job, waiter, retrying && job.lastRateLimitError
538
+ ? job.lastRateLimitError
539
+ : relayTimeoutError(job.timeoutCode, this.#lastTransportError))
540
+ }
541
+ }
542
+ if (!job.waiters.size) return
543
+ job.retryScheduled = false
544
+ job.awaitingAck = true
545
+ try {
546
+ this.send(JSON.stringify([job.type, job.event]))
547
+ } catch (error) {
548
+ job.awaitingAck = false
549
+ throw error
550
+ }
551
+ }, error => {
552
+ job.awaitingAck = false
553
+ this.#settleJob(job, error)
554
+ })
555
+ job.cancelSend = cancel
556
+ if (!this.#hasJob(job)) cancel()
557
+ }
558
+
559
+ #applyRateLimit (job, reason) {
560
+ job.awaitingAck = false
561
+ job.lastRateLimitError = reason
562
+ const retryAt = Math.max(
563
+ retryAtFrom(reason),
564
+ this.#retryAtByType.get(job.type) ?? 0
565
+ )
566
+ for (const waiter of [...job.waiters]) {
567
+ waiter.observedRateLimitFailures++
568
+ if (!retryAt || !this.#canRetryAfterLimit(waiter, retryAt)) {
569
+ this.#removeWaiter(job, waiter, reason)
309
570
  }
310
- this.#pumpBulkPublishes()
311
571
  }
312
- pending.cancelSend = this.#dispatchWork('EVENT', () => {
313
- this.send(JSON.stringify(['EVENT', pending.event]))
314
- }, error => this.#settleEvent(this.#publishes, pending.event.id, error))
572
+ if (!job.waiters.size) return
573
+ job.retryAt = retryAt
574
+ job.retryScheduled = true
575
+ job.retryAttempts++
576
+ debugRateLimitRetry({
577
+ relay: this.url,
578
+ operation: job.type,
579
+ retryAttempt: job.retryAttempts,
580
+ maxRetries: Math.max(...[...job.waiters].map(waiter => waiter.rateLimitRetries)),
581
+ retryAt
582
+ })
583
+ this.#dispatchEventAttempt(job)
315
584
  }
316
585
 
317
- #sendEventOperation (type, event, map, timeoutCode, signal, { useBulkPacing = false } = {}) {
586
+ #sendEventOperation (type, event, map, timeoutCode, signal, {
587
+ useBulkPacing = false,
588
+ rateLimitRetries = 0,
589
+ retrySignal,
590
+ deadlineAt = null
591
+ } = {}) {
318
592
  if (signal?.aborted) return Promise.reject(signal.reason)
319
- let pending = map.get(event.id)
320
- const created = !pending
593
+ let job = this.#selectJob(map, event, useBulkPacing && type === 'EVENT')
594
+ const created = !job
321
595
  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
- }
596
+ job = {
597
+ waiters: new Set(),
598
+ cancelSend: null,
599
+ event,
600
+ type,
601
+ timeoutCode,
602
+ pacing: useBulkPacing && type === 'EVENT' ? 'bulk' : 'interactive',
603
+ state: useBulkPacing && type === 'EVENT' ? 'queued' : 'active',
604
+ startedAt: 0,
605
+ retryAttempts: 0,
606
+ lastRateLimitError: null,
607
+ retryAt: 0,
608
+ retryScheduled: false,
609
+ awaitingAck: false,
610
+ detached: false,
611
+ settled: false
341
612
  }
613
+ this.#addJob(job)
342
614
  }
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)
615
+ const promise = this.#addWaiter(job, {
616
+ signal,
617
+ retrySignal,
618
+ deadlineAt,
619
+ rateLimitRetries
620
+ })
621
+ if (!created || !this.#hasJob(job)) return promise
622
+ if (job.pacing === 'bulk') {
623
+ this.#bulkQueue.push(job)
349
624
  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
625
+ } else this.#dispatchEventAttempt(job)
626
+ return promise
356
627
  }
357
628
 
358
629
  countWithHll (filters, { signal } = {}) {
@@ -369,25 +640,26 @@ export class RelayConnection {
369
640
  return deferred.promise
370
641
  }
371
642
 
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)
643
+ #settleJobsSuccess (jobs, value) {
644
+ for (const job of [...jobs]) this.#settleJob(job, null, value)
645
+ }
646
+
647
+ #handleOkFailure (jobs, type, message, params) {
648
+ const awaiting = [...jobs].filter(job => job.awaitingAck)
649
+ if (!awaiting.length) return
650
+ const reason = this.#rejection(type, message, params, 'EVENT_REJECTED')
651
+ for (const job of awaiting) {
652
+ job.awaitingAck = false
653
+ if (reason.message?.startsWith('rate-limited:')) this.#applyRateLimit(job, reason)
654
+ else this.#settleJob(job, reason)
383
655
  }
384
- pending.waiters.clear()
385
656
  }
386
657
 
387
658
  #settleCount (id, payload, reason) {
388
659
  const pending = this.#counts.get(id)
389
660
  if (!pending) return
390
661
  this.#counts.delete(id)
662
+ if (!reason) this.#recordSuccess('COUNT')
391
663
  pending.cancelSend?.()
392
664
  pending.signal?.removeEventListener('abort', pending.onAbort)
393
665
  if (reason) pending.reject(errorFrom(reason, 'COUNT_REJECTED'))
@@ -411,7 +683,11 @@ export class RelayConnection {
411
683
  return
412
684
  }
413
685
  if (data[0] === 'EOSE') {
414
- this.#subscriptions.get(data[1])?.handlers.oneose?.()
686
+ const subscription = this.#subscriptions.get(data[1])
687
+ if (subscription) {
688
+ this.#recordSuccess('REQ')
689
+ subscription.handlers.oneose?.()
690
+ }
415
691
  return
416
692
  }
417
693
  if (data[0] === 'CLOSED') {
@@ -427,10 +703,17 @@ export class RelayConnection {
427
703
  return
428
704
  }
429
705
  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])
706
+ for (const [type, map] of [['EVENT', this.#publishes], ['AUTH', this.#authentications]]) {
707
+ const jobs = map.get(data[1])
708
+ if (!jobs || ![...jobs].some(job => job.awaitingAck)) continue
709
+ if (data[2] === true) {
710
+ this.#recordSuccess(type)
711
+ // The same relay accepted this exact event. Settle every pacing job
712
+ // locally, including copies that have not started transmission.
713
+ this.#settleJobsSuccess(jobs, data[3])
714
+ } else {
715
+ this.#handleOkFailure(jobs, type, data[3], data[4])
716
+ }
434
717
  }
435
718
  return
436
719
  }
@@ -454,10 +737,10 @@ export class RelayConnection {
454
737
  subscription.cancelSend?.()
455
738
  subscription.handlers.onclose?.(reason)
456
739
  }
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)
740
+ const jobs = [...this.#allJobs(this.#publishes), ...this.#allJobs(this.#authentications)]
460
741
  this.#clearBulkScheduler()
742
+ for (const job of jobs) this.#settleJob(job, reason)
743
+ for (const id of [...this.#counts.keys()]) this.#settleCount(id, null, reason)
461
744
  this.onclose?.(reason)
462
745
  }
463
746
 
@@ -471,10 +754,10 @@ export class RelayConnection {
471
754
  subscription.cancelSend?.()
472
755
  subscription.handlers.onclose?.()
473
756
  }
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)
757
+ const jobs = [...this.#allJobs(this.#publishes), ...this.#allJobs(this.#authentications)]
477
758
  this.#clearBulkScheduler()
759
+ for (const job of jobs) this.#settleJob(job, reason)
760
+ for (const id of [...this.#counts.keys()]) this.#settleCount(id, null, reason)
478
761
  if (socket && socket.readyState < 2) socket.close()
479
762
  }
480
763
  }
@@ -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'
@@ -107,6 +108,11 @@ function validateRateLimitCapMs (value) {
107
108
  return value
108
109
  }
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
+
110
116
  function assertReadOptions (filter, timeouts) {
111
117
  if (!filter || typeof filter !== 'object' || Array.isArray(filter)) throw new ValidationError('INVALID_FILTER')
112
118
  for (const value of Object.values(timeouts)) {
@@ -161,8 +167,11 @@ export class RelayPool {
161
167
  #readRetry
162
168
  #options
163
169
 
164
- constructor ({ _createRelay, _isOnline, _onOnline, WebSocket: WebSocketImpl, rateLimitCapMs = DEFAULT_RATE_LIMIT_CAP_MS, ...capacity } = {}) {
165
- this.#options = { rateLimitCapMs: validateRateLimitCapMs(rateLimitCapMs) }
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
+ }
166
175
  this.#WebSocket = WebSocketImpl
167
176
  this.#createRelay = _createRelay ?? (url => new RelayConnection(url, {
168
177
  ...(this.#WebSocket ? { WebSocket: this.#WebSocket } : {}),
@@ -178,15 +187,20 @@ export class RelayPool {
178
187
 
179
188
  setOptions (partial = {}) {
180
189
  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')
190
+ const unknown = Object.keys(partial).find(key => !['rateLimitCapMs', 'rateLimitRetries'].includes(key))
182
191
  if (unknown) throw new ValidationError('UNKNOWN_RELAY_POOL_OPTION')
183
192
  const next = { ...this.#options }
184
193
  if (Object.hasOwn(partial, 'rateLimitCapMs')) next.rateLimitCapMs = validateRateLimitCapMs(partial.rateLimitCapMs)
194
+ if (Object.hasOwn(partial, 'rateLimitRetries')) next.rateLimitRetries = validateRateLimitRetries(partial.rateLimitRetries)
185
195
  this.#options = next
186
196
  for (const relay of this.#relays.values()) relay.setRateLimitCapMs?.(next.rateLimitCapMs)
187
197
  return this.getOptions()
188
198
  }
189
199
 
200
+ #retryCount (value) {
201
+ return validateRateLimitRetries(value === undefined ? this.#options.rateLimitRetries : value)
202
+ }
203
+
190
204
  // Injects the WebSocket implementation used by new pooled connections (e.g.
191
205
  // a launcher-owned relay multiplexer). Existing connections keep the
192
206
  // implementation they were created with.
@@ -276,21 +290,27 @@ export class RelayPool {
276
290
 
277
291
  // NIP-42 retries happen inside one relay attempt, so sendEvent still reports
278
292
  // exactly one terminal outcome for each relay URL.
279
- async #publishEvent (relay, event, getAuthEvent, signal, useBulkPacing) {
293
+ async #publishEvent (relay, event, getAuthEvent, signal, {
294
+ useBulkPacing,
295
+ rateLimitRetries,
296
+ retrySignal,
297
+ deadlineAt
298
+ }) {
280
299
  try {
281
- await relay.publish(event, { signal, useBulkPacing })
300
+ await relay.publish(event, { signal, useBulkPacing, rateLimitRetries, retrySignal, deadlineAt })
282
301
  return 'published'
283
302
  } catch (error) {
284
303
  const reason = error instanceof Error ? error : new Error(String(error))
285
304
  if (!getAuthEvent || !requiresNip42Auth(reason)) throw reason
286
305
 
287
306
  try {
288
- await relay.authenticate(getAuthEvent, { signal })
307
+ await relay.authenticate(getAuthEvent, { signal, rateLimitRetries, retrySignal, deadlineAt })
289
308
  } catch (error) {
290
309
  const authReason = error instanceof Error ? error : new Error(String(error))
310
+ if (retrySignal?.aborted && authReason.message?.startsWith('rate-limited:')) throw authReason
291
311
  throw new Nip42AuthenticationError(authReason)
292
312
  }
293
- await relay.publish(event, { signal, useBulkPacing })
313
+ await relay.publish(event, { signal, useBulkPacing, rateLimitRetries, retrySignal, deadlineAt })
294
314
  return 'published'
295
315
  }
296
316
  }
@@ -301,12 +321,14 @@ export class RelayPool {
301
321
  async countEvents (filter, relays, {
302
322
  timeout = COUNT_TIMEOUT_MS,
303
323
  timeoutAfterFirstCount = COUNT_TIMEOUT_AFTER_FIRST_COUNT_MS,
304
- signal
324
+ signal,
325
+ rateLimitRetries
305
326
  } = {}) {
306
327
  if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
307
328
  throw new ValidationError('COUNT_FILTER_REQUIRED')
308
329
  }
309
330
  if (signal?.aborted) throw new Error('Aborted')
331
+ const retries = this.#retryCount(rateLimitRetries)
310
332
 
311
333
  const urls = normalizedRelayUrls(relays)
312
334
  if (!urls.length) {
@@ -314,6 +336,10 @@ export class RelayPool {
314
336
  }
315
337
 
316
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
317
343
  const pending = new Set(urls)
318
344
  const errors = []
319
345
  let count = null
@@ -327,6 +353,8 @@ export class RelayPool {
327
353
  const cleanup = () => {
328
354
  clearTimeout(timeoutTimer)
329
355
  clearTimeout(graceTimer)
356
+ for (const controller of retryControllers.values()) controller.abort()
357
+ retryControllers.clear()
330
358
  signal?.removeEventListener('abort', onAbort)
331
359
  countController.abort()
332
360
  }
@@ -395,13 +423,48 @@ export class RelayPool {
395
423
  }
396
424
 
397
425
  const handleError = (relay, error) => {
398
- if (isResolved || !settleRelay(relay)) return
399
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)
400
463
  errors.push({ relay, reason })
401
464
  finishIfComplete()
402
465
  }
403
466
 
404
- for (const relay of urls) {
467
+ const startCount = relay => {
405
468
  this.#getRelay(relay)
406
469
  .then(async connection => {
407
470
  if (isResolved) return null
@@ -412,6 +475,7 @@ export class RelayPool {
412
475
  error => handleError(relay, error)
413
476
  )
414
477
  }
478
+ for (const relay of urls) startCount(relay)
415
479
  })
416
480
  }
417
481
 
@@ -419,12 +483,31 @@ export class RelayPool {
419
483
  // grace window; null disables that window so callers wait for every relay or
420
484
  // the operation deadline. Disabling cross-relay deduplication still suppresses
421
485
  // 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 } = {}) {
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
+ } = {}) {
423
496
  assertReadOptions(filter, { timeout, timeoutAfterFirstEose, queueTimeout })
424
497
  if (typeof deduplicateAcrossRelays !== 'boolean') throw new ValidationError('INVALID_DEDUPLICATE_ACROSS_RELAYS')
425
498
  if (signal?.aborted) throw new Error('Aborted')
499
+ const retries = this.#retryCount(rateLimitRetries)
426
500
  const urls = normalizedRelayUrls(relays)
427
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()
428
511
  const outcomes = new Map()
429
512
  const errors = []
430
513
  const events = []
@@ -440,6 +523,8 @@ export class RelayPool {
440
523
  const cleanup = () => {
441
524
  admissionAbort.abort()
442
525
  for (const timer of timers.values()) clearTimeout(timer)
526
+ for (const controller of retryControllers.values()) controller.abort()
527
+ retryControllers.clear()
443
528
  clearTimeout(eoseTimer)
444
529
  signal?.removeEventListener('abort', onAbort)
445
530
  for (const sub of subscriptions.values()) sub.close()
@@ -492,18 +577,58 @@ export class RelayPool {
492
577
  signal?.addEventListener('abort', onAbort, { once: true })
493
578
  if (!urls.length) { finish(); return }
494
579
 
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 })
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 })
498
622
  reservation.then(async slots => {
499
623
  const lease = slots.history
500
624
  if (isResolved || outcomes.has(url)) { lease.release(); return }
501
625
  leases.set(url, lease)
502
- if (timeout !== null) {
626
+ const relayTimeout = remainingTimeout(url)
627
+ if (relayTimeout !== null) {
503
628
  timers.set(url, maybeUnref(setTimeout(() => {
504
629
  settleRelay(url, 'timeout', getEventsTimeoutError())
505
630
  finishIfComplete()
506
- }, timeout)))
631
+ }, relayTimeout)))
507
632
  }
508
633
  const relay = await this.#getRelay(url)
509
634
  if (isResolved || outcomes.has(url)) return
@@ -539,6 +664,12 @@ export class RelayPool {
539
664
  onclose: error => {
540
665
  if (isResolved || outcomes.has(url)) return
541
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
+ }
542
673
  settleRelay(url, reason ? 'error' : 'closed', reason)
543
674
  subscriptions.delete(url)
544
675
  finishIfComplete()
@@ -552,6 +683,7 @@ export class RelayPool {
552
683
  finishIfComplete()
553
684
  })
554
685
  }
686
+ for (const url of urls) startRelay(url)
555
687
  })
556
688
  }
557
689
 
@@ -886,6 +1018,7 @@ export class RelayPool {
886
1018
  queueTimeout,
887
1019
  timeout: timeoutForReconnectGap,
888
1020
  timeoutAfterFirstEose: timeoutAfterFirstReconnectGapEose,
1021
+ rateLimitRetries: 0,
889
1022
  signal,
890
1023
  _stopSignal: AbortSignal.any([gapAc.signal, attempt.stop.signal])
891
1024
  })
@@ -1109,7 +1242,10 @@ export class RelayPool {
1109
1242
  const options = { timeout, timeoutAfterFirstEose, queueTimeout, signal, _stopSignal }
1110
1243
  if (!live) {
1111
1244
  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)) {
1245
+ for await (const item of _eventsGenerator(snapshot ? { ...filter, ...bounds } : filter, relays, {
1246
+ ...options,
1247
+ rateLimitRetries: 0
1248
+ })) {
1113
1249
  if (signal.aborted) return
1114
1250
  yield snapshot && item.type === 'eose' ? { ...item, snapshot: bounds } : item
1115
1251
  }
@@ -1140,7 +1276,14 @@ export class RelayPool {
1140
1276
  reservation.catch(() => {})
1141
1277
  reservations.set(url, reservation)
1142
1278
  }
1143
- 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
+ }
1144
1287
  const liveFilter = { ...filter }
1145
1288
  if (snapshot) delete liveFilter.until
1146
1289
  const liveGen = _liveGenerator(liveFilter, urls, readOptions)
@@ -1248,11 +1391,13 @@ export class RelayPool {
1248
1391
  getRetryEvent,
1249
1392
  onRelayResult,
1250
1393
  signal,
1251
- useBulkPacing = false
1394
+ useBulkPacing = false,
1395
+ rateLimitRetries
1252
1396
  } = {}) {
1253
1397
  if (signal != null && (typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function' || typeof signal.removeEventListener !== 'function')) throw new ValidationError('INVALID_RELAY_SIGNAL')
1254
1398
  if (getRetryEvent != null && typeof getRetryEvent !== 'function') throw new ValidationError('INVALID_RETRY_EVENT_CALLBACK')
1255
1399
  if (typeof useBulkPacing !== 'boolean') throw new ValidationError('INVALID_USE_BULK_PACING')
1400
+ const retries = this.#retryCount(rateLimitRetries)
1256
1401
  const urls = normalizedRelayUrls(relays)
1257
1402
  if (!urls.length) {
1258
1403
  const promise = Promise.resolve(publishSummary([], urls, {
@@ -1268,6 +1413,7 @@ export class RelayPool {
1268
1413
  const eventForAttempt = eventToSend.meta ? { ...eventToSend } : eventToSend
1269
1414
  if (eventForAttempt.meta) delete eventForAttempt.meta
1270
1415
  const sendControllers = urls.map(() => new AbortController())
1416
+ const retryControllers = urls.map(() => new AbortController())
1271
1417
  const sendDeferreds = urls.map(() => Promise.withResolvers())
1272
1418
  const sendPromises = sendDeferreds.map(({ promise }) => promise)
1273
1419
  const bufferedResults = []
@@ -1307,7 +1453,12 @@ export class RelayPool {
1307
1453
  if (operationSignal.aborted) throw operationSignal.reason
1308
1454
  const relay = await this.#getRelay(url)
1309
1455
  if (operationSignal.aborted) throw operationSignal.reason
1310
- return await this.#publishEvent(relay, eventForAttempt, getAuthEvent, operationSignal, useBulkPacing)
1456
+ return await this.#publishEvent(relay, eventForAttempt, getAuthEvent, operationSignal, {
1457
+ useBulkPacing,
1458
+ rateLimitRetries: retries,
1459
+ retrySignal: retryControllers[index].signal,
1460
+ deadlineAt: deadline
1461
+ })
1311
1462
  } catch (err) {
1312
1463
  const reason = err instanceof Error ? err : new Error(String(err))
1313
1464
  if (reason instanceof Nip42AuthenticationError) throw reason
@@ -1327,6 +1478,7 @@ export class RelayPool {
1327
1478
  const success = await firstFulfillment(sendPromises, earlyTimeout, {
1328
1479
  fallback: promise.then(report => report.success)
1329
1480
  })
1481
+ if (success) for (const controller of retryControllers) controller.abort()
1330
1482
  if (!success) settlement.timeout()
1331
1483
 
1332
1484
  const result = {