libp2r2p 0.12.9 → 0.12.11
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 +57 -4
- package/idb-queue/index.js +128 -7
- package/package.json +1 -1
- package/private-channel/helpers/history.js +4 -1
- package/private-message/helpers/idempotency.js +57 -0
- package/private-message/index.js +16 -7
- package/private-messenger/file/README.md +2 -0
- package/private-messenger/file/index.js +19 -2
- package/private-messenger/helpers/fallback-race.js +7 -1
- package/private-messenger/helpers/send-routing.js +5 -1
- package/private-messenger/index.js +172 -13
- package/private-messenger/recovery/index.js +11 -2
- package/relay/helpers/retry-debug.js +6 -2
- package/relay/services/relay-connection.js +55 -7
- package/relay/services/relay-pool.js +98 -14
package/README.md
CHANGED
|
@@ -359,6 +359,34 @@ await messenger.tell({
|
|
|
359
359
|
})
|
|
360
360
|
```
|
|
361
361
|
|
|
362
|
+
### Inbound message coalescing
|
|
363
|
+
|
|
364
|
+
`PrivateMessenger` accepts an optional synchronous
|
|
365
|
+
`resolveInboundCoalescing(message, { idempotencyKey })` constructor callback.
|
|
366
|
+
The enriched `message` includes `type` and `channelPubkey`. The callback returns
|
|
367
|
+
`null` or `{ key, keep? }`, where `key` is a lowercase 64-character SHA-256
|
|
368
|
+
digest and `keep` is `latest` (default) or `oldest`.
|
|
369
|
+
|
|
370
|
+
The resolver runs for ask, reply, tell, yell, message and nym deliveries after
|
|
371
|
+
exact event-ID deduplication. The final coalescing key is scoped by channel,
|
|
372
|
+
sender, type, message code and provenance. `latest` replaces the pending item in
|
|
373
|
+
place; `oldest` preserves it. While an item is reserved, both policies allow at
|
|
374
|
+
most one successor. Older recovered events do not replace newer requests.
|
|
375
|
+
|
|
376
|
+
For ask, reply, tell and yell, exactly one `["D", key]` tag may serve as an
|
|
377
|
+
automatic fallback when the resolver returns `null`. Its key is non-empty and
|
|
378
|
+
limited to 256 UTF-8 bytes. Message and nym always expose
|
|
379
|
+
`idempotencyKey: null` to the resolver and do not interpret D automatically, so
|
|
380
|
+
arbitrary Nostr kinds retain their own tag semantics.
|
|
381
|
+
|
|
382
|
+
`ask`, `reply`, `tell` and `yell` accept `idempotencyKey` and place D before the
|
|
383
|
+
`h` tag. Invalid keys throw `INVALID_IDEMPOTENCY_KEY`. Broadcast/signed-event
|
|
384
|
+
APIs require the app to put D into the event before hashing/signing.
|
|
385
|
+
|
|
386
|
+
Coalescing does not provide an ingress rate limit or per-peer quota. Exact
|
|
387
|
+
event deduplication, authorization, quarantine, global inbox capacity,
|
|
388
|
+
pause/ACK/NACK ownership and existing storage policy remain independent.
|
|
389
|
+
|
|
362
390
|
### Deleting Private Broadcasts
|
|
363
391
|
|
|
364
392
|
By default, each high-level private-message send creates one fresh deletion
|
|
@@ -1122,8 +1150,14 @@ applies to `sendEvent`, `getEvents`, `getEventsGenerator` and `countEvents`, and
|
|
|
1122
1150
|
each method accepts a per-call override. The budget is independent for each relay
|
|
1123
1151
|
and message type; an AUTH retry does not consume the EVENT publication budget.
|
|
1124
1152
|
`rateLimitRetries: 0` preserves the previous behavior. Relay advice replaces the
|
|
1125
|
-
local exponential backoff; without advice, retries use 1, 2, 4
|
|
1126
|
-
seconds and reset after success.
|
|
1153
|
+
local exponential backoff; without advice, retries use 1, 1.5, 2, 4, 8, 16 and
|
|
1154
|
+
30 seconds and reset after success.
|
|
1155
|
+
|
|
1156
|
+
`maxRateLimitRetryWaitMs` defaults to 1500 and may be overridden per call or set
|
|
1157
|
+
to `null`. Before an automatic retry, the pool computes the effective remaining
|
|
1158
|
+
wait from relay advice and any active cooldown for the same relay/message type.
|
|
1159
|
+
Waits above the gate return the original bounded rate-limit error immediately.
|
|
1160
|
+
Success resets only the local backoff; an
|
|
1127
1161
|
unexpired `retryAt` from a concurrent relay response remains authoritative.
|
|
1128
1162
|
An existing operation deadline is never extended, so a retry whose next deadline
|
|
1129
1163
|
would expire at or after the operation deadline returns the original bounded
|
|
@@ -1134,10 +1168,15 @@ on other relays; attempts already in flight may finish. Bulk retries retain the
|
|
|
1134
1168
|
active queue position and do not allow later work to overtake them. Intermediate
|
|
1135
1169
|
attempts do not reach callbacks, generators or aggregate reports. They may emit
|
|
1136
1170
|
the sanitized `relay rate-limit retry` debug record with only relay URL,
|
|
1137
|
-
operation, attempt/count and
|
|
1171
|
+
operation, attempt/count, numeric deadlines and the wait gate. Live and feed recovery keep
|
|
1138
1172
|
their specialized reconnect behavior; their internal one-shot gap reads disable
|
|
1139
1173
|
the generic retry budget.
|
|
1140
1174
|
|
|
1175
|
+
Paged private-channel history and private-message fallback pass
|
|
1176
|
+
`rateLimitRetries: 0`; their range recovery and routing layers own rate-limit
|
|
1177
|
+
retry and fallback timing. Ephemeral one-shots without such recovery retain the
|
|
1178
|
+
guarded default.
|
|
1179
|
+
|
|
1141
1180
|
Publication calls for the same event and relay share a physical job only when
|
|
1142
1181
|
their pacing is compatible. Calls with the same pacing share one send. An
|
|
1143
1182
|
interactive call joins an existing interactive job or a bulk job already removed
|
|
@@ -1208,6 +1247,16 @@ the old token: its `ack`, `nack` and `renew` return false. Successful writes wak
|
|
|
1208
1247
|
local waiting consumers. Like the other indexed methods, `putBy` is exclusive
|
|
1209
1248
|
to `idb-queue`; the Web Storage queue's common API is unchanged.
|
|
1210
1249
|
|
|
1250
|
+
`queue.coalesceBy(indexName, item, { keep = 'latest', compare, now })` is the
|
|
1251
|
+
non-unique-indexed coalescing variant. `latest` replaces the oldest unreserved
|
|
1252
|
+
match in place and removes other unreserved matches atomically. `oldest` keeps
|
|
1253
|
+
the existing pending match and reports it as ignored. Both policies append one
|
|
1254
|
+
successor when every match is currently reserved. The optional comparator keeps
|
|
1255
|
+
an older item from replacing a newer one. Results use `inserted`, `replaced`,
|
|
1256
|
+
`successor` or `ignored`, with the number of extra pending rows removed and the
|
|
1257
|
+
retained/appended position. Capacity and byte accounting follow the same
|
|
1258
|
+
`reject` rules as `putBy`.
|
|
1259
|
+
|
|
1211
1260
|
Both queue implementations support
|
|
1212
1261
|
`createQueue({ prefix, evictionPolicy: 'reject', maxBytes })` to opt out of
|
|
1213
1262
|
capacity eviction. Oversized items reject with `QUEUE_ITEM_TOO_LARGE`, full
|
|
@@ -1217,13 +1266,15 @@ Opening a reject-policy queue under a smaller budget preserves existing items.
|
|
|
1217
1266
|
Positional replacement and insertion follow the same rule: they reject instead
|
|
1218
1267
|
of evicting when the resulting queue would exceed the limit.
|
|
1219
1268
|
|
|
1220
|
-
`queue.reserve({ leaseMs = 30000 })` returns `null` or
|
|
1269
|
+
`queue.reserve({ leaseMs = 30000, nackCoalescingIndex })` returns `null` or
|
|
1221
1270
|
`{ item, ack, nack, renew }`. Reservation token/deadline are internal record
|
|
1222
1271
|
metadata, persisted atomically in the same IndexedDB transaction as selection.
|
|
1223
1272
|
`renew()` extends a still-valid lease. Low-level callers own renewal and release;
|
|
1224
1273
|
PrivateMessenger supplies both. Do not mix reservations with destructive or
|
|
1225
1274
|
position-shifting queue operations on the same queue except explicit removal.
|
|
1226
1275
|
A stale token cannot acknowledge a newly reserved or replaced record.
|
|
1276
|
+
`nackCoalescingIndex` names a non-unique index: when another matching item is
|
|
1277
|
+
pending, NACK deletes the superseded active item instead of requeueing it.
|
|
1227
1278
|
|
|
1228
1279
|
`queue.getCapacity()` is part of the common API and returns
|
|
1229
1280
|
`{ usedBytes, maxBytes }`; capacity rejections also expose `requiredBytes` and
|
|
@@ -1353,6 +1404,8 @@ Both packers use `useBulkPacing: true` by default. Bulk EVENT publications are
|
|
|
1353
1404
|
serialized per relay, start at least one second apart, and use a relay-local
|
|
1354
1405
|
1..30 second exponential backoff when no retryAt is supplied. Relay advice
|
|
1355
1406
|
overrides the local backoff and relays remain independent.
|
|
1407
|
+
Packers may receive a shared `idempotencyKey` base and append `:<index>` to each
|
|
1408
|
+
reply. Missing-message recovery supplies a question-scoped base by default.
|
|
1356
1409
|
|
|
1357
1410
|
|
|
1358
1411
|
### Private subscription recovery (0.11.8)
|
package/idb-queue/index.js
CHANGED
|
@@ -295,6 +295,25 @@ export async function createQueue ({
|
|
|
295
295
|
return Number.isFinite(sessionMaxBytes)
|
|
296
296
|
}
|
|
297
297
|
|
|
298
|
+
function indexDefinition (indexName) {
|
|
299
|
+
return indexDefinitions.find(index => index.name === indexName) || null
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function itemIndexKey (definition, item) {
|
|
303
|
+
const readKey = path => path.split('.').reduce((part, key) => part?.[key], item)
|
|
304
|
+
return Array.isArray(definition.keyPath)
|
|
305
|
+
? definition.keyPath.map(readKey)
|
|
306
|
+
: readKey(definition.keyPath)
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function assertValidIndexKey (key, code = 'QUEUE_PUT_KEY_INVALID') {
|
|
310
|
+
try {
|
|
311
|
+
indexedDB.cmp(key, key)
|
|
312
|
+
} catch {
|
|
313
|
+
throw new ValidationError(code)
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
298
317
|
function evictionDirectionFor (operation, { index = 0, length = 0 } = {}) {
|
|
299
318
|
if (configuredEvictionPolicy === 'head') return 'head'
|
|
300
319
|
if (configuredEvictionPolicy === 'tail') return 'tail'
|
|
@@ -735,14 +754,13 @@ export async function createQueue ({
|
|
|
735
754
|
}
|
|
736
755
|
|
|
737
756
|
async function putBy (indexName, item, { existingOnly = false } = {}) {
|
|
738
|
-
const definition =
|
|
757
|
+
const definition = indexDefinition(indexName)
|
|
739
758
|
if (!definition?.unique || definition.multiEntry) throw new ValidationError('QUEUE_PUT_INDEX_INVALID')
|
|
740
759
|
// Snapshot before awaiting IndexedDB so the lookup key and stored value
|
|
741
760
|
// cannot diverge if the caller changes its object during the transaction.
|
|
742
761
|
const value = structuredClone(item)
|
|
743
|
-
const
|
|
744
|
-
|
|
745
|
-
try { indexedDB.cmp(key, key) } catch { throw new ValidationError('QUEUE_PUT_KEY_INVALID') }
|
|
762
|
+
const key = itemIndexKey(definition, value)
|
|
763
|
+
assertValidIndexKey(key)
|
|
746
764
|
const requiredBytes = itemForStorage(0, value).byteSize
|
|
747
765
|
const written = await mutate(async (tx, state) => {
|
|
748
766
|
const { result: previous } = await run('get', [key], ITEMS_STORE, indexName, { tx })
|
|
@@ -762,6 +780,76 @@ export async function createQueue ({
|
|
|
762
780
|
return written
|
|
763
781
|
}
|
|
764
782
|
|
|
783
|
+
async function coalesceBy (indexName, item, {
|
|
784
|
+
compare,
|
|
785
|
+
keep = 'latest',
|
|
786
|
+
now = Date.now()
|
|
787
|
+
} = {}) {
|
|
788
|
+
const definition = indexDefinition(indexName)
|
|
789
|
+
if (!definition || definition.unique || definition.multiEntry) {
|
|
790
|
+
throw new ValidationError('QUEUE_COALESCE_INDEX_INVALID')
|
|
791
|
+
}
|
|
792
|
+
if (compare != null && typeof compare !== 'function') {
|
|
793
|
+
throw new ValidationError('QUEUE_COALESCE_COMPARE_INVALID')
|
|
794
|
+
}
|
|
795
|
+
if (keep !== 'oldest' && keep !== 'latest') {
|
|
796
|
+
throw new ValidationError('QUEUE_COALESCE_KEEP_INVALID')
|
|
797
|
+
}
|
|
798
|
+
if (!Number.isSafeInteger(now) || now < 0) throw new ValidationError('QUEUE_COALESCE_NOW_INVALID')
|
|
799
|
+
const value = structuredClone(item)
|
|
800
|
+
const key = itemIndexKey(definition, value)
|
|
801
|
+
assertValidIndexKey(key, 'QUEUE_COALESCE_KEY_INVALID')
|
|
802
|
+
const requiredBytes = itemForStorage(0, value).byteSize
|
|
803
|
+
return mutate(async (tx, state) => {
|
|
804
|
+
const { result: records } = await run('getAll', [key], ITEMS_STORE, indexName, { tx })
|
|
805
|
+
const active = []
|
|
806
|
+
const pending = []
|
|
807
|
+
for (const record of records) {
|
|
808
|
+
if (record.reservation?.until > now) active.push(record)
|
|
809
|
+
else pending.push(record)
|
|
810
|
+
}
|
|
811
|
+
pending.sort((left, right) => left.position - right.position)
|
|
812
|
+
if (compare && records.length) {
|
|
813
|
+
const latest = records.reduce((current, candidate) => (
|
|
814
|
+
compare(candidate.item, current.item) > 0 ? candidate : current
|
|
815
|
+
))
|
|
816
|
+
if (compare(value, latest.item) <= 0) {
|
|
817
|
+
return { status: 'ignored', removed: 0, position: null }
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
if (keep === 'oldest' && pending.length) {
|
|
822
|
+
return { status: 'ignored', removed: 0, position: null }
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
if (!pending.length) {
|
|
826
|
+
await pushInTransaction(tx, state, value)
|
|
827
|
+
return {
|
|
828
|
+
status: active.length ? 'successor' : 'inserted',
|
|
829
|
+
removed: 0,
|
|
830
|
+
position: state.tail - 1
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
const target = pending[0]
|
|
835
|
+
let removed = 0
|
|
836
|
+
for (const record of pending.slice(1)) {
|
|
837
|
+
await deleteRecord(tx, record.position)
|
|
838
|
+
state.usedBytes = Math.max(0, state.usedBytes - (record.byteSize || 0))
|
|
839
|
+
removed++
|
|
840
|
+
}
|
|
841
|
+
await putItem(tx, state, target.position, value, {
|
|
842
|
+
direction: evictionDirectionFor('setAt', {
|
|
843
|
+
index: target.position - state.head,
|
|
844
|
+
length: state.tail - state.head
|
|
845
|
+
}),
|
|
846
|
+
protectedPositions: new Set([target.position])
|
|
847
|
+
})
|
|
848
|
+
await trimBounds(tx, state)
|
|
849
|
+
return { status: 'replaced', removed, position: target.position }
|
|
850
|
+
}, { requiredBytes, wakeWaiters: true })
|
|
851
|
+
}
|
|
852
|
+
|
|
765
853
|
async function getBy (indexName, query) {
|
|
766
854
|
// Explicit index operations avoid scanning queue values in JavaScript.
|
|
767
855
|
return snapshot(async tx => {
|
|
@@ -795,8 +883,17 @@ export async function createQueue ({
|
|
|
795
883
|
// Reservations are stored atomically with the item; another tab/process can
|
|
796
884
|
// reclaim an expired lease after a crash. Destructive/positional queue APIs
|
|
797
885
|
// must not be mixed with reservations on the same queue.
|
|
798
|
-
async function reserve ({
|
|
886
|
+
async function reserve ({
|
|
887
|
+
leaseMs = 30000,
|
|
888
|
+
now = Date.now(),
|
|
889
|
+
nackCoalescingIndex
|
|
890
|
+
} = {}) {
|
|
799
891
|
if (!Number.isSafeInteger(leaseMs) || leaseMs <= 0 || !Number.isSafeInteger(now) || now < 0) throw new ValidationError('QUEUE_INVALID_LEASE')
|
|
892
|
+
const nackDefinition = nackCoalescingIndex == null ? null : indexDefinition(nackCoalescingIndex)
|
|
893
|
+
if (nackCoalescingIndex != null &&
|
|
894
|
+
(!nackDefinition || nackDefinition.unique || nackDefinition.multiEntry)) {
|
|
895
|
+
throw new ValidationError('QUEUE_NACK_COALESCE_INDEX_INVALID')
|
|
896
|
+
}
|
|
800
897
|
const token = globalThis.crypto.randomUUID()
|
|
801
898
|
const reserved = await mutate(async tx => {
|
|
802
899
|
const p = deferred()
|
|
@@ -829,8 +926,31 @@ export async function createQueue ({
|
|
|
829
926
|
await trimBounds(tx, state)
|
|
830
927
|
} else {
|
|
831
928
|
if (action === 'renew') record.reservation.until = at + leaseMs
|
|
832
|
-
else
|
|
833
|
-
|
|
929
|
+
else {
|
|
930
|
+
let superseded = false
|
|
931
|
+
if (nackDefinition) {
|
|
932
|
+
try {
|
|
933
|
+
const key = itemIndexKey(nackDefinition, record.item)
|
|
934
|
+
indexedDB.cmp(key, key)
|
|
935
|
+
const { result: matches } = await run(
|
|
936
|
+
'getAll',
|
|
937
|
+
[key],
|
|
938
|
+
ITEMS_STORE,
|
|
939
|
+
nackCoalescingIndex,
|
|
940
|
+
{ tx }
|
|
941
|
+
)
|
|
942
|
+
superseded = matches.some(match => match.position > record.position)
|
|
943
|
+
} catch {}
|
|
944
|
+
}
|
|
945
|
+
if (superseded) {
|
|
946
|
+
await deleteRecord(tx, record.position)
|
|
947
|
+
state.usedBytes = Math.max(0, state.usedBytes - record.byteSize)
|
|
948
|
+
await trimBounds(tx, state)
|
|
949
|
+
} else {
|
|
950
|
+
delete record.reservation
|
|
951
|
+
await putRecord(tx, record)
|
|
952
|
+
}
|
|
953
|
+
}
|
|
834
954
|
}
|
|
835
955
|
return true
|
|
836
956
|
}, { wakeWaiters: action !== 'renew' })
|
|
@@ -937,6 +1057,7 @@ export async function createQueue ({
|
|
|
937
1057
|
some,
|
|
938
1058
|
clear,
|
|
939
1059
|
putBy,
|
|
1060
|
+
coalesceBy,
|
|
940
1061
|
getBy,
|
|
941
1062
|
someBy,
|
|
942
1063
|
removeBy,
|
package/package.json
CHANGED
|
@@ -65,7 +65,10 @@ export async function readHistory ({ filter, relays, receiverPubkey, signal, get
|
|
|
65
65
|
releasePage = await acquirePage?.(signal)
|
|
66
66
|
signal?.throwIfAborted()
|
|
67
67
|
page = await getEvents({ ...filter, ...interval }, [relay], {
|
|
68
|
-
signal,
|
|
68
|
+
signal,
|
|
69
|
+
timeout: TIMEOUT_MS,
|
|
70
|
+
timeoutAfterFirstEose: null,
|
|
71
|
+
rateLimitRetries: 0,
|
|
69
72
|
callback: item => {
|
|
70
73
|
if (item.type !== 'event') return
|
|
71
74
|
bytes += encoder.encode(JSON.stringify(item.event)).byteLength
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { ValidationError } from '../../error/index.js'
|
|
2
|
+
|
|
3
|
+
export const IDEMPOTENCY_TAG = 'D'
|
|
4
|
+
export const MAX_IDEMPOTENCY_KEY_BYTES = 256
|
|
5
|
+
|
|
6
|
+
const encoder = new TextEncoder()
|
|
7
|
+
const MAX_CHUNK_SUFFIX_BYTES = String(Number.MAX_SAFE_INTEGER).length + 1
|
|
8
|
+
const MAX_IDEMPOTENCY_KEY_BASE_BYTES = MAX_IDEMPOTENCY_KEY_BYTES - MAX_CHUNK_SUFFIX_BYTES
|
|
9
|
+
|
|
10
|
+
function keyBytes (value) {
|
|
11
|
+
return encoder.encode(value).byteLength
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function invalidKey () {
|
|
15
|
+
return new ValidationError('INVALID_IDEMPOTENCY_KEY')
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function normalizeIdempotencyKey (value) {
|
|
19
|
+
if (value === undefined) return ''
|
|
20
|
+
if (typeof value !== 'string' || !value || keyBytes(value) > MAX_IDEMPOTENCY_KEY_BYTES) {
|
|
21
|
+
throw invalidKey()
|
|
22
|
+
}
|
|
23
|
+
return value
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function normalizeIdempotencyKeyBase (value) {
|
|
27
|
+
if (value === undefined) return ''
|
|
28
|
+
if (typeof value !== 'string' || !value || keyBytes(value) > MAX_IDEMPOTENCY_KEY_BASE_BYTES) {
|
|
29
|
+
throw invalidKey()
|
|
30
|
+
}
|
|
31
|
+
return value
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function chunkIdempotencyKey (base, index) {
|
|
35
|
+
const normalizedBase = normalizeIdempotencyKeyBase(base)
|
|
36
|
+
if (!normalizedBase) return undefined
|
|
37
|
+
if (!Number.isSafeInteger(index) || index < 0) throw invalidKey()
|
|
38
|
+
return normalizeIdempotencyKey(`${normalizedBase}:${index}`)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function appendIdempotencyTag (tags, idempotencyKey) {
|
|
42
|
+
const key = normalizeIdempotencyKey(idempotencyKey)
|
|
43
|
+
if (!key) return tags
|
|
44
|
+
return [[IDEMPOTENCY_TAG, key], ...tags]
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function readIdempotencyKey (event) {
|
|
48
|
+
const tags = (Array.isArray(event?.tags) ? event.tags : [])
|
|
49
|
+
.filter(tag => Array.isArray(tag) && tag[0] === IDEMPOTENCY_TAG)
|
|
50
|
+
if (!tags.length) return { key: null, reason: 'missing' }
|
|
51
|
+
if (tags.length !== 1 || tags[0].length !== 2) return { key: null, reason: 'malformed' }
|
|
52
|
+
try {
|
|
53
|
+
return { key: normalizeIdempotencyKey(tags[0][1]), reason: '' }
|
|
54
|
+
} catch {
|
|
55
|
+
return { key: null, reason: 'malformed' }
|
|
56
|
+
}
|
|
57
|
+
}
|
package/private-message/index.js
CHANGED
|
@@ -5,6 +5,7 @@ import { generateKeypair, keypairFromSeckey } from '../key/index.js'
|
|
|
5
5
|
import * as privateChannel from '../private-channel/index.js'
|
|
6
6
|
import { normalizeRumor, deliveryInfo } from '../private-channel/helpers/rumor.js'
|
|
7
7
|
import { normalizePreparedPublications } from '../private-channel/helpers/prepared.js'
|
|
8
|
+
import { appendIdempotencyTag } from './helpers/idempotency.js'
|
|
8
9
|
|
|
9
10
|
export const ASK_KIND = 7329
|
|
10
11
|
export const REPLY_KIND = 7330
|
|
@@ -118,11 +119,11 @@ function addHeaderTag (tags, { code, error }) {
|
|
|
118
119
|
return out.concat([header])
|
|
119
120
|
}
|
|
120
121
|
|
|
121
|
-
function makeMessageRumor ({ kind, tags, message }) {
|
|
122
|
+
function makeMessageRumor ({ kind, tags, message, idempotencyKey }) {
|
|
122
123
|
const normalized = normalizeMessage(message)
|
|
123
124
|
return {
|
|
124
125
|
kind,
|
|
125
|
-
tags: addHeaderTag(tags, normalized),
|
|
126
|
+
tags: addHeaderTag(appendIdempotencyTag(tags, idempotencyKey), normalized),
|
|
126
127
|
content: normalized.content
|
|
127
128
|
}
|
|
128
129
|
}
|
|
@@ -717,6 +718,7 @@ export async function ask ({
|
|
|
717
718
|
payload,
|
|
718
719
|
error,
|
|
719
720
|
content,
|
|
721
|
+
idempotencyKey,
|
|
720
722
|
expirationSeconds,
|
|
721
723
|
useBulkPacing = false,
|
|
722
724
|
temporaryStorageArea,
|
|
@@ -737,7 +739,7 @@ export async function ask ({
|
|
|
737
739
|
const identity = await senderSigner?.getPublicKey?.()
|
|
738
740
|
const session = defaultSessions.get(identity)
|
|
739
741
|
if (!session) throw new Error('PRIVATE_MESSAGE_NOT_WATCHING')
|
|
740
|
-
return session.ask({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receiverPubkey, relays, relayToReceivers, recoveryRelays, message, code, payload, error, content, expirationSeconds, useBulkPacing, temporaryStorageArea, _getIykcProofs, deletionPubkey, deletionSeckey, autoDeletionCapability, _publish })
|
|
742
|
+
return session.ask({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receiverPubkey, relays, relayToReceivers, recoveryRelays, message, code, payload, error, content, idempotencyKey, expirationSeconds, useBulkPacing, temporaryStorageArea, _getIykcProofs, deletionPubkey, deletionSeckey, autoDeletionCapability, _publish })
|
|
741
743
|
}
|
|
742
744
|
|
|
743
745
|
const { event: question, wireEvent } = await makeOutgoingRumor({
|
|
@@ -745,7 +747,8 @@ export async function ask ({
|
|
|
745
747
|
rumor: makeMessageRumor({
|
|
746
748
|
kind: ASK_KIND,
|
|
747
749
|
tags: [['r', receiverPubkey]],
|
|
748
|
-
message: message || { code, payload, error, content }
|
|
750
|
+
message: message || { code, payload, error, content },
|
|
751
|
+
idempotencyKey
|
|
749
752
|
})
|
|
750
753
|
})
|
|
751
754
|
const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability })
|
|
@@ -769,6 +772,7 @@ export async function reply ({
|
|
|
769
772
|
payload,
|
|
770
773
|
error,
|
|
771
774
|
content,
|
|
775
|
+
idempotencyKey,
|
|
772
776
|
expirationSeconds,
|
|
773
777
|
useBulkPacing = false,
|
|
774
778
|
temporaryStorageArea,
|
|
@@ -787,7 +791,8 @@ export async function reply ({
|
|
|
787
791
|
rumor: makeMessageRumor({
|
|
788
792
|
kind: REPLY_KIND,
|
|
789
793
|
tags: [['q', question.id], ['r', receiverPubkey]],
|
|
790
|
-
message: message || { code, payload, error, content }
|
|
794
|
+
message: message || { code, payload, error, content },
|
|
795
|
+
idempotencyKey
|
|
791
796
|
})
|
|
792
797
|
})
|
|
793
798
|
const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability })
|
|
@@ -809,6 +814,7 @@ export async function tell ({
|
|
|
809
814
|
payload,
|
|
810
815
|
error,
|
|
811
816
|
content,
|
|
817
|
+
idempotencyKey,
|
|
812
818
|
expirationSeconds,
|
|
813
819
|
useBulkPacing = false,
|
|
814
820
|
temporaryStorageArea,
|
|
@@ -826,7 +832,8 @@ export async function tell ({
|
|
|
826
832
|
rumor: makeMessageRumor({
|
|
827
833
|
kind: TELL_KIND,
|
|
828
834
|
tags: [['r', receiverPubkey]],
|
|
829
|
-
message: message || { code, payload, error, content }
|
|
835
|
+
message: message || { code, payload, error, content },
|
|
836
|
+
idempotencyKey
|
|
830
837
|
})
|
|
831
838
|
})
|
|
832
839
|
const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability })
|
|
@@ -848,6 +855,7 @@ export async function yell ({
|
|
|
848
855
|
payload,
|
|
849
856
|
error,
|
|
850
857
|
content,
|
|
858
|
+
idempotencyKey,
|
|
851
859
|
expirationSeconds,
|
|
852
860
|
useBulkPacing = false,
|
|
853
861
|
temporaryStorageArea,
|
|
@@ -870,7 +878,8 @@ export async function yell ({
|
|
|
870
878
|
const rumor = makeMessageRumor({
|
|
871
879
|
kind: TELL_KIND,
|
|
872
880
|
tags: [],
|
|
873
|
-
message: message || { code, payload, error, content }
|
|
881
|
+
message: message || { code, payload, error, content },
|
|
882
|
+
idempotencyKey
|
|
874
883
|
})
|
|
875
884
|
if (createdAt !== undefined) rumor.created_at = createdAt
|
|
876
885
|
const { event, wireEvent } = await makeOutgoingRumor({
|
|
@@ -75,6 +75,8 @@ the existing compact-record JSONL packer's `index`, `isLast`, and `jsonl` fields
|
|
|
75
75
|
The inner reply's `q` references the request event. No new terminal availability
|
|
76
76
|
message is required and `isLast` never establishes file completeness. Late
|
|
77
77
|
responses from authorized seeders remain useful during an active download.
|
|
78
|
+
Each reply carries D as `<code>:<question-id>:<root>:<index>`; retries of one
|
|
79
|
+
chunk therefore share an identity without collapsing other chunks.
|
|
78
80
|
Seed replies run outside the DM dispatcher, with at most two reply workers and
|
|
79
81
|
sixteen queued requests; workers yield between records so control traffic can
|
|
80
82
|
continue. Requests discarded at the queue bound can be retried.
|
|
@@ -196,7 +196,10 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
|
|
|
196
196
|
}
|
|
197
197
|
},
|
|
198
198
|
channelPubkey: file.fileChannelPubkey, question, receiverPubkey: question.pubkey,
|
|
199
|
-
code: FILE_CHUNKS_REPLY_CODE,
|
|
199
|
+
code: FILE_CHUNKS_REPLY_CODE,
|
|
200
|
+
idempotencyKey: `${FILE_CHUNKS_REPLY_CODE}:${question.id}:${file.root}`,
|
|
201
|
+
eventsPerChunk: 1,
|
|
202
|
+
recordsFromInput: record => [record]
|
|
200
203
|
})
|
|
201
204
|
for (const index of indices) {
|
|
202
205
|
usable(file)
|
|
@@ -224,7 +227,21 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
|
|
|
224
227
|
if (file.fileChannelPubkey !== payload.fileChannelPubkey) throw new ValidationError('FILE_CHANNEL_MISMATCH')
|
|
225
228
|
if (!packer) {
|
|
226
229
|
const routes = await routing(file, question.pubkey)
|
|
227
|
-
packer = createEventReplyPacker({
|
|
230
|
+
packer = createEventReplyPacker({
|
|
231
|
+
messenger: {
|
|
232
|
+
reply: async options => {
|
|
233
|
+
usable(file)
|
|
234
|
+
return _messages.reply({ ...sendOptions(file, routes), ...options })
|
|
235
|
+
}
|
|
236
|
+
},
|
|
237
|
+
channelPubkey: file.fileChannelPubkey,
|
|
238
|
+
question,
|
|
239
|
+
receiverPubkey: question.pubkey,
|
|
240
|
+
code: FILE_CHUNKS_REPLY_CODE,
|
|
241
|
+
idempotencyKey: `${FILE_CHUNKS_REPLY_CODE}:${question.id}:${file.root}`,
|
|
242
|
+
eventsPerChunk: 1,
|
|
243
|
+
recordsFromInput: row => compactRecordsFromSeed(row, { receiverPubkey: question.pubkey })
|
|
244
|
+
})
|
|
228
245
|
}
|
|
229
246
|
await packer.update(seed)
|
|
230
247
|
await new Promise(resolve => setTimeout(resolve, 0))
|
|
@@ -66,7 +66,13 @@ export function publishWithEarlyFallback ({ event, receivers, first, mirrors, tr
|
|
|
66
66
|
const slot = Promise.withResolvers()
|
|
67
67
|
summaries.push(slot.promise)
|
|
68
68
|
let result
|
|
69
|
-
try {
|
|
69
|
+
try {
|
|
70
|
+
result = await sendEvent(event, relays, {
|
|
71
|
+
signal: transportSignal,
|
|
72
|
+
getRetryEvent,
|
|
73
|
+
rateLimitRetries: 0
|
|
74
|
+
})
|
|
75
|
+
} catch (reason) {
|
|
70
76
|
if (reason?.code === 'RETRY_EVENT_PREPARATION_FAILED') {
|
|
71
77
|
fail(reason)
|
|
72
78
|
return
|
|
@@ -159,7 +159,11 @@ export function createSendRelayRouting ({ peer, peers = [peer], relaysByPubkey,
|
|
|
159
159
|
for (const relay of relays) tried.add(normalized(relay))
|
|
160
160
|
// Every relay in this batch serves the same pending recipient subset.
|
|
161
161
|
// One ACK covers that subset, never unrelated members of the ciphertext.
|
|
162
|
-
result = await sendEvent(event, relays, {
|
|
162
|
+
result = await sendEvent(event, relays, {
|
|
163
|
+
signal: transportSignal,
|
|
164
|
+
getRetryEvent: context.getRetryEvent,
|
|
165
|
+
rateLimitRetries: 0
|
|
166
|
+
})
|
|
163
167
|
const settled = Promise.resolve(result.promise)
|
|
164
168
|
summaries.push(settled)
|
|
165
169
|
settled.then(report => rememberSuccess(report?.succeededRelays || [])).catch(() => {})
|