libp2r2p 0.12.14 → 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
@@ -370,14 +370,29 @@ where `key` is a lowercase 64-character SHA-256 digest, `keep` is `latest`
370
370
  Sequence units are resolver-owned and are compared only within records sharing
371
371
  the final scoped coalescing key.
372
372
 
373
- The resolver runs for ask, reply, tell, yell, message and nym deliveries after
374
- exact event-ID deduplication. The final coalescing key is scoped by channel,
375
- sender, type, message code and provenance. `latest` replaces the pending item in
376
- place. Its order is: explicit sequence; `eventCreatedAtMs`, read from the inner
377
- `created_at` plus the `ms` tag; outer `created_at`; event ID. `oldest` preserves
378
- the pending item. While an item is reserved, both policies allow at most one
379
- successor. Timestamp and sequence ordering persist in internal queue metadata.
380
- Older recovered events do not replace newer requests.
373
+ Every inbox type first attempts exact deduplication by channel, type, event ID
374
+ and provenance, then a valid resolver key, then the automatic `D` fallback for
375
+ ask/reply/tell/yell. When none supplies an identity, ask, reply, tell, yell,
376
+ message and nym fall back to Nostr identity within the same channel and type:
377
+ the first usable `d` tag selects an address, replaceable/addressable events
378
+ without a usable `d` use `""`, and regular or ephemeral events use `event.id`.
379
+ Ephemeral events never use an address. An explicit `d` is not merged with a
380
+ regular event that has no address.
381
+
382
+ Resolver and `D` keys retain channel, sender, type, code and provenance scope.
383
+ Automatic keys omit sender, provenance and code. For copies with the same event
384
+ ID, provenance orders `signed > direct > hearsay`. Different versions of an
385
+ address follow NIP-01: higher inner `created_at`, then lower event ID on a tie;
386
+ `signed` and `direct` compare as legitimate versions, while hearsay never
387
+ displaces either. Address ordering ignores outer time and the `ms` tag.
388
+
389
+ Resolver/idempotency `latest` replaces the pending item in place. Its order is:
390
+ explicit sequence; `eventCreatedAtMs`, read from the inner `created_at` plus the
391
+ `ms` tag; outer `created_at`; event ID. `oldest` preserves the pending item.
392
+ While an item is reserved, all policies allow at most one successor. Ordering
393
+ metadata persists internally, is removed before app delivery, and older pending
394
+ records remain valid until drained. Older recovered events do not replace newer
395
+ requests.
381
396
 
382
397
  New high-level ask, reply, tell and yell rumors include exactly one
383
398
  `["ms", "0".."999"]` tag and use the same instant to derive inner `created_at`.
@@ -400,6 +415,29 @@ Coalescing does not provide an ingress rate limit or per-peer quota. Exact
400
415
  event deduplication, authorization, quarantine, global inbox capacity,
401
416
  pause/ACK/NACK ownership and existing storage policy remain independent.
402
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
+
403
441
  ### Inbound peer admission
404
442
 
405
443
  `PrivateMessenger` accepts an optional synchronous
@@ -1295,7 +1333,7 @@ Opening a reject-policy queue under a smaller budget preserves existing items.
1295
1333
  Positional replacement and insertion follow the same rule: they reject instead
1296
1334
  of evicting when the resulting queue would exceed the limit.
1297
1335
 
1298
- `queue.reserve({ leaseMs = 30000, nackCoalescingIndex })` returns `null` or
1336
+ `queue.reserve({ leaseMs = 30000, nackCoalescingIndex, priorityIndex, priorities })` returns `null` or
1299
1337
  `{ item, ack, nack, renew }`. Reservation token/deadline are internal record
1300
1338
  metadata, persisted atomically in the same IndexedDB transaction as selection.
1301
1339
  `renew()` extends a still-valid lease. Low-level callers own renewal and release;
@@ -1304,6 +1342,15 @@ position-shifting queue operations on the same queue except explicit removal.
1304
1342
  A stale token cannot acknowledge a newly reserved or replaced record.
