libp2r2p 0.12.15 → 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
@@ -415,6 +420,36 @@ Coalescing does not provide an ingress rate limit or per-peer quota. Exact
415
420
  event deduplication, authorization, quarantine, global inbox capacity,
416
421
  pause/ACK/NACK ownership and existing storage policy remain independent.
417
422
 
423
+ ### Inbound delivery priority
424
+
425
+ `PrivateMessenger` accepts an optional synchronous
426
+ `resolveInboundPriority(message, context)` callback. The callback returns
427
+ `"normal"`, `"lower"`, `"lowest"` or `null`; `normal` is the default. The
428
+ resolved class is stored as internal IndexedDB queue metadata, is included in
429
+ the coalescing comparator, and is removed before delivery to the app. Existing
430
+ records without priority are backfilled as `normal` during messenger
431
+ initialization.
432
+
433
+ Queue reservation selects `normal` before `lower` before `lowest` through the
434
+ `byDeliveryPriority` index, preserving FIFO within each class and never
435
+ interrupting an active reservation. Capacity
436
+ pressure blocks new inbox admission but does not block reservation,
437
+ acknowledgment or NACK of records already persisted. `onMessageQueued` is
438
+ called when capacity pressure begins and after the queue changes in a way that
439
+ can wake a durable consumer.
440
+
441
+ An invalid or asynchronous resolver result is reported as
442
+ `INVALID_INBOUND_PRIORITY` and falls back to `normal`. Callers that interpret
443
+ remote payload fields should only permit fields to lower priority; a peer must
444
+ not be able to promote itself by supplying a value.
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
+
418
453
  ### Inbound peer admission
419
454
 
420
455
  `PrivateMessenger` accepts an optional synchronous
@@ -712,6 +747,13 @@ messages. Applications still supply signers and desired channels on reopening;
712
747
  storage is scoped by origin and user pubkey, not the transient session ID.
713
748
  Failed ingestion or incomplete relay fetch reports never complete the gap.
714
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
+
715
757
  `init()` and `createPrivateMessenger()` resolve after local preparation. Likewise,
716
758
  `update(options, { waitForBackground = false })` and
717
759
  `resume(reason, { waitForBackground = false })` wait for valid local channel
@@ -771,6 +813,11 @@ process-local: they expire after `priorityTtlMs` (ten minutes) or once covered,
771
813
  and clear with channel/recovery state. Presence payloads and persisted ranges
772
814
  are unchanged.
773
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
+
774
821
  `private-channel.fetchHistory(options)` (0.11.6) is the complete-interval API
775
822
  used by messenger recovery. It accepts the signers, processor/fragment options,
776
823
  callbacks and abort signal of `fetch`, plus inclusive `since`/`until` bounds
@@ -1310,7 +1357,7 @@ Opening a reject-policy queue under a smaller budget preserves existing items.
1310
1357
  Positional replacement and insertion follow the same rule: they reject instead
1311
1358
  of evicting when the resulting queue would exceed the limit.
1312
1359
 
1313
- `queue.reserve({ leaseMs = 30000, nackCoalescingIndex })` returns `null` or
1360
+ `queue.reserve({ leaseMs = 30000, nackCoalescingIndex, priorityIndex, priorities })` returns `null` or
1314
1361
  `{ item, ack, nack, renew }`. Reservation token/deadline are internal record
1315
1362
  metadata, persisted atomically in the same IndexedDB transaction as selection.
1316
1363
  `renew()` extends a still-valid lease. Low-level callers own renewal and release;
@@ -1319,6 +1366,15 @@ position-shifting queue operations on the same queue except explicit removal.
1319
1366
  A stale token cannot acknowledge a newly reserved or replaced record.
1320
1367
  `nackCoalescingIndex` names a non-unique index: when another matching item is
1321
1368
  pending, NACK deletes the superseded active item instead of requeueing it.
1369
+ `priorityIndex` names a scalar, non-multiEntry index and `priorities` is the
1370
+ ordered list of index keys to try. Within a lane, an index cursor starts at the
1371
+ smallest queue `position`, so FIFO is preserved without reading the rest of the
1372
+ queue into memory. Duplicate priority values are ignored. Missing index values
1373
+ are not candidates; callers migrating an existing queue must backfill them.
1374
+ Invalid selectors reject with `QUEUE_PRIORITY_INDEX_INVALID`,
1375
+ `QUEUE_PRIORITY_VALUES_INVALID` or `QUEUE_PRIORITY_VALUE_INVALID`. Without a
1376
+ priority index, reservation uses a FIFO primary-key cursor. This extension
1377
+ belongs only to `idb-queue`.
1322
1378
 
1323
1379
  `queue.getCapacity()` is part of the common API and returns
1324
1380
  `{ usedBytes, maxBytes }`; capacity rejections also expose `requiredBytes` and
