ClientConnection.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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 amount of time to wait before closing the connection. The idle timeout will start only
  293. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start.
  294. ///
  295. /// If a connection becomes idle, starting a new RPC will automatically create a new connection.
  296. public var connectionIdleTimeout: TimeAmount
  297. /// The behavior used to determine when an RPC should start. That is, whether it should wait for
  298. /// an active connection or fail quickly if no connection is currently available.
  299. public var callStartBehavior: CallStartBehavior
  300. /// The HTTP/2 flow control target window size.
  301. public var httpTargetWindowSize: Int
  302. /// The HTTP protocol used for this connection.
  303. public var httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol {
  304. return self.tls == nil ? .http : .https
  305. }
  306. /// Create a `Configuration` with some pre-defined defaults. Prefer using
  307. /// `ClientConnection.secure(group:)` to build a connection secured with TLS or
  308. /// `ClientConnection.insecure(group:)` to build a plaintext connection.
  309. ///
  310. /// - Parameter target: The target to connect to.
  311. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  312. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  313. /// on debug builds.
  314. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`.
  315. /// - Parameter connectivityStateDelegateQueue: A `DispatchQueue` on which to call the
  316. /// `connectivityStateDelegate`.
  317. /// - Parameter tlsConfiguration: TLS configuration, defaulting to `nil`.
  318. /// - Parameter connectionBackoff: The connection backoff configuration to use.
  319. /// - Parameter callStartBehavior: The behavior used to determine when a call should start in
  320. /// relation to its underlying connection. Defaults to `waitsForConnectivity`.
  321. /// - Parameter messageEncoding: Message compression configuration, defaults to no compression.
  322. /// - Parameter targetWindowSize: The HTTP/2 flow control target window size.
  323. public init(
  324. target: ConnectionTarget,
  325. eventLoopGroup: EventLoopGroup,
  326. errorDelegate: ClientErrorDelegate? = LoggingClientErrorDelegate(),
  327. connectivityStateDelegate: ConnectivityStateDelegate? = nil,
  328. connectivityStateDelegateQueue: DispatchQueue? = nil,
  329. tls: Configuration.TLS? = nil,
  330. connectionBackoff: ConnectionBackoff? = ConnectionBackoff(),
  331. connectionIdleTimeout: TimeAmount = .minutes(5),
  332. callStartBehavior: CallStartBehavior = .waitsForConnectivity,
  333. httpTargetWindowSize: Int = 65535
  334. ) {
  335. self.target = target
  336. self.eventLoopGroup = eventLoopGroup
  337. self.errorDelegate = errorDelegate
  338. self.connectivityStateDelegate = connectivityStateDelegate
  339. self.connectivityStateDelegateQueue = connectivityStateDelegateQueue
  340. self.tls = tls
  341. self.connectionBackoff = connectionBackoff
  342. self.connectionIdleTimeout = connectionIdleTimeout
  343. self.callStartBehavior = callStartBehavior
  344. self.httpTargetWindowSize = httpTargetWindowSize
  345. }
  346. }
  347. }
  348. // MARK: - Configuration helpers/extensions
  349. extension ClientBootstrapProtocol {
  350. /// Connect to the given connection target.
  351. ///
  352. /// - Parameter target: The target to connect to.
  353. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  354. switch target.wrapped {
  355. case .hostAndPort(let host, let port):
  356. return self.connect(host: host, port: port)
  357. case .unixDomainSocket(let path):
  358. return self.connect(unixDomainSocketPath: path)
  359. case .socketAddress(let address):
  360. return self.connect(to: address)
  361. }
  362. }
  363. }
  364. extension Channel {
  365. /// Configure the channel with TLS.
  366. ///
  367. /// This function adds two handlers to the pipeline: the `NIOSSLClientHandler` to handle TLS, and
  368. /// the `TLSVerificationHandler` which verifies that a successful handshake was completed.
  369. ///
  370. /// - Parameter configuration: The configuration to configure the channel with.
  371. /// - Parameter serverHostname: The server hostname to use if the hostname should be verified.
  372. /// - Parameter errorDelegate: The error delegate to use for the TLS verification handler.
  373. func configureTLS(
  374. _ configuration: TLSConfiguration,
  375. serverHostname: String?,
  376. errorDelegate: ClientErrorDelegate?,
  377. logger: Logger
  378. ) -> EventLoopFuture<Void> {
  379. do {
  380. let sslClientHandler = try NIOSSLClientHandler(
  381. context: try NIOSSLContext(configuration: configuration),
  382. serverHostname: serverHostname
  383. )
  384. return self.pipeline.addHandlers(sslClientHandler, TLSVerificationHandler(logger: logger))
  385. } catch {
  386. return self.eventLoop.makeFailedFuture(error)
  387. }
  388. }
  389. func configureGRPCClient(
  390. httpTargetWindowSize: Int,
  391. tlsConfiguration: TLSConfiguration?,
  392. tlsServerHostname: String?,
  393. connectionManager: ConnectionManager,
  394. connectionIdleTimeout: TimeAmount,
  395. errorDelegate: ClientErrorDelegate?,
  396. logger: Logger
  397. ) -> EventLoopFuture<Void> {
  398. let tlsConfigured = tlsConfiguration.map {
  399. self.configureTLS($0, serverHostname: tlsServerHostname, errorDelegate: errorDelegate, logger: logger)
  400. }
  401. return (tlsConfigured ?? self.eventLoop.makeSucceededFuture(())).flatMap {
  402. self.configureHTTP2Pipeline(mode: .client, targetWindowSize: httpTargetWindowSize)
  403. }.flatMap { _ in
  404. return self.pipeline.handler(type: NIOHTTP2Handler.self).flatMap { http2Handler in
  405. self.pipeline.addHandler(
  406. GRPCIdleHandler(mode: .client(connectionManager), idleTimeout: connectionIdleTimeout),
  407. position: .after(http2Handler)
  408. )
  409. }.flatMap {
  410. let errorHandler = DelegatingErrorHandler(
  411. logger: logger,
  412. delegate: errorDelegate
  413. )
  414. return self.pipeline.addHandler(errorHandler)
  415. }
  416. }
  417. }
  418. func configureGRPCClient(
  419. errorDelegate: ClientErrorDelegate?,
  420. logger: Logger
  421. ) -> EventLoopFuture<Void> {
  422. return self.configureHTTP2Pipeline(mode: .client).flatMap { _ in
  423. self.pipeline.addHandler(DelegatingErrorHandler(logger: logger, delegate: errorDelegate))
  424. }
  425. }
  426. }
  427. extension TimeAmount {
  428. /// Creates a new `TimeAmount` from the given time interval in seconds.
  429. ///
  430. /// - Parameter timeInterval: The amount of time in seconds
  431. static func seconds(timeInterval: TimeInterval) -> TimeAmount {
  432. return .nanoseconds(Int64(timeInterval * 1_000_000_000))
  433. }
  434. }
  435. extension String {
  436. var isIPAddress: Bool {
  437. // We need some scratch space to let inet_pton write into.
  438. var ipv4Addr = in_addr()
  439. var ipv6Addr = in6_addr()
  440. return self.withCString { ptr in
  441. return inet_pton(AF_INET, ptr, &ipv4Addr) == 1 ||
  442. inet_pton(AF_INET6, ptr, &ipv6Addr) == 1
  443. }
  444. }
  445. }