ClientConnection.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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 Logging
  18. import NIOCore
  19. import NIOHPACK
  20. import NIOHTTP2
  21. import NIOSSL
  22. import NIOTLS
  23. import NIOTransportServices
  24. import SwiftProtobuf
  25. /// Provides a single, managed connection to a server which is guaranteed to always use the same
  26. /// `EventLoop`.
  27. ///
  28. /// The connection to the server is provided by a single channel which will attempt to reconnect to
  29. /// the server if the connection is dropped. When either the client or server detects that the
  30. /// connection has become idle -- that is, there are no outstanding RPCs and the idle timeout has
  31. /// passed (5 minutes, by default) -- the underlying channel will be closed. The client will not
  32. /// idle the connection if any RPC exists, even if there has been no activity on the RPC for the
  33. /// idle timeout. Long-lived, low activity RPCs may benefit from configuring keepalive (see
  34. /// `ClientConnectionKeepalive`) which periodically pings the server to ensure that the connection
  35. /// is not dropped. If the connection is idle a new channel will be created on-demand when the next
  36. /// RPC is made.
  37. ///
  38. /// The state of the connection can be observed using a `ConnectivityStateDelegate`.
  39. ///
  40. /// Since the connection is managed, and may potentially spend long periods of time waiting for a
  41. /// connection to come up (cellular connections, for example), different behaviors may be used when
  42. /// starting a call. The different behaviors are detailed in the `CallStartBehavior` documentation.
  43. ///
  44. /// ### Channel Pipeline
  45. ///
  46. /// The `NIO.ChannelPipeline` for the connection is configured as such:
  47. ///
  48. /// ┌──────────────────────────┐
  49. /// │ DelegatingErrorHandler │
  50. /// └──────────▲───────────────┘
  51. /// HTTP2Frame│
  52. /// │ ⠇ ⠇ ⠇ ⠇
  53. /// │ ┌┴─▼┐ ┌┴─▼┐
  54. /// │ │ | │ | HTTP/2 streams
  55. /// │ └▲─┬┘ └▲─┬┘
  56. /// │ │ │ │ │ HTTP2Frame
  57. /// ┌─┴────────────────┴─▼───┴─▼┐
  58. /// │ HTTP2StreamMultiplexer |
  59. /// └─▲───────────────────────┬─┘
  60. /// HTTP2Frame│ │HTTP2Frame
  61. /// ┌─┴───────────────────────▼─┐
  62. /// │ GRPCIdleHandler │
  63. /// └─▲───────────────────────┬─┘
  64. /// HTTP2Frame│ │HTTP2Frame
  65. /// ┌─┴───────────────────────▼─┐
  66. /// │ NIOHTTP2Handler │
  67. /// └─▲───────────────────────┬─┘
  68. /// ByteBuffer│ │ByteBuffer
  69. /// ┌─┴───────────────────────▼─┐
  70. /// │ NIOSSLHandler │
  71. /// └─▲───────────────────────┬─┘
  72. /// ByteBuffer│ │ByteBuffer
  73. /// │ ▼
  74. ///
  75. /// The 'GRPCIdleHandler' intercepts HTTP/2 frames and various events and is responsible for
  76. /// informing and controlling the state of the connection (idling and keepalive). The HTTP/2 streams
  77. /// are used to handle individual RPCs.
  78. public class ClientConnection {
  79. private let connectionManager: ConnectionManager
  80. /// HTTP multiplexer from the underlying channel handling gRPC calls.
  81. internal func getMultiplexer() -> EventLoopFuture<HTTP2StreamMultiplexer> {
  82. return self.connectionManager.getHTTP2Multiplexer()
  83. }
  84. /// The configuration for this client.
  85. internal let configuration: Configuration
  86. /// The scheme of the URI for each RPC, i.e. 'http' or 'https'.
  87. internal let scheme: String
  88. /// The authority of the URI for each RPC.
  89. internal let authority: String
  90. /// A monitor for the connectivity state.
  91. public let connectivity: ConnectivityStateMonitor
  92. /// The `EventLoop` this connection is using.
  93. public var eventLoop: EventLoop {
  94. return self.connectionManager.eventLoop
  95. }
  96. /// Creates a new connection from the given configuration. Prefer using
  97. /// `ClientConnection.secure(group:)` to build a connection secured with TLS or
  98. /// `ClientConnection.insecure(group:)` to build a plaintext connection.
  99. ///
  100. /// - Important: Users should prefer using `ClientConnection.secure(group:)` to build a connection
  101. /// with TLS, or `ClientConnection.insecure(group:)` to build a connection without TLS.
  102. public init(configuration: Configuration) {
  103. self.configuration = configuration
  104. self.scheme = configuration.tlsConfiguration == nil ? "http" : "https"
  105. self.authority = configuration.tlsConfiguration?.hostnameOverride ?? configuration.target.host
  106. let monitor = ConnectivityStateMonitor(
  107. delegate: configuration.connectivityStateDelegate,
  108. queue: configuration.connectivityStateDelegateQueue
  109. )
  110. self.connectivity = monitor
  111. self.connectionManager = ConnectionManager(
  112. configuration: configuration,
  113. connectivityDelegate: monitor,
  114. logger: configuration.backgroundActivityLogger
  115. )
  116. }
  117. /// Closes the connection to the server.
  118. public func close() -> EventLoopFuture<Void> {
  119. return self.connectionManager.shutdown()
  120. }
  121. /// Populates the logger in `options` and appends a request ID header to the metadata, if
  122. /// configured.
  123. /// - Parameter options: The options containing the logger to populate.
  124. private func populateLogger(in options: inout CallOptions) {
  125. // Get connection metadata.
  126. self.connectionManager.appendMetadata(to: &options.logger)
  127. // Attach a request ID.
  128. let requestID = options.requestIDProvider.requestID()
  129. if let requestID = requestID {
  130. options.logger[metadataKey: MetadataKey.requestID] = "\(requestID)"
  131. // Add the request ID header too.
  132. if let requestIDHeader = options.requestIDHeader {
  133. options.customMetadata.add(name: requestIDHeader, value: requestID)
  134. }
  135. }
  136. }
  137. }
  138. extension ClientConnection: GRPCChannel {
  139. public func makeCall<Request: Message, Response: Message>(
  140. path: String,
  141. type: GRPCCallType,
  142. callOptions: CallOptions,
  143. interceptors: [ClientInterceptor<Request, Response>]
  144. ) -> Call<Request, Response> {
  145. var options = callOptions
  146. self.populateLogger(in: &options)
  147. let multiplexer = self.getMultiplexer()
  148. let eventLoop = callOptions.eventLoopPreference.exact ?? multiplexer.eventLoop
  149. // This should be on the same event loop as the multiplexer (i.e. the event loop of the
  150. // underlying `Channel`.
  151. let channel = multiplexer.eventLoop.makePromise(of: Channel.self)
  152. multiplexer.whenComplete {
  153. ClientConnection.makeStreamChannel(using: $0, promise: channel)
  154. }
  155. return Call(
  156. path: path,
  157. type: type,
  158. eventLoop: eventLoop,
  159. options: options,
  160. interceptors: interceptors,
  161. transportFactory: .http2(
  162. channel: channel.futureResult,
  163. authority: self.authority,
  164. scheme: self.scheme,
  165. maximumReceiveMessageLength: self.configuration.maximumReceiveMessageLength,
  166. errorDelegate: self.configuration.errorDelegate
  167. )
  168. )
  169. }
  170. public func makeCall<Request: GRPCPayload, Response: GRPCPayload>(
  171. path: String,
  172. type: GRPCCallType,
  173. callOptions: CallOptions,
  174. interceptors: [ClientInterceptor<Request, Response>]
  175. ) -> Call<Request, Response> {
  176. var options = callOptions
  177. self.populateLogger(in: &options)
  178. let multiplexer = self.getMultiplexer()
  179. let eventLoop = callOptions.eventLoopPreference.exact ?? multiplexer.eventLoop
  180. // This should be on the same event loop as the multiplexer (i.e. the event loop of the
  181. // underlying `Channel`.
  182. let channel = multiplexer.eventLoop.makePromise(of: Channel.self)
  183. multiplexer.whenComplete {
  184. ClientConnection.makeStreamChannel(using: $0, promise: channel)
  185. }
  186. return Call(
  187. path: path,
  188. type: type,
  189. eventLoop: eventLoop,
  190. options: options,
  191. interceptors: interceptors,
  192. transportFactory: .http2(
  193. channel: channel.futureResult,
  194. authority: self.authority,
  195. scheme: self.scheme,
  196. maximumReceiveMessageLength: self.configuration.maximumReceiveMessageLength,
  197. errorDelegate: self.configuration.errorDelegate
  198. )
  199. )
  200. }
  201. private static func makeStreamChannel(
  202. using result: Result<HTTP2StreamMultiplexer, Error>,
  203. promise: EventLoopPromise<Channel>
  204. ) {
  205. switch result {
  206. case let .success(multiplexer):
  207. multiplexer.createStreamChannel(promise: promise) {
  208. $0.eventLoop.makeSucceededVoidFuture()
  209. }
  210. case let .failure(error):
  211. promise.fail(error)
  212. }
  213. }
  214. }
  215. // MARK: - Configuration structures
  216. /// A target to connect to.
  217. public struct ConnectionTarget {
  218. internal enum Wrapped {
  219. case hostAndPort(String, Int)
  220. case unixDomainSocket(String)
  221. case socketAddress(SocketAddress)
  222. }
  223. internal var wrapped: Wrapped
  224. private init(_ wrapped: Wrapped) {
  225. self.wrapped = wrapped
  226. }
  227. /// The host and port. The port is 443 by default.
  228. public static func host(_ host: String, port: Int = 443) -> ConnectionTarget {
  229. return ConnectionTarget(.hostAndPort(host, port))
  230. }
  231. /// The host and port.
  232. public static func hostAndPort(_ host: String, _ port: Int) -> ConnectionTarget {
  233. return ConnectionTarget(.hostAndPort(host, port))
  234. }
  235. /// The path of a Unix domain socket.
  236. public static func unixDomainSocket(_ path: String) -> ConnectionTarget {
  237. return ConnectionTarget(.unixDomainSocket(path))
  238. }
  239. /// A NIO socket address.
  240. public static func socketAddress(_ address: SocketAddress) -> ConnectionTarget {
  241. return ConnectionTarget(.socketAddress(address))
  242. }
  243. @usableFromInline
  244. var host: String {
  245. switch self.wrapped {
  246. case let .hostAndPort(host, _):
  247. return host
  248. case let .socketAddress(.v4(address)):
  249. return address.host
  250. case let .socketAddress(.v6(address)):
  251. return address.host
  252. case .unixDomainSocket, .socketAddress(.unixDomainSocket):
  253. return "localhost"
  254. }
  255. }
  256. }
  257. /// The connectivity behavior to use when starting an RPC.
  258. public struct CallStartBehavior: Hashable {
  259. internal enum Behavior: Hashable {
  260. case waitsForConnectivity
  261. case fastFailure
  262. }
  263. internal var wrapped: Behavior
  264. private init(_ wrapped: Behavior) {
  265. self.wrapped = wrapped
  266. }
  267. /// Waits for connectivity (that is, the 'ready' connectivity state) before attempting to start
  268. /// an RPC. Doing so may involve multiple connection attempts.
  269. ///
  270. /// This is the preferred, and default, behaviour.
  271. public static let waitsForConnectivity = CallStartBehavior(.waitsForConnectivity)
  272. /// The 'fast failure' behaviour is intended for cases where users would rather their RPC failed
  273. /// quickly rather than waiting for an active connection. The behaviour depends on the current
  274. /// connectivity state:
  275. ///
  276. /// - Idle: a connection attempt will be started and the RPC will fail if that attempt fails.
  277. /// - Connecting: a connection attempt is already in progress, the RPC will fail if that attempt
  278. /// fails.
  279. /// - Ready: a connection is already active: the RPC will be started using that connection.
  280. /// - Transient failure: the last connection or connection attempt failed and gRPC is waiting to
  281. /// connect again. The RPC will fail immediately.
  282. /// - Shutdown: the connection is shutdown, the RPC will fail immediately.
  283. public static let fastFailure = CallStartBehavior(.fastFailure)
  284. }
  285. extension ClientConnection {
  286. /// Configuration for a `ClientConnection`. Users should prefer using one of the
  287. /// `ClientConnection` builders: `ClientConnection.secure(_:)` or `ClientConnection.insecure(_:)`.
  288. public struct Configuration {
  289. /// The target to connect to.
  290. public var target: ConnectionTarget
  291. /// The event loop group to run the connection on.
  292. public var eventLoopGroup: EventLoopGroup
  293. /// An error delegate which is called when errors are caught. Provided delegates **must not
  294. /// maintain a strong reference to this `ClientConnection`**. Doing so will cause a retain
  295. /// cycle. Defaults to `LoggingClientErrorDelegate`.
  296. public var errorDelegate: ClientErrorDelegate? = LoggingClientErrorDelegate.shared
  297. /// A delegate which is called when the connectivity state is changed. Defaults to `nil`.
  298. public var connectivityStateDelegate: ConnectivityStateDelegate?
  299. /// The `DispatchQueue` on which to call the connectivity state delegate. If a delegate is
  300. /// provided but the queue is `nil` then one will be created by gRPC. Defaults to `nil`.
  301. public var connectivityStateDelegateQueue: DispatchQueue?
  302. /// TLS configuration for this connection. `nil` if TLS is not desired.
  303. ///
  304. /// - Important: `tls` is deprecated; use `tlsConfiguration` or one of
  305. /// the `ClientConnection.withTLS` builder functions.
  306. @available(*, deprecated, renamed: "tlsConfiguration")
  307. public var tls: TLS? {
  308. get {
  309. return self.tlsConfiguration?.asDeprecatedClientConfiguration
  310. }
  311. set {
  312. self.tlsConfiguration = newValue.map { .init(transforming: $0) }
  313. }
  314. }
  315. /// TLS configuration for this connection. `nil` if TLS is not desired.
  316. public var tlsConfiguration: GRPCTLSConfiguration?
  317. /// The connection backoff configuration. If no connection retrying is required then this should
  318. /// be `nil`.
  319. public var connectionBackoff: ConnectionBackoff? = ConnectionBackoff()
  320. /// The connection keepalive configuration.
  321. public var connectionKeepalive = ClientConnectionKeepalive()
  322. /// The amount of time to wait before closing the connection. The idle timeout will start only
  323. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start.
  324. ///
  325. /// If a connection becomes idle, starting a new RPC will automatically create a new connection.
  326. ///
  327. /// Defaults to 30 minutes.
  328. public var connectionIdleTimeout: TimeAmount = .minutes(30)
  329. /// The behavior used to determine when an RPC should start. That is, whether it should wait for
  330. /// an active connection or fail quickly if no connection is currently available.
  331. ///
  332. /// Defaults to `waitsForConnectivity`.
  333. public var callStartBehavior: CallStartBehavior = .waitsForConnectivity
  334. /// The HTTP/2 flow control target window size. Defaults to 8MB. Values are clamped between
  335. /// 1 and 2^31-1 inclusive.
  336. public var httpTargetWindowSize = 8 * 1024 * 1024 {
  337. didSet {
  338. self.httpTargetWindowSize = self.httpTargetWindowSize.clamped(to: 1 ... Int(Int32.max))
  339. }
  340. }
  341. /// The HTTP/2 max frame size. Defaults to 16384. Value is clamped between 2^14 and 2^24-1
  342. /// octets inclusive (the minimum and maximum allowable values - HTTP/2 RFC 7540 4.2).
  343. public var httpMaxFrameSize: Int = 16384 {
  344. didSet {
  345. self.httpMaxFrameSize = self.httpMaxFrameSize.clamped(to: 16384 ... 16_777_215)
  346. }
  347. }
  348. /// The HTTP protocol used for this connection.
  349. public var httpProtocol: HTTP2FramePayloadToHTTP1ClientCodec.HTTPProtocol {
  350. return self.tlsConfiguration == nil ? .http : .https
  351. }
  352. /// The maximum size in bytes of a message which may be received from a server. Defaults to 4MB.
  353. public var maximumReceiveMessageLength: Int = 4 * 1024 * 1024 {
  354. willSet {
  355. precondition(newValue >= 0, "maximumReceiveMessageLength must be positive")
  356. }
  357. }
  358. /// A logger for background information (such as connectivity state). A separate logger for
  359. /// requests may be provided in the `CallOptions`.
  360. ///
  361. /// Defaults to a no-op logger.
  362. public var backgroundActivityLogger = Logger(
  363. label: "io.grpc",
  364. factory: { _ in SwiftLogNoOpLogHandler() }
  365. )
  366. /// A channel initializer which will be run after gRPC has initialized each channel. This may be
  367. /// used to add additional handlers to the pipeline and is intended for debugging.
  368. ///
  369. /// - Warning: The initializer closure may be invoked *multiple times*.
  370. public var debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?
  371. /// Create a `Configuration` with some pre-defined defaults. Prefer using
  372. /// `ClientConnection.secure(group:)` to build a connection secured with TLS or
  373. /// `ClientConnection.insecure(group:)` to build a plaintext connection.
  374. ///
  375. /// - Parameter target: The target to connect to.
  376. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  377. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  378. /// on debug builds.
  379. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`.
  380. /// - Parameter connectivityStateDelegateQueue: A `DispatchQueue` on which to call the
  381. /// `connectivityStateDelegate`.
  382. /// - Parameter tls: TLS configuration, defaulting to `nil`.
  383. /// - Parameter connectionBackoff: The connection backoff configuration to use.
  384. /// - Parameter connectionKeepalive: The keepalive configuration to use.
  385. /// - Parameter connectionIdleTimeout: The amount of time to wait before closing the connection, defaulting to 30 minutes.
  386. /// - Parameter callStartBehavior: The behavior used to determine when a call should start in
  387. /// relation to its underlying connection. Defaults to `waitsForConnectivity`.
  388. /// - Parameter httpTargetWindowSize: The HTTP/2 flow control target window size.
  389. /// - Parameter backgroundActivityLogger: A logger for background information (such as
  390. /// connectivity state). Defaults to a no-op logger.
  391. /// - Parameter debugChannelInitializer: A channel initializer will be called after gRPC has
  392. /// initialized the channel. Defaults to `nil`.
  393. @available(*, deprecated, renamed: "default(target:eventLoopGroup:)")
  394. public init(
  395. target: ConnectionTarget,
  396. eventLoopGroup: EventLoopGroup,
  397. errorDelegate: ClientErrorDelegate? = LoggingClientErrorDelegate(),
  398. connectivityStateDelegate: ConnectivityStateDelegate? = nil,
  399. connectivityStateDelegateQueue: DispatchQueue? = nil,
  400. tls: Configuration.TLS? = nil,
  401. connectionBackoff: ConnectionBackoff? = ConnectionBackoff(),
  402. connectionKeepalive: ClientConnectionKeepalive = ClientConnectionKeepalive(),
  403. connectionIdleTimeout: TimeAmount = .minutes(30),
  404. callStartBehavior: CallStartBehavior = .waitsForConnectivity,
  405. httpTargetWindowSize: Int = 8 * 1024 * 1024,
  406. backgroundActivityLogger: Logger = Logger(
  407. label: "io.grpc",
  408. factory: { _ in SwiftLogNoOpLogHandler() }
  409. ),
  410. debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)? = nil
  411. ) {
  412. self.target = target
  413. self.eventLoopGroup = eventLoopGroup
  414. self.errorDelegate = errorDelegate
  415. self.connectivityStateDelegate = connectivityStateDelegate
  416. self.connectivityStateDelegateQueue = connectivityStateDelegateQueue
  417. self.tlsConfiguration = tls.map { GRPCTLSConfiguration(transforming: $0) }
  418. self.connectionBackoff = connectionBackoff
  419. self.connectionKeepalive = connectionKeepalive
  420. self.connectionIdleTimeout = connectionIdleTimeout
  421. self.callStartBehavior = callStartBehavior
  422. self.httpTargetWindowSize = httpTargetWindowSize
  423. self.backgroundActivityLogger = backgroundActivityLogger
  424. self.debugChannelInitializer = debugChannelInitializer
  425. }
  426. private init(eventLoopGroup: EventLoopGroup, target: ConnectionTarget) {
  427. self.eventLoopGroup = eventLoopGroup
  428. self.target = target
  429. }
  430. /// Make a new configuration using default values.
  431. ///
  432. /// - Parameters:
  433. /// - target: The target to connect to.
  434. /// - eventLoopGroup: The `EventLoopGroup` providing an `EventLoop` for the connection to
  435. /// run on.
  436. /// - Returns: A configuration with default values set.
  437. public static func `default`(
  438. target: ConnectionTarget,
  439. eventLoopGroup: EventLoopGroup
  440. ) -> Configuration {
  441. return .init(eventLoopGroup: eventLoopGroup, target: target)
  442. }
  443. }
  444. }
  445. // MARK: - Configuration helpers/extensions
  446. extension ClientBootstrapProtocol {
  447. /// Connect to the given connection target.
  448. ///
  449. /// - Parameter target: The target to connect to.
  450. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  451. switch target.wrapped {
  452. case let .hostAndPort(host, port):
  453. return self.connect(host: host, port: port)
  454. case let .unixDomainSocket(path):
  455. return self.connect(unixDomainSocketPath: path)
  456. case let .socketAddress(address):
  457. return self.connect(to: address)
  458. }
  459. }
  460. }
  461. extension ChannelPipeline.SynchronousOperations {
  462. internal func configureNIOSSLForGRPCClient(
  463. sslContext: Result<NIOSSLContext, Error>,
  464. serverHostname: String?,
  465. customVerificationCallback: NIOSSLCustomVerificationCallback?,
  466. logger: Logger
  467. ) throws {
  468. let sslContext = try sslContext.get()
  469. let sslClientHandler: NIOSSLClientHandler
  470. if let customVerificationCallback = customVerificationCallback {
  471. sslClientHandler = try NIOSSLClientHandler(
  472. context: sslContext,
  473. serverHostname: serverHostname,
  474. customVerificationCallback: customVerificationCallback
  475. )
  476. } else {
  477. sslClientHandler = try NIOSSLClientHandler(
  478. context: sslContext,
  479. serverHostname: serverHostname
  480. )
  481. }
  482. try self.addHandler(sslClientHandler)
  483. try self.addHandler(TLSVerificationHandler(logger: logger))
  484. }
  485. internal func configureHTTP2AndGRPCHandlersForGRPCClient(
  486. channel: Channel,
  487. connectionManager: ConnectionManager,
  488. connectionKeepalive: ClientConnectionKeepalive,
  489. connectionIdleTimeout: TimeAmount,
  490. httpTargetWindowSize: Int,
  491. httpMaxFrameSize: Int,
  492. errorDelegate: ClientErrorDelegate?,
  493. logger: Logger
  494. ) throws {
  495. let initialSettings = [
  496. // As per the default settings for swift-nio-http2:
  497. HTTP2Setting(parameter: .maxHeaderListSize, value: HPACKDecoder.defaultMaxHeaderListSize),
  498. // We never expect (or allow) server initiated streams.
  499. HTTP2Setting(parameter: .maxConcurrentStreams, value: 0),
  500. // As configured by the user.
  501. HTTP2Setting(parameter: .maxFrameSize, value: httpMaxFrameSize),
  502. HTTP2Setting(parameter: .initialWindowSize, value: httpTargetWindowSize),
  503. ]
  504. // We could use 'configureHTTP2Pipeline' here, but we need to add a few handlers between the
  505. // two HTTP/2 handlers so we'll do it manually instead.
  506. try self.addHandler(NIOHTTP2Handler(mode: .client, initialSettings: initialSettings))
  507. let h2Multiplexer = HTTP2StreamMultiplexer(
  508. mode: .client,
  509. channel: channel,
  510. targetWindowSize: httpTargetWindowSize,
  511. inboundStreamInitializer: nil
  512. )
  513. // The multiplexer is passed through the idle handler so it is only reported on
  514. // successful channel activation - with happy eyeballs multiple pipelines can
  515. // be constructed so it's not safe to report just yet.
  516. try self.addHandler(GRPCIdleHandler(
  517. connectionManager: connectionManager,
  518. multiplexer: h2Multiplexer,
  519. idleTimeout: connectionIdleTimeout,
  520. keepalive: connectionKeepalive,
  521. logger: logger
  522. ))
  523. try self.addHandler(h2Multiplexer)
  524. try self.addHandler(DelegatingErrorHandler(logger: logger, delegate: errorDelegate))
  525. }
  526. }
  527. extension Channel {
  528. func configureGRPCClient(
  529. errorDelegate: ClientErrorDelegate?,
  530. logger: Logger
  531. ) -> EventLoopFuture<Void> {
  532. return self.configureHTTP2Pipeline(mode: .client, inboundStreamInitializer: nil).flatMap { _ in
  533. self.pipeline.addHandler(DelegatingErrorHandler(logger: logger, delegate: errorDelegate))
  534. }
  535. }
  536. }
  537. extension TimeAmount {
  538. /// Creates a new `TimeAmount` from the given time interval in seconds.
  539. ///
  540. /// - Parameter timeInterval: The amount of time in seconds
  541. static func seconds(timeInterval: TimeInterval) -> TimeAmount {
  542. return .nanoseconds(Int64(timeInterval * 1_000_000_000))
  543. }
  544. }
  545. extension String {
  546. var isIPAddress: Bool {
  547. // We need some scratch space to let inet_pton write into.
  548. var ipv4Addr = in_addr()
  549. var ipv6Addr = in6_addr()
  550. return self.withCString { ptr in
  551. inet_pton(AF_INET, ptr, &ipv4Addr) == 1 ||
  552. inet_pton(AF_INET6, ptr, &ipv6Addr) == 1
  553. }
  554. }
  555. }