ClientConnection.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. /*
  2. * Copyright 2019, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. import NIO
  18. import NIOHTTP2
  19. import NIOSSL
  20. import NIOTLS
  21. import Logging
  22. /// Underlying channel and HTTP/2 stream multiplexer.
  23. ///
  24. /// Different service clients implementing `GRPCClient` may share an instance of this class.
  25. ///
  26. /// The connection is initially setup with a handler to verify that TLS was established
  27. /// successfully (assuming TLS is being used).
  28. ///
  29. /// ┌──────────────────────────┐
  30. /// │ DelegatingErrorHandler │
  31. /// └──────────▲───────────────┘
  32. /// HTTP2Frame│
  33. /// ┌──────────┴───────────────┐
  34. /// │ SettingsObservingHandler │
  35. /// └──────────▲───────────────┘
  36. /// HTTP2Frame│
  37. /// │ ⠇ ⠇ ⠇ ⠇
  38. /// │ ┌┴─▼┐ ┌┴─▼┐
  39. /// │ │ | │ | HTTP/2 streams
  40. /// │ └▲─┬┘ └▲─┬┘
  41. /// │ │ │ │ │ HTTP2Frame
  42. /// ┌─┴────── ─────────┴─▼───┴─▼┐
  43. /// │ HTTP2StreamMultiplexer |
  44. /// └─▲───────────────────────┬─┘
  45. /// HTTP2Frame│ │HTTP2Frame
  46. /// ┌─┴───────────────────────▼─┐
  47. /// │ NIOHTTP2Handler │
  48. /// └─▲───────────────────────┬─┘
  49. /// ByteBuffer│ │ByteBuffer
  50. /// ┌─┴───────────────────────▼─┐
  51. /// │ TLSVerificationHandler │
  52. /// └─▲───────────────────────┬─┘
  53. /// ByteBuffer│ │ByteBuffer
  54. /// ┌─┴───────────────────────▼─┐
  55. /// │ NIOSSLHandler │
  56. /// └─▲───────────────────────┬─┘
  57. /// ByteBuffer│ │ByteBuffer
  58. /// │ ▼
  59. ///
  60. /// The `TLSVerificationHandler` observes the outcome of the SSL handshake and determines
  61. /// whether a `ClientConnection` should be returned to the user. In either eventuality, the
  62. /// handler removes itself from the pipeline once TLS has been verified. There is also a handler
  63. /// after the multiplexer for observing the initial settings frame, after which it determines that
  64. /// the connection state is `.ready` and removes itself from the channel. Finally there is a
  65. /// delegated error handler which uses the error delegate associated with this connection
  66. /// (see `DelegatingErrorHandler`).
  67. ///
  68. /// See `BaseClientCall` for a description of the pipelines associated with each HTTP/2 stream.
  69. public class ClientConnection {
  70. internal let logger: Logger
  71. /// The UUID of this connection, used for logging.
  72. internal let uuid: UUID
  73. /// The channel which will handle gRPC calls.
  74. internal var channel: EventLoopFuture<Channel> {
  75. willSet {
  76. self.willSetChannel(to: newValue)
  77. }
  78. didSet {
  79. self.didSetChannel(to: self.channel)
  80. }
  81. }
  82. /// HTTP multiplexer from the `channel` handling gRPC calls.
  83. internal var multiplexer: EventLoopFuture<HTTP2StreamMultiplexer>
  84. /// The configuration for this client.
  85. internal let configuration: Configuration
  86. /// A monitor for the connectivity state.
  87. public let connectivity: ConnectivityStateMonitor
  88. /// Creates a new connection from the given configuration.
  89. public init(configuration: Configuration) {
  90. self.configuration = configuration
  91. self.connectivity = ConnectivityStateMonitor(delegate: configuration.connectivityStateDelegate)
  92. self.uuid = UUID()
  93. var logger = Logger(subsystem: .clientChannel)
  94. logger[metadataKey: MetadataKey.connectionID] = "\(self.uuid)"
  95. self.logger = logger
  96. // We need to initialize `multiplexer` before we can call `willSetChannel` (which will then
  97. // assign `multiplexer` to one from the created `Channel`s pipeline).
  98. let eventLoop = configuration.eventLoopGroup.next()
  99. let unavailable = GRPCStatus(code: .unavailable, message: nil)
  100. self.multiplexer = eventLoop.makeFailedFuture(unavailable)
  101. self.channel = ClientConnection.makeChannel(
  102. configuration: self.configuration,
  103. eventLoop: self.configuration.eventLoopGroup.next(),
  104. connectivity: self.connectivity,
  105. backoffIterator: self.configuration.connectionBackoff?.makeIterator(),
  106. logger: self.logger
  107. )
  108. // `willSet` and `didSet` are called on initialization, so call them explicitly now.
  109. self.willSetChannel(to: channel)
  110. self.didSetChannel(to: channel)
  111. }
  112. // This is only internal to expose it for testing.
  113. /// Create a `ClientConnection` for testing using the given `EmbeddedChannel`.
  114. ///
  115. /// - Parameter channel: The embedded channel to create this connection on.
  116. /// - Parameter configuration: How this connection should be configured. The `eventLoopGroup`
  117. /// on the configuration will _not_ be used by the call. As such the `eventLoop` of
  118. /// the given `channel` may be used in the configuration to avoid managing an additional
  119. /// event loop group.
  120. ///
  121. /// - Important:
  122. /// The connectivity state will not be updated using this connection and should not be
  123. /// relied on.
  124. ///
  125. /// - Precondition:
  126. /// The provided connection target in the `configuration` _must_ be a `SocketAddress`.
  127. internal init(channel: EmbeddedChannel, configuration: Configuration) {
  128. // We need a .socketAddress to connect to.
  129. let socketAddress: SocketAddress
  130. switch configuration.target {
  131. case .socketAddress(let address):
  132. socketAddress = address
  133. default:
  134. preconditionFailure("target must be SocketAddress when using EmbeddedChannel")
  135. }
  136. self.uuid = UUID()
  137. var logger = Logger(subsystem: .clientChannel)
  138. logger[metadataKey: MetadataKey.connectionID] = "\(self.uuid)"
  139. self.logger = logger
  140. self.configuration = configuration
  141. self.connectivity = ConnectivityStateMonitor(delegate: configuration.connectivityStateDelegate)
  142. // Configure the channel with the correct handlers and connect to our target.
  143. let configuredChannel = ClientConnection.initializeChannel(
  144. channel,
  145. tls: configuration.tls?.configuration,
  146. serverHostname: configuration.tls?.hostnameOverride ?? configuration.target.host,
  147. connectivityMonitor: self.connectivity,
  148. errorDelegate: configuration.errorDelegate
  149. ).flatMap {
  150. channel.connect(to: socketAddress)
  151. }.map { _ in
  152. return channel as Channel
  153. }
  154. self.multiplexer = configuredChannel.flatMap {
  155. $0.pipeline.handler(type: HTTP2StreamMultiplexer.self)
  156. }
  157. self.channel = configuredChannel
  158. }
  159. /// The `EventLoop` this connection is using.
  160. public var eventLoop: EventLoop {
  161. return self.channel.eventLoop
  162. }
  163. /// Closes the connection to the server.
  164. public func close() -> EventLoopFuture<Void> {
  165. if self.connectivity.state == .shutdown {
  166. // We're already shutdown or in the process of shutting down.
  167. return channel.flatMap { $0.closeFuture }
  168. } else {
  169. self.logger.debug("shutting down channel")
  170. self.connectivity.initiateUserShutdown()
  171. return channel.flatMap { $0.close() }
  172. }
  173. }
  174. }
  175. // MARK: - Channel creation
  176. extension ClientConnection {
  177. /// Register a callback on the close future of the given `channel` to replace the channel (if
  178. /// possible) and also replace the `multiplexer` with that from the new channel.
  179. ///
  180. /// - Parameter channel: The channel that will be set.
  181. private func willSetChannel(to channel: EventLoopFuture<Channel>) {
  182. // If we're about to set the channel and the user has initiated a shutdown (i.e. while the new
  183. // channel was being created) then it is no longer needed.
  184. guard !self.connectivity.userHasInitiatedShutdown else {
  185. channel.whenSuccess { channel in
  186. self.logger.debug("user initiated shutdown during connection, closing channel")
  187. channel.close(mode: .all, promise: nil)
  188. }
  189. return
  190. }
  191. // If we get a channel and it closes then create a new one, if necessary.
  192. channel.flatMap { $0.closeFuture }.whenComplete { result in
  193. switch result {
  194. case .success:
  195. self.logger.debug("client connection shutdown successfully")
  196. case .failure(let error):
  197. self.logger.warning(
  198. "client connection shutdown failed",
  199. metadata: [MetadataKey.error: "\(error)"]
  200. )
  201. }
  202. guard self.connectivity.canAttemptReconnect else {
  203. return
  204. }
  205. // Something went wrong, but we'll try to fix it so let's update our state to reflect that.
  206. self.connectivity.state = .transientFailure
  207. self.logger.debug("client connection channel closed, creating a new one")
  208. self.channel = ClientConnection.makeChannel(
  209. configuration: self.configuration,
  210. eventLoop: channel.eventLoop,
  211. connectivity: self.connectivity,
  212. backoffIterator: self.configuration.connectionBackoff?.makeIterator(),
  213. logger: self.logger
  214. )
  215. }
  216. self.multiplexer = channel.flatMap {
  217. $0.pipeline.handler(type: HTTP2StreamMultiplexer.self)
  218. }
  219. }
  220. /// Register a callback on the given `channel` to update the connectivity state.
  221. ///
  222. /// - Parameter channel: The channel that was set.
  223. private func didSetChannel(to channel: EventLoopFuture<Channel>) {
  224. channel.whenFailure { _ in
  225. self.connectivity.state = .shutdown
  226. }
  227. }
  228. /// Attempts to create a new `Channel` using the given configuration.
  229. ///
  230. /// This involves: creating a `ClientBootstrapProtocol`, connecting to a target and verifying that
  231. /// the TLS handshake was successful (if TLS was configured). We _may_ additiionally set a
  232. /// connection timeout and schedule a retry attempt (should the connection fail) if a
  233. /// `ConnectionBackoffIterator` is provided.
  234. ///
  235. /// - Parameter configuration: The configuration to start the connection with.
  236. /// - Parameter eventLoop: The event loop to use for this connection.
  237. /// - Parameter connectivity: A connectivity state monitor.
  238. /// - Parameter backoffIterator: An `Iterator` for `ConnectionBackoff` providing a sequence of
  239. /// connection timeouts and backoff to use when attempting to create a connection.
  240. private class func makeChannel(
  241. configuration: Configuration,
  242. eventLoop: EventLoop,
  243. connectivity: ConnectivityStateMonitor,
  244. backoffIterator: ConnectionBackoffIterator?,
  245. logger: Logger
  246. ) -> EventLoopFuture<Channel> {
  247. guard connectivity.state == .idle || connectivity.state == .transientFailure else {
  248. return configuration.eventLoopGroup.next().makeFailedFuture(GRPCStatus.processingError)
  249. }
  250. logger.debug("attempting to connect to \(configuration.target) on \(eventLoop)")
  251. connectivity.state = .connecting
  252. let timeoutAndBackoff = backoffIterator?.next()
  253. let bootstrap = self.makeBootstrap(
  254. configuration: configuration,
  255. eventLoop: eventLoop,
  256. timeout: timeoutAndBackoff?.timeout,
  257. connectivityMonitor: connectivity,
  258. logger: logger
  259. )
  260. let channel = bootstrap.connect(to: configuration.target).flatMap { channel -> EventLoopFuture<Channel> in
  261. if configuration.tls != nil {
  262. return channel.verifyTLS().map { channel }
  263. } else {
  264. return channel.eventLoop.makeSucceededFuture(channel)
  265. }
  266. }
  267. // If we don't have backoff then we can't retry, just return the `channel` no matter what
  268. // state we are in.
  269. guard let backoff = timeoutAndBackoff?.backoff else {
  270. logger.debug("backoff exhausted, no more connection attempts will be made")
  271. return channel
  272. }
  273. // If our connection attempt was unsuccessful, schedule another attempt in some time.
  274. return channel.flatMapError { error in
  275. logger.notice("connection attempt failed", metadata: [MetadataKey.error: "\(error)"])
  276. // We will try to connect again: the failure is transient.
  277. connectivity.state = .transientFailure
  278. return ClientConnection.scheduleReconnectAttempt(
  279. in: backoff,
  280. on: channel.eventLoop,
  281. configuration: configuration,
  282. connectivity: connectivity,
  283. backoffIterator: backoffIterator,
  284. logger: logger
  285. )
  286. }
  287. }
  288. /// Schedule an attempt to make a channel in `timeout` seconds on the given `eventLoop`.
  289. private class func scheduleReconnectAttempt(
  290. in timeout: TimeInterval,
  291. on eventLoop: EventLoop,
  292. configuration: Configuration,
  293. connectivity: ConnectivityStateMonitor,
  294. backoffIterator: ConnectionBackoffIterator?,
  295. logger: Logger
  296. ) -> EventLoopFuture<Channel> {
  297. logger.debug("scheduling connection attempt in \(timeout) seconds")
  298. // The `futureResult` of the scheduled task is of type
  299. // `EventLoopFuture<EventLoopFuture<Channel>>`, so we need to `flatMap` it to
  300. // remove a level of indirection.
  301. return eventLoop.scheduleTask(in: .seconds(timeInterval: timeout)) {
  302. ClientConnection.makeChannel(
  303. configuration: configuration,
  304. eventLoop: eventLoop,
  305. connectivity: connectivity,
  306. backoffIterator: backoffIterator,
  307. logger: logger
  308. )
  309. }.futureResult.flatMap { channel in
  310. channel
  311. }
  312. }
  313. /// Makes and configures a `ClientBootstrap` using the provided configuration.
  314. ///
  315. /// Enables `SO_REUSEADDR` and `TCP_NODELAY` and configures the `channelInitializer` to use the
  316. /// handlers detailed in the documentation for `ClientConnection`.
  317. ///
  318. /// - Parameter configuration: The configuration to prepare the bootstrap with.
  319. /// - Parameter eventLoop: The `EventLoop` to use for the bootstrap.
  320. /// - Parameter timeout: The connection timeout in seconds.
  321. /// - Parameter connectivityMonitor: The connectivity state monitor for the created channel.
  322. private class func makeBootstrap(
  323. configuration: Configuration,
  324. eventLoop: EventLoop,
  325. timeout: TimeInterval?,
  326. connectivityMonitor: ConnectivityStateMonitor,
  327. logger: Logger
  328. ) -> ClientBootstrapProtocol {
  329. // Provide a server hostname if we're using TLS. Prefer the override.
  330. let serverHostname: String? = configuration.tls.map {
  331. if let hostnameOverride = $0.hostnameOverride {
  332. logger.debug("using hostname override for TLS", metadata: ["server-hostname": "\(hostnameOverride)"])
  333. return hostnameOverride
  334. } else {
  335. let host = configuration.target.host
  336. logger.debug("using host from connection target for TLS", metadata: ["server-hostname": "\(host)"])
  337. return host
  338. }
  339. }
  340. let bootstrap = PlatformSupport.makeClientBootstrap(group: eventLoop)
  341. // Enable SO_REUSEADDR and TCP_NODELAY.
  342. .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
  343. .channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  344. .channelInitializer { channel in
  345. initializeChannel(
  346. channel,
  347. tls: configuration.tls?.configuration,
  348. serverHostname: serverHostname,
  349. connectivityMonitor: connectivityMonitor,
  350. errorDelegate: configuration.errorDelegate
  351. )
  352. }
  353. if let timeout = timeout {
  354. logger.debug("setting connect timeout to \(timeout) seconds")
  355. return bootstrap.connectTimeout(.seconds(timeInterval: timeout))
  356. } else {
  357. logger.debug("no connect timeout provided")
  358. return bootstrap
  359. }
  360. }
  361. /// Initialize the channel with the given TLS configuration and error delegate.
  362. ///
  363. /// - Parameter channel: The channel to initialize.
  364. /// - Parameter tls: The optional TLS configuration for the channel.
  365. /// - Parameter serverHostname: The hostname of the server to use for TLS.
  366. /// - Parameter errorDelegate: Optional client error delegate.
  367. private class func initializeChannel(
  368. _ channel: Channel,
  369. tls: TLSConfiguration?,
  370. serverHostname: String?,
  371. connectivityMonitor: ConnectivityStateMonitor,
  372. errorDelegate: ClientErrorDelegate?
  373. ) -> EventLoopFuture<Void> {
  374. let tlsConfigured = tls.map {
  375. channel.configureTLS($0, serverHostname: serverHostname, errorDelegate: errorDelegate)
  376. }
  377. return (tlsConfigured ?? channel.eventLoop.makeSucceededFuture(())).flatMap {
  378. channel.configureHTTP2Pipeline(mode: .client)
  379. }.flatMap { _ in
  380. let settingsObserver = InitialSettingsObservingHandler(connectivityStateMonitor: connectivityMonitor)
  381. let errorHandler = DelegatingErrorHandler(delegate: errorDelegate)
  382. return channel.pipeline.addHandlers(settingsObserver, errorHandler)
  383. }
  384. }
  385. }
  386. // MARK: - Configuration structures
  387. /// A target to connect to.
  388. public enum ConnectionTarget {
  389. /// The host and port.
  390. case hostAndPort(String, Int)
  391. /// The path of a Unix domain socket.
  392. case unixDomainSocket(String)
  393. /// A NIO socket address.
  394. case socketAddress(SocketAddress)
  395. var host: String {
  396. switch self {
  397. case .hostAndPort(let host, _):
  398. return host
  399. case .socketAddress(.v4(let address)):
  400. return address.host
  401. case .socketAddress(.v6(let address)):
  402. return address.host
  403. case .unixDomainSocket, .socketAddress(.unixDomainSocket):
  404. return "localhost"
  405. }
  406. }
  407. }
  408. extension ClientConnection {
  409. /// The configuration for a connection.
  410. public struct Configuration {
  411. /// The target to connect to.
  412. public var target: ConnectionTarget
  413. /// The event loop group to run the connection on.
  414. public var eventLoopGroup: EventLoopGroup
  415. /// An error delegate which is called when errors are caught. Provided delegates **must not
  416. /// maintain a strong reference to this `ClientConnection`**. Doing so will cause a retain
  417. /// cycle.
  418. public var errorDelegate: ClientErrorDelegate?
  419. /// A delegate which is called when the connectivity state is changed.
  420. public var connectivityStateDelegate: ConnectivityStateDelegate?
  421. /// TLS configuration for this connection. `nil` if TLS is not desired.
  422. public var tls: TLS?
  423. /// The connection backoff configuration. If no connection retrying is required then this should
  424. /// be `nil`.
  425. public var connectionBackoff: ConnectionBackoff?
  426. /// The HTTP protocol used for this connection.
  427. public var httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol {
  428. return self.tls == nil ? .http : .https
  429. }
  430. /// Create a `Configuration` with some pre-defined defaults.
  431. ///
  432. /// - Parameter target: The target to connect to.
  433. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  434. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  435. /// on debug builds.
  436. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`.
  437. /// - Parameter tlsConfiguration: TLS configuration, defaulting to `nil`.
  438. /// - Parameter connectionBackoff: The connection backoff configuration to use.
  439. public init(
  440. target: ConnectionTarget,
  441. eventLoopGroup: EventLoopGroup,
  442. errorDelegate: ClientErrorDelegate? = LoggingClientErrorDelegate(),
  443. connectivityStateDelegate: ConnectivityStateDelegate? = nil,
  444. tls: Configuration.TLS? = nil,
  445. connectionBackoff: ConnectionBackoff? = ConnectionBackoff()
  446. ) {
  447. self.target = target
  448. self.eventLoopGroup = eventLoopGroup
  449. self.errorDelegate = errorDelegate
  450. self.connectivityStateDelegate = connectivityStateDelegate
  451. self.tls = tls
  452. self.connectionBackoff = connectionBackoff
  453. }
  454. }
  455. }
  456. // MARK: - Configuration helpers/extensions
  457. fileprivate extension ClientBootstrapProtocol {
  458. /// Connect to the given connection target.
  459. ///
  460. /// - Parameter target: The target to connect to.
  461. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  462. switch target {
  463. case .hostAndPort(let host, let port):
  464. return self.connect(host: host, port: port)
  465. case .unixDomainSocket(let path):
  466. return self.connect(unixDomainSocketPath: path)
  467. case .socketAddress(let address):
  468. return self.connect(to: address)
  469. }
  470. }
  471. }
  472. fileprivate extension Channel {
  473. /// Configure the channel with TLS.
  474. ///
  475. /// This function adds two handlers to the pipeline: the `NIOSSLClientHandler` to handle TLS, and
  476. /// the `TLSVerificationHandler` which verifies that a successful handshake was completed.
  477. ///
  478. /// - Parameter configuration: The configuration to configure the channel with.
  479. /// - Parameter serverHostname: The server hostname to use if the hostname should be verified.
  480. /// - Parameter errorDelegate: The error delegate to use for the TLS verification handler.
  481. func configureTLS(
  482. _ configuration: TLSConfiguration,
  483. serverHostname: String?,
  484. errorDelegate: ClientErrorDelegate?
  485. ) -> EventLoopFuture<Void> {
  486. do {
  487. let sslClientHandler = try NIOSSLClientHandler(
  488. context: try NIOSSLContext(configuration: configuration),
  489. serverHostname: serverHostname
  490. )
  491. return self.pipeline.addHandlers(sslClientHandler, TLSVerificationHandler())
  492. } catch {
  493. return self.eventLoop.makeFailedFuture(error)
  494. }
  495. }
  496. /// Returns the `verification` future from the `TLSVerificationHandler` in this channels pipeline.
  497. func verifyTLS() -> EventLoopFuture<Void> {
  498. return self.pipeline.handler(type: TLSVerificationHandler.self).flatMap {
  499. $0.verification
  500. }
  501. }
  502. }
  503. fileprivate extension TimeAmount {
  504. /// Creates a new `TimeAmount` from the given time interval in seconds.
  505. ///
  506. /// - Parameter timeInterval: The amount of time in seconds
  507. static func seconds(timeInterval: TimeInterval) -> TimeAmount {
  508. return .nanoseconds(Int64(timeInterval * 1_000_000_000))
  509. }
  510. }
  511. extension HTTP2ToHTTP1ClientCodec.HTTPProtocol {
  512. var scheme: String {
  513. switch self {
  514. case .http:
  515. return "http"
  516. case .https:
  517. return "https"
  518. }
  519. }
  520. }