libp2r2p 0.12.19 → 0.12.20
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/idb-queue/index.js
CHANGED
|
@@ -949,7 +949,10 @@ export async function createQueue ({
|
|
|
949
949
|
let completedAction
|
|
950
950
|
let completedResult
|
|
951
951
|
let tail = Promise.resolve()
|
|
952
|
-
const update = (action, at = Date.now()) => {
|
|
952
|
+
const update = (action, at = Date.now(), { retryAfterMs = 0 } = {}) => {
|
|
953
|
+
if (!Number.isSafeInteger(retryAfterMs) || retryAfterMs < 0 || retryAfterMs > 2147483647) {
|
|
954
|
+
return Promise.reject(new ValidationError('QUEUE_INVALID_RETRY_AFTER'))
|
|
955
|
+
}
|
|
953
956
|
const operation = tail.then(async () => {
|
|
954
957
|
if (settled) return action === completedAction ? completedResult : false
|
|
955
958
|
const result = await mutate(async (tx, state) => {
|
|
@@ -982,7 +985,8 @@ export async function createQueue ({
|
|
|
982
985
|
state.usedBytes = Math.max(0, state.usedBytes - record.byteSize)
|
|
983
986
|
await trimBounds(tx, state)
|
|
984
987
|
} else {
|
|
985
|
-
|
|
988
|
+
if (retryAfterMs > 0) record.reservation = { token, until: at + retryAfterMs }
|
|
989
|
+
else delete record.reservation
|
|
986
990
|
await putRecord(tx, record)
|
|
987
991
|
}
|
|
988
992
|
}
|
|
@@ -999,7 +1003,12 @@ export async function createQueue ({
|
|
|
999
1003
|
tail = operation.catch(() => {})
|
|
1000
1004
|
return operation
|
|
1001
1005
|
}
|
|
1002
|
-
return {
|
|
1006
|
+
return {
|
|
1007
|
+
item: reserved.item,
|
|
1008
|
+
ack: () => update('ack'),
|
|
1009
|
+
nack: options => update('nack', Date.now(), options),
|
|
1010
|
+
renew: () => update('renew')
|
|
1011
|
+
}
|
|
1003
1012
|
}
|
|
1004
1013
|
|
|
1005
1014
|
async function snapshotStoredItems () {
|
package/package.json
CHANGED
|
@@ -82,9 +82,9 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
|
|
|
82
82
|
catalog.ready.catch(onError)
|
|
83
83
|
const keyFor = (control, root) => `${control}:${root}`
|
|
84
84
|
const emit = job => { for (const listener of listeners) listener({ root: job.file.root, controlChannelPubkey: job.file.controlChannelPubkey, status: job.status, completed: job.completed, total: job.file.size, error: job.error }) }
|
|
85
|
-
const usable = file => {
|
|
85
|
+
const usable = (file, { capacityEgress } = {}) => {
|
|
86
86
|
if (closed) throw new Error('FILE_TRANSFER_CLOSED')
|
|
87
|
-
messenger.requireWritableChannel(file.controlChannelPubkey)
|
|
87
|
+
messenger.requireWritableChannel(file.controlChannelPubkey, { capacityEgress })
|
|
88
88
|
if (!messenger.desiredChannels.has(file.controlChannelPubkey)) throw new Error('FILE_TRANSFER_CHANNEL_UNWATCHED')
|
|
89
89
|
}
|
|
90
90
|
async function register ({ controlChannelPubkey, peerPubkey, root, size, sharedAt }) {
|
|
@@ -145,9 +145,9 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
|
|
|
145
145
|
if (decoded.root !== file.root || (index !== undefined && decoded.index !== index) || (file.size !== undefined && (decoded.total !== Math.ceil(file.size / IRFS_CHUNK_BYTES) || (decoded.index === decoded.total - 1 && decoded.contentBytes.length !== file.size - decoded.index * IRFS_CHUNK_BYTES)))) throw new ValidationError('FILE_CHUNK_DESCRIPTOR_MISMATCH')
|
|
146
146
|
return decoded
|
|
147
147
|
}
|
|
148
|
-
async function routing (file, receiverPubkey, signal, attemptStartedAt, onDebug) {
|
|
149
|
-
const parent = messenger.requireWritableChannel(file.controlChannelPubkey)
|
|
150
|
-
return messenger.resolveSendRouting({ channel: parent, receiverPubkeys: [receiverPubkey], signal, attemptStartedAt, onDebug })
|
|
148
|
+
async function routing (file, receiverPubkey, signal, attemptStartedAt, onDebug, { capacityEgress } = {}) {
|
|
149
|
+
const parent = messenger.requireWritableChannel(file.controlChannelPubkey, { capacityEgress })
|
|
150
|
+
return messenger.resolveSendRouting({ channel: parent, receiverPubkeys: [receiverPubkey], signal, attemptStartedAt, onDebug, capacityEgress })
|
|
151
151
|
}
|
|
152
152
|
function sendOptions (file, routes) {
|
|
153
153
|
return { senderSigner: messenger.userSigner, imkcSigner: messenger.contentKeySigner, privateChannelSigner: file.signer, ...routes, temporaryStorageArea: messenger.temporaryStorageArea, expirationSeconds: messenger.eventExpirationSecondsFor(file.controlChannelPubkey), useBulkPacing: true, _getIykcProofs: messenger.contentKeyLookup() }
|
|
@@ -173,7 +173,7 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
|
|
|
173
173
|
await new Promise(resolve => setTimeout(resolve, 0))
|
|
174
174
|
return result
|
|
175
175
|
}
|
|
176
|
-
async function replyToRequest (controlChannelPubkey, message) {
|
|
176
|
+
async function replyToRequest (controlChannelPubkey, message, { capacityEgress } = {}) {
|
|
177
177
|
if (message.payload?.code !== FILE_CHUNKS_REQUEST_CODE) return false
|
|
178
178
|
const question = message.question || message.event
|
|
179
179
|
if (message.provenance === 'hearsay' || message.senderPubkey !== question?.pubkey || question.tags?.find(tag => tag[0] === 'r')?.[1] !== messenger.userPubkey) return true
|
|
@@ -184,13 +184,13 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
|
|
|
184
184
|
const grant = await catalog.find(controlChannelPubkey, payload.fileChannelPubkey, question.pubkey)
|
|
185
185
|
if (grant) {
|
|
186
186
|
const file = await register(grant)
|
|
187
|
-
usable(file)
|
|
187
|
+
usable(file, { capacityEgress: capacityEgress?.token })
|
|
188
188
|
if (file.fileChannelPubkey !== payload.fileChannelPubkey) throw new ValidationError('FILE_CHANNEL_MISMATCH')
|
|
189
|
-
const routes = await routing(file, question.pubkey)
|
|
189
|
+
const routes = await routing(file, question.pubkey, undefined, undefined, undefined, { capacityEgress: capacityEgress?.token })
|
|
190
190
|
const packer = createEventReplyPacker({
|
|
191
191
|
messenger: {
|
|
192
192
|
reply: async options => {
|
|
193
|
-
usable(file)
|
|
193
|
+
usable(file, { capacityEgress: capacityEgress?.token })
|
|
194
194
|
if (!await catalog.find(controlChannelPubkey, file.fileChannelPubkey, question.pubkey)) return
|
|
195
195
|
return _messages.reply({ ...sendOptions(file, routes), ...options })
|
|
196
196
|
}
|
|
@@ -202,7 +202,7 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
|
|
|
202
202
|
recordsFromInput: record => [record]
|
|
203
203
|
})
|
|
204
204
|
for (const index of indices) {
|
|
205
|
-
usable(file)
|
|
205
|
+
usable(file, { capacityEgress: capacityEgress?.token })
|
|
206
206
|
if (!await catalog.find(controlChannelPubkey, file.fileChannelPubkey, question.pubkey)) break
|
|
207
207
|
const event = await storage.read(file.root, index, file)
|
|
208
208
|
if (!event) continue
|
|
@@ -223,14 +223,14 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
|
|
|
223
223
|
if (seed.expiresAt <= _now() || seed.receivedAt + messenger.offlineRecoverySecondsFor(controlChannelPubkey) <= _now() || (seedStorage && !await seedStorage.has(seed))) continue
|
|
224
224
|
if (seed.controlChannelPubkey !== controlChannelPubkey || seed.receiverPubkey !== question.pubkey || !indices.has(seed.chunkIndex) || !seedEnabled(seed)) continue
|
|
225
225
|
const file = await register(seed)
|
|
226
|
-
usable(file)
|
|
226
|
+
usable(file, { capacityEgress: capacityEgress?.token })
|
|
227
227
|
if (file.fileChannelPubkey !== payload.fileChannelPubkey) throw new ValidationError('FILE_CHANNEL_MISMATCH')
|
|
228
228
|
if (!packer) {
|
|
229
|
-
const routes = await routing(file, question.pubkey)
|
|
229
|
+
const routes = await routing(file, question.pubkey, undefined, undefined, undefined, { capacityEgress: capacityEgress?.token })
|
|
230
230
|
packer = createEventReplyPacker({
|
|
231
231
|
messenger: {
|
|
232
232
|
reply: async options => {
|
|
233
|
-
usable(file)
|
|
233
|
+
usable(file, { capacityEgress: capacityEgress?.token })
|
|
234
234
|
return _messages.reply({ ...sendOptions(file, routes), ...options })
|
|
235
235
|
}
|
|
236
236
|
},
|
|
@@ -457,21 +457,36 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
|
|
|
457
457
|
function drainRequests () {
|
|
458
458
|
if (closed) return
|
|
459
459
|
while (replying < 2 && requests.length) {
|
|
460
|
-
const [channel, message] = requests.shift()
|
|
460
|
+
const [channel, message, capacityEgress] = requests.shift()
|
|
461
461
|
replying++
|
|
462
|
-
const task = replyToRequest(channel, message
|
|
462
|
+
const task = replyToRequest(channel, message, { capacityEgress })
|
|
463
|
+
.catch(error => { if (!(closed && error.message === 'FILE_TRANSFER_CLOSED')) onError(error) })
|
|
464
|
+
.finally(() => { capacityEgress?.release(); replying--; work.delete(task); drainRequests() })
|
|
463
465
|
work.add(task)
|
|
464
466
|
}
|
|
465
467
|
}
|
|
466
468
|
const extension = {
|
|
467
|
-
handleAsk (channel, message) {
|
|
469
|
+
handleAsk (channel, message, { capacityEgress } = {}) {
|
|
468
470
|
if (message.payload?.code !== FILE_CHUNKS_REQUEST_CODE) return false
|
|
469
471
|
// Never hold the DM dispatcher while publishing a batch of file bytes.
|
|
470
472
|
// Bound both workers and queued requests; discarded excess is retryable.
|
|
471
|
-
if (!closed && requests.length < 16) {
|
|
473
|
+
if (!closed && requests.length < 16) {
|
|
474
|
+
requests.push([channel, message, capacityEgress])
|
|
475
|
+
drainRequests()
|
|
476
|
+
} else {
|
|
477
|
+
capacityEgress?.release()
|
|
478
|
+
}
|
|
472
479
|
return true
|
|
473
480
|
},
|
|
474
|
-
pause () {
|
|
481
|
+
pause () {
|
|
482
|
+
for (const [, , capacityEgress] of requests) capacityEgress?.release()
|
|
483
|
+
requests.length = 0
|
|
484
|
+
for (const job of jobs.values()) {
|
|
485
|
+
if (['complete', 'error', 'cancelled'].includes(job.status)) continue
|
|
486
|
+
job.pauseRequested = true
|
|
487
|
+
cancelJob(job)
|
|
488
|
+
}
|
|
489
|
+
},
|
|
475
490
|
async resume () {
|
|
476
491
|
await Promise.allSettled([...work])
|
|
477
492
|
for (const job of jobs.values()) if (job.pauseRequested && job.status !== 'complete') download(job.file, { manual: job.manual, thumbnail: job.thumbnail }).catch(onError)
|
|
@@ -134,6 +134,7 @@ const COALESCING_INDEX = 'byCoalescingKey'
|
|
|
134
134
|
const DELIVERY_PRIORITY_INDEX = 'byDeliveryPriority'
|
|
135
135
|
const COALESCING_DIGEST = /^[0-9a-f]{64}$/
|
|
136
136
|
const COALESCING_KEEP = new Set(['oldest', 'latest'])
|
|
137
|
+
const CAPACITY_EGRESS = Symbol('capacityEgress')
|
|
137
138
|
const DEDUPE_TYPES = new Set(['ask', 'reply', 'tell', 'yell'])
|
|
138
139
|
const DELIVERY_PRIORITY = Object.freeze({
|
|
139
140
|
lowest: 0,
|
|
@@ -172,7 +173,25 @@ function isQueueCapacityError (error) {
|
|
|
172
173
|
}
|
|
173
174
|
|
|
174
175
|
function isPausedError (error) {
|
|
175
|
-
return error?.code === 'PRIVATE_MESSENGER_PAUSED' ||
|
|
176
|
+
return error?.code === 'PRIVATE_MESSENGER_PAUSED' ||
|
|
177
|
+
error?.code === 'PRIVATE_MESSENGER_CAPACITY_PAUSED' ||
|
|
178
|
+
error?.message === 'PRIVATE_MESSENGER_PAUSED' ||
|
|
179
|
+
error?.message === 'PRIVATE_MESSENGER_CAPACITY_PAUSED'
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function capacityPausedError () {
|
|
183
|
+
return Object.assign(new Error('PRIVATE_MESSENGER_CAPACITY_PAUSED'), {
|
|
184
|
+
code: 'PRIVATE_MESSENGER_CAPACITY_PAUSED',
|
|
185
|
+
pauseReasons: ['capacity'],
|
|
186
|
+
retryWhenAvailable: true
|
|
187
|
+
})
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function expiredCapacityEgress () {
|
|
191
|
+
return Object.assign(new Error('INBOX_DELIVERY_EXPIRED'), {
|
|
192
|
+
code: 'INBOX_DELIVERY_EXPIRED',
|
|
193
|
+
retryWhenAvailable: true
|
|
194
|
+
})
|
|
176
195
|
}
|
|
177
196
|
|
|
178
197
|
function isCapacityPressureError (error) {
|
|
@@ -1052,7 +1071,11 @@ export class PrivateMessenger {
|
|
|
1052
1071
|
return uniq([...primary, ...this.fallbackRelays].map(normalizeRelayUrl))
|
|
1053
1072
|
}
|
|
1054
1073
|
|
|
1055
|
-
async resolveSendRouting ({ channel, receiverPubkeys, relays, relayToReceivers, signal, attemptStartedAt, onDebug }) {
|
|
1074
|
+
async resolveSendRouting ({ channel, receiverPubkeys, relays, relayToReceivers, signal, attemptStartedAt, onDebug, capacityEgress }) {
|
|
1075
|
+
this.capacityEgressFor({ capacityEgress })
|
|
1076
|
+
const allowCapacity = Boolean(capacityEgress)
|
|
1077
|
+
if (this.sendingPaused()) throw this.pausedError()
|
|
1078
|
+
if (this.pauseReasons.has('capacity') && !allowCapacity) throw capacityPausedError()
|
|
1056
1079
|
if (attemptStartedAt !== undefined && (!Number.isFinite(attemptStartedAt) || attemptStartedAt < 0)) throw new ValidationError('INVALID_ATTEMPT_STARTED_AT')
|
|
1057
1080
|
const recoveryRelays = await this.recoveryMirrorRelays(channel.pubkey)
|
|
1058
1081
|
const fixed = relayToReceivers ? null : relays?.length ? uniq(relays) : channel.sendRelays.length ? channel.sendRelays : channel.relays.length ? channel.relays : null
|
|
@@ -1060,7 +1083,11 @@ export class PrivateMessenger {
|
|
|
1060
1083
|
const relaysByPubkey = fixed || relayToReceivers ? undefined : await this._getRelaysByPubkey(recipients)
|
|
1061
1084
|
const routing = createSendRelayRouting({
|
|
1062
1085
|
peers: fixed && !recipients.length ? [this.userPubkey] : recipients, relaysByPubkey, recoveryRelays, primaryRelays: fixed?.map(normalizeRelayUrl), primaryRelayToReceivers: relayToReceivers, fallbackRelays: this.fallbackRelays,
|
|
1063
|
-
signal:
|
|
1086
|
+
signal: capacityEgress
|
|
1087
|
+
? AbortSignal.any([this.sendRoutingLifetime.signal, capacityEgress.controller.signal, ...(signal ? [signal] : [])])
|
|
1088
|
+
: signal
|
|
1089
|
+
? AbortSignal.any([this.sendRoutingLifetime.signal, signal])
|
|
1090
|
+
: this.sendRoutingLifetime.signal,
|
|
1064
1091
|
exclusions: new Map(),
|
|
1065
1092
|
relayHealth: this.publicationRelayHealth,
|
|
1066
1093
|
fallbackDelayMs: this.fallbackDelayMs, attemptStartedAt, pauseSignal: this.sendRoutingPause.signal,
|
|
@@ -1075,7 +1102,9 @@ export class PrivateMessenger {
|
|
|
1075
1102
|
return result
|
|
1076
1103
|
},
|
|
1077
1104
|
isOnline: this._isOnline,
|
|
1078
|
-
isCurrent: () => !this.closePromise && !this.
|
|
1105
|
+
isCurrent: () => !this.closePromise && !this.sendingPaused() &&
|
|
1106
|
+
this.channels.has(channel.pubkey) &&
|
|
1107
|
+
(!capacityEgress || (capacityEgress.active && !capacityEgress.controller.signal.aborted))
|
|
1079
1108
|
})
|
|
1080
1109
|
if (routing.circuitOpen) throw relayCircuitError(routing.retryAt)
|
|
1081
1110
|
if (!relayMapRelays(routing.relayToReceivers).length) throw new ValidationError('NO_RELAYS')
|
|
@@ -2069,12 +2098,14 @@ export class PrivateMessenger {
|
|
|
2069
2098
|
if (typeof reason !== 'string' || !reason.trim()) throw new ValidationError('PAUSE_REASON_REQUIRED')
|
|
2070
2099
|
this.assertOpen()
|
|
2071
2100
|
this.pauseReasons.add(reason)
|
|
2072
|
-
this.decryptionRetry?.controller.abort(this.pausedError())
|
|
2073
2101
|
this.pauseRevisions.set(reason, (this.pauseRevisions.get(reason) || 0) + 1)
|
|
2074
|
-
this.sendRoutingPause.abort(this.pausedError())
|
|
2075
2102
|
const pausedError = this.pausedError()
|
|
2076
2103
|
this.notifyStatus()
|
|
2077
|
-
|
|
2104
|
+
if (reason !== 'capacity') {
|
|
2105
|
+
this.decryptionRetry?.controller.abort(pausedError)
|
|
2106
|
+
this.sendRoutingPause.abort(pausedError)
|
|
2107
|
+
for (const extension of this.extensions) extension.pause?.()
|
|
2108
|
+
}
|
|
2078
2109
|
this.recordInterruption(this.desiredChannels)
|
|
2079
2110
|
for (const controller of this.recoveryControllers) controller.abort(pausedError)
|
|
2080
2111
|
return Promise.all([this.stopWatches([...this.desiredChannels], { reason: pausedError }), this.flushStateWrites()])
|
|
@@ -2110,7 +2141,7 @@ export class PrivateMessenger {
|
|
|
2110
2141
|
if (this.pauseReasons.size || this.closePromise) return
|
|
2111
2142
|
const jobs = removed ? this.startChannelBackground(channels, { recover: true }) : [...this.channelBackground.values()].map(job => job.work)
|
|
2112
2143
|
if (removed) this.retryPendingDecryptions().catch(error => this.onError?.(error))
|
|
2113
|
-
if (removed) {
|
|
2144
|
+
if (removed && reason !== 'capacity') {
|
|
2114
2145
|
for (const extension of this.extensions) {
|
|
2115
2146
|
const work = Promise.resolve().then(() => { if (!this.pauseReasons.size && !this.closePromise) return extension.resume?.() })
|
|
2116
2147
|
work.catch(error => this.onError?.(error))
|
|
@@ -2292,9 +2323,24 @@ export class PrivateMessenger {
|
|
|
2292
2323
|
async handleAsk (channelPubkey, message) {
|
|
2293
2324
|
if (message.provenance === 'hearsay') return this.enqueueRumor('message', channelPubkey, message)
|
|
2294
2325
|
this.trackSeederActivity(channelPubkey, message)
|
|
2295
|
-
for (const extension of this.extensions)
|
|
2326
|
+
for (const extension of this.extensions) {
|
|
2327
|
+
if (!extension.handleAsk) continue
|
|
2328
|
+
const capacityEgress = this.createCapacityEgress()
|
|
2329
|
+
try {
|
|
2330
|
+
if (await extension.handleAsk(channelPubkey, message, { capacityEgress })) return
|
|
2331
|
+
capacityEgress.release()
|
|
2332
|
+
} catch (error) {
|
|
2333
|
+
capacityEgress.release(error)
|
|
2334
|
+
throw error
|
|
2335
|
+
}
|
|
2336
|
+
}
|
|
2296
2337
|
if (doesModeStoreRecoverySeeds(this.channels.get(channelPubkey)?.mode) && messageCode(message) === MISSING_MESSAGES_ASK_CODE) {
|
|
2297
|
-
|
|
2338
|
+
const capacityEgress = this.createCapacityEgress()
|
|
2339
|
+
try {
|
|
2340
|
+
await this.replyWithStoredSeeds(channelPubkey, message, { messenger: capacityEgress.messenger })
|
|
2341
|
+
} finally {
|
|
2342
|
+
capacityEgress.release()
|
|
2343
|
+
}
|
|
2298
2344
|
return
|
|
2299
2345
|
}
|
|
2300
2346
|
await this.enqueueRumor('ask', channelPubkey, message)
|
|
@@ -2821,16 +2867,18 @@ export class PrivateMessenger {
|
|
|
2821
2867
|
})
|
|
2822
2868
|
if (!reservation) return null
|
|
2823
2869
|
if (this.closePromise) { await reservation.nack(); return null }
|
|
2870
|
+
const capacityEgress = this.createCapacityEgress()
|
|
2824
2871
|
let finish
|
|
2825
2872
|
const settled = new Promise(resolve => { finish = resolve })
|
|
2826
2873
|
const done = () => {
|
|
2827
2874
|
clearInterval(timer)
|
|
2875
|
+
capacityEgress.release()
|
|
2828
2876
|
this.deliveries.delete(delivery)
|
|
2829
2877
|
finish()
|
|
2830
2878
|
this.wakeDeliveries()
|
|
2831
2879
|
}
|
|
2832
|
-
const settle = async method => {
|
|
2833
|
-
const result = await reservation[method]()
|
|
2880
|
+
const settle = async (method, options) => {
|
|
2881
|
+
const result = await reservation[method](options)
|
|
2834
2882
|
done()
|
|
2835
2883
|
if (method === 'ack' && result && !this.closePromise && this.pauseReasons.has('capacity')) {
|
|
2836
2884
|
this.checkCapacity().catch(err => this.onError?.(err))
|
|
@@ -2840,7 +2888,8 @@ export class PrivateMessenger {
|
|
|
2840
2888
|
const delivery = {
|
|
2841
2889
|
message: withoutQueueMetadata(reservation.item),
|
|
2842
2890
|
ack: () => settle('ack'),
|
|
2843
|
-
nack:
|
|
2891
|
+
nack: options => settle('nack', options),
|
|
2892
|
+
capacityEgress: capacityEgress.messenger
|
|
2844
2893
|
}
|
|
2845
2894
|
Object.defineProperty(delivery, 'settled', { value: settled })
|
|
2846
2895
|
this.deliveries.add(delivery)
|
|
@@ -2851,12 +2900,17 @@ export class PrivateMessenger {
|
|
|
2851
2900
|
return delivery
|
|
2852
2901
|
}
|
|
2853
2902
|
|
|
2854
|
-
async ask (
|
|
2855
|
-
|
|
2856
|
-
|
|
2903
|
+
async ask (options = {}) {
|
|
2904
|
+
const {
|
|
2905
|
+
channelPubkey = this.defaultChannelPubkey(), receiverPubkey, relays, relayToReceivers,
|
|
2906
|
+
message, code, payload, error, content, idempotencyKey, deletionPubkey, useBulkPacing = false
|
|
2907
|
+
} = options
|
|
2908
|
+
const capacityEgress = this.capacityEgressFor(options)
|
|
2909
|
+
const normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
|
|
2910
|
+
const channel = this.requireWritableChannel(channelPubkey, { capacityEgress })
|
|
2857
2911
|
const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
|
|
2858
2912
|
try {
|
|
2859
|
-
const routing = await this.resolveSendRouting({ channel, receiverPubkeys: [receiverPubkey], relays, relayToReceivers })
|
|
2913
|
+
const routing = await this.resolveSendRouting({ channel, receiverPubkeys: [receiverPubkey], relays, relayToReceivers, capacityEgress })
|
|
2860
2914
|
this.debugSend('ask', channelPubkey, { code, receiverPubkey })
|
|
2861
2915
|
return await this._privateMessage.ask({
|
|
2862
2916
|
senderSigner: this.userSigner,
|
|
@@ -2874,7 +2928,7 @@ export class PrivateMessenger {
|
|
|
2874
2928
|
payload,
|
|
2875
2929
|
error,
|
|
2876
2930
|
content,
|
|
2877
|
-
idempotencyKey,
|
|
2931
|
+
idempotencyKey: normalizedIdempotencyKey,
|
|
2878
2932
|
useBulkPacing,
|
|
2879
2933
|
onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
|
|
2880
2934
|
_getIykcProofs: this.contentKeyLookup()
|
|
@@ -2882,9 +2936,14 @@ export class PrivateMessenger {
|
|
|
2882
2936
|
} finally { releaseActivity() }
|
|
2883
2937
|
}
|
|
2884
2938
|
|
|
2885
|
-
async reply (
|
|
2886
|
-
|
|
2887
|
-
|
|
2939
|
+
async reply (options = {}) {
|
|
2940
|
+
const {
|
|
2941
|
+
channelPubkey = this.defaultChannelPubkey(), question, receiverPubkey, relays, relayToReceivers,
|
|
2942
|
+
message, code, payload, error, content, idempotencyKey, deletionPubkey, expiresAt, useBulkPacing = false
|
|
2943
|
+
} = options
|
|
2944
|
+
const capacityEgress = this.capacityEgressFor(options)
|
|
2945
|
+
const normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
|
|
2946
|
+
const channel = this.requireWritableChannel(channelPubkey, { capacityEgress })
|
|
2888
2947
|
const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
|
|
2889
2948
|
try {
|
|
2890
2949
|
const expirationSeconds = replyExpirationSeconds(
|
|
@@ -2893,7 +2952,7 @@ export class PrivateMessenger {
|
|
|
2893
2952
|
this._now()
|
|
2894
2953
|
)
|
|
2895
2954
|
const resolvedReceiverPubkey = receiverPubkey || question?.pubkey || ''
|
|
2896
|
-
const routing = await this.resolveSendRouting({ channel, receiverPubkeys: [resolvedReceiverPubkey], relays, relayToReceivers })
|
|
2955
|
+
const routing = await this.resolveSendRouting({ channel, receiverPubkeys: [resolvedReceiverPubkey], relays, relayToReceivers, capacityEgress })
|
|
2897
2956
|
this.debugSend('reply', channelPubkey, { code, receiverPubkey: receiverPubkey || question?.pubkey || '' })
|
|
2898
2957
|
return await this._privateMessage.reply({
|
|
2899
2958
|
senderSigner: this.userSigner,
|
|
@@ -2912,7 +2971,7 @@ export class PrivateMessenger {
|
|
|
2912
2971
|
payload,
|
|
2913
2972
|
error,
|
|
2914
2973
|
content,
|
|
2915
|
-
idempotencyKey,
|
|
2974
|
+
idempotencyKey: normalizedIdempotencyKey,
|
|
2916
2975
|
useBulkPacing,
|
|
2917
2976
|
onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
|
|
2918
2977
|
_getIykcProofs: this.contentKeyLookup()
|
|
@@ -2920,12 +2979,17 @@ export class PrivateMessenger {
|
|
|
2920
2979
|
} finally { releaseActivity() }
|
|
2921
2980
|
}
|
|
2922
2981
|
|
|
2923
|
-
async tell (
|
|
2924
|
-
|
|
2925
|
-
|
|
2982
|
+
async tell (options = {}) {
|
|
2983
|
+
const {
|
|
2984
|
+
channelPubkey = this.defaultChannelPubkey(), receiverPubkey, relays, relayToReceivers,
|
|
2985
|
+
message, code, payload, error, content, idempotencyKey, deletionPubkey, useBulkPacing = false
|
|
2986
|
+
} = options
|
|
2987
|
+
const capacityEgress = this.capacityEgressFor(options)
|
|
2988
|
+
const normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
|
|
2989
|
+
const channel = this.requireWritableChannel(channelPubkey, { capacityEgress })
|
|
2926
2990
|
const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
|
|
2927
2991
|
try {
|
|
2928
|
-
const routing = await this.resolveSendRouting({ channel, receiverPubkeys: [receiverPubkey], relays, relayToReceivers })
|
|
2992
|
+
const routing = await this.resolveSendRouting({ channel, receiverPubkeys: [receiverPubkey], relays, relayToReceivers, capacityEgress })
|
|
2929
2993
|
this.debugSend('tell', channelPubkey, { code, receiverPubkey })
|
|
2930
2994
|
return await this._privateMessage.tell({
|
|
2931
2995
|
senderSigner: this.userSigner,
|
|
@@ -2943,7 +3007,7 @@ export class PrivateMessenger {
|
|
|
2943
3007
|
payload,
|
|
2944
3008
|
error,
|
|
2945
3009
|
content,
|
|
2946
|
-
idempotencyKey,
|
|
3010
|
+
idempotencyKey: normalizedIdempotencyKey,
|
|
2947
3011
|
useBulkPacing,
|
|
2948
3012
|
onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
|
|
2949
3013
|
_getIykcProofs: this.contentKeyLookup()
|
|
@@ -2951,16 +3015,22 @@ export class PrivateMessenger {
|
|
|
2951
3015
|
} finally { releaseActivity() }
|
|
2952
3016
|
}
|
|
2953
3017
|
|
|
2954
|
-
async yell (
|
|
2955
|
-
|
|
2956
|
-
|
|
3018
|
+
async yell (options = {}) {
|
|
3019
|
+
const {
|
|
3020
|
+
channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers,
|
|
3021
|
+
message, code, payload, error, content, idempotencyKey, deletionPubkey, createdAt, createdAtMs,
|
|
3022
|
+
onPreparedSeed, preparedPublication, preparedPublications, useBulkPacing = false
|
|
3023
|
+
} = options
|
|
3024
|
+
const capacityEgress = this.capacityEgressFor(options)
|
|
3025
|
+
const normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
|
|
3026
|
+
const channel = this.requireWritableChannel(channelPubkey, { capacityEgress })
|
|
2957
3027
|
const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
|
|
2958
3028
|
try {
|
|
2959
3029
|
const prepared = normalizePreparedPublications({ preparedPublication, preparedPublications })
|
|
2960
3030
|
const receivers = uniq(receiverPubkeys?.length
|
|
2961
3031
|
? receiverPubkeys
|
|
2962
3032
|
: prepared.flatMap(publication => publication.receiverPubkeys || []))
|
|
2963
|
-
const routing = await this.resolveSendRouting({ channel, receiverPubkeys: receivers, relays, relayToReceivers })
|
|
3033
|
+
const routing = await this.resolveSendRouting({ channel, receiverPubkeys: receivers, relays, relayToReceivers, capacityEgress })
|
|
2964
3034
|
this.debugSend('yell', channelPubkey, { code, receiverPubkeys: receivers })
|
|
2965
3035
|
return await this._privateMessage.yell({
|
|
2966
3036
|
senderSigner: this.userSigner,
|
|
@@ -2978,7 +3048,7 @@ export class PrivateMessenger {
|
|
|
2978
3048
|
payload,
|
|
2979
3049
|
error,
|
|
2980
3050
|
content,
|
|
2981
|
-
idempotencyKey,
|
|
3051
|
+
idempotencyKey: normalizedIdempotencyKey,
|
|
2982
3052
|
createdAt,
|
|
2983
3053
|
createdAtMs,
|
|
2984
3054
|
useBulkPacing,
|
|
@@ -3187,9 +3257,45 @@ export class PrivateMessenger {
|
|
|
3187
3257
|
return channel
|
|
3188
3258
|
}
|
|
3189
3259
|
|
|
3190
|
-
|
|
3260
|
+
capacityEgressFor (options) {
|
|
3261
|
+
const token = options?.[CAPACITY_EGRESS] || options?.capacityEgress
|
|
3262
|
+
if (!token) return null
|
|
3263
|
+
if (!token.active || token.controller?.signal?.aborted) throw expiredCapacityEgress()
|
|
3264
|
+
return token
|
|
3265
|
+
}
|
|
3266
|
+
|
|
3267
|
+
createCapacityEgress () {
|
|
3268
|
+
const token = { active: true, controller: new AbortController() }
|
|
3269
|
+
const scopedMethod = method => options => {
|
|
3270
|
+
if (!token.active) return Promise.reject(expiredCapacityEgress())
|
|
3271
|
+
return this[method]({ ...(options || {}), [CAPACITY_EGRESS]: token })
|
|
3272
|
+
}
|
|
3273
|
+
return {
|
|
3274
|
+
messenger: Object.freeze({
|
|
3275
|
+
ask: scopedMethod('ask'),
|
|
3276
|
+
reply: scopedMethod('reply'),
|
|
3277
|
+
tell: scopedMethod('tell'),
|
|
3278
|
+
yell: scopedMethod('yell')
|
|
3279
|
+
}),
|
|
3280
|
+
token,
|
|
3281
|
+
release (reason = expiredCapacityEgress()) {
|
|
3282
|
+
if (!token.active) return
|
|
3283
|
+
token.active = false
|
|
3284
|
+
token.controller.abort(reason)
|
|
3285
|
+
}
|
|
3286
|
+
}
|
|
3287
|
+
}
|
|
3288
|
+
|
|
3289
|
+
sendingPaused () {
|
|
3290
|
+
return [...this.pauseReasons].some(reason => reason !== 'capacity')
|
|
3291
|
+
}
|
|
3292
|
+
|
|
3293
|
+
requireWritableChannel (pubkey, { capacityEgress } = {}) {
|
|
3294
|
+
this.capacityEgressFor({ capacityEgress })
|
|
3295
|
+
const allowCapacity = Boolean(capacityEgress)
|
|
3191
3296
|
this.assertOpen()
|
|
3192
|
-
if (this.
|
|
3297
|
+
if (this.sendingPaused()) throw this.pausedError()
|
|
3298
|
+
if (this.pauseReasons.has('capacity') && !allowCapacity) throw capacityPausedError()
|
|
3193
3299
|
const channel = this.requireChannel(pubkey)
|
|
3194
3300
|
if (!channel.signer) throw new ValidationError('PRIVATE_CHANNEL_WRITER_REQUIRED')
|
|
3195
3301
|
return channel
|
|
@@ -3402,14 +3508,15 @@ export class PrivateMessenger {
|
|
|
3402
3508
|
return this.#askSeedersForMissingRangeAttempt(channelPubkey, range.start, until)
|
|
3403
3509
|
}
|
|
3404
3510
|
|
|
3405
|
-
async replyWithStoredSeeds (channelPubkey, message) {
|
|
3511
|
+
async replyWithStoredSeeds (channelPubkey, message, { messenger = this } = {}) {
|
|
3406
3512
|
const payload = isPlainObject(message.payload?.payload) ? message.payload.payload : {}
|
|
3407
3513
|
const since = Number.isFinite(payload.since) ? payload.since : undefined
|
|
3408
3514
|
const until = Number.isFinite(payload.until) ? payload.until : undefined
|
|
3409
3515
|
const priority = payload.priority === 'lower' || payload.priority === 'lowest'
|
|
3410
3516
|
? payload.priority
|
|
3411
3517
|
: 'normal'
|
|
3412
|
-
const packer =
|
|
3518
|
+
const packer = createMissingMessageReplyPacker({
|
|
3519
|
+
messenger,
|
|
3413
3520
|
channelPubkey,
|
|
3414
3521
|
question: message.event,
|
|
3415
3522
|
receiverPubkey: message.event?.pubkey,
|
|
@@ -3891,7 +3998,7 @@ export class PrivateMessenger {
|
|
|
3891
3998
|
async deferDecryption (failure) {
|
|
3892
3999
|
this.assertOpen()
|
|
3893
4000
|
const pubkey = failure.record.channelPubkey
|
|
3894
|
-
if (this.
|
|
4001
|
+
if (this.sendingPaused() || !this.channels.has(pubkey)) throw this.pausedError()
|
|
3895
4002
|
try { return await this.pendingDecryption.save(failure) } catch (error) {
|
|
3896
4003
|
this.recordInterruption([pubkey], failure.record.outer?.created_at)
|
|
3897
4004
|
if (isRecoverableStorageFailure(error)) this.pauseInternally('storage').catch(err => this.onError?.(err))
|
|
@@ -3912,7 +4019,7 @@ export class PrivateMessenger {
|
|
|
3912
4019
|
|
|
3913
4020
|
retryPendingDecryptions ({ force = false } = {}) {
|
|
3914
4021
|
if (typeof force !== 'boolean') throw new ValidationError('INVALID_FORCE')
|
|
3915
|
-
if (this.closePromise || this.
|
|
4022
|
+
if (this.closePromise || this.sendingPaused() || !this.initialized) return Promise.resolve()
|
|
3916
4023
|
if (this.decryptionRetry && !this.decryptionRetry.controller.signal.aborted) {
|
|
3917
4024
|
// Before a pass reads its snapshot, new requests belong to that pass.
|
|
3918
4025
|
if (this.decryptionRetry.started) this.decryptionRetry.again = true
|
|
@@ -3936,7 +4043,7 @@ export class PrivateMessenger {
|
|
|
3936
4043
|
if (!channel || !this.desiredChannels.has(channelPubkey)) return
|
|
3937
4044
|
const current = () => {
|
|
3938
4045
|
signal.throwIfAborted()
|
|
3939
|
-
if (this.
|
|
4046
|
+
if (this.sendingPaused() || this.channels.get(channelPubkey) !== channel || !this.desiredChannels.has(channelPubkey)) throw new Error('PRIVATE_CHANNEL_CHANGED')
|
|
3940
4047
|
}
|
|
3941
4048
|
try {
|
|
3942
4049
|
await this._privateChannel.replayDeferredDecryptions({
|
|
@@ -25,7 +25,7 @@ export function wireEvent (value, owner) {
|
|
|
25
25
|
}
|
|
26
26
|
// Relay rejection text must not be interpreted as a local signer denial.
|
|
27
27
|
const retryable = error => error?.code === 'MESSAGE_NOT_PUBLISHED' || !/DENIED|PERMISSION|REVOKED|READ_ONLY|INVALID|BLOCKED|EXPIRED|NOT_IN_PERSONA/i.test(`${error?.code || ''} ${error?.message || ''}`)
|
|
28
|
-
const unavailableSend = /
|
|
28
|
+
const unavailableSend = /PRIVATE_MESSENGER_(?:CAPACITY_)?PAUSED|CHAT_UNAVAILABLE|MESSENGER_UNAVAILABLE/i
|
|
29
29
|
const isUnavailableSend = error => unavailableSend.test(`${error?.code || ''} ${error?.message || ''}`)
|
|
30
30
|
const SEND_RETRY_MIN_MS = 1000
|
|
31
31
|
const SEND_RETRY_MAX_MS = 30000
|