ClientConnection.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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. }
  252. internal var wrapped: Wrapped
  253. private init(_ wrapped: Wrapped) {
  254. self.wrapped = wrapped
  255. }
  256. /// The host and port. The port is 443 by default.
  257. public static func host(_ host: String, port: Int = 443) -> ConnectionTarget {
  258. return ConnectionTarget(.hostAndPort(host, port))
  259. }
  260. /// The host and port.
  261. public static func hostAndPort(_ host: String, _ port: Int) -> ConnectionTarget {
  262. return ConnectionTarget(.hostAndPort(host, port))
  263. }
  264. /// The path of a Unix domain socket.
  265. public static func unixDomainSocket(_ path: String) -> ConnectionTarget {
  266. return ConnectionTarget(.unixDomainSocket(path))
  267. }
  268. /// A NIO socket address.
  269. public static func socketAddress(_ address: SocketAddress) -> ConnectionTarget {
  270. return ConnectionTarget(.socketAddress(address))
  271. }
  272. @usableFromInline
  273. var host: String {
  274. switch self.wrapped {
  275. case let .hostAndPort(host, _):
  276. return host
  277. case let .socketAddress(.v4(address)):
  278. return address.host
  279. case let .socketAddress(.v6(address)):
  280. return address.host
  281. case .unixDomainSocket, .socketAddress(.unixDomainSocket):
  282. return "localhost"
  283. }
  284. }
  285. }
  286. /// The connectivity behavior to use when starting an RPC.
  287. public struct CallStartBehavior: Hashable, GRPCSendable {
  288. internal enum Behavior: Hashable, GRPCSendable {
  289. case waitsForConnectivity
  290. case fastFailure
  291. }
  292. internal var wrapped: Behavior
  293. private init(_ wrapped: Behavior) {
  294. self.wrapped = wrapped
  295. }
  296. /// Waits for connectivity (that is, the 'ready' connectivity state) before attempting to start
  297. /// an RPC. Doing so may involve multiple connection attempts.
  298. ///
  299. /// This is the preferred, and default, behaviour.
  300. public static let waitsForConnectivity = CallStartBehavior(.waitsForConnectivity)
  301. /// The 'fast failure' behaviour is intended for cases where users would rather their RPC failed
  302. /// quickly rather than waiting for an active connection. The behaviour depends on the current
  303. /// connectivity state:
  304. ///
  305. /// - Idle: a connection attempt will be started and the RPC will fail if that attempt fails.
  306. /// - Connecting: a connection attempt is already in progress, the RPC will fail if that attempt
  307. /// fails.
  308. /// - Ready: a connection is already active: the RPC will be started using that connection.
  309. /// - Transient failure: the last connection or connection attempt failed and gRPC is waiting to
  310. /// connect again. The RPC will fail immediately.
  311. /// - Shutdown: the connection is shutdown, the RPC will fail immediately.
  312. public static let fastFailure = CallStartBehavior(.fastFailure)
  313. }
  314. extension ClientConnection {
  315. /// Configuration for a `ClientConnection`. Users should prefer using one of the
  316. /// `ClientConnection` builders: `ClientConnection.secure(_:)` or `ClientConnection.insecure(_:)`.
  317. public struct Configuration: GRPCSendable {
  318. /// The target to connect to.
  319. public var target: ConnectionTarget
  320. /// The event loop group to run the connection on.
  321. public var eventLoopGroup: EventLoopGroup
  322. /// An error delegate which is called when errors are caught. Provided delegates **must not
  323. /// maintain a strong reference to this `ClientConnection`**. Doing so will cause a retain
  324. /// cycle. Defaults to `LoggingClientErrorDelegate`.
  325. public var errorDelegate: ClientErrorDelegate? = LoggingClientErrorDelegate.shared
  326. /// A delegate which is called when the connectivity state is changed. Defaults to `nil`.
  327. public var connectivityStateDelegate: ConnectivityStateDelegate?
  328. /// The `DispatchQueue` on which to call the connectivity state delegate. If a delegate is
  329. /// provided but the queue is `nil` then one will be created by gRPC. Defaults to `nil`.
  330. public var connectivityStateDelegateQueue: DispatchQueue?
  331. #if canImport(NIOSSL)
  332. /// TLS configuration for this connection. `nil` if TLS is not desired.
  333. ///
  334. /// - Important: `tls` is deprecated; use `tlsConfiguration` or one of
  335. /// the `ClientConnection.withTLS` builder functions.
  336. @available(*, deprecated, renamed: "tlsConfiguration")
  337. public var tls: TLS? {
  338. get {
  339. return self.tlsConfiguration?.asDeprecatedClientConfiguration
  340. }
  341. set {
  342. self.tlsConfiguration = newValue.map { .init(transforming: $0) }
  343. }
  344. }
  345. #endif // canImport(NIOSSL)
  346. /// TLS configuration for this connection. `nil` if TLS is not desired.
  347. public var tlsConfiguration: GRPCTLSConfiguration?
  348. /// The connection backoff configuration. If no connection retrying is required then this should
  349. /// be `nil`.
  350. public var connectionBackoff: ConnectionBackoff? = ConnectionBackoff()
  351. /// The connection keepalive configuration.
  352. public var connectionKeepalive = ClientConnectionKeepalive()
  353. /// The amount of time to wait before closing the connection. The idle timeout will start only
  354. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start.
  355. ///
  356. /// If a connection becomes idle, starting a new RPC will automatically create a new connection.
  357. ///
  358. /// Defaults to 30 minutes.
  359. public var connectionIdleTimeout: TimeAmount = .minutes(30)
  360. /// The behavior used to determine when an RPC should start. That is, whether it should wait for
  361. /// an active connection or fail quickly if no connection is currently available.
  362. ///
  363. /// Defaults to `waitsForConnectivity`.
  364. public var callStartBehavior: CallStartBehavior = .waitsForConnectivity
  365. /// The HTTP/2 flow control target window size. Defaults to 8MB. Values are clamped between
  366. /// 1 and 2^31-1 inclusive.
  367. public var httpTargetWindowSize = 8 * 1024 * 1024 {
  368. didSet {
  369. self.httpTargetWindowSize = self.httpTargetWindowSize.clamped(to: 1 ... Int(Int32.max))
  370. }
  371. }
  372. /// The HTTP/2 max frame size. Defaults to 16384. Value is clamped between 2^14 and 2^24-1
  373. /// octets inclusive (the minimum and maximum allowable values - HTTP/2 RFC 7540 4.2).
  374. public var httpMaxFrameSize: Int = 16384 {
  375. didSet {
  376. self.httpMaxFrameSize = self.httpMaxFrameSize.clamped(to: 16384 ... 16_777_215)
  377. }
  378. }
  379. /// The HTTP protocol used for this connection.
  380. public var httpProtocol: HTTP2FramePayloadToHTTP1ClientCodec.HTTPProtocol {
  381. return self.tlsConfiguration == nil ? .http : .https
  382. }
  383. /// The maximum size in bytes of a message which may be received from a server. Defaults to 4MB.
  384. public var maximumReceiveMessageLength: Int = 4 * 1024 * 1024 {
  385. willSet {
  386. precondition(newValue >= 0, "maximumReceiveMessageLength must be positive")
  387. }
  388. }
  389. /// A logger for background information (such as connectivity state). A separate logger for
  390. /// requests may be provided in the `CallOptions`.
  391. ///
  392. /// Defaults to a no-op logger.
  393. public var backgroundActivityLogger = Logger(
  394. label: "io.grpc",
  395. factory: { _ in SwiftLogNoOpLogHandler() }
  396. )
  397. /// A channel initializer which will be run after gRPC has initialized each channel. This may be
  398. /// used to add additional handlers to the pipeline and is intended for debugging.
  399. ///
  400. /// - Warning: The initializer closure may be invoked *multiple times*.
  401. public var debugChannelInitializer: GRPCChannelInitializer?
  402. #if canImport(NIOSSL)
  403. /// Create a `Configuration` with some pre-defined defaults. Prefer using
  404. /// `ClientConnection.secure(group:)` to build a connection secured with TLS or
  405. /// `ClientConnection.insecure(group:)` to build a plaintext connection.
  406. ///
  407. /// - Parameter target: The target to connect to.
  408. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  409. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  410. /// on debug builds.
  411. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`.
  412. /// - Parameter connectivityStateDelegateQueue: A `DispatchQueue` on which to call the
  413. /// `connectivityStateDelegate`.
  414. /// - Parameter tls: TLS configuration, defaulting to `nil`.
  415. /// - Parameter connectionBackoff: The connection backoff configuration to use.
  416. /// - Parameter connectionKeepalive: The keepalive configuration to use.
  417. /// - Parameter connectionIdleTimeout: The amount of time to wait before closing the connection, defaulting to 30 minutes.
  418. /// - Parameter callStartBehavior: The behavior used to determine when a call should start in
  419. /// relation to its underlying connection. Defaults to `waitsForConnectivity`.
  420. /// - Parameter httpTargetWindowSize: The HTTP/2 flow control target window size.
  421. /// - Parameter backgroundActivityLogger: A logger for background information (such as
  422. /// connectivity state). Defaults to a no-op logger.
  423. /// - Parameter debugChannelInitializer: A channel initializer will be called after gRPC has
  424. /// initialized the channel. Defaults to `nil`.
  425. @available(*, deprecated, renamed: "default(target:eventLoopGroup:)")
  426. public init(
  427. target: ConnectionTarget,
  428. eventLoopGroup: EventLoopGroup,
  429. errorDelegate: ClientErrorDelegate? = LoggingClientErrorDelegate(),
  430. connectivityStateDelegate: ConnectivityStateDelegate? = nil,
  431. connectivityStateDelegateQueue: DispatchQueue? = nil,
  432. tls: Configuration.TLS? = nil,
  433. connectionBackoff: ConnectionBackoff? = ConnectionBackoff(),
  434. connectionKeepalive: ClientConnectionKeepalive = ClientConnectionKeepalive(),
  435. connectionIdleTimeout: TimeAmount = .minutes(30),
  436. callStartBehavior: CallStartBehavior = .waitsForConnectivity,
  437. httpTargetWindowSize: Int = 8 * 1024 * 1024,
  438. backgroundActivityLogger: Logger = Logger(
  439. label: "io.grpc",
  440. factory: { _ in SwiftLogNoOpLogHandler() }
  441. ),
  442. debugChannelInitializer: GRPCChannelInitializer? = nil
  443. ) {
  444. self.target = target
  445. self.eventLoopGroup = eventLoopGroup
  446. self.errorDelegate = errorDelegate
  447. self.connectivityStateDelegate = connectivityStateDelegate
  448. self.connectivityStateDelegateQueue = connectivityStateDelegateQueue
  449. self.tlsConfiguration = tls.map { GRPCTLSConfiguration(transforming: $0) }
  450. self.connectionBackoff = connectionBackoff
  451. self.connectionKeepalive = connectionKeepalive
  452. self.connectionIdleTimeout = connectionIdleTimeout
  453. self.callStartBehavior = callStartBehavior
  454. self.httpTargetWindowSize = httpTargetWindowSize
  455. self.backgroundActivityLogger = backgroundActivityLogger
  456. self.debugChannelInitializer = debugChannelInitializer
  457. }
  458. #endif // canImport(NIOSSL)
  459. private init(eventLoopGroup: EventLoopGroup, target: ConnectionTarget) {
  460. self.eventLoopGroup = eventLoopGroup
  461. self.target = target
  462. }
  463. /// Make a new configuration using default values.
  464. ///
  465. /// - Parameters:
  466. /// - target: The target to connect to.
  467. /// - eventLoopGroup: The `EventLoopGroup` providing an `EventLoop` for the connection to
  468. /// run on.
  469. /// - Returns: A configuration with default values set.
  470. public static func `default`(
  471. target: ConnectionTarget,
  472. eventLoopGroup: EventLoopGroup
  473. ) -> Configuration {
  474. return .init(eventLoopGroup: eventLoopGroup, target: target)
  475. }
  476. }
  477. }
  478. // MARK: - Configuration helpers/extensions
  479. extension ClientBootstrapProtocol {
  480. /// Connect to the given connection target.
  481. ///
  482. /// - Parameter target: The target to connect to.
  483. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  484. switch target.wrapped {
  485. case let .hostAndPort(host, port):
  486. return self.connect(host: host, port: port)
  487. case let .unixDomainSocket(path):
  488. return self.connect(unixDomainSocketPath: path)
  489. case let .socketAddress(address):
  490. return self.connect(to: address)
  491. }
  492. }
  493. }
  494. #if canImport(NIOSSL)
  495. extension ChannelPipeline.SynchronousOperations {
  496. internal func configureNIOSSLForGRPCClient(
  497. sslContext: Result<NIOSSLContext, Error>,
  498. serverHostname: String?,
  499. customVerificationCallback: NIOSSLCustomVerificationCallback?,
  500. logger: Logger
  501. ) throws {
  502. let sslContext = try sslContext.get()
  503. let sslClientHandler: NIOSSLClientHandler
  504. if let customVerificationCallback = customVerificationCallback {
  505. sslClientHandler = try NIOSSLClientHandler(
  506. context: sslContext,
  507. serverHostname: serverHostname,
  508. customVerificationCallback: customVerificationCallback
  509. )
  510. } else {
  511. sslClientHandler = try NIOSSLClientHandler(
  512. context: sslContext,
  513. serverHostname: serverHostname
  514. )
  515. }
  516. try self.addHandler(sslClientHandler)
  517. try self.addHandler(TLSVerificationHandler(logger: logger))
  518. }
  519. }
  520. #endif // canImport(NIOSSL)
  521. extension ChannelPipeline.SynchronousOperations {
  522. internal func configureHTTP2AndGRPCHandlersForGRPCClient(
  523. channel: Channel,
  524. connectionManager: ConnectionManager,
  525. connectionKeepalive: ClientConnectionKeepalive,
  526. connectionIdleTimeout: TimeAmount,
  527. httpTargetWindowSize: Int,
  528. httpMaxFrameSize: Int,
  529. errorDelegate: ClientErrorDelegate?,
  530. logger: Logger
  531. ) throws {
  532. let initialSettings = [
  533. // As per the default settings for swift-nio-http2:
  534. HTTP2Setting(parameter: .maxHeaderListSize, value: HPACKDecoder.defaultMaxHeaderListSize),
  535. // We never expect (or allow) server initiated streams.
  536. HTTP2Setting(parameter: .maxConcurrentStreams, value: 0),
  537. // As configured by the user.
  538. HTTP2Setting(parameter: .maxFrameSize, value: httpMaxFrameSize),
  539. HTTP2Setting(parameter: .initialWindowSize, value: httpTargetWindowSize),
  540. ]
  541. // We could use 'configureHTTP2Pipeline' here, but we need to add a few handlers between the
  542. // two HTTP/2 handlers so we'll do it manually instead.
  543. try self.addHandler(NIOHTTP2Handler(mode: .client, initialSettings: initialSettings))
  544. let h2Multiplexer = HTTP2StreamMultiplexer(
  545. mode: .client,
  546. channel: channel,
  547. targetWindowSize: httpTargetWindowSize,
  548. inboundStreamInitializer: nil
  549. )
  550. // The multiplexer is passed through the idle handler so it is only reported on
  551. // successful channel activation - with happy eyeballs multiple pipelines can
  552. // be constructed so it's not safe to report just yet.
  553. try self.addHandler(GRPCIdleHandler(
  554. connectionManager: connectionManager,
  555. multiplexer: h2Multiplexer,
  556. idleTimeout: connectionIdleTimeout,
  557. keepalive: connectionKeepalive,
  558. logger: logger
  559. ))
  560. try self.addHandler(h2Multiplexer)
  561. try self.addHandler(DelegatingErrorHandler(logger: logger, delegate: errorDelegate))
  562. }
  563. }
  564. extension Channel {
  565. func configureGRPCClient(
  566. errorDelegate: ClientErrorDelegate?,
  567. logger: Logger
  568. ) -> EventLoopFuture<Void> {
  569. return self.configureHTTP2Pipeline(mode: .client, inboundStreamInitializer: nil).flatMap { _ in
  570. self.pipeline.addHandler(DelegatingErrorHandler(logger: logger, delegate: errorDelegate))
  571. }
  572. }
  573. }
  574. extension TimeAmount {
  575. /// Creates a new `TimeAmount` from the given time interval in seconds.
  576. ///
  577. /// - Parameter timeInterval: The amount of time in seconds
  578. static func seconds(timeInterval: TimeInterval) -> TimeAmount {
  579. return .nanoseconds(Int64(timeInterval * 1_000_000_000))
  580. }
  581. }
  582. extension String {
  583. var isIPAddress: Bool {
  584. // We need some scratch space to let inet_pton write into.
  585. var ipv4Addr = in_addr()
  586. var ipv6Addr = in6_addr()
  587. return self.withCString { ptr in
  588. inet_pton(AF_INET, ptr, &ipv4Addr) == 1 ||
  589. inet_pton(AF_INET6, ptr, &ipv6Addr) == 1
  590. }
  591. }
  592. }