libp2r2p 0.12.10 → 0.12.12

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
@@ -359,6 +359,39 @@ await messenger.tell({
359
359
  })
360
360
  ```
361
361
 
362
+ ### Inbound message coalescing
363
+
364
+ `PrivateMessenger` accepts an optional synchronous
365
+ `resolveInboundCoalescing(message, { idempotencyKey })` constructor callback.
366
+ The enriched `message` includes `type` and `channelPubkey`. The callback returns
367
+ `null` or `{ key, keep?, sequence? }`, where `key` is a lowercase 64-character
368
+ SHA-256 digest, `keep` is `latest` (default) or `oldest`, and `sequence` is an
369
+ optional non-negative safe integer. Sequence units are resolver-owned and are
370
+ compared only within records sharing the final scoped coalescing key.
371
+
372
+ The resolver runs for ask, reply, tell, yell, message and nym deliveries after
373
+ exact event-ID deduplication. The final coalescing key is scoped by channel,
374
+ sender, type, message code and provenance. `latest` replaces the pending item in
375
+ place; when both records carry a sequence, `latest` compares it before envelope
376
+ `created_at`, then falls back to outer/inner timestamps and event ID. `oldest`
377
+ preserves the pending item. While an item is reserved, both policies allow at
378
+ most one successor. Sequences persist in the internal queue metadata and are
379
+ not delivered to the app. Older recovered events do not replace newer requests.
380
+
381
+ For ask, reply, tell and yell, exactly one `["D", key]` tag may serve as an
382
+ automatic fallback when the resolver returns `null`. Its key is non-empty and
383
+ limited to 256 UTF-8 bytes. Message and nym always expose
384
+ `idempotencyKey: null` to the resolver and do not interpret D automatically, so
385
+ arbitrary Nostr kinds retain their own tag semantics.
386
+
387
+ `ask`, `reply`, `tell` and `yell` accept `idempotencyKey` and place D before the
388
+ `h` tag. Invalid keys throw `INVALID_IDEMPOTENCY_KEY`. Broadcast/signed-event
389
+ APIs require the app to put D into the event before hashing/signing.
390
+
391
+ Coalescing does not provide an ingress rate limit or per-peer quota. Exact
392
+ event deduplication, authorization, quarantine, global inbox capacity,
393
+ pause/ACK/NACK ownership and existing storage policy remain independent.
394
+
362
395
  ### Deleting Private Broadcasts
363
396
 
364
397
  By default, each high-level private-message send creates one fresh deletion
@@ -1219,6 +1252,16 @@ the old token: its `ack`, `nack` and `renew` return false. Successful writes wak
1219
1252
  local waiting consumers. Like the other indexed methods, `putBy` is exclusive
1220
1253
  to `idb-queue`; the Web Storage queue's common API is unchanged.
1221
1254
 
1255
+ `queue.coalesceBy(indexName, item, { keep = 'latest', compare, now })` is the
1256
+ non-unique-indexed coalescing variant. `latest` replaces the oldest unreserved
1257
+ match in place and removes other unreserved matches atomically. `oldest` keeps
1258
+ the existing pending match and reports it as ignored. Both policies append one
1259
+ successor when every match is currently reserved. The optional comparator keeps
1260
+ an older item from replacing a newer one. Results use `inserted`, `replaced`,
1261
+ `successor` or `ignored`, with the number of extra pending rows removed and the
1262
+ retained/appended position. Capacity and byte accounting follow the same
1263
+ `reject` rules as `putBy`.
1264
+
1222
1265
  Both queue implementations support
1223
1266
  `createQueue({ prefix, evictionPolicy: 'reject', maxBytes })` to opt out of
1224
1267
  capacity eviction. Oversized items reject with `QUEUE_ITEM_TOO_LARGE`, full
@@ -1228,13 +1271,15 @@ Opening a reject-policy queue under a smaller budget preserves existing items.
1228
1271
  Positional replacement and insertion follow the same rule: they reject instead
1229
1272
  of evicting when the resulting queue would exceed the limit.
1230
1273
 
1231
- `queue.reserve({ leaseMs = 30000 })` returns `null` or
1274
+ `queue.reserve({ leaseMs = 30000, nackCoalescingIndex })` returns `null` or
1232
1275
  `{ item, ack, nack, renew }`. Reservation token/deadline are internal record
1233
1276
  metadata, persisted atomically in the same IndexedDB transaction as selection.
1234
1277
  `renew()` extends a still-valid lease. Low-level callers own renewal and release;
1235
1278
  PrivateMessenger supplies both. Do not mix reservations with destructive or
1236
1279
  position-shifting queue operations on the same queue except explicit removal.
1237
1280
  A stale token cannot acknowledge a newly reserved or replaced record.
1281
+ `nackCoalescingIndex` names a non-unique index: when another matching item is
1282
+ pending, NACK deletes the superseded active item instead of requeueing it.
1238
1283
 
1239
1284
  `queue.getCapacity()` is part of the common API and returns
1240
1285
  `{ usedBytes, maxBytes }`; capacity rejections also expose `requiredBytes` and
@@ -1364,6 +1409,8 @@ Both packers use `useBulkPacing: true` by default. Bulk EVENT publications are
1364
1409
  serialized per relay, start at least one second apart, and use a relay-local
1365
1410
  1..30 second exponential backoff when no retryAt is supplied. Relay advice
1366
1411
  overrides the local backoff and relays remain independent.
1412
+ Packers may receive a shared `idempotencyKey` base and append `:<index>` to each
1413
+ reply. Missing-message recovery supplies a question-scoped base by default.
1367
1414
 
1368
1415
 
1369
1416
  ### Private subscription recovery (0.11.8)
@@ -295,6 +295,25 @@ export async function createQueue ({
295
295
  return Number.isFinite(sessionMaxBytes)
296
296
  }
297
297
 
298
+ function indexDefinition (indexName) {
299
+ return indexDefinitions.find(index => index.name === indexName) || null
300
+ }
301
+
302
+ function itemIndexKey (definition, item) {
303
+ const readKey = path => path.split('.').reduce((part, key) => part?.[key], item)
304
+ return Array.isArray(definition.keyPath)
305
+ ? definition.keyPath.map(readKey)
306
+ : readKey(definition.keyPath)
307
+ }
308
+
309
+ function assertValidIndexKey (key, code = 'QUEUE_PUT_KEY_INVALID') {
310
+ try {
311
+ indexedDB.cmp(key, key)
312
+ } catch {
313
+ throw new ValidationError(code)
314
+ }
315
+ }
316
+
298
317
  function evictionDirectionFor (operation, { index = 0, length = 0 } = {}) {
299
318
  if (configuredEvictionPolicy === 'head') return 'head'
300
319
  if (configuredEvictionPolicy === 'tail') return 'tail'
@@ -735,14 +754,13 @@ export async function createQueue ({
735
754
  }
736
755
 
737
756
  async function putBy (indexName, item, { existingOnly = false } = {}) {
738
- const definition = indexDefinitions.find(index => index.name === indexName)
757
+ const definition = indexDefinition(indexName)
739
758
  if (!definition?.unique || definition.multiEntry) throw new ValidationError('QUEUE_PUT_INDEX_INVALID')
740
759
  // Snapshot before awaiting IndexedDB so the lookup key and stored value
741
760
  // cannot diverge if the caller changes its object during the transaction.
742
761
  const value = structuredClone(item)
743
- const readKey = path => path.split('.').reduce((part, key) => part?.[key], value)
744
- const key = Array.isArray(definition.keyPath) ? definition.keyPath.map(readKey) : readKey(definition.keyPath)
745
- try { indexedDB.cmp(key, key) } catch { throw new ValidationError('QUEUE_PUT_KEY_INVALID') }
762
+ const key = itemIndexKey(definition, value)
763
+ assertValidIndexKey(key)
746
764
  const requiredBytes = itemForStorage(0, value).byteSize
747
765
  const written = await mutate(async (tx, state) => {
748
766
  const { result: previous } = await run('get', [key], ITEMS_STORE, indexName, { tx })
@@ -762,6 +780,76 @@ export async function createQueue ({
762
780
  return written
763
781
  }
764
782
 
783
+ async function coalesceBy (indexName, item, {
784
+ compare,
785
+ keep = 'latest',
786
+ now = Date.now()
787
+ } = {}) {
788
+ const definition = indexDefinition(indexName)
789
+ if (!definition || definition.unique || definition.multiEntry) {
790
+ throw new ValidationError('QUEUE_COALESCE_INDEX_INVALID')
791
+ }
792
+ if (compare != null && typeof compare !== 'function') {
793
+ throw new ValidationError('QUEUE_COALESCE_COMPARE_INVALID')
794
+ }
795
+ if (keep !== 'oldest' && keep !== 'latest') {
796
+ throw new ValidationError('QUEUE_COALESCE_KEEP_INVALID')
797
+ }
798
+ if (!Number.isSafeInteger(now) || now < 0) throw new ValidationError('QUEUE_COALESCE_NOW_INVALID')
799
+ const value = structuredClone(item)
800
+ const key = itemIndexKey(definition, value)
801
+ assertValidIndexKey(key, 'QUEUE_COALESCE_KEY_INVALID')
802
+ const requiredBytes = itemForStorage(0, value).byteSize
803
+ return mutate(async (tx, state) => {
804
+ const { result: records } = await run('getAll', [key], ITEMS_STORE, indexName, { tx })
805
+ const active = []
806
+ const pending = []
807
+ for (const record of records) {
808
+ if (record.reservation?.until > now) active.push(record)
809
+ else pending.push(record)
810
+ }
811
+ pending.sort((left, right) => left.position - right.position)
812
+ if (compare && records.length) {
813
+ const latest = records.reduce((current, candidate) => (
814
+ compare(candidate.item, current.item) > 0 ? candidate : current
815
+ ))
816
+ if (compare(value, latest.item) <= 0) {
817
+ return { status: 'ignored', removed: 0, position: null }
818
+ }
819
+ }
820
+
821
+ if (keep === 'oldest' && pending.length) {
822
+ return { status: 'ignored', removed: 0, position: null }
823
+ }
824
+
825
+ if (!pending.length) {
826
+ await pushInTransaction(tx, state, value)
827
+ return {
828
+ status: active.length ? 'successor' : 'inserted',
829
+ removed: 0,
830
+ position: state.tail - 1
831
+ }
832
+ }
833
+
834
+ const target = pending[0]
835
+ let removed = 0
836
+ for (const record of pending.slice(1)) {
837
+ await deleteRecord(tx, record.position)
838
+ state.usedBytes = Math.max(0, state.usedBytes - (record.byteSize || 0))
839
+ removed++
840
+ }
841
+ await putItem(tx, state, target.position, value, {
842
+ direction: evictionDirectionFor('setAt', {
843
+ index: target.position - state.head,
844
+ length: state.tail - state.head
845
+ }),
846
+ protectedPositions: new Set([target.position])
847
+ })
848
+ await trimBounds(tx, state)
849
+ return { status: 'replaced', removed, position: target.position }
850
+ }, { requiredBytes, wakeWaiters: true })
851
+ }
852
+
765
853
  async function getBy (indexName, query) {
766
854
  // Explicit index operations avoid scanning queue values in JavaScript.
767
855
  return snapshot(async tx => {
@@ -795,8 +883,17 @@ export async function createQueue ({
795
883
  // Reservations are stored atomically with the item; another tab/process can
796
884
  // reclaim an expired lease after a crash. Destructive/positional queue APIs
797
885
  // must not be mixed with reservations on the same queue.
798
- async function reserve ({ leaseMs = 30000, now = Date.now() } = {}) {
886
+ async function reserve ({
887
+ leaseMs = 30000,
888
+ now = Date.now(),
889
+ nackCoalescingIndex
890
+ } = {}) {
799
891
  if (!Number.isSafeInteger(leaseMs) || leaseMs <= 0 || !Number.isSafeInteger(now) || now < 0) throw new ValidationError('QUEUE_INVALID_LEASE')
892
+ const nackDefinition = nackCoalescingIndex == null ? null : indexDefinition(nackCoalescingIndex)
893
+ if (nackCoalescingIndex != null &&
894
+ (!nackDefinition || nackDefinition.unique || nackDefinition.multiEntry)) {
895
+ throw new ValidationError('QUEUE_NACK_COALESCE_INDEX_INVALID')
896
+ }
800
897
  const token = globalThis.crypto.randomUUID()
801
898
  const reserved = await mutate(async tx => {
802
899
  const p = deferred()
@@ -829,8 +926,31 @@ export async function createQueue ({
829
926
  await trimBounds(tx, state)
830
927
  } else {
831
928
  if (action === 'renew') record.reservation.until = at + leaseMs
832
- else delete record.reservation
833
- await putRecord(tx, record)
929
+ else {
930
+ let superseded = false
931
+ if (nackDefinition) {
932
+ try {
933
+ const key = itemIndexKey(nackDefinition, record.item)
934
+ indexedDB.cmp(key, key)
935
+ const { result: matches } = await run(
936
+ 'getAll',
937
+ [key],
938
+ ITEMS_STORE,
939
+ nackCoalescingIndex,
940
+ { tx }
941
+ )
942
+ superseded = matches.some(match => match.position > record.position)
943
+ } catch {}
944
+ }
945
+ if (superseded) {
946
+ await deleteRecord(tx, record.position)
947
+ state.usedBytes = Math.max(0, state.usedBytes - record.byteSize)
948
+ await trimBounds(tx, state)
949
+ } else {
950
+ delete record.reservation
951
+ await putRecord(tx, record)
952
+ }
953
+ }
834
954
  }
835
955
  return true
836
956
  }, { wakeWaiters: action !== 'renew' })
@@ -937,6 +1057,7 @@ export async function createQueue ({
937
1057
  some,
938
1058
  clear,
939
1059
  putBy,
1060
+ coalesceBy,
940
1061
  getBy,
941
1062
  someBy,
942
1063
  removeBy,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libp2r2p",
3
- "version": "0.12.10",
3
+ "version": "0.12.12",
4
4
  "description": "Peer-to-relay-to-peer",
5
5
  "keywords": [
6
6
  "p2r2p",
@@ -0,0 +1,57 @@
1
+ import { ValidationError } from '../../error/index.js'
2
+
3
+ export const IDEMPOTENCY_TAG = 'D'
4
+ export const MAX_IDEMPOTENCY_KEY_BYTES = 256
5
+
6
+ const encoder = new TextEncoder()
7
+ const MAX_CHUNK_SUFFIX_BYTES = String(Number.MAX_SAFE_INTEGER).length + 1
8
+ const MAX_IDEMPOTENCY_KEY_BASE_BYTES = MAX_IDEMPOTENCY_KEY_BYTES - MAX_CHUNK_SUFFIX_BYTES
9
+
10
+ function keyBytes (value) {
11
+ return encoder.encode(value).byteLength
12
+ }
13
+
14
+ function invalidKey () {
15
+ return new ValidationError('INVALID_IDEMPOTENCY_KEY')
16
+ }
17
+
18
+ export function normalizeIdempotencyKey (value) {
19
+ if (value === undefined) return ''
20
+ if (typeof value !== 'string' || !value || keyBytes(value) > MAX_IDEMPOTENCY_KEY_BYTES) {
21
+ throw invalidKey()
22
+ }
23
+ return value
24
+ }
25
+
26
+ export function normalizeIdempotencyKeyBase (value) {
27
+ if (value === undefined) return ''
28
+ if (typeof value !== 'string' || !value || keyBytes(value) > MAX_IDEMPOTENCY_KEY_BASE_BYTES) {
29
+ throw invalidKey()
30
+ }
31
+ return value
32
+ }
33
+
34
+ export function chunkIdempotencyKey (base, index) {
35
+ const normalizedBase = normalizeIdempotencyKeyBase(base)
36
+ if (!normalizedBase) return undefined
37
+ if (!Number.isSafeInteger(index) || index < 0) throw invalidKey()
38
+ return normalizeIdempotencyKey(`${normalizedBase}:${index}`)
39
+ }
40
+
41
+ export function appendIdempotencyTag (tags, idempotencyKey) {
42
+ const key = normalizeIdempotencyKey(idempotencyKey)
43
+ if (!key) return tags
44
+ return [[IDEMPOTENCY_TAG, key], ...tags]
45
+ }
46
+
47
+ export function readIdempotencyKey (event) {
48
+ const tags = (Array.isArray(event?.tags) ? event.tags : [])
49
+ .filter(tag => Array.isArray(tag) && tag[0] === IDEMPOTENCY_TAG)
50
+ if (!tags.length) return { key: null, reason: 'missing' }
51
+ if (tags.length !== 1 || tags[0].length !== 2) return { key: null, reason: 'malformed' }
52
+ try {
53
+ return { key: normalizeIdempotencyKey(tags[0][1]), reason: '' }
54
+ } catch {
55
+ return { key: null, reason: 'malformed' }
56
+ }
57
+ }
@@ -5,6 +5,7 @@ import { generateKeypair, keypairFromSeckey } from '../key/index.js'
5
5
  import * as privateChannel from '../private-channel/index.js'
6
6
  import { normalizeRumor, deliveryInfo } from '../private-channel/helpers/rumor.js'
7
7
  import { normalizePreparedPublications } from '../private-channel/helpers/prepared.js'
8
+ import { appendIdempotencyTag } from './helpers/idempotency.js'
8
9
 
9
10
  export const ASK_KIND = 7329
10
11
  export const REPLY_KIND = 7330
@@ -118,11 +119,11 @@ function addHeaderTag (tags, { code, error }) {
118
119
  return out.concat([header])
119
120
  }
120
121
 
121
- function makeMessageRumor ({ kind, tags, message }) {
122
+ function makeMessageRumor ({ kind, tags, message, idempotencyKey }) {
122
123
  const normalized = normalizeMessage(message)
123
124
  return {
124
125
  kind,
125
- tags: addHeaderTag(tags, normalized),
126
+ tags: addHeaderTag(appendIdempotencyTag(tags, idempotencyKey), normalized),
126
127
  content: normalized.content
127
128
  }
128
129
  }
@@ -717,6 +718,7 @@ export async function ask ({
717
718
  payload,
718
719
  error,
719
720
  content,
721
+ idempotencyKey,
720
722
  expirationSeconds,
721
723
  useBulkPacing = false,
722
724
  temporaryStorageArea,
@@ -737,7 +739,7 @@ export async function ask ({
737
739
  const identity = await senderSigner?.getPublicKey?.()
738
740
  const session = defaultSessions.get(identity)
739
741
  if (!session) throw new Error('PRIVATE_MESSAGE_NOT_WATCHING')
740
- return session.ask({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receiverPubkey, relays, relayToReceivers, recoveryRelays, message, code, payload, error, content, expirationSeconds, useBulkPacing, temporaryStorageArea, _getIykcProofs, deletionPubkey, deletionSeckey, autoDeletionCapability, _publish })
742
+ return session.ask({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receiverPubkey, relays, relayToReceivers, recoveryRelays, message, code, payload, error, content, idempotencyKey, expirationSeconds, useBulkPacing, temporaryStorageArea, _getIykcProofs, deletionPubkey, deletionSeckey, autoDeletionCapability, _publish })
741
743
  }
742
744
 
743
745
  const { event: question, wireEvent } = await makeOutgoingRumor({
@@ -745,7 +747,8 @@ export async function ask ({
745
747
  rumor: makeMessageRumor({
746
748
  kind: ASK_KIND,
747
749
  tags: [['r', receiverPubkey]],
748
- message: message || { code, payload, error, content }
750
+ message: message || { code, payload, error, content },
751
+ idempotencyKey
749
752
  })
750
753
  })
751
754
  const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability })
@@ -769,6 +772,7 @@ export async function reply ({
769
772
  payload,
770
773
  error,
771
774
  content,
775
+ idempotencyKey,
772
776
  expirationSeconds,
773
777
  useBulkPacing = false,
774
778
  temporaryStorageArea,
@@ -787,7 +791,8 @@ export async function reply ({
787
791
  rumor: makeMessageRumor({
788
792
  kind: REPLY_KIND,
789
793
  tags: [['q', question.id], ['r', receiverPubkey]],
790
- message: message || { code, payload, error, content }
794
+ message: message || { code, payload, error, content },
795
+ idempotencyKey
791
796
  })
792
797
  })
793
798
  const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability })
@@ -809,6 +814,7 @@ export async function tell ({
809
814
  payload,
810
815
  error,
811
816
  content,
817
+ idempotencyKey,
812
818
  expirationSeconds,
813
819
  useBulkPacing = false,
814
820
  temporaryStorageArea,
@@ -826,7 +832,8 @@ export async function tell ({
826
832
  rumor: makeMessageRumor({
827
833
  kind: TELL_KIND,
828
834
  tags: [['r', receiverPubkey]],
829
- message: message || { code, payload, error, content }
835
+ message: message || { code, payload, error, content },
836
+ idempotencyKey
830
837
  })
831
838
  })
832
839
  const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability })
@@ -848,6 +855,7 @@ export async function yell ({
848
855
  payload,
849
856
  error,
850
857
  content,
858
+ idempotencyKey,
851
859
  expirationSeconds,
852
860
  useBulkPacing = false,
853
861
  temporaryStorageArea,
@@ -870,7 +878,8 @@ export async function yell ({
870
878
  const rumor = makeMessageRumor({
871
879
  kind: TELL_KIND,
872
880
  tags: [],
873
- message: message || { code, payload, error, content }
881
+ message: message || { code, payload, error, content },
882
+ idempotencyKey
874
883
  })
875
884
  if (createdAt !== undefined) rumor.created_at = createdAt
876
885
  const { event, wireEvent } = await makeOutgoingRumor({
@@ -75,6 +75,8 @@ the existing compact-record JSONL packer's `index`, `isLast`, and `jsonl` fields
75
75
  The inner reply's `q` references the request event. No new terminal availability
76
76
  message is required and `isLast` never establishes file completeness. Late
77
77
  responses from authorized seeders remain useful during an active download.
78
+ Each reply carries D as `<code>:<question-id>:<root>:<index>`; retries of one
79
+ chunk therefore share an identity without collapsing other chunks.
78
80
  Seed replies run outside the DM dispatcher, with at most two reply workers and
79
81
  sixteen queued requests; workers yield between records so control traffic can
80
82
  continue. Requests discarded at the queue bound can be retried.
@@ -196,7 +196,10 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
196
196
  }
197
197
  },
198
198
  channelPubkey: file.fileChannelPubkey, question, receiverPubkey: question.pubkey,
199
- code: FILE_CHUNKS_REPLY_CODE, eventsPerChunk: 1, recordsFromInput: record => [record]
199
+ code: FILE_CHUNKS_REPLY_CODE,
200
+ idempotencyKey: `${FILE_CHUNKS_REPLY_CODE}:${question.id}:${file.root}`,
201
+ eventsPerChunk: 1,
202
+ recordsFromInput: record => [record]
200
203
  })
201
204
  for (const index of indices) {
202
205
  usable(file)
@@ -224,7 +227,21 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
224
227
  if (file.fileChannelPubkey !== payload.fileChannelPubkey) throw new ValidationError('FILE_CHANNEL_MISMATCH')
225
228
  if (!packer) {
226
229
  const routes = await routing(file, question.pubkey)
227
- packer = createEventReplyPacker({ messenger: { reply: async options => { usable(file); return _messages.reply({ ...sendOptions(file, routes), ...options }) } }, channelPubkey: file.fileChannelPubkey, question, receiverPubkey: question.pubkey, code: FILE_CHUNKS_REPLY_CODE, eventsPerChunk: 1, recordsFromInput: row => compactRecordsFromSeed(row, { receiverPubkey: question.pubkey }) })
230
+ packer = createEventReplyPacker({
231
+ messenger: {
232
+ reply: async options => {
233
+ usable(file)
234
+ return _messages.reply({ ...sendOptions(file, routes), ...options })
235
+ }
236
+ },
237
+ channelPubkey: file.fileChannelPubkey,
238
+ question,
239
+ receiverPubkey: question.pubkey,
240
+ code: FILE_CHUNKS_REPLY_CODE,
241
+ idempotencyKey: `${FILE_CHUNKS_REPLY_CODE}:${question.id}:${file.root}`,
242
+ eventsPerChunk: 1,
243
+ recordsFromInput: row => compactRecordsFromSeed(row, { receiverPubkey: question.pubkey })
244
+ })
228
245
  }
229
246
  await packer.update(seed)
230
247
  await new Promise(resolve => setTimeout(resolve, 0))
@@ -19,10 +19,10 @@
19
19
  // await persistPrivateMessage(message)
20
20
  // await ack()
21
21
  // }
22
- // await messenger.ask({ receiverPubkey, payload: { ping: true } })
23
- // await messenger.reply({ question: msg.question, payload: { ok: true } })
24
- // await messenger.tell({ receiverPubkey, payload: { note: 'hello' } })
25
- // await messenger.yell({ receiverPubkeys, payload: { notice: 'hello all' } })
22
+ // const { question } = await messenger.ask({ receiverPubkey, payload: { ping: true }, idempotencyKey: 'request:42' })
23
+ // await messenger.reply({ question, payload: { ok: true }, idempotencyKey: 'reply:42' })
24
+ // await messenger.tell({ receiverPubkey, payload: { note: 'hello' }, idempotencyKey: 'notification:42' })
25
+ // await messenger.yell({ receiverPubkeys, payload: { notice: 'hello all' }, idempotencyKey: 'notice:42' })
26
26
  // await messenger.broadcastRumor({ receiverPubkeys, rumor: { kind, tags: [], content } })
27
27
  // await messenger.broadcastEvent({ receiverPubkeys, event: signedNostrEvent })
28
28
  // await messenger.broadcastNymRumor({ rumor: { kind, tags: [], content } })
@@ -62,13 +62,16 @@ import { migrateMessageQueue } from './services/migrate-message-queue.js'
62
62
  import { createPendingDecryption, pendingContentKeyGroup, pendingMissingContentKeyGroup } from './services/pending-decryption.js'
63
63
  import { createDecryptionScheduler } from './services/decryption-scheduler.js'
64
64
  import { decryptionError, isDeferredDecryptionError } from '../private-channel/helpers/decryption-error.js'
65
+ import { bytesToHex } from '../base16/index.js'
65
66
  import { bytesToBase64 } from '../base64/index.js'
67
+ import { sha256 } from '@noble/hashes/sha2.js'
66
68
  import { ValidationError } from '../error/index.js'
67
69
  import { getRelaysByPubkey, pickRelaysForPubkeys, subscribeRelayListUpdates, relayPool } from '../relay/index.js'
68
70
  import * as privateChannel from '../private-channel/index.js'
69
71
  import { DEFAULT_RECEIVED_CHUNK_TTL_MS } from '../private-channel/services/received-chunks.js'
70
72
  import { createQueue } from '../idb-queue/index.js'
71
73
  import { createChannelStateStore } from './services/channel-state.js'
74
+ import { normalizeIdempotencyKey, readIdempotencyKey } from '../private-message/helpers/idempotency.js'
72
75
  import { DEFAULT_STALE_CHANNEL_SECONDS } from './constants/index.js'
73
76
  import {
74
77
  activatePrivateMessengerStorage,
@@ -123,8 +126,13 @@ const MESSAGE_QUEUE_HIGH_WATER_RATIO = 0.7
123
126
  const MESSAGE_QUEUE_LOW_WATER_RATIO = 0.5
124
127
  const SEED_KEY = '__p2r2pSeedKey'
125
128
  const SEED_TIME = '__p2r2pSeedTime'
129
+ const COALESCING_INDEX = 'byCoalescingKey'
130
+ const COALESCING_DIGEST = /^[0-9a-f]{64}$/
131
+ const COALESCING_KEEP = new Set(['oldest', 'latest'])
132
+ const DEDUPE_TYPES = new Set(['ask', 'reply', 'tell', 'yell'])
126
133
  const MESSAGE_QUEUE_INDEXES = {
127
134
  byChannel: 'channelPubkey',
135
+ [COALESCING_INDEX]: 'coalescingKey',
128
136
  byChannelTypeEventId: {
129
137
  keyPath: ['channelPubkey', 'type', 'event.id', 'provenance'],
130
138
  unique: true
@@ -303,6 +311,7 @@ export class PrivateMessenger {
303
311
  onStateChanged,
304
312
  onDebug,
305
313
  onError = defaultOnError,
314
+ resolveInboundCoalescing,
306
315
  _privateMessage = privateMessage,
307
316
  _privateChannel = privateChannel,
308
317
  _getRelaysByPubkey = getRelaysByPubkey,
@@ -324,6 +333,9 @@ export class PrivateMessenger {
324
333
  } = {}) {
325
334
  if (onStateChanged != null && typeof onStateChanged !== 'function') throw new ValidationError('INVALID_ON_STATE_CHANGED')
326
335
  if (typeof pendingDecryptionReady !== 'boolean') throw new ValidationError('INVALID_PENDING_DECRYPTION_READY')
336
+ if (resolveInboundCoalescing != null && typeof resolveInboundCoalescing !== 'function') {
337
+ throw new ValidationError('INVALID_RESOLVE_INBOUND_COALESCING')
338
+ }
327
339
  this.fallbackRelays = normalizeFallbackRelays(fallbackRelays)
328
340
  this.fallbackDelayMs = normalizeFallbackDelay(fallbackDelayMs)
329
341
  this.offlineRecoverySeconds = normalizeOfflineRecoverySeconds(offlineRecoverySeconds)
@@ -368,6 +380,7 @@ export class PrivateMessenger {
368
380
  this._random = _random
369
381
  this.onMessageQueued = onMessageQueued
370
382
  this.onDebug = onDebug
383
+ this.resolveInboundCoalescing = resolveInboundCoalescing
371
384
  this._privateMessage = _privateMessage.createPrivateMessageSession?.() ?? _privateMessage
372
385
  this._privateChannel = _privateChannel
373
386
  this._getRelaysByPubkey = _getRelaysByPubkey
@@ -1946,7 +1959,14 @@ export class PrivateMessenger {
1946
1959
  const pubkey = pending.record.channelPubkey
1947
1960
  if (!this.channels.has(pubkey) || !this.desiredChannels.has(pubkey)) { this.pendingStorageWrites.delete(key); continue }
1948
1961
  try {
1949
- if (!pending.dedupeKey || !await this.queue.someBy('byChannelTypeEventId', pending.dedupeKey)) await this.queue.enqueue(pending.record)
1962
+ if (pending.record.coalescingKey) {
1963
+ await this.queue.coalesceBy(COALESCING_INDEX, pending.record, {
1964
+ compare: compareCoalescingItems,
1965
+ keep: pending.record.coalescingKeep
1966
+ })
1967
+ } else if (!pending.dedupeKey || !await this.queue.someBy('byChannelTypeEventId', pending.dedupeKey)) {
1968
+ await this.queue.enqueue(pending.record)
1969
+ }
1950
1970
  } catch (error) { if (error?.name !== 'ConstraintError') throw error }
1951
1971
  signal.throwIfAborted()
1952
1972
  this.pendingStorageWrites.delete(key)
@@ -2186,6 +2206,74 @@ export class PrivateMessenger {
2186
2206
  await this.enqueueRumor('message', channelPubkey, message)
2187
2207
  }
2188
2208
 
2209
+ #coalescingMetadata (type, channelPubkey, message, info) {
2210
+ const supportsIdempotencyTag = DEDUPE_TYPES.has(type)
2211
+ const tagged = supportsIdempotencyTag
2212
+ ? readIdempotencyKey(message.event)
2213
+ : { key: null, reason: '' }
2214
+ if (tagged.reason && tagged.reason !== 'missing') {
2215
+ this.debug('idempotency-tag-ignored', {
2216
+ type,
2217
+ code: messageCode(message) || '',
2218
+ reason: tagged.reason
2219
+ })
2220
+ }
2221
+
2222
+ let resolved = null
2223
+ if (this.resolveInboundCoalescing) {
2224
+ try {
2225
+ resolved = this.resolveInboundCoalescing(
2226
+ { ...message, type, channelPubkey },
2227
+ { idempotencyKey: tagged.key }
2228
+ )
2229
+ if (resolved != null && typeof resolved?.then === 'function') {
2230
+ throw new Error('COALESCING_RESOLVER_MUST_BE_SYNCHRONOUS')
2231
+ }
2232
+ } catch (cause) {
2233
+ this.onError?.(coalescingError(cause))
2234
+ resolved = null
2235
+ }
2236
+ }
2237
+
2238
+ let digest = null
2239
+ let keep = 'latest'
2240
+ let sequence = null
2241
+ if (resolved != null) {
2242
+ if (isPlainObject(resolved) && typeof resolved.key === 'string' &&
2243
+ COALESCING_DIGEST.test(resolved.key) &&
2244
+ (resolved.keep == null || COALESCING_KEEP.has(resolved.keep)) &&
2245
+ (resolved.sequence == null ||
2246
+ (Number.isSafeInteger(resolved.sequence) && resolved.sequence >= 0))) {
2247
+ digest = resolved.key
2248
+ keep = resolved.keep || 'latest'
2249
+ sequence = resolved.sequence ?? null
2250
+ } else {
2251
+ this.onError?.(coalescingError(new ValidationError('INVALID_INBOUND_COALESCING_RESULT')))
2252
+ }
2253
+ }
2254
+ if (!digest && tagged.key) digest = idempotencyDigest(tagged.key)
2255
+ if (!digest) return null
2256
+
2257
+ const senderPubkey = info.senderPubkey || message.event?.pubkey || ''
2258
+ const code = messageCode(message)
2259
+ if (!channelPubkey || !senderPubkey || typeof code !== 'string' || !info.provenance) {
2260
+ this.onError?.(coalescingError(new ValidationError('INVALID_INBOUND_COALESCING_SCOPE')))
2261
+ return null
2262
+ }
2263
+ return {
2264
+ coalescingKey: JSON.stringify([
2265
+ channelPubkey,
2266
+ senderPubkey,
2267
+ type,
2268
+ code,
2269
+ info.provenance,
2270
+ digest
2271
+ ]),
2272
+ coalescingKeep: keep,
2273
+ coalescingOrder: coalescingOrder(message, sequence)
2274
+ }
2275
+ }
2276
+
2189
2277
  async enqueueRumor (type, channelPubkey, message) {
2190
2278
  const channel = this.channels.get(channelPubkey)
2191
2279
  if (channel?.mode === 'watchtower' && type !== 'ask') return
@@ -2215,8 +2303,33 @@ export class PrivateMessenger {
2215
2303
  outer: message.outer || null,
2216
2304
  meta: message.meta || null
2217
2305
  }
2306
+ Object.assign(record, this.#coalescingMetadata(type, channelPubkey, message, info) || {})
2218
2307
  try {
2219
- await this.queue.enqueue(record)
2308
+ const coalesced = record.coalescingKey
2309
+ ? await this.queue.coalesceBy(COALESCING_INDEX, record, {
2310
+ compare: compareCoalescingItems,
2311
+ keep: record.coalescingKeep
2312
+ })
2313
+ : null
2314
+ if (!coalesced) await this.queue.enqueue(record)
2315
+ if (coalesced?.status === 'ignored') {
2316
+ this.markSeen(channelPubkey, message.outer?.created_at || message.event?.created_at || nowSeconds())
2317
+ this.debug('message-coalescing-ignored', {
2318
+ code: messageCode(message) || '',
2319
+ keep: record.coalescingKeep,
2320
+ payloadBytes: encoder.encode(JSON.stringify(record)).byteLength
2321
+ })
2322
+ return
2323
+ }
2324
+ if (coalesced) {
2325
+ this.debug('message-coalesced', {
2326
+ code: messageCode(message) || '',
2327
+ keep: record.coalescingKeep,
2328
+ status: coalesced.status,
2329
+ removedUnreserved: coalesced.removed,
2330
+ payloadBytes: encoder.encode(JSON.stringify(record)).byteLength
2331
+ })
2332
+ }
2220
2333
  } catch (err) {
2221
2334
  // The unique index closes the small cross-instance race after `someBy`.
2222
2335
  if (dedupeKey && err?.name === 'ConstraintError') {
@@ -2227,7 +2340,14 @@ export class PrivateMessenger {
2227
2340
  this.recordInterruption([channelPubkey], message.outer?.created_at || message.event?.created_at || nowSeconds())
2228
2341
  // Do not await stop from inside its own transport callback.
2229
2342
  const atCapacity = isQueueCapacityError(err)
2230
- if (!atCapacity && isRecoverableStorageFailure(err)) this.pendingStorageWrites.set(JSON.stringify(dedupeKey || [channelPubkey, type]), { record, dedupeKey, at: message.outer?.created_at || message.event?.created_at })
2343
+ if (!atCapacity && isRecoverableStorageFailure(err)) {
2344
+ const storageKey = record.coalescingKey || JSON.stringify(dedupeKey || [channelPubkey, type])
2345
+ this.pendingStorageWrites.set(storageKey, {
2346
+ record,
2347
+ dedupeKey,
2348
+ at: message.outer?.created_at || message.event?.created_at
2349
+ })
2350
+ }
2231
2351
  if (atCapacity) {
2232
2352
  await annotateQueueCapacityError(err, 'inbox', () => this.queue.getCapacity())
2233
2353
  this.applyCapacityRecoveryTarget(err)
@@ -2243,7 +2363,7 @@ export class PrivateMessenger {
2243
2363
  }
2244
2364
  this.markSeen(channelPubkey, message.outer?.created_at || message.event?.created_at || nowSeconds())
2245
2365
  this.wakeDeliveries()
2246
- this.debug('enqueue', debugMessageInfo(type, channelPubkey, message))
2366
+ if (!record.coalescingKey) this.debug('enqueue', debugMessageInfo(type, channelPubkey, message))
2247
2367
  this.onMessageQueued?.()
2248
2368
  }
2249
2369
 
@@ -2501,7 +2621,7 @@ export class PrivateMessenger {
2501
2621
  this.assertOpen()
2502
2622
  this.touchStorageActivity().catch(err => this.onError?.(err))
2503
2623
  await this.queueOperationTail
2504
- const reservation = await this.queue.reserve()
2624
+ const reservation = await this.queue.reserve({ nackCoalescingIndex: COALESCING_INDEX })
2505
2625
  if (!reservation) return null
2506
2626
  if (this.closePromise) { await reservation.nack(); return null }
2507
2627
  let finish
@@ -2534,7 +2654,8 @@ export class PrivateMessenger {
2534
2654
  return delivery
2535
2655
  }
2536
2656
 
2537
- async ask ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkey, relays, relayToReceivers, message, code, payload, error, content, deletionPubkey, useBulkPacing = false }) {
2657
+ async ask ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkey, relays, relayToReceivers, message, code, payload, error, content, idempotencyKey, deletionPubkey, useBulkPacing = false }) {
2658
+ idempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
2538
2659
  const channel = this.requireWritableChannel(channelPubkey)
2539
2660
  const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
2540
2661
  try {
@@ -2556,6 +2677,7 @@ export class PrivateMessenger {
2556
2677
  payload,
2557
2678
  error,
2558
2679
  content,
2680
+ idempotencyKey,
2559
2681
  useBulkPacing,
2560
2682
  onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
2561
2683
  _getIykcProofs: this.contentKeyLookup()
@@ -2563,7 +2685,8 @@ export class PrivateMessenger {
2563
2685
  } finally { releaseActivity() }
2564
2686
  }
2565
2687
 
2566
- async reply ({ channelPubkey = this.defaultChannelPubkey(), question, receiverPubkey, relays, relayToReceivers, message, code, payload, error, content, deletionPubkey, useBulkPacing = false }) {
2688
+ async reply ({ channelPubkey = this.defaultChannelPubkey(), question, receiverPubkey, relays, relayToReceivers, message, code, payload, error, content, idempotencyKey, deletionPubkey, useBulkPacing = false }) {
2689
+ idempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
2567
2690
  const channel = this.requireWritableChannel(channelPubkey)
2568
2691
  const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
2569
2692
  try {
@@ -2587,6 +2710,7 @@ export class PrivateMessenger {
2587
2710
  payload,
2588
2711
  error,
2589
2712
  content,
2713
+ idempotencyKey,
2590
2714
  useBulkPacing,
2591
2715
  onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
2592
2716
  _getIykcProofs: this.contentKeyLookup()
@@ -2594,7 +2718,8 @@ export class PrivateMessenger {
2594
2718
  } finally { releaseActivity() }
2595
2719
  }
2596
2720
 
2597
- async tell ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkey, relays, relayToReceivers, message, code, payload, error, content, deletionPubkey, useBulkPacing = false }) {
2721
+ async tell ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkey, relays, relayToReceivers, message, code, payload, error, content, idempotencyKey, deletionPubkey, useBulkPacing = false }) {
2722
+ idempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
2598
2723
  const channel = this.requireWritableChannel(channelPubkey)
2599
2724
  const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
2600
2725
  try {
@@ -2616,6 +2741,7 @@ export class PrivateMessenger {
2616
2741
  payload,
2617
2742
  error,
2618
2743
  content,
2744
+ idempotencyKey,
2619
2745
  useBulkPacing,
2620
2746
  onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
2621
2747
  _getIykcProofs: this.contentKeyLookup()
@@ -2623,7 +2749,8 @@ export class PrivateMessenger {
2623
2749
  } finally { releaseActivity() }
2624
2750
  }
2625
2751
 
2626
- async yell ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, message, code, payload, error, content, deletionPubkey, createdAt, onPreparedSeed, preparedPublication, preparedPublications, useBulkPacing = false }) {
2752
+ async yell ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, message, code, payload, error, content, idempotencyKey, deletionPubkey, createdAt, onPreparedSeed, preparedPublication, preparedPublications, useBulkPacing = false }) {
2753
+ idempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
2627
2754
  const channel = this.requireWritableChannel(channelPubkey)
2628
2755
  const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
2629
2756
  try {
@@ -2649,6 +2776,7 @@ export class PrivateMessenger {
2649
2776
  payload,
2650
2777
  error,
2651
2778
  content,
2779
+ idempotencyKey,
2652
2780
  createdAt,
2653
2781
  useBulkPacing,
2654
2782
  onPreparedSeed: onPreparedSeed || this.outgoingSeedHandler(channelPubkey),
@@ -3813,6 +3941,44 @@ function messageCode (message) {
3813
3941
  : null
3814
3942
  }
3815
3943
 
3944
+ function coalescingOrder (message, sequence = null) {
3945
+ const order = {
3946
+ outer: Number.isSafeInteger(message?.outer?.created_at) ? message.outer.created_at : 0,
3947
+ inner: Number.isSafeInteger(message?.event?.created_at) ? message.event.created_at : 0,
3948
+ eventId: message?.event?.id || ''
3949
+ }
3950
+ if (sequence != null) order.sequence = sequence
3951
+ return order
3952
+ }
3953
+
3954
+ function compareCoalescingOrder (left, right) {
3955
+ if (Number.isSafeInteger(left?.sequence) && Number.isSafeInteger(right?.sequence) &&
3956
+ left.sequence !== right.sequence) {
3957
+ return left.sequence < right.sequence ? -1 : 1
3958
+ }
3959
+ if ((left?.outer || 0) !== (right?.outer || 0)) return (left?.outer || 0) - (right?.outer || 0)
3960
+ if ((left?.inner || 0) !== (right?.inner || 0)) return (left?.inner || 0) - (right?.inner || 0)
3961
+ const leftId = left?.eventId || ''
3962
+ const rightId = right?.eventId || ''
3963
+ if (leftId === rightId) return 0
3964
+ return leftId < rightId ? -1 : 1
3965
+ }
3966
+
3967
+ function compareCoalescingItems (left, right) {
3968
+ return compareCoalescingOrder(left?.coalescingOrder, right?.coalescingOrder)
3969
+ }
3970
+
3971
+ function idempotencyDigest (idempotencyKey) {
3972
+ return bytesToHex(sha256(encoder.encode(JSON.stringify(['idempotency', idempotencyKey]))))
3973
+ }
3974
+
3975
+ function coalescingError (cause) {
3976
+ return Object.assign(new Error('INVALID_INBOUND_COALESCING_KEY'), {
3977
+ code: 'INVALID_INBOUND_COALESCING_KEY',
3978
+ cause
3979
+ })
3980
+ }
3981
+
3816
3982
  function safeDiagnosticToken (value) {
3817
3983
  return typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9:._-]{0,159}$/.test(value)
3818
3984
  ? value
@@ -3902,6 +4068,9 @@ function nymCarrierSeedKey (record) {
3902
4068
  function withoutQueueMetadata (item) {
3903
4069
  if (!item) return null
3904
4070
  const value = { ...item }
4071
+ delete value.coalescingKey
4072
+ delete value.coalescingKeep
4073
+ delete value.coalescingOrder
3905
4074
  delete value[SEED_KEY]
3906
4075
  delete value[SEED_TIME]
3907
4076
  return value
@@ -2,6 +2,7 @@ import { getEventHash } from '../../event/index.js'
2
2
  import { bytesToBase64, base64ToBytes } from '../../base64/index.js'
3
3
  import { ValidationError } from '../../error/index.js'
4
4
  import { ASK_KIND, parseRumorContent } from '../../private-message/index.js'
5
+ import { chunkIdempotencyKey, normalizeIdempotencyKeyBase } from '../../private-message/helpers/idempotency.js'
5
6
 
6
7
  export const SEEDER_PRESENCE_CODE = 'seederPresence_8mj8'
7
8
  export const MISSING_MESSAGES_ASK_CODE = 'missingMessages_ask_8mj8'
@@ -228,13 +229,15 @@ export function createEventReplyPacker ({
228
229
  bytesPerChunk = DEFAULT_REPLY_BYTES_PER_CHUNK,
229
230
  recordsFromInput = eventRecordFromInput,
230
231
  sendEmptyReply = false,
231
- useBulkPacing = true
232
+ useBulkPacing = true,
233
+ idempotencyKey
232
234
  }) {
233
235
  if (!messenger?.reply) throw new ValidationError('MESSENGER_REQUIRED')
234
236
  if (!question?.id) throw new ValidationError('QUESTION_REQUIRED')
235
237
  if (!receiverPubkey) throw new ValidationError('RECEIVER_PUBKEY_REQUIRED')
236
238
  if (!Number.isSafeInteger(eventsPerChunk) || eventsPerChunk < 1) throw new ValidationError('INVALID_EVENTS_PER_CHUNK')
237
239
  if (!Number.isSafeInteger(bytesPerChunk) || bytesPerChunk < 1) throw new ValidationError('INVALID_BYTES_PER_CHUNK')
240
+ const idempotencyKeyBase = normalizeIdempotencyKeyBase(idempotencyKey)
238
241
 
239
242
  let chunk = ''
240
243
  let chunkEvents = 0
@@ -250,6 +253,9 @@ export function createEventReplyPacker ({
250
253
  question,
251
254
  receiverPubkey,
252
255
  code,
256
+ ...(idempotencyKeyBase
257
+ ? { idempotencyKey: chunkIdempotencyKey(idempotencyKeyBase, index) }
258
+ : {}),
253
259
  useBulkPacing,
254
260
  payload: {
255
261
  ...payload,
@@ -311,13 +317,15 @@ export function createMissingMessageReplyPacker ({
311
317
  eventsPerChunk = DEFAULT_EVENTS_PER_CHUNK,
312
318
  bytesPerChunk = DEFAULT_REPLY_BYTES_PER_CHUNK,
313
319
  sendEmptyReply = false,
314
- useBulkPacing = true
320
+ useBulkPacing = true,
321
+ idempotencyKey
315
322
  }) {
316
323
  if (!messenger?.reply) throw new ValidationError('MESSENGER_REQUIRED')
317
324
  if (!question?.id) throw new ValidationError('QUESTION_REQUIRED')
318
325
  if (!receiverPubkey) throw new ValidationError('RECEIVER_PUBKEY_REQUIRED')
319
326
  if (!Number.isSafeInteger(eventsPerChunk) || eventsPerChunk < 1) throw new ValidationError('INVALID_EVENTS_PER_CHUNK')
320
327
  if (!Number.isSafeInteger(bytesPerChunk) || bytesPerChunk < 1) throw new ValidationError('INVALID_BYTES_PER_CHUNK')
328
+ idempotencyKey ||= `${MISSING_MESSAGES_REPLY_CODE}:${question.id}`
321
329
 
322
330
  const range = backfillRequestRange(question, since, until)
323
331
  return createEventReplyPacker({
@@ -331,6 +339,7 @@ export function createMissingMessageReplyPacker ({
331
339
  bytesPerChunk,
332
340
  sendEmptyReply,
333
341
  useBulkPacing,
342
+ idempotencyKey,
334
343
  recordsFromInput: seed => compactRecordsFromSeed(seed, { receiverPubkey, since: range.since, until: range.until })
335
344
  })
336
345
  }