This repository has been archived by the owner on Jul 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
/
muxer.js
73 lines (60 loc) · 1.77 KB
/
muxer.js
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
'use strict'
const EventEmitter = require('events').EventEmitter
const Connection = require('interface-connection').Connection
const toPull = require('stream-to-pull-stream')
const pull = require('pull-stream')
const pullCatch = require('pull-catch')
const setImmediate = require('async/setImmediate')
const MULTIPLEX_CODEC = require('./codec')
function noop () {}
// Catch error makes sure that even though we get the "Channel destroyed" error
// from when closing streams, that it's not leaking through since it's not
// really an error for us, channels shoul close cleanly.
function catchError (stream) {
return {
source: pull(
stream.source,
pullCatch((err) => {
if (err.message === 'Channel destroyed') {
return
}
return false
})
),
sink: stream.sink
}
}
class MultiplexMuxer extends EventEmitter {
constructor (conn, multiplex) {
super()
this.multiplex = multiplex
this.conn = conn
this.multicodec = MULTIPLEX_CODEC
multiplex.on('close', () => this.emit('close'))
multiplex.on('error', (err) => this.emit('error', err))
multiplex.on('stream', (stream, id) => {
const muxedConn = new Connection(
catchError(toPull.duplex(stream)),
this.conn
)
this.emit('stream', muxedConn)
})
}
// method added to enable pure stream muxer feeling
newStream (callback) {
callback = callback || noop
let stream = this.multiplex.createStream()
const conn = new Connection(
catchError(toPull.duplex(stream)),
this.conn
)
setImmediate(() => callback(null, conn))
return conn
}
end (callback) {
callback = callback || noop
this.multiplex.once('close', callback)
this.multiplex.destroy()
}
}
module.exports = MultiplexMuxer