forked from orlandos-nl/MongoKitten
/
MongoSingleConnectionPool.swift
51 lines (42 loc) · 1.58 KB
/
MongoSingleConnectionPool.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
import NIO
import Logging
import MongoCore
public final actor MongoSingleConnectionPool: MongoConnectionPool {
public let serverApi: ServerApi?
public typealias BuildConnection = @Sendable () async throws -> MongoConnection
public var wireVersion: WireVersion? {
get async {
await connection?.wireVersion
}
}
public let sessionManager = MongoSessionManager()
public let logger = Logger(label: "org.openkitten.mongokitten.single-connection-pool")
let buildConnection: BuildConnection
let authenticationSource: String
let credentials: ConnectionSettings.Authentication
var connection: MongoConnection?
public init(
authenticationSource: String = "admin",
credentials: ConnectionSettings.Authentication = .unauthenticated,
buildConnection: @escaping BuildConnection,
api: ServerApi? = nil
) {
self.authenticationSource = authenticationSource
self.credentials = credentials
self.buildConnection = buildConnection
self.serverApi = api
}
public func next(for request: ConnectionPoolRequest) async throws -> MongoConnection {
if let connection = connection, connection.channel.isActive {
return connection
}
let connection = try await buildConnection()
try await connection.authenticate(
clientDetails: nil,
using: self.credentials,
to: self.authenticationSource
)
self.connection = connection
return connection
}
}