@peerbit/stream 5.0.0 → 5.0.1

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.
@@ -6,7 +6,7 @@ import { Cache } from "@peerbit/cache";
6
6
  import { PublicSignKey } from "@peerbit/crypto";
7
7
  import type { SignatureWithKey } from "@peerbit/crypto";
8
8
  import { ACK, AcknowledgeAnyWhere, AcknowledgeDelivery, AnyWhere, DataMessage, Goodbye, Message, MultiAddrinfo, SilentDelivery } from "@peerbit/stream-interface";
9
- import type { DirectStreamAckRouteHint, IdOptions, PeerRefs, PriorityOptions, PublicKeyFromHashResolver, StreamEvents, WaitForAnyOpts, WaitForPeer, WaitForPresentOpts, WithExtraSigners, WithMode, WithTo } from "@peerbit/stream-interface";
9
+ import type { DirectStreamAckRouteHint, ExpiresAtOptions, IdOptions, PeerRefs, PriorityOptions, PublicKeyFromHashResolver, ResponsePriorityOptions, StreamEvents, WaitForAnyOpts, WaitForPeer, WaitForPresentOpts, WithExtraSigners, WithMode, WithTo } from "@peerbit/stream-interface";
10
10
  import { pipe } from "it-pipe";
11
11
  import { type Pushable } from "it-pushable";
12
12
  import Queue from "p-queue";
@@ -23,12 +23,21 @@ export interface PeerStreamsInit {
23
23
  publicKey: PublicSignKey;
24
24
  protocol: string;
25
25
  connId: string;
26
+ outboundQueue?: PeerOutboundQueueOptions;
26
27
  }
27
28
  export interface PeerStreamEvents {
28
29
  "stream:inbound": CustomEvent<never>;
29
30
  "stream:outbound": CustomEvent<never>;
31
+ "queue:outbound": CustomEvent<never>;
30
32
  close: CustomEvent<never>;
31
33
  }
