libp2r2p 0.12.15 → 0.12.16

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
@@ -415,6 +415,29 @@ Coalescing does not provide an ingress rate limit or per-peer quota. Exact
415
415
  event deduplication, authorization, quarantine, global inbox capacity,
416
416
  pause/ACK/NACK ownership and existing storage policy remain independent.
417
417
 
418
+ ### Inbound delivery priority
419
+
420
+ `PrivateMessenger` accepts an optional synchronous
421
+ `resolveInboundPriority(message, context)` callback. The callback returns
422
+ `"normal"`, `"lower"`, `"lowest"` or `null`; `normal` is the default. The
423
+ resolved class is stored as internal IndexedDB queue metadata, is included in
424
+ the coalescing comparator, and is removed before delivery to the app. Existing
425
+ records without priority are backfilled as `normal` during messenger
426
+ initialization.
427
+
428
+ Queue reservation selects `normal` before `lower` before `lowest` through the
429
+ `byDeliveryPriority` index, preserving FIFO within each class and never
430
+ interrupting an active reservation. Capacity
431
+ pressure blocks new inbox admission but does not block reservation,
432
+ acknowledgment or NACK of records already persisted. `onMessageQueued` is
433
+ called when capacity pressure begins and after the queue changes in a way that
434
+ can wake a durable consumer.
435
+
436
+ An invalid or asynchronous resolver result is reported as
437
+ `INVALID_INBOUND_PRIORITY` and falls back to `normal`. Callers that interpret
438
+ remote payload fields should only permit fields to lower priority; a peer must
439
+ not be able to promote itself by supplying a value.
440
+
418
441
  ### Inbound peer admission
419
442
 
420
443
  `PrivateMessenger` accepts an optional synchronous
@@ -1310,7 +1333,7 @@ Opening a reject-policy queue under a smaller budget preserves existing items.
1310
1333
  Positional replacement and insertion follow the same rule: they reject instead
1311
1334
  of evicting when the resulting queue would exceed the limit.
1312
1335
 
1313
- `queue.reserve({ leaseMs = 30000, nackCoalescingIndex })` returns `null` or
1336
+ `queue.reserve({ leaseMs = 30000, nackCoalescingIndex, priorityIndex, priorities })` returns `null` or
1314
1337
  `{ item, ack, nack, renew }`. Reservation token/deadline are internal record
1315
1338
  metadata, persisted atomically in the same IndexedDB transaction as selection.
1316
1339
  `renew()` extends a still-valid lease. Low-level callers own renewal and release;
@@ -1319,6 +1342,15 @@ position-shifting queue operations on the same queue except explicit removal.
1319
1342
  A stale token cannot acknowledge a newly reserved or replaced record.
1320
1343
  `nackCoalescingIndex` names a non-unique index: when another matching item is
1321
1344
  pending, NACK deletes the superseded active item instead of requeueing it.
1345
+ `priorityIndex` names a scalar, non-multiEntry index and `priorities` is the
1346
+ ordered list of index keys to try. Within a lane, an index cursor starts at the
1347
+ smallest queue `position`, so FIFO is preserved without reading the rest of the
1348
+ queue into memory. Duplicate priority values are ignored. Missing index values
1349
+ are not candidates; callers migrating an existing queue must backfill them.
1350
+ Invalid selectors reject with `QUEUE_PRIORITY_INDEX_INVALID`,
1351
+ `QUEUE_PRIORITY_VALUES_INVALID` or `QUEUE_PRIORITY_VALUE_INVALID`. Without a
1352
+ priority index, reservation uses a FIFO primary-key cursor. This extension
1353
+ belongs only to `idb-queue`.
1322
1354
 
1323
1355
  `queue.getCapacity()` is part of the common API and returns
