nerdbank-streams 2.13.31 → 2.14.259-alpha

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.
@@ -63,7 +63,7 @@ export abstract class MultiplexingStream implements IDisposableObservable {
63
63
  * @param cancellationToken A token whose cancellation aborts the handshake with the remote end.
64
64
  * @returns The multiplexing stream, once the handshake is complete.
65
65
  */
66
- // eslint-disable-next-line @typescript-eslint/naming-convention
66
+
67
67
  public static async CreateAsync(
68
68
  stream: NodeJS.ReadWriteStream,
69
69
  options?: MultiplexingStreamOptions,
@@ -85,10 +85,10 @@ export abstract class MultiplexingStream implements IDisposableObservable {
85
85
  options.protocolMajorVersion === 1
86
86
  ? new MultiplexingStreamV1Formatter(stream)
87
87
  : options.protocolMajorVersion === 2
88
- ? new MultiplexingStreamV2Formatter(stream)
89
- : options.protocolMajorVersion === 3
90
- ? new MultiplexingStreamV3Formatter(stream)
91
- : undefined
88
+ ? new MultiplexingStreamV2Formatter(stream)
89
+ : options.protocolMajorVersion === 3
90
+ ? new MultiplexingStreamV3Formatter(stream)
91
+ : undefined
92
92
  if (!formatter) {
93
93
  throw new Error(`Protocol major version ${options.protocolMajorVersion} is not supported.`)
94
94
  }
@@ -108,7 +108,7 @@ export abstract class MultiplexingStream implements IDisposableObservable {
108
108
  * @param options Options to customize the behavior of the stream.
109
109
  * @returns The multiplexing stream.
110
110
  */
111
- // eslint-disable-next-line @typescript-eslint/naming-convention
111
+
112
112
  public static Create(stream: NodeJS.ReadWriteStream, options?: MultiplexingStreamOptions): MultiplexingStream {
113
113
  options ??= { protocolMajorVersion: 3 }
114
114
  options.protocolMajorVersion ??= 3
@@ -130,7 +130,7 @@ export abstract class MultiplexingStream implements IDisposableObservable {
130
130
  /**
131
131
  * The encoding used for characters in control frames.
132
132
  */
133
- // eslint-disable-next-line @typescript-eslint/naming-convention
133
+
134
134
  static readonly ControlFrameEncoding = 'utf-8'
135
135
 
136
136
  protected readonly _completionSource = new Deferred<void>()
@@ -600,6 +600,16 @@ export class MultiplexingStreamClass extends MultiplexingStream {
600
600
  }
601
601
  }
602
602
 
603
+ public onChannelReadingCompleted(channel: ChannelClass): Promise<void> {
604
+ // Only inform the remote side if backpressure is in play (so the frame is meaningful)
605
+ // and this channel has not already been terminated.
606
+ if (this.backpressureSupportEnabled && !channel.isDisposed && this.getOpenChannel(channel.qualifiedId)) {
607
+ return this.sendFrame(ControlCode.contentReadingCompleted, channel.qualifiedId)
608
+ }
609
+
610
+ return Promise.resolve()
611
+ }
612
+
603
613
  public async onChannelDisposed(channel: ChannelClass, error: Error | null) {
604
614
  if (!this._completionSource.isCompleted) {
605
615
  try {
@@ -648,6 +658,9 @@ export class MultiplexingStreamClass extends MultiplexingStream {
648
658
  case ControlCode.contentWritingCompleted:
649
659
  this.onContentWritingCompleted(frame.header.requiredChannel)
650
660
  break
661
+ case ControlCode.contentReadingCompleted:
662
+ this.onContentReadingCompleted(frame.header.requiredChannel)
663
+ break
651
664
  case ControlCode.channelTerminated:
652
665
  this.onChannelTerminated(frame.header.requiredChannel, frame.payload)
653
666
  break
@@ -742,6 +755,12 @@ export class MultiplexingStreamClass extends MultiplexingStream {
742
755
  channel.onContent(null) // signify that the remote is done writing.
743
756
  }
744
757
 
758
+ private onContentReadingCompleted(channelId: QualifiedChannelId) {
759
+ // The channel may have been terminated concurrently, in which case there's nothing to do.
760
+ const channel = this.getOpenChannel(channelId)
761
+ channel?.onContentReadingCompleted()
762
+ }
763
+
745
764
  /**
746
765
  * Occurs when the remote party has terminated a channel (including canceling an offer).
747
766
  * @param channelId The ID of the terminated channel.
@@ -13,18 +13,18 @@ export interface QualifiedChannelId {
13
13
  */
14
14
  export enum ChannelSource {
15
15
  /** The channel was offered by this MultiplexingStream instance to the other party. */
16
- // eslint-disable-next-line @typescript-eslint/naming-convention
16
+
17
17
  Local = 1,
18
18
 
19
19
  /** The channel was offered to this MultiplexingStream instance by the other party. */
20
- // eslint-disable-next-line @typescript-eslint/naming-convention
20
+
21
21
  Remote = -1,
22
22
 
23
23
  /**
24
24
  * The channel was seeded during construction via the Options.SeededChannels collection.
25
25
  * This channel is to be accepted by both parties.
26
26
  */
27
- // eslint-disable-next-line @typescript-eslint/naming-convention
27
+
28
28
  Seeded = 0,
29
29
  }
30
30
 
@@ -35,10 +35,10 @@ export namespace QualifiedChannelId {
35
35
  id.source === ChannelSource.Local
36
36
  ? 'local'
37
37
  : id.source === ChannelSource.Remote
38
- ? 'remote'
39
- : id.source === ChannelSource.Seeded
40
- ? 'seeded'
41
- : 'unknown'
38
+ ? 'remote'
39
+ : id.source === ChannelSource.Seeded
40
+ ? 'seeded'
41
+ : 'unknown'
42
42
  return `${id.id} (${sourceName})`
43
43
  }
44
44
  }
package/src/Utilities.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import CancellationToken from 'cancellationtoken'
2
2
  import { Readable, Writable } from 'stream'
3
- import { Deferred } from './Deferred'
4
3
  import { IDisposableObservable } from './IDisposableObservable'
5
4
 
6
5
  export async function writeAsync(stream: NodeJS.WritableStream, chunk: any) {
@@ -35,20 +34,207 @@ export function writeSubstream(stream: NodeJS.WritableStream): NodeJS.WritableSt
35
34
  })
36
35
  }
37
36
 
38
- export function readSubstream(stream: NodeJS.ReadableStream): NodeJS.ReadableStream {
37
+ /**
38
+ * Reads the next chunk from a stream, asynchronously waiting for more to be read if necessary.
39
+ * @param stream The stream to read from.
40
+ * @param cancellationToken A token whose cancellation will result in immediate rejection of the returned promise.
41
+ * @returns The result of reading from the stream. This will be null if the end of the stream is reached before any more can be read.
42
+ */
43
+ export function readAsync(stream: NodeJS.ReadableStream, cancellationToken?: CancellationToken): Promise<string | Buffer | null> {
44
+ return readAtMostAsync(stream, undefined, cancellationToken)
45
+ }
46
+
47
+ /**
48
+ * Reads the next chunk from a stream, asynchronously waiting for more to be read if necessary,
49
+ * without ever consuming more than a given number of bytes from the stream.
50
+ * @param stream The stream to read from.
51
+ * @param maxBytes The maximum number of bytes to consume from the stream, or `undefined` to consume whatever is immediately available.
52
+ * @param cancellationToken A token whose cancellation will result in immediate rejection of the returned promise.
53
+ * @returns The result of reading from the stream. This will be null if the end of the stream is reached before any more can be read.
54
+ */
55
+ function readAtMostAsync(stream: NodeJS.ReadableStream, maxBytes?: number, cancellationToken?: CancellationToken): Promise<string | Buffer | null> {
56
+ if (cancellationToken?.isCancelled) {
57
+ return Promise.reject(new CancellationToken.CancellationError(cancellationToken.reason))
58
+ }
59
+
60
+ // Always try a synchronous read first. Besides being faster, this avoids resuming on a later
61
+ // microtask, by which time the stream may have already emitted its 'end' event.
62
+ const initialChunk = readSyncAtMost(stream, maxBytes)
63
+ if (initialChunk !== null) {
64
+ return Promise.resolve(initialChunk)
65
+ }
66
+
67
+ const readable = stream as Readable
68
+ if (readable.errored) {
69
+ // The stream has already failed. Report it immediately rather than waiting for an
70
+ // 'error' event that may have already been emitted.
71
+ return Promise.reject(readable.errored)
72
+ }
73
+
74
+ if (readable.readableEnded || readable.destroyed) {
75
+ return Promise.resolve(null)
76
+ }
77
+
78
+ return new Promise<string | Buffer | null>((resolve, reject) => {
79
+ // Note that adding a 'readable' event handler switches the stream to paused mode, which is exactly what we want
80
+ // since we read explicitly. Node.js restores the stream's prior flowing state when the last such handler is removed,
81
+ // so this has no lasting impact on the stream for other consumers.
82
+ const ctReg = cancellationToken?.onCancelled(reason => {
83
+ cleanup()
84
+ reject(new CancellationToken.CancellationError(reason))
85
+ })
86
+ stream.on('readable', onReadable)
87
+ stream.once('error', onError)
88
+ stream.once('end', onEnd)
89
+ stream.once('close', onClose)
90
+
91
+ function onReadable() {
92
+ const chunk = readSyncAtMost(stream, maxBytes)
93
+ if (chunk !== null) {
94
+ cleanup()
95
+ resolve(chunk)
96
+ }
97
+ }
98
+
99
+ function onError(err: Error) {
100
+ cleanup()
101
+ reject(err)
102
+ }
103
+
104
+ function onEnd() {
105
+ cleanup()
106
+ resolve(null)
107
+ }
108
+
109
+ function onClose() {
110
+ cleanup()
111
+ resolve(null)
112
+ }
113
+
114
+ function cleanup() {
115
+ stream.off('readable', onReadable)
116
+ stream.off('error', onError)
117
+ stream.off('end', onEnd)
118
+ stream.off('close', onClose)
119
+ if (ctReg) {
120
+ ctReg()
121
+ }
122
+ }
123
+ })
124
+ }
125
+
126
+ /**
127
+ * Synchronously reads whatever is immediately available from a stream, without consuming more than `maxBytes` bytes.
128
+ * @param stream The stream to read from.
129
+ * @param maxBytes The maximum number of bytes to consume, or `undefined` for no limit.
130
+ * @returns The chunk that was read, or null if nothing was immediately available.
131
+ */
132
+ function readSyncAtMost(stream: NodeJS.ReadableStream, maxBytes?: number): string | Buffer | null {
133
+ if (maxBytes === undefined) {
134
+ return stream.read() as string | Buffer | null
135
+ }
136
+
137
+ if (maxBytes === 0) {
138
+ return null
139
+ }
140
+
141
+ // Only ask for as much as is already buffered so that `read` doesn't return null merely
142
+ // because fewer than `maxBytes` bytes have arrived so far.
143
+ const buffered = (stream as Readable).readableLength
144
+ return stream.read(buffered > 0 ? Math.min(buffered, maxBytes) : maxBytes) as string | Buffer | null
145
+ }
146
+
147
+ /**
148
+ * Returns a readable stream that will read just a slice of some existing stream.
149
+ * @param stream The stream to read from.
150
+ * @param length The maximum number of bytes to read from the stream.
151
+ * @returns A stream that will read up to the given number of bytes, leaving the rest in the underlying stream.
152
+ */
153
+ export function sliceStream(stream: NodeJS.ReadableStream, length: number): Readable {
154
+ // Reads that are in flight when this stream is destroyed must be cancelled so that
155
+ // they do not go on to consume data from the underlying stream that no one will receive.
156
+ const cts = CancellationToken.create()
39
157
  return new Readable({
40
158
  async read(_: number) {
41
- const lenBuffer = await getBufferFrom(stream, 4)
42
- const dv = new DataView(lenBuffer.buffer, lenBuffer.byteOffset, lenBuffer.length)
43
- const chunkSize = dv.getUint32(0, false)
44
- if (chunkSize === 0) {
45
- this.push(null)
46
- return
159
+ try {
160
+ if (length === 0) {
161
+ this.push(null)
162
+ return
163
+ }
164
+
165
+ const chunk = (await readAtMostAsync(stream, length, cts.token)) as Buffer | null
166
+ if (chunk === null) {
167
+ // We've reached the end of the source stream.
168
+ this.push(null)
169
+ return
170
+ }
171
+
172
+ length -= chunk.length
173
+ this.push(chunk)
174
+ if (length === 0) {
175
+ // Save another call later by informing immediately that we're at the end of the stream.
176
+ this.push(null)
177
+ }
178
+ } catch (err) {
179
+ this.destroy(err as Error)
47
180
  }
181
+ },
48
182
 
49
- // TODO: make this *stream* instead of read as an atomic chunk.
50
- const payload = await getBufferFrom(stream, chunkSize)
51
- this.push(payload)
183
+ destroy(error, callback) {
184
+ cts.cancel()
185
+ callback(error)
186
+ },
187
+ })
188
+ }
189
+
190
+ /**
191
+ * Returns a readable stream that reads a substream that was written with {@link writeSubstream}.
192
+ * @param stream The stream to read the substream from.
193
+ * @returns A stream that ends when the substream ends, leaving the rest of `stream` available to other readers.
194
+ */
195
+ export function readSubstream(stream: NodeJS.ReadableStream): Readable {
196
+ let bytesRemainingInChunk = 0
197
+ let reachedEnd = false
198
+
199
+ // Reads that are in flight when this stream is destroyed must be cancelled so that
200
+ // they do not go on to consume data from the underlying stream that no one will receive.
201
+ const cts = CancellationToken.create()
202
+ return new Readable({
203
+ async read(_: number) {
204
+ try {
205
+ if (reachedEnd) {
206
+ this.push(null)
207
+ return
208
+ }
209
+
210
+ if (bytesRemainingInChunk === 0) {
211
+ const lenBuffer = await getBufferFrom(stream, 4, false, cts.token)
212
+ const dv = new DataView(lenBuffer.buffer, lenBuffer.byteOffset, lenBuffer.length)
213
+ bytesRemainingInChunk = dv.getUint32(0, false)
214
+ if (bytesRemainingInChunk === 0) {
215
+ // We've reached the end of the substream.
216
+ reachedEnd = true
217
+ this.push(null)
218
+ return
219
+ }
220
+ }
221
+
222
+ // Push whatever is available rather than waiting for the entire chunk to arrive.
223
+ const payload = (await readAtMostAsync(stream, bytesRemainingInChunk, cts.token)) as Buffer | null
224
+ if (payload === null) {
225
+ throw new Error('Stream terminated before the substream was completed.')
226
+ }
227
+
228
+ bytesRemainingInChunk -= payload.length
229
+ this.push(payload)
230
+ } catch (err) {
231
+ this.destroy(err as Error)
232
+ }
233
+ },
234
+
235
+ destroy(error, callback) {
236
+ cts.cancel()
237
+ callback(error)
52
238
  },
53
239
  })
54
240
  }
@@ -73,81 +259,38 @@ export async function getBufferFrom(
73
259
  allowEndOfStream: boolean = false,
74
260
  cancellationToken?: CancellationToken
75
261
  ): Promise<Buffer | null> {
76
- const streamEnded = new Deferred<void>()
77
-
78
262
  if (size === 0) {
79
- return Buffer.from([])
263
+ return Buffer.alloc(0)
80
264
  }
81
265
 
82
- let readBuffer: Buffer | null = null
83
- let index: number = 0
84
- while (size > 0) {
266
+ let result: Buffer | null = null
267
+ let bytesRead = 0
268
+ while (bytesRead < size) {
85
269
  cancellationToken?.throwIfCancelled()
86
- let availableSize = (readable as Readable).readableLength
87
- if (!availableSize) {
88
- // Check the end of stream
89
- if ((readable as Readable).readableEnded || streamEnded.isCompleted) {
90
- // stream is closed
91
- if (!allowEndOfStream) {
92
- throw new Error('Stream terminated before required bytes were read.')
93
- }
94
-
95
- // Returns what has been read so far.
96
- if (readBuffer === null) {
97
- return null
98
- }
99
-
100
- // We need to trim the trailing space.
101
- return readBuffer.subarray(0, index)
102
- }
103
-
104
- // we retain this behavior when availableSize === false
105
- // to make existing unit tests happy (which assumes we will try to read stream when no data is ready.)
106
- availableSize = size
107
- } else if (availableSize > size) {
108
- availableSize = size
109
- }
110
-
111
- const newBuffer = readable.read(availableSize) as Buffer
112
- if (newBuffer) {
113
- if (newBuffer.length < availableSize && !allowEndOfStream) {
270
+ const chunk = (await readAtMostAsync(readable, size - bytesRead, cancellationToken)) as Buffer | null
271
+ if (chunk === null) {
272
+ // The stream ended before we could read everything that was requested.
273
+ if (!allowEndOfStream) {
114
274
  throw new Error('Stream terminated before required bytes were read.')
115
275
  }
116
276
 
117
- if (readBuffer === null) {
118
- if (availableSize === size || newBuffer.length < availableSize) {
119
- // In the fast pass, we read the entire data once, and do not allocate an extra array.
120
- return newBuffer
121
- }
122
-
123
- // If we read partial data, we need to allocate a buffer to join all data together.
124
- readBuffer = Buffer.alloc(size)
125
- }
126
-
127
- // now append new data to the buffer
128
- newBuffer.copy(readBuffer, index)
277
+ return bytesRead === 0 ? null : result!.subarray(0, bytesRead)
278
+ }
129
279
 
130
- size -= newBuffer.length
131
- index += newBuffer.length
280
+ if (result === null && chunk.length === size) {
281
+ // Fast path: the entire request was satisfied by a single read, so avoid an extra allocation and copy.
282
+ return chunk
132
283
  }
133
284
 
134
- if (size > 0) {
135
- const bytesAvailable = new Deferred<void>()
136
- const bytesAvailableCallback = bytesAvailable.resolve.bind(bytesAvailable)
137
- const streamEndedCallback = streamEnded.resolve.bind(streamEnded)
138
- readable.once('readable', bytesAvailableCallback)
139
- readable.once('end', streamEndedCallback)
140
- try {
141
- const endPromise = Promise.race([bytesAvailable.promise, streamEnded.promise])
142
- await (cancellationToken ? cancellationToken.racePromise(endPromise) : endPromise)
143
- } finally {
144
- readable.removeListener('readable', bytesAvailableCallback)
145
- readable.removeListener('end', streamEndedCallback)
146
- }
285
+ if (result === null) {
286
+ result = Buffer.alloc(size)
147
287
  }
288
+
289
+ chunk.copy(result, bytesRead)
290
+ bytesRead += chunk.length
148
291
  }
149
292
 
150
- return readBuffer
293
+ return result
151
294
  }
152
295
 
153
296
  export function throwIfDisposed(value: IDisposableObservable) {
package/src/index.ts CHANGED
@@ -4,5 +4,5 @@ export { FullDuplexStream } from './FullDuplexStream'
4
4
  export { IDisposableObservable } from './IDisposableObservable'
5
5
  export { MultiplexingStream } from './MultiplexingStream'
6
6
  export { MultiplexingStreamOptions } from './MultiplexingStreamOptions'
7
- export { writeSubstream, readSubstream } from './Utilities'
7
+ export { writeSubstream, readSubstream, readAsync, sliceStream } from './Utilities'
8
8
  export { QualifiedChannelId, ChannelSource } from './QualifiedChannelId'