libp2r2p 0.12.6 → 0.12.8

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
 
@@ -1101,16 +1106,17 @@ also admits relay policy refusals (`blocked:`, `restricted:`, `auth-required:`,
1101
1106
  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
- `parseRelayRetryAdvice(reason, params, { now = Date.now() })`, exported by
1109
+ `parseRelayRetryAdvice(reason, params, { now = Date.now(), capMs = 300000 })`, exported by
1105
1110
  `libp2r2p/relay`, returns `{ retryAt, retryAfterMs }` or `null`. It only interprets
1106
1111
  leading `rate-limited:` refusals. The optional string `params` is relative
1107
1112
  milliseconds (e.g. "2500"). Values must be positive safe integers in canonical
1108
1113
  decimal form, without signs, whitespace, fractions, leading zeros or prefixes.
1109
- Valid values produce both `retryAfterMs` and `retryAt`. Future waits are capped
1110
- at five minutes. Missing or invalid params are ignored and do not instruct
1111
- clients to retry immediately. Schedulers wait until
1112
- max(local backoff deadline, retryAt), never sum the two or renew the deadline on
1113
- online notifications.
1114
+ Valid values produce both `retryAfterMs` and `retryAt`, capped by `capMs`.
1115
+ Missing or invalid params are ignored and do not instruct clients to retry
1116
+ immediately. RelayPool defaults `rateLimitCapMs` to five minutes. Its
1117
+ `getOptions()` returns a frozen runtime snapshot and `setOptions(partial)`
1118
+ validates and applies allowlisted partial updates. Non-bulk schedulers retain
1119
+ their existing max(local backoff deadline, retryAt) behavior.
1114
1120
 
1115
1121
  Rate limits apply only to the client message type that triggered the refusal:
1116
1122
  `EVENT`, `AUTH`, `REQ` and `COUNT` have independent connection cooldowns. Responses
@@ -1290,7 +1296,8 @@ Optional decimal `params` milliseconds on relay `CLOSED` and rejected `OK`
1290
1296
  responses are preserved as normalized `retryAt` and `retryAfterMs` on native relay
1291
1297
  errors. Only `rate-limited:`
1292
1298
  responses apply this advice; invalid values are ignored
1293
- and delays are capped at five minutes. New operations of the refused type wait
1299
+ and delays are capped by the RelayPool runtime options, defaulting to five
1300
+ minutes. New operations of the refused type wait
1294
1301
  within their existing deadlines; active subscriptions remain live and `CLOSE`
1295
1302
  never waits. Cancelled or timed-out operations cannot be sent later. A rejection
1296
1303
  is still reported to the caller; this does not silently republish failed events.
@@ -1303,6 +1310,10 @@ publication failures retain the payload/index for retry. Outbound channel
1303
1310
  fragmentation streams from prepared encrypted rows, cleans partial writes and
1304
1311
  removes failed new keys from the temporary-storage registry. It does not raise
1305
1312
  the browser's Web Storage quota or delete unrelated application data.
1313
+ Both packers use `useBulkPacing: true` by default. Bulk EVENT publications are
1314
+ serialized per relay, start at least one second apart, and use a relay-local
1315
+ 1..30 second exponential backoff when no retryAt is supplied. Relay advice
1316
+ overrides the local backoff and relays remain independent.
1306
1317
 
1307
1318
 
1308
1319
  ### Private subscription recovery (0.11.8)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libp2r2p",
3
- "version": "0.12.6",
3
+ "version": "0.12.8",
4
4
  "description": "Peer-to-relay-to-peer",
5
5
  "keywords": [
6
6
  "p2r2p",
@@ -637,6 +637,7 @@ async function publishOuterEvents ({
637
637
  privateChannelSigner,
638
638
  expirationSeconds,
639
639
  onPreparedSeed,
640
+ useBulkPacing = false,
640
641
  _publish,
641
642
  includeCoverage = true,
642
643
  includeRoutingContext = true
@@ -664,9 +665,10 @@ async function publishOuterEvents ({
664
665
  ? {
665
666
  receiverPubkeys: receiverPubkeys(receivers),
666
667
  primaryRelays,
668
+ useBulkPacing,
667
669
  getRetryEvent
668
670
  }
669
- : { getRetryEvent })
671
+ : { useBulkPacing, getRetryEvent })
670
672
  results.push(includeCoverage ? withPublicationCoverage(report, current.events[index], receivers) : report)
671
673
  }
672
674
  return { publication: current, results }
@@ -685,7 +687,7 @@ function relayMapForReceivers (relayToReceivers, receivers) {
685
687
  return relays
686
688
  }
687
689
 
688
- export async function publish ({ senderSigner, imkcSigner, privateChannelSigner = senderSigner, privateChannelReaderPubkey, receivers, receiverTag, fileChunkIndex, onPreparedSeed, deletionPubkey, event, relays, relayToReceivers, recoveryRelays, expirationSeconds, temporaryStorageArea, _getIykcProofs = getIykcProofs, _publish = sendToRelays, preparedPublication, preparedPublications }) {
690
+ export async function publish ({ senderSigner, imkcSigner, privateChannelSigner = senderSigner, privateChannelReaderPubkey, receivers, receiverTag, fileChunkIndex, onPreparedSeed, useBulkPacing = false, deletionPubkey, event, relays, relayToReceivers, recoveryRelays, expirationSeconds, temporaryStorageArea, _getIykcProofs = getIykcProofs, _publish = sendToRelays, preparedPublication, preparedPublications }) {
689
691
  const normalizedDeletionPubkey = normalizeDeletionPubkey(deletionPubkey)
690
692
  const results = []
691
693
  const requestedReceivers = receiverPubkeys(receivers)
@@ -722,6 +724,7 @@ export async function publish ({ senderSigner, imkcSigner, privateChannelSigner
722
724
  privateChannelSigner,
723
725
  expirationSeconds,
724
726
  onPreparedSeed,
727
+ useBulkPacing,
725
728
  _publish
726
729
  })
727
730
  prepared[publicationIndex] = outcome.publication
@@ -773,6 +776,7 @@ export async function publish ({ senderSigner, imkcSigner, privateChannelSigner
773
776
  privateChannelSigner,
774
777
  expirationSeconds,
775
778
  onPreparedSeed,
779
+ useBulkPacing,
776
780
  _publish
777
781
  })
778
782
  results.push(...outcome.results)
@@ -811,13 +815,14 @@ export async function publish ({ senderSigner, imkcSigner, privateChannelSigner
811
815
  privateChannelSigner,
812
816
  expirationSeconds,
813
817
  onPreparedSeed,
818
+ useBulkPacing,
814
819
  _publish
815
820
  })
816
821
  results.push(...outcome.results)
817
822
  return results
818
823
  }
819
824
 
820
- export async function publishNymEvent ({ nymSigner, privateChannelSigner, privateChannelReaderPubkey, deletionPubkey, event, relays, relayToReceivers, recoveryRelays, expirationSeconds, _publish = sendToRelays }) {
825
+ export async function publishNymEvent ({ nymSigner, privateChannelSigner, privateChannelReaderPubkey, deletionPubkey, event, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing = false, _publish = sendToRelays }) {
821
826
  const normalizedDeletionPubkey = normalizeDeletionPubkey(deletionPubkey)
822
827
  const results = []
823
828
  const publishRelays = withRecoveryRelays(relayToReceivers ? relaysFromRelayReceivers(relayToReceivers) : relays, recoveryRelays)
@@ -834,6 +839,7 @@ export async function publishNymEvent ({ nymSigner, privateChannelSigner, privat
834
839
  receivers: [],
835
840
  privateChannelSigner,
836
841
  expirationSeconds,
842
+ useBulkPacing,
837
843
  includeCoverage: false,
838
844
  includeRoutingContext: false,
839
845
  _publish
@@ -678,10 +678,11 @@ async function sendPrivateMessage ({
678
678
  fileChunkIndex,
679
679
  onPreparedSeed,
680
680
  preparedPublications,
681
+ useBulkPacing = false,
681
682
  _publish = privateChannel.publish
682
683
  }) {
683
684
  if (!privateChannelSigner?.getPublicKey) throw new ValidationError('PRIVATE_CHANNEL_WRITER_REQUIRED')
684
- return _publish({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers, receiverTag, deletionPubkey, event, relays, relayToReceivers, recoveryRelays, expirationSeconds, temporaryStorageArea, fileChunkIndex, onPreparedSeed, preparedPublications: preparedPublications?.length ? preparedPublications : undefined, _getIykcProofs })
685
+ return _publish({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers, receiverTag, deletionPubkey, event, relays, relayToReceivers, recoveryRelays, expirationSeconds, temporaryStorageArea, fileChunkIndex, onPreparedSeed, preparedPublications: preparedPublications?.length ? preparedPublications : undefined, useBulkPacing, _getIykcProofs })
685
686
  }
686
687
 
687
688
  async function sendNymMessage ({
@@ -693,12 +694,13 @@ async function sendNymMessage ({
693
694
  relayToReceivers,
694
695
  recoveryRelays,
695
696
  expirationSeconds,
697
+ useBulkPacing = false,
696
698
  deletionPubkey,
697
699
  _publish = privateChannel.publishNymEvent
698
700
  }) {
699
701
  if (!nymSigner?.getPublicKey) throw new ValidationError('NYM_SIGNER_REQUIRED')
700
702
  if (!privateChannelSigner?.getPublicKey) throw new ValidationError('PRIVATE_CHANNEL_WRITER_REQUIRED')
701
- return _publish({ nymSigner, privateChannelSigner, privateChannelReaderPubkey, deletionPubkey, event, relays, relayToReceivers, recoveryRelays, expirationSeconds })
703
+ return _publish({ nymSigner, privateChannelSigner, privateChannelReaderPubkey, deletionPubkey, event, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing })
702
704
  }
703
705
 
704
706
  export async function ask ({
@@ -716,6 +718,7 @@ export async function ask ({
716
718
  error,
717
719
  content,
718
720
  expirationSeconds,
721
+ useBulkPacing = false,
719
722
  temporaryStorageArea,
720
723
  _getIykcProofs,
721
724
  deletionPubkey,
@@ -734,7 +737,7 @@ export async function ask ({
734
737
  const identity = await senderSigner?.getPublicKey?.()
735
738
  const session = defaultSessions.get(identity)
736
739
  if (!session) throw new Error('PRIVATE_MESSAGE_NOT_WATCHING')
737
- return session.ask({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receiverPubkey, relays, relayToReceivers, recoveryRelays, message, code, payload, error, content, expirationSeconds, temporaryStorageArea, _getIykcProofs, deletionPubkey, deletionSeckey, autoDeletionCapability, _publish })
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 })
738
741
  }
739
742
 
740
743
  const { event: question, wireEvent } = await makeOutgoingRumor({
@@ -746,7 +749,7 @@ export async function ask ({
746
749
  })
747
750
  })
748
751
  const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability })
749
- const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers: [receiverPubkey], receiverTag: receiverPubkey, deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, temporaryStorageArea, fileChunkIndex, onPreparedSeed, _getIykcProofs, _publish })
752
+ const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers: [receiverPubkey], receiverTag: receiverPubkey, deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, temporaryStorageArea, fileChunkIndex, onPreparedSeed, _getIykcProofs, _publish })
750
753
 
751
754
  return withDelivery({ question }, reports, deletion.deletionSeckey)
752
755
  }
@@ -767,6 +770,7 @@ export async function reply ({
767
770
  error,
768
771
  content,
769
772
  expirationSeconds,
773
+ useBulkPacing = false,
770
774
  temporaryStorageArea,
771
775
  _getIykcProofs,
772
776
  deletionPubkey,
@@ -787,7 +791,7 @@ export async function reply ({
787
791
  })
788
792
  })
789
793
  const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability })
790
- const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers: [receiverPubkey], receiverTag: receiverPubkey, deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, temporaryStorageArea, fileChunkIndex, onPreparedSeed, _getIykcProofs, _publish })
794
+ const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers: [receiverPubkey], receiverTag: receiverPubkey, deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, temporaryStorageArea, fileChunkIndex, onPreparedSeed, _getIykcProofs, _publish })
791
795
  return withDelivery({ reply: event }, reports, deletion.deletionSeckey)
