libp2r2p 0.12.23 → 0.12.25

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
@@ -673,10 +673,13 @@ handleMessages().catch(err => console.warn('private messenger messages failed',
673
673
  ```
674
674
 
675
675
  For one-at-a-time consumption, `await messenger.nextMessage()` returns
676
- `{ message, ack, nack }` or `null` if no record is currently available. `ack()`
677
- removes the reserved record; `nack()` releases it for another attempt. Both
678
- return a boolean and are idempotent for the same reservation. An expired or
679
- superseded reservation returns `false` and cannot delete a later delivery.
676
+ `{ message, progress, checkpoint, ownershipSignal, ack, nack, capacityEgress }`
677
+ or `null` if no record is currently available. `ack()` removes the reserved
678
+ record; `nack()` releases it for another attempt. Both return a boolean and are
679
+ idempotent for the same reservation. `checkpoint(value)` stores resumable
680
+ progress atomically with lease renewal. `ownershipSignal` aborts if the lease is
681
+ taken over. A superseded reservation returns `false`, cannot delete a later
682
+ delivery and exposes the safe reason through `lastFailure`.
680
683
 
681
684
  Delivery leases last 30 seconds and renew every 10 seconds while held. Closing
682
685
  the messenger or returning the iterator releases its unacknowledged deliveries;
@@ -1366,12 +1369,18 @@ Positional replacement and insertion follow the same rule: they reject instead
1366
1369
  of evicting when the resulting queue would exceed the limit.
1367
1370
 
1368
1371
  `queue.reserve({ leaseMs = 30000, nackCoalescingIndex, priorityIndex, priorities })` returns `null` or
1369
- `{ item, ack, nack, renew }`. Reservation token/deadline are internal record
1370
- metadata, persisted atomically in the same IndexedDB transaction as selection.
1371
- `renew()` extends a still-valid lease. Low-level callers own renewal and release;
1372
- PrivateMessenger supplies both. Do not mix reservations with destructive or
1373
- position-shifting queue operations on the same queue except explicit removal.
1374
- A stale token cannot acknowledge a newly reserved or replaced record.
1372
+ `{ item, progress, ack, nack, renew, checkpoint, lastFailure }`. Reservation
1373
+ token/deadline and optional checkpoint progress are persisted atomically in the
1374
+ same IndexedDB transaction as selection. `renew()` extends ownership when the
1375
+ token still matches, even if a delayed timer runs just after `until`.
1376
+ `checkpoint(value)` atomically stores structured-clone progress, updates logical
1377
+ byte accounting and renews the lease. Progress survives NACK and a later
1378
+ reservation, but not replacement of the queued item. Low-level callers own
1379
+ renewal and release; PrivateMessenger supplies both. Do not mix reservations with
1380
+ destructive or position-shifting queue operations on the same queue except
1381
+ explicit removal. A stale token cannot acknowledge a newly reserved or replaced
1382
+ record; after a failed operation `lastFailure.code` distinguishes taken-over,
1383
+ missing and settled reservations.
1375
1384
  `nackCoalescingIndex` names a non-unique index: when another matching item is
1376
1385
  pending, NACK deletes the superseded active item instead of requeueing it.
1377
1386
  `priorityIndex` names a scalar, non-multiEntry index and `priorities` is the
@@ -1407,6 +1416,10 @@ event after every relay terminally rejected the original with
1407
1416
  `auth-required:`/`restricted:`/`invalid:`. The replacement and its retry share the original
1408
1417
  deadline; mixed failures and ambiguous timeouts never invoke it.
1409
1418
 
1419
+ `MESSAGE_NOT_PUBLISHED` promotes the latest `retryAt` or `retryAfterMs` found in
1420
+ failed reports and their causes to the top-level error. Session storage can
1421
+ therefore honor relay cooldowns without parsing diagnostic-only report details.
1422
+
1410
1423
  ## Private file channels (0.11)
1411
1424
 
1412
1425
  `libp2r2p/private-messenger/file` provides `createPrivateFileTransfer` for
@@ -17,6 +17,8 @@ items, keyPath "position"
17
17
  position integer ordering key between the queue head and tail
18
18
  byteSize logical serialized size used by the queue capacity limit
19
19
  item caller-provided queued value
20
+ progress optional structured-clone value checkpointed by a reservation
21
+ reservation optional temporary { token, until } ownership claim
20
22
 
21
23
  items indexes
22
24
  Declared by each createQueue() caller. A requested keyPath such as "status"
@@ -235,7 +237,7 @@ async function openQueueDatabase (indexedDB, prefix, indexDefinitions) {
235
237
  throw new Error('QUEUE_SCHEMA_UPGRADE_FAILED')
236
238
  }
237
239
 
238
- function itemForStorage (position, item) {
240
+ function itemForStorage (position, item, progress) {
239
241
  // IndexedDB does not expose portable per-record byte usage, so keep a stable
240
242
  // JSON byte estimate for the queue's logical capacity limit.
241
243
  // `position` is the ordering key; queued values remain caller payloads.
@@ -243,12 +245,21 @@ function itemForStorage (position, item) {
243
245
  let byteSize = 0
244
246
  let serialized = ''
245
247
  while (true) {
246
- serialized = JSON.stringify({ byteSize, item: storedItem })
248
+ serialized = JSON.stringify({
249
+ byteSize,
250
+ item: storedItem,
251
+ ...(progress === undefined ? {} : { progress })
252
+ })
247
253
  const nextByteSize = byteLength(serialized)
248
254
  if (nextByteSize === byteSize) break
249
255
  byteSize = nextByteSize
250
256
  }
251
- return { position, byteSize, item: storedItem }
257
+ return {
258
+ position,
259
+ byteSize,
260
+ item: storedItem,
261
+ ...(progress === undefined ? {} : { progress: structuredClone(progress) })
262
+ }
252
263
  }
253
264
 
254
265
  function assertIndex (index, length, { allowEnd = false } = {}) {
@@ -948,23 +959,67 @@ export async function createQueue ({
948
959
  let settled = false
949
960
  let completedAction
950
961
  let completedResult
962
+ let lastFailure = null
951
963
  let tail = Promise.resolve()
952
- const update = (action, at = Date.now(), { retryAfterMs = 0 } = {}) => {
953
- if (!Number.isSafeInteger(retryAfterMs) || retryAfterMs < 0 || retryAfterMs > 2147483647) {
964
+ const update = (action, {
965
+ now,
966
+ retryAfterMs = 0,
967
+ progress
968
+ } = {}) => {
969
+ const at = now === undefined ? Date.now() : now
970
+ if (!Number.isSafeInteger(at) || at < 0) {
971
+ return Promise.reject(new ValidationError('QUEUE_INVALID_TIME'))
972
+ }
973
+ if (action === 'nack' &&
974
+ (!Number.isSafeInteger(retryAfterMs) || retryAfterMs < 0 || retryAfterMs > 2147483647)) {
954
975
  return Promise.reject(new ValidationError('QUEUE_INVALID_RETRY_AFTER'))
955
976
  }
977
+ let checkpoint
978
+ if (action === 'checkpoint') {
979
+ if (progress === undefined) {
980
+ return Promise.reject(new ValidationError('QUEUE_CHECKPOINT_INVALID'))
981
+ }
982
+ try {
983
+ checkpoint = structuredClone(progress)
984
+ } catch {
985
+ return Promise.reject(new ValidationError('QUEUE_CHECKPOINT_INVALID'))
986
+ }
987
+ }
956
988
  const operation = tail.then(async () => {
957
- if (settled) return action === completedAction ? completedResult : false
989
+ if (settled) {
990
+ if (action === completedAction) return completedResult
991
+ lastFailure = { code: 'QUEUE_RESERVATION_SETTLED' }
992
+ return false
993
+ }
994
+ lastFailure = null
958
995
  const result = await mutate(async (tx, state) => {
959
996
  const record = await getRecord(tx, reserved.position)
960
- if (record?.reservation?.token !== token || record.reservation.until <= at) return false
997
+ if (!record) return { ok: false, code: 'QUEUE_RESERVATION_MISSING' }
998
+ if (record.reservation?.token !== token) {
999
+ return { ok: false, code: 'QUEUE_RESERVATION_TAKEN_OVER' }
1000
+ }
961
1001
  if (action === 'ack') {
962
1002
  await deleteRecord(tx, record.position)
963
1003
  state.usedBytes = Math.max(0, state.usedBytes - record.byteSize)
964
1004
  await trimBounds(tx, state)
1005
+ } else if (action === 'checkpoint') {
1006
+ const stored = itemForStorage(record.position, record.item, checkpoint)
1007
+ if (hasByteLimit() && state.usedBytes - record.byteSize + stored.byteSize > sessionMaxBytes) {
1008
+ throw capacityError(stored.byteSize, state.usedBytes, sessionMaxBytes)
1009
+ }
1010
+ const previousByteSize = record.byteSize
1011
+ record.progress = checkpoint
1012
+ record.byteSize = stored.byteSize
1013
+ record.reservation = { token, until: at + leaseMs }
1014
+ await putRecord(tx, record)
1015
+ state.usedBytes = Math.max(0, state.usedBytes - previousByteSize + stored.byteSize)
1016
+ reserved.byteSize = stored.byteSize
1017
+ reserved.progress = structuredClone(checkpoint)
965
1018
  } else {
966
- if (action === 'renew') record.reservation.until = at + leaseMs
967
- else {
1019
+ if (action === 'renew') {
1020
+ record.reservation.until = at + leaseMs
1021
+ await putRecord(tx, record)
1022
+ } else {
968
1023
  let superseded = false
969
1024
  if (nackDefinition) {
970
1025
  try {
@@ -991,23 +1046,37 @@ export async function createQueue ({
991
1046
  }
992
1047
  }
993
1048
  }
994
- return true
995
- }, { wakeWaiters: action !== 'renew' })
996
- if (action !== 'renew' || !result) {
1049
+ return { ok: true }
1050
+ }, { wakeWaiters: action !== 'renew' && action !== 'checkpoint' })
1051
+ if (!result.ok) {
1052
+ lastFailure = { code: result.code }
1053
+ settled = true
1054
+ completedAction = action
1055
+ completedResult = false
1056
+ return false
1057
+ }
1058
+ if (action !== 'renew' && action !== 'checkpoint') {
997
1059
  settled = true
998
1060
  completedAction = action
999
- completedResult = result
1061
+ completedResult = true
1000
1062
  }
1001
- return result
1063
+ return true
1002
1064
  })
1003
1065
  tail = operation.catch(() => {})
1004
1066
  return operation
1005
1067
  }
1006
1068
  return {
1007
1069
  item: reserved.item,
1008
- ack: () => update('ack'),
1009
- nack: options => update('nack', Date.now(), options),
1010
- renew: () => update('renew')
1070
+ get progress () {
1071
+ return reserved.progress === undefined ? undefined : structuredClone(reserved.progress)
1072
+ },
1073
+ get lastFailure () {
1074
+ return lastFailure == null ? null : { ...lastFailure }
1075
+ },
1076
+ ack: options => update('ack', options),
1077
+ nack: options => update('nack', options),
1078
+ renew: options => update('renew', options),
1079
+ checkpoint: (value, options = {}) => update('checkpoint', { ...options, progress: value })
1011
1080
  }
1012
1081
  }
1013
1082
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libp2r2p",
3
- "version": "0.12.23",
3
+ "version": "0.12.25",
4
4
  "description": "Peer-to-relay-to-peer",
5
5
  "keywords": [
6
6
  "p2r2p",
@@ -47,6 +47,28 @@ function sanitizedReport (report, index) {
47
47
  }
48
48
  }
49
49
 
50
+ function latestRetryAdvice (values, now) {
51
+ const pending = values.slice()
52
+ const seen = new Set()
53
+ let retryAt = 0
54
+ while (pending.length) {
55
+ const current = pending.pop()
56
+ if (!current || typeof current !== 'object' || seen.has(current)) continue
57
+ seen.add(current)
58
+ if (Array.isArray(current)) {
59
+ pending.push(...current)
60
+ continue
61
+ }
62
+ if (Number.isSafeInteger(current.retryAt)) retryAt = Math.max(retryAt, current.retryAt)
63
+ if (Number.isSafeInteger(current.retryAfterMs) && current.retryAfterMs >= 0) {
64
+ retryAt = Math.max(retryAt, now + current.retryAfterMs)
65
+ }
66
+ for (const key of ['cause', 'reason', 'error']) pending.push(current[key])
67
+ if (Array.isArray(current.errors)) pending.push(...current.errors)
68
+ }
69
+ return retryAt
70
+ }
71
+
50
72
  const contextFields = ['operation', 'channelPubkey', 'seederPubkey', 'receiverPubkey', 'eventId']
51
73
  const contextNumbers = ['eventKind', 'since', 'until']
52
74
 
@@ -103,11 +125,13 @@ export async function assertMessagePublished (result, event) {
103
125
  const present = Array.isArray(reports) && reports.length > 0
104
126
  if (present && reports.every(report => report?.success === true)) return
105
127
 
128
+ const retrySources = []
106
129
  const failures = present
107
130
  ? await Promise.all(reports.map(async (report, index) => {
108
131
  if (report?.success === true) return null
109
132
  let settled
110
133
  try { settled = await report?.promise } catch (reason) { settled = { errors: [{ reason }] } }
134
+ retrySources.push(report, settled)
111
135
  // Never retain the broadcast result: it includes plaintext and may carry
112
136
  // delivery.deletionSeckey. Native relay errors retain transport causes.
113
137
  return {
@@ -128,9 +152,12 @@ export async function assertMessagePublished (result, event) {
128
152
  })
129
153
  return `report ${report.index + 1} (${report.total ?? '?'} relays): ${errors.join('; ') || (report.total === 0 ? 'NO_RELAYS' : 'NO_RELAY_ACKNOWLEDGEMENT')}`
130
154
  })
155
+ const now = Date.now()
156
+ const retryAt = latestRetryAdvice(retrySources, now)
131
157
  throw Object.assign(new Error(`MESSAGE_NOT_PUBLISHED: ${details.join(' | ') || reason}`), {
132
158
  code: 'MESSAGE_NOT_PUBLISHED',
133
159
  ...(failures.length && failures.every(report => report.retryWhenAvailable) ? { retryWhenAvailable: true, ...(failures.some(report => report.retryWhenOnline) ? { retryWhenOnline: true } : {}) } : {}),
160
+ ...(retryAt > 0 ? { retryAt, retryAfterMs: Math.max(0, retryAt - now) } : {}),
134
161
  reason,
135
162
  eventId: getEventHash(event),
136
163
  eventKind: event.kind,
@@ -199,6 +199,14 @@ function expiredCapacityEgress () {
199
199
  })
200
200
  }
201
201
 
202
+ function ownershipLostError (reason) {
203
+ return Object.assign(new Error('INBOX_DELIVERY_LOST'), {
204
+ code: 'INBOX_DELIVERY_LOST',
205
+ queueFailure: reason || '',
206
+ retryWhenAvailable: true
207
+ })
208
+ }
209
+
202
210
  function isCapacityPressureError (error) {
203
211
  return error?.code === 'PRIVATE_MESSENGER_CAPACITY_PRESSURE'
204
212
  }
@@ -3015,16 +3023,16 @@ export class PrivateMessenger {
3015
3023
  const capacityEgress = this.createCapacityEgress()
3016
3024
  let finish
3017
3025
  const settled = new Promise(resolve => { finish = resolve })
3018
- const done = () => {
3026
+ const done = reason => {
3019
3027
  clearInterval(timer)
3020
- capacityEgress.release()
3028
+ capacityEgress.release(reason)
3021
3029
  this.deliveries.delete(delivery)
3022
3030
  finish()
3023
3031
  this.wakeDeliveries()
3024
3032
  }
3025
3033
  const settle = async (method, options) => {
3026
3034
  const result = await reservation[method](options)
3027
- done()
3035
+ done(result ? undefined : ownershipLostError(reservation.lastFailure?.code))
3028
3036
  if (method === 'ack' && result && !this.closePromise && this.pauseReasons.has('capacity')) {
3029
3037
  this.checkCapacity().catch(err => this.onError?.(err))
3030
3038
  }
@@ -3034,12 +3042,23 @@ export class PrivateMessenger {
3034
3042
  message: withoutQueueMetadata(reservation.item),
3035
3043
  ack: () => settle('ack'),
3036
3044
  nack: options => settle('nack', options),
3037
- capacityEgress: capacityEgress.messenger
3045
+ checkpoint: async progress => {
3046
+ const result = await reservation.checkpoint(progress)
3047
+ if (!result) done(ownershipLostError(reservation.lastFailure?.code))
3048
+ return result
3049
+ },
3050
+ capacityEgress: capacityEgress.messenger,
3051
+ ownershipSignal: capacityEgress.token.controller.signal,
3052
+ get progress () { return reservation.progress },
3053
+ get lastFailure () { return reservation.lastFailure }
3038
3054
  }
3039
3055
  Object.defineProperty(delivery, 'settled', { value: settled })
3040
3056
  this.deliveries.add(delivery)
3041
3057
  const timer = setInterval(() => {
3042
- reservation.renew().then(ok => { if (!ok) done() }, err => { done(); this.onError?.(err) })
3058
+ reservation.renew().then(
3059
+ ok => { if (!ok) done(ownershipLostError(reservation.lastFailure?.code)) },
3060
+ err => { done(err); this.onError?.(err) }
3061
+ )
3043
3062
  }, 10000)
3044
3063
  timer.unref?.()
3045
3064
  return delivery