libp2r2p 0.12.9 → 0.12.11
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 +57 -4
- package/idb-queue/index.js +128 -7
- package/package.json +1 -1
- package/private-channel/helpers/history.js +4 -1
- package/private-message/helpers/idempotency.js +57 -0
- package/private-message/index.js +16 -7
- package/private-messenger/file/README.md +2 -0
- package/private-messenger/file/index.js +19 -2
- package/private-messenger/helpers/fallback-race.js +7 -1
- package/private-messenger/helpers/send-routing.js +5 -1
- package/private-messenger/index.js +172 -13
- package/private-messenger/recovery/index.js +11 -2
- package/relay/helpers/retry-debug.js +6 -2
- package/relay/services/relay-connection.js +55 -7
- package/relay/services/relay-pool.js +98 -14
|
@@ -19,10 +19,10 @@
|
|
|
19
19
|
// await persistPrivateMessage(message)
|
|
20
20
|
// await ack()
|
|
21
21
|
// }
|
|
22
|
-
// await messenger.ask({ receiverPubkey, payload: { ping: true } })
|
|
23
|
-
// await messenger.reply({ question
|
|
24
|
-
// await messenger.tell({ receiverPubkey, payload: { note: 'hello' } })
|
|
25
|
-
// await messenger.yell({ receiverPubkeys, payload: { notice: 'hello all' } })
|
|
22
|
+
// const { question } = await messenger.ask({ receiverPubkey, payload: { ping: true }, idempotencyKey: 'request:42' })
|
|
23
|
+
// await messenger.reply({ question, payload: { ok: true }, idempotencyKey: 'reply:42' })
|
|
24
|
+
// await messenger.tell({ receiverPubkey, payload: { note: 'hello' }, idempotencyKey: 'notification:42' })
|
|
25
|
+
// await messenger.yell({ receiverPubkeys, payload: { notice: 'hello all' }, idempotencyKey: 'notice:42' })
|
|
26
26
|
// await messenger.broadcastRumor({ receiverPubkeys, rumor: { kind, tags: [], content } })
|
|
27
27
|
// await messenger.broadcastEvent({ receiverPubkeys, event: signedNostrEvent })
|
|
28
28
|
// await messenger.broadcastNymRumor({ rumor: { kind, tags: [], content } })
|
|
@@ -62,13 +62,16 @@ import { migrateMessageQueue } from './services/migrate-message-queue.js'
|
|
|
62
62
|
import { createPendingDecryption, pendingContentKeyGroup, pendingMissingContentKeyGroup } from './services/pending-decryption.js'
|
|
63
63
|
import { createDecryptionScheduler } from './services/decryption-scheduler.js'
|
|
64
64
|
import { decryptionError, isDeferredDecryptionError } from '../private-channel/helpers/decryption-error.js'
|
|
65
|
+
import { bytesToHex } from '../base16/index.js'
|
|
65
66
|
import { bytesToBase64 } from '../base64/index.js'
|
|
67
|
+
import { sha256 } from '@noble/hashes/sha2.js'
|
|
66
68
|
import { ValidationError } from '../error/index.js'
|
|
67
69
|
import { getRelaysByPubkey, pickRelaysForPubkeys, subscribeRelayListUpdates, relayPool } from '../relay/index.js'
|
|
68
70
|
import * as privateChannel from '../private-channel/index.js'
|
|
69
71
|
import { DEFAULT_RECEIVED_CHUNK_TTL_MS } from '../private-channel/services/received-chunks.js'
|
|
70
72
|
import { createQueue } from '../idb-queue/index.js'
|
|
71
73
|
import { createChannelStateStore } from './services/channel-state.js'
|
|
74
|
+
import { normalizeIdempotencyKey, readIdempotencyKey } from '../private-message/helpers/idempotency.js'
|
|
72
75
|
import { DEFAULT_STALE_CHANNEL_SECONDS } from './constants/index.js'
|
|
73
76
|
import {
|
|
74
77
|
activatePrivateMessengerStorage,
|
|
@@ -123,8 +126,13 @@ const MESSAGE_QUEUE_HIGH_WATER_RATIO = 0.7
|
|
|
123
126
|
const MESSAGE_QUEUE_LOW_WATER_RATIO = 0.5
|
|
124
127
|
const SEED_KEY = '__p2r2pSeedKey'
|
|
125
128
|
const SEED_TIME = '__p2r2pSeedTime'
|
|
129
|
+
const COALESCING_INDEX = 'byCoalescingKey'
|
|
130
|
+
const COALESCING_DIGEST = /^[0-9a-f]{64}$/
|
|
131
|
+
const COALESCING_KEEP = new Set(['oldest', 'latest'])
|
|
132
|
+
const DEDUPE_TYPES = new Set(['ask', 'reply', 'tell', 'yell'])
|
|
126
133
|
const MESSAGE_QUEUE_INDEXES = {
|
|
127
134
|
byChannel: 'channelPubkey',
|
|
135
|
+
[COALESCING_INDEX]: 'coalescingKey',
|
|
128
136
|
byChannelTypeEventId: {
|
|
129
137
|
keyPath: ['channelPubkey', 'type', 'event.id', 'provenance'],
|
|
130
138
|
unique: true
|
|
@@ -303,6 +311,7 @@ export class PrivateMessenger {
|
|
|
303
311
|
onStateChanged,
|
|
304
312
|
onDebug,
|
|
305
313
|
onError = defaultOnError,
|
|
314
|
+
resolveInboundCoalescing,
|
|
306
315
|
_privateMessage = privateMessage,
|
|
307
316
|
_privateChannel = privateChannel,
|
|
308
317
|
_getRelaysByPubkey = getRelaysByPubkey,
|
|
@@ -324,6 +333,9 @@ export class PrivateMessenger {
|
|
|
324
333
|
} = {}) {
|
|
325
334
|
if (onStateChanged != null && typeof onStateChanged !== 'function') throw new ValidationError('INVALID_ON_STATE_CHANGED')
|
|
326
335
|
if (typeof pendingDecryptionReady !== 'boolean') throw new ValidationError('INVALID_PENDING_DECRYPTION_READY')
|
|
336
|
+
if (resolveInboundCoalescing != null && typeof resolveInboundCoalescing !== 'function') {
|
|
337
|
+
throw new ValidationError('INVALID_RESOLVE_INBOUND_COALESCING')
|
|
338
|
+
}
|
|
327
339
|
this.fallbackRelays = normalizeFallbackRelays(fallbackRelays)
|
|
328
340
|
this.fallbackDelayMs = normalizeFallbackDelay(fallbackDelayMs)
|
|
329
341
|
this.offlineRecoverySeconds = normalizeOfflineRecoverySeconds(offlineRecoverySeconds)
|
|
@@ -368,6 +380,7 @@ export class PrivateMessenger {
|
|
|
368
380
|
this._random = _random
|
|
369
381
|
this.onMessageQueued = onMessageQueued
|
|
370
382
|
this.onDebug = onDebug
|
|
383
|
+
this.resolveInboundCoalescing = resolveInboundCoalescing
|
|
371
384
|
this._privateMessage = _privateMessage.createPrivateMessageSession?.() ?? _privateMessage
|
|
372
385
|
this._privateChannel = _privateChannel
|
|
373
386
|
this._getRelaysByPubkey = _getRelaysByPubkey
|
|
@@ -1946,7 +1959,14 @@ export class PrivateMessenger {
|
|
|
1946
1959
|
const pubkey = pending.record.channelPubkey
|
|
1947
1960
|
if (!this.channels.has(pubkey) || !this.desiredChannels.has(pubkey)) { this.pendingStorageWrites.delete(key); continue }
|
|
1948
1961
|
try {
|
|
1949
|
-
if (
|
|
1962
|
+
if (pending.record.coalescingKey) {
|
|
1963
|
+
await this.queue.coalesceBy(COALESCING_INDEX, pending.record, {
|
|
1964
|
+
compare: compareCoalescingItems,
|
|
1965
|
+
keep: pending.record.coalescingKeep
|
|
1966
|
+
})
|
|
1967
|
+
} else if (!pending.dedupeKey || !await this.queue.someBy('byChannelTypeEventId', pending.dedupeKey)) {
|
|
1968
|
+
await this.queue.enqueue(pending.record)
|
|
1969
|
+
}
|
|
1950
1970
|
} catch (error) { if (error?.name !== 'ConstraintError') throw error }
|
|
1951
1971
|
signal.throwIfAborted()
|
|
1952
1972
|
this.pendingStorageWrites.delete(key)
|
|
@@ -2186,6 +2206,70 @@ export class PrivateMessenger {
|
|
|
2186
2206
|
await this.enqueueRumor('message', channelPubkey, message)
|
|
2187
2207
|
}
|
|
2188
2208
|
|
|
2209
|
+
#coalescingMetadata (type, channelPubkey, message, info) {
|
|
2210
|
+
const supportsIdempotencyTag = DEDUPE_TYPES.has(type)
|
|
2211
|
+
const tagged = supportsIdempotencyTag
|
|
2212
|
+
? readIdempotencyKey(message.event)
|
|
2213
|
+
: { key: null, reason: '' }
|
|
2214
|
+
if (tagged.reason && tagged.reason !== 'missing') {
|
|
2215
|
+
this.debug('idempotency-tag-ignored', {
|
|
2216
|
+
type,
|
|
2217
|
+
code: messageCode(message) || '',
|
|
2218
|
+
reason: tagged.reason
|
|
2219
|
+
})
|
|
2220
|
+
}
|
|
2221
|
+
|
|
2222
|
+
let resolved = null
|
|
2223
|
+
if (this.resolveInboundCoalescing) {
|
|
2224
|
+
try {
|
|
2225
|
+
resolved = this.resolveInboundCoalescing(
|
|
2226
|
+
{ ...message, type, channelPubkey },
|
|
2227
|
+
{ idempotencyKey: tagged.key }
|
|
2228
|
+
)
|
|
2229
|
+
if (resolved != null && typeof resolved?.then === 'function') {
|
|
2230
|
+
throw new Error('COALESCING_RESOLVER_MUST_BE_SYNCHRONOUS')
|
|
2231
|
+
}
|
|
2232
|
+
} catch (cause) {
|
|
2233
|
+
this.onError?.(coalescingError(cause))
|
|
2234
|
+
resolved = null
|
|
2235
|
+
}
|
|
2236
|
+
}
|
|
2237
|
+
|
|
2238
|
+
let digest = null
|
|
2239
|
+
let keep = 'latest'
|
|
2240
|
+
if (resolved != null) {
|
|
2241
|
+
if (isPlainObject(resolved) && typeof resolved.key === 'string' &&
|
|
2242
|
+
COALESCING_DIGEST.test(resolved.key) &&
|
|
2243
|
+
(resolved.keep == null || COALESCING_KEEP.has(resolved.keep))) {
|
|
2244
|
+
digest = resolved.key
|
|
2245
|
+
keep = resolved.keep || 'latest'
|
|
2246
|
+
} else {
|
|
2247
|
+
this.onError?.(coalescingError(new ValidationError('INVALID_INBOUND_COALESCING_RESULT')))
|
|
2248
|
+
}
|
|
2249
|
+
}
|
|
2250
|
+
if (!digest && tagged.key) digest = idempotencyDigest(tagged.key)
|
|
2251
|
+
if (!digest) return null
|
|
2252
|
+
|
|
2253
|
+
const senderPubkey = info.senderPubkey || message.event?.pubkey || ''
|
|
2254
|
+
const code = messageCode(message)
|
|
2255
|
+
if (!channelPubkey || !senderPubkey || typeof code !== 'string' || !info.provenance) {
|
|
2256
|
+
this.onError?.(coalescingError(new ValidationError('INVALID_INBOUND_COALESCING_SCOPE')))
|
|
2257
|
+
return null
|
|
2258
|
+
}
|
|
2259
|
+
return {
|
|
2260
|
+
coalescingKey: JSON.stringify([
|
|
2261
|
+
channelPubkey,
|
|
2262
|
+
senderPubkey,
|
|
2263
|
+
type,
|
|
2264
|
+
code,
|
|
2265
|
+
info.provenance,
|
|
2266
|
+
digest
|
|
2267
|
+
]),
|
|
2268
|
+
coalescingKeep: keep,
|
|
2269
|
+
coalescingOrder: coalescingOrder(message)
|
|
2270
|
+
}
|
|
2271
|
+
}
|
|
2272
|
+
|
|
2189
2273
|
async enqueueRumor (type, channelPubkey, message) {
|
|
2190
2274
|
const channel = this.channels.get(channelPubkey)
|
|
2191
2275
|
if (channel?.mode === 'watchtower' && type !== 'ask') return
|
|
@@ -2215,8 +2299,33 @@ export class PrivateMessenger {
|
|
|
2215
2299
|
outer: message.outer || null,
|
|
2216
2300
|
meta: message.meta || null
|
|
2217
2301
|
}
|
|
2302
|
+
Object.assign(record, this.#coalescingMetadata(type, channelPubkey, message, info) || {})
|
|
2218
2303
|
try {
|
|
2219
|
-
|
|
2304
|
+
const coalesced = record.coalescingKey
|
|
2305
|
+
? await this.queue.coalesceBy(COALESCING_INDEX, record, {
|
|
2306
|
+
compare: compareCoalescingItems,
|
|
2307
|
+
keep: record.coalescingKeep
|
|
2308
|
+
})
|
|
2309
|
+
: null
|
|
2310
|
+
if (!coalesced) await this.queue.enqueue(record)
|
|
2311
|
+
if (coalesced?.status === 'ignored') {
|
|
2312
|
+
this.markSeen(channelPubkey, message.outer?.created_at || message.event?.created_at || nowSeconds())
|
|
2313
|
+
this.debug('message-coalescing-ignored', {
|
|
2314
|
+
code: messageCode(message) || '',
|
|
2315
|
+
keep: record.coalescingKeep,
|
|
2316
|
+
payloadBytes: encoder.encode(JSON.stringify(record)).byteLength
|
|
2317
|
+
})
|
|
2318
|
+
return
|
|
2319
|
+
}
|
|
2320
|
+
if (coalesced) {
|
|
2321
|
+
this.debug('message-coalesced', {
|
|
2322
|
+
code: messageCode(message) || '',
|
|
2323
|
+
keep: record.coalescingKeep,
|
|
2324
|
+
status: coalesced.status,
|
|
2325
|
+
removedUnreserved: coalesced.removed,
|
|
2326
|
+
payloadBytes: encoder.encode(JSON.stringify(record)).byteLength
|
|
2327
|
+
})
|
|
2328
|
+
}
|
|
2220
2329
|
} catch (err) {
|
|
2221
2330
|
// The unique index closes the small cross-instance race after `someBy`.
|
|
2222
2331
|
if (dedupeKey && err?.name === 'ConstraintError') {
|
|
@@ -2227,7 +2336,14 @@ export class PrivateMessenger {
|
|
|
2227
2336
|
this.recordInterruption([channelPubkey], message.outer?.created_at || message.event?.created_at || nowSeconds())
|
|
2228
2337
|
// Do not await stop from inside its own transport callback.
|
|
2229
2338
|
const atCapacity = isQueueCapacityError(err)
|
|
2230
|
-
if (!atCapacity && isRecoverableStorageFailure(err))
|
|
2339
|
+
if (!atCapacity && isRecoverableStorageFailure(err)) {
|
|
2340
|
+
const storageKey = record.coalescingKey || JSON.stringify(dedupeKey || [channelPubkey, type])
|
|
2341
|
+
this.pendingStorageWrites.set(storageKey, {
|
|
2342
|
+
record,
|
|
2343
|
+
dedupeKey,
|
|
2344
|
+
at: message.outer?.created_at || message.event?.created_at
|
|
2345
|
+
})
|
|
2346
|
+
}
|
|
2231
2347
|
if (atCapacity) {
|
|
2232
2348
|
await annotateQueueCapacityError(err, 'inbox', () => this.queue.getCapacity())
|
|
2233
2349
|
this.applyCapacityRecoveryTarget(err)
|
|
@@ -2243,7 +2359,7 @@ export class PrivateMessenger {
|
|
|
2243
2359
|
}
|
|
2244
2360
|
this.markSeen(channelPubkey, message.outer?.created_at || message.event?.created_at || nowSeconds())
|
|
2245
2361
|
this.wakeDeliveries()
|
|
2246
|
-
this.debug('enqueue', debugMessageInfo(type, channelPubkey, message))
|
|
2362
|
+
if (!record.coalescingKey) this.debug('enqueue', debugMessageInfo(type, channelPubkey, message))
|
|
2247
2363
|
this.onMessageQueued?.()
|
|
2248
2364
|
}
|
|
2249
2365
|
|
|
@@ -2501,7 +2617,7 @@ export class PrivateMessenger {
|
|
|
2501
2617
|
this.assertOpen()
|
|
2502
2618
|
this.touchStorageActivity().catch(err => this.onError?.(err))
|
|
2503
2619
|
await this.queueOperationTail
|
|
2504
|
-
const reservation = await this.queue.reserve()
|
|
2620
|
+
const reservation = await this.queue.reserve({ nackCoalescingIndex: COALESCING_INDEX })
|
|
2505
2621
|
if (!reservation) return null
|
|
2506
2622
|
if (this.closePromise) { await reservation.nack(); return null }
|
|
2507
2623
|
let finish
|
|
@@ -2534,7 +2650,8 @@ export class PrivateMessenger {
|
|
|
2534
2650
|
return delivery
|
|
2535
2651
|
}
|
|
2536
2652
|
|
|
2537
|
-
async ask ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkey, relays, relayToReceivers, message, code, payload, error, content, deletionPubkey, useBulkPacing = false }) {
|
|
2653
|
+
async ask ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkey, relays, relayToReceivers, message, code, payload, error, content, idempotencyKey, deletionPubkey, useBulkPacing = false }) {
|
|
2654
|
+
idempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
|
|
2538
2655
|
const channel = this.requireWritableChannel(channelPubkey)
|
|
2539
2656
|
const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
|
|
2540
2657
|
try {
|
|
@@ -2556,6 +2673,7 @@ export class PrivateMessenger {
|
|
|
2556
2673
|
payload,
|
|
2557
2674
|
error,
|
|
2558
2675
|
content,
|
|
2676
|
+
idempotencyKey,
|
|
2559
2677
|
useBulkPacing,
|
|
2560
2678
|
onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
|
|
2561
2679
|
_getIykcProofs: this.contentKeyLookup()
|
|
@@ -2563,7 +2681,8 @@ export class PrivateMessenger {
|
|
|
2563
2681
|
} finally { releaseActivity() }
|
|
2564
2682
|
}
|
|
2565
2683
|
|
|
2566
|
-
async reply ({ channelPubkey = this.defaultChannelPubkey(), question, receiverPubkey, relays, relayToReceivers, message, code, payload, error, content, deletionPubkey, useBulkPacing = false }) {
|
|
2684
|
+
async reply ({ channelPubkey = this.defaultChannelPubkey(), question, receiverPubkey, relays, relayToReceivers, message, code, payload, error, content, idempotencyKey, deletionPubkey, useBulkPacing = false }) {
|
|
2685
|
+
idempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
|
|
2567
2686
|
const channel = this.requireWritableChannel(channelPubkey)
|
|
2568
2687
|
const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
|
|
2569
2688
|
try {
|
|
@@ -2587,6 +2706,7 @@ export class PrivateMessenger {
|
|
|
2587
2706
|
payload,
|
|
2588
2707
|
error,
|
|
2589
2708
|
content,
|
|
2709
|
+
idempotencyKey,
|
|
2590
2710
|
useBulkPacing,
|
|
2591
2711
|
onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
|
|
2592
2712
|
_getIykcProofs: this.contentKeyLookup()
|
|
@@ -2594,7 +2714,8 @@ export class PrivateMessenger {
|
|
|
2594
2714
|
} finally { releaseActivity() }
|
|
2595
2715
|
}
|
|
2596
2716
|
|
|
2597
|
-
async tell ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkey, relays, relayToReceivers, message, code, payload, error, content, deletionPubkey, useBulkPacing = false }) {
|
|
2717
|
+
async tell ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkey, relays, relayToReceivers, message, code, payload, error, content, idempotencyKey, deletionPubkey, useBulkPacing = false }) {
|
|
2718
|
+
idempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
|
|
2598
2719
|
const channel = this.requireWritableChannel(channelPubkey)
|
|
2599
2720
|
const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
|
|
2600
2721
|
try {
|
|
@@ -2616,6 +2737,7 @@ export class PrivateMessenger {
|
|
|
2616
2737
|
payload,
|
|
2617
2738
|
error,
|
|
2618
2739
|
content,
|
|
2740
|
+
idempotencyKey,
|
|
2619
2741
|
useBulkPacing,
|
|
2620
2742
|
onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
|
|
2621
2743
|
_getIykcProofs: this.contentKeyLookup()
|
|
@@ -2623,7 +2745,8 @@ export class PrivateMessenger {
|
|
|
2623
2745
|
} finally { releaseActivity() }
|
|
2624
2746
|
}
|
|
2625
2747
|
|
|
2626
|
-
async yell ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, message, code, payload, error, content, deletionPubkey, createdAt, onPreparedSeed, preparedPublication, preparedPublications, useBulkPacing = false }) {
|
|
2748
|
+
async yell ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, message, code, payload, error, content, idempotencyKey, deletionPubkey, createdAt, onPreparedSeed, preparedPublication, preparedPublications, useBulkPacing = false }) {
|
|
2749
|
+
idempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
|
|
2627
2750
|
const channel = this.requireWritableChannel(channelPubkey)
|
|
2628
2751
|
const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
|
|
2629
2752
|
try {
|
|
@@ -2649,6 +2772,7 @@ export class PrivateMessenger {
|
|
|
2649
2772
|
payload,
|
|
2650
2773
|
error,
|
|
2651
2774
|
content,
|
|
2775
|
+
idempotencyKey,
|
|
2652
2776
|
createdAt,
|
|
2653
2777
|
useBulkPacing,
|
|
2654
2778
|
onPreparedSeed: onPreparedSeed || this.outgoingSeedHandler(channelPubkey),
|
|
@@ -3813,6 +3937,38 @@ function messageCode (message) {
|
|
|
3813
3937
|
: null
|
|
3814
3938
|
}
|
|
3815
3939
|
|
|
3940
|
+
function coalescingOrder (message) {
|
|
3941
|
+
return {
|
|
3942
|
+
outer: Number.isSafeInteger(message?.outer?.created_at) ? message.outer.created_at : 0,
|
|
3943
|
+
inner: Number.isSafeInteger(message?.event?.created_at) ? message.event.created_at : 0,
|
|
3944
|
+
eventId: message?.event?.id || ''
|
|
3945
|
+
}
|
|
3946
|
+
}
|
|
3947
|
+
|
|
3948
|
+
function compareCoalescingOrder (left, right) {
|
|
3949
|
+
if ((left?.outer || 0) !== (right?.outer || 0)) return (left?.outer || 0) - (right?.outer || 0)
|
|
3950
|
+
if ((left?.inner || 0) !== (right?.inner || 0)) return (left?.inner || 0) - (right?.inner || 0)
|
|
3951
|
+
const leftId = left?.eventId || ''
|
|
3952
|
+
const rightId = right?.eventId || ''
|
|
3953
|
+
if (leftId === rightId) return 0
|
|
3954
|
+
return leftId < rightId ? -1 : 1
|
|
3955
|
+
}
|
|
3956
|
+
|
|
3957
|
+
function compareCoalescingItems (left, right) {
|
|
3958
|
+
return compareCoalescingOrder(left?.coalescingOrder, right?.coalescingOrder)
|
|
3959
|
+
}
|
|
3960
|
+
|
|
3961
|
+
function idempotencyDigest (idempotencyKey) {
|
|
3962
|
+
return bytesToHex(sha256(encoder.encode(JSON.stringify(['idempotency', idempotencyKey]))))
|
|
3963
|
+
}
|
|
3964
|
+
|
|
3965
|
+
function coalescingError (cause) {
|
|
3966
|
+
return Object.assign(new Error('INVALID_INBOUND_COALESCING_KEY'), {
|
|
3967
|
+
code: 'INVALID_INBOUND_COALESCING_KEY',
|
|
3968
|
+
cause
|
|
3969
|
+
})
|
|
3970
|
+
}
|
|
3971
|
+
|
|
3816
3972
|
function safeDiagnosticToken (value) {
|
|
3817
3973
|
return typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9:._-]{0,159}$/.test(value)
|
|
3818
3974
|
? value
|
|
@@ -3902,6 +4058,9 @@ function nymCarrierSeedKey (record) {
|
|
|
3902
4058
|
function withoutQueueMetadata (item) {
|
|
3903
4059
|
if (!item) return null
|
|
3904
4060
|
const value = { ...item }
|
|
4061
|
+
delete value.coalescingKey
|
|
4062
|
+
delete value.coalescingKeep
|
|
4063
|
+
delete value.coalescingOrder
|
|
3905
4064
|
delete value[SEED_KEY]
|
|
3906
4065
|
delete value[SEED_TIME]
|
|
3907
4066
|
return value
|
|
@@ -2,6 +2,7 @@ import { getEventHash } from '../../event/index.js'
|
|
|
2
2
|
import { bytesToBase64, base64ToBytes } from '../../base64/index.js'
|
|
3
3
|
import { ValidationError } from '../../error/index.js'
|
|
4
4
|
import { ASK_KIND, parseRumorContent } from '../../private-message/index.js'
|
|
5
|
+
import { chunkIdempotencyKey, normalizeIdempotencyKeyBase } from '../../private-message/helpers/idempotency.js'
|
|
5
6
|
|
|
6
7
|
export const SEEDER_PRESENCE_CODE = 'seederPresence_8mj8'
|
|
7
8
|
export const MISSING_MESSAGES_ASK_CODE = 'missingMessages_ask_8mj8'
|
|
@@ -228,13 +229,15 @@ export function createEventReplyPacker ({
|
|
|
228
229
|
bytesPerChunk = DEFAULT_REPLY_BYTES_PER_CHUNK,
|
|
229
230
|
recordsFromInput = eventRecordFromInput,
|
|
230
231
|
sendEmptyReply = false,
|
|
231
|
-
useBulkPacing = true
|
|
232
|
+
useBulkPacing = true,
|
|
233
|
+
idempotencyKey
|
|
232
234
|
}) {
|
|
233
235
|
if (!messenger?.reply) throw new ValidationError('MESSENGER_REQUIRED')
|
|
234
236
|
if (!question?.id) throw new ValidationError('QUESTION_REQUIRED')
|
|
235
237
|
if (!receiverPubkey) throw new ValidationError('RECEIVER_PUBKEY_REQUIRED')
|
|
236
238
|
if (!Number.isSafeInteger(eventsPerChunk) || eventsPerChunk < 1) throw new ValidationError('INVALID_EVENTS_PER_CHUNK')
|
|
237
239
|
if (!Number.isSafeInteger(bytesPerChunk) || bytesPerChunk < 1) throw new ValidationError('INVALID_BYTES_PER_CHUNK')
|
|
240
|
+
const idempotencyKeyBase = normalizeIdempotencyKeyBase(idempotencyKey)
|
|
238
241
|
|
|
239
242
|
let chunk = ''
|
|
240
243
|
let chunkEvents = 0
|
|
@@ -250,6 +253,9 @@ export function createEventReplyPacker ({
|
|
|
250
253
|
question,
|
|
251
254
|
receiverPubkey,
|
|
252
255
|
code,
|
|
256
|
+
...(idempotencyKeyBase
|
|
257
|
+
? { idempotencyKey: chunkIdempotencyKey(idempotencyKeyBase, index) }
|
|
258
|
+
: {}),
|
|
253
259
|
useBulkPacing,
|
|
254
260
|
payload: {
|
|
255
261
|
...payload,
|
|
@@ -311,13 +317,15 @@ export function createMissingMessageReplyPacker ({
|
|
|
311
317
|
eventsPerChunk = DEFAULT_EVENTS_PER_CHUNK,
|
|
312
318
|
bytesPerChunk = DEFAULT_REPLY_BYTES_PER_CHUNK,
|
|
313
319
|
sendEmptyReply = false,
|
|
314
|
-
useBulkPacing = true
|
|
320
|
+
useBulkPacing = true,
|
|
321
|
+
idempotencyKey
|
|
315
322
|
}) {
|
|
316
323
|
if (!messenger?.reply) throw new ValidationError('MESSENGER_REQUIRED')
|
|
317
324
|
if (!question?.id) throw new ValidationError('QUESTION_REQUIRED')
|
|
318
325
|
if (!receiverPubkey) throw new ValidationError('RECEIVER_PUBKEY_REQUIRED')
|
|
319
326
|
if (!Number.isSafeInteger(eventsPerChunk) || eventsPerChunk < 1) throw new ValidationError('INVALID_EVENTS_PER_CHUNK')
|
|
320
327
|
if (!Number.isSafeInteger(bytesPerChunk) || bytesPerChunk < 1) throw new ValidationError('INVALID_BYTES_PER_CHUNK')
|
|
328
|
+
idempotencyKey ||= `${MISSING_MESSAGES_REPLY_CODE}:${question.id}`
|
|
321
329
|
|
|
322
330
|
const range = backfillRequestRange(question, since, until)
|
|
323
331
|
return createEventReplyPacker({
|
|
@@ -331,6 +339,7 @@ export function createMissingMessageReplyPacker ({
|
|
|
331
339
|
bytesPerChunk,
|
|
332
340
|
sendEmptyReply,
|
|
333
341
|
useBulkPacing,
|
|
342
|
+
idempotencyKey,
|
|
334
343
|
recordsFromInput: seed => compactRecordsFromSeed(seed, { receiverPubkey, since: range.since, until: range.until })
|
|
335
344
|
})
|
|
336
345
|
}
|
|
@@ -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,
|
|
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 =
|
|
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') {
|