nerdbank-streams 2.11.86 → 2.12.84-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.
@@ -1,21 +1,21 @@
1
- import { ChannelOptions } from './ChannelOptions'
2
-
3
- export interface MultiplexingStreamOptions {
4
- /**
5
- * The protocol version to be used.
6
- * @description 1 is the original version. 2 is a protocol breaking change and adds backpressure support. 3 is a protocol breaking change, eliminates the handshake packet and adds seeded channels support.
7
- */
8
- protocolMajorVersion?: number
9
-
10
- /** The number of received bytes that may be buffered locally per channel (transmitted from the remote party but not yet processed). */
11
- defaultChannelReceivingWindowSize?: number
12
-
13
- /**
14
- * A list of options for channels that are to be "seeded" into a new MultiplexingStream.
15
- * @description Seeded channels avoid the need for a round-trip for an offer/accept packet exchange.
16
- * Seeded channels are accessed within the MultiplexingStream instance by calling AcceptChannel(ulong, ChannelOptions?)
17
- * with the 0-based index into this list used as the channel ID.
18
- * They are only supported when ProtocolMajorVersion is at least 3.
19
- */
20
- seededChannels?: ChannelOptions[]
21
- }
1
+ import { ChannelOptions } from './ChannelOptions'
2
+
3
+ export interface MultiplexingStreamOptions {
4
+ /**
5
+ * The protocol version to be used.
6
+ * @description 1 is the original version. 2 is a protocol breaking change and adds backpressure support. 3 is a protocol breaking change, eliminates the handshake packet and adds seeded channels support.
7
+ */
8
+ protocolMajorVersion?: number
9
+
10
+ /** The number of received bytes that may be buffered locally per channel (transmitted from the remote party but not yet processed). */
11
+ defaultChannelReceivingWindowSize?: number
12
+
13
+ /**
14
+ * A list of options for channels that are to be "seeded" into a new MultiplexingStream.
15
+ * @description Seeded channels avoid the need for a round-trip for an offer/accept packet exchange.
16
+ * Seeded channels are accessed within the MultiplexingStream instance by calling AcceptChannel(ulong, ChannelOptions?)
17
+ * with the 0-based index into this list used as the channel ID.
18
+ * They are only supported when ProtocolMajorVersion is at least 3.
19
+ */
20
+ seededChannels?: ChannelOptions[]
21
+ }
@@ -1,7 +1,7 @@
1
- export interface OfferParameters {
2
- /** The name of the channel. */
3
- name: string
4
-
5
- /** The maximum number of bytes that may be transmitted and not yet acknowledged as processed by the remote party. */
6
- remoteWindowSize?: number
7
- }
1
+ export interface OfferParameters {
2
+ /** The name of the channel. */
3
+ name: string
4
+
5
+ /** The maximum number of bytes that may be transmitted and not yet acknowledged as processed by the remote party. */
6
+ remoteWindowSize?: number
7
+ }
@@ -1,44 +1,44 @@
1
- export interface QualifiedChannelId {
2
- /** Gets the channel ID. */
3
- readonly id: number
4
-
5
- /** Gets a value indicating where the channel originated. */
6
- readonly source: ChannelSource
7
- }
8
-
9
- /**
10
- * An enumeration of the possible sources of a channel.
11
- * @description The ordinal values are chosen so as to make flipping the perspective as easy as negating the value,
12
- * while leaving the Seeded value unchanged.
13
- */
14
- export enum ChannelSource {
15
- /** The channel was offered by this MultiplexingStream instance to the other party. */
16
- // eslint-disable-next-line @typescript-eslint/naming-convention
17
- Local = 1,
18
-
19
- /** The channel was offered to this MultiplexingStream instance by the other party. */
20
- // eslint-disable-next-line @typescript-eslint/naming-convention
21
- Remote = -1,
22
-
23
- /**
24
- * The channel was seeded during construction via the Options.SeededChannels collection.
25
- * This channel is to be accepted by both parties.
26
- */
27
- // eslint-disable-next-line @typescript-eslint/naming-convention
28
- Seeded = 0,
29
- }
30
-
31
- // tslint:disable-next-line: no-namespace
32
- export namespace QualifiedChannelId {
33
- export function toString(id: QualifiedChannelId): string {
34
- const sourceName =
35
- id.source === ChannelSource.Local
36
- ? 'local'
37
- : id.source === ChannelSource.Remote
38
- ? 'remote'
39
- : id.source === ChannelSource.Seeded
40
- ? 'seeded'
41
- : 'unknown'
42
- return `${id.id} (${sourceName})`
43
- }
44
- }
1
+ export interface QualifiedChannelId {
2
+ /** Gets the channel ID. */
3
+ readonly id: number
4
+
5
+ /** Gets a value indicating where the channel originated. */
6
+ readonly source: ChannelSource
7
+ }
8
+
9
+ /**
10
+ * An enumeration of the possible sources of a channel.
11
+ * @description The ordinal values are chosen so as to make flipping the perspective as easy as negating the value,
12
+ * while leaving the Seeded value unchanged.
13
+ */
14
+ export enum ChannelSource {
15
+ /** The channel was offered by this MultiplexingStream instance to the other party. */
16
+ // eslint-disable-next-line @typescript-eslint/naming-convention
17
+ Local = 1,
18
+
19
+ /** The channel was offered to this MultiplexingStream instance by the other party. */
20
+ // eslint-disable-next-line @typescript-eslint/naming-convention
21
+ Remote = -1,
22
+
23
+ /**
24
+ * The channel was seeded during construction via the Options.SeededChannels collection.
25
+ * This channel is to be accepted by both parties.
26
+ */
27
+ // eslint-disable-next-line @typescript-eslint/naming-convention
28
+ Seeded = 0,
29
+ }
30
+
31
+ // tslint:disable-next-line: no-namespace
32
+ export namespace QualifiedChannelId {
33
+ export function toString(id: QualifiedChannelId): string {
34
+ const sourceName =
35
+ id.source === ChannelSource.Local
36
+ ? 'local'
37
+ : id.source === ChannelSource.Remote
38
+ ? 'remote'
39
+ : id.source === ChannelSource.Seeded
40
+ ? 'seeded'
41
+ : 'unknown'
42
+ return `${id.id} (${sourceName})`
43
+ }
44
+ }
package/src/Utilities.ts CHANGED
@@ -1,183 +1,183 @@
1
- import CancellationToken from 'cancellationtoken'
2
- import { Readable, Writable } from 'stream'
3
- import { Deferred } from './Deferred'
4
- import { IDisposableObservable } from './IDisposableObservable'
5
-
6
- export async function writeAsync(stream: NodeJS.WritableStream, chunk: any) {
7
- return new Promise<void>((resolve, reject) => {
8
- stream.write(chunk, (err: Error | null | undefined) => {
9
- if (err) {
10
- reject(err)
11
- } else {
12
- resolve()
13
- }
14
- })
15
- })
16
- }
17
-
18
- export function writeSubstream(stream: NodeJS.WritableStream): NodeJS.WritableStream {
19
- return new Writable({
20
- async write(chunk: Buffer, _: string, callback: (error?: Error | null) => void) {
21
- try {
22
- const dv = new DataView(new ArrayBuffer(4))
23
- dv.setUint32(0, chunk.length, false)
24
- await writeAsync(stream, Buffer.from(dv.buffer))
25
- await writeAsync(stream, chunk)
26
- callback()
27
- } catch (err) {
28
- callback(err as Error)
29
- }
30
- },
31
- final(callback: (error?: Error | null) => void) {
32
- // Write the terminating 0 length sequence.
33
- stream.write(new Uint8Array(4), callback)
34
- },
35
- })
36
- }
37
-
38
- export function readSubstream(stream: NodeJS.ReadableStream): NodeJS.ReadableStream {
39
- return new Readable({
40
- 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
47
- }
48
-
49
- // TODO: make this *stream* instead of read as an atomic chunk.
50
- const payload = await getBufferFrom(stream, chunkSize)
51
- this.push(payload)
52
- },
53
- })
54
- }
55
-
56
- export async function getBufferFrom(
57
- readable: NodeJS.ReadableStream,
58
- size: number,
59
- allowEndOfStream?: false,
60
- cancellationToken?: CancellationToken
61
- ): Promise<Buffer>
62
-
63
- export async function getBufferFrom(
64
- readable: NodeJS.ReadableStream,
65
- size: number,
66
- allowEndOfStream: true,
67
- cancellationToken?: CancellationToken
68
- ): Promise<Buffer | null>
69
-
70
- export async function getBufferFrom(
71
- readable: NodeJS.ReadableStream,
72
- size: number,
73
- allowEndOfStream: boolean = false,
74
- cancellationToken?: CancellationToken
75
- ): Promise<Buffer | null> {
76
- const streamEnded = new Deferred<void>()
77
-
78
- if (size === 0) {
79
- return Buffer.from([])
80
- }
81
-
82
- let readBuffer: Buffer | null = null
83
- let index: number = 0
84
- while (size > 0) {
85
- 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) {
114
- throw new Error('Stream terminated before required bytes were read.')
115
- }
116
-
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)
129
-
130
- size -= newBuffer.length
131
- index += newBuffer.length
132
- }
133
-
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
- }
147
- }
148
- }
149
-
150
- return readBuffer
151
- }
152
-
153
- export function throwIfDisposed(value: IDisposableObservable) {
154
- if (value.isDisposed) {
155
- throw new Error('disposed')
156
- }
157
- }
158
-
159
- export function requireInteger(parameterName: string, value: number, serializedByteLength: number, signed: 'unsigned' | 'signed' = 'signed'): void {
160
- if (!Number.isInteger(value)) {
161
- throw new Error(`${parameterName} must be an integer.`)
162
- }
163
-
164
- let bits = serializedByteLength * 8
165
- if (signed === 'signed') {
166
- bits--
167
- }
168
-
169
- const maxValue = Math.pow(2, bits) - 1
170
- const minValue = signed === 'signed' ? -Math.pow(2, bits) : 0
171
- if (value > maxValue || value < minValue) {
172
- throw new Error(`${parameterName} must be in the range ${minValue}-${maxValue}.`)
173
- }
174
- }
175
-
176
- export function removeFromQueue<T>(value: T, queue: T[]) {
177
- if (queue) {
178
- const idx = queue.indexOf(value)
179
- if (idx >= 0) {
180
- queue.splice(idx, 1)
181
- }
182
- }
183
- }
1
+ import CancellationToken from 'cancellationtoken'
2
+ import { Readable, Writable } from 'stream'
3
+ import { Deferred } from './Deferred'
4
+ import { IDisposableObservable } from './IDisposableObservable'
5
+
6
+ export async function writeAsync(stream: NodeJS.WritableStream, chunk: any) {
7
+ return new Promise<void>((resolve, reject) => {
8
+ stream.write(chunk, (err: Error | null | undefined) => {
9
+ if (err) {
10
+ reject(err)
11
+ } else {
12
+ resolve()
13
+ }
14
+ })
15
+ })
16
+ }
17
+
18
+ export function writeSubstream(stream: NodeJS.WritableStream): NodeJS.WritableStream {
19
+ return new Writable({
20
+ async write(chunk: Buffer, _: string, callback: (error?: Error | null) => void) {
21
+ try {
22
+ const dv = new DataView(new ArrayBuffer(4))
23
+ dv.setUint32(0, chunk.length, false)
24
+ await writeAsync(stream, Buffer.from(dv.buffer))
25
+ await writeAsync(stream, chunk)
26
+ callback()
27
+ } catch (err) {
28
+ callback(err as Error)
29
+ }
30
+ },
31
+ final(callback: (error?: Error | null) => void) {
32
+ // Write the terminating 0 length sequence.
33
+ stream.write(new Uint8Array(4), callback)
34
+ },
35
+ })
36
+ }
37
+
38
+ export function readSubstream(stream: NodeJS.ReadableStream): NodeJS.ReadableStream {
39
+ return new Readable({
40
+ 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
47
+ }
48
+
49
+ // TODO: make this *stream* instead of read as an atomic chunk.
50
+ const payload = await getBufferFrom(stream, chunkSize)
51
+ this.push(payload)
52
+ },
53
+ })
54
+ }
55
+
56
+ export async function getBufferFrom(
57
+ readable: NodeJS.ReadableStream,
58
+ size: number,
59
+ allowEndOfStream?: false,
60
+ cancellationToken?: CancellationToken
61
+ ): Promise<Buffer>
62
+
63
+ export async function getBufferFrom(
64
+ readable: NodeJS.ReadableStream,
65
+ size: number,
66
+ allowEndOfStream: true,
67
+ cancellationToken?: CancellationToken
68
+ ): Promise<Buffer | null>
69
+
70
+ export async function getBufferFrom(
71
+ readable: NodeJS.ReadableStream,
72
+ size: number,
73
+ allowEndOfStream: boolean = false,
74
+ cancellationToken?: CancellationToken
75
+ ): Promise<Buffer | null> {
76
+ const streamEnded = new Deferred<void>()
77
+
78
+ if (size === 0) {
79
+ return Buffer.from([])
80
+ }
81
+
82
+ let readBuffer: Buffer | null = null
83
+ let index: number = 0
84
+ while (size > 0) {
85
+ 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) {
114
+ throw new Error('Stream terminated before required bytes were read.')
115
+ }
116
+
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)
129
+
130
+ size -= newBuffer.length
131
+ index += newBuffer.length
132
+ }
133
+
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
+ }
147
+ }
148
+ }
149
+
150
+ return readBuffer
151
+ }
152
+
153
+ export function throwIfDisposed(value: IDisposableObservable) {
154
+ if (value.isDisposed) {
155
+ throw new Error('disposed')
156
+ }
157
+ }
158
+
159
+ export function requireInteger(parameterName: string, value: number, serializedByteLength: number, signed: 'unsigned' | 'signed' = 'signed'): void {
160
+ if (!Number.isInteger(value)) {
161
+ throw new Error(`${parameterName} must be an integer.`)
162
+ }
163
+
164
+ let bits = serializedByteLength * 8
165
+ if (signed === 'signed') {
166
+ bits--
167
+ }
168
+
169
+ const maxValue = Math.pow(2, bits) - 1
170
+ const minValue = signed === 'signed' ? -Math.pow(2, bits) : 0
171
+ if (value > maxValue || value < minValue) {
172
+ throw new Error(`${parameterName} must be in the range ${minValue}-${maxValue}.`)
173
+ }
174
+ }
175
+
176
+ export function removeFromQueue<T>(value: T, queue: T[]) {
177
+ if (queue) {
178
+ const idx = queue.indexOf(value)
179
+ if (idx >= 0) {
180
+ queue.splice(idx, 1)
181
+ }
182
+ }
183
+ }
package/src/index.ts CHANGED
@@ -1,8 +1,8 @@
1
- export { Channel } from './Channel'
2
- export { ChannelOptions } from './ChannelOptions'
3
- export { FullDuplexStream } from './FullDuplexStream'
4
- export { IDisposableObservable } from './IDisposableObservable'
5
- export { MultiplexingStream } from './MultiplexingStream'
6
- export { MultiplexingStreamOptions } from './MultiplexingStreamOptions'
7
- export { writeSubstream, readSubstream } from './Utilities'
8
- export { QualifiedChannelId, ChannelSource } from './QualifiedChannelId'
1
+ export { Channel } from './Channel'
2
+ export { ChannelOptions } from './ChannelOptions'
3
+ export { FullDuplexStream } from './FullDuplexStream'
4
+ export { IDisposableObservable } from './IDisposableObservable'
5
+ export { MultiplexingStream } from './MultiplexingStream'
6
+ export { MultiplexingStreamOptions } from './MultiplexingStreamOptions'
7
+ export { writeSubstream, readSubstream } from './Utilities'
8
+ export { QualifiedChannelId, ChannelSource } from './QualifiedChannelId'