ClientConnection.swift 28 KB

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