libp2r2p 0.12.26 → 0.12.27

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.
@@ -0,0 +1,233 @@
1
+ const VERSION = 1
2
+ const NOT_ACQUIRED = Symbol('not-acquired')
3
+ const SKIPPED = Symbol('skipped')
4
+
5
+ const fallbackMemories = new WeakMap()
6
+ const nonPersistentStorages = new WeakSet()
7
+ const localQueues = new WeakMap()
8
+ const defaultLocalQueues = new Map()
9
+ const memoryStorage = {
10
+ values: new Map(),
11
+ getItem (key) { return this.values.get(key) ?? null },
12
+ setItem (key, value) { this.values.set(key, value) }
13
+ }
14
+ const defaultReplicaId = globalThis.crypto?.randomUUID?.() ||
15
+ `${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`
16
+
17
+ function fallbackMemory (storage) {
18
+ if (!storage) return memoryStorage
19
+ let memory = fallbackMemories.get(storage)
20
+ if (!memory) {
21
+ memory = { values: new Map() }
22
+ fallbackMemories.set(storage, memory)
23
+ }
24
+ return {
25
+ getItem: key => memory.values.get(key) ?? null,
26
+ setItem: (key, value) => memory.values.set(key, value)
27
+ }
28
+ }
29
+
30
+ function defaultStorage () {
31
+ try { return globalThis.localStorage || null } catch { return null }
32
+ }
33
+
34
+ function normalizeLease (value) {
35
+ return value &&
36
+ value.version === VERSION &&
37
+ Number.isSafeInteger(value.generation) && value.generation >= 0 &&
38
+ typeof value.instanceId === 'string' && value.instanceId &&
39
+ Number.isFinite(value.leaseUntil) && value.leaseUntil >= 0 &&
40
+ Number.isFinite(value.updatedAt) && value.updatedAt >= 0
41
+ ? value
42
+ : null
43
+ }
44
+
45
+ export function readRecoverableLockLease (storageKey, storage = defaultStorage()) {
46
+ const area = storage || memoryStorage
47
+ const source = storage && nonPersistentStorages.has(storage) ? fallbackMemory(storage) : area
48
+ try {
49
+ return normalizeLease(JSON.parse(source.getItem(storageKey) || 'null'))
50
+ } catch {
51
+ return null
52
+ }
53
+ }
54
+
55
+ function writeRecoverableLockLease (storageKey, lease, storage = defaultStorage()) {
56
+ const area = storage || memoryStorage
57
+ const serialized = JSON.stringify(lease)
58
+ try {
59
+ area.setItem(storageKey, serialized)
60
+ } catch {
61
+ if (storage) nonPersistentStorages.add(storage)
62
+ }
63
+ fallbackMemory(storage).setItem(storageKey, serialized)
64
+ if (storage) {
65
+ try {
66
+ if (storage.getItem(storageKey) === serialized) nonPersistentStorages.delete(storage)
67
+ else nonPersistentStorages.add(storage)
68
+ } catch {
69
+ nonPersistentStorages.add(storage)
70
+ }
71
+ }
72
+ return lease
73
+ }
74
+
75
+ function lockAuthorityLost () {
76
+ return Object.assign(new Error('LOCK_AUTHORITY_LOST'), { code: 'LOCK_AUTHORITY_LOST' })
77
+ }
78
+
79
+ function withLocalQueue (scope, name, work) {
80
+ let map = defaultLocalQueues
81
+ if (scope && (typeof scope === 'object' || typeof scope === 'function')) {
82
+ map = localQueues.get(scope)
83
+ if (!map) {
84
+ map = new Map()
85
+ localQueues.set(scope, map)
86
+ }
87
+ }
88
+ const prior = map.get(name) || Promise.resolve()
89
+ const next = prior.catch(() => {}).then(work)
90
+ map.set(name, next.catch(() => {}))
91
+ return next
92
+ }
93
+
94
+ export async function withRecoverableLock ({
95
+ name,
96
+ storageKey = `libp2r2p:lock:${name}`,
97
+ work,
98
+ locks = globalThis.navigator?.locks,
99
+ storage = defaultStorage(),
100
+ fallbackScope,
101
+ now = Date.now,
102
+ setTimer = setTimeout,
103
+ clearTimer = clearTimeout,
104
+ leaseMs = 15_000,
105
+ heartbeatMs = 5_000,
106
+ ifAvailableOnly = false,
107
+ skippedValue = undefined,
108
+ replicaId = defaultReplicaId
109
+ }) {
110
+ if (typeof work !== 'function') throw new TypeError('RECOVERABLE_LOCK_CALLBACK_REQUIRED')
111
+
112
+ if (typeof locks?.request !== 'function') {
113
+ return withLocalQueue(fallbackScope, name, () => {
114
+ const controller = new AbortController()
115
+ return work({
116
+ signal: controller.signal,
117
+ generation: 1,
118
+ instanceId: replicaId,
119
+ assertLeader () {}
120
+ })
121
+ })
122
+ }
123
+
124
+ const run = lock => {
125
+ if (!lock) return NOT_ACQUIRED
126
+ return (async () => {
127
+ const current = readRecoverableLockLease(storageKey, storage)
128
+ const generation = Math.max(1, (current?.generation || 0) + 1)
129
+ const startedAt = now()
130
+ const controller = new AbortController()
131
+ let heartbeatTimer = null
132
+ let authorityError = null
133
+ const owns = () => {
134
+ const lease = readRecoverableLockLease(storageKey, storage)
135
+ return lease?.instanceId === replicaId &&
136
+ lease?.generation === generation &&
137
+ lease.leaseUntil > now()
138
+ }
139
+ const assertLeader = () => {
140
+ if (controller.signal.aborted || !owns()) throw authorityError || lockAuthorityLost()
141
+ }
142
+ const persist = leaseUntil => writeRecoverableLockLease(storageKey, {
143
+ version: VERSION,
144
+ generation,
145
+ instanceId: replicaId,
146
+ leaseUntil,
147
+ updatedAt: now()
148
+ }, storage)
149
+ const scheduleHeartbeat = () => {
150
+ heartbeatTimer = setTimer(() => {
151
+ heartbeatTimer = null
152
+ try {
153
+ if (!owns()) throw lockAuthorityLost()
154
+ persist(now() + leaseMs)
155
+ scheduleHeartbeat()
156
+ } catch (error) {
157
+ authorityError = error
158
+ controller.abort(error)
159
+ }
160
+ }, heartbeatMs)
161
+ heartbeatTimer?.unref?.()
162
+ }
163
+
164
+ try {
165
+ persist(startedAt + leaseMs)
166
+ scheduleHeartbeat()
167
+ const result = await work({
168
+ signal: controller.signal,
169
+ generation,
170
+ instanceId: replicaId,
171
+ assertLeader
172
+ })
173
+ if (authorityError) throw authorityError
174
+ return result
175
+ } catch (error) {
176
+ if (authorityError) throw authorityError
177
+ throw error
178
+ } finally {
179
+ if (heartbeatTimer != null) clearTimer(heartbeatTimer)
180
+ if (owns()) {
181
+ try { persist(0) } catch {}
182
+ }
183
+ }
184
+ })()
185
+ }
186
+
187
+ let fallbackDeadline = 0
188
+ while (true) {
189
+ const immediate = await locks.request(name, { ifAvailable: true }, lock => lock ? run(lock) : NOT_ACQUIRED)
190
+ if (immediate !== NOT_ACQUIRED) return immediate
191
+
192
+ const currentTime = now()
193
+ const lease = readRecoverableLockLease(storageKey, storage)
194
+ if (lease && lease.instanceId !== replicaId && lease.leaseUntil > 0 && lease.leaseUntil <= currentTime) {
195
+ return locks.request(name, { steal: true }, run)
196
+ }
197
+
198
+ if (ifAvailableOnly) return skippedValue
199
+
200
+ if (lease && lease.instanceId === replicaId && lease.leaseUntil > currentTime) {
201
+ return locks.request(name, {}, run)
202
+ }
203
+
204
+ let waitMs
205
+ if (lease && lease.instanceId !== replicaId && lease.leaseUntil > currentTime) {
206
+ waitMs = Math.max(50, Math.min(leaseMs, lease.leaseUntil - currentTime))
207
+ fallbackDeadline = 0
208
+ } else {
209
+ if (!fallbackDeadline) fallbackDeadline = currentTime + leaseMs
210
+ waitMs = fallbackDeadline - currentTime
211
+ if (waitMs <= 0) return locks.request(name, { steal: true }, run)
212
+ }
213
+
214
+ const controller = new AbortController()
215
+ let waitTimer = setTimer(() => {
216
+ waitTimer = null
217
+ controller.abort(new Error('LOCK_WAIT_EXPIRED'))
218
+ }, waitMs)
219
+ waitTimer?.unref?.()
220
+ try {
221
+ return await locks.request(name, { signal: controller.signal }, lock => {
222
+ if (waitTimer != null) { clearTimer(waitTimer); waitTimer = null }
223
+ return run(lock)
224
+ })
225
+ } catch (error) {
226
+ if (waitTimer != null) { clearTimer(waitTimer); waitTimer = null }
227
+ if (controller.signal.aborted) continue
228
+ throw error
229
+ }
230
+ }
231
+ }
232
+
233
+ export { SKIPPED }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libp2r2p",
3
- "version": "0.12.26",
3
+ "version": "0.12.27",
4
4
  "description": "Peer-to-relay-to-peer",
