-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmuxer.ts
606 lines (509 loc) · 17.3 KB
/
muxer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
import { InvalidParametersError, MuxerClosedError, TooManyOutboundProtocolStreamsError, serviceCapabilities, setMaxListeners } from '@libp2p/interface'
import { getIterator } from 'get-iterator'
import { pushable, type Pushable } from 'it-pushable'
import { Uint8ArrayList } from 'uint8arraylist'
import { type Config, defaultConfig, verifyConfig } from './config.js'
import { PROTOCOL_ERRORS } from './constants.js'
import { Decoder } from './decode.js'
import { encodeHeader } from './encode.js'
import { InvalidFrameError, NotMatchingPingError, UnrequestedPingError } from './errors.js'
import { Flag, type FrameHeader, FrameType, GoAwayCode } from './frame.js'
import { StreamState, YamuxStream } from './stream.js'
import type { YamuxMuxerComponents } from './index.js'
import type { AbortOptions, ComponentLogger, Logger, Stream, StreamMuxer, StreamMuxerFactory, StreamMuxerInit } from '@libp2p/interface'
import type { Sink, Source } from 'it-stream-types'
const YAMUX_PROTOCOL_ID = '/yamux/1.0.0'
const CLOSE_TIMEOUT = 500
export interface YamuxMuxerInit extends StreamMuxerInit, Partial<Config> {
}
export class Yamux implements StreamMuxerFactory {
protocol = YAMUX_PROTOCOL_ID
private readonly _components: YamuxMuxerComponents
private readonly _init: YamuxMuxerInit
constructor (components: YamuxMuxerComponents, init: YamuxMuxerInit = {}) {
this._components = components
this._init = init
}
readonly [Symbol.toStringTag] = '@chainsafe/libp2p-yamux'
readonly [serviceCapabilities]: string[] = [
'@libp2p/stream-multiplexing'
]
createStreamMuxer (init?: YamuxMuxerInit): YamuxMuxer {
return new YamuxMuxer(this._components, {
...this._init,
...init
})
}
}
export interface CloseOptions extends AbortOptions {
reason?: GoAwayCode
}
export class YamuxMuxer implements StreamMuxer {
protocol = YAMUX_PROTOCOL_ID
source: Pushable<Uint8ArrayList | Uint8Array>
sink: Sink<Source<Uint8ArrayList | Uint8Array>, Promise<void>>
private readonly config: Config
private readonly log?: Logger
private readonly logger: ComponentLogger
/** Used to close the muxer from either the sink or source */
private readonly closeController: AbortController
/** The next stream id to be used when initiating a new stream */
private nextStreamID: number
/** Primary stream mapping, streamID => stream */
private readonly _streams: Map<number, YamuxStream>
/** The next ping id to be used when pinging */
private nextPingID: number
/** Tracking info for the currently active ping */
private activePing?: { id: number, promise: Promise<void>, resolve(): void }
/** Round trip time */
private rtt: number
/** True if client, false if server */
private readonly client: boolean
private localGoAway?: GoAwayCode
private remoteGoAway?: GoAwayCode
/** Number of tracked inbound streams */
private numInboundStreams: number
/** Number of tracked outbound streams */
private numOutboundStreams: number
private readonly onIncomingStream?: (stream: Stream) => void
private readonly onStreamEnd?: (stream: Stream) => void
constructor (components: YamuxMuxerComponents, init: YamuxMuxerInit) {
this.client = init.direction === 'outbound'
this.config = { ...defaultConfig, ...init }
this.logger = components.logger
this.log = this.logger.forComponent('libp2p:yamux')
verifyConfig(this.config)
this.closeController = new AbortController()
setMaxListeners(Infinity, this.closeController.signal)
this.onIncomingStream = init.onIncomingStream
this.onStreamEnd = init.onStreamEnd
this._streams = new Map()
this.source = pushable({
onEnd: (): void => {
this.log?.trace('muxer source ended')
this._streams.forEach(stream => {
stream.destroy()
})
}
})
this.sink = async (source: Source<Uint8ArrayList | Uint8Array>): Promise<void> => {
const shutDownListener = (): void => {
const iterator = getIterator(source)
if (iterator.return != null) {
const res = iterator.return()
if (isPromise(res)) {
res.catch(err => {
this.log?.('could not cause sink source to return', err)
})
}
}
}
let reason, error
try {
const decoder = new Decoder(source)
try {
this.closeController.signal.addEventListener('abort', shutDownListener)
for await (const frame of decoder.emitFrames()) {
await this.handleFrame(frame.header, frame.readData)
}
} finally {
this.closeController.signal.removeEventListener('abort', shutDownListener)
}
reason = GoAwayCode.NormalTermination
} catch (err: any) {
// either a protocol or internal error
if (PROTOCOL_ERRORS.has(err.name)) {
this.log?.error('protocol error in sink', err)
reason = GoAwayCode.ProtocolError
} else {
this.log?.error('internal error in sink', err)
reason = GoAwayCode.InternalError
}
error = err as Error
}
this.log?.trace('muxer sink ended')
if (error != null) {
this.abort(error, reason)
} else {
await this.close({ reason })
}
}
this.numInboundStreams = 0
this.numOutboundStreams = 0
// client uses odd streamIDs, server uses even streamIDs
this.nextStreamID = this.client ? 1 : 2
this.nextPingID = 0
this.rtt = -1
this.log?.trace('muxer created')
if (this.config.enableKeepAlive) {
this.keepAliveLoop().catch(e => this.log?.error('keepalive error: %s', e))
}
// send an initial ping to establish RTT
this.ping().catch(e => this.log?.error('ping error: %s', e))
}
get streams (): YamuxStream[] {
return Array.from(this._streams.values())
}
newStream (name?: string | undefined): YamuxStream {
if (this.remoteGoAway !== undefined) {
throw new MuxerClosedError('Muxer closed remotely')
}
if (this.localGoAway !== undefined) {
throw new MuxerClosedError('Muxer closed locally')
}
const id = this.nextStreamID
this.nextStreamID += 2
// check against our configured maximum number of outbound streams
if (this.numOutboundStreams >= this.config.maxOutboundStreams) {
throw new TooManyOutboundProtocolStreamsError('max outbound streams exceeded')
}
this.log?.trace('new outgoing stream id=%s', id)
const stream = this._newStream(id, name, StreamState.Init, 'outbound')
this._streams.set(id, stream)
this.numOutboundStreams++
// send a window update to open the stream on the receiver end
stream.sendWindowUpdate()
return stream
}
/**
* Initiate a ping and wait for a response
*
* Note: only a single ping will be initiated at a time.
* If a ping is already in progress, a new ping will not be initiated.
*
* @returns the round-trip-time in milliseconds
*/
async ping (): Promise<number> {
if (this.remoteGoAway !== undefined) {
throw new MuxerClosedError('Muxer closed remotely')
}
if (this.localGoAway !== undefined) {
throw new MuxerClosedError('Muxer closed locally')
}
// An active ping does not yet exist, handle the process here
if (this.activePing === undefined) {
// create active ping
let _resolve = (): void => {}
this.activePing = {
id: this.nextPingID++,
// this promise awaits resolution or the close controller aborting
promise: new Promise<void>((resolve, reject) => {
const closed = (): void => {
reject(new MuxerClosedError('Muxer closed locally'))
}
this.closeController.signal.addEventListener('abort', closed, { once: true })
_resolve = (): void => {
this.closeController.signal.removeEventListener('abort', closed)
resolve()
}
}),
resolve: _resolve
}
// send ping
const start = Date.now()
this.sendPing(this.activePing.id)
// await pong
try {
await this.activePing.promise
} finally {
// clean-up active ping
delete this.activePing
}
// update rtt
const end = Date.now()
this.rtt = end - start
} else {
// an active ping is already in progress, piggyback off that
await this.activePing.promise
}
return this.rtt
}
/**
* Get the ping round trip time
*
* Note: Will return 0 if no successful ping has yet been completed
*
* @returns the round-trip-time in milliseconds
*/
getRTT (): number {
return this.rtt
}
/**
* Close the muxer
*/
async close (options: CloseOptions = {}): Promise<void> {
if (this.closeController.signal.aborted) {
// already closed
return
}
const reason = options?.reason ?? GoAwayCode.NormalTermination
this.log?.trace('muxer close reason=%s', reason)
if (options.signal == null) {
const signal = AbortSignal.timeout(CLOSE_TIMEOUT)
setMaxListeners(Infinity, signal)
options = {
...options,
signal
}
}
try {
await Promise.all(
[...this._streams.values()].map(async s => s.close(options))
)
// send reason to the other side, allow the other side to close gracefully
this.sendGoAway(reason)
this._closeMuxer()
} catch (err: any) {
this.abort(err)
}
}
abort (err: Error, reason?: GoAwayCode): void {
if (this.closeController.signal.aborted) {
// already closed
return
}
reason = reason ?? GoAwayCode.InternalError
// If reason was provided, use that, otherwise use the presence of `err` to determine the reason
this.log?.error('muxer abort reason=%s error=%s', reason, err)
// Abort all underlying streams
for (const stream of this._streams.values()) {
stream.abort(err)
}
// send reason to the other side, allow the other side to close gracefully
this.sendGoAway(reason)
this._closeMuxer()
}
isClosed (): boolean {
return this.closeController.signal.aborted
}
/**
* Called when either the local or remote shuts down the muxer
*/
private _closeMuxer (): void {
// stop the sink and any other processes
this.closeController.abort()
// stop the source
this.source.end()
}
/** Create a new stream */
private _newStream (id: number, name: string | undefined, state: StreamState, direction: 'inbound' | 'outbound'): YamuxStream {
if (this._streams.get(id) != null) {
throw new InvalidParametersError('Stream already exists with that id')
}
const stream = new YamuxStream({
id: id.toString(),
name,
state,
direction,
sendFrame: this.sendFrame.bind(this),
onEnd: () => {
this.closeStream(id)
this.onStreamEnd?.(stream)
},
log: this.logger.forComponent(`libp2p:yamux:${direction}:${id}`),
config: this.config,
getRTT: this.getRTT.bind(this)
})
return stream
}
/**
* closeStream is used to close a stream once both sides have
* issued a close.
*/
private closeStream (id: number): void {
if (this.client === (id % 2 === 0)) {
this.numInboundStreams--
} else {
this.numOutboundStreams--
}
this._streams.delete(id)
}
private async keepAliveLoop (): Promise<void> {
const abortPromise = new Promise((_resolve, reject) => { this.closeController.signal.addEventListener('abort', reject, { once: true }) })
this.log?.trace('muxer keepalive enabled interval=%s', this.config.keepAliveInterval)
while (true) {
let timeoutId
try {
await Promise.race([
abortPromise,
new Promise((resolve) => {
timeoutId = setTimeout(resolve, this.config.keepAliveInterval)
})
])
this.ping().catch(e => this.log?.error('ping error: %s', e))
} catch (e) {
// closed
clearInterval(timeoutId)
return
}
}
}
private async handleFrame (header: FrameHeader, readData?: () => Promise<Uint8ArrayList>): Promise<void> {
const {
streamID,
type,
length
} = header
this.log?.trace('received frame %o', header)
if (streamID === 0) {
switch (type) {
case FrameType.Ping:
{ this.handlePing(header); return }
case FrameType.GoAway:
{ this.handleGoAway(length); return }
default:
// Invalid state
throw new InvalidFrameError('Invalid frame type')
}
} else {
switch (header.type) {
case FrameType.Data:
case FrameType.WindowUpdate:
{ await this.handleStreamMessage(header, readData); return }
default:
// Invalid state
throw new InvalidFrameError('Invalid frame type')
}
}
}
private handlePing (header: FrameHeader): void {
// If the ping is initiated by the sender, send a response
if (header.flag === Flag.SYN) {
this.log?.trace('received ping request pingId=%s', header.length)
this.sendPing(header.length, Flag.ACK)
} else if (header.flag === Flag.ACK) {
this.log?.trace('received ping response pingId=%s', header.length)
this.handlePingResponse(header.length)
} else {
// Invalid state
throw new InvalidFrameError('Invalid frame flag')
}
}
private handlePingResponse (pingId: number): void {
if (this.activePing === undefined) {
// this ping was not requested
throw new UnrequestedPingError('ping not requested')
}
if (this.activePing.id !== pingId) {
// this ping doesn't match our active ping request
throw new NotMatchingPingError('ping doesn\'t match our id')
}
// valid ping response
this.activePing.resolve()
}
private handleGoAway (reason: GoAwayCode): void {
this.log?.trace('received GoAway reason=%s', GoAwayCode[reason] ?? 'unknown')
this.remoteGoAway = reason
// If the other side is friendly, they would have already closed all streams before sending a GoAway
// In case they weren't, reset all streams
for (const stream of this._streams.values()) {
stream.reset()
}
this._closeMuxer()
}
private async handleStreamMessage (header: FrameHeader, readData?: () => Promise<Uint8ArrayList>): Promise<void> {
const { streamID, flag, type } = header
if ((flag & Flag.SYN) === Flag.SYN) {
this.incomingStream(streamID)
}
const stream = this._streams.get(streamID)
if (stream === undefined) {
if (type === FrameType.Data) {
this.log?.('discarding data for stream id=%s', streamID)
if (readData === undefined) {
throw new Error('unreachable')
}
await readData()
} else {
this.log?.trace('frame for missing stream id=%s', streamID)
}
return
}
switch (type) {
case FrameType.WindowUpdate: {
stream.handleWindowUpdate(header); return
}
case FrameType.Data: {
if (readData === undefined) {
throw new Error('unreachable')
}
await stream.handleData(header, readData); return
}
default:
throw new Error('unreachable')
}
}
private incomingStream (id: number): void {
if (this.client !== (id % 2 === 0)) {
throw new InvalidParametersError('Both endpoints are clients')
}
if (this._streams.has(id)) {
return
}
this.log?.trace('new incoming stream id=%s', id)
if (this.localGoAway !== undefined) {
// reject (reset) immediately if we are doing a go away
this.sendFrame({
type: FrameType.WindowUpdate,
flag: Flag.RST,
streamID: id,
length: 0
}); return
}
// check against our configured maximum number of inbound streams
if (this.numInboundStreams >= this.config.maxInboundStreams) {
this.log?.('maxIncomingStreams exceeded, forcing stream reset')
this.sendFrame({
type: FrameType.WindowUpdate,
flag: Flag.RST,
streamID: id,
length: 0
}); return
}
// allocate a new stream
const stream = this._newStream(id, undefined, StreamState.SYNReceived, 'inbound')
this.numInboundStreams++
// the stream should now be tracked
this._streams.set(id, stream)
this.onIncomingStream?.(stream)
}
private sendFrame (header: FrameHeader, data?: Uint8ArrayList): void {
this.log?.trace('sending frame %o', header)
if (header.type === FrameType.Data) {
if (data === undefined) {
throw new InvalidFrameError('Invalid frame')
}
this.source.push(
new Uint8ArrayList(encodeHeader(header), data)
)
} else {
this.source.push(encodeHeader(header))
}
}
private sendPing (pingId: number, flag: Flag = Flag.SYN): void {
if (flag === Flag.SYN) {
this.log?.trace('sending ping request pingId=%s', pingId)
} else {
this.log?.trace('sending ping response pingId=%s', pingId)
}
this.sendFrame({
type: FrameType.Ping,
flag,
streamID: 0,
length: pingId
})
}
private sendGoAway (reason: GoAwayCode = GoAwayCode.NormalTermination): void {
this.log?.('sending GoAway reason=%s', GoAwayCode[reason])
this.localGoAway = reason
this.sendFrame({
type: FrameType.GoAway,
flag: 0,
streamID: 0,
length: reason
})
}
}
function isPromise <T = unknown> (thing: any): thing is Promise<T> {
return thing != null && typeof thing.then === 'function'
}