Repository navigation
Expand file tree
/
Copy pathdata-readiness.js
More file actions
52 lines (48 loc) · 1.64 KB
/
Copy pathdata-readiness.js
File metadata and controls
52 lines (48 loc) · 1.64 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
'use strict'
const { PROTOCOL_VERSION } = require('./protocol')
const { tryParseJSON } = require('./utils')
const { startSocketDeadline } = require('./lifecycle')
const { bridgeSockets } = require('./socket-bridge')
function bridgeWhenReady(dataSocket, localSocket, { messaging, timeout, trace, onSetupFailed }) {
const clearDeadline = startSocketDeadline(
dataSocket,
timeout,
trace && (() => trace('data-readiness-timeout', { timeoutMs: timeout }))
)
const decodeReady = messaging.createFirstMessageDecoder(
(data, remainder) => {
const message = tryParseJSON(data)
if (!message || message.protocolVersion !== PROTOCOL_VERSION || message.ready !== true) {
trace?.('invalid-data-ready')
return dataSocket.destroy()
}
if (localSocket.destroyed) return dataSocket.destroy()
trace?.('bridge-ready', { remainderBytes: remainder.length })
cleanup()
bridgeSockets(dataSocket, localSocket, { leftInitialData: remainder })
},
() => {
trace?.('invalid-data-frame')
dataSocket.destroy()
}
)
const onEnd = () => dataSocket.destroy()
const onLocalClose = () => dataSocket.destroy()
const onDataClose = () => {
cleanup()
onSetupFailed?.()
localSocket.destroy()
}
dataSocket.on('data', decodeReady)
dataSocket.once('end', onEnd)
dataSocket.once('close', onDataClose)
localSocket.once('close', onLocalClose)
function cleanup() {
clearDeadline()
dataSocket.off('data', decodeReady)
dataSocket.off('end', onEnd)
dataSocket.off('close', onDataClose)
localSocket.off('close', onLocalClose)
}
}
module.exports = { bridgeWhenReady }