ClientConnection.swift 26 KB

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