Skip to content

SSLContextCache: use DispatchQueue instead of NIOThreadPool #368

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions Sources/AsyncHTTPClient/ConnectionPool.swift
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,6 @@ final class ConnectionPool {
self.providers.values
}

self.sslContextCache.shutdown()

return EventLoopFuture.reduce(true, providers.map { $0.close() }, on: eventLoop) { $0 && $1 }
}

Expand Down
53 changes: 3 additions & 50 deletions Sources/AsyncHTTPClient/SSLContextCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,69 +12,22 @@
//
//===----------------------------------------------------------------------===//

import Dispatch
import Logging
import NIO
import NIOConcurrencyHelpers
import NIOSSL

class SSLContextCache {
private var state = State.activeNoThread
private let lock = Lock()
private var sslContextCache = LRUCache<BestEffortHashableTLSConfiguration, NIOSSLContext>()
private let threadPool = NIOThreadPool(numberOfThreads: 1)

enum State {
case activeNoThread
case active
case shutDown
}

init() {}

func shutdown() {
self.lock.withLock { () -> Void in
switch self.state {
case .activeNoThread:
self.state = .shutDown
case .active:
self.state = .shutDown
self.threadPool.shutdownGracefully { maybeError in
precondition(maybeError == nil, "\(maybeError!)")
}
case .shutDown:
preconditionFailure("SSLContextCache shut down twice")
}
}
}

deinit {
assert(self.state == .shutDown)
}
private let offloadQueue = DispatchQueue(label: "io.github.swift-server.AsyncHTTPClient.SSLContextCache")
}

extension SSLContextCache {
private struct SSLContextCacheShutdownError: Error {}

func sslContext(tlsConfiguration: TLSConfiguration,
eventLoop: EventLoop,
logger: Logger) -> EventLoopFuture<NIOSSLContext> {
let earlyExitError: Error? = self.lock.withLock { () -> Error? in
switch self.state {
case .activeNoThread:
self.state = .active
self.threadPool.start()
return nil
case .active:
return nil
case .shutDown:
return SSLContextCacheShutdownError()
}
}

if let error = earlyExitError {
return eventLoop.makeFailedFuture(error)
}

let eqTLSConfiguration = BestEffortHashableTLSConfiguration(wrapping: tlsConfiguration)
let sslContext = self.lock.withLock {
self.sslContextCache.find(key: eqTLSConfiguration)
Expand All @@ -88,7 +41,7 @@ extension SSLContextCache {

logger.debug("creating new SSL context",
metadata: ["ahc-tls-config": "\(tlsConfiguration)"])
let newSSLContext = self.threadPool.runIfActive(eventLoop: eventLoop) {
let newSSLContext = self.offloadQueue.asyncWithFuture(eventLoop: eventLoop) {
try NIOSSLContext(configuration: tlsConfiguration)
}

Expand Down
3 changes: 1 addition & 2 deletions Tests/AsyncHTTPClientTests/SSLContextCacheTests+XCTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,9 @@ import XCTest
extension SSLContextCacheTests {
static var allTests: [(String, (SSLContextCacheTests) -> () throws -> Void)] {
return [
("testJustStartingAndStoppingAContextCacheWorks", testJustStartingAndStoppingAContextCacheWorks),
("testRequestingSSLContextWorks", testRequestingSSLContextWorks),
("testRequestingSSLContextAfterShutdownThrows", testRequestingSSLContextAfterShutdownThrows),
("testCacheWorks", testCacheWorks),
("testCacheDoesNotReturnWrongEntry", testCacheDoesNotReturnWrongEntry),
]
}
}
32 changes: 18 additions & 14 deletions Tests/AsyncHTTPClientTests/SSLContextCacheTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,45 +18,47 @@ import NIOSSL
import XCTest

final class SSLContextCacheTests: XCTestCase {
func testJustStartingAndStoppingAContextCacheWorks() {
SSLContextCache().shutdown()
}

func testRequestingSSLContextWorks() {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let eventLoop = group.next()
let cache = SSLContextCache()
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
cache.shutdown()
}

XCTAssertNoThrow(try cache.sslContext(tlsConfiguration: .forClient(),
eventLoop: eventLoop,
logger: HTTPClient.loggingDisabled).wait())
}

func testRequestingSSLContextAfterShutdownThrows() {
func testCacheWorks() {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let eventLoop = group.next()
let cache = SSLContextCache()
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}

cache.shutdown()
XCTAssertThrowsError(try cache.sslContext(tlsConfiguration: .forClient(),
eventLoop: eventLoop,
logger: HTTPClient.loggingDisabled).wait())
var firstContext: NIOSSLContext?
var secondContext: NIOSSLContext?

XCTAssertNoThrow(firstContext = try cache.sslContext(tlsConfiguration: .forClient(),
eventLoop: eventLoop,
logger: HTTPClient.loggingDisabled).wait())
XCTAssertNoThrow(secondContext = try cache.sslContext(tlsConfiguration: .forClient(),
eventLoop: eventLoop,
logger: HTTPClient.loggingDisabled).wait())
XCTAssertNotNil(firstContext)
XCTAssertNotNil(secondContext)
XCTAssert(firstContext === secondContext)
}

func testCacheWorks() {
func testCacheDoesNotReturnWrongEntry() {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let eventLoop = group.next()
let cache = SSLContextCache()
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
cache.shutdown()
}

var firstContext: NIOSSLContext?
Expand All @@ -65,11 +67,13 @@ final class SSLContextCacheTests: XCTestCase {
XCTAssertNoThrow(firstContext = try cache.sslContext(tlsConfiguration: .forClient(),
eventLoop: eventLoop,
logger: HTTPClient.loggingDisabled).wait())
XCTAssertNoThrow(secondContext = try cache.sslContext(tlsConfiguration: .forClient(),

// Second one has a _different_ TLSConfiguration.
XCTAssertNoThrow(secondContext = try cache.sslContext(tlsConfiguration: .forClient(certificateVerification: .none),
eventLoop: eventLoop,
logger: HTTPClient.loggingDisabled).wait())
XCTAssertNotNil(firstContext)
XCTAssertNotNil(secondContext)
XCTAssert(firstContext === secondContext)
XCTAssert(firstContext !== secondContext)
}
}