libp2r2p 0.12.5 → 0.12.7

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
@@ -578,6 +578,11 @@ records and storage failures report errors and pause with reason `storage`;
578
578
  after correcting the cause, call `resume('storage')`. Retention cleanup and
579
579
  explicit `clearQueue()`/`clearChannel()` remain destructive. The queue's budget
580
580
  bounds serialized storage, not the size of every intermediate decoded message.
581
+ Pressure summaries may include bounded counts by inner message code alongside
582
+ type and age. Repeated native `AbortError` cancellations collapse into a
583
+ `PRIVATE_MESSENGER_CANCELLED` diagnostic once per 30-second window; subsequent
584
+ reports include the suppressed count. Neither diagnostic includes payloads,
585
+ ciphertext, filters or channel identities.
581
586
 
582
587
  ### Forwarded authors and isolated consumers
583
588
 
@@ -1102,25 +1107,24 @@ Local authentication denials, invalid events and unknown errors qualify for
1102
1107
  neither policy. Predicates classify individual native errors; callers decide
1103
1108
  how to handle mixed per-relay outcomes and application-specific aggregates.
1104
1109
  `parseRelayRetryAdvice(reason, params, { now = Date.now() })`, exported by
1105
- `libp2r2p/relay`, returns `{ retryAt, retryAfterMs? }` or `null`. It only interprets
1110
+ `libp2r2p/relay`, returns `{ retryAt, retryAfterMs }` or `null`. It only interprets
1106
1111
  leading `rate-limited:` refusals. The optional string `params` is relative
1107
- milliseconds (e.g. "2500") or an absolute Unix timestamp in milliseconds
1108
- prefixed with `@` (e.g. "@1791738154332"). Values must be positive safe integers
1109
- in canonical decimal form, without signs, whitespace, fractions or leading zeros.
1110
- Relative values produce both `retryAfterMs` and `retryAt`; absolute values produce
1111
- only `retryAt` and retain an expired deadline without starting a new wait.
1112
- Future waits are capped at five minutes. Missing or invalid params are ignored
1113
- and do not instruct clients to retry immediately. Schedulers wait until
1112
+ milliseconds (e.g. "2500"). Values must be positive safe integers in canonical
1113
+ decimal form, without signs, whitespace, fractions, leading zeros or prefixes.
1114
+ Valid values produce both `retryAfterMs` and `retryAt`. Future waits are capped
1115
+ at five minutes. Missing or invalid params are ignored and do not instruct
1116
+ clients to retry immediately. Schedulers wait until
1114
1117
  max(local backoff deadline, retryAt), never sum the two or renew the deadline on
1115
1118
  online notifications.
1116
1119
 
1117
1120
  Rate limits apply only to the client message type that triggered the refusal:
1118
1121
  `EVENT`, `AUTH`, `REQ` and `COUNT` have independent connection cooldowns. Responses
1119
1122
  are correlated with pending operations; unknown IDs never create cooldowns.
1120
- CLOSE cleanup remains immediate. The launcher can replace valid relative params
1121
- with `@` timestamps before queueing bridge delivery because its consumers share
1122
- its clock. No legacy timing objects are interpreted. Params never supply provenance
1123
- or retry eligibility; native messages, causes and codes remain intact.
1123
+ CLOSE cleanup remains immediate. A launcher-owned bridge may store the absolute
1124
+ deadline internally, but it refreshes the standard relative `params` immediately
1125
+ before consumer delivery; the private `@` syntax never crosses the WebSocket wire.
1126
+ No legacy timing objects are interpreted. Params never supply provenance or retry
1127
+ eligibility; native messages, causes and codes remain intact.
1124
1128
 
1125
1129
  ## Binary encodings
1126
1130
 
@@ -1287,9 +1291,9 @@ Nym broadcasts intentionally remain a single carrier union.
1287
1291
 
1288
1292
  ### Relay backpressure and bounded synchronization (0.11.7)
1289
1293
 
1290
- Optional decimal `params` milliseconds or `@` Unix milliseconds on relay `CLOSED`
1291
- and rejected `OK` responses are preserved as normalized `retryAt` (and
1292
- `retryAfterMs` for relative params) on native relay errors. Only `rate-limited:`
1294
+ Optional decimal `params` milliseconds on relay `CLOSED` and rejected `OK`
1295
+ responses are preserved as normalized `retryAt` and `retryAfterMs` on native relay
1296
+ errors. Only `rate-limited:`
1293
1297
  responses apply this advice; invalid values are ignored