5
5
  "keywords": [
6
6
  "p2r2p",
@@ -47,7 +47,20 @@ export function readChunkTag (event) {
47
47
  return { index, total }
48
48
  }
49
49
 
50
- export function makeRouterEvent ({ pubkey, senderPubkey, imkcPubkey, imkcProof, receiverPubkey, chunkIndex, chunkTotal, fileChunkIndex, content }) {
50
+ export const NOT_SEEDABLE_TAG = 'ns'
51
+
52
+ export function isRouterSeedable (event) {
53
+ const tags = event?.tags
54
+ if (!Array.isArray(tags)) return true
55
+ for (const tag of tags) {
56
+ if (!Array.isArray(tag) || tag[0] !== NOT_SEEDABLE_TAG) continue
57
+ if (tag.length === 1 || tag[1] === '1') return false
58
+ }
59
+ return true
60
+ }
61
+
62
+ export function makeRouterEvent ({ pubkey, senderPubkey, imkcPubkey, imkcProof, receiverPubkey, chunkIndex, chunkTotal, fileChunkIndex, seedable = true, content }) {
63
+ if (typeof seedable !== 'boolean') throw new ValidationError('INVALID_SEEDABLE')
51
64
  const tags = [['f', senderPubkey]]
52
65
  if (imkcPubkey) {
53
66
  if (!imkcProof) throw new ValidationError('INVALID_IMKC_PROOF')
@@ -59,6 +72,7 @@ export function makeRouterEvent ({ pubkey, senderPubkey, imkcPubkey, imkcProof,
59
72
  }
60
73
  tags.push(['c', String(chunkIndex), String(chunkTotal)])
61
74
  if (receiverPubkey) tags.push(['p', receiverPubkey])
75
+ if (!seedable) tags.push([NOT_SEEDABLE_TAG])
62
76
  return { kind: ROUTER_KIND, pubkey, created_at: nowSeconds(), tags, content }
63
77
  }
64
78
 
@@ -27,10 +27,11 @@ import {
27
27
  preparedChunks
28
28
  } from './helpers/chunks.js'
29
29
  import { EXPIRATION_SECONDS, MAX_EVENT_BYTES, NYM_CARRIER_KIND, PRIVATE_BROADCAST_KIND, ROUTER_KIND } from './constants/index.js'
30
- import { eventByteLength, hasImkcTag, makeNymCarrierEvent, makeRouterEvent, nowSeconds, readChunkTag, readFileChunkIndex, readIdTag, readImkcProof, readImkcTag, readReceiverTag, readSenderTag } from './helpers/event.js'
30
+ import { eventByteLength, hasImkcTag, isRouterSeedable, makeNymCarrierEvent, makeRouterEvent, nowSeconds, readChunkTag, readFileChunkIndex, readIdTag, readImkcProof, readImkcTag, readReceiverTag, readSenderTag } from './helpers/event.js'
31
31
  import { createReceivedChunkStore, DEFAULT_RECEIVED_CHUNK_MAX_BYTES, DEFAULT_RECEIVED_CHUNK_TTL_MS } from './services/received-chunks.js'
32
32
 
33
33
  export { EXPIRATION_SECONDS, MAX_EVENT_BYTES, NYM_CARRIER_KIND, PRIVATE_BROADCAST_KIND, ROUTER_KIND } from './constants/index.js'
34
+ export { isRouterSeedable } from './helpers/event.js'
34
35
 
35
36
  const DEFAULT_IGNORED_GROUP_TTL_MS = 30 * 60 * 1000
36
37
  const DEFAULT_IGNORED_GROUP_MAX_ENTRIES = 5000
@@ -173,7 +174,8 @@ async function validatePreparedPublication ({ privateChannelSigner, senderSigner
173
174
  return publicationReceivers
174
175
  }
175
176
 
176
- async function * wrapPreparedEvents ({ privateChannelSigner, senderSigner, event, receivers, receiverTag, fileChunkIndex, onPreparedSeed, onPreparedPublication, deletionPubkey, expirationSeconds = EXPIRATION_SECONDS, context, preparedPublication }) {
177
+ async function * wrapPreparedEvents ({ privateChannelSigner, senderSigner, event, receivers, receiverTag, fileChunkIndex, seedable = true, onPreparedSeed, onPreparedPublication, deletionPubkey, expirationSeconds = EXPIRATION_SECONDS, context, preparedPublication }) {
178
+ if (typeof seedable !== 'boolean') throw new ValidationError('INVALID_SEEDABLE')
177
179
  let publication = preparedPublication
178
180
  if (publication) {
179
181
  await validatePreparedPublication({ privateChannelSigner, senderSigner, event, receivers, preparedPublication: publication })
@@ -184,15 +186,19 @@ async function * wrapPreparedEvents ({ privateChannelSigner, senderSigner, event
184
186
  const routerReceiverTag = receiverTag ?? (receiverPubkeyList.length === 1 ? receiverPubkeyList[0] : '')
185
187
  const rowIndexes = preparedRowIndexesForReceivers(context.preparedRows, receivers)
186
188
  const total = preparedChunkCount(context.preparedRows, rowIndexes)
187
- const seedRouter = makeRouterEvent({ pubkey: routerPubkey, senderPubkey: context.senderPubkey, imkcPubkey: context.imkcPubkey, imkcProof: context.imkcProof, receiverPubkey: routerReceiverTag, chunkIndex: 0, chunkTotal: 1, fileChunkIndex, content: '' })
188
- const payloadRow = readPreparedRow(context.preparedRows, 0)
189
- const seeds = rowIndexes.map(rowIndex => ({ channelPubkey: context.channelPubkey, router: seedRouter, jsonl: `${payloadRow}\n${readPreparedRow(context.preparedRows, rowIndex)}\n` }))
189
+ const seedRouter = seedable
190
+ ? makeRouterEvent({ pubkey: routerPubkey, senderPubkey: context.senderPubkey, imkcPubkey: context.imkcPubkey, imkcProof: context.imkcProof, receiverPubkey: routerReceiverTag, chunkIndex: 0, chunkTotal: 1, fileChunkIndex, seedable, content: '' })
191
+ : null
192
+ const payloadRow = seedable ? readPreparedRow(context.preparedRows, 0) : ''
193
+ const seeds = seedable
194
+ ? rowIndexes.map(rowIndex => ({ channelPubkey: context.channelPubkey, router: seedRouter, jsonl: `${payloadRow}\n${readPreparedRow(context.preparedRows, rowIndex)}\n` }))
195
+ : []
190
196
  const events = []
191
197
  let index = 0
192
198
  for (const content of preparedChunks(context.preparedRows, rowIndexes)) {
193
199
  const router = finalizeEvent(makeRouterEvent({
194
200
  pubkey: routerPubkey, senderPubkey: context.senderPubkey, imkcPubkey: context.imkcPubkey,
195
- imkcProof: context.imkcProof, receiverPubkey: routerReceiverTag, fileChunkIndex,
201
+ imkcProof: context.imkcProof, receiverPubkey: routerReceiverTag, fileChunkIndex, seedable,
196
202
  chunkIndex: index++, chunkTotal: total, content
197
203
  }), routerSeckey)
198
204
  const createdAt = nowSeconds()
@@ -209,14 +215,15 @@ async function * wrapPreparedEvents ({ privateChannelSigner, senderSigner, event
209
215
  onPreparedPublication?.(publication)
210
216
  // The callback commits recovery data before any bytes leave this publisher.
211
217
  // A session commits its encrypted journal; a direct messenger commits seeds.
212
- if (onPreparedSeed) {
218
+ if (seedable && onPreparedSeed) {
213
219
  for (const seed of publication.seeds) await onPreparedSeed({ ...seed, publication })
214
220
  }
215
221
  yield * publication.events
216
222
  }
217
223
 
218
224
  // Streaming version of wrapEvent
219
- export async function * wrapEvents ({ senderSigner, imkcSigner, privateChannelSigner = senderSigner, privateChannelReaderPubkey, receivers, receiverTag, fileChunkIndex, onPreparedSeed, onPreparedPublication, deletionPubkey, event, expirationSeconds = EXPIRATION_SECONDS, temporaryStorageArea, _getIykcProofs = getIykcProofs, preparedPublication, preparedPublications }) {
225
+ export async function * wrapEvents ({ senderSigner, imkcSigner, privateChannelSigner = senderSigner, privateChannelReaderPubkey, receivers, receiverTag, fileChunkIndex, seedable = true, onPreparedSeed, onPreparedPublication, deletionPubkey, event, expirationSeconds = EXPIRATION_SECONDS, temporaryStorageArea, _getIykcProofs = getIykcProofs, preparedPublication, preparedPublications }) {
226
+ if (typeof seedable !== 'boolean') throw new ValidationError('INVALID_SEEDABLE')
220
227
  const normalizedDeletionPubkey = normalizeDeletionPubkey(deletionPubkey)
221
228
  const prepared = normalizePreparedPublications({ preparedPublication, preparedPublications })
222
229
  if (prepared.length > 1) throw new ValidationError('INVALID_PREPARED_PUBLICATIONS')
@@ -234,7 +241,7 @@ export async function * wrapEvents ({ senderSigner, imkcSigner, privateChannelSi
234
241
  _getIykcProofs
235
242
  })
236
243
  try {
237
- yield * wrapPreparedEvents({ privateChannelSigner, senderSigner, event, receivers, receiverTag, fileChunkIndex, onPreparedSeed, onPreparedPublication, deletionPubkey: normalizedDeletionPubkey, expirationSeconds, context, preparedPublication: publication })
244
+ yield * wrapPreparedEvents({ privateChannelSigner, senderSigner, event, receivers, receiverTag, fileChunkIndex, seedable, onPreparedSeed, onPreparedPublication, deletionPubkey: normalizedDeletionPubkey, expirationSeconds, context, preparedPublication: publication })
238
245
  } finally {
239
246
  if (context) cleanupEnvelopeRows(context.preparedRows)
240
247
  }
@@ -687,7 +694,9 @@ function relayMapForReceivers (relayToReceivers, receivers) {
687
694
  return relays
688
695
  }
689
696
 
690
- export async function publish ({ senderSigner, imkcSigner, privateChannelSigner = senderSigner, privateChannelReaderPubkey, receivers, receiverTag, fileChunkIndex, onPreparedSeed, useBulkPacing = false, deletionPubkey, event, relays, relayToReceivers, recoveryRelays, expirationSeconds, temporaryStorageArea, _getIykcProofs = getIykcProofs, _publish = sendToRelays, preparedPublication, preparedPublications }) {
697
+ export async function publish ({ senderSigner, imkcSigner, privateChannelSigner = senderSigner, privateChannelReaderPubkey, receivers, receiverTag, fileChunkIndex, seedable = true, onPreparedSeed, useBulkPacing = false, deletionPubkey, event, relays, relayToReceivers, recoveryRelays, expirationSeconds, temporaryStorageArea, _getIykcProofs = getIykcProofs, _publish = sendToRelays, preparedPublication, preparedPublications }) {
698
+ if (typeof seedable !== 'boolean') throw new ValidationError('INVALID_SEEDABLE')
699
+ const effectiveOnPreparedSeed = seedable ? onPreparedSeed : undefined
691
700
  const normalizedDeletionPubkey = normalizeDeletionPubkey(deletionPubkey)
692
701
  const results = []
693
702
  const requestedReceivers = receiverPubkeys(receivers)
@@ -710,8 +719,8 @@ export async function publish ({ senderSigner, imkcSigner, privateChannelSigner
710
719
  })
711
720
  const targeted = publicationReceivers.filter(pubkey => requested.has(pubkey))
712
721
  for (const pubkey of targeted) covered.add(pubkey)
713
- if (onPreparedSeed) {
714
- for (const seed of publication.seeds) await onPreparedSeed({ ...seed, publication })
722
+ if (effectiveOnPreparedSeed) {
723
+ for (const seed of publication.seeds) await effectiveOnPreparedSeed({ ...seed, publication })
715
724
  }
716
725
  const targetRelays = relayMapForReceivers(relayToReceivers, targeted) || uniq(relays)
717
726
  const publishRelays = withRecoveryRelays(targetRelays, recoveryRelays)
@@ -723,7 +732,7 @@ export async function publish ({ senderSigner, imkcSigner, privateChannelSigner
723
732
  receivers: targeted.map(pubkey => ({ receiverPubkey: pubkey })),
724
733
  privateChannelSigner,
725
734
  expirationSeconds,
726
- onPreparedSeed,
735
+ onPreparedSeed: effectiveOnPreparedSeed,
727
736
  useBulkPacing,
728
737
  _publish
729
738
  })
@@ -759,7 +768,8 @@ export async function publish ({ senderSigner, imkcSigner, privateChannelSigner
759
768
  receivers: group.receivers,
760
769
  receiverTag,
761
770
  fileChunkIndex,
762
- onPreparedSeed,
771
+ seedable,
772
+ onPreparedSeed: effectiveOnPreparedSeed,
763
773
  onPreparedPublication: value => { publication = value },
764
774
  deletionPubkey: normalizedDeletionPubkey,
765
775
  expirationSeconds,
@@ -775,7 +785,7 @@ export async function publish ({ senderSigner, imkcSigner, privateChannelSigner
775
785
  receivers: group.receivers,
776
786
  privateChannelSigner,
777
787
  expirationSeconds,
778
- onPreparedSeed,
788
+ onPreparedSeed: effectiveOnPreparedSeed,
779
789
  useBulkPacing,
780
790
  _publish
781
791
  })
@@ -797,7 +807,8 @@ export async function publish ({ senderSigner, imkcSigner, privateChannelSigner
797
807
  receivers,
798
808
  receiverTag,
799
809
  fileChunkIndex,
800
- onPreparedSeed,
810
+ seedable,
811
+ onPreparedSeed: effectiveOnPreparedSeed,
801
812
  onPreparedPublication: value => { publication = value },
802
813
  deletionPubkey: normalizedDeletionPubkey,
803
814
  event,
@@ -814,7 +825,7 @@ export async function publish ({ senderSigner, imkcSigner, privateChannelSigner
814
825
  receivers,
815
826
  privateChannelSigner,
816
827
  expirationSeconds,
817
- onPreparedSeed,
828
+ onPreparedSeed: effectiveOnPreparedSeed,
818
829
  useBulkPacing,
819
830
  _publish
820
831
  })
@@ -1101,7 +1112,7 @@ function createProcessor ({
1101
1112
  missing: status.missing
1102
1113
  })
1103
1114
 
1104
- const shouldSeed = doesModeStoreRecoverySeeds(channelMode)
1115
+ const shouldSeed = doesModeStoreRecoverySeeds(channelMode) && isRouterSeedable(router)
1105
1116
  const sentByReceiver = receiverPubkey && senderPubkey === receiverPubkey
1106
1117
  // Recovery seeders and own-sent messages need the full recipient list;
1107
1118
  // regular leechers can stop as soon as their envelope is decrypted.
@@ -1193,7 +1204,7 @@ function createProcessor ({
1193
1204
  receiverPubkeys,
1194
1205
  onContentKeyUsage
1195
1206
  })
1196
- if (shouldSeed) await onSeedEvent?.({ recordType: 'routerRow_v1', outer, router: completeRouter, channelPubkey, jsonl, innerEventIdsByRowIndex })
1207
+ if (shouldSeed) await onSeedEvent?.({ recordType: 'routerRow_v1', outer, router: completeRouter, channelPubkey, jsonl, innerEventIdsByRowIndex, event })
1197
1208
  if (event) await onEvent?.(event, outer, { router: completeRouter, channelPubkey, jsonl, ...deliveryInfo(event, senderPubkey) })
1198
1209
 
1199
1210
  await receivedChunks.removeGroup(groupKey)
@@ -726,13 +726,14 @@ async function sendPrivateMessage ({
726
726
  deletionPubkey,
727
727
  _getIykcProofs,
728
728
  fileChunkIndex,
729
+ seedable = true,
729
730
  onPreparedSeed,
730
731
  preparedPublications,
731
732
  useBulkPacing = false,
732
733
  _publish = privateChannel.publish
733
734
  }) {
734
735
  if (!privateChannelSigner?.getPublicKey) throw new ValidationError('PRIVATE_CHANNEL_WRITER_REQUIRED')
735
- return _publish({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers, receiverTag, deletionPubkey, event, relays, relayToReceivers, recoveryRelays, expirationSeconds, temporaryStorageArea, fileChunkIndex, onPreparedSeed, preparedPublications: preparedPublications?.length ? preparedPublications : undefined, useBulkPacing, _getIykcProofs })
736
+ return _publish({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers, receiverTag, deletionPubkey, event, relays, relayToReceivers, recoveryRelays, expirationSeconds, temporaryStorageArea, fileChunkIndex, seedable, onPreparedSeed, preparedPublications: preparedPublications?.length ? preparedPublications : undefined, useBulkPacing, _getIykcProofs })
736
737
  }
737
738
 
738
739
  async function sendNymMessage ({
@@ -776,6 +777,7 @@ export async function ask ({
776
777
  deletionSeckey,
777
778
  autoDeletionCapability = true,
778
779
  fileChunkIndex,
780
+ seedable = true,
779
781
  onPreparedSeed,
780
782
  _publish = privateChannel.publish,
781
783
  _assertWatching
@@ -788,7 +790,7 @@ export async function ask ({
788
790
  const identity = await senderSigner?.getPublicKey?.()
789
791
  const session = defaultSessions.get(identity)
790
792
  if (!session) throw new Error('PRIVATE_MESSAGE_NOT_WATCHING')
791
- 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 })
793
+ return session.ask({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receiverPubkey, relays, relayToReceivers, recoveryRelays, message, code, payload, error, content, idempotencyKey, expirationSeconds, useBulkPacing, temporaryStorageArea, _getIykcProofs, deletionPubkey, deletionSeckey, autoDeletionCapability, fileChunkIndex, seedable, onPreparedSeed, _publish })
792
794
  }
793
795
 
794
796
  const { event: question, wireEvent } = await makeOutgoingRumor({
@@ -802,7 +804,7 @@ export async function ask ({
802
804
  })
803
805
  })
804
806
  const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability })
805
- const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers: [receiverPubkey], receiverTag: receiverPubkey, deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, temporaryStorageArea, fileChunkIndex, onPreparedSeed, _getIykcProofs, _publish })
807
+ const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers: [receiverPubkey], receiverTag: receiverPubkey, deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, temporaryStorageArea, fileChunkIndex, seedable, onPreparedSeed, _getIykcProofs, _publish })
806
808
 
807
809
  return withDelivery({ question }, reports, deletion.deletionSeckey)
808
810
  }
@@ -831,6 +833,7 @@ export async function reply ({
831
833
  deletionSeckey,
832
834
  autoDeletionCapability = true,
833
835
  fileChunkIndex,
836
+ seedable = true,
834
837
  onPreparedSeed,
835
838
  _publish = privateChannel.publish
836
839
  }) {
@@ -847,7 +850,7 @@ export async function reply ({
847
850
  })
848
851
  })
849
852
  const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability })
850
- const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers: [receiverPubkey], receiverTag: receiverPubkey, deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, temporaryStorageArea, fileChunkIndex, onPreparedSeed, _getIykcProofs, _publish })
853
+ const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers: [receiverPubkey], receiverTag: receiverPubkey, deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, temporaryStorageArea, fileChunkIndex, seedable, onPreparedSeed, _getIykcProofs, _publish })
851
854
  return withDelivery({ reply: event }, reports, deletion.deletionSeckey)
852
855
  }
853
856
 
@@ -874,6 +877,7 @@ export async function tell ({
874
877
  deletionSeckey,
875
878
  autoDeletionCapability = true,
876
879
  fileChunkIndex,
880
+ seedable = true,
877
881
  onPreparedSeed,
878
882
  _publish = privateChannel.publish
879
883
  }) {
@@ -889,7 +893,7 @@ export async function tell ({
889
893
  })
890
894
  })
891
895
  const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability })
892
- const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers: [receiverPubkey], receiverTag: receiverPubkey, deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, temporaryStorageArea, fileChunkIndex, onPreparedSeed, _getIykcProofs, _publish })
896
+ const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers: [receiverPubkey], receiverTag: receiverPubkey, deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, temporaryStorageArea, fileChunkIndex, seedable, onPreparedSeed, _getIykcProofs, _publish })
893
897
  return withDelivery({ tell: event }, reports, deletion.deletionSeckey)
894
898
  }
895
899
 
@@ -916,6 +920,7 @@ export async function yell ({
916
920
  deletionSeckey,
917
921
  autoDeletionCapability = true,
918
922
  fileChunkIndex,
923
+ seedable = true,
919
924
  createdAt,
920
925
  createdAtMs,
921
926
  onPreparedSeed,
@@ -942,7 +947,7 @@ export async function yell ({
942
947
  prepared
943
948
  })
944
949
  const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability, preparedPublications: prepared })
945
- const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers, receiverTag: '', deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, temporaryStorageArea, fileChunkIndex, onPreparedSeed: preparedSeedHandler(onPreparedSeed, deletion), preparedPublications: prepared, _getIykcProofs, _publish })
950
+ const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers, receiverTag: '', deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, temporaryStorageArea, fileChunkIndex, seedable, onPreparedSeed: preparedSeedHandler(onPreparedSeed, deletion), preparedPublications: prepared, _getIykcProofs, _publish })
946
951
  return withDelivery({ yell: event }, reports, deletion.deletionSeckey)
