ClientConnection.swift 27 KB

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