1305
1343
  `nackCoalescingIndex` names a non-unique index: when another matching item is
1306
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`.
1307
1354
 
1308
1355
  `queue.getCapacity()` is part of the common API and returns
1309
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.14",
3
+ "version": "0.12.16",
4
4
  "description": "Peer-to-relay-to-peer",
5
5
  "keywords": [
6
6
  "p2r2p",
@@ -70,6 +70,7 @@ import { getRelaysByPubkey, pickRelaysForPubkeys, subscribeRelayListUpdates, rel
70
70
  import * as privateChannel from '../private-channel/index.js'
71
71
  import { DEFAULT_RECEIVED_CHUNK_TTL_MS } from '../private-channel/services/received-chunks.js'
72
72
  import { createQueue } from '../idb-queue/index.js'
73
+ import { classifyEvent, isEphemeralEvent } from '../event/index.js'
73
74
  import { createChannelStateStore } from './services/channel-state.js'
74
75
  import { normalizeIdempotencyKey, readIdempotencyKey } from '../private-message/helpers/idempotency.js'
75
76
  import { eventCreatedAtMs, readMilliseconds } from '../private-message/helpers/timestamp.js'
@@ -128,9 +129,21 @@ const MESSAGE_QUEUE_LOW_WATER_RATIO = 0.5
128
129
  const SEED_KEY = '__p2r2pSeedKey'
129
130
  const SEED_TIME = '__p2r2pSeedTime'
130
131
  const COALESCING_INDEX = 'byCoalescingKey'
132
+ const DELIVERY_PRIORITY_INDEX = 'byDeliveryPriority'
131
133
  const COALESCING_DIGEST = /^[0-9a-f]{64}$/
132
134
  const COALESCING_KEEP = new Set(['oldest', 'latest'])
133
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))
142
+ const PROVENANCE_PRIORITY = {
143
+ signed: 2,
144
+ direct: 1,
145
+ hearsay: 0
146
+ }
134
147
  const TIMESTAMPED_PRIVATE_MESSAGE_KINDS = new Set([
135
148
  privateMessage.ASK_KIND,
136
149
  privateMessage.REPLY_KIND,
@@ -139,6 +152,7 @@ const TIMESTAMPED_PRIVATE_MESSAGE_KINDS = new Set([
139
152
  const MESSAGE_QUEUE_INDEXES = {
140
153
  byChannel: 'channelPubkey',
141
154
  [COALESCING_INDEX]: 'coalescingKey',
155
+ [DELIVERY_PRIORITY_INDEX]: 'deliveryPriority',
142
156
  byChannelTypeEventId: {
143
157
  keyPath: ['channelPubkey', 'type', 'event.id', 'provenance'],
144
158
  unique: true
@@ -318,6 +332,7 @@ export class PrivateMessenger {
318
332
  onDebug,
319
333
  onError = defaultOnError,
320
334
  resolveInboundCoalescing,
335
+ resolveInboundPriority,
321
336
  admitInboundPeer,
322
337
  _privateMessage = privateMessage,
323
338
  _privateChannel = privateChannel,
@@ -343,6 +358,9 @@ export class PrivateMessenger {
343
358
  if (resolveInboundCoalescing != null && typeof resolveInboundCoalescing !== 'function') {
344
359
  throw new ValidationError('INVALID_RESOLVE_INBOUND_COALESCING')
345
360
  }
361
+ if (resolveInboundPriority != null && typeof resolveInboundPriority !== 'function') {
362
+ throw new ValidationError('INVALID_RESOLVE_INBOUND_PRIORITY')
363
+ }
346
364
  if (admitInboundPeer != null && typeof admitInboundPeer !== 'function') {
347
365
  throw new ValidationError('INVALID_ADMIT_INBOUND_PEER')
348
366
  }
@@ -391,6 +409,7 @@ export class PrivateMessenger {
391
409
  this.onMessageQueued = onMessageQueued
392
410
  this.onDebug = onDebug
393
411
  this.resolveInboundCoalescing = resolveInboundCoalescing
412
+ this.resolveInboundPriority = resolveInboundPriority
394
413
  this.admitInboundPeer = admitInboundPeer
395
414
  this._privateMessage = _privateMessage.createPrivateMessageSession?.() ?? _privateMessage
396
415
  this._privateChannel = _privateChannel
@@ -2032,6 +2051,7 @@ export class PrivateMessenger {
2032
2051
  this.automaticPauses.delete(reason)
2033
2052
  if (!this.pauseReasons.size && this.sendRoutingPause.signal.aborted) this.sendRoutingPause = new AbortController()
2034
2053
  this.notifyStatus()
2054
+ if (removed) this.onMessageQueued?.()
2035
2055
  if (reason === 'capacity' && removed) {
2036
2056
  clearInterval(this.capacityTimer)
2037
2057
  this.capacityTimer = null
@@ -2260,6 +2280,29 @@ export class PrivateMessenger {
2260
2280
  await this.enqueueRumor('message', channelPubkey, message)
2261
2281
  }
2262
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
+
2263
2306
  #coalescingMetadata (type, channelPubkey, message, info) {
2264
2307
  const supportsIdempotencyTag = DEDUPE_TYPES.has(type)
2265
2308
  const tagged = supportsIdempotencyTag
@@ -2309,6 +2352,7 @@ export class PrivateMessenger {
2309
2352
  let digest = null
2310
2353
  let keep = 'latest'
2311
2354
  let sequence = null
2355
+ let policy = 'semantic'
2312
2356
  if (resolved != null) {
2313
2357
  if (isPlainObject(resolved) && typeof resolved.key === 'string' &&
2314
2358
  COALESCING_DIGEST.test(resolved.key) &&
@@ -2322,27 +2366,37 @@ export class PrivateMessenger {
2322
2366
  this.onError?.(coalescingError(new ValidationError('INVALID_INBOUND_COALESCING_RESULT')))
2323
2367
  }
2324
2368
  }
2325
- if (!digest && tagged.key) digest = idempotencyDigest(tagged.key)
2326
- if (!digest) return null
2369
+ if (!digest && tagged.key) {
2370
+ digest = idempotencyDigest(tagged.key)
2371
+ policy = 'idempotency'
2372
+ }
2327
2373
 
2328
2374
  const senderPubkey = info.senderPubkey || message.event?.pubkey || ''
2329
2375
  const code = messageCode(message)
2330
- if (!channelPubkey || !senderPubkey || typeof code !== 'string' || !info.provenance) {
2376
+ if (digest && (!channelPubkey || !senderPubkey || typeof code !== 'string' || !info.provenance)) {
2331
2377
  this.onError?.(coalescingError(new ValidationError('INVALID_INBOUND_COALESCING_SCOPE')))
2332
- return null
2378
+ digest = null
2333
2379
  }
2334
- return {
2335
- coalescingKey: JSON.stringify([
2336
- channelPubkey,
2337
- senderPubkey,
2338
- type,
2339
- code,
2340
- info.provenance,
2341
- digest
2342
- ]),
2343
- coalescingKeep: keep,
2344
- coalescingOrder: coalescingOrder(message, sequence, messageCreatedAtMs)
2380
+ if (digest) {
2381
+ return {
2382
+ coalescingKey: JSON.stringify([
2383
+ channelPubkey,
2384
+ senderPubkey,
2385
+ type,
2386
+ code,
2387
+ info.provenance,
2388
+ digest
2389
+ ]),
2390
+ coalescingKeep: keep,
2391
+ coalescingOrder: coalescingOrder(message, {
2392
+ policy,
2393
+ sequence,
2394
+ eventCreatedAtMs: messageCreatedAtMs
2395
+ })
2396
+ }
2345
2397
  }
2398
+
2399
+ return automaticCoalescingMetadata(type, channelPubkey, message, info)
2346
2400
  }
2347
2401
 
2348
2402
  async enqueueRumor (type, channelPubkey, message) {
@@ -2350,7 +2404,7 @@ export class PrivateMessenger {
2350
2404
  if (channel?.mode === 'watchtower' && type !== 'ask') return
2351
2405
  const info = deliveryInfo(message.event, message.senderPubkey ?? message.meta?.senderPubkey ?? message.meta?.router?.tags?.find(tag => tag[0] === 'f')?.[1])
2352
2406
  const eventId = message.event?.id || ''
2353
- // Stronger provenance must reach the app even while hearsay is pending.
2407
+ // Exact copies are dropped; stronger provenance participates in coalescing below.
2354
2408
  const dedupeKey = eventId ? [channelPubkey, type, eventId, info.provenance] : null
2355
2409
  if (dedupeKey && await this.queue.someBy('byChannelTypeEventId', dedupeKey)) {
2356
2410
  this.markSeen(channelPubkey, message.outer?.created_at || message.event?.created_at || nowSeconds())
@@ -2366,6 +2420,7 @@ export class PrivateMessenger {
2366
2420
  type,
2367
2421
  channelPubkey,
2368
2422
  receivedAt: nowSeconds(),
2423
+ deliveryPriority: this.#deliveryPriority(type, channelPubkey, message),
2369
2424
  event: message.event,
2370
2425
  ...info,
2371
2426
  payload: message.payload,
@@ -2375,8 +2430,9 @@ export class PrivateMessenger {
2375
2430
  meta: message.meta || null
2376
2431
  }
2377
2432
  Object.assign(record, this.#coalescingMetadata(type, channelPubkey, message, info) || {})
2433
+ let coalesced = null
2378
2434
  try {
2379
- const coalesced = record.coalescingKey
2435
+ coalesced = record.coalescingKey
2380
2436
  ? await this.queue.coalesceBy(COALESCING_INDEX, record, {
2381
2437
  compare: compareCoalescingItems,
2382
2438
  keep: record.coalescingKeep
@@ -2387,6 +2443,7 @@ export class PrivateMessenger {
2387
2443
  this.markSeen(channelPubkey, message.outer?.created_at || message.event?.created_at || nowSeconds())
2388
2444
  this.debug('message-coalescing-ignored', {
2389
2445
  code: messageCode(message) || '',
2446
+ policy: record.coalescingOrder?.policy || 'legacy',
2390
2447
  keep: record.coalescingKeep,
2391
2448
  payloadBytes: encoder.encode(JSON.stringify(record)).byteLength
2392
2449
  })
@@ -2395,6 +2452,7 @@ export class PrivateMessenger {
2395
2452
  if (coalesced) {
2396
2453
  this.debug('message-coalesced', {
2397
2454
  code: messageCode(message) || '',
2455
+ policy: record.coalescingOrder?.policy || 'legacy',
2398
2456
  keep: record.coalescingKeep,
2399
2457
  status: coalesced.status,
2400
2458
  removedUnreserved: coalesced.removed,
@@ -2434,7 +2492,9 @@ export class PrivateMessenger {
2434
2492
  }
2435
2493
  this.markSeen(channelPubkey, message.outer?.created_at || message.event?.created_at || nowSeconds())
2436
2494
  this.wakeDeliveries()
2437
- if (!record.coalescingKey) this.debug('enqueue', debugMessageInfo(type, channelPubkey, message))
2495
+ if (!record.coalescingKey || coalesced?.status === 'inserted') {
2496
+ this.debug('enqueue', debugMessageInfo(type, channelPubkey, message))
2497
+ }
2438
2498
  this.onMessageQueued?.()
2439
2499
  }
2440
2500
 
@@ -2625,6 +2685,8 @@ export class PrivateMessenger {
2625
2685
  const pause = this.pauseReasons.has('capacity') ? null : this.pause('capacity')
2626
2686
  pause?.catch(error => this.onError?.(error))
2627
2687
  this.startCapacityMonitor()
2688
+ this.wakeDeliveries()
2689
+ this.onMessageQueued?.()
2628
2690
  let summary
2629
2691
  try { summary = await this.inboxCapacitySummary() } catch {}
2630
2692
  return Object.assign(new Error('PRIVATE_MESSENGER_CAPACITY_PRESSURE'), {
@@ -2692,7 +2754,15 @@ export class PrivateMessenger {
2692
2754
  this.assertOpen()
2693
2755
  this.touchStorageActivity().catch(err => this.onError?.(err))
2694
2756
  await this.queueOperationTail
2695
- 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
+ })
2696
2766
  if (!reservation) return null
2697
2767
  if (this.closePromise) { await reservation.nack(); return null }
2698
2768
  let finish
@@ -4013,9 +4083,65 @@ function messageCode (message) {
4013
4083
  : null
4014
4084
  }
4015
4085
 
4016
- function coalescingOrder (message, sequence = null, messageCreatedAtMs = 0) {
4086
+ function automaticCoalescingMetadata (type, channelPubkey, message, info) {
4087
+ const identity = automaticEventIdentity(message.event)
4088
+ if (!identity || !channelPubkey || !type || !info.provenance) return null
4089
+ const eventIdPriority = PROVENANCE_PRIORITY[info.provenance] ?? 0
4090
+ return {
4091
+ coalescingKey: JSON.stringify([
4092
+ channelPubkey,
4093
+ type,
4094
+ 'nostr-identity',
4095
+ identity.kind,
4096
+ identity.digest
4097
+ ]),
4098
+ coalescingKeep: 'latest',
4099
+ coalescingOrder: identity.kind === 'address'
4100
+ ? {
4101
+ policy: 'event-address',
4102
+ eventIdPriority,
4103
+ inner: Number.isSafeInteger(message.event?.created_at) ? message.event.created_at : 0,
4104
+ eventId: message.event.id
4105
+ }
4106
+ : {
4107
+ policy: 'event-id',
4108
+ eventIdPriority
4109
+ }
4110
+ }
4111
+ }
4112
+
4113
+ function automaticEventIdentity (event) {
4114
+ if (!event || typeof event.id !== 'string' || !event.id) return null
4115
+ if (!isEphemeralEvent(event)) {
4116
+ const firstD = event.tags?.find(tag => Array.isArray(tag) && tag[0] === 'd')
4117
+ let coordinate = null
4118
+ if (typeof firstD?.[1] === 'string') {
4119
+ coordinate = firstD[1]
4120
+ } else {
4121
+ const classes = classifyEvent(event)
4122
+ if (classes.includes('replaceable') || classes.includes('addressable')) coordinate = ''
4123
+ }
4124
+ if (coordinate !== null && Number.isSafeInteger(event.kind) && event.kind >= 0 && typeof event.pubkey === 'string') {
4125
+ return {
4126
+ kind: 'address',
4127
+ digest: coalescingDigest(['nostr-address:v1', event.kind, event.pubkey, coordinate])
4128
+ }
4129
+ }
4130
+ }
4131
+ return {
4132
+ kind: 'event-id',
4133
+ digest: coalescingDigest(['nostr-event-id:v1', event.id])
4134
+ }
4135
+ }
4136
+
4137
+ function coalescingOrder (message, {
4138
+ policy = 'semantic',
4139
+ sequence = null,
4140
+ eventCreatedAtMs = 0
4141
+ } = {}) {
4017
4142
  const order = {
4018
- eventTimeMs: messageCreatedAtMs,
4143
+ policy,
4144
+ eventTimeMs: eventCreatedAtMs,
4019
4145
  outer: Number.isSafeInteger(message?.outer?.created_at) ? message.outer.created_at : 0,
4020
4146
  inner: Number.isSafeInteger(message?.event?.created_at) ? message.event.created_at : 0,
4021
4147
  eventId: message?.event?.id || ''
@@ -4025,6 +4151,34 @@ function coalescingOrder (message, sequence = null, messageCreatedAtMs = 0) {
4025
4151
  }
4026
4152
 
4027
4153
  function compareCoalescingOrder (left, right) {
4154
+ if (left?.policy === 'event-id' || right?.policy === 'event-id') {
4155
+ return compareEventIdCoalescingOrder(left, right)
4156
+ }
4157
+ if (left?.policy === 'event-address' || right?.policy === 'event-address') {
4158
+ return compareAddressCoalescingOrder(left, right)
4159
+ }
4160
+ return compareLegacyCoalescingOrder(left, right)
4161
+ }
4162
+
4163
+ function compareEventIdCoalescingOrder (left, right) {
4164
+ return (left?.eventIdPriority || 0) - (right?.eventIdPriority || 0)
4165
+ }
4166
+
4167
+ function compareAddressCoalescingOrder (left, right) {
4168
+ const leftId = left?.eventId || ''
4169
+ const rightId = right?.eventId || ''
4170
+ if (leftId === rightId) {
4171
+ return (left?.eventIdPriority || 0) - (right?.eventIdPriority || 0)
4172
+ }
4173
+ const trust = ((left?.eventIdPriority || 0) > 0 ? 1 : 0) - ((right?.eventIdPriority || 0) > 0 ? 1 : 0)
4174
+ if (trust) return trust
4175
+ const leftTime = Number.isSafeInteger(left?.inner) ? left.inner : 0
4176
+ const rightTime = Number.isSafeInteger(right?.inner) ? right.inner : 0
4177
+ if (leftTime !== rightTime) return leftTime < rightTime ? -1 : 1
4178
+ return leftId < rightId ? 1 : -1
4179
+ }
4180
+
4181
+ function compareLegacyCoalescingOrder (left, right) {
4028
4182
  if (Number.isSafeInteger(left?.sequence) && Number.isSafeInteger(right?.sequence) &&
4029
4183
  left.sequence !== right.sequence) {
4030
4184
  return left.sequence < right.sequence ? -1 : 1
@@ -4044,11 +4198,18 @@ function compareCoalescingOrder (left, right) {
4044
4198
  }
4045
4199
 
4046
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
4047
4204
  return compareCoalescingOrder(left?.coalescingOrder, right?.coalescingOrder)
4048
4205
  }
4049
4206
 
4050
4207
  function idempotencyDigest (idempotencyKey) {
4051
- return bytesToHex(sha256(encoder.encode(JSON.stringify(['idempotency', idempotencyKey]))))
4208
+ return coalescingDigest(['idempotency', idempotencyKey])
4209
+ }
4210
+
4211
+ function coalescingDigest (value) {
4212
+ return bytesToHex(sha256(encoder.encode(JSON.stringify(value))))
4052
4213
  }
4053
4214
 
4054
4215
  function coalescingError (cause) {
@@ -4058,6 +4219,13 @@ function coalescingError (cause) {
4058
4219
  })
4059
4220
  }
4060
4221
 
4222
+ function inboundPriorityError (cause) {
4223
+ return Object.assign(new Error('INVALID_INBOUND_PRIORITY'), {
4224
+ code: 'INVALID_INBOUND_PRIORITY',
4225
+ cause
4226
+ })
4227
+ }
4228
+
4061
4229
  function safeDiagnosticToken (value) {
4062
4230
  return typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9:._-]{0,159}$/.test(value)
4063
4231
  ? value
@@ -4175,6 +4343,7 @@ function withoutQueueMetadata (item) {
4175
4343
  delete value.coalescingKey
4176
4344
  delete value.coalescingKeep
4177
4345
  delete value.coalescingOrder
4346
+ delete value.deliveryPriority
4178
4347
  delete value[SEED_KEY]
4179
4348
  delete value[SEED_TIME]
4180
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
  }