libp2r2p 0.12.2 → 0.12.4

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 CHANGED
@@ -296,6 +296,11 @@ Web Lock when available; waits hold neither that lock nor the normal inbox/IDB
296
296
  queues. Fragment assembly survives scheduling boundaries. Pause/close cancel
297
297
  waits; channel removal fences its queued and in-flight results.
298
298
 
299
+ `PRIVATE_MESSENGER_PAUSED` errors include the stable `code` and a copied
300
+ `pauseReasons` array. `QUEUE_CAPACITY_EXCEEDED` errors identify the affected
301
+ `inbox` or `seeds` queue and include bounded `requiredBytes`, `usedBytes` and
302
+ `maxBytes` diagnostics. These fields contain no messages or ciphertext.
303
+
299
304
  Private-channel consumers may opt in
300
305
  with `onDecryptionFailure({ error, record })`, returning true only after durable
301
306
  handling, and replay records with `replayDeferredDecryptions`. Without the hook,
@@ -54,6 +54,15 @@ function byteLength (value) {
54
54
  return encoder.encode(String(value)).length
55
55
  }
56
56
 
57
+ function capacityError (requiredBytes, usedBytes, maxBytes) {
58
+ return Object.assign(new Error('QUEUE_CAPACITY_EXCEEDED'), {
59
+ code: 'QUEUE_CAPACITY_EXCEEDED',
60
+ requiredBytes,
61
+ usedBytes,
62
+ maxBytes
63
+ })
64
+ }
65
+
57
66
  function normalizeEvictionPolicy (policy) {
58
67
  if (policy === 'opposite-end' || policy === undefined || policy === null) return 'opposite-end'
59
68
  if (policy === 'reject') return 'reject'
@@ -471,7 +480,7 @@ export async function createQueue ({
471
480
  if (requiredBytes > sessionMaxBytes) throw new Error('QUEUE_ITEM_TOO_LARGE')
472
481
  if (configuredEvictionPolicy === 'reject') {
473
482
  if (state.usedBytes + requiredBytes > sessionMaxBytes) {
474
- throw Object.assign(new Error('QUEUE_CAPACITY_EXCEEDED'), { requiredBytes, maxBytes: sessionMaxBytes })
483
+ throw capacityError(requiredBytes, state.usedBytes, sessionMaxBytes)
475
484
  }
476
485
  return
477
486
  }
@@ -480,7 +489,7 @@ export async function createQueue ({
480
489
  while (state.usedBytes + requiredBytes > targetBytes) {
481
490
  if (!await evictOne(tx, state, options)) break
482
491
  }
483
- if (state.usedBytes + requiredBytes > sessionMaxBytes) throw new Error('QUEUE_CAPACITY_EXCEEDED')
492
+ if (state.usedBytes + requiredBytes > sessionMaxBytes) throw capacityError(requiredBytes, state.usedBytes, sessionMaxBytes)
484
493
  }
485
494
 
486
495
  async function evictToBytes (tx, state, targetBytes, options = {}) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libp2r2p",
3
- "version": "0.12.2",
3
+ "version": "0.12.4",
4
4
  "description": "Peer-to-relay-to-peer",
5
5
  "keywords": [
6
6
  "p2r2p",
@@ -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 = {
@@ -133,6 +135,57 @@ const SEED_QUEUE_INDEXES = {
133
135
  byChannelTime: ['channelPubkey', SEED_TIME],
134
136
  byTime: SEED_TIME
135
137
  }
138
+
139
+ function isQueueCapacityError (error) {
140
+ return error?.code === 'QUEUE_CAPACITY_EXCEEDED' || error?.message === 'QUEUE_CAPACITY_EXCEEDED'
141
+ }
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
+
170
+ async function annotateQueueCapacityError (error, queue, getCapacity) {
171
+ if (!isQueueCapacityError(error)) return error
172
+ let capacity = {}
173
+ try {
174
+ capacity = await getCapacity?.() || {}
175
+ } catch {
176
+ // Preserve the original queue failure even if a follow-up snapshot fails.
177
+ }
178
+ const value = key => Number.isSafeInteger(error?.[key])
179
+ ? error[key]
180
+ : Number.isSafeInteger(capacity?.[key]) ? capacity[key] : undefined
181
+ return Object.assign(error, {
182
+ code: 'QUEUE_CAPACITY_EXCEEDED',
183
+ queue,
184
+ ...(value('requiredBytes') == null ? {} : { requiredBytes: value('requiredBytes') }),
185
+ ...(value('usedBytes') == null ? {} : { usedBytes: value('usedBytes') }),
186
+ ...(value('maxBytes') == null ? {} : { maxBytes: value('maxBytes') })
187
+ })
188
+ }
136
189
  const encoder = new TextEncoder()
137
190
  const noContentKeys = async () => ({})
138
191
 
@@ -370,6 +423,7 @@ export class PrivateMessenger {
370
423
  this.capacityTimer = null
371
424
  this.capacityCheck = null
372
425
  this.capacityRequiredBytes = 0
426
+ this.capacityResumeAtBytes = 0
373
427
  this.reloadGapTimers = new Map()
374
428
  this.liveInterruptions = new Map()
375
429
  this.liveRecoveryTimers = new Map()
@@ -467,6 +521,11 @@ export class PrivateMessenger {
467
521
  indexedDB: this._indexedDB
468
522
  })
469
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
+ }
470
529
  this.startStorageMaintenance()
471
530
  this.state = { channels: await this.stateStore.load() }
472
531
  await this.update({ userSigner, contentKeySigner, nymSigner: this.nymSigner, channels, relays, mode })
@@ -680,7 +739,9 @@ export class PrivateMessenger {
680
739
  this.touchStorageActivity().catch(err => this.onError?.(err))
681
740
  const run = this.queueOperationTail.then(operation)
682
741
  this.queueOperationTail = run.catch(err => {
683
- try { this.onError?.(err) } catch {}
742
+ if (!isPausedError(err)) {
743
+ try { this.onError?.(err) } catch {}
744
+ }
684
745
  })
685
746
  return run
686
747
  }
@@ -1251,7 +1312,9 @@ export class PrivateMessenger {
1251
1312
  receivedChunkTtlMs: this.receivedChunkTtlMsFor(channel),
1252
1313
  receivedChunkIndexedDB: this._indexedDB,
1253
1314
  onSubscriptionState: state => this.handleSubscriptionState(pubkey, state),
1254
- onError: err => this.onError?.(err)
1315
+ onError: err => {
1316
+ if (!isExpectedRecoveryPause(err)) this.onError?.(err)
1317
+ }
1255
1318
  })
1256
1319
  } catch (error) {
1257
1320
  if (signal?.aborted) continue
@@ -1664,6 +1727,7 @@ export class PrivateMessenger {
1664
1727
  }
1665
1728
 
1666
1729
  async finalizeRecoveryRange ({ channelPubkey, range, record }) {
1730
+ if (this.pauseReasons.size) throw this.pausedError()
1667
1731
  if (!await this.checkRecoveryOnline()) return { complete: false, failures: [], offline: true }
1668
1732
  const uncovered = subtractRanges({ start: range.start, end: range.end }, record.covered)
1669
1733
  const oldest = record.oldestCreatedAt
@@ -1675,6 +1739,7 @@ export class PrivateMessenger {
1675
1739
  const seedRanges = mergeRanges([...uncovered, ...leftEdge])
1676
1740
  const failures = []
1677
1741
  for (const seedRange of seedRanges) {
1742
+ if (this.pauseReasons.size) throw this.pausedError()
1678
1743
  const attempt = await this.#askSeedersForMissingRangeAttempt(channelPubkey, seedRange.start, seedRange.end)
1679
1744
  failures.push(...attempt.failures.map(failure => failure.error))
1680
1745
  }
@@ -1738,10 +1803,10 @@ export class PrivateMessenger {
1738
1803
  this.writeState(state)
1739
1804
  }
1740
1805
 
1741
- stopWatches (channels = [...this.stopByChannel.keys()]) {
1806
+ stopWatches (channels = [...this.stopByChannel.keys()], { reason } = {}) {
1742
1807
  const closing = []
1743
1808
  for (const pubkey of channels) {
1744
- this.channelBackground.get(pubkey)?.controller.abort()
1809
+ this.channelBackground.get(pubkey)?.controller.abort(reason)
1745
1810
  this.channelBackground.delete(pubkey)
1746
1811
  this.cancelReloadGap(pubkey)
1747
1812
  this.cancelLiveRecovery(pubkey)
@@ -1788,7 +1853,10 @@ export class PrivateMessenger {
1788
1853
  }
1789
1854
 
1790
1855
  pausedError () {
1791
- return Object.assign(new Error('PRIVATE_MESSENGER_PAUSED'), { pauseReasons: this.readStatus().pauseReasons })
1856
+ return Object.assign(new Error('PRIVATE_MESSENGER_PAUSED'), {
1857
+ code: 'PRIVATE_MESSENGER_PAUSED',
1858
+ pauseReasons: this.readStatus().pauseReasons
1859
+ })
1792
1860
  }
1793
1861
 
1794
1862
  recoveryTask (attempt, { network = false, retryable = isRecoverableStorageFailure } = {}) {
@@ -1879,11 +1947,12 @@ export class PrivateMessenger {
1879
1947
  this.decryptionRetry?.controller.abort(this.pausedError())
1880
1948
  this.pauseRevisions.set(reason, (this.pauseRevisions.get(reason) || 0) + 1)
1881
1949
  this.sendRoutingPause.abort(this.pausedError())
1950
+ const pausedError = this.pausedError()
1882
1951
  this.notifyStatus()
1883
1952
  for (const extension of this.extensions) extension.pause?.()
1884
1953
  this.recordInterruption(this.desiredChannels)
1885
- for (const controller of this.recoveryControllers) controller.abort()
1886
- 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()])
1887
1956
  }
1888
1957
 
1889
1958
  async resume (reason, { waitForBackground = false } = {}) {
@@ -1904,6 +1973,7 @@ export class PrivateMessenger {
1904
1973
  clearInterval(this.capacityTimer)
1905
1974
  this.capacityTimer = null
1906
1975
  this.capacityRequiredBytes = 0
1976
+ this.capacityResumeAtBytes = 0
1907
1977
  }
1908
1978
  if (this.pauseReasons.size) return
1909
1979
  const channels = [...this.desiredChannels]
@@ -2101,6 +2171,11 @@ export class PrivateMessenger {
2101
2171
  this.debug('dedupe', debugMessageInfo(type, channelPubkey, message))
2102
2172
  return
2103
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
+ }
2104
2179
  const record = {
2105
2180
  type,
2106
2181
  channelPubkey,
@@ -2124,15 +2199,17 @@ export class PrivateMessenger {
2124
2199
  }
2125
2200
  this.recordInterruption([channelPubkey], message.outer?.created_at || message.event?.created_at || nowSeconds())
2126
2201
  // Do not await stop from inside its own transport callback.
2127
- const atCapacity = err.message === 'QUEUE_CAPACITY_EXCEEDED'
2202
+ const atCapacity = isQueueCapacityError(err)
2128
2203
  if (!atCapacity && isRecoverableStorageFailure(err)) this.pendingStorageWrites.set(JSON.stringify(dedupeKey || [channelPubkey, type]), { record, dedupeKey, at: message.outer?.created_at || message.event?.created_at })
2129
- ;(atCapacity ? this.pause('capacity') : isRecoverableStorageFailure(err) ? this.pauseInternally('storage') : this.pause('storage')).catch(error => this.onError?.(error))
2130
2204
  if (atCapacity) {
2131
- this.capacityRequiredBytes = Math.max(this.capacityRequiredBytes, err.requiredBytes || 0)
2132
- if (!this.capacityTimer) {
2133
- this.capacityTimer = setInterval(() => this.checkCapacity().catch(error => this.onError?.(error)), 1000)
2134
- this.capacityTimer.unref?.()
2135
- }
2205
+ await annotateQueueCapacityError(err, 'inbox', () => this.queue.getCapacity())
2206
+ this.applyCapacityRecoveryTarget(err)
2207
+ const pause = this.pauseReasons.has('capacity') ? null : this.pause('capacity')
2208
+ Object.assign(err, { pauseReasons: this.readStatus().pauseReasons })
2209
+ pause?.catch(error => this.onError?.(error))
2210
+ this.startCapacityMonitor()
2211
+ } else {
2212
+ ;(isRecoverableStorageFailure(err) ? this.pauseInternally('storage') : this.pause('storage')).catch(error => this.onError?.(error))
2136
2213
  }
2137
2214
  await this.flushStateWrites()
2138
2215
  throw err
@@ -2165,7 +2242,12 @@ export class PrivateMessenger {
2165
2242
  }
2166
2243
  return
2167
2244
  }
2168
- return this.runSeedQueueOperation(() => this.enqueueQueueSeed(channelPubkey, seed))
2245
+ try {
2246
+ return await this.runSeedQueueOperation(() => this.enqueueQueueSeed(channelPubkey, seed))
2247
+ } catch (error) {
2248
+ await annotateQueueCapacityError(error, 'seeds', () => this.seedQueue?.getCapacity?.())
2249
+ throw error
2250
+ }
2169
2251
  }
2170
2252
 
2171
2253
  async enqueueQueueSeed (channelPubkey, seed) {
@@ -2237,13 +2319,92 @@ export class PrivateMessenger {
2237
2319
  const work = (async () => {
2238
2320
  if (this.closePromise || !this.pauseReasons.has('capacity')) return
2239
2321
  const { usedBytes, maxBytes } = await this.queue.getCapacity()
2240
- if (!this.closePromise && usedBytes + this.capacityRequiredBytes <= maxBytes) await this.resume('capacity')
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')
2241
2328
  })()
2242
2329
  this.capacityCheck = work
2243
2330
  work.then(() => { this.capacityCheck = null }, () => { this.capacityCheck = null })
2244
2331
  return work
2245
2332
  }
2246
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
+
2247
2408
  wakeDeliveries () {
2248
2409
  for (const wake of this.deliveryWaiters) wake()
2249
2410
  this.deliveryWaiters.clear()
@@ -2753,7 +2914,9 @@ export class PrivateMessenger {
2753
2914
  if (this.closePromise || !this.channels.has(pubkey) || !this.stopByChannel.has(pubkey)) return
2754
2915
  if ((this.watchRevisionByChannel.get(pubkey) || 0) !== revision) return
2755
2916
  if (start != null) this.addOfflineRange(pubkey, Math.max(0, start - this.offlineSkewSeconds), nowSeconds())
2756
- try { await this.recoverOfflineRanges([pubkey]) } catch (err) { this.onError?.(err) }
2917
+ try { await this.recoverOfflineRanges([pubkey]) } catch (err) {
2918
+ if (!isExpectedRecoveryPause(err)) this.onError?.(err)
2919
+ }
2757
2920
  if (!this.closePromise && !this.pauseReasons.size && this.desiredChannels.has(pubkey) && this.hasPendingRecovery(pubkey)) {
2758
2921
  this.scheduleOfflineRecovery(pubkey, { startDelayMs: 1000 })
2759
2922
  }
@@ -2788,6 +2951,7 @@ export class PrivateMessenger {
2788
2951
  }
2789
2952
 
2790
2953
  async #askSeedersForMissingRangeAttempt (channelPubkey, since, until, { seeders } = {}) {
2954
+ if (this.pauseReasons.size) throw this.pausedError()
2791
2955
  if (!this.offlineRecoverySecondsFor(channelPubkey)) return { asks: [], failures: [] }
2792
2956
  if (!this.channels.get(channelPubkey)?.signer) return { asks: [], failures: [] }
2793
2957
  const candidates = seeders ?? this.recoverySeeders(channelPubkey)
@@ -2796,6 +2960,7 @@ export class PrivateMessenger {
2796
2960
  const asks = []
2797
2961
  const failures = []
2798
2962
  for (const seeder of candidates) {
2963
+ if (this.pauseReasons.size) throw this.pausedError()
2799
2964
  try {
2800
2965
  const ask = await this.ask({
2801
2966
  channelPubkey,
@@ -3019,7 +3184,12 @@ export class PrivateMessenger {
3019
3184
  let hedgeTimer = null
3020
3185
  let secondStarted = false
3021
3186
  const launch = candidate => {
3187
+ if (this.pauseReasons.size || this.closePromise) {
3188
+ return Promise.resolve({ ok: false, relay: candidate.relay, error: this.pausedError() })
3189
+ }
3022
3190
  const controller = new AbortController()
3191
+ controller.channelPubkey = channelPubkey
3192
+ this.recoveryControllers.add(controller)
3023
3193
  const promise = this._privateChannel
3024
3194
  .fetchHistory(this.recoveryFetchOptions({
3025
3195
  channelPubkey,
@@ -3031,6 +3201,7 @@ export class PrivateMessenger {
3031
3201
  partial: true,
3032
3202
  resume: { [candidate.relay]: candidate.pending }
3033
3203
  }))
3204
+ .finally(() => this.recoveryControllers.delete(controller))
3034
3205
  .then(
3035
3206
  history => ({ ok: true, relay: candidate.relay, controller, history }),
3036
3207
  error => ({ ok: false, relay: candidate.relay, controller, error })
@@ -3050,10 +3221,12 @@ export class PrivateMessenger {
3050
3221
  })
3051
3222
  : null
3052
3223
  let settled = hedge ? await Promise.race([first, hedge]) : await first
3224
+ if (this.pauseReasons.size || this.closePromise) return null
3053
3225
  if (!settled.ok) {
3054
3226
  if (secondStarted && launched.length > 1) settled = await launched[launched.length - 1].promise
3055
3227
  else if (candidates.length > 1) settled = await launch(candidates[1])
3056
3228
  }
3229
+ if (this.pauseReasons.size || this.closePromise) return null
3057
3230
  if (!settled.ok) return null
3058
3231
  for (const entry of launched) {
3059
3232
  if (entry.controller === settled.controller) continue
@@ -3067,12 +3240,14 @@ export class PrivateMessenger {
3067
3240
 
3068
3241
  async askPrioritySeeders (channelPubkey, intervals) {
3069
3242
  if (!intervals.length) return []
3243
+ if (this.pauseReasons.size) throw this.pausedError()
3070
3244
  if (!await this.checkRecoveryOnline()) return []
3071
3245
  const seeders = this.activeRecoverySeeders(channelPubkey)
3072
3246
  if (!seeders.length) return []
3073
3247
  const failures = []
3074
3248
  const claimed = []
3075
3249
  for (const interval of mergeRanges(intervals)) {
3250
+ if (this.pauseReasons.size) throw this.pausedError()
3076
3251
  const attempt = await this.#askSeedersForMissingRangeAttempt(channelPubkey, interval.start, interval.end, { seeders })
3077
3252
  failures.push(...attempt.failures.map(failure => failure.error))
3078
3253
  if (!attempt.failures.length) claimed.push(interval)
@@ -3092,6 +3267,7 @@ export class PrivateMessenger {
3092
3267
  if (!priorities.length) return
3093
3268
  const fetchRelays = await this.resolveWatchRelays(channel)
3094
3269
  for (const range of ranges) {
3270
+ if (this.pauseReasons.size || this.closePromise) throw this.pausedError()
3095
3271
  const record = this.recoveryRangeRecord(channelPubkey, range)
3096
3272
  this.reconcileRecoveryRelays(record, fetchRelays)
3097
3273
  const priorityIntervals = intersectRanges(
@@ -3119,6 +3295,7 @@ export class PrivateMessenger {
3119
3295
  else this.applyRecoveryCoverage(record, wanted)
3120
3296
  }
3121
3297
  }
3298
+ if (this.pauseReasons.size || this.closePromise) throw this.pausedError()
3122
3299
  const uncovered = intersectRanges(wanted, subtractRanges({ start: range.start, end: range.end }, record.covered))
3123
3300
  if (uncovered.length) await this.askPrioritySeeders(channelPubkey, uncovered)
3124
3301
  }
@@ -3147,7 +3324,9 @@ export class PrivateMessenger {
3147
3324
  const processedRanges = new Set(current.offlineRanges.map(range => `${range.start}:${range.end}`))
3148
3325
 
3149
3326
  if (online) {
3150
- try { await this.runPriorityLane(pubkey, channel, current.offlineRanges) } catch (error) { this.onError?.(error) }
3327
+ try { await this.runPriorityLane(pubkey, channel, current.offlineRanges) } catch (error) {
3328
+ if (!isExpectedRecoveryPause(error)) this.onError?.(error)
3329
+ }
3151
3330
  }
3152
3331
 
3153
3332
  const remaining = []
@@ -3218,12 +3397,13 @@ export class PrivateMessenger {
3218
3397
  if (result.complete) recoveredThrough = Math.max(recoveredThrough, range.end)
3219
3398
  else remaining.push(range)
3220
3399
  } catch (err) {
3400
+ const expectedPause = isExpectedRecoveryPause(err, controller)
3221
3401
  const record = this.recoveryRanges.get(this.recoveryRangeKey(pubkey, range))
3222
- if (record && isPermanentRecoveryError(err)) {
3402
+ if (!expectedPause && record && isPermanentRecoveryError(err)) {
3223
3403
  for (const state of record.relays.values()) state.dead = true
3224
3404
  }
3225
- if (!(controller.liveInterrupted && err === controller.signal.reason)) this.onError?.(err)
3226
- failures.push(err)
3405
+ if (!expectedPause && !(controller.liveInterrupted && err === controller.signal.reason)) this.onError?.(err)
3406
+ if (!expectedPause) failures.push(err)
3227
3407
  remaining.push(range)
3228
3408
  } finally { this.recoveryControllers.delete(controller) }
3229
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.
@@ -38,6 +38,15 @@ export function createQueue ({
38
38
  return encoder.encode(String(value)).length
39
39
  }
40
40
 
41
+ function capacityError (requiredBytes, usedBytes, maxBytes) {
42
+ return Object.assign(new Error('QUEUE_CAPACITY_EXCEEDED'), {
43
+ code: 'QUEUE_CAPACITY_EXCEEDED',
44
+ requiredBytes,
45
+ usedBytes,
46
+ maxBytes
47
+ })
48
+ }
49
+
41
50
  function hasByteLimit () {
42
51
  return Number.isFinite(sessionMaxBytes)
43
52
  }
@@ -222,7 +231,7 @@ export function createQueue ({
222
231
  : evictOneFromHead(state, options)
223
232
  if (!evicted) break
224
233
  }
225
- if (state.usedBytes + requiredBytes > sessionMaxBytes) throw new Error('QUEUE_CAPACITY_EXCEEDED')
234
+ if (state.usedBytes + requiredBytes > sessionMaxBytes) throw capacityError(requiredBytes, state.usedBytes, sessionMaxBytes)
226
235
  return state
227
236
  }
228
237
 
@@ -291,7 +300,7 @@ export function createQueue ({
291
300
  if (hasByteLimit() && stored.byteSize > sessionMaxBytes) throw new Error('QUEUE_ITEM_TOO_LARGE')
292
301
  if (delta > 0) {
293
302
  if (options.evict === false) {
294
- if (hasByteLimit() && state.usedBytes + delta > sessionMaxBytes) throw new Error('QUEUE_CAPACITY_EXCEEDED')
303
+ if (hasByteLimit() && state.usedBytes + delta > sessionMaxBytes) throw capacityError(delta, state.usedBytes, sessionMaxBytes)
295
304
  } else {
296
305
  evictToFit(state, delta, options)
297
306
  }