792
796
  }
793
797
 
@@ -806,6 +810,7 @@ export async function tell ({
806
810
  error,
807
811
  content,
808
812
  expirationSeconds,
813
+ useBulkPacing = false,
809
814
  temporaryStorageArea,
810
815
  _getIykcProofs,
811
816
  deletionPubkey,
@@ -825,7 +830,7 @@ export async function tell ({
825
830
  })
826
831
  })
827
832
  const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability })
828
- const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers: [receiverPubkey], receiverTag: receiverPubkey, deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, temporaryStorageArea, fileChunkIndex, onPreparedSeed, _getIykcProofs, _publish })
833
+ const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers: [receiverPubkey], receiverTag: receiverPubkey, deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, temporaryStorageArea, fileChunkIndex, onPreparedSeed, _getIykcProofs, _publish })
829
834
  return withDelivery({ tell: event }, reports, deletion.deletionSeckey)
830
835
  }
831
836
 
@@ -844,6 +849,7 @@ export async function yell ({
844
849
  error,
845
850
  content,
846
851
  expirationSeconds,
852
+ useBulkPacing = false,
847
853
  temporaryStorageArea,
848
854
  _getIykcProofs,
849
855
  deletionPubkey,
@@ -872,7 +878,7 @@ export async function yell ({
872
878
  rumor
873
879
  })
874
880
  const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability, preparedPublications: prepared })
875
- const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers, receiverTag: '', deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, temporaryStorageArea, fileChunkIndex, onPreparedSeed: preparedSeedHandler(onPreparedSeed, deletion), preparedPublications: prepared, _getIykcProofs, _publish })
881
+ const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers, receiverTag: '', deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, temporaryStorageArea, fileChunkIndex, onPreparedSeed: preparedSeedHandler(onPreparedSeed, deletion), preparedPublications: prepared, _getIykcProofs, _publish })
876
882
  return withDelivery({ yell: event }, reports, deletion.deletionSeckey)
877
883
  }
878
884
 
