libp2r2p 0.12.9 → 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
@@ -1122,8 +1122,14 @@ applies to `sendEvent`, `getEvents`, `getEventsGenerator` and `countEvents`, and
1122
1122
  each method accepts a per-call override. The budget is independent for each relay
1123
1123
  and message type; an AUTH retry does not consume the EVENT publication budget.
1124
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
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
1127
1133
  unexpired `retryAt` from a concurrent relay response remains authoritative.
1128
1134
  An existing operation deadline is never extended, so a retry whose next deadline
1129
1135
  would expire at or after the operation deadline returns the original bounded
@@ -1134,10 +1140,15 @@ on other relays; attempts already in flight may finish. Bulk retries retain the
1134
1140
  active queue position and do not allow later work to overtake them. Intermediate
1135
1141
  attempts do not reach callbacks, generators or aggregate reports. They may emit
1136
1142
  the sanitized `relay rate-limit retry` debug record with only relay URL,
1137
- operation, attempt/count and numeric deadlines. Live and feed recovery keep
1143
+ operation, attempt/count, numeric deadlines and the wait gate. Live and feed recovery keep
1138
1144
  their specialized reconnect behavior; their internal one-shot gap reads disable
1139
1145
  the generic retry budget.
1140
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
+
1141
1152
  Publication calls for the same event and relay share a physical job only when
1142
1153
  their pacing is compatible. Calls with the same pacing share one send. An
1143
1154
  interactive call joins an existing interactive job or a bulk job already removed
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libp2r2p",
3
- "version": "0.12.9",
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(() => {})
@@ -5,7 +5,9 @@ export function debugRateLimitRetry ({
5
5
  operation,
6
6
  retryAttempt,
7
7
  maxRetries,
8
- retryAt
8
+ retryAt,
9
+ effectiveWaitMs,
10
+ maxWaitMs
9
11
  }) {
10
12
  try {
11
13
  console.debug('relay rate-limit retry', {
@@ -14,7 +16,9 @@ export function debugRateLimitRetry ({
14
16
  retryAttempt,
15
17
  maxRetries,
16
18
  retryAt,
17
- delayMs: Math.max(0, retryAt - Date.now())
19
+ delayMs: Math.max(0, retryAt - Date.now()),
20
+ effectiveWaitMs,
21
+ maxWaitMs
18
22
  })
19
23
  } catch {}
20
24
  }
@@ -9,6 +9,7 @@ const DEFAULT_CONNECT_TIMEOUT = 3000
9
9
  const DEFAULT_OPERATION_TIMEOUT = 30000
10
10
  const BULK_PACING_MS = 1000
11
11
  const RATE_LIMIT_BACKOFF_MAX_MS = 30000
12
+ const DEFAULT_MAX_RATE_LIMIT_RETRY_WAIT_MS = 1500
12
13
  const OPERATION_TYPES = ['EVENT', 'AUTH', 'REQ', 'COUNT']
13
14
 
14
15
  function errorFrom (reason, fallback) {
@@ -32,6 +33,16 @@ function retryAtFrom (value) {
32
33
  return retryAt
33
34
  }
34
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
+
35
46
  function waitForRetry (deadline, signal, retrySignal) {
36
47
  const combined = AbortSignal.any([signal, retrySignal].filter(Boolean))
37
48
  if (combined.aborted) return Promise.reject(combined.reason)
@@ -97,10 +108,12 @@ export class RelayConnection {
97
108
  #bulkNextAt = 0
98
109
  #rateLimitBackoffMs = new Map(OPERATION_TYPES.map(type => [type, BULK_PACING_MS]))
99
110
  #getRateLimitCapMs
111
+ #defaultMaxRateLimitRetryWaitMs
100
112
 
101
113
  constructor (url, {
102
114
  WebSocket: WebSocketImpl = globalThis.WebSocket,
103
- rateLimitCapMs = () => DEFAULT_RATE_LIMIT_CAP_MS
115
+ rateLimitCapMs = () => DEFAULT_RATE_LIMIT_CAP_MS,
116
+ maxRateLimitRetryWaitMs = DEFAULT_MAX_RATE_LIMIT_RETRY_WAIT_MS
104
117
  } = {}) {
105
118
  this.url = url
106
119
  this.#WebSocket = WebSocketImpl
@@ -110,6 +123,11 @@ export class RelayConnection {
110
123
  this.#getRateLimitCapMs = typeof rateLimitCapMs === 'function'
111
124
  ? rateLimitCapMs
112
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
113
131
  this.ws = null
114
132
  this.publishTimeout = DEFAULT_OPERATION_TIMEOUT
115
133
  this.onnotice = null
@@ -234,8 +252,13 @@ export class RelayConnection {
234
252
  error.retryAfterMs = delay
235
253
  }
236
254
  const delay = this.#rateLimitBackoffMs.get(type) ?? BULK_PACING_MS
237
- this.#rateLimitBackoffMs.set(type, Math.min(RATE_LIMIT_BACKOFF_MAX_MS, delay * 2))
255
+ this.#rateLimitBackoffMs.set(type, nextRateLimitBackoff(delay))
238
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
+ })
239
262
  }
240
263
  return error
241
264
  }
@@ -275,15 +298,21 @@ export class RelayConnection {
275
298
  signal,
276
299
  useBulkPacing = false,
277
300
  rateLimitRetries = 0,
301
+ maxRateLimitRetryWaitMs = this.#defaultMaxRateLimitRetryWaitMs,
278
302
  retrySignal,
279
303
  deadlineAt = null
280
304
  } = {}) {
281
305
  if (!isValidEvent(event)) return Promise.reject(new Error('INVALID_EVENT'))
282
306
  if (typeof useBulkPacing !== 'boolean') return Promise.reject(new ValidationError('INVALID_USE_BULK_PACING'))
283
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
+ }
284
312
  return this.#sendEventOperation('EVENT', event, this.#publishes, 'PUBLISH_TIMEOUT', signal, {
285
313
  useBulkPacing,
286
314
  rateLimitRetries,
315
+ maxRateLimitRetryWaitMs,
287
316
  retrySignal,
288
317
  deadlineAt
289
318
  })
