2
0

ClientConnection.swift 21 KB

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