diff --git a/Sources/PostgresNIO/Connection/PostgresConnection.swift b/Sources/PostgresNIO/Connection/PostgresConnection.swift index 08b5149e..70f61730 100644 --- a/Sources/PostgresNIO/Connection/PostgresConnection.swift +++ b/Sources/PostgresNIO/Connection/PostgresConnection.swift @@ -78,9 +78,15 @@ public final class PostgresConnection { /// - Default: 5432 public var port: Int + /// Specifies a timeout to apply to a connection attempt. + /// + /// - Default: 10 seconds + public var connectTimeout: TimeAmount + public init(host: String, port: Int = 5432) { self.host = host self.port = port + self.connectTimeout = .seconds(10) } } @@ -281,12 +287,12 @@ public final class PostgresConnection { ) -> NIOClientTCPBootstrapProtocol { #if canImport(Network) if let tsBootstrap = NIOTSConnectionBootstrap(validatingGroup: eventLoop) { - return tsBootstrap + return tsBootstrap.connectTimeout(configuration.connectTimeout) } #endif if let nioBootstrap = ClientBootstrap(validatingGroup: eventLoop) { - return nioBootstrap + return nioBootstrap.connectTimeout(configuration.connectTimeout) } fatalError("No matching bootstrap found") @@ -393,6 +399,7 @@ extension PostgresConnection { return tlsFuture.flatMap { tls in let configuration = PostgresConnection.InternalConfiguration( connection: .resolved(address: socketAddress, serverName: serverHostname), + connectTimeout: .seconds(10), authentication: nil, tls: tls ) @@ -752,6 +759,7 @@ extension PostgresConnection { } var connection: Connection + var connectTimeout: TimeAmount var authentication: Configuration.Authentication? @@ -763,6 +771,7 @@ extension PostgresConnection.InternalConfiguration { init(_ config: PostgresConnection.Configuration) { self.authentication = config.authentication self.connection = .unresolved(host: config.connection.host, port: config.connection.port) + self.connectTimeout = config.connection.connectTimeout self.tls = config.tls } } diff --git a/Tests/PostgresNIOTests/New/PostgresChannelHandlerTests.swift b/Tests/PostgresNIOTests/New/PostgresChannelHandlerTests.swift index d3c2b10f..e2e73b46 100644 --- a/Tests/PostgresNIOTests/New/PostgresChannelHandlerTests.swift +++ b/Tests/PostgresNIOTests/New/PostgresChannelHandlerTests.swift @@ -173,7 +173,8 @@ class PostgresChannelHandlerTests: XCTestCase { username: String = "test", database: String = "postgres", password: String = "password", - tls: PostgresConnection.Configuration.TLS = .disable + tls: PostgresConnection.Configuration.TLS = .disable, + connectTimeout: TimeAmount = .seconds(10) ) -> PostgresConnection.InternalConfiguration { let authentication = PostgresConnection.Configuration.Authentication( username: username, @@ -183,6 +184,7 @@ class PostgresChannelHandlerTests: XCTestCase { return PostgresConnection.InternalConfiguration( connection: .unresolved(host: host, port: port), + connectTimeout: connectTimeout, authentication: authentication, tls: tls )