@@ -292,11 +321,16 @@ export class RelayConnection {
292
321
  async authenticate (getAuthEvent, {
293
322
  signal,
294
323
  rateLimitRetries = 0,
324
+ maxRateLimitRetryWaitMs = this.#defaultMaxRateLimitRetryWaitMs,
295
325
  deadlineAt = null,
296
326
  retrySignal
297
327
  } = {}) {
298
328
  if (!this.#challenge) throw new Error('AUTH_CHALLENGE_MISSING')
299
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
+ }
300
334
  let lastRateLimitError = null
301
335
  for (let attempt = 0; ; attempt++) {
302
336
  if (signal?.aborted) throw signal.reason
@@ -309,14 +343,20 @@ export class RelayConnection {
309
343
  return await this.#sendEventOperation('AUTH', event, this.#authentications, 'AUTH_TIMEOUT', signal, { deadlineAt })
310
344
  } catch (error) {
311
345
  if (!error?.message?.startsWith('rate-limited:') || attempt >= rateLimitRetries) throw error
312
- const retryAt = retryAtFrom(error)
346
+ const retryAt = Math.max(
347
+ retryAtFrom(error),
348
+ this.#retryAtByType.get('AUTH') ?? 0
349
+ )
313
350
  if (!retryAt || (deadlineAt !== null && retryAt >= deadlineAt)) throw error
351
+ if (!retryWaitAllowed(retryAt, maxRateLimitRetryWaitMs)) throw error
314
352
  debugRateLimitRetry({
315
353
  relay: this.url,
316
354
  operation: 'AUTH',
317
355
  retryAttempt: attempt + 1,
318
356
  maxRetries: rateLimitRetries,
319
- retryAt
357
+ retryAt,
358
+ effectiveWaitMs: Math.max(0, retryAt - Date.now()),
359
+ maxWaitMs: maxRateLimitRetryWaitMs
320
360
  })
321
361
  lastRateLimitError = error
322
362
  try {
@@ -434,6 +474,7 @@ export class RelayConnection {
434
474
 
435
475
  #canRetryAfterLimit (waiter, retryAt) {
436
476
  return waiter.observedRateLimitFailures <= waiter.rateLimitRetries &&
477
+ retryWaitAllowed(retryAt, waiter.maxRateLimitRetryWaitMs) &&
437
478
  this.#canShareScheduledRetry(waiter, retryAt)
438
479
  }
439
480
 
@@ -464,7 +505,8 @@ export class RelayConnection {
464
505
  signal,
465
506
  retrySignal,
466
507
  deadlineAt,
467
- rateLimitRetries
508
+ rateLimitRetries,
509
+ maxRateLimitRetryWaitMs
468
510
  }) {
469
511
  const deferred = Promise.withResolvers()
470
512
  const waiter = {
@@ -473,6 +515,7 @@ export class RelayConnection {
473
515
  retrySignal,
474
516
  deadlineAt,
475
517
  rateLimitRetries,
518
+ maxRateLimitRetryWaitMs,
476
519
  observedRateLimitFailures: 0,
477
520
  timer: null,
478
521
  onAbort: null,
@@ -573,12 +616,15 @@ export class RelayConnection {
573
616
  job.retryAt = retryAt
574
617
  job.retryScheduled = true
575
618
  job.retryAttempts++
619
+ const waitLimits = [...job.waiters].map(waiter => waiter.maxRateLimitRetryWaitMs)
576
620
  debugRateLimitRetry({
577
621
  relay: this.url,
578
622
  operation: job.type,
579
623
  retryAttempt: job.retryAttempts,
580
624
  maxRetries: Math.max(...[...job.waiters].map(waiter => waiter.rateLimitRetries)),
581
- retryAt
625
+ retryAt,
626
+ effectiveWaitMs: Math.max(0, retryAt - Date.now()),
627
+ maxWaitMs: waitLimits.includes(null) ? null : Math.max(...waitLimits)
582
628
  })
583
629
  this.#dispatchEventAttempt(job)
584
630
  }
@@ -586,6 +632,7 @@ export class RelayConnection {
586
632
  #sendEventOperation (type, event, map, timeoutCode, signal, {
587
633
  useBulkPacing = false,
588
634
  rateLimitRetries = 0,
635
+ maxRateLimitRetryWaitMs = this.#defaultMaxRateLimitRetryWaitMs,
589
636
  retrySignal,
590
637
  deadlineAt = null
591
638
  } = {}) {
@@ -616,7 +663,8 @@ export class RelayConnection {
616
663
  signal,
617
664
  retrySignal,
618
665
  deadlineAt,
619
- rateLimitRetries
666
+ rateLimitRetries,
667
+ maxRateLimitRetryWaitMs
620
668
  })
621
669
  if (!created || !this.#hasJob(job)) return promise
622
670
  if (job.pacing === 'bulk') {
@@ -19,6 +19,7 @@ const COUNT_TIMEOUT_AFTER_FIRST_COUNT_MS = 500
19
19
  const SEND_TIMEOUT_MS = 30000
20
20
  const LIVE_OVERLAP_SECONDS = 600
21
21
  const LIVE_PROGRESS_INTERVAL_MS = 60000
22
+ const DEFAULT_MAX_RATE_LIMIT_RETRY_WAIT_MS = 1500
22
23
 
23
24
  // Returns a function that should be called for each received event (valid or invalid).
24
25
  // Calls onSatisfied() and stops counting once the filter is fully satisfied per relay:
@@ -113,6 +114,36 @@ function validateRateLimitRetries (value) {
113
114
  return value
114
115
  }
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
+
116
147
  function assertReadOptions (filter, timeouts) {
117
148
  if (!filter || typeof filter !== 'object' || Array.isArray(filter)) throw new ValidationError('INVALID_FILTER')
118
149
  for (const value of Object.values(timeouts)) {
@@ -167,10 +198,20 @@ export class RelayPool {
167
198
  #readRetry
168
199
  #options
169
200
 
170
- constructor ({ _createRelay, _isOnline, _onOnline, WebSocket: WebSocketImpl, rateLimitCapMs = DEFAULT_RATE_LIMIT_CAP_MS, rateLimitRetries = 1, ...capacity } = {}) {
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
+ } = {}) {
171
211
  this.#options = {
172
212
  rateLimitCapMs: validateRateLimitCapMs(rateLimitCapMs),
173
- rateLimitRetries: validateRateLimitRetries(rateLimitRetries)
213
+ rateLimitRetries: validateRateLimitRetries(rateLimitRetries),
214
+ maxRateLimitRetryWaitMs: validateMaxRateLimitRetryWaitMs(maxRateLimitRetryWaitMs)
174
215
  }
175
216
  this.#WebSocket = WebSocketImpl
176
217
  this.#createRelay = _createRelay ?? (url => new RelayConnection(url, {
@@ -187,11 +228,14 @@ export class RelayPool {
187
228
 
188
229
  setOptions (partial = {}) {
189
230
  if (!partial || typeof partial !== 'object' || Array.isArray(partial)) throw new ValidationError('INVALID_RELAY_POOL_OPTIONS')
190
- const unknown = Object.keys(partial).find(key => !['rateLimitCapMs', 'rateLimitRetries'].includes(key))
231
+ const unknown = Object.keys(partial).find(key => !['rateLimitCapMs', 'rateLimitRetries', 'maxRateLimitRetryWaitMs'].includes(key))
191
232
  if (unknown) throw new ValidationError('UNKNOWN_RELAY_POOL_OPTION')
192
233
  const next = { ...this.#options }
193
234
  if (Object.hasOwn(partial, 'rateLimitCapMs')) next.rateLimitCapMs = validateRateLimitCapMs(partial.rateLimitCapMs)
194
235
  if (Object.hasOwn(partial, 'rateLimitRetries')) next.rateLimitRetries = validateRateLimitRetries(partial.rateLimitRetries)
236
+ if (Object.hasOwn(partial, 'maxRateLimitRetryWaitMs')) {
237
+ next.maxRateLimitRetryWaitMs = validateMaxRateLimitRetryWaitMs(partial.maxRateLimitRetryWaitMs)
238
+ }
195
239
  this.#options = next
196
240
  for (const relay of this.#relays.values()) relay.setRateLimitCapMs?.(next.rateLimitCapMs)
197
241
  return this.getOptions()
@@ -201,6 +245,12 @@ export class RelayPool {
201
245
  return validateRateLimitRetries(value === undefined ? this.#options.rateLimitRetries : value)
202
246
  }
203
247
 
248
+ #maxRetryWait (value) {
249
+ return validateMaxRateLimitRetryWaitMs(
250
+ value === undefined ? this.#options.maxRateLimitRetryWaitMs : value
251
+ )
252
+ }
253
+
204
254
  // Injects the WebSocket implementation used by new pooled connections (e.g.
205
255
  // a launcher-owned relay multiplexer). Existing connections keep the
206
256
  // implementation they were created with.
@@ -293,24 +343,45 @@ export class RelayPool {
293
343
  async #publishEvent (relay, event, getAuthEvent, signal, {
294
344
  useBulkPacing,
295
345
  rateLimitRetries,
346
+ maxRateLimitRetryWaitMs,
296
347
  retrySignal,
297
348
  deadlineAt
298
349
  }) {
299
350
  try {
300
- await relay.publish(event, { signal, useBulkPacing, rateLimitRetries, retrySignal, deadlineAt })
351
+ await relay.publish(event, {
352
+ signal,
353
+ useBulkPacing,
354
+ rateLimitRetries,
355
+ maxRateLimitRetryWaitMs,
356
+ retrySignal,
357
+ deadlineAt
358
+ })
301
359
  return 'published'
302
360
  } catch (error) {
303
361
  const reason = error instanceof Error ? error : new Error(String(error))
304
362
  if (!getAuthEvent || !requiresNip42Auth(reason)) throw reason
305
363
 
306
364
  try {
307
- await relay.authenticate(getAuthEvent, { signal, rateLimitRetries, retrySignal, deadlineAt })
365
+ await relay.authenticate(getAuthEvent, {
366
+ signal,
367
+ rateLimitRetries,
368
+ maxRateLimitRetryWaitMs,
369
+ retrySignal,
370
+ deadlineAt
371
+ })
308
372
  } catch (error) {
309
373
  const authReason = error instanceof Error ? error : new Error(String(error))
310
374
  if (retrySignal?.aborted && authReason.message?.startsWith('rate-limited:')) throw authReason
311
375
  throw new Nip42AuthenticationError(authReason)
312
376
  }
313
- await relay.publish(event, { signal, useBulkPacing, rateLimitRetries, retrySignal, deadlineAt })
377
+ await relay.publish(event, {
378
+ signal,
379
+ useBulkPacing,
380
+ rateLimitRetries,
381
+ maxRateLimitRetryWaitMs,
382
+ retrySignal,
383
+ deadlineAt
384
+ })
314
385
  return 'published'
315
386
  }
316
387
  }
@@ -322,13 +393,15 @@ export class RelayPool {
322
393
  timeout = COUNT_TIMEOUT_MS,
323
394
  timeoutAfterFirstCount = COUNT_TIMEOUT_AFTER_FIRST_COUNT_MS,
324
395
  signal,
325
- rateLimitRetries
396
+ rateLimitRetries,
397
+ maxRateLimitRetryWaitMs
326
398
  } = {}) {
327
399
  if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
328
400
  throw new ValidationError('COUNT_FILTER_REQUIRED')
329
401
  }
330
402
  if (signal?.aborted) throw new Error('Aborted')
331
403
  const retries = this.#retryCount(rateLimitRetries)
404
+ const maxRetryWait = this.#maxRetryWait(maxRateLimitRetryWaitMs)
332
405
 
333
406
  const urls = normalizedRelayUrls(relays)
334
407
  if (!urls.length) {
@@ -425,9 +498,10 @@ export class RelayPool {
425
498
  const handleError = (relay, error) => {
426
499
  const reason = error instanceof Error ? error : new Error(String(error))
427
500
  if (isResolved || !pending.has(relay)) return
428
- const retryAt = Number.isSafeInteger(reason.retryAt) ? reason.retryAt : 0
501
+ const retryAt = effectiveRetryAt(reason)
429
502
  if (reason.message?.startsWith('rate-limited:') && retryAt &&
430
- retryCounts.get(relay) < retries && (deadline === null || retryAt < deadline)) {
503
+ retryCounts.get(relay) < retries && (deadline === null || retryAt < deadline) &&
504
+ retryWaitAllowed(retryAt, maxRetryWait)) {
431
505
  retryCounts.set(relay, retryCounts.get(relay) + 1)
432
506
  retryErrors.set(relay, reason)
433
507
  debugRateLimitRetry({
@@ -435,7 +509,9 @@ export class RelayPool {
435
509
  operation: 'COUNT',
436
510
  retryAttempt: retryCounts.get(relay),
437
511
  maxRetries: retries,
438
- retryAt
512
+ retryAt,
513
+ effectiveWaitMs: Math.max(0, retryAt - Date.now()),
514
+ maxWaitMs: maxRetryWait
439
515
  })
440
516
  const controller = new AbortController()
441
517
  const combined = AbortSignal.any([countController.signal, controller.signal])
@@ -491,12 +567,14 @@ export class RelayPool {
491
567
  deduplicateAcrossRelays = true,
492
568
  queueTimeout = 30000,
493
569
  rateLimitRetries,
570
+ maxRateLimitRetryWaitMs,
494
571
  _admissions
495
572
  } = {}) {
496
573
  assertReadOptions(filter, { timeout, timeoutAfterFirstEose, queueTimeout })
497
574
  if (typeof deduplicateAcrossRelays !== 'boolean') throw new ValidationError('INVALID_DEDUPLICATE_ACROSS_RELAYS')
498
575
  if (signal?.aborted) throw new Error('Aborted')
499
576
  const retries = this.#retryCount(rateLimitRetries)
577
+ const maxRetryWait = this.#maxRetryWait(maxRateLimitRetryWaitMs)
500
578
  const urls = normalizedRelayUrls(relays)
501
579
  const subscriptions = new Map()
502
580
  const retryControllers = new Map()
@@ -580,15 +658,18 @@ export class RelayPool {
580
658
  const scheduleRetry = (url, error) => {
581
659
  if (isResolved || outcomes.has(url) || retryControllers.has(url) ||
582
660
  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
661
+ const retryAt = effectiveRetryAt(error)
662
+ if (!retryAt || (deadlines.has(url) && retryAt >= deadlines.get(url)) ||
663
+ !retryWaitAllowed(retryAt, maxRetryWait)) return false
585
664
  retryCounts.set(url, retryCounts.get(url) + 1)
586
665
  debugRateLimitRetry({
587
666
  relay: url,
588
667
  operation: 'REQ',
589
668
  retryAttempt: retryCounts.get(url),
590
669
  maxRetries: retries,
591
- retryAt
670
+ retryAt,
671
+ effectiveWaitMs: Math.max(0, retryAt - Date.now()),
672
+ maxWaitMs: maxRetryWait
592
673
  })
593
674
  const controller = new AbortController()
594
675
  const combined = AbortSignal.any([admissionSignal, controller.signal])
@@ -1392,12 +1473,14 @@ export class RelayPool {
1392
1473
  onRelayResult,
1393
1474
  signal,
1394
1475
  useBulkPacing = false,
1395
- rateLimitRetries
1476
+ rateLimitRetries,
1477
+ maxRateLimitRetryWaitMs
1396
1478
  } = {}) {
1397
1479
  if (signal != null && (typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function' || typeof signal.removeEventListener !== 'function')) throw new ValidationError('INVALID_RELAY_SIGNAL')
1398
1480
  if (getRetryEvent != null && typeof getRetryEvent !== 'function') throw new ValidationError('INVALID_RETRY_EVENT_CALLBACK')
1399
1481
  if (typeof useBulkPacing !== 'boolean') throw new ValidationError('INVALID_USE_BULK_PACING')
1400
1482
  const retries = this.#retryCount(rateLimitRetries)
1483
+ const maxRetryWait = this.#maxRetryWait(maxRateLimitRetryWaitMs)
1401
1484
  const urls = normalizedRelayUrls(relays)
1402
1485
  if (!urls.length) {
1403
1486
  const promise = Promise.resolve(publishSummary([], urls, {
@@ -1456,6 +1539,7 @@ export class RelayPool {
1456
1539
  return await this.#publishEvent(relay, eventForAttempt, getAuthEvent, operationSignal, {
1457
1540
  useBulkPacing,
1458
1541
  rateLimitRetries: retries,
1542
+ maxRateLimitRetryWaitMs: maxRetryWait,
1459
1543
  retrySignal: retryControllers[index].signal,
1460
1544
  deadlineAt: deadline
1461
1545
  })