947
952
  }
948
953
 
@@ -964,6 +969,7 @@ export async function broadcastRumor ({
964
969
  deletionSeckey,
965
970
  autoDeletionCapability = true,
966
971
  fileChunkIndex,
972
+ seedable = true,
967
973
  onPreparedSeed,
968
974
  preparedPublication,
969
975
  preparedPublications,
@@ -974,7 +980,7 @@ export async function broadcastRumor ({
974
980
  const prepared = normalizePreparedPublications({ preparedPublication, preparedPublications })
975
981
  const { event, wireEvent } = await makeOutgoingRumor({ senderSigner, rumor })
976
982
  const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability, preparedPublications: prepared })
977
- const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers, receiverTag: '', deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, temporaryStorageArea, fileChunkIndex, onPreparedSeed: preparedSeedHandler(onPreparedSeed, deletion), preparedPublications: prepared, _getIykcProofs, _publish })
983
+ const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers, receiverTag: '', deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, temporaryStorageArea, fileChunkIndex, seedable, onPreparedSeed: preparedSeedHandler(onPreparedSeed, deletion), preparedPublications: prepared, _getIykcProofs, _publish })
978
984
  return withDelivery({ rumor: event }, reports, deletion.deletionSeckey)
979
985
  }
980
986
 
