libp2r2p 0.12.19 → 0.12.21
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')
|
|
@@ -1910,11 +1939,13 @@ export class PrivateMessenger {
|
|
|
1910
1939
|
}
|
|
1911
1940
|
|
|
1912
1941
|
recordInterruption (channels, at = nowSeconds()) {
|
|
1942
|
+
const now = nowSeconds()
|
|
1943
|
+
const eventTime = Number.isSafeInteger(at) && at >= 0 ? Math.min(at, now) : now
|
|
1913
1944
|
const state = this.readState()
|
|
1914
1945
|
for (const pubkey of channels) {
|
|
1915
1946
|
if (!this.offlineRecoverySecondsFor(pubkey)) continue
|
|
1916
1947
|
const current = state.channels[pubkey] || {}
|
|
1917
|
-
const start = Math.max(0,
|
|
1948
|
+
const start = Math.max(0, eventTime - this.offlineSkewSeconds)
|
|
1918
1949
|
current.openOfflineStart = Math.min(current.openOfflineStart ?? start, start)
|
|
1919
1950
|
state.channels[pubkey] = current
|
|
1920
1951
|
}
|
|
@@ -2069,12 +2100,14 @@ export class PrivateMessenger {
|
|
|
2069
2100
|
if (typeof reason !== 'string' || !reason.trim()) throw new ValidationError('PAUSE_REASON_REQUIRED')
|
|
2070
2101
|
this.assertOpen()
|
|
2071
2102
|
this.pauseReasons.add(reason)
|
|
2072
|
-
this.decryptionRetry?.controller.abort(this.pausedError())
|
|
2073
2103
|
this.pauseRevisions.set(reason, (this.pauseRevisions.get(reason) || 0) + 1)
|
|
2074
|
-
this.sendRoutingPause.abort(this.pausedError())
|
|
2075
2104
|
const pausedError = this.pausedError()
|
|
2076
2105
|
this.notifyStatus()
|
|
2077
|
-
|
|
2106
|
+
if (reason !== 'capacity') {
|
|
2107
|
+
this.decryptionRetry?.controller.abort(pausedError)
|
|
2108
|
+
this.sendRoutingPause.abort(pausedError)
|
|
2109
|
+
for (const extension of this.extensions) extension.pause?.()
|
|
2110
|
+
}
|
|
2078
2111
|
this.recordInterruption(this.desiredChannels)
|
|
2079
2112
|
for (const controller of this.recoveryControllers) controller.abort(pausedError)
|
|
2080
2113
|
return Promise.all([this.stopWatches([...this.desiredChannels], { reason: pausedError }), this.flushStateWrites()])
|
|
@@ -2110,7 +2143,7 @@ export class PrivateMessenger {
|
|
|
2110
2143
|
if (this.pauseReasons.size || this.closePromise) return
|
|
2111
2144
|
const jobs = removed ? this.startChannelBackground(channels, { recover: true }) : [...this.channelBackground.values()].map(job => job.work)
|
|
2112
2145
|
if (removed) this.retryPendingDecryptions().catch(error => this.onError?.(error))
|
|
2113
|
-
if (removed) {
|
|
2146
|
+
if (removed && reason !== 'capacity') {
|
|
2114
2147
|
for (const extension of this.extensions) {
|
|
2115
2148
|
const work = Promise.resolve().then(() => { if (!this.pauseReasons.size && !this.closePromise) return extension.resume?.() })
|
|
2116
2149
|
work.catch(error => this.onError?.(error))
|
|
@@ -2292,9 +2325,24 @@ export class PrivateMessenger {
|
|
|
2292
2325
|
async handleAsk (channelPubkey, message) {
|
|
2293
2326
|
if (message.provenance === 'hearsay') return this.enqueueRumor('message', channelPubkey, message)
|
|
2294
2327
|
this.trackSeederActivity(channelPubkey, message)
|
|
2295
|
-
for (const extension of this.extensions)
|
|
2328
|
+
for (const extension of this.extensions) {
|
|
2329
|
+
if (!extension.handleAsk) continue
|
|
2330
|
+
const capacityEgress = this.createCapacityEgress()
|
|
2331
|
+
try {
|
|
2332
|
+
if (await extension.handleAsk(channelPubkey, message, { capacityEgress })) return
|
|
2333
|
+
capacityEgress.release()
|
|
2334
|
+
} catch (error) {
|
|
2335
|
+
capacityEgress.release(error)
|
|
2336
|
+
throw error
|
|
2337
|
+
}
|
|
2338
|
+
}
|
|
2296
2339
|
if (doesModeStoreRecoverySeeds(this.channels.get(channelPubkey)?.mode) && messageCode(message) === MISSING_MESSAGES_ASK_CODE) {
|
|
2297
|
-
|
|
2340
|
+
const capacityEgress = this.createCapacityEgress()
|
|
2341
|
+
try {
|
|
2342
|
+
await this.replyWithStoredSeeds(channelPubkey, message, { messenger: capacityEgress.messenger })
|
|
2343
|
+
} finally {
|
|
2344
|
+
capacityEgress.release()
|
|
2345
|
+
}
|
|
2298
2346
|
return
|
|
2299
2347
|
}
|
|
2300
2348
|
await this.enqueueRumor('ask', channelPubkey, message)
|
|
@@ -2467,7 +2515,10 @@ export class PrivateMessenger {
|
|
|
2467
2515
|
if (this.pauseReasons.has('capacity')) throw this.pausedError()
|
|
2468
2516
|
const capacity = await this.queue.getCapacity()
|
|
2469
2517
|
if (capacity.usedBytes >= inboxCapacityLimits(capacity.maxBytes).highWaterBytes) {
|
|
2470
|
-
throw await this.beginCapacityPressure(capacity
|
|
2518
|
+
throw await this.beginCapacityPressure(capacity, {
|
|
2519
|
+
channelPubkey,
|
|
2520
|
+
interruptionAt: messageTime(message)
|
|
2521
|
+
})
|
|
2471
2522
|
}
|
|
2472
2523
|
const record = {
|
|
2473
2524
|
type,
|
|
@@ -2736,7 +2787,8 @@ export class PrivateMessenger {
|
|
|
2736
2787
|
}
|
|
2737
2788
|
}
|
|
2738
2789
|
|
|
2739
|
-
async beginCapacityPressure (capacity) {
|
|
2790
|
+
async beginCapacityPressure (capacity, { channelPubkey, interruptionAt = nowSeconds() } = {}) {
|
|
2791
|
+
if (channelPubkey) this.recordInterruption([channelPubkey], interruptionAt)
|
|
2740
2792
|
this.applyCapacityRecoveryTarget(capacity)
|
|
2741
2793
|
const pause = this.pauseReasons.has('capacity') ? null : this.pause('capacity')
|
|
2742
2794
|
pause?.catch(error => this.onError?.(error))
|
|
@@ -2821,16 +2873,18 @@ export class PrivateMessenger {
|
|
|
2821
2873
|
})
|
|
2822
2874
|
if (!reservation) return null
|
|
2823
2875
|
if (this.closePromise) { await reservation.nack(); return null }
|
|
2876
|
+
const capacityEgress = this.createCapacityEgress()
|
|
2824
2877
|
let finish
|
|
2825
2878
|
const settled = new Promise(resolve => { finish = resolve })
|
|
2826
2879
|
const done = () => {
|
|
2827
2880
|
clearInterval(timer)
|
|
2881
|
+
capacityEgress.release()
|
|
2828
2882
|
this.deliveries.delete(delivery)
|
|
2829
2883
|
finish()
|
|
2830
2884
|
this.wakeDeliveries()
|
|
2831
2885
|
}
|
|
2832
|
-
const settle = async method => {
|
|
2833
|
-
const result = await reservation[method]()
|
|
2886
|
+
const settle = async (method, options) => {
|
|
2887
|
+
const result = await reservation[method](options)
|
|
2834
2888
|
done()
|
|
2835
2889
|
if (method === 'ack' && result && !this.closePromise && this.pauseReasons.has('capacity')) {
|
|
2836
2890
|
this.checkCapacity().catch(err => this.onError?.(err))
|
|
@@ -2840,7 +2894,8 @@ export class PrivateMessenger {
|
|
|
2840
2894
|
const delivery = {
|
|
2841
2895
|
message: withoutQueueMetadata(reservation.item),
|
|
2842
2896
|
ack: () => settle('ack'),
|
|
2843
|
-
nack:
|
|
2897
|
+
nack: options => settle('nack', options),
|
|
2898
|
+
capacityEgress: capacityEgress.messenger
|
|
2844
2899
|
}
|
|
2845
2900
|
Object.defineProperty(delivery, 'settled', { value: settled })
|
|
2846
2901
|
this.deliveries.add(delivery)
|
|
@@ -2851,12 +2906,17 @@ export class PrivateMessenger {
|
|
|
2851
2906
|
return delivery
|
|
2852
2907
|
}
|
|
2853
2908
|
|
|
2854
|
-
async ask (
|
|
2855
|
-
|
|
2856
|
-
|
|
2909
|
+
async ask (options = {}) {
|
|
2910
|
+
const {
|
|
2911
|
+
channelPubkey = this.defaultChannelPubkey(), receiverPubkey, relays, relayToReceivers,
|
|
2912
|
+
message, code, payload, error, content, idempotencyKey, deletionPubkey, useBulkPacing = false
|
|
2913
|
+
} = options
|
|
2914
|
+
const capacityEgress = this.capacityEgressFor(options)
|
|
2915
|
+
const normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
|
|
2916
|
+
const channel = this.requireWritableChannel(channelPubkey, { capacityEgress })
|
|
2857
2917
|
const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
|
|
2858
2918
|
try {
|
|
2859
|
-
const routing = await this.resolveSendRouting({ channel, receiverPubkeys: [receiverPubkey], relays, relayToReceivers })
|
|
2919
|
+
const routing = await this.resolveSendRouting({ channel, receiverPubkeys: [receiverPubkey], relays, relayToReceivers, capacityEgress })
|
|
2860
2920
|
this.debugSend('ask', channelPubkey, { code, receiverPubkey })
|
|
2861
2921
|
return await this._privateMessage.ask({
|
|
2862
2922
|
senderSigner: this.userSigner,
|
|
@@ -2874,7 +2934,7 @@ export class PrivateMessenger {
|
|
|
2874
2934
|
payload,
|
|
2875
2935
|
error,
|
|
2876
2936
|
content,
|
|
2877
|
-
idempotencyKey,
|
|
2937
|
+
idempotencyKey: normalizedIdempotencyKey,
|
|
2878
2938
|
useBulkPacing,
|
|
2879
2939
|
onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
|
|
2880
2940
|
_getIykcProofs: this.contentKeyLookup()
|
|
@@ -2882,9 +2942,14 @@ export class PrivateMessenger {
|
|
|
2882
2942
|
} finally { releaseActivity() }
|
|
2883
2943
|
}
|
|
2884
2944
|
|
|
2885
|
-
async reply (
|
|
2886
|
-
|
|
2887
|
-
|
|
2945
|
+
async reply (options = {}) {
|
|
2946
|
+
const {
|
|
2947
|
+
channelPubkey = this.defaultChannelPubkey(), question, receiverPubkey, relays, relayToReceivers,
|
|
2948
|
+
message, code, payload, error, content, idempotencyKey, deletionPubkey, expiresAt, useBulkPacing = false
|
|
2949
|
+
} = options
|
|
2950
|
+
const capacityEgress = this.capacityEgressFor(options)
|
|
2951
|
+
const normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
|
|
2952
|
+
const channel = this.requireWritableChannel(channelPubkey, { capacityEgress })
|
|
2888
2953
|
const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
|
|
2889
2954
|
try {
|
|
2890
2955
|
const expirationSeconds = replyExpirationSeconds(
|
|
@@ -2893,7 +2958,7 @@ export class PrivateMessenger {
|
|
|
2893
2958
|
this._now()
|
|
2894
2959
|
)
|
|
2895
2960
|
const resolvedReceiverPubkey = receiverPubkey || question?.pubkey || ''
|
|
2896
|
-
const routing = await this.resolveSendRouting({ channel, receiverPubkeys: [resolvedReceiverPubkey], relays, relayToReceivers })
|
|
2961
|
+
const routing = await this.resolveSendRouting({ channel, receiverPubkeys: [resolvedReceiverPubkey], relays, relayToReceivers, capacityEgress })
|
|
2897
2962
|
this.debugSend('reply', channelPubkey, { code, receiverPubkey: receiverPubkey || question?.pubkey || '' })
|
|
2898
2963
|
return await this._privateMessage.reply({
|
|
2899
2964
|
senderSigner: this.userSigner,
|
|
@@ -2912,7 +2977,7 @@ export class PrivateMessenger {
|
|
|
2912
2977
|
payload,
|
|
2913
2978
|
error,
|
|
2914
2979
|
content,
|
|
2915
|
-
idempotencyKey,
|
|
2980
|
+
idempotencyKey: normalizedIdempotencyKey,
|
|
2916
2981
|
useBulkPacing,
|
|
2917
2982
|
onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
|
|
2918
2983
|
_getIykcProofs: this.contentKeyLookup()
|
|
@@ -2920,12 +2985,17 @@ export class PrivateMessenger {
|
|
|
2920
2985
|
} finally { releaseActivity() }
|
|
2921
2986
|
}
|
|
2922
2987
|
|
|
2923
|
-
async tell (
|
|
2924
|
-
|
|
2925
|
-
|
|
2988
|
+
async tell (options = {}) {
|
|
2989
|
+
const {
|
|
2990
|
+
channelPubkey = this.defaultChannelPubkey(), receiverPubkey, relays, relayToReceivers,
|
|
2991
|
+
message, code, payload, error, content, idempotencyKey, deletionPubkey, useBulkPacing = false
|
|
2992
|
+
} = options
|
|
2993
|
+
const capacityEgress = this.capacityEgressFor(options)
|
|
2994
|
+
const normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
|
|
2995
|
+
const channel = this.requireWritableChannel(channelPubkey, { capacityEgress })
|
|
2926
2996
|
const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
|
|
2927
2997
|
try {
|
|
2928
|
-
const routing = await this.resolveSendRouting({ channel, receiverPubkeys: [receiverPubkey], relays, relayToReceivers })
|
|
2998
|
+
const routing = await this.resolveSendRouting({ channel, receiverPubkeys: [receiverPubkey], relays, relayToReceivers, capacityEgress })
|
|
2929
2999
|
this.debugSend('tell', channelPubkey, { code, receiverPubkey })
|
|
2930
3000
|
return await this._privateMessage.tell({
|
|
2931
3001
|
senderSigner: this.userSigner,
|
|
@@ -2943,7 +3013,7 @@ export class PrivateMessenger {
|
|
|
2943
3013
|
payload,
|
|
2944
3014
|
error,
|
|
2945
3015
|
content,
|
|
2946
|
-
idempotencyKey,
|
|
3016
|
+
idempotencyKey: normalizedIdempotencyKey,
|
|
2947
3017
|
useBulkPacing,
|
|
2948
3018
|
onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
|
|
2949
3019
|
_getIykcProofs: this.contentKeyLookup()
|
|
@@ -2951,16 +3021,22 @@ export class PrivateMessenger {
|
|
|
2951
3021
|
} finally { releaseActivity() }
|
|
2952
3022
|
}
|
|
2953
3023
|
|
|
2954
|
-
async yell (
|
|
2955
|
-
|
|
2956
|
-
|
|
3024
|
+
async yell (options = {}) {
|
|
3025
|
+
const {
|
|
3026
|
+
channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers,
|
|
3027
|
+
message, code, payload, error, content, idempotencyKey, deletionPubkey, createdAt, createdAtMs,
|
|
3028
|
+
onPreparedSeed, preparedPublication, preparedPublications, useBulkPacing = false
|
|
3029
|
+
} = options
|
|
3030
|
+
const capacityEgress = this.capacityEgressFor(options)
|
|
3031
|
+
const normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
|
|
3032
|
+
const channel = this.requireWritableChannel(channelPubkey, { capacityEgress })
|
|
2957
3033
|
const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
|
|
2958
3034
|
try {
|
|
2959
3035
|
const prepared = normalizePreparedPublications({ preparedPublication, preparedPublications })
|
|
2960
3036
|
const receivers = uniq(receiverPubkeys?.length
|
|
2961
3037
|
? receiverPubkeys
|
|
2962
3038
|
: prepared.flatMap(publication => publication.receiverPubkeys || []))
|
|
2963
|
-
const routing = await this.resolveSendRouting({ channel, receiverPubkeys: receivers, relays, relayToReceivers })
|
|
3039
|
+
const routing = await this.resolveSendRouting({ channel, receiverPubkeys: receivers, relays, relayToReceivers, capacityEgress })
|
|
2964
3040
|
this.debugSend('yell', channelPubkey, { code, receiverPubkeys: receivers })
|
|
2965
3041
|
return await this._privateMessage.yell({
|
|
2966
3042
|
senderSigner: this.userSigner,
|
|
@@ -2978,7 +3054,7 @@ export class PrivateMessenger {
|
|
|
2978
3054
|
payload,
|
|
2979
3055
|
error,
|
|
2980
3056
|
content,
|
|
2981
|
-
idempotencyKey,
|
|
3057
|
+
idempotencyKey: normalizedIdempotencyKey,
|
|
2982
3058
|
createdAt,
|
|
2983
3059
|
createdAtMs,
|
|
2984
3060
|
useBulkPacing,
|
|
@@ -3187,9 +3263,45 @@ export class PrivateMessenger {
|
|
|
3187
3263
|
return channel
|
|
3188
3264
|
}
|
|
3189
3265
|
|
|
3190
|
-
|
|
3266
|
+
capacityEgressFor (options) {
|
|
3267
|
+
const token = options?.[CAPACITY_EGRESS] || options?.capacityEgress
|
|
3268
|
+
if (!token) return null
|
|
3269
|
+
if (!token.active || token.controller?.signal?.aborted) throw expiredCapacityEgress()
|
|
3270
|
+
return token
|
|
3271
|
+
}
|
|
3272
|
+
|
|
3273
|
+
createCapacityEgress () {
|
|
3274
|
+
const token = { active: true, controller: new AbortController() }
|
|
3275
|
+
const scopedMethod = method => options => {
|
|
3276
|
+
if (!token.active) return Promise.reject(expiredCapacityEgress())
|
|
3277
|
+
return this[method]({ ...(options || {}), [CAPACITY_EGRESS]: token })
|
|
3278
|
+
}
|
|
3279
|
+
return {
|
|
3280
|
+
messenger: Object.freeze({
|
|
3281
|
+
ask: scopedMethod('ask'),
|
|
3282
|
+
reply: scopedMethod('reply'),
|
|
3283
|
+
tell: scopedMethod('tell'),
|
|
3284
|
+
yell: scopedMethod('yell')
|
|
3285
|
+
}),
|
|
3286
|
+
token,
|
|
3287
|
+
release (reason = expiredCapacityEgress()) {
|
|
3288
|
+
if (!token.active) return
|
|
3289
|
+
token.active = false
|
|
3290
|
+
token.controller.abort(reason)
|
|
3291
|
+
}
|
|
3292
|
+
}
|
|
3293
|
+
}
|
|
3294
|
+
|
|
3295
|
+
sendingPaused () {
|
|
3296
|
+
return [...this.pauseReasons].some(reason => reason !== 'capacity')
|
|
3297
|
+
}
|
|
3298
|
+
|
|
3299
|
+
requireWritableChannel (pubkey, { capacityEgress } = {}) {
|
|
3300
|
+
this.capacityEgressFor({ capacityEgress })
|
|
3301
|
+
const allowCapacity = Boolean(capacityEgress)
|
|
3191
3302
|
this.assertOpen()
|
|
3192
|
-
if (this.
|
|
3303
|
+
if (this.sendingPaused()) throw this.pausedError()
|
|
3304
|
+
if (this.pauseReasons.has('capacity') && !allowCapacity) throw capacityPausedError()
|
|
3193
3305
|
const channel = this.requireChannel(pubkey)
|
|
3194
3306
|
if (!channel.signer) throw new ValidationError('PRIVATE_CHANNEL_WRITER_REQUIRED')
|
|
3195
3307
|
return channel
|
|
@@ -3402,14 +3514,15 @@ export class PrivateMessenger {
|
|
|
3402
3514
|
return this.#askSeedersForMissingRangeAttempt(channelPubkey, range.start, until)
|
|
3403
3515
|
}
|
|
3404
3516
|
|
|
3405
|
-
async replyWithStoredSeeds (channelPubkey, message) {
|
|
3517
|
+
async replyWithStoredSeeds (channelPubkey, message, { messenger = this } = {}) {
|
|
3406
3518
|
const payload = isPlainObject(message.payload?.payload) ? message.payload.payload : {}
|
|
3407
3519
|
const since = Number.isFinite(payload.since) ? payload.since : undefined
|
|
3408
3520
|
const until = Number.isFinite(payload.until) ? payload.until : undefined
|
|
3409
3521
|
const priority = payload.priority === 'lower' || payload.priority === 'lowest'
|
|
3410
3522
|
? payload.priority
|
|
3411
3523
|
: 'normal'
|
|
3412
|
-
const packer =
|
|
3524
|
+
const packer = createMissingMessageReplyPacker({
|
|
3525
|
+
messenger,
|
|
3413
3526
|
channelPubkey,
|
|
3414
3527
|
question: message.event,
|
|
3415
3528
|
receiverPubkey: message.event?.pubkey,
|
|
@@ -3891,7 +4004,7 @@ export class PrivateMessenger {
|
|
|
3891
4004
|
async deferDecryption (failure) {
|
|
3892
4005
|
this.assertOpen()
|
|
3893
4006
|
const pubkey = failure.record.channelPubkey
|
|
3894
|
-
if (this.
|
|
4007
|
+
if (this.sendingPaused() || !this.channels.has(pubkey)) throw this.pausedError()
|
|
3895
4008
|
try { return await this.pendingDecryption.save(failure) } catch (error) {
|
|
3896
4009
|
this.recordInterruption([pubkey], failure.record.outer?.created_at)
|
|
3897
4010
|
if (isRecoverableStorageFailure(error)) this.pauseInternally('storage').catch(err => this.onError?.(err))
|
|
@@ -3912,7 +4025,7 @@ export class PrivateMessenger {
|
|
|
3912
4025
|
|
|
3913
4026
|
retryPendingDecryptions ({ force = false } = {}) {
|
|
3914
4027
|
if (typeof force !== 'boolean') throw new ValidationError('INVALID_FORCE')
|
|
3915
|
-
if (this.closePromise || this.
|
|
4028
|
+
if (this.closePromise || this.sendingPaused() || !this.initialized) return Promise.resolve()
|
|
3916
4029
|
if (this.decryptionRetry && !this.decryptionRetry.controller.signal.aborted) {
|
|
3917
4030
|
// Before a pass reads its snapshot, new requests belong to that pass.
|
|
3918
4031
|
if (this.decryptionRetry.started) this.decryptionRetry.again = true
|
|
@@ -3936,7 +4049,7 @@ export class PrivateMessenger {
|
|
|
3936
4049
|
if (!channel || !this.desiredChannels.has(channelPubkey)) return
|
|
3937
4050
|
const current = () => {
|
|
3938
4051
|
signal.throwIfAborted()
|
|
3939
|
-
if (this.
|
|
4052
|
+
if (this.sendingPaused() || this.channels.get(channelPubkey) !== channel || !this.desiredChannels.has(channelPubkey)) throw new Error('PRIVATE_CHANNEL_CHANGED')
|
|
3940
4053
|
}
|
|
3941
4054
|
try {
|
|
3942
4055
|
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
|