ClientConnection.swift 24 KB

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