ClientConnection.swift 27 KB

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