1324
1356
  `{ 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.16",
4
4
  "description": "Peer-to-relay-to-peer",
5
5
  "keywords": [
6
6
  "p2r2p",
@@ -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
@@ -324,6 +332,7 @@ export class PrivateMessenger {
324
332
  onDebug,
325
333
  onError = defaultOnError,
326
334
  resolveInboundCoalescing,
335
+ resolveInboundPriority,
327
336
  admitInboundPeer,
328
337
  _privateMessage = privateMessage,
329
338
  _privateChannel = privateChannel,
@@ -349,6 +358,9 @@ export class PrivateMessenger {
349
358
  if (resolveInboundCoalescing != null && typeof resolveInboundCoalescing !== 'function') {
350
359
  throw new ValidationError('INVALID_RESOLVE_INBOUND_COALESCING')
351
360
  }
361
+ if (resolveInboundPriority != null && typeof resolveInboundPriority !== 'function') {
362
+ throw new ValidationError('INVALID_RESOLVE_INBOUND_PRIORITY')
363
+ }
352
364
  if (admitInboundPeer != null && typeof admitInboundPeer !== 'function') {
353
365
  throw new ValidationError('INVALID_ADMIT_INBOUND_PEER')
354
366
  }
@@ -397,6 +409,7 @@ export class PrivateMessenger {
397
409
  this.onMessageQueued = onMessageQueued
398
410
  this.onDebug = onDebug
399
411
  this.resolveInboundCoalescing = resolveInboundCoalescing
412
+ this.resolveInboundPriority = resolveInboundPriority
400
413
  this.admitInboundPeer = admitInboundPeer
401
414
  this._privateMessage = _privateMessage.createPrivateMessageSession?.() ?? _privateMessage
402
415
  this._privateChannel = _privateChannel
@@ -2038,6 +2051,7 @@ export class PrivateMessenger {
2038
2051
  this.automaticPauses.delete(reason)
2039
2052
  if (!this.pauseReasons.size && this.sendRoutingPause.signal.aborted) this.sendRoutingPause = new AbortController()
2040
2053
  this.notifyStatus()
2054
+ if (removed) this.onMessageQueued?.()
2041
2055
  if (reason === 'capacity' && removed) {
2042
2056
  clearInterval(this.capacityTimer)
2043
2057
  this.capacityTimer = null
@@ -2266,6 +2280,29 @@ export class PrivateMessenger {
2266
2280
  await this.enqueueRumor('message', channelPubkey, message)
2267
2281
  }
2268
2282
 
2283
+ #deliveryPriority (type, channelPubkey, message) {
2284
+ if (!this.resolveInboundPriority) return DELIVERY_PRIORITY.normal
2285
+ let resolved
2286
+ try {
2287
+ resolved = this.resolveInboundPriority(
2288
+ { ...message, type, channelPubkey },
2289
+ { type, channelPubkey }
2290
+ )
2291
+ if (resolved != null && typeof resolved?.then === 'function') {
2292
+ throw new Error('INBOUND_PRIORITY_MUST_BE_SYNCHRONOUS')
2293
+ }
2294
+ } catch (cause) {
2295
+ this.onError?.(inboundPriorityError(cause))
2296
+ return DELIVERY_PRIORITY.normal
2297
+ }
2298
+ if (resolved == null) return DELIVERY_PRIORITY.normal
2299
+ if (typeof resolved === 'string' && DELIVERY_PRIORITY_NAMES.has(resolved)) {
2300
+ return DELIVERY_PRIORITY[resolved]
2301
+ }
2302
+ this.onError?.(inboundPriorityError(new ValidationError('INVALID_INBOUND_PRIORITY')))
2303
+ return DELIVERY_PRIORITY.normal
2304
+ }
2305
+
2269
2306
  #coalescingMetadata (type, channelPubkey, message, info) {
2270
2307
  const supportsIdempotencyTag = DEDUPE_TYPES.has(type)
2271
2308
  const tagged = supportsIdempotencyTag
@@ -2383,6 +2420,7 @@ export class PrivateMessenger {
2383
2420
  type,
2384
2421
  channelPubkey,
2385
2422
  receivedAt: nowSeconds(),
2423
+ deliveryPriority: this.#deliveryPriority(type, channelPubkey, message),
2386
2424
  event: message.event,
2387
2425
  ...info,
2388
2426
  payload: message.payload,
@@ -2647,6 +2685,8 @@ export class PrivateMessenger {
2647
2685
  const pause = this.pauseReasons.has('capacity') ? null : this.pause('capacity')
2648
2686
  pause?.catch(error => this.onError?.(error))
2649
2687
  this.startCapacityMonitor()
2688
+ this.wakeDeliveries()
2689
+ this.onMessageQueued?.()
2650
2690
  let summary
2651
2691
  try { summary = await this.inboxCapacitySummary() } catch {}
2652
2692
  return Object.assign(new Error('PRIVATE_MESSENGER_CAPACITY_PRESSURE'), {
@@ -2714,7 +2754,15 @@ export class PrivateMessenger {
2714
2754
  this.assertOpen()
2715
2755
  this.touchStorageActivity().catch(err => this.onError?.(err))
2716
2756
  await this.queueOperationTail
2717
- const reservation = await this.queue.reserve({ nackCoalescingIndex: COALESCING_INDEX })
2757
+ const reservation = await this.queue.reserve({
2758
+ nackCoalescingIndex: COALESCING_INDEX,
2759
+ priorityIndex: DELIVERY_PRIORITY_INDEX,
2760
+ priorities: [
2761
+ DELIVERY_PRIORITY.normal,
2762
+ DELIVERY_PRIORITY.lower,
2763
+ DELIVERY_PRIORITY.lowest
2764
+ ]
2765
+ })
2718
2766
  if (!reservation) return null
2719
2767
  if (this.closePromise) { await reservation.nack(); return null }
2720
2768
  let finish
@@ -4150,6 +4198,9 @@ function compareLegacyCoalescingOrder (left, right) {
4150
4198
  }
4151
4199
 
4152
4200
  function compareCoalescingItems (left, right) {
4201
+ const leftPriority = left?.deliveryPriority ?? DELIVERY_PRIORITY.normal
4202
+ const rightPriority = right?.deliveryPriority ?? DELIVERY_PRIORITY.normal
4203
+ if (leftPriority !== rightPriority) return leftPriority - rightPriority
4153
4204
  return compareCoalescingOrder(left?.coalescingOrder, right?.coalescingOrder)
4154
4205
  }
4155
4206
 
@@ -4168,6 +4219,13 @@ function coalescingError (cause) {
4168
4219
  })
4169
4220
  }
4170
4221
 
4222
+ function inboundPriorityError (cause) {
4223
+ return Object.assign(new Error('INVALID_INBOUND_PRIORITY'), {
4224
+ code: 'INVALID_INBOUND_PRIORITY',
4225
+ cause
4226
+ })
4227
+ }
4228
+
4171
4229
  function safeDiagnosticToken (value) {
4172
4230
  return typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9:._-]{0,159}$/.test(value)
4173
4231
  ? value
@@ -4285,6 +4343,7 @@ function withoutQueueMetadata (item) {
4285
4343
  delete value.coalescingKey
4286
4344
  delete value.coalescingKeep
4287
4345
  delete value.coalescingOrder
4346
+ delete value.deliveryPriority
4288
4347
  delete value[SEED_KEY]
4289
4348
  delete value[SEED_TIME]
4290
4349
  return value
@@ -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
  }