libp2r2p 0.12.25 → 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.
package/README.md CHANGED
@@ -688,6 +688,14 @@ consumer's expired leases are reclaimable by another instance. Apps must save
688
688
  idempotently: a crash between their commit and `ack()` can repeat delivery.
689
689
  The queue is shared by identity, so concurrent consumers claim distinct records.
690
690
 
691
+ An inbound reservation's `capacityEgress` can answer its own work while
692
+ `capacity` is the sole pause reason. `createCapacityEgress()` provides the same
693
+ short-lived scope to a durable sender and covers `ask`, `reply`, `tell`, `yell`,
694
+ `broadcastRumor` and `broadcastEvent`. The scope expires on release. It never
695
+ bypasses network, storage, signer, session-storage or another simultaneous pause.
696
+ The session outbox exposes this only through opt-in
697
+ `enqueue({ ..., allowCapacityEgress: true })`; the default is `false`.
698
+
691
699
  The app-message queue defaults to 16 MiB and rejects writes at capacity, without
692
700
  evicting pending messages. Capacity pressure pauses ingestion and records a
693
701
  recovery gap; successful acknowledgments resume it when possible. While capacity-paused, a
@@ -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.25",
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)