forked from swift-server/async-http-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSSLContextCache.swift
57 lines (50 loc) · 2.08 KB
/
SSLContextCache.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
56
57
//===----------------------------------------------------------------------===//
//
// This source file is part of the AsyncHTTPClient open source project
//
// Copyright (c) 2021 Apple Inc. and the AsyncHTTPClient project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Dispatch
import Logging
import NIOConcurrencyHelpers
import NIOCore
import NIOSSL
class SSLContextCache {
private let lock = Lock()
private var sslContextCache = LRUCache<BestEffortHashableTLSConfiguration, NIOSSLContext>()
private let offloadQueue = DispatchQueue(label: "io.github.swift-server.AsyncHTTPClient.SSLContextCache")
}
extension SSLContextCache {
func sslContext(tlsConfiguration: TLSConfiguration,
eventLoop: EventLoop,
logger: Logger) -> EventLoopFuture<NIOSSLContext> {
let eqTLSConfiguration = BestEffortHashableTLSConfiguration(wrapping: tlsConfiguration)
let sslContext = self.lock.withLock {
self.sslContextCache.find(key: eqTLSConfiguration)
}
if let sslContext = sslContext {
logger.debug("found SSL context in cache",
metadata: ["ahc-tls-config": "\(tlsConfiguration)"])
return eventLoop.makeSucceededFuture(sslContext)
}
logger.debug("creating new SSL context",
metadata: ["ahc-tls-config": "\(tlsConfiguration)"])
let newSSLContext = self.offloadQueue.asyncWithFuture(eventLoop: eventLoop) {
try NIOSSLContext(configuration: tlsConfiguration)
}
newSSLContext.whenSuccess { (newSSLContext: NIOSSLContext) -> Void in
self.lock.withLock { () -> Void in
self.sslContextCache.append(key: eqTLSConfiguration,
value: newSSLContext)
}
}
return newSSLContext
}
}