@@ -996,6 +1002,7 @@ export async function broadcastEvent ({
996
1002
  deletionSeckey,
997
1003
  autoDeletionCapability = true,
998
1004
  fileChunkIndex,
1005
+ seedable = true,
999
1006
  onPreparedSeed,
1000
1007
  preparedPublication,
1001
1008
  preparedPublications,
@@ -1006,7 +1013,7 @@ export async function broadcastEvent ({
1006
1013
  const prepared = normalizePreparedPublications({ preparedPublication, preparedPublications })
1007
1014
  const wireEvent = assertValidSignedEvent({ ...event, tags: cloneTags(event?.tags) })
1008
1015
  const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability, preparedPublications: prepared })
1009
- const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers, receiverTag: '', deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, temporaryStorageArea, fileChunkIndex, onPreparedSeed: preparedSeedHandler(onPreparedSeed, deletion), preparedPublications: prepared, _getIykcProofs, _publish })
1016
+ const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers, receiverTag: '', deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, temporaryStorageArea, fileChunkIndex, seedable, onPreparedSeed: preparedSeedHandler(onPreparedSeed, deletion), preparedPublications: prepared, _getIykcProofs, _publish })
1010
1017
  return withDelivery({ event: wireEvent }, reports, deletion.deletionSeckey)
1011
1018
  }
1012
1019
 
@@ -1 +1,3 @@
1
1
  export const DEFAULT_STALE_CHANNEL_SECONDS = 45 * 24 * 60 * 60
2
+ export const FILE_CHUNKS_REQUEST_CODE = 'fileChunksRequest_p5cc'
3
+ export const FILE_CHUNKS_REPLY_CODE = 'fileChunksReply_p5cc'
@@ -1,8 +1,10 @@
1
1
  import { ValidationError } from '../../../error/index.js'
2
+ import { withRecoverableLock } from '../../../helpers/recoverable-lock.js'
2
3
  import { createQueue } from '../../../idb-queue/index.js'
3
4
 
4
- const localLocks = new WeakMap()
5
5
  const keyFor = row => `${row.controlChannelPubkey}:${row.fileChannelPubkey}:${row.receiverPubkey}`
