ClientConnection.swift 29 KB

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