(options: MakeConnectionOptions)
| 376 | } |
| 377 | |
| 378 | export async function makeSocket(options: MakeConnectionOptions): Promise<Stream> { |
| 379 | const useTLS = options.tls ?? false; |
| 380 | const connectTimeoutMS = options.connectTimeoutMS ?? 30000; |
| 381 | const existingSocket = options.existingSocket; |
| 382 | const keepAliveInitialDelay = |
| 383 | options.keepAliveInitialDelay ?? DEFAULT_KEEP_ALIVE_INITIAL_DELAY_MS; |
| 384 | const noDelay = options.noDelay ?? true; |
| 385 | |
| 386 | let socket: Stream; |
| 387 | |
| 388 | if (options.proxyHost != null) { |
| 389 | // Currently, only Socks5 is supported. |
| 390 | return await makeSocks5Connection({ |
| 391 | ...options, |
| 392 | connectTimeoutMS // Should always be present for Socks5 |
| 393 | }); |
| 394 | } |
| 395 | |
| 396 | if (useTLS) { |
| 397 | const tlsSocket = tls.connect(parseSslOptions(options)); |
| 398 | if (typeof tlsSocket.disableRenegotiation === 'function') { |
| 399 | tlsSocket.disableRenegotiation(); |
| 400 | } |
| 401 | socket = tlsSocket; |
| 402 | } else if (existingSocket) { |
| 403 | // In the TLS case, parseSslOptions() sets options.socket to existingSocket, |
| 404 | // so we only need to handle the non-TLS case here (where existingSocket |
| 405 | // gives us all we need out of the box). |
| 406 | socket = existingSocket; |
| 407 | } else { |
| 408 | socket = net.createConnection(parseConnectOptions(options)); |
| 409 | } |
| 410 | |
| 411 | // Explicit setKeepAlive/setNoDelay are required because tls.connect() silently |
| 412 | // ignores these constructor options due to a Node.js bug. |
| 413 | // See: https://github.com/nodejs/node/issues/62003 |
| 414 | // TODO(NODE-7474): remove this fix once the underlying Node.js issue is resolved. |
| 415 | socket.setKeepAlive(true, keepAliveInitialDelay); |
| 416 | socket.setNoDelay(noDelay); |
| 417 | socket.setTimeout(connectTimeoutMS); |
| 418 | |
| 419 | let cancellationHandler: ((err: Error) => void) | null = null; |
| 420 | |
| 421 | const { promise: connectedSocket, resolve, reject } = promiseWithResolvers<Stream>(); |
| 422 | if (existingSocket) { |
| 423 | resolve(socket); |
| 424 | } else { |
| 425 | const start = performance.now(); |
| 426 | const connectEvent = useTLS ? 'secureConnect' : 'connect'; |
| 427 | socket |
| 428 | .once(connectEvent, () => resolve(socket)) |
| 429 | .once('error', cause => |
| 430 | reject(new MongoNetworkError(MongoError.buildErrorMessage(cause), { cause })) |
| 431 | ) |
| 432 | .once('timeout', () => { |
| 433 | reject( |
| 434 | new MongoNetworkTimeoutError( |
| 435 | `Socket '${connectEvent}' timed out after ${(performance.now() - start) | 0}ms (connectTimeoutMS: ${connectTimeoutMS})` |
no test coverage detected