6
+ const CATALOG_LOCK_LEASE_MS = 15_000
7
+ const CATALOG_LOCK_HEARTBEAT_MS = 5_000
6
8
 
7
9
  // A grant contains no payload, key material or retention reference in the file
8
10
  // store. Serialize read/merge/write with other coordinators for this identity.
@@ -33,12 +35,13 @@ export function createFileCatalog ({ messenger, now, storage }) {
33
35
  let database
34
36
  const db = () => (database ??= createQueue({ prefix, indexedDB: messenger._indexedDB, evictionPolicy: 'reject', indexes: { key: { keyPath: 'key', unique: true }, channel: 'fileChannelPubkey' } }))
35
37
  function lock (work) {
36
- if (globalThis.navigator?.locks?.request) return navigator.locks.request(prefix, work)
37
- let locks = localLocks.get(messenger._indexedDB)
38
- if (!locks) localLocks.set(messenger._indexedDB, (locks = new Map()))
39
- const task = (locks.get(prefix) || Promise.resolve()).catch(() => {}).then(work)
40
- locks.set(prefix, task.catch(() => {}))
41
- return task
38
+ return withRecoverableLock({
39
+ name: prefix,
40
+ work,
41
+ fallbackScope: messenger._indexedDB,
42
+ leaseMs: CATALOG_LOCK_LEASE_MS,
43
+ heartbeatMs: CATALOG_LOCK_HEARTBEAT_MS
44
+ })
42
45
  }
43
46
  function isValid (row) {
44
47
  const parent = messenger.channels.get(row.controlChannelPubkey)
@@ -12,9 +12,9 @@ import * as channelTransport from '../../private-channel/index.js'
12
12
  import * as messages from '../../private-message/index.js'
13
13
  import { readFileChunkIndex } from '../../private-channel/helpers/event.js'
14
14
  import { compactSeedRouterRows, compactRecordsFromSeed, createEventReplyPacker, ROUTER_SEED_RECORD_TYPE } from '../recovery/index.js'
15
+ import { FILE_CHUNKS_REQUEST_CODE, FILE_CHUNKS_REPLY_CODE } from '../constants/index.js'
15
16
 
16
- export const FILE_CHUNKS_REQUEST_CODE = 'fileChunksRequest_p5cc'
17
- export const FILE_CHUNKS_REPLY_CODE = 'fileChunksReply_p5cc'
17
+ export { FILE_CHUNKS_REQUEST_CODE, FILE_CHUNKS_REPLY_CODE }
18
18
  export const IRFS_CHUNK_RECORD_TYPE = 'irfsChunk_v1'
19
19
  export const AUTO_DOWNLOAD_BYTES = 1024 * 1024
20
20
  export const FILE_REQUEST_CHUNKS = 16
@@ -199,6 +199,7 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
199
199
  code: FILE_CHUNKS_REPLY_CODE,
200
200
  idempotencyKey: `${FILE_CHUNKS_REPLY_CODE}:${question.id}:${file.root}`,
201
201
  eventsPerChunk: 1,
202
+ seedable: false,
202
203
  recordsFromInput: record => [record]
203
204
  })
204
205
  for (const index of indices) {
@@ -240,6 +241,7 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
240
241
  code: FILE_CHUNKS_REPLY_CODE,
241
242
  idempotencyKey: `${FILE_CHUNKS_REPLY_CODE}:${question.id}:${file.root}`,
242
243
  eventsPerChunk: 1,
244
+ seedable: false,
243
245
  recordsFromInput: row => compactRecordsFromSeed(row, { receiverPubkey: question.pubkey })
244
246
  })
245
247
  }
@@ -369,7 +371,7 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
369
371
  requestedSeeders.add(peer)
370
372
  requestRoundAt = Date.now() + _hedgeMs
371
373
  // The request is on dm; its compact reply is on the file channel.
372
- await messenger.ask({ channelPubkey: file.controlChannelPubkey, receiverPubkey: peer, code: FILE_CHUNKS_REQUEST_CODE, payload: { fileChannelPubkey: file.fileChannelPubkey, missingRanges: rangesFor(missing) } }).catch(reportError)
374
+ await messenger.ask({ channelPubkey: file.controlChannelPubkey, receiverPubkey: peer, code: FILE_CHUNKS_REQUEST_CODE, seedable: false, payload: { fileChannelPubkey: file.fileChannelPubkey, missingRanges: rangesFor(missing) } }).catch(reportError)
373
375
  }
