-
Notifications
You must be signed in to change notification settings - Fork 445
/
socket-to-conn.ts
222 lines (184 loc) · 6.99 KB
/
socket-to-conn.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
import { CodeError } from '@libp2p/interface'
import { ipPortToMultiaddr as toMultiaddr } from '@libp2p/utils/ip-port-to-multiaddr'
import { duplex } from 'stream-to-it'
import { CLOSE_TIMEOUT, SOCKET_TIMEOUT } from './constants.js'
import { multiaddrToNetConfig } from './utils.js'
import type { ComponentLogger, MultiaddrConnection, CounterGroup } from '@libp2p/interface'
import type { AbortOptions, Multiaddr } from '@multiformats/multiaddr'
import type { Socket } from 'net'
interface ToConnectionOptions {
listeningAddr?: Multiaddr
remoteAddr?: Multiaddr
localAddr?: Multiaddr
socketInactivityTimeout?: number
socketCloseTimeout?: number
metrics?: CounterGroup
metricPrefix?: string
logger: ComponentLogger
}
/**
* Convert a socket into a MultiaddrConnection
* https://github.com/libp2p/interface-transport#multiaddrconnection
*/
export const toMultiaddrConnection = (socket: Socket, options: ToConnectionOptions): MultiaddrConnection => {
let closePromise: Promise<void> | null = null
const log = options.logger.forComponent('libp2p:tcp:socket')
const metrics = options.metrics
const metricPrefix = options.metricPrefix ?? ''
const inactivityTimeout = options.socketInactivityTimeout ?? SOCKET_TIMEOUT
const closeTimeout = options.socketCloseTimeout ?? CLOSE_TIMEOUT
// Check if we are connected on a unix path
if (options.listeningAddr?.getPath() != null) {
options.remoteAddr = options.listeningAddr
}
if (options.remoteAddr?.getPath() != null) {
options.localAddr = options.remoteAddr
}
let remoteAddr: Multiaddr
if (options.remoteAddr != null) {
remoteAddr = options.remoteAddr
} else {
if (socket.remoteAddress == null || socket.remotePort == null) {
// this can be undefined if the socket is destroyed (for example, if the client disconnected)
// https://nodejs.org/dist/latest-v16.x/docs/api/net.html#socketremoteaddress
throw new CodeError('Could not determine remote address or port', 'ERR_NO_REMOTE_ADDRESS')
}
remoteAddr = toMultiaddr(socket.remoteAddress, socket.remotePort)
}
const lOpts = multiaddrToNetConfig(remoteAddr)
const lOptsStr = lOpts.path ?? `${lOpts.host ?? ''}:${lOpts.port ?? ''}`
const { sink, source } = duplex(socket)
// by default there is no timeout
// https://nodejs.org/dist/latest-v16.x/docs/api/net.html#socketsettimeouttimeout-callback
socket.setTimeout(inactivityTimeout, () => {
log('%s socket read timeout', lOptsStr)
metrics?.increment({ [`${metricPrefix}timeout`]: true })
// only destroy with an error if the remote has not sent the FIN message
let err: Error | undefined
if (socket.readable) {
err = new CodeError('Socket read timeout', 'ERR_SOCKET_READ_TIMEOUT')
}
// if the socket times out due to inactivity we must manually close the connection
// https://nodejs.org/dist/latest-v16.x/docs/api/net.html#event-timeout
socket.destroy(err)
})
socket.once('close', () => {
log('%s socket close', lOptsStr)
metrics?.increment({ [`${metricPrefix}close`]: true })
// In instances where `close` was not explicitly called,
// such as an iterable stream ending, ensure we have set the close
// timeline
if (maConn.timeline.close == null) {
maConn.timeline.close = Date.now()
}
})
socket.once('end', () => {
// the remote sent a FIN packet which means no more data will be sent
// https://nodejs.org/dist/latest-v16.x/docs/api/net.html#event-end
log('%s socket end', lOptsStr)
metrics?.increment({ [`${metricPrefix}end`]: true })
})
const maConn: MultiaddrConnection = {
async sink (source) {
try {
await sink((async function * () {
for await (const buf of source) {
if (buf instanceof Uint8Array) {
yield buf
} else {
yield buf.subarray()
}
}
})())
} catch (err: any) {
// If aborted we can safely ignore
if (err.type !== 'aborted') {
// If the source errored the socket will already have been destroyed by
// duplex(). If the socket errored it will already be
// destroyed. There's nothing to do here except log the error & return.
log.error('%s error in sink', lOptsStr, err)
}
}
// we have finished writing, send the FIN message
socket.end()
},
source,
// If the remote address was passed, use it - it may have the peer ID encapsulated
remoteAddr,
timeline: { open: Date.now() },
async close (options: AbortOptions = {}) {
if (socket.destroyed) {
log('The %s socket is destroyed', lOptsStr)
return
}
if (closePromise != null) {
log('The %s socket is closed or closing', lOptsStr)
return closePromise
}
if (options.signal == null) {
const signal = AbortSignal.timeout(closeTimeout)
options = {
...options,
signal
}
}
const abortSignalListener = (): void => {
socket.destroy(new CodeError('Destroying socket after timeout', 'ERR_CLOSE_TIMEOUT'))
}
options.signal?.addEventListener('abort', abortSignalListener)
try {
log('%s closing socket', lOptsStr)
closePromise = new Promise<void>((resolve, reject) => {
socket.once('close', () => {
// socket completely closed
log('%s socket closed', lOptsStr)
resolve()
})
socket.once('error', (err: Error) => {
log('%s socket error', lOptsStr, err)
// error closing socket
if (maConn.timeline.close == null) {
maConn.timeline.close = Date.now()
}
if (!socket.destroyed) {
reject(err)
}
// if socket is destroyed, 'closed' event will be emitted later to resolve the promise
})
// shorten inactivity timeout
socket.setTimeout(closeTimeout)
// close writable end of the socket
socket.end()
if (socket.writableLength > 0) {
// there are outgoing bytes waiting to be sent
socket.once('drain', () => {
log('%s socket drained', lOptsStr)
// all bytes have been sent we can destroy the socket (maybe) before the timeout
socket.destroy()
})
} else {
// nothing to send, destroy immediately, no need for the timeout
socket.destroy()
}
})
await closePromise
} catch (err: any) {
this.abort(err)
} finally {
options.signal?.removeEventListener('abort', abortSignalListener)
}
},
abort: (err: Error) => {
log('%s socket abort due to error', lOptsStr, err)
// the abortSignalListener may already destroyed the socket with an error
if (!socket.destroyed) {
socket.destroy(err)
}
if (maConn.timeline.close == null) {
maConn.timeline.close = Date.now()
}
},
log
}
return maConn
}