ClientConnection.swift 28 KB

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