forked from feross/simple-peer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatachannel.js
More file actions
259 lines (212 loc) · 6.56 KB
/
Copy pathdatachannel.js
File metadata and controls
259 lines (212 loc) · 6.56 KB
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
/*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
var debug = require('debug')('simple-peer')
var stream = require('readable-stream')
var errCode = require('err-code')
var MAX_BUFFERED_AMOUNT = 64 * 1024
var CHANNEL_CLOSING_TIMEOUT = 5 * 1000
var CHANNEL_CLOSE_DELAY = 3 * 1000
function closeChannel (channel) {
try {
channel.close()
} catch (err) { }
}
class DataChannel extends stream.Duplex {
constructor (opts = {}) {
opts = Object.assign({
allowHalfOpen: false
}, opts)
super(opts)
this.closed = false
this._chunk = null
this._cb = null
this._interval = null
this._channel = null
this._fresh = true
this._open = false
this.channelName = opts.channelName || null
this.channelConfig = opts.channelConfig || DataChannel.channelConfig
this.channelNegotiated = this.channelConfig.negotiated
// HACK: Chrome will sometimes get stuck in readyState "closing", let's check for this condition
var isClosing = false
this._closingInterval = setInterval(() => { // No "onclosing" event
if (this._channel && this._channel.readyState === 'closing') {
if (isClosing) this._onChannelClose() // Equivalent to onclose firing.
isClosing = true
} else {
isClosing = false
}
}, CHANNEL_CLOSING_TIMEOUT)
}
_setDataChannel (channel) {
this._channel = channel
this._channel.binaryType = 'arraybuffer'
if (typeof this._channel.bufferedAmountLowThreshold === 'number') {
this._channel.bufferedAmountLowThreshold = MAX_BUFFERED_AMOUNT
}
this.channelName = this._channel.label.split('@')[0]
this._channel.onmessage = event => {
this._onChannelMessage(event)
}
this._channel.onbufferedamountlow = () => {
this._onChannelBufferedAmountLow()
}
this._channel.onopen = () => {
this._onChannelOpen()
}
this._channel.onclose = () => {
this._onChannelClose()
}
this._channel.onerror = err => {
this.close(errCode(err, 'ERR_DATA_CHANNEL'))
}
this._onFinishBound = () => {
this._onFinish()
}
this.once('finish', this._onFinishBound)
}
_read () { }
_write (chunk, encoding, cb) {
if (this.closed) return cb(errCode(new Error('cannot write after channel is closed'), 'ERR_DATA_CHANNEL'))
if (this._channel && this._channel.readyState === 'open') {
try {
this.send(chunk)
} catch (err) {
this.close(errCode(err, 'ERR_DATA_CHANNEL'))
}
if (this._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) {
this._debug('start backpressure: bufferedAmount %d', this._channel.bufferedAmount)
this._cb = cb
} else {
cb(null)
}
} else {
this._debug('write before connect')
this._chunk = chunk
this._cb = cb
}
}
// When stream finishes writing, close socket. Half open connections are not
// supported.
_onFinish () {
if (this.closed) return
// Wait a bit before closing so the socket flushes.
// TODO: is there a more reliable way to accomplish this?
const closeSoon = () => {
setTimeout(() => this.close(), 1000)
}
if (this._open) {
closeSoon()
} else {
this.once('open', closeSoon)
}
}
_onInterval () {
if (!this._cb || !this._channel || this._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) {
return
}
this._onChannelBufferedAmountLow()
}
_onChannelMessage (event) {
if (this.closed) return
var data = event.data
if (data instanceof ArrayBuffer) data = Buffer.from(data)
this.push(data)
}
_onChannelBufferedAmountLow () {
if (this.closed || !this._cb) return
this._debug('ending backpressure: bufferedAmount %d', this._channel.bufferedAmount)
var cb = this._cb
this._cb = null
cb(null)
}
_onChannelOpen () {
this._debug('on channel open', this.channelName)
this._open = true
this.emit('open')
this._sendChunk()
setTimeout(() => {
this._fresh = false
}, CHANNEL_CLOSE_DELAY)
}
_onChannelClose () {
this._debug('on channel close')
return this.close()
}
_sendChunk () { // called when peer connects or this._channel set
if (this.closed) return
if (this._chunk) {
try {
this.send(this._chunk)
} catch (err) {
return this.close(errCode(err, 'ERR_DATA_CHANNEL'))
}
this._chunk = null
this._debug('sent chunk from "write before connect"')
var cb = this._cb
this._cb = null
cb(null)
}
// If `bufferedAmountLowThreshold` and 'onbufferedamountlow' are unsupported,
// fallback to using setInterval to implement backpressure.
if (!this._interval && typeof this._channel.bufferedAmountLowThreshold !== 'number') {
this._interval = setInterval(() => { this._onInterval() }, 150)
if (this._interval.unref) this._interval.unref()
}
}
get bufferSize () {
return (this._channel && this._channel.bufferedAmount) || 0
}
/**
* Send text/binary data to the remote peer.
* @param {ArrayBufferView|ArrayBuffer|Buffer|string|Blob} chunk
*/
send (chunk) {
this._channel.send(chunk)
}
destroy (err) {
DataChannel.prototype._destroy.call(this, err, () => { })
}
_destroy (err, cb) {
this.close(err)
cb()
}
close (err) {
if (this.closed) return
this._debug('close datachannel (error: %s)', err && (err.message || err))
if (this._channel) {
if (this._fresh) { // HACK: Safari sometimes cannot close channels immediately after opening them
setTimeout(closeChannel.bind(this, this._channel), CHANNEL_CLOSE_DELAY)
} else {
closeChannel(this._channel)
}
this._channel.onmessage = null
this._channel.onopen = null
this._channel.onclose = null
this._channel.onerror = null
this._channel = null
}
this.readable = this.writable = false
if (!this._readableState.ended) this.push(null)
if (!this._writableState.finished) this.end()
this.closed = true
this._open = false
clearInterval(this._closingInterval)
this._closingInterval = null
clearInterval(this._interval)
this._interval = null
this._chunk = null
this._cb = null
this.channelName = null
if (this._onFinishBound) this.removeListener('finish', this._onFinishBound)
this._onFinishBound = null
if (err) this.emit('error', err)
this.emit('close')
}
_debug () {
var args = [].slice.call(arguments)
args[0] = '[' + this._id + '] ' + args[0]
debug.apply(null, args)
}
}
DataChannel.channelConfig = {}
module.exports = DataChannel