1294
1298
  and delays are capped at five minutes. New operations of the refused type wait
1295
1299
  within their existing deadlines; active subscriptions remain live and `CLOSE`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libp2r2p",
3
- "version": "0.12.5",
3
+ "version": "0.12.7",
4
4
  "description": "Peer-to-relay-to-peer",
5
5
  "keywords": [
6
6
  "p2r2p",
@@ -0,0 +1,61 @@
1
+ const DEFAULT_CANCELLATION_WINDOW_MS = 30_000
2
+ const MAX_CANCELLATION_KEYS = 32
3
+ const SAFE_TOKEN = /^[A-Za-z0-9][A-Za-z0-9:._-]{0,159}$/
4
+
5
+ function safeToken (value) {
6
+ return typeof value === 'string' && SAFE_TOKEN.test(value) ? value : undefined
7
+ }
8
+
9
+ function cancellationKey (error) {
10
+ return [
11
+ safeToken(error?.name) || 'AbortError',
12
+ Number.isSafeInteger(error?.code) ? String(error.code) : safeToken(error?.code) || '',
13
+ safeToken(error?.operation) || '',
14
+ safeToken(error?.phase) || ''
15
+ ].join(':')
16
+ }
17
+
18
+ // AbortError is the normal cancellation primitive used while pauses tear down
19
+ // subscriptions and recovery work. Keep the first occurrence visible, suppress
20
+ // repeats for a bounded window, then report how many were omitted.
21
+ export function createPrivateMessengerErrorReporter ({
22
+ report,
23
+ now = Date.now,
24
+ intervalMs = DEFAULT_CANCELLATION_WINDOW_MS,
25
+ status = () => ({ paused: false, pauseReasons: [] })
26
+ } = {}) {
27
+ if (typeof report !== 'function') throw new TypeError('report must be a function')
28
+ const reported = new Map()
29
+
30
+ return error => {
31
+ if (error?.name !== 'AbortError') return report(error)
32
+
33
+ const current = now()
34
+ const key = cancellationKey(error)
35
+ const previous = reported.get(key)
36
+ if (previous && current - previous.at < intervalMs) {
37
+ previous.suppressed++
38
+ return false
39
+ }
40
+
41
+ const runtime = status() || {}
42
+ const pauseReasons = Array.isArray(runtime.pauseReasons)
43
+ ? runtime.pauseReasons.filter(reason => safeToken(reason)).slice(0, 8)
44
+ : []
45
+ const diagnostic = Object.assign(new Error('PRIVATE_MESSENGER_CANCELLED'), {
46
+ name: 'AbortError',
47
+ code: 'PRIVATE_MESSENGER_CANCELLED',
48
+ operation: safeToken(error.operation) || 'private-messenger',
49
+ phase: safeToken(error.phase) || (runtime.paused === true ? 'paused' : 'operation'),
50
+ expectedCancellation: runtime.paused === true,
51
+ cause: error,
52
+ ...(pauseReasons.length ? { pauseReasons } : {}),
53
+ ...(previous?.suppressed ? { suppressedCount: previous.suppressed } : {})
54
+ })
55
+
56
+ reported.delete(key)
57
+ reported.set(key, { at: current, suppressed: 0 })
58
+ if (reported.size > MAX_CANCELLATION_KEYS) reported.delete(reported.keys().next().value)
59
+ return report(diagnostic)
60
+ }
61
+ }
@@ -51,6 +51,7 @@ import { createPauseRecovery, isRecoverableStorageFailure } from './helpers/paus
51
51
  import { backgroundSigner } from './helpers/background-signer.js'
52
52
  import { createPublicationRelayHealth } from './helpers/publication-relay-health.js'
53
53
  import { createSendRelayRouting, normalizeFallbackRelays, normalizeFallbackDelay, relayCircuitError } from './helpers/send-routing.js'
54
+ import { createPrivateMessengerErrorReporter } from './helpers/error-reporting.js'
54
55
  import { incompleteFetchError } from '../private-channel/helpers/fetch-error.js'
55
56
  import { recoveryRetryDelay, isPermanentRecoveryError } from './helpers/recovery-retry.js'
56
57
  import { assertMessagePublished, publicationFailureDiagnostic, sanitizePublicationError } from './helpers/publication.js'
@@ -367,7 +368,6 @@ export class PrivateMessenger {
367
368
  this._random = _random
368
369
  this.onMessageQueued = onMessageQueued
369
370
  this.onDebug = onDebug
370
- this.onError = onError
371
371
  this._privateMessage = _privateMessage.createPrivateMessageSession?.() ?? _privateMessage
372
372
  this._privateChannel = _privateChannel
373
373
  this._getRelaysByPubkey = _getRelaysByPubkey
@@ -404,6 +404,11 @@ export class PrivateMessenger {
404
404
  this.stopByChannel = new Map()
405
405
  this.desiredChannels = new Set()
406
406
  this.pauseReasons = new Set()
407
+ this.onError = createPrivateMessengerErrorReporter({
408
+ report: typeof onError === 'function' ? onError : () => {},
409
+ now: _now,
410
+ status: () => this.readStatus()
411
+ })
407
412
  this.deliveries = new Set()
408
413
  this.deliveryReads = new Set()
409
414
  this.deliveryWaiters = new Set()
@@ -427,6 +432,7 @@ export class PrivateMessenger {
427
432
  this.reloadGapTimers = new Map()
428
433
  this.liveInterruptions = new Map()
429
434
  this.liveRecoveryTimers = new Map()
435
+ this.subscriptionDebugKeys = new Set()
430
436
  this.watchRevisionByChannel = new Map()
431
437
  this.presenceTimers = new Map()
432
438
  this.presenceJobs = new Map()
@@ -765,6 +771,15 @@ export class PrivateMessenger {
765
771
  }
766
772
  }
767
773
 
774
+ debugOnce (key, action, detail = {}) {
775
+ if (this.subscriptionDebugKeys.has(key)) return
776
+ this.subscriptionDebugKeys.add(key)
777
+ if (this.subscriptionDebugKeys.size > 256) {
778
+ this.subscriptionDebugKeys.delete(this.subscriptionDebugKeys.values().next().value)
779
+ }
780
+ this.debug(action, detail)
781
+ }
782
+
768
783
  debugSend (method, channelPubkey, detail = {}) {
769
784
  const receiverPubkeys = uniq(detail.receiverPubkeys || (detail.receiverPubkey ? [detail.receiverPubkey] : []))
770
785
  this.debug('send', {
@@ -1373,7 +1388,7 @@ export class PrivateMessenger {
1373
1388
  return this
1374
1389
  }
1375
1390
 
1376
- async handleSubscriptionState (pubkey, { state, relay, since, until }) {
1391
+ async handleSubscriptionState (pubkey, { state, relay, since, until, error }) {
1377
1392
  if (this.closePromise || this.pauseReasons.size || !this.desiredChannels.has(pubkey)) return
1378
1393
  if (!this.offlineRecoverySecondsFor(pubkey)) return
1379
1394
  let interrupted = this.liveInterruptions.get(pubkey)
@@ -1389,6 +1404,12 @@ export class PrivateMessenger {
1389
1404
  }
1390
1405
  this.recordInterruption([pubkey], start)
1391
1406
  this.addOfflineRange(pubkey, Math.max(0, start - this.offlineSkewSeconds), nowSeconds())
1407
+ const diagnosticRelay = safeDiagnosticRelay(relay)
1408
+ this.debugOnce(`subscription-interrupted:${diagnosticRelay || ''}:${start}:${safeDiagnosticToken(error?.code) || ''}`, 'subscription-interrupted', {
1409
+ relay: diagnosticRelay,
1410
+ rangeStart: start,
1411
+ ...subscriptionErrorDiagnostic(error)
1412
+ })
1392
1413
  // This rejection prevents the session from reopening the shared relay.
1393
1414
  await this.flushStateWrites()
1394
1415
  } else if (state === 'ready' && interrupted?.has(relay)) {
@@ -1399,6 +1420,12 @@ export class PrivateMessenger {
1399
1420
  if (this.closePromise || this.pauseReasons.size || !this.desiredChannels.has(pubkey) || this.liveInterruptions.get(pubkey) !== interrupted) return
1400
1421
  interrupted.delete(relay)
1401
1422
  if (!interrupted.size) this.liveInterruptions.delete(pubkey)
1423
+ this.debugOnce(`subscription-recovered:${safeDiagnosticRelay(relay) || ''}:${start}`, 'subscription-recovered', {
1424
+ relay: safeDiagnosticRelay(relay),
1425
+ rangeStart: start,
1426
+ rangeEnd: until,
1427
+ remainingInterruptedRelays: interrupted.size
1428
+ })
1402
1429
  this.scheduleLiveRecovery(pubkey)
1403
1430
  }
1404
1431
  }
@@ -2351,6 +2378,7 @@ export class PrivateMessenger {
2351
2378
 
2352
2379
  async inboxCapacitySummary () {
2353
2380
  const buckets = new Map()
2381
+ const codeBuckets = new Map()
2354
2382
  const channels = new Set()
2355
2383
  const now = nowSeconds()
2356
2384
  let count = 0
@@ -2372,6 +2400,14 @@ export class PrivateMessenger {
2372
2400
  bucket.count++
2373
2401
  bucket.bytes += itemBytes
2374
2402
  buckets.set(key, bucket)
2403
+ const code = safeDiagnosticToken(messageCode(item))
2404
+ if (code) {
2405
+ const codeKey = `${type}:${code}`
2406
+ const codeBucket = codeBuckets.get(codeKey) || { type, code, count: 0, bytes: 0 }
2407
+ codeBucket.count++
2408
+ codeBucket.bytes += itemBytes
2409
+ codeBuckets.set(codeKey, codeBucket)
2410
+ }
2375
2411
  if (typeof item?.channelPubkey === 'string' && item.channelPubkey) channels.add(item.channelPubkey)
2376
2412
  count++
2377
2413
  bytes += itemBytes
@@ -2382,7 +2418,14 @@ export class PrivateMessenger {
2382
2418
  channelCount: channels.size,
2383
2419
  buckets: [...buckets.values()].sort((a, b) =>
2384
2420
  a.type.localeCompare(b.type) || a.ageBucket.localeCompare(b.ageBucket)
2385
- )
2421
+ ),
2422
+ ...(codeBuckets.size
2423
+ ? {
2424
+ codes: [...codeBuckets.values()]
2425
+ .sort((a, b) => a.type.localeCompare(b.type) || a.code.localeCompare(b.code))
2426
+ .slice(0, 32)
2427
+ }
2428
+ : {})
2386
2429
  }
2387
2430
  }
2388
2431
 
@@ -3392,7 +3435,16 @@ export class PrivateMessenger {
3392
3435
  remaining.push(range)
3393
3436
  continue
3394
3437
  }
3438
+ const recoveryStartedAt = this._now()
3395
3439
  const result = await this.finalizeRecoveryRange({ channelPubkey: pubkey, range, record })
3440
+ this.debug('recovery-range-complete', {
3441
+ rangeStart: range.start,
3442
+ rangeEnd: range.end,
3443
+ complete: result.complete === true,
3444
+ failureCount: result.failures.length,
3445
+ pendingRelayCount: [...record.relays.values()].filter(state => state.pending.length && !state.dead).length,
3446
+ elapsedMs: Math.max(0, Math.round(this._now() - recoveryStartedAt))
3447
+ })
3396
3448
  failures.push(...result.failures)
3397
3449
  if (result.complete) recoveredThrough = Math.max(recoveredThrough, range.end)
3398
3450
  else remaining.push(range)
@@ -3751,6 +3803,38 @@ function messageCode (message) {
3751
3803
  : null
3752
3804
  }
3753
3805
 
3806
+ function safeDiagnosticToken (value) {
3807
+ return typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9:._-]{0,159}$/.test(value)
3808
+ ? value
3809
+ : undefined
3810
+ }
3811
+
3812
+ function safeDiagnosticRelay (value) {
3813
+ if (typeof value !== 'string') return undefined
3814
+ try {
3815
+ const url = new URL(value)
3816
+ return ['ws:', 'wss:'].includes(url.protocol) ? `${url.protocol}//${url.host}` : undefined
3817
+ } catch {
3818
+ return undefined
3819
+ }
3820
+ }
3821
+
3822
+ function subscriptionErrorDiagnostic (error) {
3823
+ if (!error || typeof error !== 'object') return {}
3824
+ const buffer = error.buffer && typeof error.buffer === 'object' ? error.buffer : null
3825
+ return {
3826
+ errorCode: safeDiagnosticToken(error.code),
3827
+ operation: safeDiagnosticToken(error.operation),
3828
+ phase: safeDiagnosticToken(error.phase),
3829
+ recoverySince: Number.isSafeInteger(error.recoverySince) && error.recoverySince >= 0 ? error.recoverySince : undefined,
3830
+ bufferStage: safeDiagnosticToken(buffer?.stage),
3831
+ queuedEvents: Number.isSafeInteger(buffer?.queuedEvents) ? buffer.queuedEvents : undefined,
3832
+ queuedBytes: Number.isSafeInteger(buffer?.queuedBytes) ? buffer.queuedBytes : undefined,
3833
+ oldestQueuedMs: Number.isFinite(buffer?.oldestQueuedMs) ? buffer.oldestQueuedMs : undefined,
3834
+ maxBytes: Number.isSafeInteger(buffer?.limits?.bytes) ? buffer.limits.bytes : undefined
3835
+ }
3836
+ }
3837
+
3754
3838
  function debugMessageInfo (type, channelPubkey, message) {
3755
3839
  return {
3756
3840
  type,
@@ -152,9 +152,16 @@ at 70% of its effective byte limit and resumes only after acknowledgment lowers
152
152
  usage to 50%, leaving room for an in-flight history page without evicting pending
153
153
  messages. Entering pressure emits one sanitized
154
154
  `PRIVATE_MESSENGER_CAPACITY_PRESSURE` event with byte metrics and aggregate
155
- type/age buckets; it never exposes IDs, pubkeys, filters, ciphertext or payloads.
155
+ type/age buckets plus bounded counts by inner message code; it never exposes IDs,
156
+ pubkeys, filters, ciphertext or payloads.
156
157
  Physical `QUEUE_CAPACITY_EXCEEDED` behavior remains unchanged.
157
158
 
159
+ Native `AbortError` values represent pause/teardown cancellation. The messenger
160
+ reports the first occurrence in each 30-second window as
161
+ `PRIVATE_MESSENGER_CANCELLED`, retaining the native error as `cause`, and adds
162
+ `suppressedCount` when another report is emitted later. Non-cancellation errors
163
+ remain one-for-one callbacks.
164
+
158
165
  External recovery factories are owned by their caller and must be closed after
159
166
  the session. Work storage opened by the session is closed by the session.
160
167
  This is a DM profile; group membership/key derivation is not implemented.
@@ -282,7 +289,11 @@ Account shutdown fences late admissions and waits for both processors and cleanu
282
289
  `onDebug(record)` is disabled by default. Records carry fixed stage names, public
283
290
  event/peer identifiers and elapsed milliseconds for admission, local processing,
284
291
  channel preparation, publication acceptance and cleanup. Callback failures never
285
- change delivery. Connect only in development; never log events or crypto buffers.
292
+ change delivery. Connect only under an explicit diagnostic opt-in; consumers
293
+ must sanitize the callback and never log events or crypto buffers.
294
+ Operational diagnostics for subscription interruption/recovery and completed
295
+ recovery ranges contain only relay, code, category, byte, count and elapsed-time
296
+ fields; they never include message filters, payloads or channel identities.
286
297
  Custom outbox factories also receive this optional callback for storage timings.
287
298
  Recovery archive completion also reports `publicationId`, one aggregate
288
299
  `recovery-archive-result` per `putMany`, and sanitized row/unique/existing/
@@ -31,8 +31,8 @@ export function relayCloseError (event, category, cause) {
31
31
  return categorizeRelayError(error, category)
32
32
  }
33
33
 
34
- // Keep native diagnostics and attach only bounded timing advice. An absolute
35
- // deadline survives delayed delivery through a launcher-owned relay bridge.
34
+ // Keep native diagnostics and attach only bounded timing advice. The launcher
35
+ // bridge refreshes the standard relative value immediately before delivery.
36
36
  export function relayRejectionError (reason, params, fallback) {
37
37
  const error = categorizeRelayError(reason, 'relay', fallback)
38
38
  Object.assign(error, parseRelayRetryAdvice(error.message, params))
@@ -1,13 +1,11 @@
1
- // Nostr params use relative milliseconds or @Unix milliseconds. Advice never
2
- // supplies an error category, provenance or a routing/retry policy.
1
+ // Nostr params use relative milliseconds. Advice never supplies an error
2
+ // category, provenance or a routing/retry policy.
3
3
  export function parseRelayRetryAdvice (reason, params, { now = Date.now() } = {}) {
4
4
  if (typeof reason !== 'string' || !reason.startsWith('rate-limited:') ||
5
- typeof params !== 'string' || params.match(/^@?[1-9]\d*$/)?.[0] !== params || !Number.isFinite(now)) return null
5
+ typeof params !== 'string' || params.match(/^[1-9]\d*$/)?.[0] !== params || !Number.isFinite(now)) return null
6
6
 
7
- const absolute = params.startsWith('@')
8
- const value = Number(absolute ? params.slice(1) : params)
7
+ const value = Number(params)
9
8
  if (!Number.isSafeInteger(value)) return null
10
- if (absolute) return { retryAt: Math.min(value, now + 300000) }
11
9
  const retryAfterMs = Math.min(value, 300000)
12
10
  return { retryAfterMs, retryAt: now + retryAfterMs }
13
11
  }