ClientConnection.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  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. @preconcurrency 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 final class ClientConnection: Sendable {
  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: Sendable {
  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, Sendable {
  287. internal enum Behavior: Hashable, Sendable {
  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(group:)`` or ``ClientConnection/insecure(group:)``.
  316. public struct Configuration: Sendable {
  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/usingTLS(with:on:)`` 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 ``CallStartBehavior/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. @preconcurrency
  401. public var debugChannelInitializer: (@Sendable (Channel) -> EventLoopFuture<Void>)?
  402. #if canImport(NIOSSL)
  403. /// Create a `Configuration` with some pre-defined defaults. Prefer using
  404. /// `ClientConnection.secure(group:)` to build a connection secured with TLS or
  405. /// `ClientConnection.insecure(group:)` to build a plaintext connection.
  406. ///
  407. /// - Parameter target: The target to connect to.
  408. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  409. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  410. /// on debug builds.
  411. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`.
  412. /// - Parameter connectivityStateDelegateQueue: A `DispatchQueue` on which to call the
  413. /// `connectivityStateDelegate`.
  414. /// - Parameter tls: TLS configuration, defaulting to `nil`.
  415. /// - Parameter connectionBackoff: The connection backoff configuration to use.
  416. /// - Parameter connectionKeepalive: The keepalive configuration to use.
  417. /// - Parameter connectionIdleTimeout: The amount of time to wait before closing the connection, defaulting to 30 minutes.
  418. /// - Parameter callStartBehavior: The behavior used to determine when a call should start in
  419. /// relation to its underlying connection. Defaults to `waitsForConnectivity`.
  420. /// - Parameter httpTargetWindowSize: The HTTP/2 flow control target window size.
  421. /// - Parameter backgroundActivityLogger: A logger for background information (such as
  422. /// connectivity state). Defaults to a no-op logger.
  423. /// - Parameter debugChannelInitializer: A channel initializer will be called after gRPC has
  424. /// initialized the channel. Defaults to `nil`.
  425. @available(*, deprecated, renamed: "default(target:eventLoopGroup:)")
  426. @preconcurrency
  427. public init(
  428. target: ConnectionTarget,
  429. eventLoopGroup: EventLoopGroup,
  430. errorDelegate: ClientErrorDelegate? = LoggingClientErrorDelegate(),
  431. connectivityStateDelegate: ConnectivityStateDelegate? = nil,
  432. connectivityStateDelegateQueue: DispatchQueue? = nil,
  433. tls: Configuration.TLS? = nil,
  434. connectionBackoff: ConnectionBackoff? = ConnectionBackoff(),
  435. connectionKeepalive: ClientConnectionKeepalive = ClientConnectionKeepalive(),
  436. connectionIdleTimeout: TimeAmount = .minutes(30),
  437. callStartBehavior: CallStartBehavior = .waitsForConnectivity,
  438. httpTargetWindowSize: Int = 8 * 1024 * 1024,
  439. backgroundActivityLogger: Logger = Logger(
  440. label: "io.grpc",
  441. factory: { _ in SwiftLogNoOpLogHandler() }
  442. ),
  443. debugChannelInitializer: (@Sendable (Channel) -> EventLoopFuture<Void>)? = nil
  444. ) {
  445. self.target = target
  446. self.eventLoopGroup = eventLoopGroup
  447. self.errorDelegate = errorDelegate
  448. self.connectivityStateDelegate = connectivityStateDelegate
  449. self.connectivityStateDelegateQueue = connectivityStateDelegateQueue
  450. self.tlsConfiguration = tls.map { GRPCTLSConfiguration(transforming: $0) }
  451. self.connectionBackoff = connectionBackoff
  452. self.connectionKeepalive = connectionKeepalive
  453. self.connectionIdleTimeout = connectionIdleTimeout
  454. self.callStartBehavior = callStartBehavior
  455. self.httpTargetWindowSize = httpTargetWindowSize
  456. self.backgroundActivityLogger = backgroundActivityLogger
  457. self.debugChannelInitializer = debugChannelInitializer
  458. }
  459. #endif // canImport(NIOSSL)
  460. private init(eventLoopGroup: EventLoopGroup, target: ConnectionTarget) {
  461. self.eventLoopGroup = eventLoopGroup
  462. self.target = target
  463. }
  464. /// Make a new configuration using default values.
  465. ///
  466. /// - Parameters:
  467. /// - target: The target to connect to.
  468. /// - eventLoopGroup: The `EventLoopGroup` providing an `EventLoop` for the connection to
  469. /// run on.
  470. /// - Returns: A configuration with default values set.
  471. public static func `default`(
  472. target: ConnectionTarget,
  473. eventLoopGroup: EventLoopGroup
  474. ) -> Configuration {
  475. return .init(eventLoopGroup: eventLoopGroup, target: target)
  476. }
  477. }
  478. }
  479. // MARK: - Configuration helpers/extensions
  480. extension ClientBootstrapProtocol {
  481. /// Connect to the given connection target.
  482. ///
  483. /// - Parameter target: The target to connect to.
  484. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  485. switch target.wrapped {
  486. case let .hostAndPort(host, port):
  487. return self.connect(host: host, port: port)
  488. case let .unixDomainSocket(path):
  489. return self.connect(unixDomainSocketPath: path)
  490. case let .socketAddress(address):
  491. return self.connect(to: address)
  492. case let .connectedSocket(socket):
  493. return self.withConnectedSocket(socket)
  494. }
  495. }
  496. }
  497. #if canImport(NIOSSL)
  498. extension ChannelPipeline.SynchronousOperations {
  499. internal func configureNIOSSLForGRPCClient(
  500. sslContext: Result<NIOSSLContext, Error>,
  501. serverHostname: String?,
  502. customVerificationCallback: NIOSSLCustomVerificationCallback?,
  503. logger: Logger
  504. ) throws {
  505. let sslContext = try sslContext.get()
  506. let sslClientHandler: NIOSSLClientHandler
  507. if let customVerificationCallback = customVerificationCallback {
  508. sslClientHandler = try NIOSSLClientHandler(
  509. context: sslContext,
  510. serverHostname: serverHostname,
  511. customVerificationCallback: customVerificationCallback
  512. )
  513. } else {
  514. sslClientHandler = try NIOSSLClientHandler(
  515. context: sslContext,
  516. serverHostname: serverHostname
  517. )
  518. }
  519. try self.addHandler(sslClientHandler)
  520. try self.addHandler(TLSVerificationHandler(logger: logger))
  521. }
  522. }
  523. #endif // canImport(NIOSSL)
  524. extension ChannelPipeline.SynchronousOperations {
  525. internal func configureHTTP2AndGRPCHandlersForGRPCClient(
  526. channel: Channel,
  527. connectionManager: ConnectionManager,
  528. connectionKeepalive: ClientConnectionKeepalive,
  529. connectionIdleTimeout: TimeAmount,
  530. httpTargetWindowSize: Int,
  531. httpMaxFrameSize: Int,
  532. errorDelegate: ClientErrorDelegate?,
  533. logger: Logger
  534. ) throws {
  535. let initialSettings = [
  536. // As per the default settings for swift-nio-http2:
  537. HTTP2Setting(parameter: .maxHeaderListSize, value: HPACKDecoder.defaultMaxHeaderListSize),
  538. // We never expect (or allow) server initiated streams.
  539. HTTP2Setting(parameter: .maxConcurrentStreams, value: 0),
  540. // As configured by the user.
  541. HTTP2Setting(parameter: .maxFrameSize, value: httpMaxFrameSize),
  542. HTTP2Setting(parameter: .initialWindowSize, value: httpTargetWindowSize),
  543. ]
  544. // We could use 'configureHTTP2Pipeline' here, but we need to add a few handlers between the
  545. // two HTTP/2 handlers so we'll do it manually instead.
  546. try self.addHandler(NIOHTTP2Handler(mode: .client, initialSettings: initialSettings))
  547. let h2Multiplexer = HTTP2StreamMultiplexer(
  548. mode: .client,
  549. channel: channel,
  550. targetWindowSize: httpTargetWindowSize,
  551. inboundStreamInitializer: nil
  552. )
  553. // The multiplexer is passed through the idle handler so it is only reported on
  554. // successful channel activation - with happy eyeballs multiple pipelines can
  555. // be constructed so it's not safe to report just yet.
  556. try self.addHandler(GRPCIdleHandler(
  557. connectionManager: connectionManager,
  558. multiplexer: h2Multiplexer,
  559. idleTimeout: connectionIdleTimeout,
  560. keepalive: connectionKeepalive,
  561. logger: logger
  562. ))
  563. try self.addHandler(h2Multiplexer)
  564. try self.addHandler(DelegatingErrorHandler(logger: logger, delegate: errorDelegate))
  565. }
  566. }
  567. extension Channel {
  568. func configureGRPCClient(
  569. errorDelegate: ClientErrorDelegate?,
  570. logger: Logger
  571. ) -> EventLoopFuture<Void> {
  572. return self.configureHTTP2Pipeline(mode: .client, inboundStreamInitializer: nil).flatMap { _ in
  573. self.pipeline.addHandler(DelegatingErrorHandler(logger: logger, delegate: errorDelegate))
  574. }
  575. }
  576. }
  577. extension TimeAmount {
  578. /// Creates a new `TimeAmount` from the given time interval in seconds.
  579. ///
  580. /// - Parameter timeInterval: The amount of time in seconds
  581. static func seconds(timeInterval: TimeInterval) -> TimeAmount {
  582. return .nanoseconds(Int64(timeInterval * 1_000_000_000))
  583. }
  584. }
  585. extension String {
  586. var isIPAddress: Bool {
  587. // We need some scratch space to let inet_pton write into.
  588. var ipv4Addr = in_addr()
  589. var ipv6Addr = in6_addr()
  590. return self.withCString { ptr in
  591. inet_pton(AF_INET, ptr, &ipv4Addr) == 1 ||
  592. inet_pton(AF_INET6, ptr, &ipv6Addr) == 1
  593. }
  594. }
  595. }