libp2r2p 0.12.16 → 0.12.18
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 +24 -0
- package/package.json +1 -1
- package/private-message/index.js +28 -2
- package/private-messenger/event-store/helpers/codec.js +2 -0
- package/private-messenger/event-store/index.js +39 -1
- package/private-messenger/index.js +154 -29
- package/private-messenger/recovery/index.js +14 -5
- package/private-messenger/services/pending-decryption.js +34 -0
- package/private-messenger/session/index.js +1 -0
package/README.md
CHANGED
|
@@ -269,6 +269,11 @@ evidence, while startup, resume and routine reconciliation retain normal retries
|
|
|
269
269
|
Success enters the normal acknowledged inbox before removing the pending item.
|
|
270
270
|
The session coordinator forwards this API.
|
|
271
271
|
|
|
272
|
+
Messenger initialization and storage maintenance also perform a bounded cleanup
|
|
273
|
+
of historical suspended records. Only `INVALID_MAC` packets with at least three
|
|
274
|
+
MAC attempts and an outer timestamp older than 30 days are removed, at most 100
|
|
275
|
+
per run. Recent MAC failures and every `CONTENT_KEY_NOT_FOUND` packet are kept.
|
|
276
|
+
|
|
272
277
|
Pending recovery waits for 250 ms without channel setup, live/history processing
|
|
273
278
|
or publication activity. Session foreground persistence/publication also delays
|
|
274
279
|
it. After at most five seconds of eligible waiting, a busy channel may advance
|
|
@@ -438,6 +443,13 @@ An invalid or asynchronous resolver result is reported as
|
|
|
438
443
|
remote payload fields should only permit fields to lower priority; a peer must
|
|
439
444
|
not be able to promote itself by supplying a value.
|
|
440
445
|
|
|
446
|
+
Protocol recovery messages enforce the same rule inside the messenger, even when
|
|
447
|
+
an application resolver returns `normal` or another higher class. Seeder presence
|
|
448
|
+
is always `lowest`; missing-message asks and replies accept only the additive
|
|
449
|
+
payload values `lower` or `lowest`, while malformed or promoting values remain
|
|
450
|
+
`normal`. Application resolvers can lower those protocol classes but cannot
|
|
451
|
+
raise them.
|
|
452
|
+
|
|
441
453
|
### Inbound peer admission
|
|
442
454
|
|
|
443
455
|
`PrivateMessenger` accepts an optional synchronous
|
|
@@ -735,6 +747,13 @@ messages. Applications still supply signers and desired channels on reopening;
|
|
|
735
747
|
storage is scoped by origin and user pubkey, not the transient session ID.
|
|
736
748
|
Failed ingestion or incomplete relay fetch reports never complete the gap.
|
|
737
749
|
|
|
750
|
+
`deferColdRecovery` is opt-in and defaults to `false`. The session coordinator
|
|
751
|
+
enables it so reopening many stored conversations first fetches only the recent
|
|
752
|
+
six-hour tail and leaves the rest of the persisted range pending. A later
|
|
753
|
+
`prioritizeRange()` request schedules the foreground recovery pass immediately;
|
|
754
|
+
ordinary live watches remain active throughout, and local conversation summaries
|
|
755
|
+
do not wait for the cold range to finish.
|
|
756
|
+
|
|
738
757
|
`init()` and `createPrivateMessenger()` resolve after local preparation. Likewise,
|
|
739
758
|
`update(options, { waitForBackground = false })` and
|
|
740
759
|
`resume(reason, { waitForBackground = false })` wait for valid local channel
|
|
@@ -794,6 +813,11 @@ process-local: they expire after `priorityTtlMs` (ten minutes) or once covered,
|
|
|
794
813
|
and clear with channel/recovery state. Presence payloads and persisted ranges
|
|
795
814
|
are unchanged.
|
|
796
815
|
|
|
816
|
+
With deferred cold recovery, the background recent-tail probe is sent as
|
|
817
|
+
`lower`; app-directed ranges remain `normal`. Missing-message replies inherit
|
|
818
|
+
the ask's additive priority, defaulting to `lower`, and all recovery traffic uses
|
|
819
|
+
bulk pacing unless explicitly `normal`.
|
|
820
|
+
|
|
797
821
|
`private-channel.fetchHistory(options)` (0.11.6) is the complete-interval API
|
|
798
822
|
used by messenger recovery. It accepts the signers, processor/fragment options,
|
|
799
823
|
callbacks and abort signal of `fetch`, plus inclusive `since`/`until` bounds
|
package/package.json
CHANGED
package/private-message/index.js
CHANGED
|
@@ -212,6 +212,9 @@ export function createPrivateMessageSession ({ _setTimeout = setTimeout, _clearT
|
|
|
212
212
|
let requestSequence = 0
|
|
213
213
|
const watchRequests = new Map()
|
|
214
214
|
let identity
|
|
215
|
+
let rebuildScheduled = false
|
|
216
|
+
let rebuildOptions
|
|
217
|
+
let rebuildWaiters = []
|
|
215
218
|
const receivedChunkScope = globalThis.crypto.randomUUID()
|
|
216
219
|
let subscribe = privateChannel.subscribe
|
|
217
220
|
function assertWatching (channelPubkey) {
|
|
@@ -553,6 +556,27 @@ export function createPrivateMessageSession ({ _setTimeout = setTimeout, _clearT
|
|
|
553
556
|
return Promise.allSettled(closing)
|
|
554
557
|
}
|
|
555
558
|
|
|
559
|
+
function scheduleSubscriptionRebuild (options = {}) {
|
|
560
|
+
rebuildOptions = { ...(rebuildOptions || {}), ...options }
|
|
561
|
+
const result = new Promise((resolve, reject) => rebuildWaiters.push({ resolve, reject }))
|
|
562
|
+
if (rebuildScheduled) return result
|
|
563
|
+
rebuildScheduled = true
|
|
564
|
+
Promise.resolve().then(async () => {
|
|
565
|
+
rebuildScheduled = false
|
|
566
|
+
const current = rebuildOptions || {}
|
|
567
|
+
const waiters = rebuildWaiters
|
|
568
|
+
rebuildOptions = undefined
|
|
569
|
+
rebuildWaiters = []
|
|
570
|
+
try {
|
|
571
|
+
const value = await rebuildSubscriptions(current)
|
|
572
|
+
for (const waiter of waiters) waiter.resolve(value)
|
|
573
|
+
} catch (error) {
|
|
574
|
+
for (const waiter of waiters) waiter.reject(error)
|
|
575
|
+
}
|
|
576
|
+
})
|
|
577
|
+
return result
|
|
578
|
+
}
|
|
579
|
+
|
|
556
580
|
async function watch ({
|
|
557
581
|
channels,
|
|
558
582
|
relays,
|
|
@@ -581,6 +605,7 @@ export function createPrivateMessageSession ({ _setTimeout = setTimeout, _clearT
|
|
|
581
605
|
ignoredGroupTtlMs,
|
|
582
606
|
ignoredGroupMaxEntries,
|
|
583
607
|
since = nowSeconds(),
|
|
608
|
+
_onWatchScheduled,
|
|
584
609
|
_subscribe = privateChannel.subscribe
|
|
585
610
|
}) {
|
|
586
611
|
if (!relays?.length) throw new ValidationError('NO_RELAYS')
|
|
@@ -640,7 +665,8 @@ export function createPrivateMessageSession ({ _setTimeout = setTimeout, _clearT
|
|
|
640
665
|
watchesByChannel.set(channel, next)
|
|
641
666
|
}
|
|
642
667
|
|
|
643
|
-
|
|
668
|
+
_onWatchScheduled?.()
|
|
669
|
+
await scheduleSubscriptionRebuild({ _subscribe })
|
|
644
670
|
return () => {
|
|
645
671
|
const owned = channelList.filter(channel => watchRequests.get(channel) === request)
|
|
646
672
|
return unwatch(owned)
|
|
@@ -653,7 +679,7 @@ export function createPrivateMessageSession ({ _setTimeout = setTimeout, _clearT
|
|
|
653
679
|
watchRequests.set(channel, ++requestSequence)
|
|
654
680
|
watchesByChannel.delete(channel)
|
|
655
681
|
}
|
|
656
|
-
return
|
|
682
|
+
return scheduleSubscriptionRebuild({ gracefulClose: false })
|
|
657
683
|
}
|
|
658
684
|
|
|
659
685
|
function clearChannelState (channelPubkey) {
|
|
@@ -51,6 +51,7 @@ function body (type, row) {
|
|
|
51
51
|
})
|
|
52
52
|
add('payload', payload[0]); add('key', envelope[1])
|
|
53
53
|
if (envelope.length > 2) add('iykc', ...envelope.slice(2))
|
|
54
|
+
if (row.rowHash) add('row', hex(row.rowHash))
|
|
54
55
|
if (row.innerEventId) add('event', hex(row.innerEventId))
|
|
55
56
|
const first = integer(row.firstSeenAt ?? row.router.created_at), last = integer(row.lastSeenAt ?? row.router.created_at)
|
|
56
57
|
if (first > last) fail()
|
|
@@ -114,6 +115,7 @@ export function decodeRecord (event) {
|
|
|
114
115
|
row.payloadRow = JSON.stringify(one('payload'))
|
|
115
116
|
const envelope = [row.receiverPubkey, ...one('key'), ...(one('iykc', false) || [])]
|
|
116
117
|
row.row = JSON.stringify(envelope); row.iykcPubkey = envelope[2] || ''
|
|
118
|
+
row.rowHash = one('row', false)?.[0] || ''
|
|
117
119
|
row.innerEventId = one('event', false)?.[0] || ''
|
|
118
120
|
const file = one('file', false)
|
|
119
121
|
if (file) Object.assign(row, { controlChannelPubkey: file[0], peerPubkey: file[1], root: file[2], fileChannelPubkey: row.channelPubkey, chunkIndex: integer(row.router.tags.find(t => t[0] === 'i')?.[1]), receivedAt: integer(one('received')[0]) })
|
|
@@ -134,6 +134,29 @@ export function createPersonalCopyRecoveryStorage ({ eventStore, signer, now = n
|
|
|
134
134
|
}
|
|
135
135
|
}
|
|
136
136
|
}
|
|
137
|
+
async function existingLogicalRows (rows) {
|
|
138
|
+
const byHash = new Map()
|
|
139
|
+
const logicalKey = row => row.rowHash ? `${row.channelPubkey}:${row.receiverPubkey || ''}:${row.rowHash}` : ''
|
|
140
|
+
for (const row of rows) {
|
|
141
|
+
if (row.rowHash) byHash.set(row.rowHash, row)
|
|
142
|
+
}
|
|
143
|
+
if (!byHash.size) return new Map()
|
|
144
|
+
const hashes = [...byHash.keys()]
|
|
145
|
+
const mirrors = new Map(await Promise.all(hashes.map(async hash => [await mirror('row', hash), hash])))
|
|
146
|
+
const found = new Map()
|
|
147
|
+
for (const batch of chunks([...mirrors.keys()])) {
|
|
148
|
+
const filter = await exactFilterFor('seed')
|
|
149
|
+
filter['#o'] = batch
|
|
150
|
+
for await (const wrapper of pages(eventStore, filter)) {
|
|
151
|
+
const expiry = Number(wrapper.tags?.find(tag => Array.isArray(tag) && tag[0] === 'expiration')?.[1])
|
|
152
|
+
if (!Number.isSafeInteger(expiry) || expiry <= now()) continue
|
|
153
|
+
const { row } = await read(wrapper)
|
|
154
|
+
const hash = mirrors.get(wrapper.tags?.find(tag => Array.isArray(tag) && tag[0] === 'o' && mirrors.has(tag[1]))?.[1])
|
|
155
|
+
if (hash && logicalKey(byHash.get(hash)) === logicalKey(row)) found.set(hash, row)
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return found
|
|
159
|
+
}
|
|
137
160
|
function store (type) {
|
|
138
161
|
async function putMany (rows, options = {}) {
|
|
139
162
|
return serializeMutation(eventStore, () => putManyNow(rows, options))
|
|
@@ -154,7 +177,22 @@ export function createPersonalCopyRecoveryStorage ({ eventStore, signer, now = n
|
|
|
154
177
|
if (record) stored.set(recordId, { ...record.row, recordId })
|
|
155
178
|
}
|
|
156
179
|
}
|
|
157
|
-
|
|
180
|
+
let existingCount = stored.size
|
|
181
|
+
if (type === 'seed') {
|
|
182
|
+
const pendingRows = [...unique.entries()]
|
|
183
|
+
.filter(([recordId]) => !stored.has(recordId))
|
|
184
|
+
.map(([, record]) => record.row)
|
|
185
|
+
const logical = await existingLogicalRows(pendingRows)
|
|
186
|
+
for (const [recordId, record] of unique) {
|
|
187
|
+
if (stored.has(recordId) || !record.row.rowHash) continue
|
|
188
|
+
const hash = record.row.rowHash
|
|
189
|
+
if (logical.has(hash) && logical.get(hash).channelPubkey === record.row.channelPubkey &&
|
|
190
|
+
(logical.get(hash).receiverPubkey || '') === (record.row.receiverPubkey || '')) {
|
|
191
|
+
stored.set(recordId, logical.get(hash))
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
existingCount = stored.size
|
|
195
|
+
}
|
|
158
196
|
let insertedCount = 0
|
|
159
197
|
let blockedCount = 0
|
|
160
198
|
for (const [recordId, record] of unique) {
|
|
@@ -21,6 +21,8 @@
|
|
|
21
21
|
// }
|
|
22
22
|
// const { question } = await messenger.ask({ receiverPubkey, payload: { ping: true }, idempotencyKey: 'request:42' })
|
|
23
23
|
// await messenger.reply({ question, payload: { ok: true }, idempotencyKey: 'reply:42' })
|
|
24
|
+
// Optional expiresAt (Unix seconds) can only shorten the channel default:
|
|
25
|
+
// await messenger.reply({ question, payload: { ok: true }, expiresAt: askExpiration })
|
|
24
26
|
// await messenger.tell({ receiverPubkey, payload: { note: 'hello' }, idempotencyKey: 'notification:42' })
|
|
25
27
|
// await messenger.yell({ receiverPubkeys, payload: { notice: 'hello all' }, idempotencyKey: 'notice:42' })
|
|
26
28
|
// await messenger.broadcastRumor({ receiverPubkeys, rumor: { kind, tags: [], content } })
|
|
@@ -241,6 +243,16 @@ function nowSeconds () {
|
|
|
241
243
|
return Math.floor(Date.now() / 1000)
|
|
242
244
|
}
|
|
243
245
|
|
|
246
|
+
function replyExpirationSeconds (defaultSeconds, expiresAt, nowMs) {
|
|
247
|
+
if (expiresAt === undefined) return defaultSeconds
|
|
248
|
+
if (!Number.isSafeInteger(expiresAt) || expiresAt <= 0) {
|
|
249
|
+
throw new ValidationError('INVALID_EXPIRES_AT')
|
|
250
|
+
}
|
|
251
|
+
const now = Math.floor(nowMs / 1000)
|
|
252
|
+
if (expiresAt <= now) throw new ValidationError('QUESTION_EXPIRED')
|
|
253
|
+
return Math.min(defaultSeconds, expiresAt - now)
|
|
254
|
+
}
|
|
255
|
+
|
|
244
256
|
function normalizeOfflineRecoverySeconds (value) {
|
|
245
257
|
if (!Number.isSafeInteger(value) || value < 0 || value > MAX_OFFLINE_RECOVERY_SECONDS) {
|
|
246
258
|
throw new ValidationError('INVALID_OFFLINE_RECOVERY_SECONDS')
|
|
@@ -316,6 +328,7 @@ export class PrivateMessenger {
|
|
|
316
328
|
priorityTtlMs = DEFAULT_PRIORITY_TTL_MS,
|
|
317
329
|
priorityHedgeDelayMs = DEFAULT_PRIORITY_HEDGE_DELAY_MS,
|
|
318
330
|
priorityHedgeRelays = DEFAULT_PRIORITY_HEDGE_RELAYS,
|
|
331
|
+
deferColdRecovery = false,
|
|
319
332
|
maxDynamicRecoverySeeders = DEFAULT_MAX_DYNAMIC_RECOVERY_SEEDERS,
|
|
320
333
|
messageQueueMaxBytes = DEFAULT_MESSAGE_QUEUE_MAX_BYTES,
|
|
321
334
|
seedQueueMaxBytes = DEFAULT_SEED_QUEUE_MAX_BYTES,
|
|
@@ -386,6 +399,8 @@ export class PrivateMessenger {
|
|
|
386
399
|
this.priorityHedgeRelays = Number.isSafeInteger(hedgeRelays) && hedgeRelays >= 1
|
|
387
400
|
? Math.min(hedgeRelays, 3)
|
|
388
401
|
: DEFAULT_PRIORITY_HEDGE_RELAYS
|
|
402
|
+
if (typeof deferColdRecovery !== 'boolean') throw new ValidationError('INVALID_DEFER_COLD_RECOVERY')
|
|
403
|
+
this.deferColdRecovery = deferColdRecovery
|
|
389
404
|
this.maxDynamicRecoverySeeders = maxDynamicRecoverySeeders
|
|
390
405
|
this.messageQueueMaxBytes = messageQueueMaxBytes
|
|
391
406
|
this.seedQueueMaxBytes = seedQueueMaxBytes
|
|
@@ -476,6 +491,8 @@ export class PrivateMessenger {
|
|
|
476
491
|
this.liveInterruptions = new Map()
|
|
477
492
|
this.liveRecoveryTimers = new Map()
|
|
478
493
|
this.subscriptionDebugKeys = new Set()
|
|
494
|
+
this.channelDebugRefs = new Map()
|
|
495
|
+
this.nextChannelDebugRef = 0
|
|
479
496
|
this.watchRevisionByChannel = new Map()
|
|
480
497
|
this.presenceTimers = new Map()
|
|
481
498
|
this.presenceJobs = new Map()
|
|
@@ -555,6 +572,7 @@ export class PrivateMessenger {
|
|
|
555
572
|
prefix: this.prefix, indexedDB: this._indexedDB,
|
|
556
573
|
report: detail => this.debug('pending-decryption', detail)
|
|
557
574
|
})
|
|
575
|
+
try { await this.pendingDecryption.cleanupSuspended?.() } catch (error) { this.onError?.(error) }
|
|
558
576
|
this.seedQueue = this.seedStorage
|
|
559
577
|
? null
|
|
560
578
|
: await createQueue({
|
|
@@ -741,6 +759,7 @@ export class PrivateMessenger {
|
|
|
741
759
|
})
|
|
742
760
|
await this.refreshAndApplyStoragePolicy()
|
|
743
761
|
await this.cleanupStaleChannels()
|
|
762
|
+
try { await this.pendingDecryption?.cleanupSuspended?.() } catch (error) { this.onError?.(error) }
|
|
744
763
|
await this.pruneStoredSeeds()
|
|
745
764
|
})().catch(err => {
|
|
746
765
|
try { this.onError?.(err) } catch {}
|
|
@@ -823,6 +842,15 @@ export class PrivateMessenger {
|
|
|
823
842
|
this.debug(action, detail)
|
|
824
843
|
}
|
|
825
844
|
|
|
845
|
+
channelDebugRef (pubkey) {
|
|
846
|
+
let ref = this.channelDebugRefs.get(pubkey)
|
|
847
|
+
if (!ref) {
|
|
848
|
+
ref = `channel-${++this.nextChannelDebugRef}`
|
|
849
|
+
this.channelDebugRefs.set(pubkey, ref)
|
|
850
|
+
}
|
|
851
|
+
return ref
|
|
852
|
+
}
|
|
853
|
+
|
|
826
854
|
debugSend (method, channelPubkey, detail = {}) {
|
|
827
855
|
const receiverPubkeys = uniq(detail.receiverPubkeys || (detail.receiverPubkey ? [detail.receiverPubkey] : []))
|
|
828
856
|
this.debug('send', {
|
|
@@ -900,7 +928,10 @@ export class PrivateMessenger {
|
|
|
900
928
|
|
|
901
929
|
if (removedPubkeys.length) {
|
|
902
930
|
await this.stampChannelActivity(removedPubkeys)
|
|
903
|
-
for (const pubkey of removedPubkeys)
|
|
931
|
+
for (const pubkey of removedPubkeys) {
|
|
932
|
+
this.dropRecoveryState(pubkey)
|
|
933
|
+
this.channelDebugRefs.delete(pubkey)
|
|
934
|
+
}
|
|
904
935
|
}
|
|
905
936
|
|
|
906
937
|
const storageSnapshot = await activatePrivateMessengerStorage({
|
|
@@ -1318,7 +1349,7 @@ export class PrivateMessenger {
|
|
|
1318
1349
|
this.writeState(state)
|
|
1319
1350
|
}
|
|
1320
1351
|
|
|
1321
|
-
async watch (channels = [...this.channels.keys()], { scheduleReloadGap = true, signal } = {}) {
|
|
1352
|
+
async watch (channels = [...this.channels.keys()], { scheduleReloadGap = true, signal, _onWatchScheduled } = {}) {
|
|
1322
1353
|
this.assertOpen()
|
|
1323
1354
|
const channelPubkeys = uniq(channels)
|
|
1324
1355
|
for (const pubkey of channelPubkeys) {
|
|
@@ -1334,6 +1365,12 @@ export class PrivateMessenger {
|
|
|
1334
1365
|
for (const pubkey of channelPubkeys) {
|
|
1335
1366
|
const channel = this.channels.get(pubkey)
|
|
1336
1367
|
if (!channel) throw new ValidationError('UNKNOWN_CHANNEL')
|
|
1368
|
+
const channelRef = this.channelDebugRef(pubkey)
|
|
1369
|
+
this.debug('prepare-start', {
|
|
1370
|
+
channelRef,
|
|
1371
|
+
mode: channel.mode,
|
|
1372
|
+
seederCount: channel.seeders.length
|
|
1373
|
+
})
|
|
1337
1374
|
const revision = (this.watchRevisionByChannel.get(pubkey) || 0) + 1
|
|
1338
1375
|
this.watchRevisionByChannel.set(pubkey, revision)
|
|
1339
1376
|
// Persist the pending interval before live delivery can advance lastSeenAt.
|
|
@@ -1375,6 +1412,7 @@ export class PrivateMessenger {
|
|
|
1375
1412
|
receivedChunkTtlMs: this.receivedChunkTtlMsFor(channel),
|
|
1376
1413
|
receivedChunkIndexedDB: this._indexedDB,
|
|
1377
1414
|
onSubscriptionState: state => this.handleSubscriptionState(pubkey, state),
|
|
1415
|
+
_onWatchScheduled,
|
|
1378
1416
|
onError: err => {
|
|
1379
1417
|
if (!isExpectedRecoveryPause(err)) this.onError?.(err)
|
|
1380
1418
|
}
|
|
@@ -1419,8 +1457,8 @@ export class PrivateMessenger {
|
|
|
1419
1457
|
seeders: channel.seeders,
|
|
1420
1458
|
offlineRecoverySeconds: channel.offlineRecoverySeconds
|
|
1421
1459
|
})
|
|
1422
|
-
this.debug('watch', {
|
|
1423
|
-
|
|
1460
|
+
this.debug('watch-ready', {
|
|
1461
|
+
channelRef,
|
|
1424
1462
|
relays: watchRelays,
|
|
1425
1463
|
mode: channel.mode,
|
|
1426
1464
|
seeders: channel.seeders,
|
|
@@ -1454,6 +1492,7 @@ export class PrivateMessenger {
|
|
|
1454
1492
|
this.addOfflineRange(pubkey, Math.max(0, start - this.offlineSkewSeconds), nowSeconds())
|
|
1455
1493
|
const diagnosticRelay = safeDiagnosticRelay(relay)
|
|
1456
1494
|
this.debugOnce(`subscription-interrupted:${diagnosticRelay || ''}:${start}:${safeDiagnosticToken(error?.code) || ''}`, 'subscription-interrupted', {
|
|
1495
|
+
channelRef: this.channelDebugRef(pubkey),
|
|
1457
1496
|
relay: diagnosticRelay,
|
|
1458
1497
|
rangeStart: start,
|
|
1459
1498
|
...subscriptionErrorDiagnostic(error)
|
|
@@ -1469,6 +1508,7 @@ export class PrivateMessenger {
|
|
|
1469
1508
|
interrupted.delete(relay)
|
|
1470
1509
|
if (!interrupted.size) this.liveInterruptions.delete(pubkey)
|
|
1471
1510
|
this.debugOnce(`subscription-recovered:${safeDiagnosticRelay(relay) || ''}:${start}`, 'subscription-recovered', {
|
|
1511
|
+
channelRef: this.channelDebugRef(pubkey),
|
|
1472
1512
|
relay: safeDiagnosticRelay(relay),
|
|
1473
1513
|
rangeStart: start,
|
|
1474
1514
|
rangeEnd: until,
|
|
@@ -1657,6 +1697,9 @@ export class PrivateMessenger {
|
|
|
1657
1697
|
entries.push({ start, end, type, createdAt, expiresAt: createdAt + ttl })
|
|
1658
1698
|
this.recoveryPriority.set(channelPubkey, entries)
|
|
1659
1699
|
}
|
|
1700
|
+
if (this.deferColdRecovery && this.stopByChannel.has(channelPubkey) && !this.pauseReasons.size) {
|
|
1701
|
+
this.scheduleOfflineRecovery(channelPubkey, { startDelayMs: 0 })
|
|
1702
|
+
}
|
|
1660
1703
|
return true
|
|
1661
1704
|
}
|
|
1662
1705
|
|
|
@@ -2098,11 +2141,20 @@ export class PrivateMessenger {
|
|
|
2098
2141
|
const work = Promise.resolve().then(async () => {
|
|
2099
2142
|
if (!this.initialized) await this.initSettledPromise
|
|
2100
2143
|
if (!active()) return
|
|
2101
|
-
|
|
2144
|
+
let release = await this.channelSetupAdmission.acquire(controller.signal)
|
|
2145
|
+
const releaseSetup = () => {
|
|
2146
|
+
const current = release
|
|
2147
|
+
release = null
|
|
2148
|
+
current?.()
|
|
2149
|
+
}
|
|
2102
2150
|
try {
|
|
2103
2151
|
if (!active()) return
|
|
2104
|
-
await this.watch([pubkey], {
|
|
2105
|
-
|
|
2152
|
+
await this.watch([pubkey], {
|
|
2153
|
+
scheduleReloadGap: !recover,
|
|
2154
|
+
signal: controller.signal,
|
|
2155
|
+
_onWatchScheduled: releaseSetup
|
|
2156
|
+
})
|
|
2157
|
+
} finally { releaseSetup() }
|
|
2106
2158
|
if (!active()) return
|
|
2107
2159
|
phase = 'presence'
|
|
2108
2160
|
if (doesModeStoreRecoverySeeds(channel.mode)) await this.startPresencePublisher(pubkey)
|
|
@@ -2281,7 +2333,8 @@ export class PrivateMessenger {
|
|
|
2281
2333
|
}
|
|
2282
2334
|
|
|
2283
2335
|
#deliveryPriority (type, channelPubkey, message) {
|
|
2284
|
-
|
|
2336
|
+
const protocolPriority = protocolDeliveryPriority(message)
|
|
2337
|
+
if (!this.resolveInboundPriority) return protocolPriority
|
|
2285
2338
|
let resolved
|
|
2286
2339
|
try {
|
|
2287
2340
|
resolved = this.resolveInboundPriority(
|
|
@@ -2293,14 +2346,14 @@ export class PrivateMessenger {
|
|
|
2293
2346
|
}
|
|
2294
2347
|
} catch (cause) {
|
|
2295
2348
|
this.onError?.(inboundPriorityError(cause))
|
|
2296
|
-
return
|
|
2349
|
+
return protocolPriority
|
|
2297
2350
|
}
|
|
2298
|
-
if (resolved == null) return
|
|
2351
|
+
if (resolved == null) return protocolPriority
|
|
2299
2352
|
if (typeof resolved === 'string' && DELIVERY_PRIORITY_NAMES.has(resolved)) {
|
|
2300
|
-
return DELIVERY_PRIORITY[resolved]
|
|
2353
|
+
return Math.min(protocolPriority, DELIVERY_PRIORITY[resolved])
|
|
2301
2354
|
}
|
|
2302
2355
|
this.onError?.(inboundPriorityError(new ValidationError('INVALID_INBOUND_PRIORITY')))
|
|
2303
|
-
return
|
|
2356
|
+
return protocolPriority
|
|
2304
2357
|
}
|
|
2305
2358
|
|
|
2306
2359
|
#coalescingMetadata (type, channelPubkey, message, info) {
|
|
@@ -2493,7 +2546,10 @@ export class PrivateMessenger {
|
|
|
2493
2546
|
this.markSeen(channelPubkey, message.outer?.created_at || message.event?.created_at || nowSeconds())
|
|
2494
2547
|
this.wakeDeliveries()
|
|
2495
2548
|
if (!record.coalescingKey || coalesced?.status === 'inserted') {
|
|
2496
|
-
this.debug('
|
|
2549
|
+
this.debug('message-received', {
|
|
2550
|
+
channelRef: this.channelDebugRef(channelPubkey),
|
|
2551
|
+
...debugMessageInfo(type, channelPubkey, message)
|
|
2552
|
+
})
|
|
2497
2553
|
}
|
|
2498
2554
|
this.onMessageQueued?.()
|
|
2499
2555
|
}
|
|
@@ -2826,11 +2882,16 @@ export class PrivateMessenger {
|
|
|
2826
2882
|
} finally { releaseActivity() }
|
|
2827
2883
|
}
|
|
2828
2884
|
|
|
2829
|
-
async reply ({ channelPubkey = this.defaultChannelPubkey(), question, receiverPubkey, relays, relayToReceivers, message, code, payload, error, content, idempotencyKey, deletionPubkey, useBulkPacing = false }) {
|
|
2885
|
+
async reply ({ channelPubkey = this.defaultChannelPubkey(), question, receiverPubkey, relays, relayToReceivers, message, code, payload, error, content, idempotencyKey, deletionPubkey, expiresAt, useBulkPacing = false }) {
|
|
2830
2886
|
idempotencyKey = normalizeIdempotencyKey(idempotencyKey) || undefined
|
|
2831
2887
|
const channel = this.requireWritableChannel(channelPubkey)
|
|
2832
2888
|
const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
|
|
2833
2889
|
try {
|
|
2890
|
+
const expirationSeconds = replyExpirationSeconds(
|
|
2891
|
+
this.eventExpirationSecondsFor(channel),
|
|
2892
|
+
expiresAt,
|
|
2893
|
+
this._now()
|
|
2894
|
+
)
|
|
2834
2895
|
const resolvedReceiverPubkey = receiverPubkey || question?.pubkey || ''
|
|
2835
2896
|
const routing = await this.resolveSendRouting({ channel, receiverPubkeys: [resolvedReceiverPubkey], relays, relayToReceivers })
|
|
2836
2897
|
this.debugSend('reply', channelPubkey, { code, receiverPubkey: receiverPubkey || question?.pubkey || '' })
|
|
@@ -2842,7 +2903,7 @@ export class PrivateMessenger {
|
|
|
2842
2903
|
question,
|
|
2843
2904
|
receiverPubkey,
|
|
2844
2905
|
...routing,
|
|
2845
|
-
expirationSeconds
|
|
2906
|
+
expirationSeconds,
|
|
2846
2907
|
temporaryStorageArea: this.temporaryStorageArea,
|
|
2847
2908
|
deletionPubkey,
|
|
2848
2909
|
autoDeletionCapability: this.autoDeletionCapabilityFor(channel),
|
|
@@ -3236,10 +3297,28 @@ export class PrivateMessenger {
|
|
|
3236
3297
|
if (this.closePromise || !this.channels.has(pubkey) || !this.stopByChannel.has(pubkey)) return
|
|
3237
3298
|
if ((this.watchRevisionByChannel.get(pubkey) || 0) !== revision) return
|
|
3238
3299
|
if (start != null) this.addOfflineRange(pubkey, Math.max(0, start - this.offlineSkewSeconds), nowSeconds())
|
|
3239
|
-
|
|
3300
|
+
const priority = this.recoveryPriorities(pubkey)
|
|
3301
|
+
const backgroundOnly = this.deferColdRecovery && priority.length === 0
|
|
3302
|
+
if (backgroundOnly) {
|
|
3303
|
+
const ranges = this.readState().channels[pubkey]?.offlineRanges || []
|
|
3304
|
+
const range = ranges.toSorted((left, right) => right.end - left.end)[0]
|
|
3305
|
+
if (range) {
|
|
3306
|
+
const end = Math.min(range.end, nowSeconds())
|
|
3307
|
+
const entry = {
|
|
3308
|
+
start: Math.max(range.start, end - this.priorityTailSeconds),
|
|
3309
|
+
end,
|
|
3310
|
+
type: 'tail',
|
|
3311
|
+
background: true,
|
|
3312
|
+
createdAt: Date.now(),
|
|
3313
|
+
expiresAt: Date.now() + this.priorityTtlMs
|
|
3314
|
+
}
|
|
3315
|
+
this.recoveryPriority.set(pubkey, [entry])
|
|
3316
|
+
}
|
|
3317
|
+
}
|
|
3318
|
+
try { await this.recoverOfflineRanges([pubkey], { priorityOnly: backgroundOnly }) } catch (err) {
|
|
3240
3319
|
if (!isExpectedRecoveryPause(err)) this.onError?.(err)
|
|
3241
3320
|
}
|
|
3242
|
-
if (!this.closePromise && !this.pauseReasons.size && this.desiredChannels.has(pubkey) && this.hasPendingRecovery(pubkey)) {
|
|
3321
|
+
if (!backgroundOnly && !this.closePromise && !this.pauseReasons.size && this.desiredChannels.has(pubkey) && this.hasPendingRecovery(pubkey)) {
|
|
3243
3322
|
this.scheduleOfflineRecovery(pubkey, { startDelayMs: 1000 })
|
|
3244
3323
|
}
|
|
3245
3324
|
}, this.reloadGapDelayMs)
|
|
@@ -3267,12 +3346,12 @@ export class PrivateMessenger {
|
|
|
3267
3346
|
}
|
|
3268
3347
|
}
|
|
3269
3348
|
|
|
3270
|
-
async askSeedersForMissingRange (channelPubkey, since, until) {
|
|
3271
|
-
const { asks } = await this.#askSeedersForMissingRangeAttempt(channelPubkey, since, until)
|
|
3349
|
+
async askSeedersForMissingRange (channelPubkey, since, until, { priority = 'lower' } = {}) {
|
|
3350
|
+
const { asks } = await this.#askSeedersForMissingRangeAttempt(channelPubkey, since, until, { priority })
|
|
3272
3351
|
return asks
|
|
3273
3352
|
}
|
|
3274
3353
|
|
|
3275
|
-
async #askSeedersForMissingRangeAttempt (channelPubkey, since, until, { seeders } = {}) {
|
|
3354
|
+
async #askSeedersForMissingRangeAttempt (channelPubkey, since, until, { seeders, priority = 'lower' } = {}) {
|
|
3276
3355
|
if (this.pauseReasons.size) throw this.pausedError()
|
|
3277
3356
|
if (!this.offlineRecoverySecondsFor(channelPubkey)) return { asks: [], failures: [] }
|
|
3278
3357
|
if (!this.channels.get(channelPubkey)?.signer) return { asks: [], failures: [] }
|
|
@@ -3288,8 +3367,12 @@ export class PrivateMessenger {
|
|
|
3288
3367
|
channelPubkey,
|
|
3289
3368
|
receiverPubkey: seeder,
|
|
3290
3369
|
code: MISSING_MESSAGES_ASK_CODE,
|
|
3291
|
-
payload: {
|
|
3292
|
-
|
|
3370
|
+
payload: {
|
|
3371
|
+
since,
|
|
3372
|
+
until,
|
|
3373
|
+
...(priority === 'normal' ? {} : { priority })
|
|
3374
|
+
},
|
|
3375
|
+
useBulkPacing: priority !== 'normal'
|
|
3293
3376
|
})
|
|
3294
3377
|
asks.push(ask)
|
|
3295
3378
|
await assertMessagePublished(ask, ask.question)
|
|
@@ -3323,12 +3406,16 @@ export class PrivateMessenger {
|
|
|
3323
3406
|
const payload = isPlainObject(message.payload?.payload) ? message.payload.payload : {}
|
|
3324
3407
|
const since = Number.isFinite(payload.since) ? payload.since : undefined
|
|
3325
3408
|
const until = Number.isFinite(payload.until) ? payload.until : undefined
|
|
3409
|
+
const priority = payload.priority === 'lower' || payload.priority === 'lowest'
|
|
3410
|
+
? payload.priority
|
|
3411
|
+
: 'normal'
|
|
3326
3412
|
const packer = this.createMissingMessageReplyPacker({
|
|
3327
3413
|
channelPubkey,
|
|
3328
3414
|
question: message.event,
|
|
3329
3415
|
receiverPubkey: message.event?.pubkey,
|
|
3330
3416
|
since,
|
|
3331
3417
|
until,
|
|
3418
|
+
priority,
|
|
3332
3419
|
sendEmptyReply: !this.offlineRecoverySecondsFor(channelPubkey)
|
|
3333
3420
|
})
|
|
3334
3421
|
|
|
@@ -3456,13 +3543,13 @@ export class PrivateMessenger {
|
|
|
3456
3543
|
}
|
|
3457
3544
|
}
|
|
3458
3545
|
|
|
3459
|
-
async recoverOfflineRanges (channels = [...this.stopByChannel.keys()]) {
|
|
3546
|
+
async recoverOfflineRanges (channels = [...this.stopByChannel.keys()], { priorityOnly = false } = {}) {
|
|
3460
3547
|
const failures = []
|
|
3461
3548
|
for (const pubkey of uniq(channels)) {
|
|
3462
3549
|
if (this.pauseReasons.size || this.closePromise || !this.desiredChannels.has(pubkey)) continue
|
|
3463
3550
|
let work = this.recoveries.get(pubkey)
|
|
3464
3551
|
if (!work) {
|
|
3465
|
-
work = this.recoverChannelRanges([pubkey])
|
|
3552
|
+
work = this.recoverChannelRanges([pubkey], { priorityOnly })
|
|
3466
3553
|
this.recoveries.set(pubkey, work)
|
|
3467
3554
|
}
|
|
3468
3555
|
try { failures.push(...await work) } finally { if (this.recoveries.get(pubkey) === work) this.recoveries.delete(pubkey) }
|
|
@@ -3561,7 +3648,7 @@ export class PrivateMessenger {
|
|
|
3561
3648
|
}
|
|
3562
3649
|
}
|
|
3563
3650
|
|
|
3564
|
-
async askPrioritySeeders (channelPubkey, intervals) {
|
|
3651
|
+
async askPrioritySeeders (channelPubkey, intervals, { priority = 'normal' } = {}) {
|
|
3565
3652
|
if (!intervals.length) return []
|
|
3566
3653
|
if (this.pauseReasons.size) throw this.pausedError()
|
|
3567
3654
|
if (!await this.checkRecoveryOnline()) return []
|
|
@@ -3571,7 +3658,10 @@ export class PrivateMessenger {
|
|
|
3571
3658
|
const claimed = []
|
|
3572
3659
|
for (const interval of mergeRanges(intervals)) {
|
|
3573
3660
|
if (this.pauseReasons.size) throw this.pausedError()
|
|
3574
|
-
const attempt = await this.#askSeedersForMissingRangeAttempt(channelPubkey, interval.start, interval.end, {
|
|
3661
|
+
const attempt = await this.#askSeedersForMissingRangeAttempt(channelPubkey, interval.start, interval.end, {
|
|
3662
|
+
seeders,
|
|
3663
|
+
priority
|
|
3664
|
+
})
|
|
3575
3665
|
failures.push(...attempt.failures.map(failure => failure.error))
|
|
3576
3666
|
if (!attempt.failures.length) claimed.push(interval)
|
|
3577
3667
|
}
|
|
@@ -3588,6 +3678,13 @@ export class PrivateMessenger {
|
|
|
3588
3678
|
async runPriorityLane (channelPubkey, channel, ranges) {
|
|
3589
3679
|
const priorities = this.recoveryPriorities(channelPubkey)
|
|
3590
3680
|
if (!priorities.length) return
|
|
3681
|
+
const windowsFor = background => mergeRanges(
|
|
3682
|
+
priorities
|
|
3683
|
+
.filter(entry => Boolean(entry.background) === background)
|
|
3684
|
+
.map(entry => ({ start: entry.start, end: entry.end }))
|
|
3685
|
+
)
|
|
3686
|
+
const normalWindows = windowsFor(false)
|
|
3687
|
+
const backgroundWindows = windowsFor(true)
|
|
3591
3688
|
const fetchRelays = await this.resolveWatchRelays(channel)
|
|
3592
3689
|
for (const range of ranges) {
|
|
3593
3690
|
if (this.pauseReasons.size || this.closePromise) throw this.pausedError()
|
|
@@ -3619,13 +3716,19 @@ export class PrivateMessenger {
|
|
|
3619
3716
|
}
|
|
3620
3717
|
}
|
|
3621
3718
|
if (this.pauseReasons.size || this.closePromise) throw this.pausedError()
|
|
3622
|
-
const
|
|
3623
|
-
|
|
3719
|
+
const currentUncovered = () => intersectRanges(
|
|
3720
|
+
wanted,
|
|
3721
|
+
subtractRanges({ start: range.start, end: range.end }, record.covered)
|
|
3722
|
+
)
|
|
3723
|
+
const normalUncovered = intersectRanges(currentUncovered(), normalWindows)
|
|
3724
|
+
if (normalUncovered.length) await this.askPrioritySeeders(channelPubkey, normalUncovered, { priority: 'normal' })
|
|
3725
|
+
const backgroundUncovered = intersectRanges(currentUncovered(), backgroundWindows)
|
|
3726
|
+
if (backgroundUncovered.length) await this.askPrioritySeeders(channelPubkey, backgroundUncovered, { priority: 'lower' })
|
|
3624
3727
|
}
|
|
3625
3728
|
this.prunePriorityEntries(channelPubkey)
|
|
3626
3729
|
}
|
|
3627
3730
|
|
|
3628
|
-
async recoverChannelRanges (channels) {
|
|
3731
|
+
async recoverChannelRanges (channels, { priorityOnly = false } = {}) {
|
|
3629
3732
|
const failures = []
|
|
3630
3733
|
const state = this.readState()
|
|
3631
3734
|
const now = nowSeconds()
|
|
@@ -3652,6 +3755,8 @@ export class PrivateMessenger {
|
|
|
3652
3755
|
}
|
|
3653
3756
|
}
|
|
3654
3757
|
|
|
3758
|
+
if (priorityOnly) continue
|
|
3759
|
+
|
|
3655
3760
|
const remaining = []
|
|
3656
3761
|
let recoveredThrough = current.recoveredThrough || 0
|
|
3657
3762
|
for (const range of current.offlineRanges) {
|
|
@@ -3716,8 +3821,15 @@ export class PrivateMessenger {
|
|
|
3716
3821
|
continue
|
|
3717
3822
|
}
|
|
3718
3823
|
const recoveryStartedAt = this._now()
|
|
3824
|
+
this.debug('range-recovery-start', {
|
|
3825
|
+
channelRef: this.channelDebugRef(pubkey),
|
|
3826
|
+
rangeStart: range.start,
|
|
3827
|
+
rangeEnd: range.end,
|
|
3828
|
+
tier: record.tier || 'bulk'
|
|
3829
|
+
})
|
|
3719
3830
|
const result = await this.finalizeRecoveryRange({ channelPubkey: pubkey, range, record })
|
|
3720
3831
|
this.debug('recovery-range-complete', {
|
|
3832
|
+
channelRef: this.channelDebugRef(pubkey),
|
|
3721
3833
|
rangeStart: range.start,
|
|
3722
3834
|
rangeEnd: range.end,
|
|
3723
3835
|
complete: result.complete === true,
|
|
@@ -3759,6 +3871,7 @@ export class PrivateMessenger {
|
|
|
3759
3871
|
await this._privateMessage.clearChannelState?.(pubkey)
|
|
3760
3872
|
this.dropRecoveryState(pubkey)
|
|
3761
3873
|
return this.runQueueOperation(async () => {
|
|
3874
|
+
this.channelDebugRefs.delete(pubkey)
|
|
3762
3875
|
this.channels.delete(pubkey)
|
|
3763
3876
|
this.decryptionReadyChannels?.delete(pubkey)
|
|
3764
3877
|
this.removeChannelState(pubkey)
|
|
@@ -4226,6 +4339,18 @@ function inboundPriorityError (cause) {
|
|
|
4226
4339
|
})
|
|
4227
4340
|
}
|
|
4228
4341
|
|
|
4342
|
+
function protocolDeliveryPriority (message) {
|
|
4343
|
+
const code = message?.payload?.code
|
|
4344
|
+
if (code === SEEDER_PRESENCE_CODE) return DELIVERY_PRIORITY.lowest
|
|
4345
|
+
if (code !== MISSING_MESSAGES_ASK_CODE && code !== MISSING_MESSAGES_REPLY_CODE) {
|
|
4346
|
+
return DELIVERY_PRIORITY.normal
|
|
4347
|
+
}
|
|
4348
|
+
const priority = message?.payload?.payload?.priority
|
|
4349
|
+
return priority === 'lower' || priority === 'lowest'
|
|
4350
|
+
? DELIVERY_PRIORITY[priority]
|
|
4351
|
+
: DELIVERY_PRIORITY.normal
|
|
4352
|
+
}
|
|
4353
|
+
|
|
4229
4354
|
function safeDiagnosticToken (value) {
|
|
4230
4355
|
return typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9:._-]{0,159}$/.test(value)
|
|
4231
4356
|
? value
|
|
@@ -12,6 +12,7 @@ export const NYM_CARRIER_SEED_RECORD_TYPE = 'nymCarrier_v1'
|
|
|
12
12
|
|
|
13
13
|
export const DEFAULT_REPLY_BYTES_PER_CHUNK = 128 * 1024
|
|
14
14
|
const DEFAULT_EVENTS_PER_CHUNK = 100
|
|
15
|
+
const RECOVERY_PRIORITIES = new Set(['normal', 'lower', 'lowest'])
|
|
15
16
|
const encoder = new TextEncoder()
|
|
16
17
|
const decoder = new TextDecoder()
|
|
17
18
|
const HASH_PUBKEY = '0'.repeat(64)
|
|
@@ -113,6 +114,7 @@ export function compactSeedRouterRows (seed = {}) {
|
|
|
113
114
|
const parsed = parseRouterRow(row)
|
|
114
115
|
if (!parsed?.receiverPubkey) continue
|
|
115
116
|
const innerEventId = innerEventIdsByRowIndex[index] || innerEventIdsByRowIndex[String(index)] || ''
|
|
117
|
+
const hash = rowHash(payloadRow, row)
|
|
116
118
|
rows.push({
|
|
117
119
|
type: 'seed',
|
|
118
120
|
recordType: ROUTER_SEED_RECORD_TYPE,
|
|
@@ -120,7 +122,7 @@ export function compactSeedRouterRows (seed = {}) {
|
|
|
120
122
|
receiverPubkey: parsed.receiverPubkey,
|
|
121
123
|
iykcPubkey: parsed.iykcPubkey,
|
|
122
124
|
innerEventId,
|
|
123
|
-
rowHash:
|
|
125
|
+
rowHash: hash,
|
|
124
126
|
payloadRow,
|
|
125
127
|
row,
|
|
126
128
|
firstSeenAt: createdAt,
|
|
@@ -137,7 +139,7 @@ export function routerSeedRowKey (seed = {}) {
|
|
|
137
139
|
return [
|
|
138
140
|
seed.channelPubkey || '',
|
|
139
141
|
seed.receiverPubkey || row?.receiverPubkey || '',
|
|
140
|
-
|
|
142
|
+
fallbackRowHash ? `row:${fallbackRowHash}` : innerEventId ? `event:${innerEventId}` : ''
|
|
141
143
|
].join(':')
|
|
142
144
|
}
|
|
143
145
|
|
|
@@ -314,10 +316,11 @@ export function createMissingMessageReplyPacker ({
|
|
|
314
316
|
receiverPubkey = question?.pubkey,
|
|
315
317
|
since,
|
|
316
318
|
until,
|
|
319
|
+
priority = 'lower',
|
|
317
320
|
eventsPerChunk = DEFAULT_EVENTS_PER_CHUNK,
|
|
318
321
|
bytesPerChunk = DEFAULT_REPLY_BYTES_PER_CHUNK,
|
|
319
322
|
sendEmptyReply = false,
|
|
320
|
-
useBulkPacing
|
|
323
|
+
useBulkPacing,
|
|
321
324
|
idempotencyKey
|
|
322
325
|
}) {
|
|
323
326
|
if (!messenger?.reply) throw new ValidationError('MESSENGER_REQUIRED')
|
|
@@ -325,6 +328,8 @@ export function createMissingMessageReplyPacker ({
|
|
|
325
328
|
if (!receiverPubkey) throw new ValidationError('RECEIVER_PUBKEY_REQUIRED')
|
|
326
329
|
if (!Number.isSafeInteger(eventsPerChunk) || eventsPerChunk < 1) throw new ValidationError('INVALID_EVENTS_PER_CHUNK')
|
|
327
330
|
if (!Number.isSafeInteger(bytesPerChunk) || bytesPerChunk < 1) throw new ValidationError('INVALID_BYTES_PER_CHUNK')
|
|
331
|
+
if (!RECOVERY_PRIORITIES.has(priority)) throw new ValidationError('INVALID_RECOVERY_PRIORITY')
|
|
332
|
+
if (useBulkPacing !== undefined && typeof useBulkPacing !== 'boolean') throw new ValidationError('INVALID_USE_BULK_PACING')
|
|
328
333
|
idempotencyKey ||= `${MISSING_MESSAGES_REPLY_CODE}:${question.id}`
|
|
329
334
|
|
|
330
335
|
const range = backfillRequestRange(question, since, until)
|
|
@@ -334,11 +339,15 @@ export function createMissingMessageReplyPacker ({
|
|
|
334
339
|
question,
|
|
335
340
|
receiverPubkey,
|
|
336
341
|
code: MISSING_MESSAGES_REPLY_CODE,
|
|
337
|
-
payload: {
|
|
342
|
+
payload: {
|
|
343
|
+
since: range.since,
|
|
344
|
+
until: range.until,
|
|
345
|
+
...(priority === 'normal' ? {} : { priority })
|
|
346
|
+
},
|
|
338
347
|
eventsPerChunk,
|
|
339
348
|
bytesPerChunk,
|
|
340
349
|
sendEmptyReply,
|
|
341
|
-
useBulkPacing,
|
|
350
|
+
useBulkPacing: useBulkPacing ?? priority !== 'normal',
|
|
342
351
|
idempotencyKey,
|
|
343
352
|
recordsFromInput: seed => compactRecordsFromSeed(seed, { receiverPubkey, since: range.since, until: range.until })
|
|
344
353
|
})
|
|
@@ -2,6 +2,7 @@ import { sha256 } from '@noble/hashes/sha2.js'
|
|
|
2
2
|
import { bytesToHex } from '../../base16/index.js'
|
|
3
3
|
import { base64ToBytes } from '../../base64/index.js'
|
|
4
4
|
import { createQueue } from '../../idb-queue/index.js'
|
|
5
|
+
import { ValidationError } from '../../error/index.js'
|
|
5
6
|
import { isDeferredDecryptionError } from '../../private-channel/helpers/decryption-error.js'
|
|
6
7
|
|
|
7
8
|
const encoder = new TextEncoder()
|
|
@@ -9,6 +10,8 @@ const decoder = new TextDecoder()
|
|
|
9
10
|
const HEX64 = /^[0-9a-f]{64}$/i
|
|
10
11
|
const CONTENT_KEY_FIELDS = ['receiverPubkey', 'ownContentPubkey', 'peerContentPubkey']
|
|
11
12
|
export const PENDING_DECRYPTION_MAX_BYTES = 16 * 1024 * 1024
|
|
13
|
+
export const PENDING_DECRYPTION_CLEANUP_MAX_AGE_SECONDS = 30 * 24 * 60 * 60
|
|
14
|
+
export const PENDING_DECRYPTION_CLEANUP_LIMIT = 100
|
|
12
15
|
|
|
13
16
|
function storedBytes (item) {
|
|
14
17
|
let byteSize = 0
|
|
@@ -180,6 +183,37 @@ export async function createPendingDecryption ({ prefix, indexedDB, maxBytes = P
|
|
|
180
183
|
}
|
|
181
184
|
})
|
|
182
185
|
},
|
|
186
|
+
cleanupSuspended ({
|
|
187
|
+
now = Math.floor(Date.now() / 1000),
|
|
188
|
+
maxAgeSeconds = PENDING_DECRYPTION_CLEANUP_MAX_AGE_SECONDS,
|
|
189
|
+
limit = PENDING_DECRYPTION_CLEANUP_LIMIT
|
|
190
|
+
} = {}) {
|
|
191
|
+
if (!Number.isSafeInteger(now) || now < 0 ||
|
|
192
|
+
!Number.isSafeInteger(maxAgeSeconds) || maxAgeSeconds < 0 ||
|
|
193
|
+
!Number.isSafeInteger(limit) || limit <= 0) {
|
|
194
|
+
return Promise.reject(new ValidationError('INVALID_PENDING_DECRYPTION_CLEANUP_OPTIONS'))
|
|
195
|
+
}
|
|
196
|
+
return serial(async () => {
|
|
197
|
+
const selected = []
|
|
198
|
+
for await (const item of queue.storedItems()) {
|
|
199
|
+
const createdAt = item?.packet?.outer?.created_at ?? item?.outer?.created_at
|
|
200
|
+
if (item.code !== 'INVALID_MAC' || item.macAttempts < 3 ||
|
|
201
|
+
!Number.isSafeInteger(createdAt) || createdAt >= now - maxAgeSeconds) continue
|
|
202
|
+
selected.push(item.id)
|
|
203
|
+
if (selected.length >= limit) break
|
|
204
|
+
}
|
|
205
|
+
for (const id of selected) await queue.removeBy('byId', id)
|
|
206
|
+
if (selected.length) {
|
|
207
|
+
notify('cleaned', {
|
|
208
|
+
reason: 'suspended-age',
|
|
209
|
+
code: 'INVALID_MAC',
|
|
210
|
+
count: selected.length,
|
|
211
|
+
maxAgeSeconds
|
|
212
|
+
})
|
|
213
|
+
}
|
|
214
|
+
return selected.length
|
|
215
|
+
})
|
|
216
|
+
},
|
|
183
217
|
clearChannel: channel => serial(() => queue.removeBy('byChannel', channel)),
|
|
184
218
|
async close () { await tail; flush(); await queue.close() }
|
|
185
219
|
}
|
|
@@ -259,6 +259,7 @@ export function createPrivateMessageSession ({ owner, signer, eventStore, messag
|
|
|
259
259
|
try {
|
|
260
260
|
candidate = await Messenger({
|
|
261
261
|
fallbackRelays, fallbackDelayMs, pendingDecryptionReady, seedStorage, _pendingSeedRecords: () => journal.pendingRows(), userSigner, channels: [], useContentKeys, _waitForForeground: foreground.wait, _observeForeground: foreground.observe,
|
|
262
|
+
deferColdRecovery: true,
|
|
262
263
|
onMessageQueued: () => { if (messengerBinding === binding) return drain() },
|
|
263
264
|
onStateChanged: state => {
|
|
264
265
|
if (closed || messengerBinding !== binding) return
|