@@ -887,6 +893,7 @@ export async function broadcastRumor ({
887
893
  recoveryRelays,
888
894
  rumor,
889
895
  expirationSeconds,
896
+ useBulkPacing = false,
890
897
  temporaryStorageArea,
891
898
  _getIykcProofs,
892
899
  deletionPubkey,
@@ -903,7 +910,7 @@ export async function broadcastRumor ({
903
910
  const prepared = normalizePreparedPublications({ preparedPublication, preparedPublications })
904
911
  const { event, wireEvent } = await makeOutgoingRumor({ senderSigner, rumor })
905
912
  const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability, preparedPublications: prepared })
906
- const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers, receiverTag: '', deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, temporaryStorageArea, fileChunkIndex, onPreparedSeed: preparedSeedHandler(onPreparedSeed, deletion), preparedPublications: prepared, _getIykcProofs, _publish })
913
+ const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers, receiverTag: '', deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, temporaryStorageArea, fileChunkIndex, onPreparedSeed: preparedSeedHandler(onPreparedSeed, deletion), preparedPublications: prepared, _getIykcProofs, _publish })
907
914
  return withDelivery({ rumor: event }, reports, deletion.deletionSeckey)
908
915
  }
909
916
 
@@ -918,6 +925,7 @@ export async function broadcastEvent ({
918
925
  recoveryRelays,
919
926
  event,
920
927
  expirationSeconds,
928
+ useBulkPacing = false,
921
929
  temporaryStorageArea,
922
930
  _getIykcProofs,
923
931
  deletionPubkey,
@@ -934,7 +942,7 @@ export async function broadcastEvent ({
934
942
  const prepared = normalizePreparedPublications({ preparedPublication, preparedPublications })
935
943
  const wireEvent = assertValidSignedEvent({ ...event, tags: cloneTags(event?.tags) })
936
944
  const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability, preparedPublications: prepared })
937
- const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers, receiverTag: '', deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, temporaryStorageArea, fileChunkIndex, onPreparedSeed: preparedSeedHandler(onPreparedSeed, deletion), preparedPublications: prepared, _getIykcProofs, _publish })
945
+ const reports = await sendPrivateMessage({ senderSigner, imkcSigner, privateChannelSigner, privateChannelReaderPubkey, receivers, receiverTag: '', deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, temporaryStorageArea, fileChunkIndex, onPreparedSeed: preparedSeedHandler(onPreparedSeed, deletion), preparedPublications: prepared, _getIykcProofs, _publish })
938
946
  return withDelivery({ event: wireEvent }, reports, deletion.deletionSeckey)
939
947
  }
940
948
 
@@ -947,6 +955,7 @@ export async function broadcastNymRumor ({
947
955
  recoveryRelays,
948
956
  rumor,
949
957
  expirationSeconds,
958
+ useBulkPacing = false,
950
959
  deletionPubkey,
951
960
  deletionSeckey,
952
961
  autoDeletionCapability = true,
@@ -957,7 +966,7 @@ export async function broadcastNymRumor ({
957
966
  if (rumor.pubkey !== undefined && rumor.pubkey !== await nymSigner.getPublicKey()) throw new ValidationError('NYM_RUMOR_AUTHOR_MISMATCH')
958
967
  const { event, wireEvent } = await makeOutgoingRumor({ senderSigner: nymSigner, rumor })
959
968
  const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability })
960
- const reports = await sendNymMessage({ nymSigner, privateChannelSigner, privateChannelReaderPubkey, deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, _publish })
969
+ const reports = await sendNymMessage({ nymSigner, privateChannelSigner, privateChannelReaderPubkey, deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, _publish })
961
970
  return withDelivery({ rumor: event }, reports, deletion.deletionSeckey)
962
971
  }
963
972
 
@@ -970,6 +979,7 @@ export async function broadcastNymEvent ({
970
979
  recoveryRelays,
971
980
  event,
972
981
  expirationSeconds,
982
+ useBulkPacing = false,
973
983
  deletionPubkey,
974
984
  deletionSeckey,
975
985
  autoDeletionCapability = true,
@@ -978,6 +988,6 @@ export async function broadcastNymEvent ({
978
988
  if (!nymSigner?.getPublicKey) throw new ValidationError('NYM_SIGNER_REQUIRED')
979
989
  const wireEvent = assertValidSignedEvent({ ...event, tags: cloneTags(event?.tags) })
980
990
  const deletion = resolveDeletionCapability({ deletionPubkey, deletionSeckey, autoDeletionCapability })
981
- const reports = await sendNymMessage({ nymSigner, privateChannelSigner, privateChannelReaderPubkey, deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, _publish })
991
+ const reports = await sendNymMessage({ nymSigner, privateChannelSigner, privateChannelReaderPubkey, deletionPubkey: deletion.deletionPubkey, event: wireEvent, relays, relayToReceivers, recoveryRelays, expirationSeconds, useBulkPacing, _publish })
982
992
  return withDelivery({ event: wireEvent }, reports, deletion.deletionSeckey)
983
993
  }
@@ -150,7 +150,7 @@ export function createPrivateFileTransfer ({ messenger, resolveChannel, storage,
150
150
  return messenger.resolveSendRouting({ channel: parent, receiverPubkeys: [receiverPubkey], signal, attemptStartedAt, onDebug })
151
151
  }
152
152
  function sendOptions (file, routes) {
153
- return { senderSigner: messenger.userSigner, imkcSigner: messenger.contentKeySigner, privateChannelSigner: file.signer, ...routes, temporaryStorageArea: messenger.temporaryStorageArea, expirationSeconds: messenger.eventExpirationSecondsFor(file.controlChannelPubkey), _getIykcProofs: messenger.contentKeyLookup() }
153
+ return { senderSigner: messenger.userSigner, imkcSigner: messenger.contentKeySigner, privateChannelSigner: file.signer, ...routes, temporaryStorageArea: messenger.temporaryStorageArea, expirationSeconds: messenger.eventExpirationSecondsFor(file.controlChannelPubkey), useBulkPacing: true, _getIykcProofs: messenger.contentKeyLookup() }
154
154
  }
155
155
  async function publishChunk (descriptor, event, { signal, attemptStartedAt, onPreparedSeed, preparedPublication, preparedPublications, onDebug } = {}) {
156
156
  const file = await register(descriptor)
@@ -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
 
@@ -2491,7 +2534,7 @@ export class PrivateMessenger {
2491
2534
  return delivery
2492
2535
  }
2493
2536
 
2494
- async ask ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkey, relays, relayToReceivers, message, code, payload, error, content, deletionPubkey }) {
2537
+ async ask ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkey, relays, relayToReceivers, message, code, payload, error, content, deletionPubkey, useBulkPacing = false }) {
2495
2538
  const channel = this.requireWritableChannel(channelPubkey)
2496
2539
  const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
2497
2540
  try {
@@ -2513,13 +2556,14 @@ export class PrivateMessenger {
2513
2556
  payload,
2514
2557
  error,
2515
2558
  content,
2559
+ useBulkPacing,
2516
2560
  onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
2517
2561
  _getIykcProofs: this.contentKeyLookup()
2518
2562
  })
2519
2563
  } finally { releaseActivity() }
2520
2564
  }
2521
2565
 
2522
- async reply ({ channelPubkey = this.defaultChannelPubkey(), question, receiverPubkey, relays, relayToReceivers, message, code, payload, error, content, deletionPubkey }) {
2566
+ async reply ({ channelPubkey = this.defaultChannelPubkey(), question, receiverPubkey, relays, relayToReceivers, message, code, payload, error, content, deletionPubkey, useBulkPacing = false }) {
2523
2567
  const channel = this.requireWritableChannel(channelPubkey)
2524
2568
  const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
2525
2569
  try {
@@ -2543,13 +2587,14 @@ export class PrivateMessenger {
2543
2587
  payload,
2544
2588
  error,
2545
2589
  content,
2590
+ useBulkPacing,
2546
2591
  onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
2547
2592
  _getIykcProofs: this.contentKeyLookup()
2548
2593
  })
2549
2594
  } finally { releaseActivity() }
2550
2595
  }
2551
2596
 
2552
- async tell ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkey, relays, relayToReceivers, message, code, payload, error, content, deletionPubkey }) {
2597
+ async tell ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkey, relays, relayToReceivers, message, code, payload, error, content, deletionPubkey, useBulkPacing = false }) {
2553
2598
  const channel = this.requireWritableChannel(channelPubkey)
2554
2599
  const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
2555
2600
  try {
@@ -2571,13 +2616,14 @@ export class PrivateMessenger {
2571
2616
  payload,
2572
2617
  error,
2573
2618
  content,
2619
+ useBulkPacing,
2574
2620
  onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
2575
2621
  _getIykcProofs: this.contentKeyLookup()
2576
2622
  })
2577
2623
  } finally { releaseActivity() }
