nerdbank-streams 2.11.86 → 2.12.74-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,761 +1,761 @@
1
- /* TODO:
2
- * Tracing
3
- * Auto-terminate channels when both ends have finished writing (AutoCloseOnPipesClosureAsync)
4
- */
5
-
6
- import { Semaphore } from 'await-semaphore'
7
- import CancellationToken from 'cancellationtoken'
8
- import { EventEmitter } from 'events'
9
- import { Channel, ChannelClass } from './Channel'
10
- import { ChannelOptions } from './ChannelOptions'
11
- import { ControlCode } from './ControlCode'
12
- import { Deferred } from './Deferred'
13
- import { FrameHeader } from './FrameHeader'
14
- import { IChannelOfferEventArgs } from './IChannelOfferEventArgs'
15
- import { IDisposableObservable } from './IDisposableObservable'
16
- import {
17
- MultiplexingStreamFormatter,
18
- MultiplexingStreamV1Formatter,
19
- MultiplexingStreamV2Formatter,
20
- MultiplexingStreamV3Formatter,
21
- } from './MultiplexingStreamFormatters'
22
- import './MultiplexingStreamOptions'
23
- import { MultiplexingStreamOptions } from './MultiplexingStreamOptions'
24
- import { OfferParameters } from './OfferParameters'
25
- import { ChannelSource, QualifiedChannelId } from './QualifiedChannelId'
26
- import { removeFromQueue, throwIfDisposed } from './Utilities'
27
- import caught = require('caught')
28
-
29
- export abstract class MultiplexingStream implements IDisposableObservable {
30
- /**
31
- * The maximum length of a frame's payload.
32
- */
33
- static readonly framePayloadMaxLength = 20 * 1024
34
-
35
- private static readonly recommendedDefaultChannelReceivingWindowSize = 5 * MultiplexingStream.framePayloadMaxLength
36
-
37
- /** The default window size used for new channels that do not specify a value for ChannelOptions.ChannelReceivingWindowSize. */
38
- readonly defaultChannelReceivingWindowSize: number
39
-
40
- protected get disposalToken() {
41
- return this.disposalTokenSource.token
42
- }
43
-
44
- /**
45
- * Gets a promise that is resolved or rejected based on how this stream is disposed or fails.
46
- */
47
- public get completion(): Promise<void> {
48
- return this._completionSource.promise
49
- }
50
-
51
- /**
52
- * Gets a value indicating whether this instance has been disposed.
53
- */
54
- public get isDisposed(): boolean {
55
- return this.disposalTokenSource.token.isCancelled
56
- }
57
-
58
- /**
59
- * Initializes a new instance of the `MultiplexingStream` class.
60
- * @param stream The duplex stream to read and write to.
61
- * Use `FullDuplexStream.Splice` if you have distinct input/output streams.
62
- * @param options Options to customize the behavior of the stream.
63
- * @param cancellationToken A token whose cancellation aborts the handshake with the remote end.
64
- * @returns The multiplexing stream, once the handshake is complete.
65
- */
66
- // eslint-disable-next-line @typescript-eslint/naming-convention
67
- public static async CreateAsync(
68
- stream: NodeJS.ReadWriteStream,
69
- options?: MultiplexingStreamOptions,
70
- cancellationToken: CancellationToken = CancellationToken.CONTINUE
71
- ): Promise<MultiplexingStream> {
72
- if (!stream) {
73
- throw new Error('stream must be specified.')
74
- }
75
-
76
- options = options || {}
77
- options.protocolMajorVersion ??= 1
78
- options.defaultChannelReceivingWindowSize = options.defaultChannelReceivingWindowSize || MultiplexingStream.recommendedDefaultChannelReceivingWindowSize
79
- if (options.protocolMajorVersion < 3 && options.seededChannels && options.seededChannels.length > 0) {
80
- throw new Error('Seeded channels require v3 of the protocol at least.')
81
- }
82
-
83
- // Send the protocol magic number, and a random 16-byte number to establish even/odd assignments.
84
- const formatter: MultiplexingStreamFormatter | undefined =
85
- options.protocolMajorVersion === 1
86
- ? new MultiplexingStreamV1Formatter(stream)
87
- : options.protocolMajorVersion === 2
88
- ? new MultiplexingStreamV2Formatter(stream)
89
- : options.protocolMajorVersion === 3
90
- ? new MultiplexingStreamV3Formatter(stream)
91
- : undefined
92
- if (!formatter) {
93
- throw new Error(`Protocol major version ${options.protocolMajorVersion} is not supported.`)
94
- }
95
-
96
- const writeHandshakeData = await formatter.writeHandshakeAsync()
97
- const handshakeResult = await formatter.readHandshakeAsync(writeHandshakeData, cancellationToken)
98
- formatter.isOdd = handshakeResult.isOdd
99
-
100
- return new MultiplexingStreamClass(formatter, handshakeResult.isOdd, options)
101
- }
102
-
103
- /**
104
- * Initializes a new instance of the `MultiplexingStream` class
105
- * with protocolMajorVersion set to 3.
106
- * @param stream The duplex stream to read and write to.
107
- * Use `FullDuplexStream.Splice` if you have distinct input/output streams.
108
- * @param options Options to customize the behavior of the stream.
109
- * @returns The multiplexing stream.
110
- */
111
- // eslint-disable-next-line @typescript-eslint/naming-convention
112
- public static Create(stream: NodeJS.ReadWriteStream, options?: MultiplexingStreamOptions): MultiplexingStream {
113
- options ??= { protocolMajorVersion: 3 }
114
- options.protocolMajorVersion ??= 3
115
-
116
- const formatter: MultiplexingStreamFormatter | undefined = options.protocolMajorVersion === 3 ? new MultiplexingStreamV3Formatter(stream) : undefined
117
- if (!formatter) {
118
- throw new Error(`Protocol major version ${options.protocolMajorVersion} is not supported. Try CreateAsync instead.`)
119
- }
120
-
121
- return new MultiplexingStreamClass(formatter, undefined, options)
122
- }
123
-
124
- /**
125
- * The options to use for channels we create in response to incoming offers.
126
- * @description Whatever these settings are, they can be replaced when the channel is accepted.
127
- */
128
- protected static readonly defaultChannelOptions: ChannelOptions = {}
129
-
130
- /**
131
- * The encoding used for characters in control frames.
132
- */
133
- // eslint-disable-next-line @typescript-eslint/naming-convention
134
- static readonly ControlFrameEncoding = 'utf-8'
135
-
136
- protected readonly _completionSource = new Deferred<void>()
137
-
138
- /**
139
- * A dictionary of channels that were seeded, keyed by their ID.
140
- */
141
- protected readonly seededOpenChannels: { [id: number]: ChannelClass } = {}
142
-
143
- /**
144
- * A dictionary of channels that were offered locally, keyed by their ID.
145
- */
146
- protected readonly locallyOfferedOpenChannels: { [id: number]: ChannelClass } = {}
147
-
148
- /**
149
- * A dictionary of channels that were offered remotely, keyed by their ID.
150
- */
151
- protected readonly remotelyOfferedOpenChannels: { [id: number]: ChannelClass } = {}
152
-
153
- /**
154
- * The last number assigned to a channel.
155
- * Each use of this should increment by two if isOdd is defined.
156
- * It should never exceed uint32.MaxValue
157
- */
158
- protected abstract lastOfferedChannelId: number
159
-
160
- /**
161
- * A map of channel names to queues of channels waiting for local acceptance.
162
- */
163
- protected readonly channelsOfferedByThemByName: { [name: string]: ChannelClass[] } = {}
164
-
165
- /**
166
- * A map of channel names to queues of Deferred<Channel> from waiting accepters.
167
- */
168
- protected readonly acceptingChannels: { [name: string]: Deferred<ChannelClass>[] } = {}
169
-
170
- /** The major version of the protocol being used for this connection. */
171
- protected readonly protocolMajorVersion: number
172
-
173
- private readonly eventEmitter = new EventEmitter()
174
-
175
- private disposalTokenSource = CancellationToken.create()
176
-
177
- protected constructor(
178
- protected readonly formatter: MultiplexingStreamFormatter,
179
- private readonly isOdd: boolean | undefined,
180
- options: MultiplexingStreamOptions
181
- ) {
182
- this.defaultChannelReceivingWindowSize = options.defaultChannelReceivingWindowSize ?? MultiplexingStream.recommendedDefaultChannelReceivingWindowSize
183
- this.protocolMajorVersion = options.protocolMajorVersion ?? 1
184
-
185
- if (options.seededChannels) {
186
- for (let i = 0; i < options.seededChannels.length; i++) {
187
- const channelOptions = options.seededChannels[i]
188
- const id = { id: i, source: ChannelSource.Seeded }
189
- this.setOpenChannel(
190
- new ChannelClass(this as unknown as MultiplexingStreamClass, id, {
191
- name: '',
192
- remoteWindowSize: channelOptions.channelReceivingWindowSize ?? this.defaultChannelReceivingWindowSize,
193
- })
194
- )
195
- }
196
- }
197
- }
198
-
199
- /**
200
- * Creates an anonymous channel that may be accepted by <see cref="AcceptChannel(int, ChannelOptions)"/>.
201
- * Its existance must be communicated by other means (typically another, existing channel) to encourage acceptance.
202
- * @param options A set of options that describe local treatment of this channel.
203
- * @returns The anonymous channel.
204
- * @description Note that while the channel is created immediately, any local write to that channel will be
205
- * buffered locally until the remote party accepts the channel.
206
- */
207
- public createChannel(options?: ChannelOptions): Channel {
208
- const offerParameters: OfferParameters = {
209
- name: '',
210
- remoteWindowSize: options?.channelReceivingWindowSize ?? this.defaultChannelReceivingWindowSize,
211
- }
212
- const payload = this.formatter.serializeOfferParameters(offerParameters)
213
- const channel = new ChannelClass(
214
- this as any as MultiplexingStreamClass,
215
- { id: this.getUnusedChannelId(), source: ChannelSource.Local },
216
- offerParameters
217
- )
218
- this.setOpenChannel(channel)
219
-
220
- this.rejectOnFailure(this.sendFrameAsync(new FrameHeader(ControlCode.offer, channel.qualifiedId), payload, this.disposalToken))
221
- return channel
222
- }
223
-
224
- /**
225
- * Accepts a channel with a specific ID.
226
- * @param id The id of the channel to accept.
227
- * @param options A set of options that describe local treatment of this channel.
228
- * @description This method can be used to accept anonymous channels created with <see cref="CreateChannel"/>.
229
- * Unlike <see cref="AcceptChannelAsync(string, ChannelOptions, CancellationToken)"/> which will await
230
- * for a channel offer if a matching one has not been made yet, this method only accepts an offer
231
- * for a channel that has already been made.
232
- */
233
- public acceptChannel(id: number, options?: ChannelOptions): Channel {
234
- const channel = this.remotelyOfferedOpenChannels[id] || this.seededOpenChannels[id]
235
- if (!channel) {
236
- throw new Error('No channel with ID ' + id)
237
- }
238
-
239
- this.removeChannelFromOfferedQueue(channel)
240
-
241
- this.acceptChannelOrThrow(channel, options)
242
- return channel
243
- }
244
-
245
- /**
246
- * Rejects an offer for the channel with a specified ID.
247
- * @param id The ID of the channel whose offer should be rejected.
248
- */
249
- public rejectChannel(id: number) {
250
- const channel = this.remotelyOfferedOpenChannels[id]
251
- if (channel) {
252
- removeFromQueue(channel, this.channelsOfferedByThemByName[channel.name])
253
- } else {
254
- throw new Error('No channel with that ID found.')
255
- }
256
-
257
- // Rejecting a channel rejects a couple promises that we don't want the caller to have to observe
258
- // separately since they are explicitly stating they want to take this action now.
259
- caught(channel.acceptance)
260
- caught(channel.completion)
261
-
262
- channel.dispose()
263
- }
264
-
265
- /**
266
- * Offers a new, named channel to the remote party so they may accept it with
267
- * {@link acceptChannelAsync}.
268
- * @param name A name for the channel, which must be accepted on the remote end to complete creation.
269
- * It need not be unique, and may be empty but must not be null.
270
- * Any characters are allowed, and max length is determined by the maximum frame payload (based on UTF-8 encoding).
271
- * @param options A set of options that describe local treatment of this channel.
272
- * @param cancellationToken A cancellation token. Do NOT let this be a long-lived token
273
- * or a memory leak will result since we add continuations to its promise.
274
- * @returns A task that completes with the `Channel` if the offer is accepted on the remote end
275
- * or faults with `MultiplexingProtocolException` if the remote end rejects the channel.
276
- */
277
- public async offerChannelAsync(
278
- name: string,
279
- options?: ChannelOptions,
280
- cancellationToken: CancellationToken = CancellationToken.CONTINUE
281
- ): Promise<Channel> {
282
- if (name === null || name === undefined) {
283
- throw new Error('Name must be specified (but may be empty).')
284
- }
285
-
286
- cancellationToken.throwIfCancelled()
287
- throwIfDisposed(this)
288
-
289
- const offerParameters: OfferParameters = {
290
- name,
291
- remoteWindowSize: options?.channelReceivingWindowSize ?? this.defaultChannelReceivingWindowSize,
292
- }
293
- const payload = this.formatter.serializeOfferParameters(offerParameters)
294
- const channel = new ChannelClass(
295
- this as any as MultiplexingStreamClass,
296
- { id: this.getUnusedChannelId(), source: ChannelSource.Local },
297
- offerParameters
298
- )
299
- this.setOpenChannel(channel)
300
-
301
- const header = new FrameHeader(ControlCode.offer, channel.qualifiedId)
302
-
303
- const unsubscribeFromCT = cancellationToken.onCancelled(reason => this.offerChannelCanceled(channel, reason))
304
- try {
305
- // We *will* recognize rejection of this promise. But just in case sendFrameAsync completes synchronously,
306
- // we want to signify that we *will* catch it first to avoid node.js emitting warnings or crashing.
307
- caught(channel.acceptance)
308
-
309
- await this.sendFrameAsync(header, payload, cancellationToken)
310
- await channel.acceptance
311
-
312
- return channel
313
- } finally {
314
- unsubscribeFromCT()
315
- }
316
- }
317
-
318
- /**
319
- * Accepts a channel that the remote end has attempted or may attempt to create.
320
- * @param name The name of the channel to accept.
321
- * An empty string will match an offer made via {@link offerChannelAsync} with an empty channel name.
322
- * It will also match an anonymous channel offer made with {@link createChannel}.
323
- * @param options A set of options that describe local treatment of this channel.
324
- * @param cancellationToken A token to indicate lost interest in accepting the channel.
325
- * Do NOT let this be a long-lived token
326
- * or a memory leak will result since we add continuations to its promise.
327
- * @returns The `Channel`, after its offer has been received from the remote party and accepted.
328
- * @description If multiple offers exist with the specified `name`, the first one received will be accepted.
329
- */
330
- public async acceptChannelAsync(
331
- name: string,
332
- options?: ChannelOptions,
333
- cancellationToken: CancellationToken = CancellationToken.CONTINUE
334
- ): Promise<Channel> {
335
- if (name === null || name === undefined) {
336
- throw new Error('Name must be specified (but may be empty).')
337
- }
338
-
339
- cancellationToken.throwIfCancelled()
340
- throwIfDisposed(this)
341
-
342
- let channel: ChannelClass | undefined
343
- let pendingAcceptChannel: Deferred<ChannelClass>
344
- const channelsOfferedByThem = this.channelsOfferedByThemByName[name] as ChannelClass[]
345
- if (channelsOfferedByThem) {
346
- while (channel === undefined && channelsOfferedByThem.length > 0) {
347
- channel = channelsOfferedByThem.shift()!
348
- if (channel.isAccepted || channel.isRejectedOrCanceled) {
349
- channel = undefined
350
- continue
351
- }
352
- }
353
- }
354
-
355
- if (channel === undefined) {
356
- let acceptingChannels = this.acceptingChannels[name]
357
- if (!acceptingChannels) {
358
- this.acceptingChannels[name] = acceptingChannels = []
359
- }
360
-
361
- pendingAcceptChannel = new Deferred<ChannelClass>(options)
362
- acceptingChannels.push(pendingAcceptChannel)
363
- }
364
-
365
- if (channel !== undefined) {
366
- this.acceptChannelOrThrow(channel, options)
367
- return channel
368
- } else {
369
- const unsubscribeFromCT = cancellationToken.onCancelled(reason => this.acceptChannelCanceled(pendingAcceptChannel, name, reason))
370
- try {
371
- return await pendingAcceptChannel!.promise
372
- } finally {
373
- unsubscribeFromCT()
374
- }
375
- }
376
- }
377
-
378
- /**
379
- * Disposes the stream.
380
- */
381
- public dispose() {
382
- this.disposeCore(false)
383
- }
384
-
385
- protected disposeCore(remoteDisconnect: boolean) {
386
- this.disposalTokenSource.cancel()
387
- this._completionSource.resolve()
388
-
389
- this.formatter.end()
390
- ;[this.locallyOfferedOpenChannels, this.remotelyOfferedOpenChannels].forEach(cb => {
391
- for (const channelId in cb) {
392
- if (cb.hasOwnProperty(channelId)) {
393
- const channel = cb[channelId]
394
-
395
- // Acceptance gets rejected when a channel is disposed.
396
- // Avoid a node.js crash or test failure for unobserved channels (e.g. offers for channels from the other party that no one cared to receive on this side).
397
- caught(channel.acceptance)
398
-
399
- channel.dispose()
400
- }
401
- }
402
- })
403
-
404
- // Iterate over acceptingChannels to reject each promise
405
- const errorMessage = remoteDisconnect ? 'The remote party has disconnected.' : 'The stream is being disposed locally.'
406
- for (const name in this.acceptingChannels) {
407
- if (this.acceptingChannels.hasOwnProperty(name)) {
408
- const acceptingChannels = this.acceptingChannels[name]
409
- for (const channelDeferral of acceptingChannels) {
410
- channelDeferral.reject(new Error(errorMessage))
411
- }
412
-
413
- delete this.acceptingChannels[name]
414
- }
415
- }
416
- }
417
-
418
- public on(event: 'channelOffered', listener: (args: IChannelOfferEventArgs) => void) {
419
- this.eventEmitter.on(event, listener)
420
- }
421
-
422
- public off(event: 'channelOffered', listener: (args: IChannelOfferEventArgs) => void) {
423
- this.eventEmitter.off(event, listener)
424
- }
425
-
426
- public once(event: 'channelOffered', listener: (args: IChannelOfferEventArgs) => void) {
427
- this.eventEmitter.once(event, listener)
428
- }
429
-
430
- protected raiseChannelOffered(id: number, name: string, isAccepted: boolean) {
431
- const args: IChannelOfferEventArgs = {
432
- id,
433
- isAccepted,
434
- name,
435
- }
436
- try {
437
- this.eventEmitter.emit('channelOffered', args)
438
- } catch (err) {
439
- this._completionSource.reject(err)
440
- }
441
- }
442
-
443
- protected abstract sendFrameAsync(header: FrameHeader, payload: Buffer, cancellationToken: CancellationToken): Promise<void>
444
-
445
- protected abstract sendFrame(code: ControlCode, channelId: QualifiedChannelId): Promise<void>
446
-
447
- protected acceptChannelOrThrow(channel: ChannelClass, options?: ChannelOptions) {
448
- if (channel.tryAcceptOffer(options)) {
449
- const acceptanceParameters = {
450
- remoteWindowSize: options?.channelReceivingWindowSize ?? channel.localWindowSize ?? this.defaultChannelReceivingWindowSize,
451
- }
452
- if (acceptanceParameters.remoteWindowSize < this.defaultChannelReceivingWindowSize) {
453
- acceptanceParameters.remoteWindowSize = this.defaultChannelReceivingWindowSize
454
- }
455
-
456
- if (channel.qualifiedId.source !== ChannelSource.Seeded) {
457
- const payload = this.formatter.serializeAcceptanceParameters(acceptanceParameters)
458
- this.rejectOnFailure(this.sendFrameAsync(new FrameHeader(ControlCode.offerAccepted, channel.qualifiedId), payload, this.disposalToken))
459
- }
460
- } else if (channel.isAccepted) {
461
- throw new Error('Channel is already accepted.')
462
- } else if (channel.isRejectedOrCanceled) {
463
- throw new Error('Channel is no longer available for acceptance.')
464
- } else {
465
- throw new Error('Channel could not be accepted.')
466
- }
467
- }
468
-
469
- /**
470
- * Disposes this instance if the specified promise is rejected.
471
- * @param promise The promise to check for failures.
472
- */
473
- protected async rejectOnFailure<T>(promise: Promise<T>) {
474
- try {
475
- await promise
476
- } catch (err) {
477
- this._completionSource.reject(err)
478
- }
479
- }
480
-
481
- protected removeChannelFromOfferedQueue(channel: ChannelClass) {
482
- if (channel.name) {
483
- removeFromQueue(channel, this.channelsOfferedByThemByName[channel.name])
484
- }
485
- }
486
-
487
- protected getOpenChannel(qualifiedId: QualifiedChannelId): ChannelClass | undefined {
488
- return this.getChannelCollection(qualifiedId.source)[qualifiedId.id]
489
- }
490
-
491
- protected setOpenChannel(channel: ChannelClass) {
492
- this.getChannelCollection(channel.qualifiedId.source)[channel.qualifiedId.id] = channel
493
- }
494
-
495
- protected deleteOpenChannel(qualifiedId: QualifiedChannelId) {
496
- delete this.getChannelCollection(qualifiedId.source)[qualifiedId.id]
497
- }
498
-
499
- private getChannelCollection(source: ChannelSource): { [id: number]: ChannelClass } {
500
- switch (source) {
501
- case ChannelSource.Local:
502
- return this.locallyOfferedOpenChannels
503
- case ChannelSource.Remote:
504
- return this.remotelyOfferedOpenChannels
505
- case ChannelSource.Seeded:
506
- return this.seededOpenChannels
507
- }
508
- }
509
-
510
- /**
511
- * Cancels a prior call to acceptChannelAsync
512
- * @param channel The promise of a channel to be canceled.
513
- * @param name The name of the channel the caller was accepting.
514
- * @param reason The reason for cancellation.
515
- */
516
- private acceptChannelCanceled(channel: Deferred<ChannelClass>, name: string, reason: any) {
517
- if (channel.reject(new CancellationToken.CancellationError(reason))) {
518
- removeFromQueue(channel, this.acceptingChannels[name])
519
- }
520
- }
521
-
522
- /**
523
- * Responds to cancellation of a prior call to offerChannelAsync.
524
- * @param channel The channel previously offered.
525
- */
526
- private offerChannelCanceled(channel: ChannelClass, reason: any) {
527
- channel.tryCancelOffer(reason)
528
- }
529
-
530
- /**
531
- * Gets a unique number that can be used to represent a channel.
532
- * @description The channel numbers increase by two in order to maintain odd or even numbers,
533
- * since each party is allowed to create only one or the other.
534
- */
535
- private getUnusedChannelId() {
536
- return (this.lastOfferedChannelId += this.isOdd !== undefined ? 2 : 1)
537
- }
538
- }
539
-
540
- // tslint:disable-next-line:max-classes-per-file
541
- export class MultiplexingStreamClass extends MultiplexingStream {
542
- protected lastOfferedChannelId: number
543
- private readonly sendingSemaphore = new Semaphore(1)
544
-
545
- constructor(formatter: MultiplexingStreamFormatter, isOdd: boolean | undefined, options: MultiplexingStreamOptions) {
546
- super(formatter, isOdd, options)
547
-
548
- this.lastOfferedChannelId = isOdd ? -1 : 0 // the first channel created should be 1 or 2
549
- this.lastOfferedChannelId += options.seededChannels?.length ?? 0
550
-
551
- // Initiate reading from the transport stream. This will not end until the stream does, or we're disposed.
552
- // If reading the stream fails, we'll dispose ourselves.
553
- this.readFromStream(this.disposalToken).catch(err => this._completionSource.reject(err))
554
- }
555
-
556
- get backpressureSupportEnabled(): boolean {
557
- return this.protocolMajorVersion > 1
558
- }
559
-
560
- public async sendFrameAsync(header: FrameHeader, payload?: Buffer, cancellationToken: CancellationToken = CancellationToken.CONTINUE): Promise<void> {
561
- if (!header) {
562
- throw new Error('Header is required.')
563
- }
564
-
565
- await this.sendingSemaphore.use(async () => {
566
- cancellationToken.throwIfCancelled()
567
- throwIfDisposed(this)
568
-
569
- await this.formatter.writeFrameAsync(header, payload)
570
- })
571
- }
572
-
573
- /**
574
- * Transmits a frame over the stream.
575
- * @param code The op code for the channel.
576
- * @param channelId The ID of the channel to receive the frame.
577
- * @description The promise returned from this function is always resolved (not rejected)
578
- * since it is anticipated that callers may not be awaiting its result.
579
- */
580
- public async sendFrame(code: ControlCode, channelId: QualifiedChannelId) {
581
- try {
582
- if (this._completionSource.isCompleted) {
583
- // Any frames that come in after we're done are most likely frames just informing that channels are
584
- // being terminated, which we do not need to communicate since the connection going down implies that.
585
- return
586
- }
587
-
588
- const header = new FrameHeader(code, channelId)
589
- await this.sendFrameAsync(header)
590
- } catch (error) {
591
- // We mustn't throw back to our caller. So report the failure by disposing with failure.
592
- this._completionSource.reject(error)
593
- }
594
- }
595
-
596
- public onChannelWritingCompleted(channel: ChannelClass) {
597
- // Only inform the remote side if this channel has not already been terminated.
598
- if (!channel.isDisposed && this.getOpenChannel(channel.qualifiedId)) {
599
- this.sendFrame(ControlCode.contentWritingCompleted, channel.qualifiedId)
600
- }
601
- }
602
-
603
- public async onChannelDisposed(channel: ChannelClass, error: Error | null) {
604
- if (!this._completionSource.isCompleted) {
605
- try {
606
- const payload =
607
- this.protocolMajorVersion > 1 && error ? (this.formatter as MultiplexingStreamV2Formatter).serializeException(error) : Buffer.alloc(0)
608
-
609
- const frameHeader = new FrameHeader(ControlCode.channelTerminated, channel.qualifiedId)
610
- await this.sendFrameAsync(frameHeader, payload)
611
- } catch (err) {
612
- // Swallow exceptions thrown about channel disposal if the whole stream has been taken down.
613
- if (this.isDisposed) {
614
- return
615
- }
616
-
617
- throw err
618
- }
619
- }
620
- }
621
-
622
- public localContentExamined(channel: ChannelClass, bytesConsumed: number) {
623
- const payload = this.formatter.serializeContentProcessed(bytesConsumed)
624
- this.rejectOnFailure(this.sendFrameAsync(new FrameHeader(ControlCode.contentProcessed, channel.qualifiedId), payload))
625
- }
626
-
627
- private async readFromStream(cancellationToken: CancellationToken) {
628
- while (!this.isDisposed) {
629
- const frame = await this.formatter.readFrameAsync(cancellationToken)
630
- if (frame === null) {
631
- break
632
- }
633
-
634
- frame.header.flipChannelPerspective()
635
- switch (frame.header.code) {
636
- case ControlCode.offer:
637
- this.onOffer(frame.header.requiredChannel, frame.payload)
638
- break
639
- case ControlCode.offerAccepted:
640
- this.onOfferAccepted(frame.header.requiredChannel, frame.payload)
641
- break
642
- case ControlCode.content:
643
- this.onContent(frame.header.requiredChannel, frame.payload)
644
- break
645
- case ControlCode.contentProcessed:
646
- this.onContentProcessed(frame.header.requiredChannel, frame.payload)
647
- break
648
- case ControlCode.contentWritingCompleted:
649
- this.onContentWritingCompleted(frame.header.requiredChannel)
650
- break
651
- case ControlCode.channelTerminated:
652
- this.onChannelTerminated(frame.header.requiredChannel, frame.payload)
653
- break
654
- default:
655
- break
656
- }
657
- }
658
-
659
- this.disposeCore(true)
660
- }
661
-
662
- private onOffer(channelId: QualifiedChannelId, payload: Buffer) {
663
- const offerParameters = this.formatter.deserializeOfferParameters(payload)
664
- const channel = new ChannelClass(this, channelId, offerParameters)
665
- let acceptingChannelAlreadyPresent = false
666
- let options: ChannelOptions | undefined
667
-
668
- let acceptingChannels: Deferred<ChannelClass>[]
669
- if ((acceptingChannels = this.acceptingChannels[offerParameters.name]) !== undefined) {
670
- while (acceptingChannels.length > 0) {
671
- const candidate = acceptingChannels.shift()!
672
- if (candidate.resolve(channel)) {
673
- acceptingChannelAlreadyPresent = true
674
- options = candidate.state as ChannelOptions
675
- break
676
- }
677
- }
678
- }
679
-
680
- if (!acceptingChannelAlreadyPresent) {
681
- let offeredChannels: Channel[]
682
- if (!(offeredChannels = this.channelsOfferedByThemByName[offerParameters.name])) {
683
- this.channelsOfferedByThemByName[offerParameters.name] = offeredChannels = []
684
- }
685
-
686
- offeredChannels.push(channel)
687
- }
688
-
689
- this.setOpenChannel(channel)
690
-
691
- if (acceptingChannelAlreadyPresent) {
692
- this.acceptChannelOrThrow(channel, options)
693
- }
694
-
695
- this.raiseChannelOffered(channel.id, channel.name, acceptingChannelAlreadyPresent)
696
- }
697
-
698
- private onOfferAccepted(channelId: QualifiedChannelId, payload: Buffer) {
699
- if (channelId.source !== ChannelSource.Local) {
700
- throw new Error('Remote party tried to accept a channel that they offered.')
701
- }
702
-
703
- const acceptanceParameter = this.formatter.deserializeAcceptanceParameters(payload)
704
- const channel = this.getOpenChannel(channelId)
705
- if (!channel) {
706
- throw new Error(`Unexpected channel created with ID ${QualifiedChannelId.toString(channelId)}`)
707
- }
708
-
709
- if (!channel.onAccepted(acceptanceParameter)) {
710
- // This may be an acceptance of a channel that we canceled an offer for, and a race condition
711
- // led to our cancellation notification crossing in transit with their acceptance notification.
712
- // In this case, do nothing since we already sent a channel termination message, and the remote side
713
- // should notice it soon.
714
- }
715
- }
716
-
717
- private onContent(channelId: QualifiedChannelId, payload: Buffer) {
718
- const channel = this.getOpenChannel(channelId)
719
- if (!channel) {
720
- throw new Error(`No channel with id ${channelId} found.`)
721
- }
722
-
723
- channel.onContent(payload)
724
- }
725
-
726
- private onContentProcessed(channelId: QualifiedChannelId, payload: Buffer) {
727
- const channel = this.getOpenChannel(channelId)
728
- if (!channel) {
729
- throw new Error(`No channel with id ${channelId} found.`)
730
- }
731
-
732
- const bytesProcessed = this.formatter.deserializeContentProcessed(payload)
733
- channel.onContentProcessed(bytesProcessed)
734
- }
735
-
736
- private onContentWritingCompleted(channelId: QualifiedChannelId) {
737
- const channel = this.getOpenChannel(channelId)
738
- if (!channel) {
739
- throw new Error(`No channel with id ${channelId} found.`)
740
- }
741
-
742
- channel.onContent(null) // signify that the remote is done writing.
743
- }
744
-
745
- /**
746
- * Occurs when the remote party has terminated a channel (including canceling an offer).
747
- * @param channelId The ID of the terminated channel.
748
- */
749
- private onChannelTerminated(channelId: QualifiedChannelId, payload: Buffer) {
750
- const channel = this.getOpenChannel(channelId)
751
- if (channel) {
752
- this.deleteOpenChannel(channelId)
753
- this.removeChannelFromOfferedQueue(channel)
754
-
755
- // Extract the exception that we received from the remote side.
756
- const remoteException = this.protocolMajorVersion > 1 ? (this.formatter as MultiplexingStreamV2Formatter).deserializeException(payload) : null
757
-
758
- channel.dispose(remoteException)
759
- }
760
- }
761
- }
1
+ /* TODO:
2
+ * Tracing
3
+ * Auto-terminate channels when both ends have finished writing (AutoCloseOnPipesClosureAsync)
4
+ */
5
+
6
+ import { Semaphore } from 'await-semaphore'
7
+ import CancellationToken from 'cancellationtoken'
8
+ import { EventEmitter } from 'events'
9
+ import { Channel, ChannelClass } from './Channel'
10
+ import { ChannelOptions } from './ChannelOptions'
11
+ import { ControlCode } from './ControlCode'
12
+ import { Deferred } from './Deferred'
13
+ import { FrameHeader } from './FrameHeader'
14
+ import { IChannelOfferEventArgs } from './IChannelOfferEventArgs'
15
+ import { IDisposableObservable } from './IDisposableObservable'
16
+ import {
17
+ MultiplexingStreamFormatter,
18
+ MultiplexingStreamV1Formatter,
19
+ MultiplexingStreamV2Formatter,
20
+ MultiplexingStreamV3Formatter,
21
+ } from './MultiplexingStreamFormatters'
22
+ import './MultiplexingStreamOptions'
23
+ import { MultiplexingStreamOptions } from './MultiplexingStreamOptions'
24
+ import { OfferParameters } from './OfferParameters'
25
+ import { ChannelSource, QualifiedChannelId } from './QualifiedChannelId'
26
+ import { removeFromQueue, throwIfDisposed } from './Utilities'
27
+ import caught = require('caught')
28
+
29
+ export abstract class MultiplexingStream implements IDisposableObservable {
30
+ /**
31
+ * The maximum length of a frame's payload.
32
+ */
33
+ static readonly framePayloadMaxLength = 20 * 1024
34
+
35
+ private static readonly recommendedDefaultChannelReceivingWindowSize = 5 * MultiplexingStream.framePayloadMaxLength
36
+
37
+ /** The default window size used for new channels that do not specify a value for ChannelOptions.ChannelReceivingWindowSize. */
38
+ readonly defaultChannelReceivingWindowSize: number
39
+
40
+ protected get disposalToken() {
41
+ return this.disposalTokenSource.token
42
+ }
43
+
44
+ /**
45
+ * Gets a promise that is resolved or rejected based on how this stream is disposed or fails.
46
+ */
47
+ public get completion(): Promise<void> {
48
+ return this._completionSource.promise
49
+ }
50
+
51
+ /**
52
+ * Gets a value indicating whether this instance has been disposed.
53
+ */
54
+ public get isDisposed(): boolean {
55
+ return this.disposalTokenSource.token.isCancelled
56
+ }
57
+
58
+ /**
59
+ * Initializes a new instance of the `MultiplexingStream` class.
60
+ * @param stream The duplex stream to read and write to.
61
+ * Use `FullDuplexStream.Splice` if you have distinct input/output streams.
62
+ * @param options Options to customize the behavior of the stream.
63
+ * @param cancellationToken A token whose cancellation aborts the handshake with the remote end.
64
+ * @returns The multiplexing stream, once the handshake is complete.
65
+ */
66
+ // eslint-disable-next-line @typescript-eslint/naming-convention
67
+ public static async CreateAsync(
68
+ stream: NodeJS.ReadWriteStream,
69
+ options?: MultiplexingStreamOptions,
70
+ cancellationToken: CancellationToken = CancellationToken.CONTINUE
71
+ ): Promise<MultiplexingStream> {
72
+ if (!stream) {
73
+ throw new Error('stream must be specified.')
74
+ }
75
+
76
+ options = options || {}
77
+ options.protocolMajorVersion ??= 1
78
+ options.defaultChannelReceivingWindowSize = options.defaultChannelReceivingWindowSize || MultiplexingStream.recommendedDefaultChannelReceivingWindowSize
79
+ if (options.protocolMajorVersion < 3 && options.seededChannels && options.seededChannels.length > 0) {
80
+ throw new Error('Seeded channels require v3 of the protocol at least.')
81
+ }
82
+
83
+ // Send the protocol magic number, and a random 16-byte number to establish even/odd assignments.
84
+ const formatter: MultiplexingStreamFormatter | undefined =
85
+ options.protocolMajorVersion === 1
86
+ ? new MultiplexingStreamV1Formatter(stream)
87
+ : options.protocolMajorVersion === 2
88
+ ? new MultiplexingStreamV2Formatter(stream)
89
+ : options.protocolMajorVersion === 3
90
+ ? new MultiplexingStreamV3Formatter(stream)
91
+ : undefined
92
+ if (!formatter) {
93
+ throw new Error(`Protocol major version ${options.protocolMajorVersion} is not supported.`)
94
+ }
95
+
96
+ const writeHandshakeData = await formatter.writeHandshakeAsync()
97
+ const handshakeResult = await formatter.readHandshakeAsync(writeHandshakeData, cancellationToken)
98
+ formatter.isOdd = handshakeResult.isOdd
99
+
100
+ return new MultiplexingStreamClass(formatter, handshakeResult.isOdd, options)
101
+ }
102
+
103
+ /**
104
+ * Initializes a new instance of the `MultiplexingStream` class
105
+ * with protocolMajorVersion set to 3.
106
+ * @param stream The duplex stream to read and write to.
107
+ * Use `FullDuplexStream.Splice` if you have distinct input/output streams.
108
+ * @param options Options to customize the behavior of the stream.
109
+ * @returns The multiplexing stream.
110
+ */
111
+ // eslint-disable-next-line @typescript-eslint/naming-convention
112
+ public static Create(stream: NodeJS.ReadWriteStream, options?: MultiplexingStreamOptions): MultiplexingStream {
113
+ options ??= { protocolMajorVersion: 3 }
114
+ options.protocolMajorVersion ??= 3
115
+
116
+ const formatter: MultiplexingStreamFormatter | undefined = options.protocolMajorVersion === 3 ? new MultiplexingStreamV3Formatter(stream) : undefined
117
+ if (!formatter) {
118
+ throw new Error(`Protocol major version ${options.protocolMajorVersion} is not supported. Try CreateAsync instead.`)
119
+ }
120
+
121
+ return new MultiplexingStreamClass(formatter, undefined, options)
122
+ }
123
+
124
+ /**
125
+ * The options to use for channels we create in response to incoming offers.
126
+ * @description Whatever these settings are, they can be replaced when the channel is accepted.
127
+ */
128
+ protected static readonly defaultChannelOptions: ChannelOptions = {}
129
+
130
+ /**
131
+ * The encoding used for characters in control frames.
132
+ */
133
+ // eslint-disable-next-line @typescript-eslint/naming-convention
134
+ static readonly ControlFrameEncoding = 'utf-8'
135
+
136
+ protected readonly _completionSource = new Deferred<void>()
137
+
138
+ /**
139
+ * A dictionary of channels that were seeded, keyed by their ID.
140
+ */
141
+ protected readonly seededOpenChannels: { [id: number]: ChannelClass } = {}
142
+
143
+ /**
144
+ * A dictionary of channels that were offered locally, keyed by their ID.
145
+ */
146
+ protected readonly locallyOfferedOpenChannels: { [id: number]: ChannelClass } = {}
147
+
148
+ /**
149
+ * A dictionary of channels that were offered remotely, keyed by their ID.
150
+ */
151
+ protected readonly remotelyOfferedOpenChannels: { [id: number]: ChannelClass } = {}
152
+
153
+ /**
154
+ * The last number assigned to a channel.
155
+ * Each use of this should increment by two if isOdd is defined.
156
+ * It should never exceed uint32.MaxValue
157
+ */
158
+ protected abstract lastOfferedChannelId: number
159
+
160
+ /**
161
+ * A map of channel names to queues of channels waiting for local acceptance.
162
+ */
163
+ protected readonly channelsOfferedByThemByName: { [name: string]: ChannelClass[] } = {}
164
+
165
+ /**
166
+ * A map of channel names to queues of Deferred<Channel> from waiting accepters.
167
+ */
168
+ protected readonly acceptingChannels: { [name: string]: Deferred<ChannelClass>[] } = {}
169
+
170
+ /** The major version of the protocol being used for this connection. */
171
+ protected readonly protocolMajorVersion: number
172
+
173
+ private readonly eventEmitter = new EventEmitter()
174
+
175
+ private disposalTokenSource = CancellationToken.create()
176
+
177
+ protected constructor(
178
+ protected readonly formatter: MultiplexingStreamFormatter,
179
+ private readonly isOdd: boolean | undefined,
180
+ options: MultiplexingStreamOptions
181
+ ) {
182
+ this.defaultChannelReceivingWindowSize = options.defaultChannelReceivingWindowSize ?? MultiplexingStream.recommendedDefaultChannelReceivingWindowSize
183
+ this.protocolMajorVersion = options.protocolMajorVersion ?? 1
184
+
185
+ if (options.seededChannels) {
186
+ for (let i = 0; i < options.seededChannels.length; i++) {
187
+ const channelOptions = options.seededChannels[i]
188
+ const id = { id: i, source: ChannelSource.Seeded }
189
+ this.setOpenChannel(
190
+ new ChannelClass(this as unknown as MultiplexingStreamClass, id, {
191
+ name: '',
192
+ remoteWindowSize: channelOptions.channelReceivingWindowSize ?? this.defaultChannelReceivingWindowSize,
193
+ })
194
+ )
195
+ }
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Creates an anonymous channel that may be accepted by <see cref="AcceptChannel(int, ChannelOptions)"/>.
201
+ * Its existance must be communicated by other means (typically another, existing channel) to encourage acceptance.
202
+ * @param options A set of options that describe local treatment of this channel.
203
+ * @returns The anonymous channel.
204
+ * @description Note that while the channel is created immediately, any local write to that channel will be
205
+ * buffered locally until the remote party accepts the channel.
206
+ */
207
+ public createChannel(options?: ChannelOptions): Channel {
208
+ const offerParameters: OfferParameters = {
209
+ name: '',
210
+ remoteWindowSize: options?.channelReceivingWindowSize ?? this.defaultChannelReceivingWindowSize,
211
+ }
212
+ const payload = this.formatter.serializeOfferParameters(offerParameters)
213
+ const channel = new ChannelClass(
214
+ this as any as MultiplexingStreamClass,
215
+ { id: this.getUnusedChannelId(), source: ChannelSource.Local },
216
+ offerParameters
217
+ )
218
+ this.setOpenChannel(channel)
219
+
220
+ this.rejectOnFailure(this.sendFrameAsync(new FrameHeader(ControlCode.offer, channel.qualifiedId), payload, this.disposalToken))
221
+ return channel
222
+ }
223
+
224
+ /**
225
+ * Accepts a channel with a specific ID.
226
+ * @param id The id of the channel to accept.
227
+ * @param options A set of options that describe local treatment of this channel.
228
+ * @description This method can be used to accept anonymous channels created with <see cref="CreateChannel"/>.
229
+ * Unlike <see cref="AcceptChannelAsync(string, ChannelOptions, CancellationToken)"/> which will await
230
+ * for a channel offer if a matching one has not been made yet, this method only accepts an offer
231
+ * for a channel that has already been made.
232
+ */
233
+ public acceptChannel(id: number, options?: ChannelOptions): Channel {
234
+ const channel = this.remotelyOfferedOpenChannels[id] || this.seededOpenChannels[id]
235
+ if (!channel) {
236
+ throw new Error('No channel with ID ' + id)
237
+ }
238
+
239
+ this.removeChannelFromOfferedQueue(channel)
240
+
241
+ this.acceptChannelOrThrow(channel, options)
242
+ return channel
243
+ }
244
+
245
+ /**
246
+ * Rejects an offer for the channel with a specified ID.
247
+ * @param id The ID of the channel whose offer should be rejected.
248
+ */
249
+ public rejectChannel(id: number) {
250
+ const channel = this.remotelyOfferedOpenChannels[id]
251
+ if (channel) {
252
+ removeFromQueue(channel, this.channelsOfferedByThemByName[channel.name])
253
+ } else {
254
+ throw new Error('No channel with that ID found.')
255
+ }
256
+
257
+ // Rejecting a channel rejects a couple promises that we don't want the caller to have to observe
258
+ // separately since they are explicitly stating they want to take this action now.
259
+ caught(channel.acceptance)
260
+ caught(channel.completion)
261
+
262
+ channel.dispose()
263
+ }
264
+
265
+ /**
266
+ * Offers a new, named channel to the remote party so they may accept it with
267
+ * {@link acceptChannelAsync}.
268
+ * @param name A name for the channel, which must be accepted on the remote end to complete creation.
269
+ * It need not be unique, and may be empty but must not be null.
270
+ * Any characters are allowed, and max length is determined by the maximum frame payload (based on UTF-8 encoding).
271
+ * @param options A set of options that describe local treatment of this channel.
272
+ * @param cancellationToken A cancellation token. Do NOT let this be a long-lived token
273
+ * or a memory leak will result since we add continuations to its promise.
274
+ * @returns A task that completes with the `Channel` if the offer is accepted on the remote end
275
+ * or faults with `MultiplexingProtocolException` if the remote end rejects the channel.
276
+ */
277
+ public async offerChannelAsync(
278
+ name: string,
279
+ options?: ChannelOptions,
280
+ cancellationToken: CancellationToken = CancellationToken.CONTINUE
281
+ ): Promise<Channel> {
282
+ if (name === null || name === undefined) {
283
+ throw new Error('Name must be specified (but may be empty).')
284
+ }
285
+
286
+ cancellationToken.throwIfCancelled()
287
+ throwIfDisposed(this)
288
+
289
+ const offerParameters: OfferParameters = {
290
+ name,
291
+ remoteWindowSize: options?.channelReceivingWindowSize ?? this.defaultChannelReceivingWindowSize,
292
+ }
293
+ const payload = this.formatter.serializeOfferParameters(offerParameters)
294
+ const channel = new ChannelClass(
295
+ this as any as MultiplexingStreamClass,
296
+ { id: this.getUnusedChannelId(), source: ChannelSource.Local },
297
+ offerParameters
298
+ )
299
+ this.setOpenChannel(channel)
300
+
301
+ const header = new FrameHeader(ControlCode.offer, channel.qualifiedId)
302
+
303
+ const unsubscribeFromCT = cancellationToken.onCancelled(reason => this.offerChannelCanceled(channel, reason))
304
+ try {
305
+ // We *will* recognize rejection of this promise. But just in case sendFrameAsync completes synchronously,
306
+ // we want to signify that we *will* catch it first to avoid node.js emitting warnings or crashing.
307
+ caught(channel.acceptance)
308
+
309
+ await this.sendFrameAsync(header, payload, cancellationToken)
310
+ await channel.acceptance
311
+
312
+ return channel
313
+ } finally {
314
+ unsubscribeFromCT()
315
+ }
316
+ }
317
+
318
+ /**
319
+ * Accepts a channel that the remote end has attempted or may attempt to create.
320
+ * @param name The name of the channel to accept.
321
+ * An empty string will match an offer made via {@link offerChannelAsync} with an empty channel name.
322
+ * It will also match an anonymous channel offer made with {@link createChannel}.
323
+ * @param options A set of options that describe local treatment of this channel.
324
+ * @param cancellationToken A token to indicate lost interest in accepting the channel.
325
+ * Do NOT let this be a long-lived token
326
+ * or a memory leak will result since we add continuations to its promise.
327
+ * @returns The `Channel`, after its offer has been received from the remote party and accepted.
328
+ * @description If multiple offers exist with the specified `name`, the first one received will be accepted.
329
+ */
330
+ public async acceptChannelAsync(
331
+ name: string,
332
+ options?: ChannelOptions,
333
+ cancellationToken: CancellationToken = CancellationToken.CONTINUE
334
+ ): Promise<Channel> {
335
+ if (name === null || name === undefined) {
336
+ throw new Error('Name must be specified (but may be empty).')
337
+ }
338
+
339
+ cancellationToken.throwIfCancelled()
340
+ throwIfDisposed(this)
341
+
342
+ let channel: ChannelClass | undefined
343
+ let pendingAcceptChannel: Deferred<ChannelClass>
344
+ const channelsOfferedByThem = this.channelsOfferedByThemByName[name] as ChannelClass[]
345
+ if (channelsOfferedByThem) {
346
+ while (channel === undefined && channelsOfferedByThem.length > 0) {
347
+ channel = channelsOfferedByThem.shift()!
348
+ if (channel.isAccepted || channel.isRejectedOrCanceled) {
349
+ channel = undefined
350
+ continue
351
+ }
352
+ }
353
+ }
354
+
355
+ if (channel === undefined) {
356
+ let acceptingChannels = this.acceptingChannels[name]
357
+ if (!acceptingChannels) {
358
+ this.acceptingChannels[name] = acceptingChannels = []
359
+ }
360
+
361
+ pendingAcceptChannel = new Deferred<ChannelClass>(options)
362
+ acceptingChannels.push(pendingAcceptChannel)
363
+ }
364
+
365
+ if (channel !== undefined) {
366
+ this.acceptChannelOrThrow(channel, options)
367
+ return channel
368
+ } else {
369
+ const unsubscribeFromCT = cancellationToken.onCancelled(reason => this.acceptChannelCanceled(pendingAcceptChannel, name, reason))
370
+ try {
371
+ return await pendingAcceptChannel!.promise
372
+ } finally {
373
+ unsubscribeFromCT()
374
+ }
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Disposes the stream.
380
+ */
381
+ public dispose() {
382
+ this.disposeCore(false)
383
+ }
384
+
385
+ protected disposeCore(remoteDisconnect: boolean) {
386
+ this.disposalTokenSource.cancel()
387
+ this._completionSource.resolve()
388
+
389
+ this.formatter.end()
390
+ ;[this.locallyOfferedOpenChannels, this.remotelyOfferedOpenChannels].forEach(cb => {
391
+ for (const channelId in cb) {
392
+ if (cb.hasOwnProperty(channelId)) {
393
+ const channel = cb[channelId]
394
+
395
+ // Acceptance gets rejected when a channel is disposed.
396
+ // Avoid a node.js crash or test failure for unobserved channels (e.g. offers for channels from the other party that no one cared to receive on this side).
397
+ caught(channel.acceptance)
398
+
399
+ channel.dispose()
400
+ }
401
+ }
402
+ })
403
+
404
+ // Iterate over acceptingChannels to reject each promise
405
+ const errorMessage = remoteDisconnect ? 'The remote party has disconnected.' : 'The stream is being disposed locally.'
406
+ for (const name in this.acceptingChannels) {
407
+ if (this.acceptingChannels.hasOwnProperty(name)) {
408
+ const acceptingChannels = this.acceptingChannels[name]
409
+ for (const channelDeferral of acceptingChannels) {
410
+ channelDeferral.reject(new Error(errorMessage))
411
+ }
412
+
413
+ delete this.acceptingChannels[name]
414
+ }
415
+ }
416
+ }
417
+
418
+ public on(event: 'channelOffered', listener: (args: IChannelOfferEventArgs) => void) {
419
+ this.eventEmitter.on(event, listener)
420
+ }
421
+
422
+ public off(event: 'channelOffered', listener: (args: IChannelOfferEventArgs) => void) {
423
+ this.eventEmitter.off(event, listener)
424
+ }
425
+
426
+ public once(event: 'channelOffered', listener: (args: IChannelOfferEventArgs) => void) {
427
+ this.eventEmitter.once(event, listener)
428
+ }
429
+
430
+ protected raiseChannelOffered(id: number, name: string, isAccepted: boolean) {
431
+ const args: IChannelOfferEventArgs = {
432
+ id,
433
+ isAccepted,
434
+ name,
435
+ }
436
+ try {
437
+ this.eventEmitter.emit('channelOffered', args)
438
+ } catch (err) {
439
+ this._completionSource.reject(err)
440
+ }
441
+ }
442
+
443
+ protected abstract sendFrameAsync(header: FrameHeader, payload: Buffer, cancellationToken: CancellationToken): Promise<void>
444
+
445
+ protected abstract sendFrame(code: ControlCode, channelId: QualifiedChannelId): Promise<void>
446
+
447
+ protected acceptChannelOrThrow(channel: ChannelClass, options?: ChannelOptions) {
448
+ if (channel.tryAcceptOffer(options)) {
449
+ const acceptanceParameters = {
450
+ remoteWindowSize: options?.channelReceivingWindowSize ?? channel.localWindowSize ?? this.defaultChannelReceivingWindowSize,
451
+ }
452
+ if (acceptanceParameters.remoteWindowSize < this.defaultChannelReceivingWindowSize) {
453
+ acceptanceParameters.remoteWindowSize = this.defaultChannelReceivingWindowSize
454
+ }
455
+
456
+ if (channel.qualifiedId.source !== ChannelSource.Seeded) {
457
+ const payload = this.formatter.serializeAcceptanceParameters(acceptanceParameters)
458
+ this.rejectOnFailure(this.sendFrameAsync(new FrameHeader(ControlCode.offerAccepted, channel.qualifiedId), payload, this.disposalToken))
459
+ }
460
+ } else if (channel.isAccepted) {
461
+ throw new Error('Channel is already accepted.')
462
+ } else if (channel.isRejectedOrCanceled) {
463
+ throw new Error('Channel is no longer available for acceptance.')
464
+ } else {
465
+ throw new Error('Channel could not be accepted.')
466
+ }
467
+ }
468
+
469
+ /**
470
+ * Disposes this instance if the specified promise is rejected.
471
+ * @param promise The promise to check for failures.
472
+ */
473
+ protected async rejectOnFailure<T>(promise: Promise<T>) {
474
+ try {
475
+ await promise
476
+ } catch (err) {
477
+ this._completionSource.reject(err)
478
+ }
479
+ }
480
+
481
+ protected removeChannelFromOfferedQueue(channel: ChannelClass) {
482
+ if (channel.name) {
483
+ removeFromQueue(channel, this.channelsOfferedByThemByName[channel.name])
484
+ }
485
+ }
486
+
487
+ protected getOpenChannel(qualifiedId: QualifiedChannelId): ChannelClass | undefined {
488
+ return this.getChannelCollection(qualifiedId.source)[qualifiedId.id]
489
+ }
490
+
491
+ protected setOpenChannel(channel: ChannelClass) {
492
+ this.getChannelCollection(channel.qualifiedId.source)[channel.qualifiedId.id] = channel
493
+ }
494
+
495
+ protected deleteOpenChannel(qualifiedId: QualifiedChannelId) {
496
+ delete this.getChannelCollection(qualifiedId.source)[qualifiedId.id]
497
+ }
498
+
499
+ private getChannelCollection(source: ChannelSource): { [id: number]: ChannelClass } {
500
+ switch (source) {
501
+ case ChannelSource.Local:
502
+ return this.locallyOfferedOpenChannels
503
+ case ChannelSource.Remote:
504
+ return this.remotelyOfferedOpenChannels
505
+ case ChannelSource.Seeded:
506
+ return this.seededOpenChannels
507
+ }
508
+ }
509
+
510
+ /**
511
+ * Cancels a prior call to acceptChannelAsync
512
+ * @param channel The promise of a channel to be canceled.
513
+ * @param name The name of the channel the caller was accepting.
514
+ * @param reason The reason for cancellation.
515
+ */
516
+ private acceptChannelCanceled(channel: Deferred<ChannelClass>, name: string, reason: any) {
517
+ if (channel.reject(new CancellationToken.CancellationError(reason))) {
518
+ removeFromQueue(channel, this.acceptingChannels[name])
519
+ }
520
+ }
521
+
522
+ /**
523
+ * Responds to cancellation of a prior call to offerChannelAsync.
524
+ * @param channel The channel previously offered.
525
+ */
526
+ private offerChannelCanceled(channel: ChannelClass, reason: any) {
527
+ channel.tryCancelOffer(reason)
528
+ }
529
+
530
+ /**
531
+ * Gets a unique number that can be used to represent a channel.
532
+ * @description The channel numbers increase by two in order to maintain odd or even numbers,
533
+ * since each party is allowed to create only one or the other.
534
+ */
535
+ private getUnusedChannelId() {
536
+ return (this.lastOfferedChannelId += this.isOdd !== undefined ? 2 : 1)
537
+ }
538
+ }
539
+
540
+ // tslint:disable-next-line:max-classes-per-file
541
+ export class MultiplexingStreamClass extends MultiplexingStream {
542
+ protected lastOfferedChannelId: number
543
+ private readonly sendingSemaphore = new Semaphore(1)
544
+
545
+ constructor(formatter: MultiplexingStreamFormatter, isOdd: boolean | undefined, options: MultiplexingStreamOptions) {
546
+ super(formatter, isOdd, options)
547
+
548
+ this.lastOfferedChannelId = isOdd ? -1 : 0 // the first channel created should be 1 or 2
549
+ this.lastOfferedChannelId += options.seededChannels?.length ?? 0
550
+
551
+ // Initiate reading from the transport stream. This will not end until the stream does, or we're disposed.
552
+ // If reading the stream fails, we'll dispose ourselves.
553
+ this.readFromStream(this.disposalToken).catch(err => this._completionSource.reject(err))
554
+ }
555
+
556
+ get backpressureSupportEnabled(): boolean {
557
+ return this.protocolMajorVersion > 1
558
+ }
559
+
560
+ public async sendFrameAsync(header: FrameHeader, payload?: Buffer, cancellationToken: CancellationToken = CancellationToken.CONTINUE): Promise<void> {
561
+ if (!header) {
562
+ throw new Error('Header is required.')
563
+ }
564
+
565
+ await this.sendingSemaphore.use(async () => {
566
+ cancellationToken.throwIfCancelled()
567
+ throwIfDisposed(this)
568
+
569
+ await this.formatter.writeFrameAsync(header, payload)
570
+ })
571
+ }
572
+
573
+ /**
574
+ * Transmits a frame over the stream.
575
+ * @param code The op code for the channel.
576
+ * @param channelId The ID of the channel to receive the frame.
577
+ * @description The promise returned from this function is always resolved (not rejected)
578
+ * since it is anticipated that callers may not be awaiting its result.
579
+ */
580
+ public async sendFrame(code: ControlCode, channelId: QualifiedChannelId) {
581
+ try {
582
+ if (this._completionSource.isCompleted) {
583
+ // Any frames that come in after we're done are most likely frames just informing that channels are
584
+ // being terminated, which we do not need to communicate since the connection going down implies that.
585
+ return
586
+ }
587
+
588
+ const header = new FrameHeader(code, channelId)
589
+ await this.sendFrameAsync(header)
590
+ } catch (error) {
591
+ // We mustn't throw back to our caller. So report the failure by disposing with failure.
592
+ this._completionSource.reject(error)
593
+ }
594
+ }
595
+
596
+ public onChannelWritingCompleted(channel: ChannelClass) {
597
+ // Only inform the remote side if this channel has not already been terminated.
598
+ if (!channel.isDisposed && this.getOpenChannel(channel.qualifiedId)) {
599
+ this.sendFrame(ControlCode.contentWritingCompleted, channel.qualifiedId)
600
+ }
601
+ }
602
+
603
+ public async onChannelDisposed(channel: ChannelClass, error: Error | null) {
604
+ if (!this._completionSource.isCompleted) {
605
+ try {
606
+ const payload =
607
+ this.protocolMajorVersion > 1 && error ? (this.formatter as MultiplexingStreamV2Formatter).serializeException(error) : Buffer.alloc(0)
608
+
609
+ const frameHeader = new FrameHeader(ControlCode.channelTerminated, channel.qualifiedId)
610
+ await this.sendFrameAsync(frameHeader, payload)
611
+ } catch (err) {
612
+ // Swallow exceptions thrown about channel disposal if the whole stream has been taken down.
613
+ if (this.isDisposed) {
614
+ return
615
+ }
616
+
617
+ throw err
618
+ }
619
+ }
620
+ }
621
+
622
+ public localContentExamined(channel: ChannelClass, bytesConsumed: number) {
623
+ const payload = this.formatter.serializeContentProcessed(bytesConsumed)
624
+ this.rejectOnFailure(this.sendFrameAsync(new FrameHeader(ControlCode.contentProcessed, channel.qualifiedId), payload))
625
+ }
626
+
627
+ private async readFromStream(cancellationToken: CancellationToken) {
628
+ while (!this.isDisposed) {
629
+ const frame = await this.formatter.readFrameAsync(cancellationToken)
630
+ if (frame === null) {
631
+ break
632
+ }
633
+
634
+ frame.header.flipChannelPerspective()
635
+ switch (frame.header.code) {
636
+ case ControlCode.offer:
637
+ this.onOffer(frame.header.requiredChannel, frame.payload)
638
+ break
639
+ case ControlCode.offerAccepted:
640
+ this.onOfferAccepted(frame.header.requiredChannel, frame.payload)
641
+ break
642
+ case ControlCode.content:
643
+ this.onContent(frame.header.requiredChannel, frame.payload)
644
+ break
645
+ case ControlCode.contentProcessed:
646
+ this.onContentProcessed(frame.header.requiredChannel, frame.payload)
647
+ break
648
+ case ControlCode.contentWritingCompleted:
649
+ this.onContentWritingCompleted(frame.header.requiredChannel)
650
+ break
651
+ case ControlCode.channelTerminated:
652
+ this.onChannelTerminated(frame.header.requiredChannel, frame.payload)
653
+ break
654
+ default:
655
+ break
656
+ }
657
+ }
658
+
659
+ this.disposeCore(true)
660
+ }
661
+
662
+ private onOffer(channelId: QualifiedChannelId, payload: Buffer) {
663
+ const offerParameters = this.formatter.deserializeOfferParameters(payload)
664
+ const channel = new ChannelClass(this, channelId, offerParameters)
665
+ let acceptingChannelAlreadyPresent = false
666
+ let options: ChannelOptions | undefined
667
+
668
+ let acceptingChannels: Deferred<ChannelClass>[]
669
+ if ((acceptingChannels = this.acceptingChannels[offerParameters.name]) !== undefined) {
670
+ while (acceptingChannels.length > 0) {
671
+ const candidate = acceptingChannels.shift()!
672
+ if (candidate.resolve(channel)) {
673
+ acceptingChannelAlreadyPresent = true
674
+ options = candidate.state as ChannelOptions
675
+ break
676
+ }
677
+ }
678
+ }
679
+
680
+ if (!acceptingChannelAlreadyPresent) {
681
+ let offeredChannels: Channel[]
682
+ if (!(offeredChannels = this.channelsOfferedByThemByName[offerParameters.name])) {
683
+ this.channelsOfferedByThemByName[offerParameters.name] = offeredChannels = []
684
+ }
685
+
686
+ offeredChannels.push(channel)
687
+ }
688
+
689
+ this.setOpenChannel(channel)
690
+
691
+ if (acceptingChannelAlreadyPresent) {
692
+ this.acceptChannelOrThrow(channel, options)
693
+ }
694
+
695
+ this.raiseChannelOffered(channel.id, channel.name, acceptingChannelAlreadyPresent)
696
+ }
697
+
698
+ private onOfferAccepted(channelId: QualifiedChannelId, payload: Buffer) {
699
+ if (channelId.source !== ChannelSource.Local) {
700
+ throw new Error('Remote party tried to accept a channel that they offered.')
701
+ }
702
+
703
+ const acceptanceParameter = this.formatter.deserializeAcceptanceParameters(payload)
704
+ const channel = this.getOpenChannel(channelId)
705
+ if (!channel) {
706
+ throw new Error(`Unexpected channel created with ID ${QualifiedChannelId.toString(channelId)}`)
707
+ }
708
+
709
+ if (!channel.onAccepted(acceptanceParameter)) {
710
+ // This may be an acceptance of a channel that we canceled an offer for, and a race condition
711
+ // led to our cancellation notification crossing in transit with their acceptance notification.
712
+ // In this case, do nothing since we already sent a channel termination message, and the remote side
713
+ // should notice it soon.
714
+ }
715
+ }
716
+
717
+ private onContent(channelId: QualifiedChannelId, payload: Buffer) {
718
+ const channel = this.getOpenChannel(channelId)
719
+ if (!channel) {
720
+ throw new Error(`No channel with id ${channelId} found.`)
721
+ }
722
+
723
+ channel.onContent(payload)
724
+ }
725
+
726
+ private onContentProcessed(channelId: QualifiedChannelId, payload: Buffer) {
727
+ const channel = this.getOpenChannel(channelId)
728
+ if (!channel) {
729
+ throw new Error(`No channel with id ${channelId} found.`)
730
+ }
731
+
732
+ const bytesProcessed = this.formatter.deserializeContentProcessed(payload)
733
+ channel.onContentProcessed(bytesProcessed)
734
+ }
735
+
736
+ private onContentWritingCompleted(channelId: QualifiedChannelId) {
737
+ const channel = this.getOpenChannel(channelId)
738
+ if (!channel) {
739
+ throw new Error(`No channel with id ${channelId} found.`)
740
+ }
741
+
742
+ channel.onContent(null) // signify that the remote is done writing.
743
+ }
744
+
745
+ /**
746
+ * Occurs when the remote party has terminated a channel (including canceling an offer).
747
+ * @param channelId The ID of the terminated channel.
748
+ */
749
+ private onChannelTerminated(channelId: QualifiedChannelId, payload: Buffer) {
750
+ const channel = this.getOpenChannel(channelId)
751
+ if (channel) {
752
+ this.deleteOpenChannel(channelId)
753
+ this.removeChannelFromOfferedQueue(channel)
754
+
755
+ // Extract the exception that we received from the remote side.
756
+ const remoteException = this.protocolMajorVersion > 1 ? (this.formatter as MultiplexingStreamV2Formatter).deserializeException(payload) : null
757
+
758
+ channel.dispose(remoteException)
759
+ }
760
+ }
761
+ }