34
+ type OutboundQueueOptions = {
35
+ maxBufferedBytes: number;
36
+ reservedPriorityBytes: number;
37
+ maxTotalBufferedBytes: number;
38
+ reservedTotalPriorityBytes: number;
39
+ };
40
+ type PeerOutboundQueueOptions = Pick<OutboundQueueOptions, "maxBufferedBytes" | "reservedPriorityBytes">;
32
41
  export interface InboundStreamRecord {
33
42
  raw: Stream;
34
43
  iterable: AsyncIterable<Uint8ArrayList>;
@@ -37,6 +46,22 @@ export interface InboundStreamRecord {
37
46
  lastActivity: number;
38
47
  bytesReceived: number;
39
48
  }
49
+ export declare class BackpressureError extends Error {
50
+ readonly scope: "peer" | "node";
51
+ readonly peerId: PeerId;
52
+ readonly priority: number;
53
+ readonly limitBytes: number;
54
+ readonly currentBufferedBytes: number;
55
+ readonly attemptedBytes: number;
56
+ constructor(options: {
57
+ scope: "peer" | "node";
58
+ peerId: PeerId;
59
+ priority: number;
60
+ limitBytes: number;
61
+ currentBufferedBytes: number;
62
+ attemptedBytes: number;
63
+ });
64
+ }
40
65
  export declare let measureOutboundQueuedBytes: (ps: PeerStreams) => number;
41
66
  /**
42
67
  * Thin wrapper around a peer's inbound / outbound pubsub streams
@@ -63,6 +88,7 @@ export declare class PeerStreams extends TypedEventEmitter<PeerStreamEvents> {
63
88
  connId: string;
64
89
  seekedOnce: boolean;
65
90
  private usedBandWidthTracker;
91
+ private readonly outboundQueue?;
66
92
  private outboundStreams;
67
93
  get rawOutboundStreams(): Stream[];
68
94
  _getActiveOutboundPushable(): PushableLanes<Uint8Array> | undefined;
@@ -90,6 +116,9 @@ export declare class PeerStreams extends TypedEventEmitter<PeerStreamEvents> {
90
116
  */
91
117
  get isWritable(): boolean;
92
118
  get usedBandwidth(): number;
119
+ private getQueueAdmissionLimitBytes;
120
+ private assertQueueCapacity;
121
+ private waitForQueueCapacity;
93
122
  /**
94
123
  * Send a message to this peer.
95
124
  * Throws if there is no `stream` to write to available.
@@ -148,6 +177,12 @@ export type ConnectionManagerArguments = (Partial<Pick<ConnectionManagerOptions,
148
177
  } & {
149
178
  dialer?: Partial<DialerOptions> | false;
150
179
  }) | false;
180
+ type OutboundQueueArguments = {
181
+ maxBufferedBytes?: number;
182
+ reservedPriorityBytes?: number;
183
+ maxTotalBufferedBytes?: number;
184
+ reservedTotalPriorityBytes?: number;
185
+ } | false;
151
186
  export type DirectStreamOptions = {
152
187
  canRelayMessage?: boolean;
153
188
  messageProcessingConcurrency?: number;
@@ -176,6 +211,7 @@ export type DirectStreamOptions = {
176
211
  sharedRouting?: boolean;
177
212
  seenCacheMax?: number;
178
213
  seenCacheTtlMs?: number;
214
+ outboundQueue?: OutboundQueueArguments;
179
215
  };
180
216
  type ConnectionManagerLike = {
181
217
  getConnections(peerId?: PeerId): Connection[];
@@ -198,7 +234,7 @@ export interface DirectStreamComponents {
198
234
  events: TypedEventTarget<Libp2pEvents>;
199
235
  privateKey: PrivateKey;
200
236
  }
201
- export type PublishOptions = (WithMode | WithTo) & PriorityOptions & WithExtraSigners;
237
+ export type PublishOptions = (WithMode | WithTo) & PriorityOptions & ResponsePriorityOptions & ExpiresAtOptions & WithExtraSigners;
202
238
  export declare abstract class DirectStream<Events extends {
203
239
  [s: string]: any;
204
240
  } = StreamEvents> extends TypedEventEmitter<Events> implements WaitForPeer, PublicKeyFromHashResolver {
@@ -242,6 +278,8 @@ export declare abstract class DirectStream<Events extends {
242
278
  private routeCacheMaxTargetsPerFrom?;
243
279
  private routeCacheMaxRelaysPerTarget?;
244
280
  private readonly sharedRouting;
281
+ private readonly outboundQueueOptions?;
282
+ private readonly totalOutboundQueueWaiters;
245
283
  private sharedRoutingKey?;
246
284
  private sharedRoutingState?;
247
285
  outboundInflightQueue: Pushable<{
@@ -316,7 +354,7 @@ export declare abstract class DirectStream<Events extends {
316
354
  onGoodBye(publicKey: PublicSignKey, peerStream: PeerStreams, messageBytes: Uint8ArrayList | Uint8Array, message: Goodbye): Promise<boolean>;
317
355
  private maybeDeleteRemoteRoutes;
318
356
  private checkIsAlive;
319
- createMessage(data: Uint8Array | Uint8ArrayList | undefined, options: (WithTo | WithMode) & PriorityOptions & IdOptions & {
357
+ createMessage(data: Uint8Array | Uint8ArrayList | undefined, options: (WithTo | WithMode) & PriorityOptions & ResponsePriorityOptions & ExpiresAtOptions & IdOptions & {
320
358
  skipRecipientValidation?: boolean;
321
359
  } & WithExtraSigners): Promise<DataMessage<SilentDelivery | AcknowledgeDelivery | AcknowledgeAnyWhere | AnyWhere>>;
322
360
  /**
@@ -335,6 +373,11 @@ export declare abstract class DirectStream<Events extends {
335
373
  get pending(): boolean;
336
374
  maybePruneConnections(): Promise<void>;
337
375
  pruneConnections(): Promise<void>;
376
+ private getTotalQueueAdmissionLimitBytes;
377
+ private assertTotalQueueCapacity;
378
+ private notifyTotalOutboundQueueWaiters;
379
+ private waitForTotalQueueCapacity;
380
+ protected waitForPeerWrite(stream: PeerStreams, bytes: Uint8Array | Uint8ArrayList, priority?: number, signal?: AbortSignal): Promise<void>;
338
381
  getQueuedBytes(): number;
339
382
  }
340
383
  export declare const waitForReachable: (...libs: {
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,iBAAiB,EAEjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EACX,YAAY,EACZ,UAAU,EACV,YAAY,EACZ,MAAM,EACN,SAAS,EACT,UAAU,EACV,MAAM,EACN,gBAAgB,EAChB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AAC5E,OAAO,EAAE,KAAK,SAAS,EAAa,MAAM,yBAAyB,CAAC;AAEpE,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,EACN,aAAa,EAMb,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACxD,OAAO,EACN,GAAG,EACH,mBAAmB,EACnB,mBAAmB,EACnB,QAAQ,EACR,WAAW,EAEX,OAAO,EAEP,OAAO,EAEP,aAAa,EAEb,cAAc,EAKd,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EACX,wBAAwB,EACxB,SAAS,EACT,QAAQ,EACR,eAAe,EACf,yBAAyB,EACzB,YAAY,EACZ,cAAc,EA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CAAgC;IAgBxC,OAAO,CAAC,wBAAwB;IAsBhC,OAAO,CAAC,+BAA+B;YAazB,yBAAyB;cA4CvB,gBAAgB,CAC/B,MAAM,EAAE,WAAW,EACnB,KAAK,EAAE,UAAU,GAAG,cAAc,EAClC,QAAQ,SAAI,EACZ,MAAM,CAAC,EAAE,WAAW;IAgBrB,cAAc,IAAI,MAAM;CAOxB;AAED,eAAO,MAAM,gBAAgB,GAC5B,GAAG,MAAM;IACR,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,GAAG,aAAa,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACzD,MAAM,EAAE,MAAM,CAAC;CACf,EAAE,kBAWH,CAAC;AAEF,eAAO,MAAM,gBAAgB,GAC5B,GAAG,MAAM;IACR,OAAO,EAAE,CACR,IAAI,EAAE,QAAQ,EACd,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,UAAU,CAAA;KAAE,KAC7B,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IACvB,MAAM,EAAE,MAAM,CAAC;CACf,EAAE,kBAcH,CAAC"}
package/dist/src/index.js CHANGED
@@ -79,6 +79,8 @@ const ROUTE_MAX_RETANTION_PERIOD = 5e4;
79
79
  const MAX_DATA_LENGTH_IN = 15e6 + 1000; // 15 mb and some metadata
80
80
  const MAX_DATA_LENGTH_OUT = 1e7 + 1000; // 10 mb and some metadata
81
81
  const MAX_QUEUED_BYTES = MAX_DATA_LENGTH_IN * 50;
82
+ const DEFAULT_OUTBOUND_QUEUE_MAX_BYTES = MAX_DATA_LENGTH_OUT * 2;
83
+ const DEFAULT_OUTBOUND_QUEUE_RESERVED_PRIORITY_BYTES = 1024 * 1024;
82
84
  const DEFAULT_PRUNE_CONNECTIONS_INTERVAL = 2e4;
83
85
  const DEFAULT_MIN_CONNECTIONS = 2;
84
86
  const DEFAULT_MAX_CONNECTIONS = 300;
@@ -95,6 +97,25 @@ const getLaneFromPriority = (priority) => {
95
97
  const clampedPriority = Math.max(0, Math.min(maxLane, Math.floor(priority)));
96
98
  return maxLane - clampedPriority;
97
99
  };
100
+ export class BackpressureError extends Error {
101
+ scope;
102
+ peerId;
103
+ priority;
104
+ limitBytes;
105
+ currentBufferedBytes;
106
+ attemptedBytes;
107
+ constructor(options) {
108
+ super(`Outbound ${options.scope} queue full for ${options.peerId.toString()} on priority ${options.priority}: ` +
109
+ `${options.currentBufferedBytes} buffered + ${options.attemptedBytes} attempted > ${options.limitBytes} limit`);
110
+ this.name = "BackpressureError";
111
+ this.scope = options.scope;
112
+ this.peerId = options.peerId;
113
+ this.priority = options.priority;
114
+ this.limitBytes = options.limitBytes;
115
+ this.currentBufferedBytes = options.currentBufferedBytes;
116
+ this.attemptedBytes = options.attemptedBytes;
117
+ }
118
+ }
98
119
  // Hook for tests to override queued length measurement (peerStreams, default impl)
99
120
  export let measureOutboundQueuedBytes = (ps) => {
100
121
  const active = ps._getActiveOutboundPushable();
@@ -139,6 +160,7 @@ export class PeerStreams extends TypedEventEmitter {
139
160
  connId;
140
161
  seekedOnce;
141
162
  usedBandWidthTracker;
163
+ outboundQueue;
142
164
  // Unified outbound streams list (during grace may contain >1; after pruning length==1)
143
165
  outboundStreams = [];
144
166
  // Public debug exposure of current raw outbound streams (during grace may contain >1)
@@ -183,6 +205,11 @@ export class PeerStreams extends TypedEventEmitter {
183
205
  return existing;
184
206
  const pushableInst = pushableLanes({
185
207
  lanes: PRIORITY_LANES,
208
+ maxBufferedBytes: this.outboundQueue?.maxBufferedBytes,
209
+ overflow: "throw",
210
+ onBufferSize: () => {
211
+ this.dispatchEvent(new CustomEvent("queue:outbound"));
212
+ },
186
213
  onPush: (val) => {
187
214
  candidate.bytesDelivered += val.length || val.byteLength || 0;
188
215
  },
@@ -266,6 +293,7 @@ export class PeerStreams extends TypedEventEmitter {
266
293
  this.connId = init.connId;
267
294
  this.usedBandWidthTracker = new BandwidthTracker(10);
268
295
  this.usedBandWidthTracker.start();
296
+ this.outboundQueue = init.outboundQueue;
269
297
  }
270
298
  /**
271
299
  * Do we have a connection to read from?
@@ -282,6 +310,49 @@ export class PeerStreams extends TypedEventEmitter {
282
310
  get usedBandwidth() {
283
311
  return this.usedBandWidthTracker.value;
284
312
  }
313
+ getQueueAdmissionLimitBytes(lane) {
314
+ if (!this.outboundQueue) {
315
+ return undefined;
316
+ }
317
+ if (lane === getLaneFromPriority(0)) {
318
+ return Math.max(0, this.outboundQueue.maxBufferedBytes -
319
+ this.outboundQueue.reservedPriorityBytes);
320
+ }
321
+ return this.outboundQueue.maxBufferedBytes;
322
+ }
323
+ assertQueueCapacity(candidate, payloadBytes, priority) {
324
+ const lane = getLaneFromPriority(priority);
325
+ const limitBytes = this.getQueueAdmissionLimitBytes(lane);
326
+ if (limitBytes == null) {
327
+ return;
328
+ }
329
+ const currentBufferedBytes = candidate.pushable.getReadableLength();
330
+ if (currentBufferedBytes + payloadBytes > limitBytes) {
331
+ throw new BackpressureError({
332
+ scope: "peer",
333
+ peerId: this.peerId,
334
+ priority,
335
+ limitBytes,
336
+ currentBufferedBytes,
337
+ attemptedBytes: payloadBytes,
338
+ });
339
+ }
340
+ }
341
+ async waitForQueueCapacity(payloadBytes, priority, signal) {
342
+ const lane = getLaneFromPriority(priority);
343
+ const limitBytes = this.getQueueAdmissionLimitBytes(lane);
344
+ if (limitBytes == null) {
345
+ return;
346
+ }
347
+ const threshold = Math.max(0, limitBytes - payloadBytes);
348
+ const waiters = this.outboundStreams
349
+ .filter((candidate) => !candidate.aborted)
350
+ .map((candidate) => candidate.pushable.onBufferedBelow(threshold, { signal }));
351
+ if (waiters.length === 0) {
352
+ throw new Error("No writable connection to " + this.peerId.toString());
353
+ }
354
+ await Promise.race(waiters);
355
+ }
285
356
  /**
286
357
  * Send a message to this peer.
287
358
  * Throws if there is no `stream` to write to available.
@@ -294,7 +365,6 @@ export class PeerStreams extends TypedEventEmitter {
294
365
  logger.error("No writable connection to " + this.peerId.toString());
295
366
  throw new Error("No writable connection to " + this.peerId.toString());
296
367
  }
297
- this.usedBandWidthTracker.add(data.byteLength);
298
368
  // Write to all current outbound streams (normally 1, but >1 during grace)
299
369
  const payload = data instanceof Uint8Array ? data : data.subarray();
300
370
  let successes = 0;
@@ -307,6 +377,7 @@ export class PeerStreams extends TypedEventEmitter {
307
377
  continue;
308
378
  }
309
379
  try {
380
+ this.assertQueueCapacity(c, payload.byteLength, priority);
310
381
  c.pushable.push(payload, getLaneFromPriority(priority));
311
382
  successes++;
312
383
  }
@@ -317,6 +388,10 @@ export class PeerStreams extends TypedEventEmitter {
317
388
  }
318
389
  }
319
390
  if (successes === 0) {
391
+ const backpressureFailures = failures.filter((f) => f instanceof BackpressureError);
392
+ if (backpressureFailures.length === failures.length) {
393
+ throw backpressureFailures[0];
394
+ }
320
395
  throw new Error("All outbound writes failed (" +
321
396
  failures.map((f) => f?.message).join(", ") +
322
397
  ")");
@@ -347,6 +422,7 @@ export class PeerStreams extends TypedEventEmitter {
347
422
  this.dispatchEvent(new CustomEvent("stream:outbound"));
348
423
  }
349
424
  }
425
+ this.usedBandWidthTracker.add(payload.byteLength);
350
426
  }
351
427
  /**
352
428
  * Write to the outbound stream, waiting until it becomes writable.
@@ -358,47 +434,56 @@ export class PeerStreams extends TypedEventEmitter {
358
434
  logger.error(`Failed to send to stream ${this.peerId}: closed`);
359
435
  return;
360
436
  }
361
- if (this.isWritable) {
362
- this.write(bytes, priority);
363
- return;
364
- }
365
- // Outbound stream negotiation can legitimately take several seconds in CI
366
- // (identify/protocol discovery, resource contention, etc). Keep this fairly
367
- // generous so control-plane messages (joins/subscriptions) don't flap.
368
- const timeoutMs = 10_000;
369
- await new Promise((resolve, reject) => {
370
- const onOutbound = () => {
371
- cleanup();
372
- resolve();
373
- };
374
- const onAbortOrClose = () => {
375
- cleanup();
376
- reject(new AbortError("Closed"));
377
- };
378
- const onTimeout = () => {
379
- cleanup();
380
- reject(new TimeoutError("Failed to deliver message, never reachable"));
381
- };
382
- const timerId = setTimeout(onTimeout, timeoutMs);
383
- const cleanup = () => {
384
- clearTimeout(timerId);
385
- this.removeEventListener("stream:outbound", onOutbound);
386
- this.removeEventListener("close", onAbortOrClose);
387
- signal?.removeEventListener("abort", onAbortOrClose);
388
- };
389
- this.addEventListener("stream:outbound", onOutbound, { once: true });
390
- this.addEventListener("close", onAbortOrClose, { once: true });
391
- if (signal?.aborted) {
392
- onAbortOrClose();
437
+ while (true) {
438
+ if (!this.isWritable) {
439
+ // Outbound stream negotiation can legitimately take several seconds in CI
440
+ // (identify/protocol discovery, resource contention, etc). Keep this fairly
441
+ // generous so control-plane messages (joins/subscriptions) don't flap.
442
+ const timeoutMs = 10_000;
443
+ await new Promise((resolve, reject) => {
444
+ const onOutbound = () => {
445
+ cleanup();
446
+ resolve();
447
+ };
448
+ const onAbortOrClose = () => {
449
+ cleanup();
450
+ reject(new AbortError("Closed"));
451
+ };
452
+ const onTimeout = () => {
453
+ cleanup();
454
+ reject(new TimeoutError("Failed to deliver message, never reachable"));
455
+ };
456
+ const timerId = setTimeout(onTimeout, timeoutMs);
457
+ const cleanup = () => {
458
+ clearTimeout(timerId);
459
+ this.removeEventListener("stream:outbound", onOutbound);
460
+ this.removeEventListener("close", onAbortOrClose);
461
+ signal?.removeEventListener("abort", onAbortOrClose);
462
+ };
463
+ this.addEventListener("stream:outbound", onOutbound, { once: true });
464
+ this.addEventListener("close", onAbortOrClose, { once: true });
465
+ if (signal?.aborted) {
466
+ onAbortOrClose();
467
+ }
468
+ else {
469
+ signal?.addEventListener("abort", onAbortOrClose, { once: true });
470
+ }
471
+ // Catch a race where writability flips after the first check.
472
+ if (this.isWritable)
473
+ onOutbound();
474
+ });
393
475
  }
394
- else {
395
- signal?.addEventListener("abort", onAbortOrClose, { once: true });
476
+ try {
477
+ this.write(bytes, priority);
478
+ return;
396
479
  }
397
- // Catch a race where writability flips after the first check.
398
- if (this.isWritable)
399
- onOutbound();
400
- });
401
- this.write(bytes, priority);
480
+ catch (error) {
481
+ if (!(error instanceof BackpressureError)) {
482
+ throw error;
483
+ }
484
+ await this.waitForQueueCapacity(bytes.byteLength, priority, signal);
485
+ }
486
+ }
402
487
  }
403
488
  /**
404
489
  * Attach a raw inbound stream and setup a read stream
@@ -708,6 +793,8 @@ export class DirectStream extends TypedEventEmitter {
708
793
  routeCacheMaxTargetsPerFrom;
709
794
  routeCacheMaxRelaysPerTarget;
710
795
  sharedRouting;
796
+ outboundQueueOptions;
797
+ totalOutboundQueueWaiters = new Set();
711
798
  sharedRoutingKey;
712
799
  sharedRoutingState;
713
800
  // for sequential creation of outbound streams
@@ -720,7 +807,7 @@ export class DirectStream extends TypedEventEmitter {
720
807
  constructor(components, multicodecs, options) {
721
808
  super();
722
809
  this.components = components;
723
- const { canRelayMessage = true, messageProcessingConcurrency = 10, maxInboundStreams, maxOutboundStreams, connectionManager, seekTimeout = SEEK_DELIVERY_TIMEOUT, routeMaxRetentionPeriod = ROUTE_MAX_RETANTION_PERIOD, routeCacheMaxFromEntries, routeCacheMaxTargetsPerFrom, routeCacheMaxRelaysPerTarget, sharedRouting = true, seenCacheMax = 1e6, seenCacheTtlMs = 10 * 60 * 1e3, inboundIdleTimeout, } = options || {};
810
+ const { canRelayMessage = true, messageProcessingConcurrency = 10, maxInboundStreams, maxOutboundStreams, connectionManager, seekTimeout = SEEK_DELIVERY_TIMEOUT, routeMaxRetentionPeriod = ROUTE_MAX_RETANTION_PERIOD, routeCacheMaxFromEntries, routeCacheMaxTargetsPerFrom, routeCacheMaxRelaysPerTarget, sharedRouting = true, seenCacheMax = 1e6, seenCacheTtlMs = 10 * 60 * 1e3, inboundIdleTimeout, outboundQueue, } = options || {};
724
811
  const signKey = getKeypairFromPrivateKey(components.privateKey);
725
812
  this.seekTimeout = seekTimeout;
726
813
  this.sign = signKey.sign.bind(signKey);
@@ -781,6 +868,25 @@ export class DirectStream extends TypedEventEmitter {
781
868
  : undefined,
782
869
  };
783
870
  }
871
+ if (outboundQueue === false) {
872
+ this.outboundQueueOptions = undefined;
873
+ }
874
+ else {
875
+ const maxBufferedBytes = Math.max(MAX_DATA_LENGTH_OUT, Math.floor(outboundQueue?.maxBufferedBytes ?? DEFAULT_OUTBOUND_QUEUE_MAX_BYTES));
876
+ const reservedPriorityBytes = Math.max(0, Math.min(maxBufferedBytes, Math.floor(outboundQueue?.reservedPriorityBytes ??
877
+ DEFAULT_OUTBOUND_QUEUE_RESERVED_PRIORITY_BYTES)));
878
+ const maxTotalBufferedBytes = Math.max(maxBufferedBytes, Math.floor(outboundQueue?.maxTotalBufferedBytes ??
879
+ this.connectionManagerOptions.pruner?.maxBuffer ??
880
+ MAX_QUEUED_BYTES));
881
+ const reservedTotalPriorityBytes = Math.max(0, Math.min(maxTotalBufferedBytes, Math.floor(outboundQueue?.reservedTotalPriorityBytes ??
882
+ DEFAULT_OUTBOUND_QUEUE_RESERVED_PRIORITY_BYTES)));
883
+ this.outboundQueueOptions = {
884
+ maxBufferedBytes,
885
+ reservedPriorityBytes,
886
+ maxTotalBufferedBytes,
887
+ reservedTotalPriorityBytes,
888
+ };
889
+ }
784
890
  this.recentDials = this.connectionManagerOptions.dialer
785
891
  ? new Cache({
786
892
  ttl: this.connectionManagerOptions.dialer.retryDelay,
@@ -1333,20 +1439,25 @@ export class DirectStream extends TypedEventEmitter {
1333
1439
  publicKey,
1334
1440
  protocol,
1335
1441
  connId,
1442
+ outboundQueue: this.outboundQueueOptions,
1336
1443
  });
1337
1444
  this.peers.set(publicKeyHash, peerStreams);
1338
1445
  this.updateSession(publicKey, -1);
1339
1446
  // Propagate per-peer stream readiness events to the parent emitter
1340
1447
  const forwardOutbound = () => this.dispatchEvent(new CustomEvent("stream:outbound"));
1341
1448
  const forwardInbound = () => this.dispatchEvent(new CustomEvent("stream:inbound"));
1449
+ const forwardQueue = () => this.notifyTotalOutboundQueueWaiters();
1342
1450
  peerStreams.addEventListener("stream:outbound", forwardOutbound);
1343
1451
  peerStreams.addEventListener("stream:inbound", forwardInbound);
1452
+ peerStreams.addEventListener("queue:outbound", forwardQueue);
1344
1453
  peerStreams.addEventListener("close", () => this._removePeer(publicKey), {
1345
1454
  once: true,
1346
1455
  });
1347
1456
  peerStreams.addEventListener("close", () => {
1348
1457
  peerStreams.removeEventListener("stream:outbound", forwardOutbound);
1349
1458
  peerStreams.removeEventListener("stream:inbound", forwardInbound);
1459
+ peerStreams.removeEventListener("queue:outbound", forwardQueue);
1460
+ this.notifyTotalOutboundQueueWaiters();
1350
1461
  }, { once: true });
1351
1462
  this.addRouteConnection(this.publicKeyHash, publicKey.hashcode(), publicKey, -1, +new Date(), -1);
1352
1463
  // Enforce connection manager limits eagerly when new peers are added. Without this,
@@ -1724,6 +1835,8 @@ export class DirectStream extends TypedEventEmitter {
1724
1835
  mode,
1725
1836
  session: this.session,
1726
1837
  priority: options.priority,
1838
+ responsePriority: options.responsePriority,
1839
+ expires: options.expiresAt,
1727
1840
  }),
1728
1841
  });
1729
1842
  // TODO allow messages to also be sent unsigned (signaturePolicy property)
@@ -2050,10 +2163,10 @@ export class DirectStream extends TypedEventEmitter {
2050
2163
  continue;
2051
2164
  if (message.header.mode instanceof SilentDelivery) {
2052
2165
  message.header.mode.to = [..._distantPeers.keys()];
2053
- promises.push(stream.waitForWrite(message.bytes(), message.header.priority));
2166
+ promises.push(this.waitForPeerWrite(stream, message.bytes(), message.header.priority));
2054
2167
  }
2055
2168
  else {
2056
- promises.push(stream.waitForWrite(bytes, message.header.priority));
2169
+ promises.push(this.waitForPeerWrite(stream, bytes, message.header.priority));
2057
2170
  }
2058
2171
  usedNeighbours.add(neighbour);
2059
2172
  }
@@ -2074,7 +2187,7 @@ export class DirectStream extends TypedEventEmitter {
2074
2187
  if (usedNeighbours.has(neighbour))
2075
2188
  continue;
2076
2189
  usedNeighbours.add(neighbour);
2077
- promises.push(stream.waitForWrite(bytes, message.header.priority));
2190
+ promises.push(this.waitForPeerWrite(stream, bytes, message.header.priority));
2078
2191
  }
2079
2192
  }
2080
2193
  await Promise.all(promises);
@@ -2099,7 +2212,7 @@ export class DirectStream extends TypedEventEmitter {
2099
2212
  continue; // recipient already signed/seen this message
2100
2213
  }
2101
2214
  message.header.mode.to = [recipient];
2102
- promises.push(stream.waitForWrite(message.bytes(), message.header.priority));
2215
+ promises.push(this.waitForPeerWrite(stream, message.bytes(), message.header.priority));
2103
2216
  }
2104
2217
  message.header.mode.to = originalTo;
2105
2218
  if (promises.length > 0) {
@@ -2130,7 +2243,7 @@ export class DirectStream extends TypedEventEmitter {
2130
2243
  continue;
2131
2244
  }
2132
2245
  sentOnce = true;
2133
- promises.push(id.waitForWrite(bytes, message.header.priority));
2246
+ promises.push(this.waitForPeerWrite(id, bytes, message.header.priority));
2134
2247
  }
2135
2248
  await Promise.all(promises);
2136
2249
  if (!sentOnce) {
@@ -2334,6 +2447,95 @@ export class DirectStream extends TypedEventEmitter {
2334
2447
  await this.onPeerDisconnected(stream.peerId);
2335
2448
  return this.components.connectionManager.closeConnections(stream.peerId);
2336
2449
  }
2450
+ getTotalQueueAdmissionLimitBytes(priority) {
2451
+ const limitBytes = this.outboundQueueOptions?.maxTotalBufferedBytes;
2452
+ if (limitBytes == null) {
2453
+ return undefined;
2454
+ }
2455
+ if (getLaneFromPriority(priority) === getLaneFromPriority(0)) {
2456
+ return Math.max(0, limitBytes - this.outboundQueueOptions.reservedTotalPriorityBytes);
2457
+ }
2458
+ return limitBytes;
2459
+ }
2460
+ assertTotalQueueCapacity(peerId, payloadBytes, priority) {
2461
+ const limitBytes = this.getTotalQueueAdmissionLimitBytes(priority);
2462
+ if (limitBytes == null) {
2463
+ return;
2464
+ }
2465
+ const currentBufferedBytes = this.getQueuedBytes();
2466
+ if (currentBufferedBytes + payloadBytes > limitBytes) {
2467
+ throw new BackpressureError({
2468
+ scope: "node",
2469
+ peerId,
2470
+ priority,
2471
+ limitBytes,
2472
+ currentBufferedBytes,
2473
+ attemptedBytes: payloadBytes,
2474
+ });
2475
+ }
2476
+ }
2477
+ notifyTotalOutboundQueueWaiters() {
2478
+ if (this.totalOutboundQueueWaiters.size === 0) {
2479
+ return;
2480
+ }
2481
+ const queuedBytes = this.getQueuedBytes();
2482
+ for (const waiter of [...this.totalOutboundQueueWaiters]) {
2483
+ if (queuedBytes <= waiter.limitBytes) {
2484
+ this.totalOutboundQueueWaiters.delete(waiter);
2485
+ waiter.deferred.resolve();
2486
+ }
2487
+ }
2488
+ }
2489
+ async waitForTotalQueueCapacity(payloadBytes, priority, signal) {
2490
+ const limitBytes = this.getTotalQueueAdmissionLimitBytes(priority);
2491
+ if (limitBytes == null) {
2492
+ return;
2493
+ }
2494
+ const threshold = Math.max(0, limitBytes - payloadBytes);
2495
+ if (this.getQueuedBytes() <= threshold) {
2496
+ return;
2497
+ }
2498
+ const waiter = {
2499
+ limitBytes: threshold,
2500
+ deferred: pDefer(),
2501
+ };
2502
+ this.totalOutboundQueueWaiters.add(waiter);
2503
+ let cancel;
2504
+ let listener;
2505
+ if (signal != null) {
2506
+ cancel = new Promise((_resolve, reject) => {
2507
+ listener = () => {
2508
+ this.totalOutboundQueueWaiters.delete(waiter);
2509
+ reject(new AbortError());
2510
+ };
2511
+ signal.addEventListener("abort", listener);
2512
+ });
2513
+ }
2514
+ try {
2515
+ await Promise.race(cancel != null ? [waiter.deferred.promise, cancel] : [waiter.deferred.promise]);
2516
+ }
2517
+ finally {
2518
+ this.totalOutboundQueueWaiters.delete(waiter);
2519
+ if (listener != null) {
2520
+ signal?.removeEventListener("abort", listener);
2521
+ }
2522
+ }
2523
+ }
2524
+ async waitForPeerWrite(stream, bytes, priority = 0, signal) {
2525
+ while (true) {
2526
+ try {
2527
+ this.assertTotalQueueCapacity(stream.peerId, bytes.byteLength, priority);
2528
+ await stream.waitForWrite(bytes, priority, signal);
2529
+ return;
2530
+ }
2531
+ catch (error) {
2532
+ if (!(error instanceof BackpressureError) || error.scope !== "node") {
2533
+ throw error;
2534
+ }
2535
+ await this.waitForTotalQueueCapacity(bytes.byteLength, priority, signal);
2536
+ }
2537
+ }
2538
+ }
2337
2539
  getQueuedBytes() {
2338
2540
  let sum = 0;
2339
2541
  for (const [_k, ps] of this.peers) {