2578
2624
  }
2579
2625
 
2580
- async yell ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, message, code, payload, error, content, deletionPubkey, createdAt, onPreparedSeed, preparedPublication, preparedPublications }) {
2626
+ async yell ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, message, code, payload, error, content, deletionPubkey, createdAt, onPreparedSeed, preparedPublication, preparedPublications, useBulkPacing = false }) {
2581
2627
  const channel = this.requireWritableChannel(channelPubkey)
2582
2628
  const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
2583
2629
  try {
@@ -2604,6 +2650,7 @@ export class PrivateMessenger {
2604
2650
  error,
2605
2651
  content,
2606
2652
  createdAt,
2653
+ useBulkPacing,
2607
2654
  onPreparedSeed: onPreparedSeed || this.outgoingSeedHandler(channelPubkey),
2608
2655
  preparedPublications: prepared.length ? prepared : undefined,
2609
2656
  _getIykcProofs: this.contentKeyLookup()
@@ -2611,7 +2658,7 @@ export class PrivateMessenger {
2611
2658
  } finally { releaseActivity() }
2612
2659
  }
2613
2660
 
2614
- async broadcastRumor ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, rumor, deletionPubkey, signal, attemptStartedAt, onPreparedSeed, preparedPublication, preparedPublications, onDebug }) {
2661
+ async broadcastRumor ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, rumor, deletionPubkey, signal, attemptStartedAt, onPreparedSeed, preparedPublication, preparedPublications, onDebug, useBulkPacing = false }) {
2615
2662
  const channel = this.requireWritableChannel(channelPubkey)
2616
2663
  const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
2617
2664
  try {
@@ -2633,6 +2680,7 @@ export class PrivateMessenger {
2633
2680
  deletionPubkey,
2634
2681
  autoDeletionCapability: this.autoDeletionCapabilityFor(channel),
2635
2682
  rumor,
2683
+ useBulkPacing,
2636
2684
  onPreparedSeed: onPreparedSeed || this.outgoingSeedHandler(channelPubkey),
2637
2685
  preparedPublications: prepared.length ? prepared : undefined,
2638
2686
  _getIykcProofs: this.contentKeyLookup()
@@ -2640,7 +2688,7 @@ export class PrivateMessenger {
2640
2688
  } finally { releaseActivity() }
2641
2689
  }
2642
2690
 
2643
- async broadcastEvent ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, event, deletionPubkey, signal, attemptStartedAt, onPreparedSeed, preparedPublication, preparedPublications, onDebug }) {
2691
+ async broadcastEvent ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, event, deletionPubkey, signal, attemptStartedAt, onPreparedSeed, preparedPublication, preparedPublications, onDebug, useBulkPacing = false }) {
2644
2692
  const channel = this.requireWritableChannel(channelPubkey)
2645
2693
  const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
2646
2694
  try {
@@ -2662,6 +2710,7 @@ export class PrivateMessenger {
2662
2710
  deletionPubkey,
2663
2711
  autoDeletionCapability: this.autoDeletionCapabilityFor(channel),
2664
2712
  event,
2713
+ useBulkPacing,
2665
2714
  onPreparedSeed: onPreparedSeed || this.outgoingSeedHandler(channelPubkey),
2666
2715
  preparedPublications: prepared.length ? prepared : undefined,
2667
2716
  _getIykcProofs: this.contentKeyLookup()
@@ -2669,7 +2718,7 @@ export class PrivateMessenger {
2669
2718
  } finally { releaseActivity() }
2670
2719
  }
2671
2720
 
2672
- async broadcastNymRumor ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, rumor, nymSigner, deletionPubkey }) {
2721
+ async broadcastNymRumor ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, rumor, nymSigner, deletionPubkey, useBulkPacing = false }) {
2673
2722
  const channel = this.requireWritableChannel(channelPubkey)
2674
2723
  const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
2675
2724
  try {
@@ -2684,12 +2733,13 @@ export class PrivateMessenger {
2684
2733
  expirationSeconds: this.eventExpirationSecondsFor(channel),
2685
2734
  deletionPubkey,
2686
2735
  autoDeletionCapability: this.autoDeletionCapabilityFor(channel),
2687
- rumor
2736
+ rumor,
2737
+ useBulkPacing
2688
2738
  })
2689
2739
  } finally { releaseActivity() }
2690
2740
  }
2691
2741
 
2692
- async broadcastNymEvent ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, event, nymSigner, deletionPubkey }) {
2742
+ async broadcastNymEvent ({ channelPubkey = this.defaultChannelPubkey(), receiverPubkeys, relays, relayToReceivers, event, nymSigner, deletionPubkey, useBulkPacing = false }) {
2693
2743
  const channel = this.requireWritableChannel(channelPubkey)
2694
2744
  const releaseActivity = this.decryptionScheduler.activity(channelPubkey)
2695
2745
  try {
@@ -2704,7 +2754,8 @@ export class PrivateMessenger {
2704
2754
  expirationSeconds: this.eventExpirationSecondsFor(channel),
2705
2755
  deletionPubkey,
2706
2756
  autoDeletionCapability: this.autoDeletionCapabilityFor(channel),
2707
- event
2757
+ event,
2758
+ useBulkPacing
2708
2759
  })
2709
2760
  } finally { releaseActivity() }
2710
2761
  }
@@ -2727,6 +2778,7 @@ export class PrivateMessenger {
2727
2778
  autoDeletionCapability: this.autoDeletionCapabilityFor(channel),
2728
2779
  code: SEEDER_PRESENCE_CODE,
2729
2780
  payload: {},
2781
+ useBulkPacing: true,
2730
2782
  onPreparedSeed: this.outgoingSeedHandler(channelPubkey),
2731
2783
  _getIykcProofs: this.contentKeyLookup()
2732
2784
  })
@@ -2966,7 +3018,8 @@ export class PrivateMessenger {
2966
3018
  channelPubkey,
2967
3019
  receiverPubkey: seeder,
2968
3020
  code: MISSING_MESSAGES_ASK_CODE,
2969
- payload: { since, until }
3021
+ payload: { since, until },
3022
+ useBulkPacing: true
2970
3023
  })
