libp2r2p 0.12.3 → 0.12.5
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 +9 -3
- package/package.json +1 -1
- package/private-messenger/index.js +162 -19
- package/private-messenger/session/README.md +8 -0
- package/web-storage-queue/index.js +13 -1
package/README.md
CHANGED
|
@@ -1166,11 +1166,14 @@ the old token: its `ack`, `nack` and `renew` return false. Successful writes wak
|
|
|
1166
1166
|
local waiting consumers. Like the other indexed methods, `putBy` is exclusive
|
|
1167
1167
|
to `idb-queue`; the Web Storage queue's common API is unchanged.
|
|
1168
1168
|
|
|
1169
|
-
|
|
1169
|
+
Both queue implementations support
|
|
1170
|
+
`createQueue({ prefix, evictionPolicy: 'reject', maxBytes })` to opt out of
|
|
1170
1171
|
capacity eviction. Oversized items reject with `QUEUE_ITEM_TOO_LARGE`, full
|
|
1171
1172
|
queues with `QUEUE_CAPACITY_EXCEEDED`; browser quota errors propagate without
|
|
1172
1173
|
trimming existing records. Other eviction policies retain their cache behavior.
|
|
1173
1174
|
Opening a reject-policy queue under a smaller budget preserves existing items.
|
|
1175
|
+
Positional replacement and insertion follow the same rule: they reject instead
|
|
1176
|
+
of evicting when the resulting queue would exceed the limit.
|
|
1174
1177
|
|
|
1175
1178
|
`queue.reserve({ leaseMs = 30000 })` returns `null` or
|
|
1176
1179
|
`{ item, ack, nack, renew }`. Reservation token/deadline are internal record
|
|
@@ -1180,8 +1183,11 @@ PrivateMessenger supplies both. Do not mix reservations with destructive or
|
|
|
1180
1183
|
position-shifting queue operations on the same queue except explicit removal.
|
|
1181
1184
|
A stale token cannot acknowledge a newly reserved or replaced record.
|
|
1182
1185
|
|
|
1183
|
-
`queue.getCapacity()`
|
|
1184
|
-
also expose `requiredBytes` and
|
|
1186
|
+
`queue.getCapacity()` is part of the common API and returns
|
|
1187
|
+
`{ usedBytes, maxBytes }`; capacity rejections also expose `requiredBytes` and
|
|
1188
|
+
`maxBytes`, without retaining the rejected item. IDB queues return a Promise,
|
|
1189
|
+
while Web Storage queues return the object synchronously according to their
|
|
1190
|
+
respective operation conventions; callers can await either form.
|
|
1185
1191
|
|
|
1186
1192
|
|
|
1187
1193
|
### Publication acknowledgement deadlines
|
package/package.json
CHANGED
|
@@ -118,6 +118,8 @@ const DEFAULT_SEEDER_ONLINE_SECONDS = 20 * 60
|
|
|
118
118
|
const DEFAULT_MAX_DYNAMIC_RECOVERY_SEEDERS = 8
|
|
119
119
|
const DEFAULT_MESSAGE_QUEUE_MAX_BYTES = 16 * 1024 * 1024 // 16 MiB
|
|
120
120
|
const DEFAULT_SEED_QUEUE_MAX_BYTES = 64 * 1024 * 1024 // 64 MiB
|
|
121
|
+
const MESSAGE_QUEUE_HIGH_WATER_RATIO = 0.7
|
|
122
|
+
const MESSAGE_QUEUE_LOW_WATER_RATIO = 0.5
|
|
121
123
|
const SEED_KEY = '__p2r2pSeedKey'
|
|
122
124
|
const SEED_TIME = '__p2r2pSeedTime'
|
|
123
125
|
const MESSAGE_QUEUE_INDEXES = {
|
|
@@ -138,6 +140,33 @@ function isQueueCapacityError (error) {
|
|
|
138
140
|
return error?.code === 'QUEUE_CAPACITY_EXCEEDED' || error?.message === 'QUEUE_CAPACITY_EXCEEDED'
|
|
139
141
|
}
|
|
140
142
|
|
|
143
|
+
function isPausedError (error) {
|
|
144
|
+
return error?.code === 'PRIVATE_MESSENGER_PAUSED' || error?.message === 'PRIVATE_MESSENGER_PAUSED'
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function isCapacityPressureError (error) {
|
|
148
|
+
return error?.code === 'PRIVATE_MESSENGER_CAPACITY_PRESSURE'
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function isExpectedRecoveryPause (error, controller) {
|
|
152
|
+
return isPausedError(error) || isCapacityPressureError(error) ||
|
|
153
|
+
isPausedError(controller?.signal?.reason) || isCapacityPressureError(controller?.signal?.reason)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function inboxCapacityLimits (maxBytes) {
|
|
157
|
+
if (maxBytes === Infinity) {
|
|
158
|
+
return { highWaterBytes: Infinity, resumeAtBytes: 0, maxBytes: Infinity }
|
|
159
|
+
}
|
|
160
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {
|
|
161
|
+
return { highWaterBytes: 0, resumeAtBytes: 0, maxBytes: 0 }
|
|
162
|
+
}
|
|
163
|
+
return {
|
|
164
|
+
highWaterBytes: Math.max(1, Math.floor(maxBytes * MESSAGE_QUEUE_HIGH_WATER_RATIO)),
|
|
165
|
+
resumeAtBytes: Math.max(1, Math.floor(maxBytes * MESSAGE_QUEUE_LOW_WATER_RATIO)),
|
|
166
|
+
maxBytes
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
141
170
|
async function annotateQueueCapacityError (error, queue, getCapacity) {
|
|
142
171
|
if (!isQueueCapacityError(error)) return error
|
|
143
172
|
let capacity = {}
|
|
@@ -394,6 +423,7 @@ export class PrivateMessenger {
|
|
|
394
423
|
this.capacityTimer = null
|
|
395
424
|
this.capacityCheck = null
|
|
396
425
|
this.capacityRequiredBytes = 0
|
|
426
|
+
this.capacityResumeAtBytes = 0
|
|
397
427
|
this.reloadGapTimers = new Map()
|
|
398
428
|
this.liveInterruptions = new Map()
|
|
399
429
|
this.liveRecoveryTimers = new Map()
|
|
@@ -491,6 +521,11 @@ export class PrivateMessenger {
|
|
|
491
521
|
indexedDB: this._indexedDB
|
|
492
522
|
})
|
|
493
523
|
this.assertOpen()
|
|
524
|
+
const initialCapacity = await this.queue.getCapacity()
|
|
525
|
+
if (initialCapacity.usedBytes >= inboxCapacityLimits(initialCapacity.maxBytes).highWaterBytes) {
|
|
526
|
+
const pressure = await this.beginCapacityPressure(initialCapacity)
|
|
527
|
+
try { this.onError?.(pressure) } catch {}
|
|
528
|
+
}
|
|
494
529
|
this.startStorageMaintenance()
|
|
495
530
|
this.state = { channels: await this.stateStore.load() }
|
|
496
531
|
await this.update({ userSigner, contentKeySigner, nymSigner: this.nymSigner, channels, relays, mode })
|
|
@@ -704,7 +739,9 @@ export class PrivateMessenger {
|
|
|
704
739
|
this.touchStorageActivity().catch(err => this.onError?.(err))
|
|
705
740
|
const run = this.queueOperationTail.then(operation)
|
|
706
741
|
this.queueOperationTail = run.catch(err => {
|
|
707
|
-
|
|
742
|
+
if (!isPausedError(err)) {
|
|
743
|
+
try { this.onError?.(err) } catch {}
|
|
744
|
+
}
|
|
708
745
|
})
|
|
709
746
|
return run
|
|
710
747
|
}
|
|
@@ -1275,7 +1312,9 @@ export class PrivateMessenger {
|
|
|
1275
1312
|
receivedChunkTtlMs: this.receivedChunkTtlMsFor(channel),
|
|
1276
1313
|
receivedChunkIndexedDB: this._indexedDB,
|
|
1277
1314
|
onSubscriptionState: state => this.handleSubscriptionState(pubkey, state),
|
|
1278
|
-
onError: err =>
|
|
1315
|
+
onError: err => {
|
|
1316
|
+
if (!isExpectedRecoveryPause(err)) this.onError?.(err)
|
|
1317
|
+
}
|
|
1279
1318
|
})
|
|
1280
1319
|
} catch (error) {
|
|
1281
1320
|
if (signal?.aborted) continue
|
|
@@ -1688,6 +1727,7 @@ export class PrivateMessenger {
|
|
|
1688
1727
|
}
|
|
1689
1728
|
|
|
1690
1729
|
async finalizeRecoveryRange ({ channelPubkey, range, record }) {
|
|
1730
|
+
if (this.pauseReasons.size) throw this.pausedError()
|
|
1691
1731
|
if (!await this.checkRecoveryOnline()) return { complete: false, failures: [], offline: true }
|
|
1692
1732
|
const uncovered = subtractRanges({ start: range.start, end: range.end }, record.covered)
|
|
1693
1733
|
const oldest = record.oldestCreatedAt
|
|
@@ -1699,6 +1739,7 @@ export class PrivateMessenger {
|
|
|
1699
1739
|
const seedRanges = mergeRanges([...uncovered, ...leftEdge])
|
|
1700
1740
|
const failures = []
|
|
1701
1741
|
for (const seedRange of seedRanges) {
|
|
1742
|
+
if (this.pauseReasons.size) throw this.pausedError()
|
|
1702
1743
|
const attempt = await this.#askSeedersForMissingRangeAttempt(channelPubkey, seedRange.start, seedRange.end)
|
|
1703
1744
|
failures.push(...attempt.failures.map(failure => failure.error))
|
|
1704
1745
|
}
|
|
@@ -1762,10 +1803,10 @@ export class PrivateMessenger {
|
|
|
1762
1803
|
this.writeState(state)
|
|
1763
1804
|
}
|
|
1764
1805
|
|
|
1765
|
-
stopWatches (channels = [...this.stopByChannel.keys()]) {
|
|
1806
|
+
stopWatches (channels = [...this.stopByChannel.keys()], { reason } = {}) {
|
|
1766
1807
|
const closing = []
|
|
1767
1808
|
for (const pubkey of channels) {
|
|
1768
|
-
this.channelBackground.get(pubkey)?.controller.abort()
|
|
1809
|
+
this.channelBackground.get(pubkey)?.controller.abort(reason)
|
|
1769
1810
|
this.channelBackground.delete(pubkey)
|
|
1770
1811
|
this.cancelReloadGap(pubkey)
|
|
1771
1812
|
this.cancelLiveRecovery(pubkey)
|
|
@@ -1906,11 +1947,12 @@ export class PrivateMessenger {
|
|
|
1906
1947
|
this.decryptionRetry?.controller.abort(this.pausedError())
|
|
1907
1948
|
this.pauseRevisions.set(reason, (this.pauseRevisions.get(reason) || 0) + 1)
|
|
1908
1949
|
this.sendRoutingPause.abort(this.pausedError())
|
|
1950
|
+
const pausedError = this.pausedError()
|
|
1909
1951
|
this.notifyStatus()
|
|
1910
1952
|
for (const extension of this.extensions) extension.pause?.()
|
|
1911
1953
|
this.recordInterruption(this.desiredChannels)
|
|
1912
|
-
for (const controller of this.recoveryControllers) controller.abort()
|
|
1913
|
-
return Promise.all([this.stopWatches([...this.desiredChannels]), this.flushStateWrites()])
|
|
1954
|
+
for (const controller of this.recoveryControllers) controller.abort(pausedError)
|
|
1955
|
+
return Promise.all([this.stopWatches([...this.desiredChannels], { reason: pausedError }), this.flushStateWrites()])
|
|
1914
1956
|
}
|
|
1915
1957
|
|
|
1916
1958
|
async resume (reason, { waitForBackground = false } = {}) {
|
|
@@ -1931,6 +1973,7 @@ export class PrivateMessenger {
|
|
|
1931
1973
|
clearInterval(this.capacityTimer)
|
|
1932
1974
|
this.capacityTimer = null
|
|
1933
1975
|
this.capacityRequiredBytes = 0
|
|
1976
|
+
this.capacityResumeAtBytes = 0
|
|
1934
1977
|
}
|
|
1935
1978
|
if (this.pauseReasons.size) return
|
|
1936
1979
|
const channels = [...this.desiredChannels]
|
|
@@ -2128,6 +2171,11 @@ export class PrivateMessenger {
|
|
|
2128
2171
|
this.debug('dedupe', debugMessageInfo(type, channelPubkey, message))
|
|
2129
2172
|
return
|
|
2130
2173
|
}
|
|
2174
|
+
if (this.pauseReasons.has('capacity')) throw this.pausedError()
|
|
2175
|
+
const capacity = await this.queue.getCapacity()
|
|
2176
|
+
if (capacity.usedBytes >= inboxCapacityLimits(capacity.maxBytes).highWaterBytes) {
|
|
2177
|
+
throw await this.beginCapacityPressure(capacity)
|
|
2178
|
+
}
|
|
2131
2179
|
const record = {
|
|
2132
2180
|
type,
|
|
2133
2181
|
channelPubkey,
|
|
@@ -2155,14 +2203,11 @@ export class PrivateMessenger {
|
|
|
2155
2203
|
if (!atCapacity && isRecoverableStorageFailure(err)) this.pendingStorageWrites.set(JSON.stringify(dedupeKey || [channelPubkey, type]), { record, dedupeKey, at: message.outer?.created_at || message.event?.created_at })
|
|
2156
2204
|
if (atCapacity) {
|
|
2157
2205
|
await annotateQueueCapacityError(err, 'inbox', () => this.queue.getCapacity())
|
|
2158
|
-
|
|
2206
|
+
this.applyCapacityRecoveryTarget(err)
|
|
2207
|
+
const pause = this.pauseReasons.has('capacity') ? null : this.pause('capacity')
|
|
2159
2208
|
Object.assign(err, { pauseReasons: this.readStatus().pauseReasons })
|
|
2160
|
-
pause
|
|
2161
|
-
this.
|
|
2162
|
-
if (!this.capacityTimer) {
|
|
2163
|
-
this.capacityTimer = setInterval(() => this.checkCapacity().catch(error => this.onError?.(error)), 1000)
|
|
2164
|
-
this.capacityTimer.unref?.()
|
|
2165
|
-
}
|
|
2209
|
+
pause?.catch(error => this.onError?.(error))
|
|
2210
|
+
this.startCapacityMonitor()
|
|
2166
2211
|
} else {
|
|
2167
2212
|
;(isRecoverableStorageFailure(err) ? this.pauseInternally('storage') : this.pause('storage')).catch(error => this.onError?.(error))
|
|
2168
2213
|
}
|
|
@@ -2274,13 +2319,92 @@ export class PrivateMessenger {
|
|
|
2274
2319
|
const work = (async () => {
|
|
2275
2320
|
if (this.closePromise || !this.pauseReasons.has('capacity')) return
|
|
2276
2321
|
const { usedBytes, maxBytes } = await this.queue.getCapacity()
|
|
2277
|
-
|
|
2322
|
+
const resumeAtBytes = this.capacityResumeAtBytes ||
|
|
2323
|
+
Math.min(
|
|
2324
|
+
inboxCapacityLimits(maxBytes).resumeAtBytes,
|
|
2325
|
+
Math.max(0, maxBytes - this.capacityRequiredBytes)
|
|
2326
|
+
)
|
|
2327
|
+
if (!this.closePromise && usedBytes <= resumeAtBytes) await this.resume('capacity')
|
|
2278
2328
|
})()
|
|
2279
2329
|
this.capacityCheck = work
|
|
2280
2330
|
work.then(() => { this.capacityCheck = null }, () => { this.capacityCheck = null })
|
|
2281
2331
|
return work
|
|
2282
2332
|
}
|
|
2283
2333
|
|
|
2334
|
+
applyCapacityRecoveryTarget (capacity) {
|
|
2335
|
+
const limits = inboxCapacityLimits(capacity?.maxBytes)
|
|
2336
|
+
const requiredBytes = Number.isSafeInteger(capacity?.requiredBytes) && capacity.requiredBytes >= 0
|
|
2337
|
+
? capacity.requiredBytes
|
|
2338
|
+
: 0
|
|
2339
|
+
this.capacityRequiredBytes = Math.max(this.capacityRequiredBytes, requiredBytes)
|
|
2340
|
+
this.capacityResumeAtBytes = Math.min(
|
|
2341
|
+
limits.resumeAtBytes,
|
|
2342
|
+
Math.max(0, limits.maxBytes - requiredBytes)
|
|
2343
|
+
)
|
|
2344
|
+
}
|
|
2345
|
+
|
|
2346
|
+
startCapacityMonitor () {
|
|
2347
|
+
if (this.capacityTimer) return
|
|
2348
|
+
this.capacityTimer = setInterval(() => this.checkCapacity().catch(error => this.onError?.(error)), 1000)
|
|
2349
|
+
this.capacityTimer.unref?.()
|
|
2350
|
+
}
|
|
2351
|
+
|
|
2352
|
+
async inboxCapacitySummary () {
|
|
2353
|
+
const buckets = new Map()
|
|
2354
|
+
const channels = new Set()
|
|
2355
|
+
const now = nowSeconds()
|
|
2356
|
+
let count = 0
|
|
2357
|
+
let bytes = 0
|
|
2358
|
+
for await (const item of this.queue.storedItems()) {
|
|
2359
|
+
const type = ['message', 'ask', 'reply', 'tell', 'yell', 'nym'].includes(item?.type) ? item.type : 'other'
|
|
2360
|
+
const receivedAt = Number.isSafeInteger(item?.receivedAt) && item.receivedAt >= 0 ? item.receivedAt : null
|
|
2361
|
+
const ageSeconds = receivedAt == null ? null : Math.max(0, now - receivedAt)
|
|
2362
|
+
let ageBucket = 'unknown'
|
|
2363
|
+
if (ageSeconds != null) {
|
|
2364
|
+
if (ageSeconds < 3600) ageBucket = '<1h'
|
|
2365
|
+
else if (ageSeconds < 86400) ageBucket = '1-24h'
|
|
2366
|
+
else if (ageSeconds < 7 * 86400) ageBucket = '1-7d'
|
|
2367
|
+
else ageBucket = '>7d'
|
|
2368
|
+
}
|
|
2369
|
+
const key = `${type}:${ageBucket}`
|
|
2370
|
+
const itemBytes = encoder.encode(JSON.stringify(item)).length
|
|
2371
|
+
const bucket = buckets.get(key) || { type, ageBucket, count: 0, bytes: 0 }
|
|
2372
|
+
bucket.count++
|
|
2373
|
+
bucket.bytes += itemBytes
|
|
2374
|
+
buckets.set(key, bucket)
|
|
2375
|
+
if (typeof item?.channelPubkey === 'string' && item.channelPubkey) channels.add(item.channelPubkey)
|
|
2376
|
+
count++
|
|
2377
|
+
bytes += itemBytes
|
|
2378
|
+
}
|
|
2379
|
+
return {
|
|
2380
|
+
count,
|
|
2381
|
+
bytes,
|
|
2382
|
+
channelCount: channels.size,
|
|
2383
|
+
buckets: [...buckets.values()].sort((a, b) =>
|
|
2384
|
+
a.type.localeCompare(b.type) || a.ageBucket.localeCompare(b.ageBucket)
|
|
2385
|
+
)
|
|
2386
|
+
}
|
|
2387
|
+
}
|
|
2388
|
+
|
|
2389
|
+
async beginCapacityPressure (capacity) {
|
|
2390
|
+
this.applyCapacityRecoveryTarget(capacity)
|
|
2391
|
+
const pause = this.pauseReasons.has('capacity') ? null : this.pause('capacity')
|
|
2392
|
+
pause?.catch(error => this.onError?.(error))
|
|
2393
|
+
this.startCapacityMonitor()
|
|
2394
|
+
let summary
|
|
2395
|
+
try { summary = await this.inboxCapacitySummary() } catch {}
|
|
2396
|
+
return Object.assign(new Error('PRIVATE_MESSENGER_CAPACITY_PRESSURE'), {
|
|
2397
|
+
code: 'PRIVATE_MESSENGER_CAPACITY_PRESSURE',
|
|
2398
|
+
queue: 'inbox',
|
|
2399
|
+
usedBytes: capacity?.usedBytes,
|
|
2400
|
+
highWaterBytes: inboxCapacityLimits(capacity?.maxBytes).highWaterBytes,
|
|
2401
|
+
resumeAtBytes: this.capacityResumeAtBytes,
|
|
2402
|
+
maxBytes: capacity?.maxBytes,
|
|
2403
|
+
pauseReasons: this.readStatus().pauseReasons,
|
|
2404
|
+
...(summary ? { summary } : {})
|
|
2405
|
+
})
|
|
2406
|
+
}
|
|
2407
|
+
|
|
2284
2408
|
wakeDeliveries () {
|
|
2285
2409
|
for (const wake of this.deliveryWaiters) wake()
|
|
2286
2410
|
this.deliveryWaiters.clear()
|
|
@@ -2790,7 +2914,9 @@ export class PrivateMessenger {
|
|
|
2790
2914
|
if (this.closePromise || !this.channels.has(pubkey) || !this.stopByChannel.has(pubkey)) return
|
|
2791
2915
|
if ((this.watchRevisionByChannel.get(pubkey) || 0) !== revision) return
|
|
2792
2916
|
if (start != null) this.addOfflineRange(pubkey, Math.max(0, start - this.offlineSkewSeconds), nowSeconds())
|
|
2793
|
-
try { await this.recoverOfflineRanges([pubkey]) } catch (err) {
|
|
2917
|
+
try { await this.recoverOfflineRanges([pubkey]) } catch (err) {
|
|
2918
|
+
if (!isExpectedRecoveryPause(err)) this.onError?.(err)
|
|
2919
|
+
}
|
|
2794
2920
|
if (!this.closePromise && !this.pauseReasons.size && this.desiredChannels.has(pubkey) && this.hasPendingRecovery(pubkey)) {
|
|
2795
2921
|
this.scheduleOfflineRecovery(pubkey, { startDelayMs: 1000 })
|
|
2796
2922
|
}
|
|
@@ -2825,6 +2951,7 @@ export class PrivateMessenger {
|
|
|
2825
2951
|
}
|
|
2826
2952
|
|
|
2827
2953
|
async #askSeedersForMissingRangeAttempt (channelPubkey, since, until, { seeders } = {}) {
|
|
2954
|
+
if (this.pauseReasons.size) throw this.pausedError()
|
|
2828
2955
|
if (!this.offlineRecoverySecondsFor(channelPubkey)) return { asks: [], failures: [] }
|
|
2829
2956
|
if (!this.channels.get(channelPubkey)?.signer) return { asks: [], failures: [] }
|
|
2830
2957
|
const candidates = seeders ?? this.recoverySeeders(channelPubkey)
|
|
@@ -2833,6 +2960,7 @@ export class PrivateMessenger {
|
|
|
2833
2960
|
const asks = []
|
|
2834
2961
|
const failures = []
|
|
2835
2962
|
for (const seeder of candidates) {
|
|
2963
|
+
if (this.pauseReasons.size) throw this.pausedError()
|
|
2836
2964
|
try {
|
|
2837
2965
|
const ask = await this.ask({
|
|
2838
2966
|
channelPubkey,
|
|
@@ -3056,7 +3184,12 @@ export class PrivateMessenger {
|
|
|
3056
3184
|
let hedgeTimer = null
|
|
3057
3185
|
let secondStarted = false
|
|
3058
3186
|
const launch = candidate => {
|
|
3187
|
+
if (this.pauseReasons.size || this.closePromise) {
|
|
3188
|
+
return Promise.resolve({ ok: false, relay: candidate.relay, error: this.pausedError() })
|
|
3189
|
+
}
|
|
3059
3190
|
const controller = new AbortController()
|
|
3191
|
+
controller.channelPubkey = channelPubkey
|
|
3192
|
+
this.recoveryControllers.add(controller)
|
|
3060
3193
|
const promise = this._privateChannel
|
|
3061
3194
|
.fetchHistory(this.recoveryFetchOptions({
|
|
3062
3195
|
channelPubkey,
|
|
@@ -3068,6 +3201,7 @@ export class PrivateMessenger {
|
|
|
3068
3201
|
partial: true,
|
|
3069
3202
|
resume: { [candidate.relay]: candidate.pending }
|
|
3070
3203
|
}))
|
|
3204
|
+
.finally(() => this.recoveryControllers.delete(controller))
|
|
3071
3205
|
.then(
|
|
3072
3206
|
history => ({ ok: true, relay: candidate.relay, controller, history }),
|
|
3073
3207
|
error => ({ ok: false, relay: candidate.relay, controller, error })
|
|
@@ -3087,10 +3221,12 @@ export class PrivateMessenger {
|
|
|
3087
3221
|
})
|
|
3088
3222
|
: null
|
|
3089
3223
|
let settled = hedge ? await Promise.race([first, hedge]) : await first
|
|
3224
|
+
if (this.pauseReasons.size || this.closePromise) return null
|
|
3090
3225
|
if (!settled.ok) {
|
|
3091
3226
|
if (secondStarted && launched.length > 1) settled = await launched[launched.length - 1].promise
|
|
3092
3227
|
else if (candidates.length > 1) settled = await launch(candidates[1])
|
|
3093
3228
|
}
|
|
3229
|
+
if (this.pauseReasons.size || this.closePromise) return null
|
|
3094
3230
|
if (!settled.ok) return null
|
|
3095
3231
|
for (const entry of launched) {
|
|
3096
3232
|
if (entry.controller === settled.controller) continue
|
|
@@ -3104,12 +3240,14 @@ export class PrivateMessenger {
|
|
|
3104
3240
|
|
|
3105
3241
|
async askPrioritySeeders (channelPubkey, intervals) {
|
|
3106
3242
|
if (!intervals.length) return []
|
|
3243
|
+
if (this.pauseReasons.size) throw this.pausedError()
|
|
3107
3244
|
if (!await this.checkRecoveryOnline()) return []
|
|
3108
3245
|
const seeders = this.activeRecoverySeeders(channelPubkey)
|
|
3109
3246
|
if (!seeders.length) return []
|
|
3110
3247
|
const failures = []
|
|
3111
3248
|
const claimed = []
|
|
3112
3249
|
for (const interval of mergeRanges(intervals)) {
|
|
3250
|
+
if (this.pauseReasons.size) throw this.pausedError()
|
|
3113
3251
|
const attempt = await this.#askSeedersForMissingRangeAttempt(channelPubkey, interval.start, interval.end, { seeders })
|
|
3114
3252
|
failures.push(...attempt.failures.map(failure => failure.error))
|
|
3115
3253
|
if (!attempt.failures.length) claimed.push(interval)
|
|
@@ -3129,6 +3267,7 @@ export class PrivateMessenger {
|
|
|
3129
3267
|
if (!priorities.length) return
|
|
3130
3268
|
const fetchRelays = await this.resolveWatchRelays(channel)
|
|
3131
3269
|
for (const range of ranges) {
|
|
3270
|
+
if (this.pauseReasons.size || this.closePromise) throw this.pausedError()
|
|
3132
3271
|
const record = this.recoveryRangeRecord(channelPubkey, range)
|
|
3133
3272
|
this.reconcileRecoveryRelays(record, fetchRelays)
|
|
3134
3273
|
const priorityIntervals = intersectRanges(
|
|
@@ -3156,6 +3295,7 @@ export class PrivateMessenger {
|
|
|
3156
3295
|
else this.applyRecoveryCoverage(record, wanted)
|
|
3157
3296
|
}
|
|
3158
3297
|
}
|
|
3298
|
+
if (this.pauseReasons.size || this.closePromise) throw this.pausedError()
|
|
3159
3299
|
const uncovered = intersectRanges(wanted, subtractRanges({ start: range.start, end: range.end }, record.covered))
|
|
3160
3300
|
if (uncovered.length) await this.askPrioritySeeders(channelPubkey, uncovered)
|
|
3161
3301
|
}
|
|
@@ -3184,7 +3324,9 @@ export class PrivateMessenger {
|
|
|
3184
3324
|
const processedRanges = new Set(current.offlineRanges.map(range => `${range.start}:${range.end}`))
|
|
3185
3325
|
|
|
3186
3326
|
if (online) {
|
|
3187
|
-
try { await this.runPriorityLane(pubkey, channel, current.offlineRanges) } catch (error) {
|
|
3327
|
+
try { await this.runPriorityLane(pubkey, channel, current.offlineRanges) } catch (error) {
|
|
3328
|
+
if (!isExpectedRecoveryPause(error)) this.onError?.(error)
|
|
3329
|
+
}
|
|
3188
3330
|
}
|
|
3189
3331
|
|
|
3190
3332
|
const remaining = []
|
|
@@ -3255,12 +3397,13 @@ export class PrivateMessenger {
|
|
|
3255
3397
|
if (result.complete) recoveredThrough = Math.max(recoveredThrough, range.end)
|
|
3256
3398
|
else remaining.push(range)
|
|
3257
3399
|
} catch (err) {
|
|
3400
|
+
const expectedPause = isExpectedRecoveryPause(err, controller)
|
|
3258
3401
|
const record = this.recoveryRanges.get(this.recoveryRangeKey(pubkey, range))
|
|
3259
|
-
if (record && isPermanentRecoveryError(err)) {
|
|
3402
|
+
if (!expectedPause && record && isPermanentRecoveryError(err)) {
|
|
3260
3403
|
for (const state of record.relays.values()) state.dead = true
|
|
3261
3404
|
}
|
|
3262
|
-
if (!(controller.liveInterrupted && err === controller.signal.reason)) this.onError?.(err)
|
|
3263
|
-
failures.push(err)
|
|
3405
|
+
if (!expectedPause && !(controller.liveInterrupted && err === controller.signal.reason)) this.onError?.(err)
|
|
3406
|
+
if (!expectedPause) failures.push(err)
|
|
3264
3407
|
remaining.push(range)
|
|
3265
3408
|
} finally { this.recoveryControllers.delete(controller) }
|
|
3266
3409
|
}
|
|
@@ -147,6 +147,14 @@ no automatic age eviction or synchronization is performed. `close()` releases
|
|
|
147
147
|
connections without deleting pending work. Apps can preserve existing storage by
|
|
148
148
|
passing their established factories, as Zillion does.
|
|
149
149
|
|
|
150
|
+
The private messenger inbox is a durable reject-on-capacity queue. Admission stops
|
|
151
|
+
at 70% of its effective byte limit and resumes only after acknowledgment lowers
|
|
152
|
+
usage to 50%, leaving room for an in-flight history page without evicting pending
|
|
153
|
+
messages. Entering pressure emits one sanitized
|
|
154
|
+
`PRIVATE_MESSENGER_CAPACITY_PRESSURE` event with byte metrics and aggregate
|
|
155
|
+
type/age buckets; it never exposes IDs, pubkeys, filters, ciphertext or payloads.
|
|
156
|
+
Physical `QUEUE_CAPACITY_EXCEEDED` behavior remains unchanged.
|
|
157
|
+
|
|
150
158
|
External recovery factories are owned by their caller and must be closed after
|
|
151
159
|
the session. Work storage opened by the session is closed by the session.
|
|
152
160
|
This is a DM profile; group membership/key derivation is not implemented.
|
|
@@ -53,6 +53,7 @@ export function createQueue ({
|
|
|
53
53
|
|
|
54
54
|
function normalizeEvictionPolicy (policy) {
|
|
55
55
|
if (policy === 'opposite-end' || policy === undefined || policy === null) return 'opposite-end'
|
|
56
|
+
if (policy === 'reject') return 'reject'
|
|
56
57
|
if (policy === 'fifo' || policy === 'head') return 'head'
|
|
57
58
|
if (policy === 'lifo' || policy === 'tail') return 'tail'
|
|
58
59
|
throw new ValidationError('QUEUE_INVALID_EVICTION_POLICY')
|
|
@@ -223,6 +224,12 @@ export function createQueue ({
|
|
|
223
224
|
if (!hasByteLimit()) return state
|
|
224
225
|
const { direction = 'head' } = options
|
|
225
226
|
if (requiredBytes > sessionMaxBytes) throw new Error('QUEUE_ITEM_TOO_LARGE')
|
|
227
|
+
if (configuredEvictionPolicy === 'reject') {
|
|
228
|
+
if (state.usedBytes + requiredBytes > sessionMaxBytes) {
|
|
229
|
+
throw capacityError(requiredBytes, state.usedBytes, sessionMaxBytes)
|
|
230
|
+
}
|
|
231
|
+
return state
|
|
232
|
+
}
|
|
226
233
|
// Make room for the write and retain eviction headroom for the next one.
|
|
227
234
|
const targetBytes = targetBytesAfterWrite(requiredBytes)
|
|
228
235
|
while (state.usedBytes + requiredBytes > targetBytes) {
|
|
@@ -236,7 +243,7 @@ export function createQueue ({
|
|
|
236
243
|
}
|
|
237
244
|
|
|
238
245
|
function recoverByteLimit (state) {
|
|
239
|
-
if (!hasByteLimit()) return state
|
|
246
|
+
if (!hasByteLimit() || configuredEvictionPolicy === 'reject') return state
|
|
240
247
|
return evictToBytes(state, Math.min(sessionMaxBytes, targetBytesAfterWrite(0)), { direction: evictionDirectionFor('recover') })
|
|
241
248
|
}
|
|
242
249
|
|
|
@@ -284,6 +291,7 @@ export function createQueue ({
|
|
|
284
291
|
storage().setItem(key, raw)
|
|
285
292
|
} catch (err) {
|
|
286
293
|
if (!isQuotaExceeded(err) || !hasByteLimit()) throw err
|
|
294
|
+
if (configuredEvictionPolicy === 'reject') throw err
|
|
287
295
|
// Actual browser quota can be lower than the configured logical budget.
|
|
288
296
|
lowerSessionMaxBytes(requiredBytes)
|
|
289
297
|
if (options.evict === false) throw err
|
|
@@ -643,6 +651,10 @@ export function createQueue ({
|
|
|
643
651
|
readState()
|
|
644
652
|
|
|
645
653
|
return {
|
|
654
|
+
getCapacity: () => {
|
|
655
|
+
const state = readState()
|
|
656
|
+
return { usedBytes: state.usedBytes, maxBytes: sessionMaxBytes }
|
|
657
|
+
},
|
|
646
658
|
enqueue: push,
|
|
647
659
|
push,
|
|
648
660
|
pop,
|