libp2r2p 0.12.16 → 0.12.17

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
@@ -269,6 +269,11 @@ evidence, while startup, resume and routine reconciliation retain normal retries
269
269
  Success enters the normal acknowledged inbox before removing the pending item.
270
270
  The session coordinator forwards this API.
271
271
 
272
+ Messenger initialization and storage maintenance also perform a bounded cleanup
273
+ of historical suspended records. Only `INVALID_MAC` packets with at least three
274
+ MAC attempts and an outer timestamp older than 30 days are removed, at most 100
275
+ per run. Recent MAC failures and every `CONTENT_KEY_NOT_FOUND` packet are kept.
276
+
272
277
  Pending recovery waits for 250 ms without channel setup, live/history processing
273
278
  or publication activity. Session foreground persistence/publication also delays
274
279
  it. After at most five seconds of eligible waiting, a busy channel may advance
@@ -438,6 +443,13 @@ An invalid or asynchronous resolver result is reported as
438
443
  remote payload fields should only permit fields to lower priority; a peer must
439
444
  not be able to promote itself by supplying a value.
440
445
 
446
+ Protocol recovery messages enforce the same rule inside the messenger, even when
447
+ an application resolver returns `normal` or another higher class. Seeder presence
448
+ is always `lowest`; missing-message asks and replies accept only the additive
449
+ payload values `lower` or `lowest`, while malformed or promoting values remain
450
+ `normal`. Application resolvers can lower those protocol classes but cannot
451
+ raise them.
452
+
441
453
  ### Inbound peer admission
442
454
 
443
455
  `PrivateMessenger` accepts an optional synchronous
@@ -735,6 +747,13 @@ messages. Applications still supply signers and desired channels on reopening;
735
747
  storage is scoped by origin and user pubkey, not the transient session ID.
736
748
  Failed ingestion or incomplete relay fetch reports never complete the gap.
737
749
 
750
+ `deferColdRecovery` is opt-in and defaults to `false`. The session coordinator
751
+ enables it so reopening many stored conversations first fetches only the recent
752
+ six-hour tail and leaves the rest of the persisted range pending. A later
753
+ `prioritizeRange()` request schedules the foreground recovery pass immediately;
754
+ ordinary live watches remain active throughout, and local conversation summaries
755
+ do not wait for the cold range to finish.
756
+
738
757
  `init()` and `createPrivateMessenger()` resolve after local preparation. Likewise,
739
758
  `update(options, { waitForBackground = false })` and
740
759
  `resume(reason, { waitForBackground = false })` wait for valid local channel
@@ -794,6 +813,11 @@ process-local: they expire after `priorityTtlMs` (ten minutes) or once covered,
794
813
  and clear with channel/recovery state. Presence payloads and persisted ranges
795
814
  are unchanged.
796
815
 
816
+ With deferred cold recovery, the background recent-tail probe is sent as
817
+ `lower`; app-directed ranges remain `normal`. Missing-message replies inherit
818
+ the ask's additive priority, defaulting to `lower`, and all recovery traffic uses
819
+ bulk pacing unless explicitly `normal`.
820
+
797
821
  `private-channel.fetchHistory(options)` (0.11.6) is the complete-interval API
798
822
  used by messenger recovery. It accepts the signers, processor/fragment options,
799
823
  callbacks and abort signal of `fetch`, plus inclusive `since`/`until` bounds
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libp2r2p",
3
- "version": "0.12.16",
3
+ "version": "0.12.17",
4
4
  "description": "Peer-to-relay-to-peer",