374
376
  if (!remaining.length && Date.now() - Math.max(lastProgress, requestRoundAt - _hedgeMs) >= _idleMs) {
375
377
  const details = {
@@ -79,7 +79,7 @@ import { classifyEvent, isEphemeralEvent } from '../event/index.js'
79
79
  import { createChannelStateStore } from './services/channel-state.js'
80
80
  import { normalizeIdempotencyKey, readIdempotencyKey } from '../private-message/helpers/idempotency.js'
81
81
  import { eventCreatedAtMs, readMilliseconds } from '../private-message/helpers/timestamp.js'
82
- import { DEFAULT_STALE_CHANNEL_SECONDS } from './constants/index.js'
82
+ import { DEFAULT_STALE_CHANNEL_SECONDS, FILE_CHUNKS_REPLY_CODE, FILE_CHUNKS_REQUEST_CODE } from './constants/index.js'
83
83
  import {
84
84
  activatePrivateMessengerStorage,
85
85
  DEFAULT_IDENTITY_STORAGE_RETENTION_SECONDS,
@@ -147,6 +147,45 @@ const DELIVERY_PRIORITY = Object.freeze({
147
147
  normal: 2
148
148
  })
149
149
  const DELIVERY_PRIORITY_NAMES = new Set(Object.keys(DELIVERY_PRIORITY))
150
+ const DEFAULT_RESERVE_PRIORITIES = Object.freeze([
151
+ DELIVERY_PRIORITY.normal,
152
+ DELIVERY_PRIORITY.lower,
153
+ DELIVERY_PRIORITY.lowest
154
+ ])
155
+ const NON_SEEDABLE_PROTOCOL_CODES = new Set([
156
+ SEEDER_PRESENCE_CODE,
157
+ MISSING_MESSAGES_ASK_CODE,
158
+ MISSING_MESSAGES_REPLY_CODE,
159
+ FILE_CHUNKS_REQUEST_CODE,
160
+ FILE_CHUNKS_REPLY_CODE
161
+ ])
162
+
163
+ function assertSeedableOption (seedable) {
164
+ if (typeof seedable !== 'boolean') throw new ValidationError('INVALID_SEEDABLE')
165
+ }
166
+
167
+ function resolvedMessageCode (message, code) {
168
+ if (message && typeof message === 'object' && message.code != null) return String(message.code)
169
+ return code == null ? '' : String(code)
170
+ }
171
+
172
+ function normalizeReservePriorities (priorities) {
173
+ if (priorities === undefined) return DEFAULT_RESERVE_PRIORITIES
174
+ if (!Array.isArray(priorities) || !priorities.length) {
175
+ throw new ValidationError('INVALID_DELIVERY_PRIORITIES')
176
+ }
177
+ const seen = new Set()
178
+ const mapped = []
179
+ for (const name of priorities) {
180
+ if (typeof name !== 'string' || !DELIVERY_PRIORITY_NAMES.has(name)) {
181
+ throw new ValidationError('INVALID_DELIVERY_PRIORITIES')
182
+ }
183
+ if (seen.has(name)) continue
184
+ seen.add(name)
185
+ mapped.push(DELIVERY_PRIORITY[name])
186
+ }
187
+ return mapped
188
+ }
150
189
  const PROVENANCE_PRIORITY = {
151
190
  signed: 2,
152
191
  direct: 1,
@@ -378,6 +417,7 @@ export class PrivateMessenger {
378
417
  onError = defaultOnError,
379
418
  resolveInboundCoalescing,
380
419
  resolveInboundPriority,
420
+ resolveInboundSeedable,
381
421
  admitInboundPeer,
382
422
  _privateMessage = privateMessage,
383
423
  _privateChannel = privateChannel,
@@ -406,6 +446,9 @@ export class PrivateMessenger {
406
446
  if (resolveInboundPriority != null && typeof resolveInboundPriority !== 'function') {
407
447
  throw new ValidationError('INVALID_RESOLVE_INBOUND_PRIORITY')
408
448
  }
449
+ if (resolveInboundSeedable != null && typeof resolveInboundSeedable !== 'function') {
450
+ throw new ValidationError('INVALID_RESOLVE_INBOUND_SEEDABLE')
451
+ }
409
452
  if (admitInboundPeer != null && typeof admitInboundPeer !== 'function') {
410
453
  throw new ValidationError('INVALID_ADMIT_INBOUND_PEER')
411
454
  }
@@ -457,6 +500,7 @@ export class PrivateMessenger {
457
500
  this.onDebug = onDebug
458
501
  this.resolveInboundCoalescing = resolveInboundCoalescing
459
502
  this.resolveInboundPriority = resolveInboundPriority
503
+ this.resolveInboundSeedable = resolveInboundSeedable
460
504
  this.admitInboundPeer = admitInboundPeer
461
505
  this._privateMessage = _privateMessage.createPrivateMessageSession?.() ?? _privateMessage
462
506
  this._privateChannel = _privateChannel
@@ -2757,8 +2801,39 @@ export class PrivateMessenger {
2757
2801
  return seed => this.enqueueSeed(channelPubkey, seed)
2758
2802
  }
2759
2803
 
2804
+ shouldSeedInbound (channelPubkey, seed) {
2805
+ if (!seed) return false
2806
+ if (seed.router && !privateChannel.isRouterSeedable(seed.router)) return false
2807
+ if (seed.event) {
2808
+ let payload = null
2809
+ try { payload = privateMessage.parseRumorContent(seed.event) } catch {}
2810
+ const code = isPlainObject(payload) && typeof payload.code === 'string' ? payload.code : ''
2811
+ if (code && NON_SEEDABLE_PROTOCOL_CODES.has(code)) return false
2812
+ if (this.resolveInboundSeedable) {
2813
+ try {
2814
+ const decision = this.resolveInboundSeedable({
2815
+ event: seed.event,
2816
+ outer: seed.outer,
2817
+ router: seed.router,
2818
+ channelPubkey,
2819
+ code,
2820
+ payload
2821
+ })
2822
+ if (decision === false) return false
2823
+ if (decision !== true && decision != null) {
2824
+ this.onError?.(new ValidationError('INVALID_RESOLVE_INBOUND_SEEDABLE_RESULT'))
2825
+ }
2826
+ } catch (error) {
2827
+ this.onError?.(error)
2828
+ }
2829
+ }
2830
+ }
2831
+ return true
2832
+ }
2833
+
2760
2834
  async enqueueSeed (channelPubkey, seed) {
2761
2835
  if (!this.offlineRecoverySecondsFor(channelPubkey)) return
2836
+ if (!this.shouldSeedInbound(channelPubkey, seed)) return
2762
2837
  if (this.seedStorage) {
2763
2838
  const receivedAt = nowSeconds()
2764
2839
  const rows = seed.recordType === NYM_CARRIER_SEED_RECORD_TYPE || seed.carriers?.length
@@ -2962,14 +3037,15 @@ export class PrivateMessenger {
2962
3037
  }
2963
3038
 
2964
3039
  // A cancellable iterator, including while next() is waiting on an empty queue.
2965
- messages () {
3040
+ messages (options = {}) {
3041
+ normalizeReservePriorities(options?.priorities)
2966
3042
  let cancelled = false
2967
3043
  const held = new Set()
2968
3044
  let tail = Promise.resolve()
2969
3045
  const next = async () => {
2970
3046
  while (true) {
2971
3047
  if (cancelled || this.closePromise) break
2972
- const delivery = await this.nextMessage()
3048
+ const delivery = await this.nextMessage({ priorities: options?.priorities })
2973
3049
  if (delivery) {
2974
3050
  if (cancelled || this.closePromise) { await delivery.nack(); break }
2975
3051
  held.add(delivery)
@@ -2998,25 +3074,26 @@ export class PrivateMessenger {
2998
3074
  }
2999
3075
  }
3000
3076
 
3001
- nextMessage () {
3002
- const work = this.reserveMessage()
3077
+ get supportsPriorityLanes () {
3078
+ return true
3079
+ }
3080
+
3081
+ nextMessage (options = {}) {
3082
+ const priorities = normalizeReservePriorities(options?.priorities)
3083
+ const work = this.reserveMessage({ priorities })
3003
3084
  this.deliveryReads.add(work)
3004
3085
  work.then(() => this.deliveryReads.delete(work), () => this.deliveryReads.delete(work))
3005
3086
  return work
3006
3087
  }
3007
3088
 
3008
- async reserveMessage () {
3089
+ async reserveMessage ({ priorities = DEFAULT_RESERVE_PRIORITIES } = {}) {
3009
3090
  this.assertOpen()
3010
3091
  this.touchStorageActivity().catch(err => this.onError?.(err))
3011
3092
  await this.queueOperationTail
3012
3093
  const reservation = await this.queue.reserve({
3013
3094
  nackCoalescingIndex: COALESCING_INDEX,
3014
3095
  priorityIndex: DELIVERY_PRIORITY_INDEX,
3015
- priorities: [
3016
- DELIVERY_PRIORITY.normal,
3017
- DELIVERY_PRIORITY.lower,
3018
- DELIVERY_PRIORITY.lowest
3019
- ]
3096
+ priorities
3020
3097
  })
3021
3098
  if (!reservation) return null
3022
3099
  if (this.closePromise) { await reservation.nack(); return null }
@@ -3067,8 +3144,11 @@ export class PrivateMessenger {
3067
3144
  async ask (options = {}) {
3068
3145
  const {
3069
3146
  channelPubkey = this.defaultChannelPubkey(), receiverPubkey, relays, relayToReceivers,
3070
- message, code, payload, error, content, idempotencyKey, deletionPubkey, useBulkPacing = false
3147
+ message, code, payload, error, content, idempotencyKey, deletionPubkey, useBulkPacing = false,
3148
+ seedable = true
3071
3149
  } = options
3150
+ assertSeedableOption(seedable)
3151
+ const effectiveSeedable = seedable && !NON_SEEDABLE_PROTOCOL_CODES.has(resolvedMessageCode(message, code))
3072
3152
  const capacityEgress = this.capacityEgressFor(options)
3073
3153
  const normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
3074
3154
  const channel = this.requireWritableChannel(channelPubkey, { capacityEgress })
@@ -3094,7 +3174,8 @@ export class PrivateMessenger {
3094
3174
  content,
3095
3175
  idempotencyKey: normalizedIdempotencyKey,
3096
3176
  useBulkPacing,
3097
- onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
3177
+ seedable: effectiveSeedable,
3178
+ onPreparedSeed: effectiveSeedable ? this.outgoingSeedHandler(channelPubkey) : undefined,
3098
3179
  _getIykcProofs: this.contentKeyLookup()
3099
3180
  })
3100
3181
  } finally { releaseActivity() }
@@ -3103,8 +3184,11 @@ export class PrivateMessenger {
3103
3184
  async reply (options = {}) {
3104
3185
  const {
3105
3186
  channelPubkey = this.defaultChannelPubkey(), question, receiverPubkey, relays, relayToReceivers,
3106
- message, code, payload, error, content, idempotencyKey, deletionPubkey, expiresAt, useBulkPacing = false
3187
+ message, code, payload, error, content, idempotencyKey, deletionPubkey, expiresAt, useBulkPacing = false,
3188
+ seedable = true
3107
3189
  } = options
3190
+ assertSeedableOption(seedable)
3191
+ const effectiveSeedable = seedable && !NON_SEEDABLE_PROTOCOL_CODES.has(resolvedMessageCode(message, code))
3108
3192
  const capacityEgress = this.capacityEgressFor(options)
3109
3193
  const normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
3110
3194
  const channel = this.requireWritableChannel(channelPubkey, { capacityEgress })
@@ -3137,7 +3221,8 @@ export class PrivateMessenger {
3137
3221
  content,
3138
3222
  idempotencyKey: normalizedIdempotencyKey,
3139
3223
  useBulkPacing,
3140
- onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
3224
+ seedable: effectiveSeedable,
3225
+ onPreparedSeed: effectiveSeedable ? this.outgoingSeedHandler(channelPubkey) : undefined,
3141
3226
  _getIykcProofs: this.contentKeyLookup()
3142
3227
  })
3143
3228
  } finally { releaseActivity() }
@@ -3146,8 +3231,11 @@ export class PrivateMessenger {
3146
3231
  async tell (options = {}) {
3147
3232
  const {
3148
3233
  channelPubkey = this.defaultChannelPubkey(), receiverPubkey, relays, relayToReceivers,
3149
- message, code, payload, error, content, idempotencyKey, deletionPubkey, useBulkPacing = false
3234
+ message, code, payload, error, content, idempotencyKey, deletionPubkey, useBulkPacing = false,
3235
+ seedable = true
3150
3236
  } = options
3237
+ assertSeedableOption(seedable)
3238
+ const effectiveSeedable = seedable && !NON_SEEDABLE_PROTOCOL_CODES.has(resolvedMessageCode(message, code))
3151
3239
  const capacityEgress = this.capacityEgressFor(options)
3152
3240
  const normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
3153
3241
  const channel = this.requireWritableChannel(channelPubkey, { capacityEgress })
@@ -3173,7 +3261,8 @@ export class PrivateMessenger {
3173
3261
  content,
3174
3262
  idempotencyKey: normalizedIdempotencyKey,
3175
3263
  useBulkPacing,
3176
- onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
3264
+ seedable: effectiveSeedable,
3265
+ onPreparedSeed: effectiveSeedable ? this.outgoingSeedHandler(channelPubkey) : undefined,
3177
3266
  _getIykcProofs: this.contentKeyLookup()
3178
3267
  })
3179
3268
  } finally { releaseActivity() }
@@ -3183,8 +3272,11 @@ export class PrivateMessenger {
3183
3272
  const {
3184
3273
  channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers,
3185
3274
  message, code, payload, error, content, idempotencyKey, deletionPubkey, createdAt, createdAtMs,
3186
- onPreparedSeed, preparedPublication, preparedPublications, useBulkPacing = false
3275
+ onPreparedSeed, preparedPublication, preparedPublications, useBulkPacing = false,
3276
+ seedable = true
3187
3277
  } = options
3278
+ assertSeedableOption(seedable)
3279
+ const effectiveSeedable = seedable && !NON_SEEDABLE_PROTOCOL_CODES.has(resolvedMessageCode(message, code))
3188
3280
  const capacityEgress = this.capacityEgressFor(options)
3189
3281
  const normalizedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
3190
3282
  const channel = this.requireWritableChannel(channelPubkey, { capacityEgress })
@@ -3216,14 +3308,16 @@ export class PrivateMessenger {
3216
3308
  createdAt,
3217
3309
  createdAtMs,
3218
3310
  useBulkPacing,
3219
- onPreparedSeed: onPreparedSeed || this.outgoingSeedHandler(channelPubkey),
3311
+ seedable: effectiveSeedable,
3312
+ onPreparedSeed: effectiveSeedable ? (onPreparedSeed || this.outgoingSeedHandler(channelPubkey)) : undefined,
3220
3313
  preparedPublications: prepared.length ? prepared : undefined,
3221
3314
  _getIykcProofs: this.contentKeyLookup()
3222
3315
  })
3223
3316
  } finally { releaseActivity() }
3224
3317
  }
3225
3318
 
3226
- async broadcastRumor ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, rumor, deletionPubkey, signal, attemptStartedAt, onPreparedSeed, preparedPublication, preparedPublications, onDebug, useBulkPacing = false, capacityEgress, [CAPACITY_EGRESS]: scopedCapacityEgress }) {
3319
+ async broadcastRumor ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, rumor, deletionPubkey, signal, attemptStartedAt, onPreparedSeed, preparedPublication, preparedPublications, onDebug, useBulkPacing = false, seedable = true, capacityEgress, [CAPACITY_EGRESS]: scopedCapacityEgress }) {
3320
+ assertSeedableOption(seedable)
3227
3321
  const capacityEgressToken = this.capacityEgressFor({ capacityEgress: scopedCapacityEgress || capacityEgress })
3228
3322
  const channel = this.requireWritableChannel(channelPubkey, { capacityEgress: capacityEgressToken })
3229
3323
  const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
@@ -3247,14 +3341,16 @@ export class PrivateMessenger {
3247
3341
  autoDeletionCapability: this.autoDeletionCapabilityFor(channel),
3248
3342
  rumor,
3249
3343
  useBulkPacing,
3250
- onPreparedSeed: onPreparedSeed || this.outgoingSeedHandler(channelPubkey),
3344
+ seedable,
3345
+ onPreparedSeed: seedable ? (onPreparedSeed || this.outgoingSeedHandler(channelPubkey)) : undefined,
3251
3346
  preparedPublications: prepared.length ? prepared : undefined,
3252
3347
  _getIykcProofs: this.contentKeyLookup()
3253
3348
  })
3254
3349
  } finally { releaseActivity() }
3255
3350
  }
3256
3351
 
3257
- async broadcastEvent ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, event, deletionPubkey, signal, attemptStartedAt, onPreparedSeed, preparedPublication, preparedPublications, onDebug, useBulkPacing = false, capacityEgress, [CAPACITY_EGRESS]: scopedCapacityEgress }) {
3352
+ async broadcastEvent ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, event, deletionPubkey, signal, attemptStartedAt, onPreparedSeed, preparedPublication, preparedPublications, onDebug, useBulkPacing = false, seedable = true, capacityEgress, [CAPACITY_EGRESS]: scopedCapacityEgress }) {
3353
+ assertSeedableOption(seedable)
3258
3354
  const capacityEgressToken = this.capacityEgressFor({ capacityEgress: scopedCapacityEgress || capacityEgress })
3259
3355
  const channel = this.requireWritableChannel(channelPubkey, { capacityEgress: capacityEgressToken })
3260
3356
  const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
@@ -3278,7 +3374,8 @@ export class PrivateMessenger {
3278
3374
  autoDeletionCapability: this.autoDeletionCapabilityFor(channel),
3279
3375
  event,
3280
3376
  useBulkPacing,
3281
- onPreparedSeed: onPreparedSeed || this.outgoingSeedHandler(channelPubkey),
3377
+ seedable,
3378
+ onPreparedSeed: seedable ? (onPreparedSeed || this.outgoingSeedHandler(channelPubkey)) : undefined,
3282
3379
  preparedPublications: prepared.length ? prepared : undefined,
3283
3380
  _getIykcProofs: this.contentKeyLookup()
3284
3381
  })
@@ -3346,7 +3443,7 @@ export class PrivateMessenger {
3346
3443
  code: SEEDER_PRESENCE_CODE,
3347
3444
  payload: {},
3348
3445
  useBulkPacing: true,
3349
- onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
3446
+ seedable: false,
3350
3447
  _getIykcProofs: this.contentKeyLookup()
3351
3448
  })
3352
3449
  }
@@ -3654,7 +3751,8 @@ export class PrivateMessenger {
3654
3751
  until,
3655
3752
  ...(priority === 'normal' ? {} : { priority })
3656
3753
  },
3657
- useBulkPacing: priority !== 'normal'
3754
+ useBulkPacing: priority !== 'normal',
3755
+ seedable: false
3658
3756
  })
3659
3757
  await assertMessagePublished(ask, ask.question)
3660
3758
  asks.push(ask)
@@ -232,6 +232,7 @@ export function createEventReplyPacker ({
232
232
  recordsFromInput = eventRecordFromInput,
233
233
  sendEmptyReply = false,
234
234
  useBulkPacing = true,
235
+ seedable = true,
235
236
  idempotencyKey
236
237
  }) {
237
238
  if (!messenger?.reply) throw new ValidationError('MESSENGER_REQUIRED')
@@ -239,6 +240,7 @@ export function createEventReplyPacker ({
239
240
  if (!receiverPubkey) throw new ValidationError('RECEIVER_PUBKEY_REQUIRED')
240
241
  if (!Number.isSafeInteger(eventsPerChunk) || eventsPerChunk < 1) throw new ValidationError('INVALID_EVENTS_PER_CHUNK')
241
242
  if (!Number.isSafeInteger(bytesPerChunk) || bytesPerChunk < 1) throw new ValidationError('INVALID_BYTES_PER_CHUNK')
243
+ if (typeof seedable !== 'boolean') throw new ValidationError('INVALID_SEEDABLE')
242
244
  const idempotencyKeyBase = normalizeIdempotencyKeyBase(idempotencyKey)
243
245
 
244
246
  let chunk = ''
@@ -259,6 +261,7 @@ export function createEventReplyPacker ({
259
261
  ? { idempotencyKey: chunkIdempotencyKey(idempotencyKeyBase, index) }
260
262
  : {}),
261
263
  useBulkPacing,
264
+ ...(seedable ? {} : { seedable: false }),
262
265
  payload: {
263
266
  ...payload,
264
267
  index,
@@ -321,6 +324,7 @@ export function createMissingMessageReplyPacker ({
321
324
  bytesPerChunk = DEFAULT_REPLY_BYTES_PER_CHUNK,
322
325
  sendEmptyReply = false,
323
326
  useBulkPacing,
327
+ seedable = false,
324
328
  idempotencyKey
325
329
  }) {
326
330
  if (!messenger?.reply) throw new ValidationError('MESSENGER_REQUIRED')
@@ -330,6 +334,7 @@ export function createMissingMessageReplyPacker ({
330
334
  if (!Number.isSafeInteger(bytesPerChunk) || bytesPerChunk < 1) throw new ValidationError('INVALID_BYTES_PER_CHUNK')
331
335
  if (!RECOVERY_PRIORITIES.has(priority)) throw new ValidationError('INVALID_RECOVERY_PRIORITY')
332
336
  if (useBulkPacing !== undefined && typeof useBulkPacing !== 'boolean') throw new ValidationError('INVALID_USE_BULK_PACING')
337
+ if (typeof seedable !== 'boolean') throw new ValidationError('INVALID_SEEDABLE')
333
338
  idempotencyKey ||= `${MISSING_MESSAGES_REPLY_CODE}:${question.id}`
334
339
 
335
340
  const range = backfillRequestRange(question, since, until)
@@ -348,6 +353,7 @@ export function createMissingMessageReplyPacker ({
348
353
  bytesPerChunk,
349
354
  sendEmptyReply,
350
355
  useBulkPacing: useBulkPacing ?? priority !== 'normal',
356
+ seedable,
351
357
  idempotencyKey,
352
358
  recordsFromInput: seed => compactRecordsFromSeed(seed, { receiverPubkey, since: range.since, until: range.until })
353
359
  })
@@ -1,4 +1,5 @@
1
1
  import { run } from '../../idb/index.js'
2
+ import { withRecoverableLock } from '../../helpers/recoverable-lock.js'
2
3
  import { cleanupReceivedChunkStorage } from '../../private-channel/services/received-chunks.js'
3
4
  import { cleanupTemporaryStorage } from '../../temporary-storage/index.js'
4
5
  import { DEFAULT_STALE_CHANNEL_SECONDS } from '../constants/index.js'
@@ -8,12 +9,14 @@ const REGISTRY_VERSION = 1
8
9
  const STORAGE_SETS_STORE = 'storageSets'
9
10
  const LEASES_STORE = 'leases'
10
11
  const LOCK_NAME = 'libp2r2p:private-messenger:storage-maintenance'
12
+ const LOCK_LEASE_MS = 15_000
13
+ const LOCK_HEARTBEAT_MS = 5_000
14
+ const DELETE_DATABASE_BLOCKED_TIMEOUT_MS = 5_000
11
15
  const LEASE_MS = 2 * 60 * 60 * 1000 // 2 hours
12
16
  const DEFAULT_IDENTITY_STORAGE_RETENTION_SECONDS = 60 * 24 * 60 * 60
13
17
  const MAX_RETENTION_SECONDS = Math.floor(Number.MAX_SAFE_INTEGER / 1000)
14
18
  const MAX_RETRY_MS = 5 * 60 * 1000
15
19
 
16
- const localLocks = new WeakMap()
17
20
  const retryTimers = new WeakMap()
18
21
 
19
22
  /*
@@ -167,18 +170,16 @@ function storagePolicy (storageSet) {
167
170
  }
168
171
  }
169
172
 
170
- function withLocalLock (indexedDB, work) {
171
- const prior = localLocks.get(indexedDB) || Promise.resolve()
172
- const next = prior.catch(() => {}).then(work)
173
- localLocks.set(indexedDB, next.catch(() => {}))
174
- return next
175
- }
176
-
177
- function withMaintenanceLock (indexedDB, work) {
173
+ function withMaintenanceLock (indexedDB, work, options = {}) {
178
174
  if (!indexedDB?.open) return Promise.reject(new Error('IDB_UNAVAILABLE'))
179
- const locks = globalThis.navigator?.locks
180
- if (typeof locks?.request === 'function') return locks.request(LOCK_NAME, work)
181
- return withLocalLock(indexedDB, work)
175
+ return withRecoverableLock({
176
+ name: LOCK_NAME,
177
+ work,
178
+ fallbackScope: indexedDB,
179
+ leaseMs: LOCK_LEASE_MS,
180
+ heartbeatMs: LOCK_HEARTBEAT_MS,
181
+ ...options
182
+ })
182
183
  }
183
184
 
184
185
  function storageDatabaseNames (userPubkey) {
@@ -194,27 +195,46 @@ function storageDatabaseNames (userPubkey) {
194
195
  ]
195
196
  }
196
197
 
197
- function deleteDatabase (indexedDB, name) {
198
+ function deleteDatabase (indexedDB, name, { blockedTimeoutMs = DELETE_DATABASE_BLOCKED_TIMEOUT_MS, signal } = {}) {
198
199
  return new Promise(resolve => {
200
+ let settled = false
201
+ let blockedTimer = null
202
+ const finish = value => {
203
+ if (settled) return
204
+ settled = true
205
+ if (blockedTimer != null) clearTimeout(blockedTimer)
206
+ signal?.removeEventListener('abort', onAbort)
207
+ resolve(value)
208
+ }
209
+ const onAbort = () => finish(false)
210
+ if (signal?.aborted) {
211
+ finish(false)
212
+ return
213
+ }
214
+ signal?.addEventListener('abort', onAbort, { once: true })
199
215
  let request
200
216
  try {
201
217
  request = indexedDB.deleteDatabase(name)
202
218
  } catch {
203
- resolve(false)
219
+ finish(false)
204
220
  return
205
221
  }
206
- request.onsuccess = () => resolve(true)
207
- request.onerror = () => resolve(false)
208
- // A blocked delete request remains live and will continue automatically
209
- // after every other connection closes. Keep the maintenance lock until
210
- // that definitive success/error instead of scheduling a second request.
211
- request.onblocked = () => {}
222
+ request.onsuccess = () => finish(true)
223
+ request.onerror = () => finish(false)
224
+ // A blocked delete request stays live for a bounded grace window so a
225
+ // closing handle can finish, without pinning the cross-tab maintenance lock
226
+ // indefinitely if another tab remains open or frozen.
227
+ request.onblocked = () => {
228
+ if (blockedTimer != null) return
229
+ blockedTimer = setTimeout(() => finish(false), blockedTimeoutMs)
230
+ blockedTimer?.unref?.()
231
+ }
212
232
  })
213
233
  }
214
234
 
215
- async function deleteStorageSet (indexedDB, userPubkey) {
235
+ async function deleteStorageSet (indexedDB, userPubkey, options) {
216
236
  const results = await Promise.all(storageDatabaseNames(userPubkey)
217
- .map(name => deleteDatabase(indexedDB, name)))
237
+ .map(name => deleteDatabase(indexedDB, name, options)))
218
238
  return results.every(Boolean)
219
239
  }
220
240
 
@@ -277,10 +297,12 @@ async function finishDeleteAttempt (indexedDB, attempted, deleted, now) {
277
297
  })
278
298
  }
279
299
 
280
- async function maintainRegistry (indexedDB, now) {
300
+ async function maintainRegistry (indexedDB, now, { assertLeader, signal, blockedTimeoutMs } = {}) {
281
301
  const due = await markAndListDueStorageSets(indexedDB, now)
282
302
  for (const storageSet of due) {
283
- const deleted = await deleteStorageSet(indexedDB, storageSet.userPubkey)
303
+ assertLeader?.()
304
+ const deleted = await deleteStorageSet(indexedDB, storageSet.userPubkey, { blockedTimeoutMs, signal })
305
+ assertLeader?.()
284
306
  await finishDeleteAttempt(indexedDB, storageSet, deleted, now)
285
307
  }
286
308
  const nextAttemptAt = await withRegistryTransaction(indexedDB, 'readonly', async tx => {
@@ -314,11 +336,16 @@ function schedulePendingRetry (indexedDB, temporaryStorageArea, nextAttemptAt, n
314
336
  export async function maintainPrivateMessengerStorage ({
315
337
  indexedDB = globalThis.indexedDB,
316
338
  temporaryStorageArea = globalThis.sessionStorage,
317
- now = Date.now()
339
+ now = Date.now(),
340
+ blockedTimeoutMs = DELETE_DATABASE_BLOCKED_TIMEOUT_MS
318
341
  } = {}) {
319
342
  if (temporaryStorageArea) cleanupTemporaryStorage({ storageArea: temporaryStorageArea })
320
343
  await cleanupReceivedChunkStorage({ indexedDB, now })
321
- const result = await withMaintenanceLock(indexedDB, () => maintainRegistry(indexedDB, now))
344
+ const result = await withMaintenanceLock(
345
+ indexedDB,
346
+ ({ assertLeader, signal }) => maintainRegistry(indexedDB, now, { assertLeader, signal, blockedTimeoutMs }),
347
+ { ifAvailableOnly: true, skippedValue: { processed: 0, nextAttemptAt: null } }
348
+ )
322
349
  schedulePendingRetry(indexedDB, temporaryStorageArea, result.nextAttemptAt, now)
323
350
  return result.processed
324
351
  }