forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgresConnection+Connect.swift
55 lines (50 loc) · 1.95 KB
/
PostgresConnection+Connect.swift
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
import Logging
import NIO
extension PostgresConnection {
public static func connect(
to socketAddress: SocketAddress,
tlsConfiguration: TLSConfiguration? = nil,
serverHostname: String? = nil,
logger: Logger = .init(label: "codes.vapor.postgres"),
on eventLoop: EventLoop
) -> EventLoopFuture<PostgresConnection> {
let bootstrap = ClientBootstrap(group: eventLoop)
.channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
return bootstrap.connect(to: socketAddress).flatMap { channel in
return channel.pipeline.addHandlers([
ByteToMessageHandler(PostgresMessageDecoder(logger: logger)),
MessageToByteHandler(PostgresMessageEncoder(logger: logger)),
PostgresRequestHandler(logger: logger),
PostgresErrorHandler(logger: logger)
]).map {
return PostgresConnection(channel: channel, logger: logger)
}
}.flatMap { (conn: PostgresConnection) in
if let tlsConfiguration = tlsConfiguration {
return conn.requestTLS(
using: tlsConfiguration,
serverHostname: serverHostname,
logger: logger
).flatMapError { error in
conn.close().flatMapThrowing {
throw error
}
}.map { conn }
} else {
return eventLoop.makeSucceededFuture(conn)
}
}
}
}
private final class PostgresErrorHandler: ChannelInboundHandler {
typealias InboundIn = Never
let logger: Logger
init(logger: Logger) {
self.logger = logger
}
func errorCaught(context: ChannelHandlerContext, error: Error) {
self.logger.error("Uncaught error: \(error)")
context.close(promise: nil)
context.fireErrorCaught(error)
}
}