Skip to content

Commit 57fb6bb

Browse files
committed
Add option to limit OutboundStream buffer size
1 parent 9f0be04 commit 57fb6bb

File tree

2 files changed

+23
-6
lines changed

2 files changed

+23
-6
lines changed

src/index.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,12 @@ export interface GossipsubOpts extends GossipsubOptsSpec, PubSubInit {
151151
* streams that are allowed to be open concurrently
152152
*/
153153
maxOutboundStreams?: number
154+
155+
/**
156+
* Specify max buffer size in bytes for OutboundStream.
157+
* If full it will throw and reject sending any more data.
158+
*/
159+
maxOutboundBufferSize?: number
154160
}
155161

156162
export interface GossipsubMessage {
@@ -691,8 +697,10 @@ export class GossipSub extends EventEmitter<GossipsubEvents> implements Initiali
691697
}
692698

693699
try {
694-
const stream = new OutboundStream(await connection.newStream(this.multicodecs), (e) =>
695-
this.log.error('outbound pipe error', e)
700+
const stream = new OutboundStream(
701+
await connection.newStream(this.multicodecs),
702+
(e) => this.log.error('outbound pipe error', e),
703+
{ maxBufferSize: this.opts.maxOutboundBufferSize }
696704
)
697705

698706
this.log('create outbound stream %p', peerId)

src/stream.ts

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,20 @@ import { pushable, Pushable } from 'it-pushable'
55
import { encode, decode } from 'it-length-prefixed'
66
import { Uint8ArrayList } from 'uint8arraylist'
77

8+
type OutboundStreamOpts = {
9+
/** Max size in bytes for pushable buffer. If full, will throw on .push */
10+
maxBufferSize?: number
11+
}
12+
813
export class OutboundStream {
9-
private readonly rawStream: Stream
1014
private readonly pushable: Pushable<Uint8Array>
1115
private readonly closeController: AbortController
16+
private readonly maxBufferSize: number
1217

13-
constructor(rawStream: Stream, errCallback: (e: Error) => void) {
14-
this.rawStream = rawStream
15-
this.pushable = pushable()
18+
constructor(private readonly rawStream: Stream, errCallback: (e: Error) => void, opts: OutboundStreamOpts) {
19+
this.pushable = pushable({ objectMode: false })
1620
this.closeController = new AbortController()
21+
this.maxBufferSize = opts.maxBufferSize ?? Infinity
1722

1823
pipe(
1924
abortableSource(this.pushable, this.closeController.signal, { returnOnAbort: true }),
@@ -28,6 +33,10 @@ export class OutboundStream {
2833
}
2934

3035
push(data: Uint8Array): void {
36+
if (this.pushable.readableLength > this.maxBufferSize) {
37+
throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`)
38+
}
39+
3140
this.pushable.push(data)
3241
}
3342

0 commit comments

Comments
 (0)