ClientConnection.swift 27 KB

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