2971
3024
  asks.push(ask)
2972
3025
  await assertMessagePublished(ask, ask.question)
@@ -3392,7 +3445,16 @@ export class PrivateMessenger {
3392
3445
  remaining.push(range)
3393
3446
  continue
3394
3447
  }
3448
+ const recoveryStartedAt = this._now()
3395
3449
  const result = await this.finalizeRecoveryRange({ channelPubkey: pubkey, range, record })
3450
+ this.debug('recovery-range-complete', {
3451
+ rangeStart: range.start,
3452
+ rangeEnd: range.end,
3453
+ complete: result.complete === true,
3454
+ failureCount: result.failures.length,
3455
+ pendingRelayCount: [...record.relays.values()].filter(state => state.pending.length && !state.dead).length,
3456
+ elapsedMs: Math.max(0, Math.round(this._now() - recoveryStartedAt))
3457
+ })
3396
3458
  failures.push(...result.failures)
3397
3459
  if (result.complete) recoveredThrough = Math.max(recoveredThrough, range.end)
3398
3460
  else remaining.push(range)
@@ -3751,6 +3813,38 @@ function messageCode (message) {
3751
3813
  : null
3752
3814
  }
3753
3815
 
3816
+ function safeDiagnosticToken (value) {
3817
+ return typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9:._-]{0,159}$/.test(value)
3818
+ ? value
3819
+ : undefined
3820
+ }
3821
+
3822
+ function safeDiagnosticRelay (value) {
3823
+ if (typeof value !== 'string') return undefined
3824
+ try {
3825
+ const url = new URL(value)
3826
+ return ['ws:', 'wss:'].includes(url.protocol) ? `${url.protocol}//${url.host}` : undefined
3827
+ } catch {
3828
+ return undefined
3829
+ }
3830
+ }
3831
+
3832
+ function subscriptionErrorDiagnostic (error) {
3833
+ if (!error || typeof error !== 'object') return {}
3834
+ const buffer = error.buffer && typeof error.buffer === 'object' ? error.buffer : null
3835
+ return {
3836
+ errorCode: safeDiagnosticToken(error.code),
3837
+ operation: safeDiagnosticToken(error.operation),
3838
+ phase: safeDiagnosticToken(error.phase),
3839
+ recoverySince: Number.isSafeInteger(error.recoverySince) && error.recoverySince >= 0 ? error.recoverySince : undefined,
3840
+ bufferStage: safeDiagnosticToken(buffer?.stage),
3841
+ queuedEvents: Number.isSafeInteger(buffer?.queuedEvents) ? buffer.queuedEvents : undefined,
3842
+ queuedBytes: Number.isSafeInteger(buffer?.queuedBytes) ? buffer.queuedBytes : undefined,
3843
+ oldestQueuedMs: Number.isFinite(buffer?.oldestQueuedMs) ? buffer.oldestQueuedMs : undefined,
3844
+ maxBytes: Number.isSafeInteger(buffer?.limits?.bytes) ? buffer.limits.bytes : undefined
3845
+ }
3846
+ }
3847
+
3754
3848
  function debugMessageInfo (type, channelPubkey, message) {
3755
3849
  return {
3756
3850
  type,
@@ -227,7 +227,8 @@ export function createEventReplyPacker ({
227
227
  eventsPerChunk = DEFAULT_EVENTS_PER_CHUNK,
228
228
  bytesPerChunk = DEFAULT_REPLY_BYTES_PER_CHUNK,
229
229
  recordsFromInput = eventRecordFromInput,
230
- sendEmptyReply = false
230
+ sendEmptyReply = false,
231
+ useBulkPacing = true
231
232
  }) {
232
233
  if (!messenger?.reply) throw new ValidationError('MESSENGER_REQUIRED')
233
234
  if (!question?.id) throw new ValidationError('QUESTION_REQUIRED')
@@ -249,6 +250,7 @@ export function createEventReplyPacker ({
249
250
  question,
250
251
  receiverPubkey,
251
252
  code,
253
+ useBulkPacing,
252
254
  payload: {
253
255
  ...payload,
254
256
  index,
@@ -308,7 +310,8 @@ export function createMissingMessageReplyPacker ({
308
310
  until,
309
311
  eventsPerChunk = DEFAULT_EVENTS_PER_CHUNK,
310
312
  bytesPerChunk = DEFAULT_REPLY_BYTES_PER_CHUNK,
311
- sendEmptyReply = false
313
+ sendEmptyReply = false,
314
+ useBulkPacing = true
312
315
  }) {
313
316
  if (!messenger?.reply) throw new ValidationError('MESSENGER_REQUIRED')
314
317
  if (!question?.id) throw new ValidationError('QUESTION_REQUIRED')
@@ -327,6 +330,7 @@ export function createMissingMessageReplyPacker ({
327
330
  eventsPerChunk,
328
331
  bytesPerChunk,
329
332
  sendEmptyReply,
333
+ useBulkPacing,
330
334
  recordsFromInput: seed => compactRecordsFromSeed(seed, { receiverPubkey, since: range.since, until: range.until })
331
335
  })
332
336
  }
@@ -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,8 +289,17 @@ 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.
298
+ Private-message methods accept runtime-only `useBulkPacing`. Recovery packers,
299
+ seeder asks, presence and file chunks enable it by default; interactive chat
300
+ omits it. The relay pool serializes bulk event sends per relay, spaces starts by
301
+ at least one second, resets backoff after success and lets relay retryAt override
302
+ the local exponential deadline.
287
303
  Recovery archive completion also reports `publicationId`, one aggregate
288
304
  `recovery-archive-result` per `putMany`, and sanitized row/unique/existing/
289
305
  inserted/blocked/expired/stored/skipped counts. A single-row batch may include
@@ -1,4 +1,4 @@
1
- import { parseRelayRetryAdvice } from './retry-advice.js'
1
+ import { DEFAULT_RATE_LIMIT_CAP_MS, parseRelayRetryAdvice } from './retry-advice.js'
2
2
 
3
3
  // Adds transport context without replacing native messages, codes or causes.
4
4
  export function categorizeRelayError (reason, category, fallback = 'RELAY_OPERATION_FAILED') {
@@ -33,8 +33,8 @@ export function relayCloseError (event, category, cause) {
33
33
 
34
34
  // Keep native diagnostics and attach only bounded timing advice. The launcher
35
35
  // bridge refreshes the standard relative value immediately before delivery.
36
- export function relayRejectionError (reason, params, fallback) {
36
+ export function relayRejectionError (reason, params, fallback, { rateLimitCapMs = DEFAULT_RATE_LIMIT_CAP_MS } = {}) {
37
37
  const error = categorizeRelayError(reason, 'relay', fallback)
38
- Object.assign(error, parseRelayRetryAdvice(error.message, params))
38
+ Object.assign(error, parseRelayRetryAdvice(error.message, params, { capMs: rateLimitCapMs }))
39
39
  return error
40
40
  }
@@ -1,11 +1,16 @@
1
+ export const DEFAULT_RATE_LIMIT_CAP_MS = 300_000
2
+
1
3
  // Nostr params use relative milliseconds. Advice never supplies an error
2
4
  // category, provenance or a routing/retry policy.
3
- export function parseRelayRetryAdvice (reason, params, { now = Date.now() } = {}) {
5
+ export function parseRelayRetryAdvice (reason, params, { now = Date.now(), capMs = DEFAULT_RATE_LIMIT_CAP_MS } = {}) {
4
6
  if (typeof reason !== 'string' || !reason.startsWith('rate-limited:') ||
5
- typeof params !== 'string' || params.match(/^[1-9]\d*$/)?.[0] !== params || !Number.isFinite(now)) return null
7
+ typeof params !== 'string' || params.match(/^[1-9]\d*$/)?.[0] !== params || !Number.isFinite(now) ||
8
+ !Number.isSafeInteger(capMs) || capMs < 1) return null
6
9
 
7
10
  const value = Number(params)
8
11
  if (!Number.isSafeInteger(value)) return null
9
- const retryAfterMs = Math.min(value, 300000)
12
+ const maxRetryAfterMs = Math.min(capMs, Number.MAX_SAFE_INTEGER - now)
13
+ if (maxRetryAfterMs < 1) return null
14
+ const retryAfterMs = Math.min(value, maxRetryAfterMs)
10
15
  return { retryAfterMs, retryAt: now + retryAfterMs }
11
16
  }
@@ -2,14 +2,34 @@ import { isValidEvent } from '../../event/index.js'
2
2
  import { ValidationError } from '../../error/index.js'
3
3
  import { maybeUnref } from '../helpers/timer.js'
4
4
  import { categorizeRelayError, relayCloseError, relayTimeoutError, relayRejectionError } from '../helpers/error.js'
5
+ import { DEFAULT_RATE_LIMIT_CAP_MS } from '../helpers/retry-advice.js'
5
6
 
6
7
  const DEFAULT_CONNECT_TIMEOUT = 3000
7
8
  const DEFAULT_OPERATION_TIMEOUT = 30000
9
+ const BULK_PACING_MS = 1000
10
+ const BULK_BACKOFF_MAX_MS = 30000
8
11
 
9
12
  function errorFrom (reason, fallback) {
10
13
  return reason instanceof Error ? reason : new Error(String(reason || fallback))
11
14
  }
12
15
 
16
+ function retryAtFrom (value) {
17
+ const pending = [value]
18
+ const seen = new Set()
19
+ let retryAt = 0
20
+ while (pending.length) {
21
+ const current = pending.pop()
22
+ if (!current || typeof current !== 'object' || seen.has(current)) continue
23
+ seen.add(current)
24
+ if (Number.isSafeInteger(current.retryAt)) retryAt = Math.max(retryAt, current.retryAt)
25
+ for (const key of ['cause', 'reason', 'error']) pending.push(current[key])
26
+ for (const key of ['errors', 'reports', 'relays']) {
27
+ if (Array.isArray(current[key])) pending.push(...current[key])
28
+ }
29
+ }
30
+ return retryAt
31
+ }
32
+
13
33
  function hasMatchingPrefix (values, candidate) {
14
34
  return !values || values.some(value => typeof value === 'string' && candidate.startsWith(value))
15
35
  }
@@ -51,10 +71,26 @@ export class RelayConnection {
51
71
  #authentications = new Map()
52
72
  #counts = new Map()
53
73
  #retryAtByType = new Map()
74
+ #cooldownWaiters = new Set()
75
+ #bulkQueue = []
76
+ #bulkActive = null
77
+ #bulkTimer = null
78
+ #bulkBackoffMs = BULK_PACING_MS
79
+ #bulkNextAt = 0
80
+ #getRateLimitCapMs
54
81
 
55
- constructor (url, { WebSocket: WebSocketImpl = globalThis.WebSocket } = {}) {
82
+ constructor (url, {
83
+ WebSocket: WebSocketImpl = globalThis.WebSocket,
84
+ rateLimitCapMs = () => DEFAULT_RATE_LIMIT_CAP_MS
85
+ } = {}) {
56
86
  this.url = url
57
87
  this.#WebSocket = WebSocketImpl
88
+ if (typeof rateLimitCapMs !== 'function' && (!Number.isSafeInteger(rateLimitCapMs) || rateLimitCapMs < 1)) {
89
+ throw new ValidationError('INVALID_RATE_LIMIT_CAP_MS')
90
+ }
91
+ this.#getRateLimitCapMs = typeof rateLimitCapMs === 'function'
92
+ ? rateLimitCapMs
93
+ : () => rateLimitCapMs
58
94
  this.ws = null
59
95
  this.publishTimeout = DEFAULT_OPERATION_TIMEOUT
60
96
  this.onnotice = null
@@ -66,6 +102,19 @@ export class RelayConnection {
66
102
  // Exposes socket context to the pool's operation-wide publication deadline.
67
103
  get lastTransportError () { return this.#lastTransportError }
68
104
 
105
+ setRateLimitCapMs (capMs, now = Date.now()) {
106
+ if (!Number.isSafeInteger(capMs) || capMs < 1) throw new ValidationError('INVALID_RATE_LIMIT_CAP_MS')
107
+ const limit = now + Math.min(capMs, Number.MAX_SAFE_INTEGER - now)
108
+ let changed = false
109
+ for (const [type, retryAt] of this.#retryAtByType) {
110
+ if (retryAt <= limit) continue
111
+ this.#retryAtByType.set(type, limit)
112
+ changed = true
113
+ }
114
+ if (changed) for (const wake of [...this.#cooldownWaiters]) wake()
115
+ this.#pumpBulkPublishes()
116
+ }
117
+
69
118
  async connect ({ timeout = DEFAULT_CONNECT_TIMEOUT, signal } = {}) {
70
119
  if (this.ws?.readyState === 1) return
71
120
  if (this.#connectPromise) return await this.#connectPromise
@@ -127,21 +176,35 @@ export class RelayConnection {
127
176
  #dispatchWork (type, send, fail) {
128
177
  let timer = null
129
178
  let cancelled = false
130
- const dispatch = () => {
179
+ const wake = () => {
180
+ clearTimeout(timer)
181
+ timer = null
182
+ schedule()
183
+ }
184
+ const schedule = () => {
131
185
  if (cancelled) return
132
186
  const remaining = (this.#retryAtByType.get(type) ?? 0) - Date.now()
133
187
  if (remaining > 0) {
134
- timer = maybeUnref(setTimeout(dispatch, remaining))
188
+ timer = maybeUnref(setTimeout(wake, remaining))
135
189
  return
136
190
  }
191
+ this.#cooldownWaiters.delete(wake)
137
192
  try { send() } catch (error) { fail(error) }
138
193
  }
194
+ const dispatch = () => {
195
+ this.#cooldownWaiters.add(wake)
196
+ schedule()
197
+ }
139
198
  dispatch()
140
- return () => { cancelled = true; clearTimeout(timer) }
199
+ return () => {
200
+ cancelled = true
201
+ this.#cooldownWaiters.delete(wake)
202
+ clearTimeout(timer)
203
+ }
141
204
  }
142
205
 
143
206
  #rejection (type, reason, params, fallback) {
144
- const error = relayRejectionError(reason, params, fallback)
207
+ const error = relayRejectionError(reason, params, fallback, { rateLimitCapMs: this.#getRateLimitCapMs() })
145
208
  if (error.retryAt !== undefined) this.#retryAtByType.set(type, Math.max(this.#retryAtByType.get(type) ?? 0, error.retryAt))
146
209
  return error
147
210
  }
@@ -173,9 +236,10 @@ export class RelayConnection {
173
236
  return { id, close }
174
237
  }
175
238
 
176
- publish (event, { signal } = {}) {
239
+ publish (event, { signal, useBulkPacing = false } = {}) {
177
240
  if (!isValidEvent(event)) return Promise.reject(new Error('INVALID_EVENT'))
178
- return this.#sendEventOperation('EVENT', event, this.#publishes, 'PUBLISH_TIMEOUT', signal)
241
+ if (typeof useBulkPacing !== 'boolean') return Promise.reject(new ValidationError('INVALID_USE_BULK_PACING'))
242
+ return this.#sendEventOperation('EVENT', event, this.#publishes, 'PUBLISH_TIMEOUT', signal, { useBulkPacing })
179
243
  }
180
244
 
181
245
  async authenticate (getAuthEvent, { signal } = {}) {
@@ -185,13 +249,78 @@ export class RelayConnection {
185
249
  return await this.#sendEventOperation('AUTH', event, this.#authentications, 'AUTH_TIMEOUT', signal)
186
250
  }
187
251
 
188
- #sendEventOperation (type, event, map, timeoutCode, signal) {
252
+ #removeBulkPublish (pending) {
253
+ const index = this.#bulkQueue.indexOf(pending)
254
+ if (index >= 0) this.#bulkQueue.splice(index, 1)
255
+ if (this.#bulkActive === pending) {
256
+ this.#bulkActive = null
257
+ pending.onSettled = null
258
+ this.#bulkNextAt = Math.max(this.#bulkNextAt, Date.now() + BULK_PACING_MS)
259
+ }
260
+ this.#pumpBulkPublishes()
261
+ }
262
+
263
+ #clearBulkScheduler () {
264
+ clearTimeout(this.#bulkTimer)
265
+ this.#bulkTimer = null
266
+ this.#bulkQueue.length = 0
267
+ this.#bulkActive = null
268
+ this.#bulkNextAt = 0
269
+ this.#bulkBackoffMs = BULK_PACING_MS
270
+ }
271
+
272
+ #pumpBulkPublishes () {
273
+ if (this.#bulkActive || this.#bulkQueue.length === 0) return
274
+ clearTimeout(this.#bulkTimer)
275
+ this.#bulkTimer = null
276
+ while (this.#bulkQueue.length) {
277
+ const pending = this.#bulkQueue[0]
278
+ if (this.#publishes.get(pending.event.id) === pending && pending.waiters.size > 0) break
279
+ this.#bulkQueue.shift()
280
+ }
281
+ if (!this.#bulkQueue.length) return
282
+
283
+ const now = Date.now()
284
+ const eligibleAt = Math.max(this.#bulkNextAt, this.#retryAtByType.get('EVENT') ?? 0)
285
+ if (eligibleAt > now) {
286
+ this.#bulkTimer = maybeUnref(setTimeout(() => this.#pumpBulkPublishes(), eligibleAt - now))
287
+ return
288
+ }
289
+
290
+ const pending = this.#bulkQueue.shift()
291
+ const startedAt = now
292
+ this.#bulkActive = pending
293
+ pending.onSettled = (success, reason) => {
294
+ if (this.#bulkActive !== pending) return
295
+ this.#bulkActive = null
296
+ pending.onSettled = null
297
+ const completedAt = Date.now()
298
+ const hintedRetryAt = retryAtFrom(reason)
299
+ if (success) {
300
+ this.#bulkBackoffMs = BULK_PACING_MS
301
+ this.#bulkNextAt = Math.max(completedAt, startedAt + BULK_PACING_MS)
302
+ } else if (hintedRetryAt) {
303
+ // The relay advice overrides the local backoff for this retry.
304
+ this.#bulkNextAt = Math.max(completedAt, startedAt + BULK_PACING_MS)
305
+ this.#bulkBackoffMs = Math.min(BULK_BACKOFF_MAX_MS, this.#bulkBackoffMs * 2)
306
+ } else {
307
+ this.#bulkNextAt = Math.max(completedAt + this.#bulkBackoffMs, startedAt + BULK_PACING_MS)
308
+ this.#bulkBackoffMs = Math.min(BULK_BACKOFF_MAX_MS, this.#bulkBackoffMs * 2)
309
+ }
310
+ this.#pumpBulkPublishes()
311
+ }
312
+ pending.cancelSend = this.#dispatchWork('EVENT', () => {
313
+ this.send(JSON.stringify(['EVENT', pending.event]))
314
+ }, error => this.#settleEvent(this.#publishes, pending.event.id, error))
315
+ }
316
+
317
+ #sendEventOperation (type, event, map, timeoutCode, signal, { useBulkPacing = false } = {}) {
189
318
  if (signal?.aborted) return Promise.reject(signal.reason)
190
319
  let pending = map.get(event.id)
191
320
  const created = !pending
192
321
  if (created) {
193
322
  const timer = maybeUnref(setTimeout(() => this.#settleEvent(map, event.id, relayTimeoutError(timeoutCode, this.#lastTransportError)), this.publishTimeout))
194
- pending = { timer, waiters: new Set(), cancelSend: null }
323
+ pending = { timer, waiters: new Set(), cancelSend: null, event, type, timeoutCode, useBulkPacing, onSettled: null }
195
324
  map.set(event.id, pending)
196
325
  }
197
326
  const deferred = Promise.withResolvers()
@@ -203,12 +332,22 @@ export class RelayConnection {
203
332
  map.delete(event.id)
204
333
  pending.cancelSend?.()
205
334
  clearTimeout(pending.timer)
335
+ if (this.#bulkActive === pending) {
336
+ this.#bulkActive = null
337
+ pending.onSettled = null
338
+ this.#bulkNextAt = Math.max(this.#bulkNextAt, Date.now() + BULK_PACING_MS)
339
+ this.#pumpBulkPublishes()
340
+ }
206
341
  }
207
342
  }
208
343
  const waiter = { ...deferred, stopAbort: () => signal?.removeEventListener('abort', onAbort) }
209
344
  pending.waiters.add(waiter)
210
345
  signal?.addEventListener('abort', onAbort, { once: true })
211
- if (created) {
346
+ if (created && useBulkPacing && type === 'EVENT') {
347
+ pending.cancelSend = () => this.#removeBulkPublish(pending)
348
+ this.#bulkQueue.push(pending)
349
+ this.#pumpBulkPublishes()
350
+ } else if (created) {
212
351
  pending.cancelSend = this.#dispatchWork(type, () => {
213
352
  this.send(JSON.stringify([type, event]))
214
353
  }, error => this.#settleEvent(map, event.id, error))
@@ -236,6 +375,7 @@ export class RelayConnection {
236
375
  map.delete(id)
237
376
  pending.cancelSend?.()
238
377
  clearTimeout(pending.timer)
378
+ pending.onSettled?.(!reason, reason)
239
379
  for (const waiter of pending.waiters) {
240
380
  waiter.stopAbort()
241
381
  if (reason) waiter.reject(errorFrom(reason, 'OPERATION_REJECTED'))
@@ -317,6 +457,7 @@ export class RelayConnection {
317
457
  for (const id of [...this.#publishes.keys()]) this.#settleEvent(this.#publishes, id, reason)
318
458
  for (const id of [...this.#authentications.keys()]) this.#settleEvent(this.#authentications, id, reason)
319
459
  for (const id of [...this.#counts.keys()]) this.#settleCount(id, null, reason)
460
+ this.#clearBulkScheduler()
320
461
  this.onclose?.(reason)
321
462
  }
322
463
 
@@ -333,6 +474,7 @@ export class RelayConnection {
333
474
  for (const id of [...this.#publishes.keys()]) this.#settleEvent(this.#publishes, id, reason)
334
475
  for (const id of [...this.#authentications.keys()]) this.#settleEvent(this.#authentications, id, reason)
335
476
  for (const id of [...this.#counts.keys()]) this.#settleCount(id, null, reason)
477
+ this.#clearBulkScheduler()
336
478
  if (socket && socket.readyState < 2) socket.close()
337
479
  }
338
480
  }
@@ -7,6 +7,7 @@ import { drainableStream } from '../helpers/drainable-stream.js'
7
7
  import { maybeUnref } from '../helpers/timer.js'
8
8
  import { categorizeRelayError, relayTimeoutError } from '../helpers/error.js'
9
9
  import { ReadRetry, isRetryableReadFailure, needsConnectivityCheck, waitUntil } from '../helpers/read-retry.js'
10
+ import { DEFAULT_RATE_LIMIT_CAP_MS } from '../helpers/retry-advice.js'
10
11
  import { normalizeRelayUrl } from '../../url/index.js'
11
12
  import { isValidEvent } from '../../event/index.js'
12
13
  import { RelayConnection } from './relay-connection.js'
@@ -101,6 +102,11 @@ function asError (error) {
101
102
  return error instanceof Error ? error : new Error(String(error))
102
103
  }
103
104
 
105
+ function validateRateLimitCapMs (value) {
106
+ if (!Number.isSafeInteger(value) || value < 1) throw new ValidationError('INVALID_RATE_LIMIT_CAP_MS')
107
+ return value
108
+ }
109
+
104
110
  function assertReadOptions (filter, timeouts) {
105
111
  if (!filter || typeof filter !== 'object' || Array.isArray(filter)) throw new ValidationError('INVALID_FILTER')
106
112
  for (const value of Object.values(timeouts)) {
@@ -153,14 +159,34 @@ export class RelayPool {
153
159
  #WebSocket
154
160
  #admission
155
161
  #readRetry
162
+ #options
156
163
 
157
- constructor ({ _createRelay, _isOnline, _onOnline, WebSocket: WebSocketImpl, ...capacity } = {}) {
164
+ constructor ({ _createRelay, _isOnline, _onOnline, WebSocket: WebSocketImpl, rateLimitCapMs = DEFAULT_RATE_LIMIT_CAP_MS, ...capacity } = {}) {
165
+ this.#options = { rateLimitCapMs: validateRateLimitCapMs(rateLimitCapMs) }
158
166
  this.#WebSocket = WebSocketImpl
159
- this.#createRelay = _createRelay ?? (url => new RelayConnection(url, this.#WebSocket ? { WebSocket: this.#WebSocket } : undefined))
167
+ this.#createRelay = _createRelay ?? (url => new RelayConnection(url, {
168
+ ...(this.#WebSocket ? { WebSocket: this.#WebSocket } : {}),
169
+ rateLimitCapMs: () => this.#options.rateLimitCapMs
170
+ }))
160
171
  this.#admission = new ReadAdmission(capacity)
161
172
  this.#readRetry = new ReadRetry({ checkOnline: _isOnline, watchOnline: _onOnline })
162
173
  }
163
174
 
175
+ getOptions () {
176
+ return Object.freeze({ ...this.#options })
177
+ }
178
+
179
+ setOptions (partial = {}) {
180
+ if (!partial || typeof partial !== 'object' || Array.isArray(partial)) throw new ValidationError('INVALID_RELAY_POOL_OPTIONS')
181
+ const unknown = Object.keys(partial).find(key => key !== 'rateLimitCapMs')
182
+ if (unknown) throw new ValidationError('UNKNOWN_RELAY_POOL_OPTION')
183
+ const next = { ...this.#options }
184
+ if (Object.hasOwn(partial, 'rateLimitCapMs')) next.rateLimitCapMs = validateRateLimitCapMs(partial.rateLimitCapMs)
185
+ this.#options = next
186
+ for (const relay of this.#relays.values()) relay.setRateLimitCapMs?.(next.rateLimitCapMs)
187
+ return this.getOptions()
188
+ }
189
+
164
190
  // Injects the WebSocket implementation used by new pooled connections (e.g.
165
191
  // a launcher-owned relay multiplexer). Existing connections keep the
166
192
  // implementation they were created with.
@@ -250,9 +276,9 @@ export class RelayPool {
250
276
 
251
277
  // NIP-42 retries happen inside one relay attempt, so sendEvent still reports
252
278
  // exactly one terminal outcome for each relay URL.
253
- async #publishEvent (relay, event, getAuthEvent, signal) {
279
+ async #publishEvent (relay, event, getAuthEvent, signal, useBulkPacing) {
254
280
  try {
255
- await relay.publish(event, { signal })
281
+ await relay.publish(event, { signal, useBulkPacing })
256
282
  return 'published'
257
283
  } catch (error) {
258
284
  const reason = error instanceof Error ? error : new Error(String(error))
@@ -264,7 +290,7 @@ export class RelayPool {
264
290
  const authReason = error instanceof Error ? error : new Error(String(error))
265
291
  throw new Nip42AuthenticationError(authReason)
266
292
  }
267
- await relay.publish(event, { signal })
293
+ await relay.publish(event, { signal, useBulkPacing })
268
294
  return 'published'
269
295
  }
270
296
  }
@@ -1221,10 +1247,12 @@ export class RelayPool {
1221
1247
  getAuthEvent,
1222
1248
  getRetryEvent,
1223
1249
  onRelayResult,
1224
- signal
1250
+ signal,
1251
+ useBulkPacing = false
1225
1252
  } = {}) {
1226
1253
  if (signal != null && (typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function' || typeof signal.removeEventListener !== 'function')) throw new ValidationError('INVALID_RELAY_SIGNAL')
1227
1254
  if (getRetryEvent != null && typeof getRetryEvent !== 'function') throw new ValidationError('INVALID_RETRY_EVENT_CALLBACK')
1255
+ if (typeof useBulkPacing !== 'boolean') throw new ValidationError('INVALID_USE_BULK_PACING')
1228
1256
  const urls = normalizedRelayUrls(relays)
1229
1257
  if (!urls.length) {
1230
1258
  const promise = Promise.resolve(publishSummary([], urls, {
@@ -1279,7 +1307,7 @@ export class RelayPool {
1279
1307
  if (operationSignal.aborted) throw operationSignal.reason
1280
1308
  const relay = await this.#getRelay(url)
1281
1309
  if (operationSignal.aborted) throw operationSignal.reason
1282
- return await this.#publishEvent(relay, eventForAttempt, getAuthEvent, operationSignal)
1310
+ return await this.#publishEvent(relay, eventForAttempt, getAuthEvent, operationSignal, useBulkPacing)
1283
1311
  } catch (err) {
1284
1312
  const reason = err instanceof Error ? err : new Error(String(err))
1285
1313
  if (reason instanceof Nip42AuthenticationError) throw reason