libp2r2p 0.12.3 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libp2r2p",
3
- "version": "0.12.3",
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 = {
@@ -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
- try { this.onError?.(err) } catch {}
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 => this.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
- const pause = this.pause('capacity')
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.catch(error => this.onError?.(error))
2161
- this.capacityRequiredBytes = Math.max(this.capacityRequiredBytes, err.requiredBytes || 0)
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
- 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')
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) { this.onError?.(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) { this.onError?.(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.