@@ -441,6 +441,18 @@ export async function createQueue ({
441
441
  return (await p.promise).result
442
442
  }
443
443
 
444
+ async function firstEligibleRecord (tx, { indexName = null, query = [], now }) {
445
+ const p = deferred()
446
+ const args = indexName ? [query, 'next'] : [undefined, 'next']
447
+ let cursor = (await run('openCursor', args, ITEMS_STORE, indexName, { tx, p })).result
448
+ while (cursor) {
449
+ const record = cursor.value
450
+ if (!record.reservation || record.reservation.until <= now) return record
451
+ cursor = await nextCursor(cursor, p)
452
+ }
453
+ return null
454
+ }
455
+
444
456
  async function storedRecordAtEnd (tx, state, direction, excludedPositions = new Set()) {
445
457
  // Queue positions are the object-store primary key, so an end cursor finds
446
458
  // an eviction candidate without reading every queued record into memory.
@@ -886,7 +898,9 @@ export async function createQueue ({
886
898
  async function reserve ({
887
899
  leaseMs = 30000,
888
900
  now = Date.now(),
889
- nackCoalescingIndex
901
+ nackCoalescingIndex,
902
+ priorityIndex,
903
+ priorities
890
904
  } = {}) {
891
905
  if (!Number.isSafeInteger(leaseMs) || leaseMs <= 0 || !Number.isSafeInteger(now) || now < 0) throw new ValidationError('QUEUE_INVALID_LEASE')
892
906
  const nackDefinition = nackCoalescingIndex == null ? null : indexDefinition(nackCoalescingIndex)
@@ -894,20 +908,41 @@ export async function createQueue ({
894
908
  (!nackDefinition || nackDefinition.unique || nackDefinition.multiEntry)) {
895
909
  throw new ValidationError('QUEUE_NACK_COALESCE_INDEX_INVALID')
896
910
  }
911
+ const priorityDefinition = priorityIndex == null ? null : indexDefinition(priorityIndex)
912
+ if (priorityIndex != null && (!priorityDefinition || priorityDefinition.multiEntry)) {
913
+ throw new ValidationError('QUEUE_PRIORITY_INDEX_INVALID')
914
+ }
915
+ if (priorityDefinition && (!Array.isArray(priorities) || priorities.length === 0)) {
916
+ throw new ValidationError('QUEUE_PRIORITY_VALUES_INVALID')
917
+ }
918
+ if (!priorityDefinition && priorities != null) {
919
+ throw new ValidationError('QUEUE_PRIORITY_INDEX_REQUIRED')
920
+ }
921
+ const orderedPriorities = []
922
+ for (const value of priorities || []) {
923
+ assertValidIndexKey(value, 'QUEUE_PRIORITY_VALUE_INVALID')
924
+ if (orderedPriorities.some(existing => indexedDB.cmp(existing, value) === 0)) continue
925
+ orderedPriorities.push(value)
926
+ }
897
927
  const token = globalThis.crypto.randomUUID()
898
928
  const reserved = await mutate(async tx => {
899
- const p = deferred()
900
- let cursor = (await run('openCursor', [], ITEMS_STORE, null, { tx, p })).result
901
- while (cursor) {
902
- const record = cursor.value
903
- if (!record.reservation || record.reservation.until <= now) {
904
- record.reservation = { token, until: now + leaseMs }
905
- await putRecord(tx, record)
906
- return record
929
+ let candidate = null
930
+ if (priorityDefinition) {
931
+ for (const value of orderedPriorities) {
932
+ candidate = await firstEligibleRecord(tx, {
933
+ indexName: priorityIndex,
934
+ query: value,
935
+ now
936
+ })
937
+ if (candidate) break
907
938
  }
908
- cursor = await nextCursor(cursor, p)
939
+ } else {
940
+ candidate = await firstEligibleRecord(tx, { now })
909
941
  }
910
- return null
942
+ if (!candidate) return null
943
+ candidate.reservation = { token, until: now + leaseMs }
944
+ await putRecord(tx, candidate)
945
+ return candidate
911
946
  })
912
947
  if (!reserved) return null
913
948
  let settled = false
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libp2r2p",
3
- "version": "0.12.15",
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) {
@@ -129,9 +129,16 @@ const MESSAGE_QUEUE_LOW_WATER_RATIO = 0.5
129
129
  const SEED_KEY = '__p2r2pSeedKey'
130
130
  const SEED_TIME = '__p2r2pSeedTime'
131
131
  const COALESCING_INDEX = 'byCoalescingKey'
132
+ const DELIVERY_PRIORITY_INDEX = 'byDeliveryPriority'
132
133
  const COALESCING_DIGEST = /^[0-9a-f]{64}$/
133
134
  const COALESCING_KEEP = new Set(['oldest', 'latest'])
134
135
  const DEDUPE_TYPES = new Set(['ask', 'reply', 'tell', 'yell'])
136
+ const DELIVERY_PRIORITY = Object.freeze({
137
+ lowest: 0,
138
+ lower: 1,
139
+ normal: 2
140
+ })
141
+ const DELIVERY_PRIORITY_NAMES = new Set(Object.keys(DELIVERY_PRIORITY))
135
142
  const PROVENANCE_PRIORITY = {
136
143
  signed: 2,
137
144
  direct: 1,
@@ -145,6 +152,7 @@ const TIMESTAMPED_PRIVATE_MESSAGE_KINDS = new Set([
145
152
  const MESSAGE_QUEUE_INDEXES = {
146
153
  byChannel: 'channelPubkey',
147
154
  [COALESCING_INDEX]: 'coalescingKey',
155
+ [DELIVERY_PRIORITY_INDEX]: 'deliveryPriority',
148
156
  byChannelTypeEventId: {
149
157
  keyPath: ['channelPubkey', 'type', 'event.id', 'provenance'],
150
158
  unique: true
@@ -308,6 +316,7 @@ export class PrivateMessenger {
308
316
  priorityTtlMs = DEFAULT_PRIORITY_TTL_MS,
309
317
  priorityHedgeDelayMs = DEFAULT_PRIORITY_HEDGE_DELAY_MS,
310
318
  priorityHedgeRelays = DEFAULT_PRIORITY_HEDGE_RELAYS,
319
+ deferColdRecovery = false,
311
320
  maxDynamicRecoverySeeders = DEFAULT_MAX_DYNAMIC_RECOVERY_SEEDERS,
312
321
  messageQueueMaxBytes = DEFAULT_MESSAGE_QUEUE_MAX_BYTES,
313
322
  seedQueueMaxBytes = DEFAULT_SEED_QUEUE_MAX_BYTES,
@@ -324,6 +333,7 @@ export class PrivateMessenger {
324
333
  onDebug,
325
334
  onError = defaultOnError,
326
335
  resolveInboundCoalescing,
336
+ resolveInboundPriority,
327
337
  admitInboundPeer,
328
338
  _privateMessage = privateMessage,
329
339
  _privateChannel = privateChannel,
@@ -349,6 +359,9 @@ export class PrivateMessenger {
349
359
  if (resolveInboundCoalescing != null && typeof resolveInboundCoalescing !== 'function') {
350
360
  throw new ValidationError('INVALID_RESOLVE_INBOUND_COALESCING')
351
361
  }
362
+ if (resolveInboundPriority != null && typeof resolveInboundPriority !== 'function') {
363
+ throw new ValidationError('INVALID_RESOLVE_INBOUND_PRIORITY')
364
+ }
352
365
  if (admitInboundPeer != null && typeof admitInboundPeer !== 'function') {
353
366
  throw new ValidationError('INVALID_ADMIT_INBOUND_PEER')
354
367
  }
@@ -374,6 +387,8 @@ export class PrivateMessenger {
374
387
  this.priorityHedgeRelays = Number.isSafeInteger(hedgeRelays) && hedgeRelays >= 1
375
388
  ? Math.min(hedgeRelays, 3)
376
389
  : DEFAULT_PRIORITY_HEDGE_RELAYS
390
+ if (typeof deferColdRecovery !== 'boolean') throw new ValidationError('INVALID_DEFER_COLD_RECOVERY')
391
+ this.deferColdRecovery = deferColdRecovery
377
392
  this.maxDynamicRecoverySeeders = maxDynamicRecoverySeeders
378
393
  this.messageQueueMaxBytes = messageQueueMaxBytes
379
394
  this.seedQueueMaxBytes = seedQueueMaxBytes
@@ -397,6 +412,7 @@ export class PrivateMessenger {
397
412
  this.onMessageQueued = onMessageQueued
398
413
  this.onDebug = onDebug
399
414
  this.resolveInboundCoalescing = resolveInboundCoalescing
415
+ this.resolveInboundPriority = resolveInboundPriority
400
416
  this.admitInboundPeer = admitInboundPeer
401
417
  this._privateMessage = _privateMessage.createPrivateMessageSession?.() ?? _privateMessage
402
418
  this._privateChannel = _privateChannel
@@ -463,6 +479,8 @@ export class PrivateMessenger {
463
479
  this.liveInterruptions = new Map()
464
480
  this.liveRecoveryTimers = new Map()
465
481
  this.subscriptionDebugKeys = new Set()
482
+ this.channelDebugRefs = new Map()
483
+ this.nextChannelDebugRef = 0
466
484
  this.watchRevisionByChannel = new Map()
467
485
  this.presenceTimers = new Map()
468
486
  this.presenceJobs = new Map()
@@ -542,6 +560,7 @@ export class PrivateMessenger {
542
560
  prefix: this.prefix, indexedDB: this._indexedDB,
543
561
  report: detail => this.debug('pending-decryption', detail)
544
562
  })
563
+ try { await this.pendingDecryption.cleanupSuspended?.() } catch (error) { this.onError?.(error) }
545
564
  this.seedQueue = this.seedStorage
546
565
  ? null
547
566
  : await createQueue({
@@ -728,6 +747,7 @@ export class PrivateMessenger {
728
747
  })
729
748
  await this.refreshAndApplyStoragePolicy()
730
749
  await this.cleanupStaleChannels()
750
+ try { await this.pendingDecryption?.cleanupSuspended?.() } catch (error) { this.onError?.(error) }
731
751
  await this.pruneStoredSeeds()
732
752
  })().catch(err => {
733
753
  try { this.onError?.(err) } catch {}
@@ -810,6 +830,15 @@ export class PrivateMessenger {
810
830
  this.debug(action, detail)
811
831
  }
812
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
+
813
842
  debugSend (method, channelPubkey, detail = {}) {
814
843
  const receiverPubkeys = uniq(detail.receiverPubkeys || (detail.receiverPubkey ? [detail.receiverPubkey] : []))
815
844
  this.debug('send', {
@@ -887,7 +916,10 @@ export class PrivateMessenger {
887
916
 
888
917
  if (removedPubkeys.length) {
889
918
  await this.stampChannelActivity(removedPubkeys)
890
- for (const pubkey of removedPubkeys) this.dropRecoveryState(pubkey)
919
+ for (const pubkey of removedPubkeys) {
920
+ this.dropRecoveryState(pubkey)
921
+ this.channelDebugRefs.delete(pubkey)
922
+ }
891
923
  }
892
924
 
893
925
  const storageSnapshot = await activatePrivateMessengerStorage({
@@ -1305,7 +1337,7 @@ export class PrivateMessenger {
1305
1337
  this.writeState(state)
1306
1338
  }
1307
1339
 
1308
- async watch (channels = [...this.channels.keys()], { scheduleReloadGap = true, signal } = {}) {
1340
+ async watch (channels = [...this.channels.keys()], { scheduleReloadGap = true, signal, _onWatchScheduled } = {}) {
1309
1341
  this.assertOpen()
1310
1342
  const channelPubkeys = uniq(channels)
1311
1343
  for (const pubkey of channelPubkeys) {
@@ -1321,6 +1353,12 @@ export class PrivateMessenger {
1321
1353
  for (const pubkey of channelPubkeys) {
1322
1354
  const channel = this.channels.get(pubkey)
1323
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
+ })
1324
1362
  const revision = (this.watchRevisionByChannel.get(pubkey) || 0) + 1
1325
1363
  this.watchRevisionByChannel.set(pubkey, revision)
1326
1364
  // Persist the pending interval before live delivery can advance lastSeenAt.
@@ -1362,6 +1400,7 @@ export class PrivateMessenger {
1362
1400
  receivedChunkTtlMs: this.receivedChunkTtlMsFor(channel),
1363
1401
  receivedChunkIndexedDB: this._indexedDB,
1364
1402
  onSubscriptionState: state => this.handleSubscriptionState(pubkey, state),
1403
+ _onWatchScheduled,
1365
1404
  onError: err => {
1366
1405
  if (!isExpectedRecoveryPause(err)) this.onError?.(err)
1367
1406
  }
@@ -1406,8 +1445,8 @@ export class PrivateMessenger {
1406
1445
  seeders: channel.seeders,
1407
1446
  offlineRecoverySeconds: channel.offlineRecoverySeconds
1408
1447
  })
1409
- this.debug('watch', {
1410
- channelPubkey: pubkey,
1448
+ this.debug('watch-ready', {
1449
+ channelRef,
1411
1450
  relays: watchRelays,
1412
1451
  mode: channel.mode,
1413
1452
  seeders: channel.seeders,
@@ -1441,6 +1480,7 @@ export class PrivateMessenger {
1441
1480
  this.addOfflineRange(pubkey, Math.max(0, start - this.offlineSkewSeconds), nowSeconds())
1442
1481
  const diagnosticRelay = safeDiagnosticRelay(relay)
1443
1482
  this.debugOnce(`subscription-interrupted:${diagnosticRelay || ''}:${start}:${safeDiagnosticToken(error?.code) || ''}`, 'subscription-interrupted', {
1483
+ channelRef: this.channelDebugRef(pubkey),
1444
1484
  relay: diagnosticRelay,
1445
1485
  rangeStart: start,
1446
1486
  ...subscriptionErrorDiagnostic(error)
@@ -1456,6 +1496,7 @@ export class PrivateMessenger {
1456
1496
  interrupted.delete(relay)
1457
1497
  if (!interrupted.size) this.liveInterruptions.delete(pubkey)
1458
1498
  this.debugOnce(`subscription-recovered:${safeDiagnosticRelay(relay) || ''}:${start}`, 'subscription-recovered', {
1499
+ channelRef: this.channelDebugRef(pubkey),
1459
1500
  relay: safeDiagnosticRelay(relay),
1460
1501
  rangeStart: start,
1461
1502
  rangeEnd: until,
@@ -1644,6 +1685,9 @@ export class PrivateMessenger {
1644
1685
  entries.push({ start, end, type, createdAt, expiresAt: createdAt + ttl })
1645
1686
  this.recoveryPriority.set(channelPubkey, entries)
1646
1687
  }
1688
+ if (this.deferColdRecovery && this.stopByChannel.has(channelPubkey) && !this.pauseReasons.size) {
1689
+ this.scheduleOfflineRecovery(channelPubkey, { startDelayMs: 0 })
1690
+ }
1647
1691
  return true
1648
1692
  }
1649
1693
 
@@ -2038,6 +2082,7 @@ export class PrivateMessenger {
2038
2082
  this.automaticPauses.delete(reason)
2039
2083
  if (!this.pauseReasons.size && this.sendRoutingPause.signal.aborted) this.sendRoutingPause = new AbortController()
2040
2084
  this.notifyStatus()
2085
+ if (removed) this.onMessageQueued?.()
2041
2086
  if (reason === 'capacity' && removed) {
2042
2087
  clearInterval(this.capacityTimer)
2043
2088
  this.capacityTimer = null
@@ -2084,11 +2129,20 @@ export class PrivateMessenger {
2084
2129
  const work = Promise.resolve().then(async () => {
2085
2130
  if (!this.initialized) await this.initSettledPromise
2086
2131
  if (!active()) return
2087
- 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
+ }
2088
2138
  try {
2089
2139
  if (!active()) return
2090
- await this.watch([pubkey], { scheduleReloadGap: !recover, signal: controller.signal })
2091
- } finally { release() }
2140
+ await this.watch([pubkey], {
2141
+ scheduleReloadGap: !recover,
2142
+ signal: controller.signal,
2143
+ _onWatchScheduled: releaseSetup
2144
+ })
2145
+ } finally { releaseSetup() }
2092
2146
  if (!active()) return
2093
2147
  phase = 'presence'
2094
2148
  if (doesModeStoreRecoverySeeds(channel.mode)) await this.startPresencePublisher(pubkey)
@@ -2266,6 +2320,30 @@ export class PrivateMessenger {
2266
2320
  await this.enqueueRumor('message', channelPubkey, message)
2267
2321
  }
2268
2322
 
2323
+ #deliveryPriority (type, channelPubkey, message) {
2324
+ const protocolPriority = protocolDeliveryPriority(message)
2325
+ if (!this.resolveInboundPriority) return protocolPriority
2326
+ let resolved
2327
+ try {
2328
+ resolved = this.resolveInboundPriority(
2329
+ { ...message, type, channelPubkey },
2330
+ { type, channelPubkey }
2331
+ )
2332
+ if (resolved != null && typeof resolved?.then === 'function') {
2333
+ throw new Error('INBOUND_PRIORITY_MUST_BE_SYNCHRONOUS')
2334
+ }
2335
+ } catch (cause) {
2336
+ this.onError?.(inboundPriorityError(cause))
2337
+ return protocolPriority
2338
+ }
2339
+ if (resolved == null) return protocolPriority
2340
+ if (typeof resolved === 'string' && DELIVERY_PRIORITY_NAMES.has(resolved)) {
2341
+ return Math.min(protocolPriority, DELIVERY_PRIORITY[resolved])
2342
+ }
2343
+ this.onError?.(inboundPriorityError(new ValidationError('INVALID_INBOUND_PRIORITY')))
2344
+ return protocolPriority
2345
+ }
2346
+
2269
2347
  #coalescingMetadata (type, channelPubkey, message, info) {
2270
2348
  const supportsIdempotencyTag = DEDUPE_TYPES.has(type)
2271
2349
  const tagged = supportsIdempotencyTag
@@ -2383,6 +2461,7 @@ export class PrivateMessenger {
2383
2461
  type,
2384
2462
  channelPubkey,
2385
2463
  receivedAt: nowSeconds(),
2464
+ deliveryPriority: this.#deliveryPriority(type, channelPubkey, message),
2386
2465
  event: message.event,
2387
2466
  ...info,
2388
2467
  payload: message.payload,
@@ -2455,7 +2534,10 @@ export class PrivateMessenger {
2455
2534
  this.markSeen(channelPubkey, message.outer?.created_at || message.event?.created_at || nowSeconds())
2456
2535
  this.wakeDeliveries()
2457
2536
  if (!record.coalescingKey || coalesced?.status === 'inserted') {
2458
- this.debug('enqueue', debugMessageInfo(type, channelPubkey, message))
2537
+ this.debug('message-received', {
2538
+ channelRef: this.channelDebugRef(channelPubkey),
2539
+ ...debugMessageInfo(type, channelPubkey, message)
2540
+ })
2459
2541
  }
2460
2542
  this.onMessageQueued?.()
2461
2543
  }
@@ -2647,6 +2729,8 @@ export class PrivateMessenger {
2647
2729
  const pause = this.pauseReasons.has('capacity') ? null : this.pause('capacity')
2648
2730
  pause?.catch(error => this.onError?.(error))
2649
2731
  this.startCapacityMonitor()
2732
+ this.wakeDeliveries()
2733
+ this.onMessageQueued?.()
2650
2734
  let summary
2651
2735
  try { summary = await this.inboxCapacitySummary() } catch {}
2652
2736
  return Object.assign(new Error('PRIVATE_MESSENGER_CAPACITY_PRESSURE'), {
@@ -2714,7 +2798,15 @@ export class PrivateMessenger {
2714
2798
  this.assertOpen()
2715
2799
  this.touchStorageActivity().catch(err => this.onError?.(err))
2716
2800
  await this.queueOperationTail
2717
- const reservation = await this.queue.reserve({ nackCoalescingIndex: COALESCING_INDEX })
2801
+ const reservation = await this.queue.reserve({
2802
+ nackCoalescingIndex: COALESCING_INDEX,
2803
+ priorityIndex: DELIVERY_PRIORITY_INDEX,
2804
+ priorities: [
2805
+ DELIVERY_PRIORITY.normal,
2806
+ DELIVERY_PRIORITY.lower,
2807
+ DELIVERY_PRIORITY.lowest
2808
+ ]
2809
+ })
2718
2810
  if (!reservation) return null
2719
2811
  if (this.closePromise) { await reservation.nack(); return null }
2720
2812
  let finish
@@ -3188,10 +3280,28 @@ export class PrivateMessenger {
3188
3280
  if (this.closePromise || !this.channels.has(pubkey) || !this.stopByChannel.has(pubkey)) return
3189
3281
  if ((this.watchRevisionByChannel.get(pubkey) || 0) !== revision) return
3190
3282
  if (start != null) this.addOfflineRange(pubkey, Math.max(0, start - this.offlineSkewSeconds), nowSeconds())
3191
- 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) {
3192
3302
  if (!isExpectedRecoveryPause(err)) this.onError?.(err)
3193
3303
  }
3194
- 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)) {
3195
3305
  this.scheduleOfflineRecovery(pubkey, { startDelayMs: 1000 })
3196
3306
  }
3197
3307
  }, this.reloadGapDelayMs)
@@ -3219,12 +3329,12 @@ export class PrivateMessenger {
3219
3329
  }
3220
3330
  }
3221
3331
 
3222
- async askSeedersForMissingRange (channelPubkey, since, until) {
3223
- 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 })
3224
3334
  return asks
3225
3335
  }
3226
3336
 
3227
- async #askSeedersForMissingRangeAttempt (channelPubkey, since, until, { seeders } = {}) {
3337
+ async #askSeedersForMissingRangeAttempt (channelPubkey, since, until, { seeders, priority = 'lower' } = {}) {
3228
3338
  if (this.pauseReasons.size) throw this.pausedError()
3229
3339
  if (!this.offlineRecoverySecondsFor(channelPubkey)) return { asks: [], failures: [] }
3230
3340
  if (!this.channels.get(channelPubkey)?.signer) return { asks: [], failures: [] }
@@ -3240,8 +3350,12 @@ export class PrivateMessenger {
3240
3350
  channelPubkey,
3241
3351
  receiverPubkey: seeder,
3242
3352
  code: MISSING_MESSAGES_ASK_CODE,
3243
- payload: { since, until },
3244
- useBulkPacing: true
3353
+ payload: {
3354
+ since,
3355
+ until,
3356
+ ...(priority === 'normal' ? {} : { priority })
3357
+ },
3358
+ useBulkPacing: priority !== 'normal'
3245
3359
  })
3246
3360
  asks.push(ask)
3247
3361
  await assertMessagePublished(ask, ask.question)
@@ -3275,12 +3389,16 @@ export class PrivateMessenger {
3275
3389
  const payload = isPlainObject(message.payload?.payload) ? message.payload.payload : {}
3276
3390
  const since = Number.isFinite(payload.since) ? payload.since : undefined
3277
3391
  const until = Number.isFinite(payload.until) ? payload.until : undefined
3392
+ const priority = payload.priority === 'lower' || payload.priority === 'lowest'
3393
+ ? payload.priority
3394
+ : 'normal'
3278
3395
  const packer = this.createMissingMessageReplyPacker({
3279
3396
  channelPubkey,
3280
3397
  question: message.event,
3281
3398
  receiverPubkey: message.event?.pubkey,
3282
3399
  since,
3283
3400
  until,
3401
+ priority,
3284
3402
  sendEmptyReply: !this.offlineRecoverySecondsFor(channelPubkey)
3285
3403
  })
3286
3404
 
@@ -3408,13 +3526,13 @@ export class PrivateMessenger {
3408
3526
  }
3409
3527
  }
3410
3528
 
3411
- async recoverOfflineRanges (channels = [...this.stopByChannel.keys()]) {
3529
+ async recoverOfflineRanges (channels = [...this.stopByChannel.keys()], { priorityOnly = false } = {}) {
3412
3530
  const failures = []
3413
3531
  for (const pubkey of uniq(channels)) {
3414
3532
  if (this.pauseReasons.size || this.closePromise || !this.desiredChannels.has(pubkey)) continue
3415
3533
  let work = this.recoveries.get(pubkey)
3416
3534
  if (!work) {
3417
- work = this.recoverChannelRanges([pubkey])
3535
+ work = this.recoverChannelRanges([pubkey], { priorityOnly })
3418
3536
  this.recoveries.set(pubkey, work)
3419
3537
  }
3420
3538
  try { failures.push(...await work) } finally { if (this.recoveries.get(pubkey) === work) this.recoveries.delete(pubkey) }
@@ -3513,7 +3631,7 @@ export class PrivateMessenger {
3513
3631
  }
3514
3632
  }
3515
3633
 
3516
- async askPrioritySeeders (channelPubkey, intervals) {
3634
+ async askPrioritySeeders (channelPubkey, intervals, { priority = 'normal' } = {}) {
3517
3635
  if (!intervals.length) return []
3518
3636
  if (this.pauseReasons.size) throw this.pausedError()
3519
3637
  if (!await this.checkRecoveryOnline()) return []
@@ -3523,7 +3641,10 @@ export class PrivateMessenger {
3523
3641
  const claimed = []
3524
3642
  for (const interval of mergeRanges(intervals)) {
3525
3643
  if (this.pauseReasons.size) throw this.pausedError()
3526
- 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
+ })
3527
3648
  failures.push(...attempt.failures.map(failure => failure.error))
3528
3649
  if (!attempt.failures.length) claimed.push(interval)
3529
3650
  }
@@ -3540,6 +3661,13 @@ export class PrivateMessenger {
3540
3661
  async runPriorityLane (channelPubkey, channel, ranges) {
3541
3662
  const priorities = this.recoveryPriorities(channelPubkey)
3542
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)
3543
3671
  const fetchRelays = await this.resolveWatchRelays(channel)
3544
3672
  for (const range of ranges) {
3545
3673
  if (this.pauseReasons.size || this.closePromise) throw this.pausedError()
@@ -3571,13 +3699,19 @@ export class PrivateMessenger {
3571
3699
  }
3572
3700
  }
3573
3701
  if (this.pauseReasons.size || this.closePromise) throw this.pausedError()
3574
- const uncovered = intersectRanges(wanted, subtractRanges({ start: range.start, end: range.end }, record.covered))
3575
- 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' })
3576
3710
  }
3577
3711
  this.prunePriorityEntries(channelPubkey)
3578
3712
  }
3579
3713
 
3580
- async recoverChannelRanges (channels) {
3714
+ async recoverChannelRanges (channels, { priorityOnly = false } = {}) {
3581
3715
  const failures = []
3582
3716
  const state = this.readState()
3583
3717
  const now = nowSeconds()
@@ -3604,6 +3738,8 @@ export class PrivateMessenger {
3604
3738
  }
3605
3739
  }
3606
3740
 
3741
+ if (priorityOnly) continue
3742
+
3607
3743
  const remaining = []
3608
3744
  let recoveredThrough = current.recoveredThrough || 0
3609
3745
  for (const range of current.offlineRanges) {
@@ -3668,8 +3804,15 @@ export class PrivateMessenger {
3668
3804
  continue
3669
3805
  }
3670
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
+ })
3671
3813
  const result = await this.finalizeRecoveryRange({ channelPubkey: pubkey, range, record })
3672
3814
  this.debug('recovery-range-complete', {
3815
+ channelRef: this.channelDebugRef(pubkey),
3673
3816
  rangeStart: range.start,
3674
3817
  rangeEnd: range.end,
3675
3818
  complete: result.complete === true,
@@ -3711,6 +3854,7 @@ export class PrivateMessenger {
3711
3854
  await this._privateMessage.clearChannelState?.(pubkey)
3712
3855
  this.dropRecoveryState(pubkey)
3713
3856
  return this.runQueueOperation(async () => {
3857
+ this.channelDebugRefs.delete(pubkey)
3714
3858
  this.channels.delete(pubkey)
3715
3859
  this.decryptionReadyChannels?.delete(pubkey)
3716
3860
  this.removeChannelState(pubkey)
@@ -4150,6 +4294,9 @@ function compareLegacyCoalescingOrder (left, right) {
4150
4294
  }
4151
4295
 
4152
4296
  function compareCoalescingItems (left, right) {
4297
+ const leftPriority = left?.deliveryPriority ?? DELIVERY_PRIORITY.normal
4298
+ const rightPriority = right?.deliveryPriority ?? DELIVERY_PRIORITY.normal
4299
+ if (leftPriority !== rightPriority) return leftPriority - rightPriority
4153
4300
  return compareCoalescingOrder(left?.coalescingOrder, right?.coalescingOrder)
4154
4301
  }
4155
4302
 
@@ -4168,6 +4315,25 @@ function coalescingError (cause) {
4168
4315
  })
4169
4316
  }
4170
4317
 
4318
+ function inboundPriorityError (cause) {
4319
+ return Object.assign(new Error('INVALID_INBOUND_PRIORITY'), {
4320
+ code: 'INVALID_INBOUND_PRIORITY',
4321
+ cause
4322
+ })
4323
+ }
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
+
4171
4337
  function safeDiagnosticToken (value) {
4172
4338
  return typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9:._-]{0,159}$/.test(value)
4173
4339
  ? value
@@ -4285,6 +4451,7 @@ function withoutQueueMetadata (item) {
4285
4451
  delete value.coalescingKey
4286
4452
  delete value.coalescingKeep
4287
4453
  delete value.coalescingOrder
4454
+ delete value.deliveryPriority
4288
4455
  delete value[SEED_KEY]
4289
4456
  delete value[SEED_TIME]
4290
4457
  return 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,8 @@ import { deliveryInfo } from '../../private-channel/helpers/rumor.js'
2
2
 
3
3
  const encoder = new TextEncoder()
4
4
  const indexName = 'byChannelTypeEventId'
5
+ const deliveryPriorityProperty = 'deliveryPriority'
6
+ const deliveryPriorityNormal = 2
5
7
  const oldPath = ['item.channelPubkey', 'item.type', 'item.event.id']
6
8
  const newPath = [...oldPath, 'item.provenance']
7
9
  const equal = (a, b) => JSON.stringify(a) === JSON.stringify(b)
@@ -35,20 +37,101 @@ function matchesLegacy (items) {
35
37
  !items.index('byChannel').unique && !items.index('byChannel').multiEntry
36
38
  }
37
39
 
40
+ function normalizedDeliveryPriority (value) {
41
+ if (Number.isSafeInteger(value) && value >= 0 && value <= deliveryPriorityNormal) return value
42
+ if (value === 'lowest') return 0
43
+ if (value === 'lower') return 1
44
+ return deliveryPriorityNormal
45
+ }
46
+
47
+ function itemByteSize (item) {
48
+ let byteSize = 0
49
+ while (true) {
50
+ const size = encoder.encode(JSON.stringify({ byteSize, item })).length
51
+ if (size === byteSize) return byteSize
52
+ byteSize = size
53
+ }
54
+ }
55
+
56
+ async function backfillDeliveryPriority (indexedDB, name) {
57
+ const db = await open(indexedDB, name)
58
+ if (!db.objectStoreNames.contains('items') || !db.objectStoreNames.contains('state')) {
59
+ db.close()
60
+ return
61
+ }
62
+ if (db.transaction('items', 'readonly').objectStore('items').indexNames.contains('byDeliveryPriority')) {
63
+ db.close()
64
+ return
65
+ }
66
+ const tx = db.transaction(['items', 'state'], 'readwrite')
67
+ const done = new Promise((resolve, reject) => {
68
+ tx.oncomplete = resolve
69
+ tx.onabort = () => reject(tx.error || new Error('IDB_TRANSACTION_ABORTED'))
70
+ tx.onerror = () => reject(tx.error || new Error('IDB_TRANSACTION_FAILED'))
71
+ })
72
+ const items = tx.objectStore('items')
73
+ const state = tx.objectStore('state')
74
+ let delta = 0
75
+ const cursor = items.openCursor()
76
+ cursor.onsuccess = () => {
77
+ try {
78
+ const row = cursor.result
79
+ if (!row) {
80
+ const request = state.get('queue')
81
+ request.onsuccess = () => {
82
+ if (!request.result || !delta) return
83
+ state.put({
84
+ ...request.result,
85
+ usedBytes: Math.max(0, request.result.usedBytes + delta)
86
+ })
87
+ }
88
+ return
89
+ }
90
+ const record = row.value
91
+ if (!record.item || typeof record.item !== 'object' || Array.isArray(record.item)) {
92
+ row.continue()
93
+ return
94
+ }
95
+ const current = record.item[deliveryPriorityProperty]
96
+ const priority = normalizedDeliveryPriority(current)
97
+ if (current === priority) {
98
+ row.continue()
99
+ return
100
+ }
101
+ const item = { ...record.item, [deliveryPriorityProperty]: priority }
102
+ const byteSize = itemByteSize(item)
103
+ delta += byteSize - (record.byteSize || 0)
104
+ row.update({ ...record, item, byteSize })
105
+ row.continue()
106
+ } catch {
107
+ tx.abort()
108
+ }
109
+ }
110
+ try {
111
+ await done
112
+ } finally {
113
+ db.close()
114
+ }
115
+ }
116
+
38
117
  // The generic queue remains strict. Only this historical messenger schema is
39
- // migrated, atomically with its records and capacity accounting.
118
+ // migrated. Legacy records then receive the default normal delivery lane before
119
+ // createQueue adds its byDeliveryPriority index.
40
120
  export async function migrateMessageQueue (indexedDB, prefix) {
41
121
  if (!indexedDB?.open) throw new Error('IDB_UNAVAILABLE')
42
122
  const name = `${prefix}:idb-queue`
43
123
  for (let attempt = 0; attempt < 3; attempt++) {
44
124
  const db = await open(indexedDB, name)
45
- if (!db.objectStoreNames.contains('items') || !db.objectStoreNames.contains('state')) { db.close(); return }
125
+ if (!db.objectStoreNames.contains('items') || !db.objectStoreNames.contains('state')) {
126
+ db.close()
127
+ break
128
+ }
46
129
  const tx = db.transaction(['items', 'state'], 'readonly')
47
130
  const legacy = matchesLegacy(tx.objectStore('items')) && tx.objectStore('state').keyPath === 'key'
48
131
  const version = db.version + 1
49
132
  await new Promise((resolve, reject) => { tx.oncomplete = resolve; tx.onabort = () => reject(tx.error) })
50
133
  db.close()
51
- if (!legacy) return
134
+ if (!legacy) break
52
135
  try {
53
136
  const upgraded = await open(indexedDB, name, version, (_db, tx) => {
54
137
  const items = tx.objectStore('items')
@@ -87,9 +170,10 @@ export async function migrateMessageQueue (indexedDB, prefix) {
87
170
  }
88
171
  })
89
172
  upgraded.close()
90
- return
173
+ break
91
174
  } catch (error) {
92
175
  if (error?.name !== 'VersionError' || attempt === 2) throw error
93
176
  }
94
177
  }
178
+ await backfillDeliveryPriority(indexedDB, name)
95
179
  }
@@ -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