Skip to content

Commit e184939

Browse files
committed
cache NIOSSLContext (saves 27k allocs per conn)
Motivation: At the moment, AHC assumes that creating a `NIOSSLContext` is both cheap and doesn't block. Neither of these two assumptions are true. To create a `NIOSSLContext`, BoringSSL will have to read a lot of certificates in the trust store (on disk) which require a lot of ASN1 parsing and much much more. On my Ubuntu test machine, creating one `NIOSSLContext` is about 27,000 allocations!!! To make it worse, AHC allocates a fresh `NIOSSLContext` for _every single connection_, whether HTTP or HTTPS. Yes, correct. Modification: - Cache NIOSSLContexts per TLSConfiguration in a LRU cache - Don't get an NIOSSLContext for HTTP (plain text) connections Result: New connections should be _much_ faster in general assuming that you're not using a different TLSConfiguration for every connection.
1 parent ca722d8 commit e184939

13 files changed

+708
-187
lines changed

Sources/AsyncHTTPClient/ConnectionPool.swift

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import NIO
1818
import NIOConcurrencyHelpers
1919
import NIOHTTP1
2020
import NIOHTTPCompression
21+
import NIOSSL
2122
import NIOTLS
2223
import NIOTransportServices
2324

@@ -41,6 +42,8 @@ final class ConnectionPool {
4142

4243
private let backgroundActivityLogger: Logger
4344

45+
let sslContextCache = SSLContextCache()
46+
4447
init(configuration: HTTPClient.Configuration, backgroundActivityLogger: Logger) {
4548
self.configuration = configuration
4649
self.backgroundActivityLogger = backgroundActivityLogger
@@ -106,6 +109,8 @@ final class ConnectionPool {
106109
self.providers.values
107110
}
108111

112+
self.sslContextCache.shutdown()
113+
109114
return EventLoopFuture.reduce(true, providers.map { $0.close() }, on: eventLoop) { $0 && $1 }
110115
}
111116

@@ -148,7 +153,7 @@ final class ConnectionPool {
148153
var host: String
149154
var port: Int
150155
var unixPath: String
151-
var tlsConfiguration: BestEffortHashableTLSConfiguration?
156+
private var tlsConfiguration: BestEffortHashableTLSConfiguration?
152157

153158
enum Scheme: Hashable {
154159
case http
@@ -249,14 +254,15 @@ class HTTP1ConnectionProvider {
249254
} else {
250255
logger.trace("opening fresh connection (found matching but inactive connection)",
251256
metadata: ["ahc-dead-connection": "\(connection)"])
252-
self.makeChannel(preference: waiter.preference).whenComplete { result in
257+
self.makeChannel(preference: waiter.preference,
258+
logger: logger).whenComplete { result in
253259
self.connect(result, waiter: waiter, logger: logger)
254260
}
255261
}
256262
}
257263
case .create(let waiter):
258264
logger.trace("opening fresh connection (no connections to reuse available)")
259-
self.makeChannel(preference: waiter.preference).whenComplete { result in
265+
self.makeChannel(preference: waiter.preference, logger: logger).whenComplete { result in
260266
self.connect(result, waiter: waiter, logger: logger)
261267
}
262268
case .replace(let connection, let waiter):
@@ -266,7 +272,7 @@ class HTTP1ConnectionProvider {
266272
logger.trace("opening fresh connection (replacing exising connection)",
267273
metadata: ["ahc-old-connection": "\(connection)",
268274
"ahc-waiter": "\(waiter)"])
269-
self.makeChannel(preference: waiter.preference).whenComplete { result in
275+
self.makeChannel(preference: waiter.preference, logger: logger).whenComplete { result in
270276
self.connect(result, waiter: waiter, logger: logger)
271277
}
272278
}
@@ -434,8 +440,14 @@ class HTTP1ConnectionProvider {
434440
return self.closePromise.futureResult.map { true }
435441
}
436442

437-
private func makeChannel(preference: HTTPClient.EventLoopPreference) -> EventLoopFuture<Channel> {
438-
return NIOClientTCPBootstrap.makeHTTP1Channel(destination: self.key, eventLoop: self.eventLoop, configuration: self.configuration, preference: preference)
443+
private func makeChannel(preference: HTTPClient.EventLoopPreference,
444+
logger: Logger) -> EventLoopFuture<Channel> {
445+
return NIOClientTCPBootstrap.makeHTTP1Channel(destination: self.key,
446+
eventLoop: self.eventLoop,
447+
configuration: self.configuration,
448+
sslContextCache: self.pool.sslContextCache,
449+
preference: preference,
450+
logger: logger)
439451
}
440452

441453
/// A `Waiter` represents a request that waits for a connection when none is

Sources/AsyncHTTPClient/HTTPClient.swift

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -900,7 +900,9 @@ extension ChannelPipeline {
900900
try sync.addHandler(handler)
901901
}
902902

903-
func syncAddLateSSLHandlerIfNeeded(for key: ConnectionPool.Key, tlsConfiguration: TLSConfiguration?, handshakePromise: EventLoopPromise<Void>) {
903+
func syncAddLateSSLHandlerIfNeeded(for key: ConnectionPool.Key,
904+
sslContext: NIOSSLContext,
905+
handshakePromise: EventLoopPromise<Void>) {
904906
precondition(key.scheme.requiresTLS)
905907

906908
do {
@@ -913,10 +915,9 @@ extension ChannelPipeline {
913915
try synchronousPipelineView.addHandler(eventsHandler, name: TLSEventsHandler.handlerName)
914916

915917
// Then we add the SSL handler.
916-
let tlsConfiguration = tlsConfiguration ?? TLSConfiguration.forClient()
917-
let context = try NIOSSLContext(configuration: tlsConfiguration)
918918
try synchronousPipelineView.addHandler(
919-
try NIOSSLClientHandler(context: context, serverHostname: (key.host.isIPAddress || key.host.isEmpty) ? nil : key.host),
919+
try NIOSSLClientHandler(context: sslContext,
920+
serverHostname: (key.host.isIPAddress || key.host.isEmpty) ? nil : key.host),
920921
position: .before(eventsHandler)
921922
)
922923
} catch {
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the AsyncHTTPClient open source project
4+
//
5+
// Copyright (c) 2021 Apple Inc. and the AsyncHTTPClient project authors
6+
// Licensed under Apache License v2.0
7+
//
8+
// See LICENSE.txt for license information
9+
// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors
10+
//
11+
// SPDX-License-Identifier: Apache-2.0
12+
//
13+
//===----------------------------------------------------------------------===//
14+
15+
struct LRUCache<Key: Equatable & Hashable,
16+
Value> {
17+
private typealias Generation = UInt64
18+
private struct Element {
19+
var generation: Generation
20+
var key: Key
21+
var value: Value
22+
}
23+
24+
private let capacity: Int
25+
private var generation: Generation = 0
26+
private var elements: [Element]
27+
28+
init(capacity: Int = 8) {
29+
self.capacity = capacity
30+
self.elements = []
31+
self.elements.reserveCapacity(capacity)
32+
}
33+
34+
private mutating func findIndex(key: Key) -> Int? {
35+
self.generation += 1
36+
37+
let found = self.elements.firstIndex { element in
38+
element.key == key
39+
}
40+
41+
return found
42+
}
43+
44+
mutating func find(key: Key) -> Value? {
45+
if let found = self.findIndex(key: key) {
46+
self.elements[found].generation = self.generation
47+
return self.elements[found].value
48+
} else {
49+
return nil
50+
}
51+
}
52+
53+
@discardableResult
54+
mutating func append(key: Key, value: Value) -> Value {
55+
let newElement = Element(generation: self.generation,
56+
key: key,
57+
value: value)
58+
if let found = self.findIndex(key: key) {
59+
self.elements[found] = newElement
60+
return value
61+
}
62+
63+
if self.elements.count < self.capacity {
64+
self.elements.append(newElement)
65+
return value
66+
}
67+
assert(self.elements.count == self.capacity)
68+
assert(self.elements.count > 0)
69+
70+
let minIndex = self.elements.minIndex { l, r in
71+
l.generation < r.generation
72+
}!
73+
74+
self.elements.swapAt(minIndex, self.elements.endIndex - 1)
75+
self.elements.removeLast()
76+
self.elements.append(newElement)
77+
78+
return value
79+
}
80+
81+
mutating func findOrAppend(key: Key, _ valueGenerator: (Key) -> Value) -> Value {
82+
if let found = self.find(key: key) {
83+
return found
84+
}
85+
86+
return self.append(key: key, value: valueGenerator(key))
87+
}
88+
}
89+
90+
extension Array {
91+
func minIndex(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> Index? {
92+
var minSoFar: (Index, Element)?
93+
94+
for indexElement in self.enumerated() {
95+
if let min = minSoFar {
96+
if try areInIncreasingOrder(indexElement.1, min.1) {
97+
minSoFar = indexElement
98+
}
99+
} else {
100+
minSoFar = indexElement
101+
}
102+
}
103+
104+
return minSoFar.map { $0.0 }
105+
}
106+
}

Sources/AsyncHTTPClient/NIOTransportServices/NWErrorHandler.swift

Lines changed: 58 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -12,73 +12,77 @@
1212
//
1313
//===----------------------------------------------------------------------===//
1414

15-
#if canImport(Network)
15+
import Network
16+
import NIO
17+
import NIOHTTP1
18+
import NIOTransportServices
1619

17-
import Network
18-
import NIO
19-
import NIOHTTP1
20-
import NIOTransportServices
20+
extension HTTPClient {
21+
public struct NWPOSIXError: Error, CustomStringConvertible {
22+
/// POSIX error code (enum)
23+
public let errorCode: POSIXErrorCode
2124

22-
extension HTTPClient {
23-
public struct NWPOSIXError: Error, CustomStringConvertible {
24-
/// POSIX error code (enum)
25-
public let errorCode: POSIXErrorCode
25+
/// actual reason, in human readable form
26+
private let reason: String
2627

27-
/// actual reason, in human readable form
28-
private let reason: String
29-
30-
/// Initialise a NWPOSIXError
31-
/// - Parameters:
32-
/// - errorType: posix error type
33-
/// - reason: String describing reason for error
34-
public init(_ errorCode: POSIXErrorCode, reason: String) {
35-
self.errorCode = errorCode
36-
self.reason = reason
37-
}
38-
39-
public var description: String { return self.reason }
28+
/// Initialise a NWPOSIXError
29+
/// - Parameters:
30+
/// - errorType: posix error type
31+
/// - reason: String describing reason for error
32+
public init(_ errorCode: POSIXErrorCode, reason: String) {
33+
self.errorCode = errorCode
34+
self.reason = reason
4035
}
4136

42-
public struct NWTLSError: Error, CustomStringConvertible {
43-
/// TLS error status. List of TLS errors can be found in <Security/SecureTransport.h>
44-
public let status: OSStatus
37+
public var description: String { return self.reason }
38+
}
4539

46-
/// actual reason, in human readable form
47-
private let reason: String
40+
public struct NWTLSError: Error, CustomStringConvertible {
41+
/// TLS error status. List of TLS errors can be found in <Security/SecureTransport.h>
42+
public let status: OSStatus
4843

49-
/// initialise a NWTLSError
50-
/// - Parameters:
51-
/// - status: TLS status
52-
/// - reason: String describing reason for error
53-
public init(_ status: OSStatus, reason: String) {
54-
self.status = status
55-
self.reason = reason
56-
}
44+
/// actual reason, in human readable form
45+
private let reason: String
5746

58-
public var description: String { return self.reason }
47+
/// initialise a NWTLSError
48+
/// - Parameters:
49+
/// - status: TLS status
50+
/// - reason: String describing reason for error
51+
public init(_ status: OSStatus, reason: String) {
52+
self.status = status
53+
self.reason = reason
5954
}
6055

61-
@available(macOS 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
62-
class NWErrorHandler: ChannelInboundHandler {
63-
typealias InboundIn = HTTPClientResponsePart
56+
public var description: String { return self.reason }
57+
}
58+
59+
class NWErrorHandler: ChannelInboundHandler {
60+
typealias InboundIn = HTTPClientResponsePart
6461

65-
func errorCaught(context: ChannelHandlerContext, error: Error) {
66-
context.fireErrorCaught(NWErrorHandler.translateError(error))
67-
}
62+
func errorCaught(context: ChannelHandlerContext, error: Error) {
63+
context.fireErrorCaught(NWErrorHandler.translateError(error))
64+
}
6865

69-
static func translateError(_ error: Error) -> Error {
70-
if let error = error as? NWError {
71-
switch error {
72-
case .tls(let status):
73-
return NWTLSError(status, reason: error.localizedDescription)
74-
case .posix(let errorCode):
75-
return NWPOSIXError(errorCode, reason: error.localizedDescription)
76-
default:
77-
return error
66+
static func translateError(_ error: Error) -> Error {
67+
#if canImport(Network)
68+
if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
69+
if let error = error as? NWError {
70+
switch error {
71+
case .tls(let status):
72+
return NWTLSError(status, reason: error.localizedDescription)
73+
case .posix(let errorCode):
74+
return NWPOSIXError(errorCode, reason: error.localizedDescription)
75+
default:
76+
return error
77+
}
7878
}
79+
return error
80+
} else {
81+
preconditionFailure("\(self) used on a non-NIOTS Channel")
7982
}
80-
return error
81-
}
83+
#else
84+
preconditionFailure("\(self) used on a non-NIOTS Channel")
85+
#endif
8286
}
8387
}
84-
#endif
88+
}

0 commit comments

Comments
 (0)