5
5
  "keywords": [
6
6
  "p2r2p",
@@ -212,6 +212,9 @@ export function createPrivateMessageSession ({ _setTimeout = setTimeout, _clearT
212
212
  let requestSequence = 0
213
213
  const watchRequests = new Map()
214
214
  let identity
215
+ let rebuildScheduled = false
216
+ let rebuildOptions
217
+ let rebuildWaiters = []
215
218
  const receivedChunkScope = globalThis.crypto.randomUUID()
216
219
  let subscribe = privateChannel.subscribe
217
220
  function assertWatching (channelPubkey) {
@@ -553,6 +556,27 @@ export function createPrivateMessageSession ({ _setTimeout = setTimeout, _clearT
553
556
  return Promise.allSettled(closing)
554
557
  }
555
558
 
559
+ function scheduleSubscriptionRebuild (options = {}) {
560
+ rebuildOptions = { ...(rebuildOptions || {}), ...options }
561
+ const result = new Promise((resolve, reject) => rebuildWaiters.push({ resolve, reject }))
562
+ if (rebuildScheduled) return result
563
+ rebuildScheduled = true
564
+ Promise.resolve().then(async () => {
565
+ rebuildScheduled = false
566
+ const current = rebuildOptions || {}
567
+ const waiters = rebuildWaiters
568
+ rebuildOptions = undefined
569
+ rebuildWaiters = []
570
+ try {
571
+ const value = await rebuildSubscriptions(current)
572
+ for (const waiter of waiters) waiter.resolve(value)
573
+ } catch (error) {
574
+ for (const waiter of waiters) waiter.reject(error)
575
+ }
576
+ })
577
+ return result
578
+ }
579
+
556
580
  async function watch ({
557
581
  channels,
558
582
  relays,
@@ -581,6 +605,7 @@ export function createPrivateMessageSession ({ _setTimeout = setTimeout, _clearT
581
605
  ignoredGroupTtlMs,
582
606
  ignoredGroupMaxEntries,
583
607
  since = nowSeconds(),
608
+ _onWatchScheduled,
584
609
  _subscribe = privateChannel.subscribe
585
610
  }) {
586
611
  if (!relays?.length) throw new ValidationError('NO_RELAYS')
@@ -640,7 +665,8 @@ export function createPrivateMessageSession ({ _setTimeout = setTimeout, _clearT
640
665
  watchesByChannel.set(channel, next)
641
666
  }
642
667
 
643
- await rebuildSubscriptions({ _subscribe })
668
+ _onWatchScheduled?.()
669
+ await scheduleSubscriptionRebuild({ _subscribe })
644
670
  return () => {
645
671
  const owned = channelList.filter(channel => watchRequests.get(channel) === request)
646
672
  return unwatch(owned)
@@ -653,7 +679,7 @@ export function createPrivateMessageSession ({ _setTimeout = setTimeout, _clearT
653
679
  watchRequests.set(channel, ++requestSequence)
654
680
  watchesByChannel.delete(channel)
655
681
  }
656
- return rebuildSubscriptions({ gracefulClose: false })
682
+ return scheduleSubscriptionRebuild({ gracefulClose: false })
657
683
  }
658
684
 
659
685
  function clearChannelState (channelPubkey) {
@@ -51,6 +51,7 @@ function body (type, row) {
51
51
  })
52
52
  add('payload', payload[0]); add('key', envelope[1])
53
53
  if (envelope.length > 2) add('iykc', ...envelope.slice(2))
54
+ if (row.rowHash) add('row', hex(row.rowHash))
54
55
  if (row.innerEventId) add('event', hex(row.innerEventId))
55
56
  const first = integer(row.firstSeenAt ?? row.router.created_at), last = integer(row.lastSeenAt ?? row.router.created_at)
56
57
  if (first > last) fail()
@@ -114,6 +115,7 @@ export function decodeRecord (event) {
114
115
  row.payloadRow = JSON.stringify(one('payload'))
115
116
  const envelope = [row.receiverPubkey, ...one('key'), ...(one('iykc', false) || [])]
116
117
  row.row = JSON.stringify(envelope); row.iykcPubkey = envelope[2] || ''
118
+ row.rowHash = one('row', false)?.[0] || ''
117
119
  row.innerEventId = one('event', false)?.[0] || ''
118
120
  const file = one('file', false)
119
121
  if (file) Object.assign(row, { controlChannelPubkey: file[0], peerPubkey: file[1], root: file[2], fileChannelPubkey: row.channelPubkey, chunkIndex: integer(row.router.tags.find(t => t[0] === 'i')?.[1]), receivedAt: integer(one('received')[0]) })
@@ -134,6 +134,29 @@ export function createPersonalCopyRecoveryStorage ({ eventStore, signer, now = n
134
134
  }
135
135
  }
136
136
  }
137
+ async function existingLogicalRows (rows) {
138
+ const byHash = new Map()
139
+ const logicalKey = row => row.rowHash ? `${row.channelPubkey}:${row.receiverPubkey || ''}:${row.rowHash}` : ''
140
+ for (const row of rows) {
141
+ if (row.rowHash) byHash.set(row.rowHash, row)
142
+ }
143
+ if (!byHash.size) return new Map()
144
+ const hashes = [...byHash.keys()]
145
+ const mirrors = new Map(await Promise.all(hashes.map(async hash => [await mirror('row', hash), hash])))
146
+ const found = new Map()
147
+ for (const batch of chunks([...mirrors.keys()])) {
148
+ const filter = await exactFilterFor('seed')
149
+ filter['#o'] = batch
150
+ for await (const wrapper of pages(eventStore, filter)) {
151
+ const expiry = Number(wrapper.tags?.find(tag => Array.isArray(tag) && tag[0] === 'expiration')?.[1])
152
+ if (!Number.isSafeInteger(expiry) || expiry <= now()) continue
153
+ const { row } = await read(wrapper)
154
+ const hash = mirrors.get(wrapper.tags?.find(tag => Array.isArray(tag) && tag[0] === 'o' && mirrors.has(tag[1]))?.[1])
155
+ if (hash && logicalKey(byHash.get(hash)) === logicalKey(row)) found.set(hash, row)
156
+ }
157
+ }
158
+ return found
159
+ }
137
160
  function store (type) {
138
161
  async function putMany (rows, options = {}) {
139
162
  return serializeMutation(eventStore, () => putManyNow(rows, options))
@@ -154,7 +177,22 @@ export function createPersonalCopyRecoveryStorage ({ eventStore, signer, now = n
154
177
  if (record) stored.set(recordId, { ...record.row, recordId })
155
178
  }
156
179
  }
157
- const existingCount = stored.size
180
+ let existingCount = stored.size
181
+ if (type === 'seed') {
182
+ const pendingRows = [...unique.entries()]
183
+ .filter(([recordId]) => !stored.has(recordId))
184
+ .map(([, record]) => record.row)
185
+ const logical = await existingLogicalRows(pendingRows)
186
+ for (const [recordId, record] of unique) {
187
+ if (stored.has(recordId) || !record.row.rowHash) continue
188
+ const hash = record.row.rowHash
189
+ if (logical.has(hash) && logical.get(hash).channelPubkey === record.row.channelPubkey &&
190
+ (logical.get(hash).receiverPubkey || '') === (record.row.receiverPubkey || '')) {
191
+ stored.set(recordId, logical.get(hash))
192
+ }
193
+ }
194
+ existingCount = stored.size
195
+ }
158
196
  let insertedCount = 0
159
197
  let blockedCount = 0
160
198
  for (const [recordId, record] of unique) {
@@ -316,6 +316,7 @@ export class PrivateMessenger {
316
316
  priorityTtlMs = DEFAULT_PRIORITY_TTL_MS,
317
317
  priorityHedgeDelayMs = DEFAULT_PRIORITY_HEDGE_DELAY_MS,
318
318
  priorityHedgeRelays = DEFAULT_PRIORITY_HEDGE_RELAYS,
319
+ deferColdRecovery = false,
319
320
  maxDynamicRecoverySeeders = DEFAULT_MAX_DYNAMIC_RECOVERY_SEEDERS,
320
321
  messageQueueMaxBytes = DEFAULT_MESSAGE_QUEUE_MAX_BYTES,
321
322
  seedQueueMaxBytes = DEFAULT_SEED_QUEUE_MAX_BYTES,
@@ -386,6 +387,8 @@ export class PrivateMessenger {
386
387
  this.priorityHedgeRelays = Number.isSafeInteger(hedgeRelays) && hedgeRelays >= 1
387
388
  ? Math.min(hedgeRelays, 3)
388
389
  : DEFAULT_PRIORITY_HEDGE_RELAYS
390
+ if (typeof deferColdRecovery !== 'boolean') throw new ValidationError('INVALID_DEFER_COLD_RECOVERY')
391
+ this.deferColdRecovery = deferColdRecovery
389
392
  this.maxDynamicRecoverySeeders = maxDynamicRecoverySeeders
390
393
  this.messageQueueMaxBytes = messageQueueMaxBytes
391
394
  this.seedQueueMaxBytes = seedQueueMaxBytes
@@ -476,6 +479,8 @@ export class PrivateMessenger {
476
479
  this.liveInterruptions = new Map()
477
480
  this.liveRecoveryTimers = new Map()
478
481
  this.subscriptionDebugKeys = new Set()
482
+ this.channelDebugRefs = new Map()
483
+ this.nextChannelDebugRef = 0
479
484
  this.watchRevisionByChannel = new Map()
480
485
  this.presenceTimers = new Map()
481
486
  this.presenceJobs = new Map()
@@ -555,6 +560,7 @@ export class PrivateMessenger {
555
560
  prefix: this.prefix, indexedDB: this._indexedDB,
556
561
  report: detail => this.debug('pending-decryption', detail)
557
562
  })
563
+ try { await this.pendingDecryption.cleanupSuspended?.() } catch (error) { this.onError?.(error) }
558
564
  this.seedQueue = this.seedStorage
559
565
  ? null
560
566
  : await createQueue({
@@ -741,6 +747,7 @@ export class PrivateMessenger {
741
747
  })
742
748
  await this.refreshAndApplyStoragePolicy()
743
749
  await this.cleanupStaleChannels()
750
+ try { await this.pendingDecryption?.cleanupSuspended?.() } catch (error) { this.onError?.(error) }
744
751
  await this.pruneStoredSeeds()
745
752
  })().catch(err => {
746
753
  try { this.onError?.(err) } catch {}
@@ -823,6 +830,15 @@ export class PrivateMessenger {
823
830
  this.debug(action, detail)
824
831
  }
825
832
 
833
+ channelDebugRef (pubkey) {
834
+ let ref = this.channelDebugRefs.get(pubkey)
835
+ if (!ref) {
836
+ ref = `channel-${++this.nextChannelDebugRef}`
837
+ this.channelDebugRefs.set(pubkey, ref)
838
+ }
839
+ return ref
840
+ }
841
+
826
842
  debugSend (method, channelPubkey, detail = {}) {
827
843
  const receiverPubkeys = uniq(detail.receiverPubkeys || (detail.receiverPubkey ? [detail.receiverPubkey] : []))
828
844
  this.debug('send', {
@@ -900,7 +916,10 @@ export class PrivateMessenger {
900
916
 
901
917
  if (removedPubkeys.length) {
902
918
  await this.stampChannelActivity(removedPubkeys)
903
- for (const pubkey of removedPubkeys) this.dropRecoveryState(pubkey)
919
+ for (const pubkey of removedPubkeys) {
920
+ this.dropRecoveryState(pubkey)
921
+ this.channelDebugRefs.delete(pubkey)
922
+ }
904
923
  }
905
924
 
906
925
  const storageSnapshot = await activatePrivateMessengerStorage({
@@ -1318,7 +1337,7 @@ export class PrivateMessenger {
1318
1337
  this.writeState(state)
1319
1338
  }
1320
1339
 
1321
- async watch (channels = [...this.channels.keys()], { scheduleReloadGap = true, signal } = {}) {
1340
+ async watch (channels = [...this.channels.keys()], { scheduleReloadGap = true, signal, _onWatchScheduled } = {}) {
1322
1341
  this.assertOpen()
1323
1342
  const channelPubkeys = uniq(channels)
1324
1343
  for (const pubkey of channelPubkeys) {
@@ -1334,6 +1353,12 @@ export class PrivateMessenger {
1334
1353
  for (const pubkey of channelPubkeys) {
1335
1354
  const channel = this.channels.get(pubkey)
1336
1355
  if (!channel) throw new ValidationError('UNKNOWN_CHANNEL')
1356
+ const channelRef = this.channelDebugRef(pubkey)
1357
+ this.debug('prepare-start', {
1358
+ channelRef,
1359
+ mode: channel.mode,
1360
+ seederCount: channel.seeders.length
1361
+ })
1337
1362
  const revision = (this.watchRevisionByChannel.get(pubkey) || 0) + 1
1338
1363
  this.watchRevisionByChannel.set(pubkey, revision)
1339
1364
  // Persist the pending interval before live delivery can advance lastSeenAt.
@@ -1375,6 +1400,7 @@ export class PrivateMessenger {
1375
1400
  receivedChunkTtlMs: this.receivedChunkTtlMsFor(channel),
1376
1401
  receivedChunkIndexedDB: this._indexedDB,
1377
1402
  onSubscriptionState: state => this.handleSubscriptionState(pubkey, state),
1403
+ _onWatchScheduled,
1378
1404
  onError: err => {
1379
1405
  if (!isExpectedRecoveryPause(err)) this.onError?.(err)
1380
1406
  }
@@ -1419,8 +1445,8 @@ export class PrivateMessenger {
1419
1445
  seeders: channel.seeders,
1420
1446
  offlineRecoverySeconds: channel.offlineRecoverySeconds
1421
1447
  })
1422
- this.debug('watch', {
1423
- channelPubkey: pubkey,
1448
+ this.debug('watch-ready', {
1449
+ channelRef,
1424
1450
  relays: watchRelays,
1425
1451
  mode: channel.mode,
1426
1452
  seeders: channel.seeders,
@@ -1454,6 +1480,7 @@ export class PrivateMessenger {
1454
1480
  this.addOfflineRange(pubkey, Math.max(0, start - this.offlineSkewSeconds), nowSeconds())
1455
1481
  const diagnosticRelay = safeDiagnosticRelay(relay)
1456
1482
  this.debugOnce(`subscription-interrupted:${diagnosticRelay || ''}:${start}:${safeDiagnosticToken(error?.code) || ''}`, 'subscription-interrupted', {
1483
+ channelRef: this.channelDebugRef(pubkey),
1457
1484
  relay: diagnosticRelay,
1458
1485
  rangeStart: start,
1459
1486
  ...subscriptionErrorDiagnostic(error)
@@ -1469,6 +1496,7 @@ export class PrivateMessenger {
1469
1496
  interrupted.delete(relay)
1470
1497
  if (!interrupted.size) this.liveInterruptions.delete(pubkey)
1471
1498
  this.debugOnce(`subscription-recovered:${safeDiagnosticRelay(relay) || ''}:${start}`, 'subscription-recovered', {
1499
+ channelRef: this.channelDebugRef(pubkey),
1472
1500
  relay: safeDiagnosticRelay(relay),
1473
1501
  rangeStart: start,
1474
1502
  rangeEnd: until,
@@ -1657,6 +1685,9 @@ export class PrivateMessenger {
1657
1685
  entries.push({ start, end, type, createdAt, expiresAt: createdAt + ttl })
1658
1686
  this.recoveryPriority.set(channelPubkey, entries)
1659
1687
  }
1688
+ if (this.deferColdRecovery && this.stopByChannel.has(channelPubkey) && !this.pauseReasons.size) {
1689
+ this.scheduleOfflineRecovery(channelPubkey, { startDelayMs: 0 })
1690
+ }
1660
1691
  return true
1661
1692
  }
1662
1693
 
@@ -2098,11 +2129,20 @@ export class PrivateMessenger {
2098
2129
  const work = Promise.resolve().then(async () => {
2099
2130
  if (!this.initialized) await this.initSettledPromise
2100
2131
  if (!active()) return
2101
- const release = await this.channelSetupAdmission.acquire(controller.signal)
2132
+ let release = await this.channelSetupAdmission.acquire(controller.signal)
2133
+ const releaseSetup = () => {
2134
+ const current = release
2135
+ release = null
2136
+ current?.()
2137
+ }
2102
2138
  try {
2103
2139
  if (!active()) return
2104
- await this.watch([pubkey], { scheduleReloadGap: !recover, signal: controller.signal })
2105
- } finally { release() }
2140
+ await this.watch([pubkey], {
2141
+ scheduleReloadGap: !recover,
2142
+ signal: controller.signal,
2143
+ _onWatchScheduled: releaseSetup
2144
+ })
2145
+ } finally { releaseSetup() }
2106
2146
  if (!active()) return
2107
2147
  phase = 'presence'
2108
2148
  if (doesModeStoreRecoverySeeds(channel.mode)) await this.startPresencePublisher(pubkey)
@@ -2281,7 +2321,8 @@ export class PrivateMessenger {
2281
2321
  }
2282
2322
 
2283
2323
  #deliveryPriority (type, channelPubkey, message) {
2284
- if (!this.resolveInboundPriority) return DELIVERY_PRIORITY.normal
2324
+ const protocolPriority = protocolDeliveryPriority(message)
2325
+ if (!this.resolveInboundPriority) return protocolPriority
2285
2326
  let resolved
2286
2327
  try {
2287
2328
  resolved = this.resolveInboundPriority(
@@ -2293,14 +2334,14 @@ export class PrivateMessenger {
2293
2334
  }
2294
2335
  } catch (cause) {
2295
2336
  this.onError?.(inboundPriorityError(cause))
2296
- return DELIVERY_PRIORITY.normal
2337
+ return protocolPriority
2297
2338
  }
2298
- if (resolved == null) return DELIVERY_PRIORITY.normal
2339
+ if (resolved == null) return protocolPriority
2299
2340
  if (typeof resolved === 'string' && DELIVERY_PRIORITY_NAMES.has(resolved)) {
2300
- return DELIVERY_PRIORITY[resolved]
2341
+ return Math.min(protocolPriority, DELIVERY_PRIORITY[resolved])
2301
2342
  }
2302
2343
  this.onError?.(inboundPriorityError(new ValidationError('INVALID_INBOUND_PRIORITY')))
2303
- return DELIVERY_PRIORITY.normal
2344
+ return protocolPriority
2304
2345
  }
2305
2346
 
2306
2347
  #coalescingMetadata (type, channelPubkey, message, info) {
@@ -2493,7 +2534,10 @@ export class PrivateMessenger {
2493
2534
  this.markSeen(channelPubkey, message.outer?.created_at || message.event?.created_at || nowSeconds())
2494
2535
  this.wakeDeliveries()
2495
2536
  if (!record.coalescingKey || coalesced?.status === 'inserted') {
2496
- this.debug('enqueue', debugMessageInfo(type, channelPubkey, message))
2537
+ this.debug('message-received', {
2538
+ channelRef: this.channelDebugRef(channelPubkey),
2539
+ ...debugMessageInfo(type, channelPubkey, message)
2540
+ })
2497
2541
  }
2498
2542
  this.onMessageQueued?.()
2499
2543
  }
@@ -3236,10 +3280,28 @@ export class PrivateMessenger {
3236
3280
  if (this.closePromise || !this.channels.has(pubkey) || !this.stopByChannel.has(pubkey)) return
3237
3281
  if ((this.watchRevisionByChannel.get(pubkey) || 0) !== revision) return
3238
3282
  if (start != null) this.addOfflineRange(pubkey, Math.max(0, start - this.offlineSkewSeconds), nowSeconds())
3239
- try { await this.recoverOfflineRanges([pubkey]) } catch (err) {
3283
+ const priority = this.recoveryPriorities(pubkey)
3284
+ const backgroundOnly = this.deferColdRecovery && priority.length === 0
3285
+ if (backgroundOnly) {
3286
+ const ranges = this.readState().channels[pubkey]?.offlineRanges || []
3287
+ const range = ranges.toSorted((left, right) => right.end - left.end)[0]
3288
+ if (range) {
3289
+ const end = Math.min(range.end, nowSeconds())
3290
+ const entry = {
3291
+ start: Math.max(range.start, end - this.priorityTailSeconds),
3292
+ end,
3293
+ type: 'tail',
3294
+ background: true,
3295
+ createdAt: Date.now(),
3296
+ expiresAt: Date.now() + this.priorityTtlMs
3297
+ }
3298
+ this.recoveryPriority.set(pubkey, [entry])
3299
+ }
3300
+ }
3301
+ try { await this.recoverOfflineRanges([pubkey], { priorityOnly: backgroundOnly }) } catch (err) {
3240
3302
  if (!isExpectedRecoveryPause(err)) this.onError?.(err)
3241
3303
  }
3242
- if (!this.closePromise && !this.pauseReasons.size && this.desiredChannels.has(pubkey) && this.hasPendingRecovery(pubkey)) {
3304
+ if (!backgroundOnly && !this.closePromise && !this.pauseReasons.size && this.desiredChannels.has(pubkey) && this.hasPendingRecovery(pubkey)) {
3243
3305
  this.scheduleOfflineRecovery(pubkey, { startDelayMs: 1000 })
3244
3306
  }
3245
3307
  }, this.reloadGapDelayMs)
@@ -3267,12 +3329,12 @@ export class PrivateMessenger {
3267
3329
  }
3268
3330
  }
3269
3331
 
3270
- async askSeedersForMissingRange (channelPubkey, since, until) {
3271
- const { asks } = await this.#askSeedersForMissingRangeAttempt(channelPubkey, since, until)
3332
+ async askSeedersForMissingRange (channelPubkey, since, until, { priority = 'lower' } = {}) {
3333
+ const { asks } = await this.#askSeedersForMissingRangeAttempt(channelPubkey, since, until, { priority })
3272
3334
  return asks
3273
3335
  }
3274
3336
 
3275
- async #askSeedersForMissingRangeAttempt (channelPubkey, since, until, { seeders } = {}) {
3337
+ async #askSeedersForMissingRangeAttempt (channelPubkey, since, until, { seeders, priority = 'lower' } = {}) {
3276
3338
  if (this.pauseReasons.size) throw this.pausedError()
3277
3339
  if (!this.offlineRecoverySecondsFor(channelPubkey)) return { asks: [], failures: [] }
3278
3340
  if (!this.channels.get(channelPubkey)?.signer) return { asks: [], failures: [] }
@@ -3288,8 +3350,12 @@ export class PrivateMessenger {
3288
3350
  channelPubkey,
3289
3351
  receiverPubkey: seeder,
3290
3352
  code: MISSING_MESSAGES_ASK_CODE,
3291
- payload: { since, until },
3292
- useBulkPacing: true
3353
+ payload: {
3354
+ since,
3355
+ until,
3356
+ ...(priority === 'normal' ? {} : { priority })
3357
+ },
3358
+ useBulkPacing: priority !== 'normal'
3293
3359
  })
3294
3360
  asks.push(ask)
3295
3361
  await assertMessagePublished(ask, ask.question)
@@ -3323,12 +3389,16 @@ export class PrivateMessenger {
3323
3389
  const payload = isPlainObject(message.payload?.payload) ? message.payload.payload : {}
3324
3390
  const since = Number.isFinite(payload.since) ? payload.since : undefined
3325
3391
  const until = Number.isFinite(payload.until) ? payload.until : undefined
3392
+ const priority = payload.priority === 'lower' || payload.priority === 'lowest'
3393
+ ? payload.priority
3394
+ : 'normal'
3326
3395
  const packer = this.createMissingMessageReplyPacker({
3327
3396
  channelPubkey,
3328
3397
  question: message.event,
3329
3398
  receiverPubkey: message.event?.pubkey,
3330
3399
  since,
3331
3400
  until,
3401
+ priority,
3332
3402
  sendEmptyReply: !this.offlineRecoverySecondsFor(channelPubkey)
3333
3403
  })
3334
3404
 
@@ -3456,13 +3526,13 @@ export class PrivateMessenger {
3456
3526
  }
3457
3527
  }
3458
3528
 
3459
- async recoverOfflineRanges (channels = [...this.stopByChannel.keys()]) {
3529
+ async recoverOfflineRanges (channels = [...this.stopByChannel.keys()], { priorityOnly = false } = {}) {
3460
3530
  const failures = []
3461
3531
  for (const pubkey of uniq(channels)) {
3462
3532
  if (this.pauseReasons.size || this.closePromise || !this.desiredChannels.has(pubkey)) continue
3463
3533
  let work = this.recoveries.get(pubkey)
3464
3534
  if (!work) {
3465
- work = this.recoverChannelRanges([pubkey])
3535
+ work = this.recoverChannelRanges([pubkey], { priorityOnly })
3466
3536
  this.recoveries.set(pubkey, work)
3467
3537
  }
3468
3538
  try { failures.push(...await work) } finally { if (this.recoveries.get(pubkey) === work) this.recoveries.delete(pubkey) }
@@ -3561,7 +3631,7 @@ export class PrivateMessenger {
3561
3631
  }
3562
3632
  }
3563
3633
 
3564
- async askPrioritySeeders (channelPubkey, intervals) {
3634
+ async askPrioritySeeders (channelPubkey, intervals, { priority = 'normal' } = {}) {
3565
3635
  if (!intervals.length) return []
3566
3636
  if (this.pauseReasons.size) throw this.pausedError()
3567
3637
  if (!await this.checkRecoveryOnline()) return []
@@ -3571,7 +3641,10 @@ export class PrivateMessenger {
3571
3641
  const claimed = []
3572
3642
  for (const interval of mergeRanges(intervals)) {
3573
3643
  if (this.pauseReasons.size) throw this.pausedError()
3574
- const attempt = await this.#askSeedersForMissingRangeAttempt(channelPubkey, interval.start, interval.end, { seeders })
3644
+ const attempt = await this.#askSeedersForMissingRangeAttempt(channelPubkey, interval.start, interval.end, {
3645
+ seeders,
3646
+ priority
3647
+ })
3575
3648
  failures.push(...attempt.failures.map(failure => failure.error))
3576
3649
  if (!attempt.failures.length) claimed.push(interval)
3577
3650
  }
@@ -3588,6 +3661,13 @@ export class PrivateMessenger {
3588
3661
  async runPriorityLane (channelPubkey, channel, ranges) {
3589
3662
  const priorities = this.recoveryPriorities(channelPubkey)
3590
3663
  if (!priorities.length) return
3664
+ const windowsFor = background => mergeRanges(
3665
+ priorities
3666
+ .filter(entry => Boolean(entry.background) === background)
3667
+ .map(entry => ({ start: entry.start, end: entry.end }))
3668
+ )
3669
+ const normalWindows = windowsFor(false)
3670
+ const backgroundWindows = windowsFor(true)
3591
3671
  const fetchRelays = await this.resolveWatchRelays(channel)
3592
3672
  for (const range of ranges) {
3593
3673
  if (this.pauseReasons.size || this.closePromise) throw this.pausedError()
@@ -3619,13 +3699,19 @@ export class PrivateMessenger {
3619
3699
  }
3620
3700
  }
3621
3701
  if (this.pauseReasons.size || this.closePromise) throw this.pausedError()
3622
- const uncovered = intersectRanges(wanted, subtractRanges({ start: range.start, end: range.end }, record.covered))
3623
- if (uncovered.length) await this.askPrioritySeeders(channelPubkey, uncovered)
3702
+ const currentUncovered = () => intersectRanges(
3703
+ wanted,
3704
+ subtractRanges({ start: range.start, end: range.end }, record.covered)
3705
+ )
3706
+ const normalUncovered = intersectRanges(currentUncovered(), normalWindows)
3707
+ if (normalUncovered.length) await this.askPrioritySeeders(channelPubkey, normalUncovered, { priority: 'normal' })
3708
+ const backgroundUncovered = intersectRanges(currentUncovered(), backgroundWindows)
3709
+ if (backgroundUncovered.length) await this.askPrioritySeeders(channelPubkey, backgroundUncovered, { priority: 'lower' })
3624
3710
  }
3625
3711
  this.prunePriorityEntries(channelPubkey)
3626
3712
  }
3627
3713
 
3628
- async recoverChannelRanges (channels) {
3714
+ async recoverChannelRanges (channels, { priorityOnly = false } = {}) {
3629
3715
  const failures = []
3630
3716
  const state = this.readState()
3631
3717
  const now = nowSeconds()
@@ -3652,6 +3738,8 @@ export class PrivateMessenger {
3652
3738
  }
3653
3739
  }
3654
3740
 
3741
+ if (priorityOnly) continue
3742
+
3655
3743
  const remaining = []
3656
3744
  let recoveredThrough = current.recoveredThrough || 0
3657
3745
  for (const range of current.offlineRanges) {
@@ -3716,8 +3804,15 @@ export class PrivateMessenger {
3716
3804
  continue
3717
3805
  }
3718
3806
  const recoveryStartedAt = this._now()
3807
+ this.debug('range-recovery-start', {
3808
+ channelRef: this.channelDebugRef(pubkey),
3809
+ rangeStart: range.start,
3810
+ rangeEnd: range.end,
3811
+ tier: record.tier || 'bulk'
3812
+ })
3719
3813
  const result = await this.finalizeRecoveryRange({ channelPubkey: pubkey, range, record })
3720
3814
  this.debug('recovery-range-complete', {
3815
+ channelRef: this.channelDebugRef(pubkey),
3721
3816
  rangeStart: range.start,
3722
3817
  rangeEnd: range.end,
3723
3818
  complete: result.complete === true,
@@ -3759,6 +3854,7 @@ export class PrivateMessenger {
3759
3854
  await this._privateMessage.clearChannelState?.(pubkey)
3760
3855
  this.dropRecoveryState(pubkey)
3761
3856
  return this.runQueueOperation(async () => {
3857
+ this.channelDebugRefs.delete(pubkey)
3762
3858
  this.channels.delete(pubkey)
3763
3859
  this.decryptionReadyChannels?.delete(pubkey)
3764
3860
  this.removeChannelState(pubkey)
@@ -4226,6 +4322,18 @@ function inboundPriorityError (cause) {
4226
4322
  })
4227
4323
  }
4228
4324
 
4325
+ function protocolDeliveryPriority (message) {
4326
+ const code = message?.payload?.code
4327
+ if (code === SEEDER_PRESENCE_CODE) return DELIVERY_PRIORITY.lowest
4328
+ if (code !== MISSING_MESSAGES_ASK_CODE && code !== MISSING_MESSAGES_REPLY_CODE) {
4329
+ return DELIVERY_PRIORITY.normal
4330
+ }
4331
+ const priority = message?.payload?.payload?.priority
4332
+ return priority === 'lower' || priority === 'lowest'
4333
+ ? DELIVERY_PRIORITY[priority]
4334
+ : DELIVERY_PRIORITY.normal
4335
+ }
4336
+
4229
4337
  function safeDiagnosticToken (value) {
4230
4338
  return typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9:._-]{0,159}$/.test(value)
4231
4339
  ? value
@@ -12,6 +12,7 @@ export const NYM_CARRIER_SEED_RECORD_TYPE = 'nymCarrier_v1'
12
12
 
13
13
  export const DEFAULT_REPLY_BYTES_PER_CHUNK = 128 * 1024
14
14
  const DEFAULT_EVENTS_PER_CHUNK = 100
15
+ const RECOVERY_PRIORITIES = new Set(['normal', 'lower', 'lowest'])
15
16
  const encoder = new TextEncoder()
16
17
  const decoder = new TextDecoder()
17
18
  const HASH_PUBKEY = '0'.repeat(64)
@@ -113,6 +114,7 @@ export function compactSeedRouterRows (seed = {}) {
113
114
  const parsed = parseRouterRow(row)
114
115
  if (!parsed?.receiverPubkey) continue
115
116
  const innerEventId = innerEventIdsByRowIndex[index] || innerEventIdsByRowIndex[String(index)] || ''
117
+ const hash = rowHash(payloadRow, row)
116
118
  rows.push({
117
119
  type: 'seed',
118
120
  recordType: ROUTER_SEED_RECORD_TYPE,
@@ -120,7 +122,7 @@ export function compactSeedRouterRows (seed = {}) {
120
122
  receiverPubkey: parsed.receiverPubkey,
121
123
  iykcPubkey: parsed.iykcPubkey,
122
124
  innerEventId,
123
- rowHash: innerEventId ? '' : rowHash(payloadRow, row),
125
+ rowHash: hash,
124
126
  payloadRow,
125
127
  row,
126
128
  firstSeenAt: createdAt,
@@ -137,7 +139,7 @@ export function routerSeedRowKey (seed = {}) {
137
139
  return [
138
140
  seed.channelPubkey || '',
139
141
  seed.receiverPubkey || row?.receiverPubkey || '',
140
- innerEventId ? `event:${innerEventId}` : `row:${fallbackRowHash}`
142
+ fallbackRowHash ? `row:${fallbackRowHash}` : innerEventId ? `event:${innerEventId}` : ''
141
143
  ].join(':')
142
144
  }
143
145
 
@@ -314,10 +316,11 @@ export function createMissingMessageReplyPacker ({
314
316
  receiverPubkey = question?.pubkey,
315
317
  since,
316
318
  until,
319
+ priority = 'lower',
317
320
  eventsPerChunk = DEFAULT_EVENTS_PER_CHUNK,
318
321
  bytesPerChunk = DEFAULT_REPLY_BYTES_PER_CHUNK,
319
322
  sendEmptyReply = false,
320
- useBulkPacing = true,
323
+ useBulkPacing,
321
324
  idempotencyKey
322
325
  }) {
323
326
  if (!messenger?.reply) throw new ValidationError('MESSENGER_REQUIRED')
@@ -325,6 +328,8 @@ export function createMissingMessageReplyPacker ({
325
328
  if (!receiverPubkey) throw new ValidationError('RECEIVER_PUBKEY_REQUIRED')
326
329
  if (!Number.isSafeInteger(eventsPerChunk) || eventsPerChunk < 1) throw new ValidationError('INVALID_EVENTS_PER_CHUNK')
327
330
  if (!Number.isSafeInteger(bytesPerChunk) || bytesPerChunk < 1) throw new ValidationError('INVALID_BYTES_PER_CHUNK')
331
+ if (!RECOVERY_PRIORITIES.has(priority)) throw new ValidationError('INVALID_RECOVERY_PRIORITY')
332
+ if (useBulkPacing !== undefined && typeof useBulkPacing !== 'boolean') throw new ValidationError('INVALID_USE_BULK_PACING')
328
333
  idempotencyKey ||= `${MISSING_MESSAGES_REPLY_CODE}:${question.id}`
329
334
 
330
335
  const range = backfillRequestRange(question, since, until)
@@ -334,11 +339,15 @@ export function createMissingMessageReplyPacker ({
334
339
  question,
335
340
  receiverPubkey,
336
341
  code: MISSING_MESSAGES_REPLY_CODE,
337
- payload: { since: range.since, until: range.until },
342
+ payload: {
343
+ since: range.since,
344
+ until: range.until,
345
+ ...(priority === 'normal' ? {} : { priority })
346
+ },
338
347
  eventsPerChunk,
339
348
  bytesPerChunk,
340
349
  sendEmptyReply,
341
- useBulkPacing,
350
+ useBulkPacing: useBulkPacing ?? priority !== 'normal',
342
351
  idempotencyKey,
343
352
  recordsFromInput: seed => compactRecordsFromSeed(seed, { receiverPubkey, since: range.since, until: range.until })
344
353
  })
@@ -2,6 +2,7 @@ import { sha256 } from '@noble/hashes/sha2.js'
2
2
  import { bytesToHex } from '../../base16/index.js'
3
3
  import { base64ToBytes } from '../../base64/index.js'
4
4
  import { createQueue } from '../../idb-queue/index.js'
5
+ import { ValidationError } from '../../error/index.js'
5
6
  import { isDeferredDecryptionError } from '../../private-channel/helpers/decryption-error.js'
6
7
 
7
8
  const encoder = new TextEncoder()
@@ -9,6 +10,8 @@ const decoder = new TextDecoder()
9
10
  const HEX64 = /^[0-9a-f]{64}$/i
10
11
  const CONTENT_KEY_FIELDS = ['receiverPubkey', 'ownContentPubkey', 'peerContentPubkey']
11
12
  export const PENDING_DECRYPTION_MAX_BYTES = 16 * 1024 * 1024
13
+ export const PENDING_DECRYPTION_CLEANUP_MAX_AGE_SECONDS = 30 * 24 * 60 * 60
14
+ export const PENDING_DECRYPTION_CLEANUP_LIMIT = 100
12
15
 
13
16
  function storedBytes (item) {
14
17
  let byteSize = 0
@@ -180,6 +183,37 @@ export async function createPendingDecryption ({ prefix, indexedDB, maxBytes = P
180
183
  }
181
184
  })
182
185
  },
186
+ cleanupSuspended ({
187
+ now = Math.floor(Date.now() / 1000),
188
+ maxAgeSeconds = PENDING_DECRYPTION_CLEANUP_MAX_AGE_SECONDS,
189
+ limit = PENDING_DECRYPTION_CLEANUP_LIMIT
190
+ } = {}) {
191
+ if (!Number.isSafeInteger(now) || now < 0 ||
192
+ !Number.isSafeInteger(maxAgeSeconds) || maxAgeSeconds < 0 ||
193
+ !Number.isSafeInteger(limit) || limit <= 0) {
194
+ return Promise.reject(new ValidationError('INVALID_PENDING_DECRYPTION_CLEANUP_OPTIONS'))
195
+ }
196
+ return serial(async () => {
197
+ const selected = []
198
+ for await (const item of queue.storedItems()) {
199
+ const createdAt = item?.packet?.outer?.created_at ?? item?.outer?.created_at
200
+ if (item.code !== 'INVALID_MAC' || item.macAttempts < 3 ||
201
+ !Number.isSafeInteger(createdAt) || createdAt >= now - maxAgeSeconds) continue
202
+ selected.push(item.id)
203
+ if (selected.length >= limit) break
204
+ }
205
+ for (const id of selected) await queue.removeBy('byId', id)
206
+ if (selected.length) {
207
+ notify('cleaned', {
208
+ reason: 'suspended-age',
209
+ code: 'INVALID_MAC',
210
+ count: selected.length,
211
+ maxAgeSeconds
212
+ })
213
+ }
214
+ return selected.length
215
+ })
216
+ },
183
217
  clearChannel: channel => serial(() => queue.removeBy('byChannel', channel)),
184
218
  async close () { await tail; flush(); await queue.close() }
185
219
  }
@@ -259,6 +259,7 @@ export function createPrivateMessageSession ({ owner, signer, eventStore, messag
259
259
  try {
260
260
  candidate = await Messenger({
261
261
  fallbackRelays, fallbackDelayMs, pendingDecryptionReady, seedStorage, _pendingSeedRecords: () => journal.pendingRows(), userSigner, channels: [], useContentKeys, _waitForForeground: foreground.wait, _observeForeground: foreground.observe,
262
+ deferColdRecovery: true,
262
263
  onMessageQueued: () => { if (messengerBinding === binding) return drain() },
263
264
  onStateChanged: state => {
264
265
  if (closed || messengerBinding !== binding) return