ClientConnection.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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. var host: String {
  244. switch self.wrapped {
  245. case let .hostAndPort(host, _):
  246. return host
  247. case let .socketAddress(.v4(address)):
  248. return address.host
  249. case let .socketAddress(.v6(address)):
  250. return address.host
  251. case .unixDomainSocket, .socketAddress(.unixDomainSocket):
  252. return "localhost"
  253. }
  254. }
  255. }
  256. /// The connectivity behavior to use when starting an RPC.
  257. public struct CallStartBehavior: Hashable {
  258. internal enum Behavior: Hashable {
  259. case waitsForConnectivity
  260. case fastFailure
  261. }
  262. internal var wrapped: Behavior
  263. private init(_ wrapped: Behavior) {
  264. self.wrapped = wrapped
  265. }
  266. /// Waits for connectivity (that is, the 'ready' connectivity state) before attempting to start
  267. /// an RPC. Doing so may involve multiple connection attempts.
  268. ///
  269. /// This is the preferred, and default, behaviour.
  270. public static let waitsForConnectivity = CallStartBehavior(.waitsForConnectivity)
  271. /// The 'fast failure' behaviour is intended for cases where users would rather their RPC failed
  272. /// quickly rather than waiting for an active connection. The behaviour depends on the current
  273. /// connectivity state:
  274. ///
  275. /// - Idle: a connection attempt will be started and the RPC will fail if that attempt fails.
  276. /// - Connecting: a connection attempt is already in progress, the RPC will fail if that attempt
  277. /// fails.
  278. /// - Ready: a connection is already active: the RPC will be started using that connection.
  279. /// - Transient failure: the last connection or connection attempt failed and gRPC is waiting to
  280. /// connect again. The RPC will fail immediately.
  281. /// - Shutdown: the connection is shutdown, the RPC will fail immediately.
  282. public static let fastFailure = CallStartBehavior(.fastFailure)
  283. }
  284. extension ClientConnection {
  285. /// Configuration for a `ClientConnection`. Users should prefer using one of the
  286. /// `ClientConnection` builders: `ClientConnection.secure(_:)` or `ClientConnection.insecure(_:)`.
  287. public struct Configuration {
  288. /// The target to connect to.
  289. public var target: ConnectionTarget
  290. /// The event loop group to run the connection on.
  291. public var eventLoopGroup: EventLoopGroup
  292. /// An error delegate which is called when errors are caught. Provided delegates **must not
  293. /// maintain a strong reference to this `ClientConnection`**. Doing so will cause a retain
  294. /// cycle. Defaults to `LoggingClientErrorDelegate`.
  295. public var errorDelegate: ClientErrorDelegate? = LoggingClientErrorDelegate.shared
  296. /// A delegate which is called when the connectivity state is changed. Defaults to `nil`.
  297. public var connectivityStateDelegate: ConnectivityStateDelegate?
  298. /// The `DispatchQueue` on which to call the connectivity state delegate. If a delegate is
  299. /// provided but the queue is `nil` then one will be created by gRPC. Defaults to `nil`.
  300. public var connectivityStateDelegateQueue: DispatchQueue?
  301. /// TLS configuration for this connection. `nil` if TLS is not desired.
  302. ///
  303. /// - Important: `tls` is deprecated; use `tlsConfiguration` or one of
  304. /// the `ClientConnection.withTLS` builder functions.
  305. @available(*, deprecated, renamed: "tlsConfiguration")
  306. public var tls: TLS? {
  307. get {
  308. return self.tlsConfiguration?.asDeprecatedClientConfiguration
  309. }
  310. set {
  311. self.tlsConfiguration = newValue.map { .init(transforming: $0) }
  312. }
  313. }
  314. /// TLS configuration for this connection. `nil` if TLS is not desired.
  315. public var tlsConfiguration: GRPCTLSConfiguration?
  316. /// The connection backoff configuration. If no connection retrying is required then this should
  317. /// be `nil`.
  318. public var connectionBackoff: ConnectionBackoff? = ConnectionBackoff()
  319. /// The connection keepalive configuration.
  320. public var connectionKeepalive = ClientConnectionKeepalive()
  321. /// The amount of time to wait before closing the connection. The idle timeout will start only
  322. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start.
  323. ///
  324. /// If a connection becomes idle, starting a new RPC will automatically create a new connection.
  325. ///
  326. /// Defaults to 30 minutes.
  327. public var connectionIdleTimeout: TimeAmount = .minutes(30)
  328. /// The behavior used to determine when an RPC should start. That is, whether it should wait for
  329. /// an active connection or fail quickly if no connection is currently available.
  330. ///
  331. /// Defaults to `waitsForConnectivity`.
  332. public var callStartBehavior: CallStartBehavior = .waitsForConnectivity
  333. /// The HTTP/2 flow control target window size. Defaults to 8MB. Values are clamped between
  334. /// 1 and 2^31-1 inclusive.
  335. public var httpTargetWindowSize = 8 * 1024 * 1024 {
  336. didSet {
  337. self.httpTargetWindowSize = self.httpTargetWindowSize.clamped(to: 1 ... Int(Int32.max))
  338. }
  339. }
  340. /// The HTTP/2 max frame size. Defaults to 16384. Value is clamped between 2^14 and 2^24-1
  341. /// octets inclusive (the minimum and maximum allowable values - HTTP/2 RFC 7540 4.2).
  342. public var httpMaxFrameSize: Int = 16384 {
  343. didSet {
  344. self.httpMaxFrameSize = self.httpMaxFrameSize.clamped(to: 16384 ... 16_777_215)
  345. }
  346. }
  347. /// The HTTP protocol used for this connection.
  348. public var httpProtocol: HTTP2FramePayloadToHTTP1ClientCodec.HTTPProtocol {
  349. return self.tlsConfiguration == nil ? .http : .https
  350. }
  351. /// The maximum size in bytes of a message which may be received from a server. Defaults to 4MB.
  352. public var maximumReceiveMessageLength: Int = 4 * 1024 * 1024 {
  353. willSet {
  354. precondition(newValue >= 0, "maximumReceiveMessageLength must be positive")
  355. }
  356. }
  357. /// A logger for background information (such as connectivity state). A separate logger for
  358. /// requests may be provided in the `CallOptions`.
  359. ///
  360. /// Defaults to a no-op logger.
  361. public var backgroundActivityLogger = Logger(
  362. label: "io.grpc",
  363. factory: { _ in SwiftLogNoOpLogHandler() }
  364. )
  365. /// A channel initializer which will be run after gRPC has initialized each channel. This may be
  366. /// used to add additional handlers to the pipeline and is intended for debugging.
  367. ///
  368. /// - Warning: The initializer closure may be invoked *multiple times*.
  369. public var debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?
  370. /// Create a `Configuration` with some pre-defined defaults. Prefer using
  371. /// `ClientConnection.secure(group:)` to build a connection secured with TLS or
  372. /// `ClientConnection.insecure(group:)` to build a plaintext connection.
  373. ///
  374. /// - Parameter target: The target to connect to.
  375. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  376. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  377. /// on debug builds.
  378. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`.
  379. /// - Parameter connectivityStateDelegateQueue: A `DispatchQueue` on which to call the
  380. /// `connectivityStateDelegate`.
  381. /// - Parameter tls: TLS configuration, defaulting to `nil`.
  382. /// - Parameter connectionBackoff: The connection backoff configuration to use.
  383. /// - Parameter connectionKeepalive: The keepalive configuration to use.
  384. /// - Parameter connectionIdleTimeout: The amount of time to wait before closing the connection, defaulting to 30 minutes.
  385. /// - Parameter callStartBehavior: The behavior used to determine when a call should start in
  386. /// relation to its underlying connection. Defaults to `waitsForConnectivity`.
  387. /// - Parameter httpTargetWindowSize: The HTTP/2 flow control target window size.
  388. /// - Parameter backgroundActivityLogger: A logger for background information (such as
  389. /// connectivity state). Defaults to a no-op logger.
  390. /// - Parameter debugChannelInitializer: A channel initializer will be called after gRPC has
  391. /// initialized the channel. Defaults to `nil`.
  392. @available(*, deprecated, renamed: "default(target:eventLoopGroup:)")
  393. public init(
  394. target: ConnectionTarget,
  395. eventLoopGroup: EventLoopGroup,
  396. errorDelegate: ClientErrorDelegate? = LoggingClientErrorDelegate(),
  397. connectivityStateDelegate: ConnectivityStateDelegate? = nil,
  398. connectivityStateDelegateQueue: DispatchQueue? = nil,
  399. tls: Configuration.TLS? = nil,
  400. connectionBackoff: ConnectionBackoff? = ConnectionBackoff(),
  401. connectionKeepalive: ClientConnectionKeepalive = ClientConnectionKeepalive(),
  402. connectionIdleTimeout: TimeAmount = .minutes(30),
  403. callStartBehavior: CallStartBehavior = .waitsForConnectivity,
  404. httpTargetWindowSize: Int = 8 * 1024 * 1024,
  405. backgroundActivityLogger: Logger = Logger(
  406. label: "io.grpc",
  407. factory: { _ in SwiftLogNoOpLogHandler() }
  408. ),
  409. debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)? = nil
  410. ) {
  411. self.target = target
  412. self.eventLoopGroup = eventLoopGroup
  413. self.errorDelegate = errorDelegate
  414. self.connectivityStateDelegate = connectivityStateDelegate
  415. self.connectivityStateDelegateQueue = connectivityStateDelegateQueue
  416. self.tlsConfiguration = tls.map { GRPCTLSConfiguration(transforming: $0) }
  417. self.connectionBackoff = connectionBackoff
  418. self.connectionKeepalive = connectionKeepalive
  419. self.connectionIdleTimeout = connectionIdleTimeout
  420. self.callStartBehavior = callStartBehavior
  421. self.httpTargetWindowSize = httpTargetWindowSize
  422. self.backgroundActivityLogger = backgroundActivityLogger
  423. self.debugChannelInitializer = debugChannelInitializer
  424. }
  425. private init(eventLoopGroup: EventLoopGroup, target: ConnectionTarget) {
  426. self.eventLoopGroup = eventLoopGroup
  427. self.target = target
  428. }
  429. /// Make a new configuration using default values.
  430. ///
  431. /// - Parameters:
  432. /// - target: The target to connect to.
  433. /// - eventLoopGroup: The `EventLoopGroup` providing an `EventLoop` for the connection to
  434. /// run on.
  435. /// - Returns: A configuration with default values set.
  436. public static func `default`(
  437. target: ConnectionTarget,
  438. eventLoopGroup: EventLoopGroup
  439. ) -> Configuration {
  440. return .init(eventLoopGroup: eventLoopGroup, target: target)
  441. }
  442. }
  443. }
  444. // MARK: - Configuration helpers/extensions
  445. extension ClientBootstrapProtocol {
  446. /// Connect to the given connection target.
  447. ///
  448. /// - Parameter target: The target to connect to.
  449. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  450. switch target.wrapped {
  451. case let .hostAndPort(host, port):
  452. return self.connect(host: host, port: port)
  453. case let .unixDomainSocket(path):
  454. return self.connect(unixDomainSocketPath: path)
  455. case let .socketAddress(address):
  456. return self.connect(to: address)
  457. }
  458. }
  459. }
  460. extension ChannelPipeline.SynchronousOperations {
  461. internal func configureNIOSSLForGRPCClient(
  462. sslContext: Result<NIOSSLContext, Error>,
  463. serverHostname: String?,
  464. customVerificationCallback: NIOSSLCustomVerificationCallback?,
  465. logger: Logger
  466. ) throws {
  467. let sslContext = try sslContext.get()
  468. let sslClientHandler: NIOSSLClientHandler
  469. if let customVerificationCallback = customVerificationCallback {
  470. sslClientHandler = try NIOSSLClientHandler(
  471. context: sslContext,
  472. serverHostname: serverHostname,
  473. customVerificationCallback: customVerificationCallback
  474. )
  475. } else {
  476. sslClientHandler = try NIOSSLClientHandler(
  477. context: sslContext,
  478. serverHostname: serverHostname
  479. )
  480. }
  481. try self.addHandler(sslClientHandler)
  482. try self.addHandler(TLSVerificationHandler(logger: logger))
  483. }
  484. internal func configureHTTP2AndGRPCHandlersForGRPCClient(
  485. channel: Channel,
  486. connectionManager: ConnectionManager,
  487. connectionKeepalive: ClientConnectionKeepalive,
  488. connectionIdleTimeout: TimeAmount,
  489. httpTargetWindowSize: Int,
  490. httpMaxFrameSize: Int,
  491. errorDelegate: ClientErrorDelegate?,
  492. logger: Logger
  493. ) throws {
  494. let initialSettings = [
  495. // As per the default settings for swift-nio-http2:
  496. HTTP2Setting(parameter: .maxHeaderListSize, value: HPACKDecoder.defaultMaxHeaderListSize),
  497. // We never expect (or allow) server initiated streams.
  498. HTTP2Setting(parameter: .maxConcurrentStreams, value: 0),
  499. // As configured by the user.
  500. HTTP2Setting(parameter: .maxFrameSize, value: httpMaxFrameSize),
  501. HTTP2Setting(parameter: .initialWindowSize, value: httpTargetWindowSize),
  502. ]
  503. // We could use 'configureHTTP2Pipeline' here, but we need to add a few handlers between the
  504. // two HTTP/2 handlers so we'll do it manually instead.
  505. try self.addHandler(NIOHTTP2Handler(mode: .client, initialSettings: initialSettings))
  506. let h2Multiplexer = HTTP2StreamMultiplexer(
  507. mode: .client,
  508. channel: channel,
  509. targetWindowSize: httpTargetWindowSize,
  510. inboundStreamInitializer: nil
  511. )
  512. // The multiplexer is passed through the idle handler so it is only reported on
  513. // successful channel activation - with happy eyeballs multiple pipelines can
  514. // be constructed so it's not safe to report just yet.
  515. try self.addHandler(GRPCIdleHandler(
  516. connectionManager: connectionManager,
  517. multiplexer: h2Multiplexer,
  518. idleTimeout: connectionIdleTimeout,
  519. keepalive: connectionKeepalive,
  520. logger: logger
  521. ))
  522. try self.addHandler(h2Multiplexer)
  523. try self.addHandler(DelegatingErrorHandler(logger: logger, delegate: errorDelegate))
  524. }
  525. }
  526. extension Channel {
  527. func configureGRPCClient(
  528. errorDelegate: ClientErrorDelegate?,
  529. logger: Logger
  530. ) -> EventLoopFuture<Void> {
  531. return self.configureHTTP2Pipeline(mode: .client, inboundStreamInitializer: nil).flatMap { _ in
  532. self.pipeline.addHandler(DelegatingErrorHandler(logger: logger, delegate: errorDelegate))
  533. }
  534. }
  535. }
  536. extension TimeAmount {
  537. /// Creates a new `TimeAmount` from the given time interval in seconds.
  538. ///
  539. /// - Parameter timeInterval: The amount of time in seconds
  540. static func seconds(timeInterval: TimeInterval) -> TimeAmount {
  541. return .nanoseconds(Int64(timeInterval * 1_000_000_000))
  542. }
  543. }
  544. extension String {
  545. var isIPAddress: Bool {
  546. // We need some scratch space to let inet_pton write into.
  547. var ipv4Addr = in_addr()
  548. var ipv6Addr = in6_addr()
  549. return self.withCString { ptr in
  550. inet_pton(AF_INET, ptr, &ipv4Addr) == 1 ||
  551. inet_pton(AF_INET6, ptr, &ipv6Addr) == 1
  552. }
  553. }
  554. }