ClientConnection.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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 Foundation
  17. import NIO
  18. import NIOHTTP2
  19. import NIOSSL
  20. import NIOTLS
  21. import Logging
  22. /// Provides a single, managed connection to a server.
  23. ///
  24. /// The connection to the server is provided by a single channel which will attempt to reconnect
  25. /// to the server if the connection is dropped. This connection is guaranteed to always use the same
  26. /// event loop.
  27. ///
  28. /// The connection is initially setup with a handler to verify that TLS was established
  29. /// successfully (assuming TLS is being used).
  30. ///
  31. /// ┌──────────────────────────┐
  32. /// │ DelegatingErrorHandler │
  33. /// └──────────▲───────────────┘
  34. /// HTTP2Frame│
  35. /// ┌──────────┴───────────────┐
  36. /// │ SettingsObservingHandler │
  37. /// └──────────▲───────────────┘
  38. /// HTTP2Frame│
  39. /// │ ⠇ ⠇ ⠇ ⠇
  40. /// │ ┌┴─▼┐ ┌┴─▼┐
  41. /// │ │ | │ | HTTP/2 streams
  42. /// │ └▲─┬┘ └▲─┬┘
  43. /// │ │ │ │ │ HTTP2Frame
  44. /// ┌─┴────────────────┴─▼───┴─▼┐
  45. /// │ HTTP2StreamMultiplexer |
  46. /// └─▲───────────────────────┬─┘
  47. /// HTTP2Frame│ │HTTP2Frame
  48. /// ┌─┴───────────────────────▼─┐
  49. /// │ NIOHTTP2Handler │
  50. /// └─▲───────────────────────┬─┘
  51. /// ByteBuffer│ │ByteBuffer
  52. /// ┌─┴───────────────────────▼─┐
  53. /// │ TLSVerificationHandler │
  54. /// └─▲───────────────────────┬─┘
  55. /// ByteBuffer│ │ByteBuffer
  56. /// ┌─┴───────────────────────▼─┐
  57. /// │ NIOSSLHandler │
  58. /// └─▲───────────────────────┬─┘
  59. /// ByteBuffer│ │ByteBuffer
  60. /// │ ▼
  61. ///
  62. /// The `TLSVerificationHandler` observes the outcome of the SSL handshake and determines
  63. /// whether a `ClientConnection` should be returned to the user. In either eventuality, the
  64. /// handler removes itself from the pipeline once TLS has been verified. There is also a handler
  65. /// after the multiplexer for observing the initial settings frame, after which it determines that
  66. /// the connection state is `.ready` and removes itself from the channel. Finally there is a
  67. /// delegated error handler which uses the error delegate associated with this connection
  68. /// (see `DelegatingErrorHandler`).
  69. ///
  70. /// See `BaseClientCall` for a description of the pipelines associated with each HTTP/2 stream.
  71. public class ClientConnection {
  72. private let connectionManager: ConnectionManager
  73. private func getChannel() -> EventLoopFuture<Channel> {
  74. switch self.configuration.callStartBehavior.wrapped {
  75. case .waitsForConnectivity:
  76. return self.connectionManager.getChannel()
  77. case .fastFailure:
  78. return self.connectionManager.getOptimisticChannel()
  79. }
  80. }
  81. /// HTTP multiplexer from the `channel` handling gRPC calls.
  82. internal var multiplexer: EventLoopFuture<HTTP2StreamMultiplexer> {
  83. return self.getChannel().flatMap {
  84. $0.pipeline.handler(type: HTTP2StreamMultiplexer.self)
  85. }
  86. }
  87. /// The configuration for this client.
  88. internal let configuration: Configuration
  89. internal let scheme: String
  90. internal let authority: String
  91. /// A monitor for the connectivity state.
  92. public var connectivity: ConnectivityStateMonitor {
  93. return self.connectionManager.monitor
  94. }
  95. /// The `EventLoop` this connection is using.
  96. public var eventLoop: EventLoop {
  97. return self.connectionManager.eventLoop
  98. }
  99. /// Creates a new connection from the given configuration. Prefer using
  100. /// `ClientConnection.secure(group:)` to build a connection secured with TLS or
  101. /// `ClientConnection.insecure(group:)` to build a plaintext connection.
  102. ///
  103. /// - Important: Users should prefer using `ClientConnection.secure(group:)` to build a connection
  104. /// with TLS, or `ClientConnection.insecure(group:)` to build a connection without TLS.
  105. public init(configuration: Configuration) {
  106. self.configuration = configuration
  107. self.scheme = configuration.tls == nil ? "http" : "https"
  108. self.authority = configuration.target.host
  109. self.connectionManager = ConnectionManager(
  110. configuration: configuration,
  111. logger: Logger(subsystem: .clientChannel)
  112. )
  113. }
  114. /// Closes the connection to the server.
  115. public func close() -> EventLoopFuture<Void> {
  116. return self.connectionManager.shutdown()
  117. }
  118. private func loggerWithRequestID(_ requestID: String) -> Logger {
  119. var logger = self.connectionManager.logger
  120. logger[metadataKey: MetadataKey.requestID] = "\(requestID)"
  121. return logger
  122. }
  123. private func makeRequestHead(path: String, options: CallOptions, requestID: String) -> _GRPCRequestHead {
  124. return _GRPCRequestHead(
  125. scheme: self.scheme,
  126. path: path,
  127. host: self.authority,
  128. requestID: requestID,
  129. options: options
  130. )
  131. }
  132. }
  133. // Note: documentation is inherited.
  134. extension ClientConnection: GRPCChannel {
  135. public func makeUnaryCall<Request: GRPCPayload, Response: GRPCPayload>(
  136. path: String,
  137. request: Request,
  138. callOptions: CallOptions
  139. ) -> UnaryCall<Request, Response> where Request : GRPCPayload, Response : GRPCPayload {
  140. let requestID = callOptions.requestIDProvider.requestID()
  141. let logger = self.loggerWithRequestID(requestID)
  142. logger.debug("starting rpc", metadata: ["path": "\(path)"])
  143. let call = UnaryCall<Request, Response>.makeOnHTTP2Stream(
  144. multiplexer: self.multiplexer,
  145. callOptions: callOptions,
  146. errorDelegate: self.configuration.errorDelegate,
  147. logger: logger
  148. )
  149. call.send(self.makeRequestHead(path: path, options: callOptions, requestID: requestID), request: request)
  150. return call
  151. }
  152. public func makeClientStreamingCall<Request: GRPCPayload, Response: GRPCPayload>(
  153. path: String,
  154. callOptions: CallOptions
  155. ) -> ClientStreamingCall<Request, Response> {
  156. let requestID = callOptions.requestIDProvider.requestID()
  157. let logger = self.loggerWithRequestID(requestID)
  158. logger.debug("starting rpc", metadata: ["path": "\(path)"])
  159. let call = ClientStreamingCall<Request, Response>.makeOnHTTP2Stream(
  160. multiplexer: self.multiplexer,
  161. callOptions: callOptions,
  162. errorDelegate: self.configuration.errorDelegate,
  163. logger: logger
  164. )
  165. call.sendHead(self.makeRequestHead(path: path, options: callOptions, requestID: requestID))
  166. return call
  167. }
  168. public func makeServerStreamingCall<Request: GRPCPayload, Response: GRPCPayload>(
  169. path: String,
  170. request: Request,
  171. callOptions: CallOptions,
  172. handler: @escaping (Response) -> Void
  173. ) -> ServerStreamingCall<Request, Response> {
  174. let requestID = callOptions.requestIDProvider.requestID()
  175. let logger = self.loggerWithRequestID(requestID)
  176. logger.debug("starting rpc", metadata: ["path": "\(path)"])
  177. let call = ServerStreamingCall<Request, Response>.makeOnHTTP2Stream(
  178. multiplexer: multiplexer,
  179. callOptions: callOptions,
  180. errorDelegate: self.configuration.errorDelegate,
  181. logger: logger,
  182. responseHandler: handler
  183. )
  184. call.send(self.makeRequestHead(path: path, options: callOptions, requestID: requestID), request: request)
  185. return call
  186. }
  187. public func makeBidirectionalStreamingCall<Request: GRPCPayload, Response: GRPCPayload>(
  188. path: String,
  189. callOptions: CallOptions,
  190. handler: @escaping (Response) -> Void
  191. ) -> BidirectionalStreamingCall<Request, Response> {
  192. let requestID = callOptions.requestIDProvider.requestID()
  193. let logger = self.loggerWithRequestID(requestID)
  194. logger.debug("starting rpc", metadata: ["path": "\(path)"])
  195. let call = BidirectionalStreamingCall<Request, Response>.makeOnHTTP2Stream(
  196. multiplexer: multiplexer,
  197. callOptions: callOptions,
  198. errorDelegate: self.configuration.errorDelegate,
  199. logger: logger,
  200. responseHandler: handler
  201. )
  202. call.sendHead(self.makeRequestHead(path: path, options: callOptions, requestID: requestID))
  203. return call
  204. }
  205. }
  206. // MARK: - Configuration structures
  207. /// A target to connect to.
  208. public struct ConnectionTarget {
  209. internal enum Wrapped {
  210. case hostAndPort(String, Int)
  211. case unixDomainSocket(String)
  212. case socketAddress(SocketAddress)
  213. }
  214. internal var wrapped: Wrapped
  215. private init(_ wrapped: Wrapped) {
  216. self.wrapped = wrapped
  217. }
  218. /// The host and port.
  219. public static func hostAndPort(_ host: String, _ port: Int) -> ConnectionTarget {
  220. return ConnectionTarget(.hostAndPort(host, port))
  221. }
  222. /// The path of a Unix domain socket.
  223. public static func unixDomainSocket(_ path: String) -> ConnectionTarget {
  224. return ConnectionTarget(.unixDomainSocket(path))
  225. }
  226. /// A NIO socket address.
  227. public static func socketAddress(_ address: SocketAddress) -> ConnectionTarget {
  228. return ConnectionTarget(.socketAddress(address))
  229. }
  230. var host: String {
  231. switch self.wrapped {
  232. case .hostAndPort(let host, _):
  233. return host
  234. case .socketAddress(.v4(let address)):
  235. return address.host
  236. case .socketAddress(.v6(let address)):
  237. return address.host
  238. case .unixDomainSocket, .socketAddress(.unixDomainSocket):
  239. return "localhost"
  240. }
  241. }
  242. }
  243. /// The connectivity behavior to use when starting an RPC.
  244. public struct CallStartBehavior: Hashable {
  245. internal enum Behavior: Hashable {
  246. case waitsForConnectivity
  247. case fastFailure
  248. }
  249. internal var wrapped: Behavior
  250. private init(_ wrapped: Behavior) {
  251. self.wrapped = wrapped
  252. }
  253. /// Waits for connectivity (that is, the 'ready' connectivity state) before attempting to start
  254. /// an RPC. Doing so may involve multiple connection attempts.
  255. ///
  256. /// This is the preferred, and default, behaviour.
  257. public static let waitsForConnectivity = CallStartBehavior(.waitsForConnectivity)
  258. /// The 'fast failure' behaviour is intended for cases where users would rather their RPC failed
  259. /// quickly rather than waiting for an active connection. The behaviour depends on the current
  260. /// connectivity state:
  261. ///
  262. /// - Idle: a connection attempt will be started and the RPC will fail if that attempt fails.
  263. /// - Connecting: a connection attempt is already in progress, the RPC will fail if that attempt
  264. /// fails.
  265. /// - Ready: a connection is already active: the RPC will be started using that connection.
  266. /// - Transient failure: the last connection or connection attempt failed and gRPC is waiting to
  267. /// connect again. The RPC will fail immediately.
  268. /// - Shutdown: the connection is shutdown, the RPC will fail immediately.
  269. public static let fastFailure = CallStartBehavior(.fastFailure)
  270. }
  271. extension ClientConnection {
  272. /// The configuration for a connection.
  273. public struct Configuration {
  274. /// The target to connect to.
  275. public var target: ConnectionTarget
  276. /// The event loop group to run the connection on.
  277. public var eventLoopGroup: EventLoopGroup
  278. /// An error delegate which is called when errors are caught. Provided delegates **must not
  279. /// maintain a strong reference to this `ClientConnection`**. Doing so will cause a retain
  280. /// cycle.
  281. public var errorDelegate: ClientErrorDelegate?
  282. /// A delegate which is called when the connectivity state is changed.
  283. public var connectivityStateDelegate: ConnectivityStateDelegate?
  284. /// The `DispatchQueue` on which to call the connectivity state delegate. If a delegate is
  285. /// provided but the queue is `nil` then one will be created by gRPC.
  286. public var connectivityStateDelegateQueue: DispatchQueue?
  287. /// TLS configuration for this connection. `nil` if TLS is not desired.
  288. public var tls: TLS?
  289. /// The connection backoff configuration. If no connection retrying is required then this should
  290. /// be `nil`.
  291. public var connectionBackoff: ConnectionBackoff?
  292. /// The connection keepalive configuration.
  293. public var connectionKeepalive: ClientConnectionKeepalive
  294. /// The amount of time to wait before closing the connection. The idle timeout will start only
  295. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start.
  296. ///
  297. /// If a connection becomes idle, starting a new RPC will automatically create a new connection.
  298. public var connectionIdleTimeout: TimeAmount
  299. /// The behavior used to determine when an RPC should start. That is, whether it should wait for
  300. /// an active connection or fail quickly if no connection is currently available.
  301. public var callStartBehavior: CallStartBehavior
  302. /// The HTTP/2 flow control target window size.
  303. public var httpTargetWindowSize: Int
  304. /// The HTTP protocol used for this connection.
  305. public var httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol {
  306. return self.tls == nil ? .http : .https
  307. }
  308. /// Create a `Configuration` with some pre-defined defaults. Prefer using
  309. /// `ClientConnection.secure(group:)` to build a connection secured with TLS or
  310. /// `ClientConnection.insecure(group:)` to build a plaintext connection.
  311. ///
  312. /// - Parameter target: The target to connect to.
  313. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  314. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  315. /// on debug builds.
  316. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`.
  317. /// - Parameter connectivityStateDelegateQueue: A `DispatchQueue` on which to call the
  318. /// `connectivityStateDelegate`.
  319. /// - Parameter tls: TLS configuration, defaulting to `nil`.
  320. /// - Parameter connectionBackoff: The connection backoff configuration to use.
  321. /// - Parameter connectionKeepalive: The keepalive configuration to use.
  322. /// - Parameter connectionIdleTimeout: The amount of time to wait before closing the connection, defaulting to 5 minutes.
  323. /// - Parameter callStartBehavior: The behavior used to determine when a call should start in
  324. /// relation to its underlying connection. Defaults to `waitsForConnectivity`.
  325. /// - Parameter httpTargetWindowSize: The HTTP/2 flow control target window size.
  326. public init(
  327. target: ConnectionTarget,
  328. eventLoopGroup: EventLoopGroup,
  329. errorDelegate: ClientErrorDelegate? = LoggingClientErrorDelegate(),
  330. connectivityStateDelegate: ConnectivityStateDelegate? = nil,
  331. connectivityStateDelegateQueue: DispatchQueue? = nil,
  332. tls: Configuration.TLS? = nil,
  333. connectionBackoff: ConnectionBackoff? = ConnectionBackoff(),
  334. connectionKeepalive: ClientConnectionKeepalive = ClientConnectionKeepalive(),
  335. connectionIdleTimeout: TimeAmount = .minutes(5),
  336. callStartBehavior: CallStartBehavior = .waitsForConnectivity,
  337. httpTargetWindowSize: Int = 65535
  338. ) {
  339. self.target = target
  340. self.eventLoopGroup = eventLoopGroup
  341. self.errorDelegate = errorDelegate
  342. self.connectivityStateDelegate = connectivityStateDelegate
  343. self.connectivityStateDelegateQueue = connectivityStateDelegateQueue
  344. self.tls = tls
  345. self.connectionBackoff = connectionBackoff
  346. self.connectionKeepalive = connectionKeepalive
  347. self.connectionIdleTimeout = connectionIdleTimeout
  348. self.callStartBehavior = callStartBehavior
  349. self.httpTargetWindowSize = httpTargetWindowSize
  350. }
  351. }
  352. }
  353. // MARK: - Configuration helpers/extensions
  354. extension ClientBootstrapProtocol {
  355. /// Connect to the given connection target.
  356. ///
  357. /// - Parameter target: The target to connect to.
  358. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  359. switch target.wrapped {
  360. case .hostAndPort(let host, let port):
  361. return self.connect(host: host, port: port)
  362. case .unixDomainSocket(let path):
  363. return self.connect(unixDomainSocketPath: path)
  364. case .socketAddress(let address):
  365. return self.connect(to: address)
  366. }
  367. }
  368. }
  369. extension Channel {
  370. /// Configure the channel with TLS.
  371. ///
  372. /// This function adds two handlers to the pipeline: the `NIOSSLClientHandler` to handle TLS, and
  373. /// the `TLSVerificationHandler` which verifies that a successful handshake was completed.
  374. ///
  375. /// - Parameter configuration: The configuration to configure the channel with.
  376. /// - Parameter serverHostname: The server hostname to use if the hostname should be verified.
  377. /// - Parameter errorDelegate: The error delegate to use for the TLS verification handler.
  378. func configureTLS(
  379. _ configuration: TLSConfiguration,
  380. serverHostname: String?,
  381. errorDelegate: ClientErrorDelegate?,
  382. logger: Logger
  383. ) -> EventLoopFuture<Void> {
  384. do {
  385. let sslClientHandler = try NIOSSLClientHandler(
  386. context: try NIOSSLContext(configuration: configuration),
  387. serverHostname: serverHostname
  388. )
  389. return self.pipeline.addHandlers(sslClientHandler, TLSVerificationHandler(logger: logger))
  390. } catch {
  391. return self.eventLoop.makeFailedFuture(error)
  392. }
  393. }
  394. func configureGRPCClient(
  395. httpTargetWindowSize: Int,
  396. tlsConfiguration: TLSConfiguration?,
  397. tlsServerHostname: String?,
  398. connectionManager: ConnectionManager,
  399. connectionKeepalive: ClientConnectionKeepalive,
  400. connectionIdleTimeout: TimeAmount,
  401. errorDelegate: ClientErrorDelegate?,
  402. logger: Logger
  403. ) -> EventLoopFuture<Void> {
  404. let tlsConfigured = tlsConfiguration.map {
  405. self.configureTLS($0, serverHostname: tlsServerHostname, errorDelegate: errorDelegate, logger: logger)
  406. }
  407. return (tlsConfigured ?? self.eventLoop.makeSucceededFuture(())).flatMap {
  408. self.configureHTTP2Pipeline(mode: .client, targetWindowSize: httpTargetWindowSize)
  409. }.flatMap { _ in
  410. return self.pipeline.handler(type: NIOHTTP2Handler.self).flatMap { http2Handler in
  411. self.pipeline.addHandlers([
  412. GRPCClientKeepaliveHandler(configuration: connectionKeepalive),
  413. GRPCIdleHandler(mode: .client(connectionManager), idleTimeout: connectionIdleTimeout)],
  414. position: .after(http2Handler)
  415. )
  416. }.flatMap {
  417. let errorHandler = DelegatingErrorHandler(
  418. logger: logger,
  419. delegate: errorDelegate
  420. )
  421. return self.pipeline.addHandler(errorHandler)
  422. }
  423. }
  424. }
  425. func configureGRPCClient(
  426. errorDelegate: ClientErrorDelegate?,
  427. logger: Logger
  428. ) -> EventLoopFuture<Void> {
  429. return self.configureHTTP2Pipeline(mode: .client).flatMap { _ in
  430. self.pipeline.addHandler(DelegatingErrorHandler(logger: logger, delegate: errorDelegate))
  431. }
  432. }
  433. }
  434. extension TimeAmount {
  435. /// Creates a new `TimeAmount` from the given time interval in seconds.
  436. ///
  437. /// - Parameter timeInterval: The amount of time in seconds
  438. static func seconds(timeInterval: TimeInterval) -> TimeAmount {
  439. return .nanoseconds(Int64(timeInterval * 1_000_000_000))
  440. }
  441. }
  442. extension String {
  443. var isIPAddress: Bool {
  444. // We need some scratch space to let inet_pton write into.
  445. var ipv4Addr = in_addr()
  446. var ipv6Addr = in6_addr()
  447. return self.withCString { ptr in
  448. return inet_pton(AF_INET, ptr, &ipv4Addr) == 1 ||
  449. inet_pton(AF_INET6, ptr, &ipv6Addr) == 1
  450. }
  451. }
  452. }