ClientConnection.swift 27 KB

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