Skip to content
This repository was archived by the owner on Aug 29, 2023. It is now read-only.

Commit 3637489

Browse files
authored
fix: on MultiaddrConnection close() only create timer if needed (#262)
1 parent d2ef2d0 commit 3637489

File tree

1 file changed

+21
-16
lines changed

1 file changed

+21
-16
lines changed

src/socket-to-conn.ts

+21-16
Original file line numberDiff line numberDiff line change
@@ -130,24 +130,14 @@ export const toMultiaddrConnection = (socket: Socket, options: ToConnectionOptio
130130
await new Promise<void>((resolve, reject) => {
131131
const start = Date.now()
132132

133-
// Attempt to end the socket. If it takes longer to close than the
134-
// timeout, destroy it manually.
135-
const timeout = setTimeout(() => {
136-
if (socket.destroyed) {
137-
log('%s is already destroyed', lOptsStr)
138-
resolve()
139-
} else {
140-
log('%s socket close timeout after %dms, destroying it manually', lOptsStr, Date.now() - start)
141-
142-
// will trigger 'error' and 'close' events that resolves promise
143-
socket.destroy(new CodeError('Socket close timeout', 'ERR_SOCKET_CLOSE_TIMEOUT'))
144-
}
145-
}, closeTimeout).unref()
133+
let timeout: NodeJS.Timeout | undefined
146134

147135
socket.once('close', () => {
148136
log('%s socket closed', lOptsStr)
149137
// socket completely closed
150-
clearTimeout(timeout)
138+
if (timeout !== undefined) {
139+
clearTimeout(timeout)
140+
}
151141
resolve()
152142
})
153143
socket.once('error', (err: Error) => {
@@ -159,7 +149,9 @@ export const toMultiaddrConnection = (socket: Socket, options: ToConnectionOptio
159149
}
160150

161151
if (socket.destroyed) {
162-
clearTimeout(timeout)
152+
if (timeout !== undefined) {
153+
clearTimeout(timeout)
154+
}
163155
}
164156

165157
reject(err)
@@ -172,6 +164,19 @@ export const toMultiaddrConnection = (socket: Socket, options: ToConnectionOptio
172164
socket.end()
173165

174166
if (socket.writableLength > 0) {
167+
// Attempt to end the socket. If it takes longer to close than the
168+
// timeout, destroy it manually.
169+
timeout = setTimeout(() => {
170+
if (socket.destroyed) {
171+
log('%s is already destroyed', lOptsStr)
172+
resolve()
173+
} else {
174+
log('%s socket close timeout after %dms, destroying it manually', lOptsStr, Date.now() - start)
175+
176+
// will trigger 'error' and 'close' events that resolves promise
177+
socket.destroy(new CodeError('Socket close timeout', 'ERR_SOCKET_CLOSE_TIMEOUT'))
178+
}
179+
}, closeTimeout).unref()
175180
// there are outgoing bytes waiting to be sent
176181
socket.once('drain', () => {
177182
log('%s socket drained', lOptsStr)
@@ -180,7 +185,7 @@ export const toMultiaddrConnection = (socket: Socket, options: ToConnectionOptio
180185
socket.destroy()
181186
})
182187
} else {
183-
// nothing to send, destroy immediately
188+
// nothing to send, destroy immediately, no need the timeout
184189
socket.destroy()
185190
}
186191
})

0 commit comments

Comments
 (0)