libp2r2p 0.12.7 → 0.12.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -8
- package/package.json +1 -1
- package/private-channel/index.js +9 -3
- package/private-message/index.js +21 -11
- package/private-messenger/file/index.js +1 -1
- package/private-messenger/index.js +21 -11
- package/private-messenger/recovery/index.js +6 -2
- package/private-messenger/session/README.md +13 -0
- package/relay/helpers/error.js +3 -3
- package/relay/helpers/retry-advice.js +8 -3
- package/relay/helpers/retry-debug.js +20 -0
- package/relay/services/relay-connection.js +481 -56
- package/relay/services/relay-pool.js +199 -19
|
@@ -2,14 +2,53 @@ 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'
|
|
6
|
+
import { DEFAULT_RATE_LIMIT_CAP_MS } from '../helpers/retry-advice.js'
|
|
5
7
|
|
|
6
8
|
const DEFAULT_CONNECT_TIMEOUT = 3000
|
|
7
9
|
const DEFAULT_OPERATION_TIMEOUT = 30000
|
|
10
|
+
const BULK_PACING_MS = 1000
|
|
11
|
+
const RATE_LIMIT_BACKOFF_MAX_MS = 30000
|
|
12
|
+
const OPERATION_TYPES = ['EVENT', 'AUTH', 'REQ', 'COUNT']
|
|
8
13
|
|
|
9
14
|
function errorFrom (reason, fallback) {
|
|
10
15
|
return reason instanceof Error ? reason : new Error(String(reason || fallback))
|
|
11
16
|
}
|
|
12
17
|
|
|
18
|
+
function retryAtFrom (value) {
|
|
19
|
+
const pending = [value]
|
|
20
|
+
const seen = new Set()
|
|
21
|
+
let retryAt = 0
|
|
22
|
+
while (pending.length) {
|
|
23
|
+
const current = pending.pop()
|
|
24
|
+
if (!current || typeof current !== 'object' || seen.has(current)) continue
|
|
25
|
+
seen.add(current)
|
|
26
|
+
if (Number.isSafeInteger(current.retryAt)) retryAt = Math.max(retryAt, current.retryAt)
|
|
27
|
+
for (const key of ['cause', 'reason', 'error']) pending.push(current[key])
|
|
28
|
+
for (const key of ['errors', 'reports', 'relays']) {
|
|
29
|
+
if (Array.isArray(current[key])) pending.push(...current[key])
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return retryAt
|
|
33
|
+
}
|
|
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
|
+
|
|
13
52
|
function hasMatchingPrefix (values, candidate) {
|
|
14
53
|
return !values || values.some(value => typeof value === 'string' && candidate.startsWith(value))
|
|
15
54
|
}
|
|
@@ -51,10 +90,26 @@ export class RelayConnection {
|
|
|
51
90
|
#authentications = new Map()
|
|
52
91
|
#counts = new Map()
|
|
53
92
|
#retryAtByType = new Map()
|
|
93
|
+
#cooldownWaiters = new Set()
|
|
94
|
+
#bulkQueue = []
|
|
95
|
+
#bulkActive = null
|
|
96
|
+
#bulkTimer = null
|
|
97
|
+
#bulkNextAt = 0
|
|
98
|
+
#rateLimitBackoffMs = new Map(OPERATION_TYPES.map(type => [type, BULK_PACING_MS]))
|
|
99
|
+
#getRateLimitCapMs
|
|
54
100
|
|
|
55
|
-
constructor (url, {
|
|
101
|
+
constructor (url, {
|
|
102
|
+
WebSocket: WebSocketImpl = globalThis.WebSocket,
|
|
103
|
+
rateLimitCapMs = () => DEFAULT_RATE_LIMIT_CAP_MS
|
|
104
|
+
} = {}) {
|
|
56
105
|
this.url = url
|
|
57
106
|
this.#WebSocket = WebSocketImpl
|
|
107
|
+
if (typeof rateLimitCapMs !== 'function' && (!Number.isSafeInteger(rateLimitCapMs) || rateLimitCapMs < 1)) {
|
|
108
|
+
throw new ValidationError('INVALID_RATE_LIMIT_CAP_MS')
|
|
109
|
+
}
|
|
110
|
+
this.#getRateLimitCapMs = typeof rateLimitCapMs === 'function'
|
|
111
|
+
? rateLimitCapMs
|
|
112
|
+
: () => rateLimitCapMs
|
|
58
113
|
this.ws = null
|
|
59
114
|
this.publishTimeout = DEFAULT_OPERATION_TIMEOUT
|
|
60
115
|
this.onnotice = null
|
|
@@ -66,6 +121,19 @@ export class RelayConnection {
|
|
|
66
121
|
// Exposes socket context to the pool's operation-wide publication deadline.
|
|
67
122
|
get lastTransportError () { return this.#lastTransportError }
|
|
68
123
|
|
|
124
|
+
setRateLimitCapMs (capMs, now = Date.now()) {
|
|
125
|
+
if (!Number.isSafeInteger(capMs) || capMs < 1) throw new ValidationError('INVALID_RATE_LIMIT_CAP_MS')
|
|
126
|
+
const limit = now + Math.min(capMs, Number.MAX_SAFE_INTEGER - now)
|
|
127
|
+
let changed = false
|
|
128
|
+
for (const [type, retryAt] of this.#retryAtByType) {
|
|
129
|
+
if (retryAt <= limit) continue
|
|
130
|
+
this.#retryAtByType.set(type, limit)
|
|
131
|
+
changed = true
|
|
132
|
+
}
|
|
133
|
+
if (changed) for (const wake of [...this.#cooldownWaiters]) wake()
|
|
134
|
+
this.#pumpBulkPublishes()
|
|
135
|
+
}
|
|
136
|
+
|
|
69
137
|
async connect ({ timeout = DEFAULT_CONNECT_TIMEOUT, signal } = {}) {
|
|
70
138
|
if (this.ws?.readyState === 1) return
|
|
71
139
|
if (this.#connectPromise) return await this.#connectPromise
|
|
@@ -124,28 +192,58 @@ export class RelayConnection {
|
|
|
124
192
|
|
|
125
193
|
// New work respects relay cooldowns; cleanup uses send() directly. These
|
|
126
194
|
// waits stay within the caller's existing deadline and are cancellable.
|
|
127
|
-
#dispatchWork (type, send, fail) {
|
|
195
|
+
#dispatchWork (type, send, fail, onDispatch) {
|
|
128
196
|
let timer = null
|
|
129
197
|
let cancelled = false
|
|
130
|
-
const
|
|
198
|
+
const wake = () => {
|
|
199
|
+
clearTimeout(timer)
|
|
200
|
+
timer = null
|
|
201
|
+
schedule()
|
|
202
|
+
}
|
|
203
|
+
const schedule = () => {
|
|
131
204
|
if (cancelled) return
|
|
132
205
|
const remaining = (this.#retryAtByType.get(type) ?? 0) - Date.now()
|
|
133
206
|
if (remaining > 0) {
|
|
134
|
-
timer = maybeUnref(setTimeout(
|
|
207
|
+
timer = maybeUnref(setTimeout(wake, remaining))
|
|
135
208
|
return
|
|
136
209
|
}
|
|
210
|
+
this.#cooldownWaiters.delete(wake)
|
|
211
|
+
onDispatch?.()
|
|
137
212
|
try { send() } catch (error) { fail(error) }
|
|
138
213
|
}
|
|
214
|
+
const dispatch = () => {
|
|
215
|
+
this.#cooldownWaiters.add(wake)
|
|
216
|
+
schedule()
|
|
217
|
+
}
|
|
139
218
|
dispatch()
|
|
140
|
-
return () => {
|
|
219
|
+
return () => {
|
|
220
|
+
cancelled = true
|
|
221
|
+
this.#cooldownWaiters.delete(wake)
|
|
222
|
+
clearTimeout(timer)
|
|
223
|
+
}
|
|
141
224
|
}
|
|
142
225
|
|
|
143
226
|
#rejection (type, reason, params, fallback) {
|
|
144
|
-
const error = relayRejectionError(reason, params, fallback)
|
|
145
|
-
if (error.
|
|
227
|
+
const error = relayRejectionError(reason, params, fallback, { rateLimitCapMs: this.#getRateLimitCapMs() })
|
|
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
|
+
}
|
|
146
240
|
return error
|
|
147
241
|
}
|
|
148
242
|
|
|
243
|
+
#recordSuccess (type) {
|
|
244
|
+
this.#rateLimitBackoffMs.set(type, BULK_PACING_MS)
|
|
245
|
+
}
|
|
246
|
+
|
|
149
247
|
subscribe (filters, handlers = {}) {
|
|
150
248
|
if (!Array.isArray(filters) || !filters.length) throw new ValidationError('SUBSCRIPTION_FILTERS_REQUIRED')
|
|
151
249
|
const id = `p2r2p-sub:${++this.#serial}`
|
|
@@ -173,47 +271,359 @@ export class RelayConnection {
|
|
|
173
271
|
return { id, close }
|
|
174
272
|
}
|
|
175
273
|
|
|
176
|
-
publish (event, {
|
|
274
|
+
publish (event, {
|
|
275
|
+
signal,
|
|
276
|
+
useBulkPacing = false,
|
|
277
|
+
rateLimitRetries = 0,
|
|
278
|
+
retrySignal,
|
|
279
|
+
deadlineAt = null
|
|
280
|
+
} = {}) {
|
|
177
281
|
if (!isValidEvent(event)) return Promise.reject(new Error('INVALID_EVENT'))
|
|
178
|
-
|
|
282
|
+
if (typeof useBulkPacing !== 'boolean') return Promise.reject(new ValidationError('INVALID_USE_BULK_PACING'))
|
|
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
|
+
})
|
|
179
290
|
}
|
|
180
291
|
|
|
181
|
-
async authenticate (getAuthEvent, {
|
|
292
|
+
async authenticate (getAuthEvent, {
|
|
293
|
+
signal,
|
|
294
|
+
rateLimitRetries = 0,
|
|
295
|
+
deadlineAt = null,
|
|
296
|
+
retrySignal
|
|
297
|
+
} = {}) {
|
|
182
298
|
if (!this.#challenge) throw new Error('AUTH_CHALLENGE_MISSING')
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
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
|
+
}
|
|
186
330
|
}
|
|
187
331
|
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
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
|
|
196
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)
|
|
383
|
+
}
|
|
384
|
+
|
|
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)
|
|
399
|
+
if (index >= 0) this.#bulkQueue.splice(index, 1)
|
|
400
|
+
const wasActive = this.#bulkActive === job
|
|
401
|
+
if (wasActive) {
|
|
402
|
+
this.#bulkActive = null
|
|
403
|
+
this.#bulkNextAt = Math.max(this.#bulkNextAt, Date.now(), job.startedAt + BULK_PACING_MS)
|
|
404
|
+
}
|
|
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
|
+
}) {
|
|
197
469
|
const deferred = Promise.withResolvers()
|
|
198
|
-
const
|
|
199
|
-
|
|
200
|
-
signal
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
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
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
#clearBulkScheduler () {
|
|
498
|
+
clearTimeout(this.#bulkTimer)
|
|
499
|
+
this.#bulkTimer = null
|
|
500
|
+
this.#bulkQueue.length = 0
|
|
501
|
+
this.#bulkActive = null
|
|
502
|
+
this.#bulkNextAt = 0
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
#pumpBulkPublishes () {
|
|
506
|
+
if (this.#bulkActive || this.#bulkQueue.length === 0) return
|
|
507
|
+
clearTimeout(this.#bulkTimer)
|
|
508
|
+
this.#bulkTimer = null
|
|
509
|
+
while (this.#bulkQueue.length) {
|
|
510
|
+
const job = this.#bulkQueue[0]
|
|
511
|
+
if (this.#hasJob(job) && job.waiters.size > 0) break
|
|
512
|
+
this.#bulkQueue.shift()
|
|
513
|
+
}
|
|
514
|
+
if (!this.#bulkQueue.length) return
|
|
515
|
+
|
|
516
|
+
const now = Date.now()
|
|
517
|
+
const eligibleAt = Math.max(this.#bulkNextAt, this.#retryAtByType.get('EVENT') ?? 0)
|
|
518
|
+
if (eligibleAt > now) {
|
|
519
|
+
this.#bulkTimer = maybeUnref(setTimeout(() => this.#pumpBulkPublishes(), eligibleAt - now))
|
|
520
|
+
return
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
const job = this.#bulkQueue.shift()
|
|
524
|
+
const startedAt = now
|
|
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)
|
|
206
570
|
}
|
|
207
571
|
}
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
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)
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
#sendEventOperation (type, event, map, timeoutCode, signal, {
|
|
587
|
+
useBulkPacing = false,
|
|
588
|
+
rateLimitRetries = 0,
|
|
589
|
+
retrySignal,
|
|
590
|
+
deadlineAt = null
|
|
591
|
+
} = {}) {
|
|
592
|
+
if (signal?.aborted) return Promise.reject(signal.reason)
|
|
593
|
+
let job = this.#selectJob(map, event, useBulkPacing && type === 'EVENT')
|
|
594
|
+
const created = !job
|
|
211
595
|
if (created) {
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
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
|
|
612
|
+
}
|
|
613
|
+
this.#addJob(job)
|
|
215
614
|
}
|
|
216
|
-
|
|
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)
|
|
624
|
+
this.#pumpBulkPublishes()
|
|
625
|
+
} else this.#dispatchEventAttempt(job)
|
|
626
|
+
return promise
|
|
217
627
|
}
|
|
218
628
|
|
|
219
629
|
countWithHll (filters, { signal } = {}) {
|
|
@@ -230,24 +640,26 @@ export class RelayConnection {
|
|
|
230
640
|
return deferred.promise
|
|
231
641
|
}
|
|
232
642
|
|
|
233
|
-
#
|
|
234
|
-
const
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
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)
|
|
243
655
|
}
|
|
244
|
-
pending.waiters.clear()
|
|
245
656
|
}
|
|
246
657
|
|
|
247
658
|
#settleCount (id, payload, reason) {
|
|
248
659
|
const pending = this.#counts.get(id)
|
|
249
660
|
if (!pending) return
|
|
250
661
|
this.#counts.delete(id)
|
|
662
|
+
if (!reason) this.#recordSuccess('COUNT')
|
|
251
663
|
pending.cancelSend?.()
|
|
252
664
|
pending.signal?.removeEventListener('abort', pending.onAbort)
|
|
253
665
|
if (reason) pending.reject(errorFrom(reason, 'COUNT_REJECTED'))
|
|
@@ -271,7 +683,11 @@ export class RelayConnection {
|
|
|
271
683
|
return
|
|
272
684
|
}
|
|
273
685
|
if (data[0] === 'EOSE') {
|
|
274
|
-
this.#subscriptions.get(data[1])
|
|
686
|
+
const subscription = this.#subscriptions.get(data[1])
|
|
687
|
+
if (subscription) {
|
|
688
|
+
this.#recordSuccess('REQ')
|
|
689
|
+
subscription.handlers.oneose?.()
|
|
690
|
+
}
|
|
275
691
|
return
|
|
276
692
|
}
|
|
277
693
|
if (data[0] === 'CLOSED') {
|
|
@@ -287,10 +703,17 @@ export class RelayConnection {
|
|
|
287
703
|
return
|
|
288
704
|
}
|
|
289
705
|
if (data[0] === 'OK') {
|
|
290
|
-
for (const [type,
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
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
|
+
}
|
|
294
717
|
}
|
|
295
718
|
return
|
|
296
719
|
}
|
|
@@ -314,8 +737,9 @@ export class RelayConnection {
|
|
|
314
737
|
subscription.cancelSend?.()
|
|
315
738
|
subscription.handlers.onclose?.(reason)
|
|
316
739
|
}
|
|
317
|
-
|
|
318
|
-
|
|
740
|
+
const jobs = [...this.#allJobs(this.#publishes), ...this.#allJobs(this.#authentications)]
|
|
741
|
+
this.#clearBulkScheduler()
|
|
742
|
+
for (const job of jobs) this.#settleJob(job, reason)
|
|
319
743
|
for (const id of [...this.#counts.keys()]) this.#settleCount(id, null, reason)
|
|
320
744
|
this.onclose?.(reason)
|
|
321
745
|
}
|
|
@@ -330,8 +754,9 @@ export class RelayConnection {
|
|
|
330
754
|
subscription.cancelSend?.()
|
|
331
755
|
subscription.handlers.onclose?.()
|
|
332
756
|
}
|
|
333
|
-
|
|
334
|
-
|
|
757
|
+
const jobs = [...this.#allJobs(this.#publishes), ...this.#allJobs(this.#authentications)]
|
|
758
|
+
this.#clearBulkScheduler()
|
|
759
|
+
for (const job of jobs) this.#settleJob(job, reason)
|
|
335
760
|
for (const id of [...this.#counts.keys()]) this.#settleCount(id, null, reason)
|
|
336
761
|
if (socket && socket.readyState < 2) socket.close()
|
|
337
762
|
}
|