Repository navigation
Expand file tree
/
Copy pathpeer-session.js
More file actions
197 lines (175 loc) · 5.29 KB
/
Copy pathpeer-session.js
File metadata and controls
197 lines (175 loc) · 5.29 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
'use strict'
const { createDiagnostics } = require('./diagnostics')
const { connectToRelay } = require('./relay-connection')
const { PROTOCOL_VERSION, CONNECTION_KINDS } = require('./protocol')
const { tryParseJSON } = require('./utils')
const { enableSocketKeepAlive, startSocketDeadline, createBackoff, destroySockets } = require('./lifecycle')
function createPeerSession({
config,
messaging,
type,
name,
portCount = 1,
onConnected,
onDisconnected,
onMessage,
onFatal,
errorLabel = 'CONTROL_SOCKET'
}) {
const { log, sendJson, createMessageDecoder } = messaging
const { debug, traceSocket } = createDiagnostics(log)
const backoff = createBackoff({
baseDelay: config.reconnectDelay,
maxDelay: config.reconnectMaxDelay,
jitterPercent: config.reconnectJitterPercent
})
let socket
let uuid
let reconnectTimer
let pinger
let pongDeadline
let stopping = false
let fatalError = false
let connected = false
function start() {
if (!stopping && !fatalError && !socket) connect()
}
function connect() {
if (stopping || fatalError) return
let trace
const nextSocket = connectToRelay(config, {}, () => {
enableSocketKeepAlive(nextSocket)
const message = {
kind: CONNECTION_KINDS.CONTROL,
type,
name,
portCount
}
if (uuid) message.uuid = uuid
sendJson(nextSocket, message)
})
trace = traceSocket?.(nextSocket, `${type}-control`)
const clearReadinessDeadline = startSocketDeadline(
nextSocket,
config.handshakeTimeout,
trace &&
(() => {
trace('registration-timeout', { timeoutMs: config.handshakeTimeout })
})
)
const decodeMessage = createMessageDecoder(
data => handleMessage(nextSocket, data, clearReadinessDeadline, trace),
() => {
trace?.('invalid-control-frame')
nextSocket.destroy()
}
)
socket = nextSocket
nextSocket.on('data', decodeMessage)
nextSocket.on('error', error => log.err(errorLabel, error.name || error.code, error.message))
nextSocket.on('close', () => {
clearReadinessDeadline()
nextSocket.removeListener('data', decodeMessage)
if (nextSocket !== socket) return
const wasConnected = connected
socket = undefined
connected = false
clearPinger()
if (wasConnected) onDisconnected()
if (!stopping && !fatalError) connectWithDelay(backoff.next())
})
}
function handleMessage(messageSocket, data, clearReadinessDeadline, trace) {
if (messageSocket !== socket) return
const message = tryParseJSON(data)
if (!message || typeof message !== 'object') return messageSocket.destroy()
if (message.protocolVersion !== PROTOCOL_VERSION) {
return fail(
`protocol version mismatch: ${type}=${PROTOCOL_VERSION}, relay=${message.protocolVersion ?? 'unknown'}`
)
}
const registration = isRegistration(message)
if (registration) uuid = message.registration.uuid
if (!connected && registration) {
clearReadinessDeadline()
trace?.('relay-registered')
connected = true
backoff.reset()
startPinger(messageSocket)
onConnected()
} else if (!connected && !message.error) {
return messageSocket.destroy()
}
if (message.pong) {
clearTimeout(pongDeadline)
pongDeadline = undefined
return
}
onMessage(message, {
disconnect() {
messageSocket.destroy()
},
fail
})
}
function connectWithDelay(delay) {
if (stopping || fatalError) return
if (reconnectTimer) clearTimeout(reconnectTimer)
debug?.(`${errorLabel} reconnect-scheduled`, { delayMs: delay })
reconnectTimer = setTimeout(() => {
reconnectTimer = undefined
connect()
}, delay)
}
function startPinger(activeSocket) {
clearPinger()
pinger = setInterval(() => {
if (pongDeadline) return
pongDeadline = setTimeout(() => {
log.info(`${errorLabel}: relay pong timed out; reconnecting`)
activeSocket.destroy()
}, config.heartbeatTimeout ?? 7_000)
sendJson(activeSocket, { ping: true })
}, config.heartbeatInterval ?? 2_000)
}
function clearPinger() {
clearTimeout(pongDeadline)
pongDeadline = undefined
if (pinger) clearInterval(pinger)
pinger = undefined
}
function fail(error) {
if (fatalError) return
fatalError = true
const fatal = error instanceof Error ? error : new Error(error)
log.info(fatal.message)
if (reconnectTimer) clearTimeout(reconnectTimer)
reconnectTimer = undefined
clearPinger()
if (socket && !socket.destroyed) socket.destroy()
onFatal(fatal)
}
function send(message) {
return sendJson(socket, message)
}
async function close() {
stopping = true
if (reconnectTimer) clearTimeout(reconnectTimer)
reconnectTimer = undefined
clearPinger()
await destroySockets(socket ? [socket] : [])
}
function getState() {
return { connected, stopping, fatal: fatalError }
}
return { start, close, send, fail, getState }
}
function isRegistration(message) {
return (
message.registration &&
typeof message.registration.uuid === 'string' &&
message.registration.uuid.length > 0 &&
typeof message.registration.ready === 'boolean'
)
}
module.exports = { createPeerSession }