ClientConnection.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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. /// HTTP multiplexer from the underlying channel handling gRPC calls.
  76. internal func getMultiplexer() -> EventLoopFuture<HTTP2StreamMultiplexer> {
  77. return self.connectionManager.getHTTP2Multiplexer()
  78. }
  79. /// The configuration for this client.
  80. internal let configuration: Configuration
  81. internal let scheme: String
  82. internal let authority: String
  83. /// A monitor for the connectivity state.
  84. public var connectivity: ConnectivityStateMonitor {
  85. return self.connectionManager.monitor
  86. }
  87. /// The `EventLoop` this connection is using.
  88. public var eventLoop: EventLoop {
  89. return self.connectionManager.eventLoop
  90. }
  91. /// Creates a new connection from the given configuration. Prefer using
  92. /// `ClientConnection.secure(group:)` to build a connection secured with TLS or
  93. /// `ClientConnection.insecure(group:)` to build a plaintext connection.
  94. ///
  95. /// - Important: Users should prefer using `ClientConnection.secure(group:)` to build a connection
  96. /// with TLS, or `ClientConnection.insecure(group:)` to build a connection without TLS.
  97. public init(configuration: Configuration) {
  98. self.configuration = configuration
  99. self.scheme = configuration.tls == nil ? "http" : "https"
  100. self.authority = configuration.tls?.hostnameOverride ?? configuration.target.host
  101. self.connectionManager = ConnectionManager(
  102. configuration: configuration,
  103. logger: configuration.backgroundActivityLogger
  104. )
  105. }
  106. /// Closes the connection to the server.
  107. public func close() -> EventLoopFuture<Void> {
  108. return self.connectionManager.shutdown()
  109. }
  110. /// Populates the logger in `options` and appends a request ID header to the metadata, if
  111. /// configured.
  112. /// - Parameter options: The options containing the logger to populate.
  113. private func populateLogger(in options: inout CallOptions) {
  114. // Get connection metadata.
  115. self.connectionManager.appendMetadata(to: &options.logger)
  116. // Attach a request ID.
  117. let requestID = options.requestIDProvider.requestID()
  118. if let requestID = requestID {
  119. options.logger[metadataKey: MetadataKey.requestID] = "\(requestID)"
  120. // Add the request ID header too.
  121. if let requestIDHeader = options.requestIDHeader {
  122. options.customMetadata.add(name: requestIDHeader, value: requestID)
  123. }
  124. }
  125. }
  126. }
  127. extension ClientConnection: GRPCChannel {
  128. public func makeCall<Request: Message, Response: Message>(
  129. path: String,
  130. type: GRPCCallType,
  131. callOptions: CallOptions,
  132. interceptors: [ClientInterceptor<Request, Response>]
  133. ) -> Call<Request, Response> {
  134. var options = callOptions
  135. self.populateLogger(in: &options)
  136. let multiplexer = self.getMultiplexer()
  137. return Call(
  138. path: path,
  139. type: type,
  140. eventLoop: multiplexer.eventLoop,
  141. options: options,
  142. interceptors: interceptors,
  143. transportFactory: .http2(
  144. multiplexer: multiplexer,
  145. authority: self.authority,
  146. scheme: self.scheme,
  147. errorDelegate: self.configuration.errorDelegate
  148. )
  149. )
  150. }
  151. public func makeCall<Request: GRPCPayload, Response: GRPCPayload>(
  152. path: String,
  153. type: GRPCCallType,
  154. callOptions: CallOptions,
  155. interceptors: [ClientInterceptor<Request, Response>]
  156. ) -> Call<Request, Response> {
  157. var options = callOptions
  158. self.populateLogger(in: &options)
  159. let multiplexer = self.getMultiplexer()
  160. return Call(
  161. path: path,
  162. type: type,
  163. eventLoop: multiplexer.eventLoop,
  164. options: options,
  165. interceptors: interceptors,
  166. transportFactory: .http2(
  167. multiplexer: multiplexer,
  168. authority: self.authority,
  169. scheme: self.scheme,
  170. errorDelegate: self.configuration.errorDelegate
  171. )
  172. )
  173. }
  174. }
  175. // MARK: - Configuration structures
  176. /// A target to connect to.
  177. public struct ConnectionTarget {
  178. internal enum Wrapped {
  179. case hostAndPort(String, Int)
  180. case unixDomainSocket(String)
  181. case socketAddress(SocketAddress)
  182. }
  183. internal var wrapped: Wrapped
  184. private init(_ wrapped: Wrapped) {
  185. self.wrapped = wrapped
  186. }
  187. /// The host and port.
  188. public static func hostAndPort(_ host: String, _ port: Int) -> ConnectionTarget {
  189. return ConnectionTarget(.hostAndPort(host, port))
  190. }
  191. /// The path of a Unix domain socket.
  192. public static func unixDomainSocket(_ path: String) -> ConnectionTarget {
  193. return ConnectionTarget(.unixDomainSocket(path))
  194. }
  195. /// A NIO socket address.
  196. public static func socketAddress(_ address: SocketAddress) -> ConnectionTarget {
  197. return ConnectionTarget(.socketAddress(address))
  198. }
  199. var host: String {
  200. switch self.wrapped {
  201. case let .hostAndPort(host, _):
  202. return host
  203. case let .socketAddress(.v4(address)):
  204. return address.host
  205. case let .socketAddress(.v6(address)):
  206. return address.host
  207. case .unixDomainSocket, .socketAddress(.unixDomainSocket):
  208. return "localhost"
  209. }
  210. }
  211. }
  212. /// The connectivity behavior to use when starting an RPC.
  213. public struct CallStartBehavior: Hashable {
  214. internal enum Behavior: Hashable {
  215. case waitsForConnectivity
  216. case fastFailure
  217. }
  218. internal var wrapped: Behavior
  219. private init(_ wrapped: Behavior) {
  220. self.wrapped = wrapped
  221. }
  222. /// Waits for connectivity (that is, the 'ready' connectivity state) before attempting to start
  223. /// an RPC. Doing so may involve multiple connection attempts.
  224. ///
  225. /// This is the preferred, and default, behaviour.
  226. public static let waitsForConnectivity = CallStartBehavior(.waitsForConnectivity)
  227. /// The 'fast failure' behaviour is intended for cases where users would rather their RPC failed
  228. /// quickly rather than waiting for an active connection. The behaviour depends on the current
  229. /// connectivity state:
  230. ///
  231. /// - Idle: a connection attempt will be started and the RPC will fail if that attempt fails.
  232. /// - Connecting: a connection attempt is already in progress, the RPC will fail if that attempt
  233. /// fails.
  234. /// - Ready: a connection is already active: the RPC will be started using that connection.
  235. /// - Transient failure: the last connection or connection attempt failed and gRPC is waiting to
  236. /// connect again. The RPC will fail immediately.
  237. /// - Shutdown: the connection is shutdown, the RPC will fail immediately.
  238. public static let fastFailure = CallStartBehavior(.fastFailure)
  239. }
  240. extension ClientConnection {
  241. /// The configuration for a connection.
  242. public struct Configuration {
  243. /// The target to connect to.
  244. public var target: ConnectionTarget
  245. /// The event loop group to run the connection on.
  246. public var eventLoopGroup: EventLoopGroup
  247. /// An error delegate which is called when errors are caught. Provided delegates **must not
  248. /// maintain a strong reference to this `ClientConnection`**. Doing so will cause a retain
  249. /// cycle.
  250. public var errorDelegate: ClientErrorDelegate?
  251. /// A delegate which is called when the connectivity state is changed.
  252. public var connectivityStateDelegate: ConnectivityStateDelegate?
  253. /// The `DispatchQueue` on which to call the connectivity state delegate. If a delegate is
  254. /// provided but the queue is `nil` then one will be created by gRPC.
  255. public var connectivityStateDelegateQueue: DispatchQueue?
  256. /// TLS configuration for this connection. `nil` if TLS is not desired.
  257. public var tls: TLS?
  258. /// The connection backoff configuration. If no connection retrying is required then this should
  259. /// be `nil`.
  260. public var connectionBackoff: ConnectionBackoff?
  261. /// The connection keepalive configuration.
  262. public var connectionKeepalive: ClientConnectionKeepalive
  263. /// The amount of time to wait before closing the connection. The idle timeout will start only
  264. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start.
  265. ///
  266. /// If a connection becomes idle, starting a new RPC will automatically create a new connection.
  267. public var connectionIdleTimeout: TimeAmount
  268. /// The behavior used to determine when an RPC should start. That is, whether it should wait for
  269. /// an active connection or fail quickly if no connection is currently available.
  270. public var callStartBehavior: CallStartBehavior
  271. /// The HTTP/2 flow control target window size.
  272. public var httpTargetWindowSize: Int
  273. /// The HTTP protocol used for this connection.
  274. public var httpProtocol: HTTP2FramePayloadToHTTP1ClientCodec.HTTPProtocol {
  275. return self.tls == nil ? .http : .https
  276. }
  277. /// A logger for background information (such as connectivity state). A separate logger for
  278. /// requests may be provided in the `CallOptions`.
  279. ///
  280. /// Defaults to a no-op logger.
  281. public var backgroundActivityLogger: Logger
  282. /// A channel initializer which will be run after gRPC has initialized each channel. This may be
  283. /// used to add additional handlers to the pipeline and is intended for debugging.
  284. ///
  285. /// - Warning: The initializer closure may be invoked *multiple times*.
  286. public var debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?
  287. /// Create a `Configuration` with some pre-defined defaults. Prefer using
  288. /// `ClientConnection.secure(group:)` to build a connection secured with TLS or
  289. /// `ClientConnection.insecure(group:)` to build a plaintext connection.
  290. ///
  291. /// - Parameter target: The target to connect to.
  292. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  293. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  294. /// on debug builds.
  295. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`.
  296. /// - Parameter connectivityStateDelegateQueue: A `DispatchQueue` on which to call the
  297. /// `connectivityStateDelegate`.
  298. /// - Parameter tls: TLS configuration, defaulting to `nil`.
  299. /// - Parameter connectionBackoff: The connection backoff configuration to use.
  300. /// - Parameter connectionKeepalive: The keepalive configuration to use.
  301. /// - Parameter connectionIdleTimeout: The amount of time to wait before closing the connection, defaulting to 30 minutes.
  302. /// - Parameter callStartBehavior: The behavior used to determine when a call should start in
  303. /// relation to its underlying connection. Defaults to `waitsForConnectivity`.
  304. /// - Parameter httpTargetWindowSize: The HTTP/2 flow control target window size.
  305. /// - Parameter backgroundActivityLogger: A logger for background information (such as
  306. /// connectivity state). Defaults to a no-op logger.
  307. /// - Parameter debugChannelInitializer: A channel initializer will be called after gRPC has
  308. /// initialized the channel. Defaults to `nil`.
  309. public init(
  310. target: ConnectionTarget,
  311. eventLoopGroup: EventLoopGroup,
  312. errorDelegate: ClientErrorDelegate? = LoggingClientErrorDelegate(),
  313. connectivityStateDelegate: ConnectivityStateDelegate? = nil,
  314. connectivityStateDelegateQueue: DispatchQueue? = nil,
  315. tls: Configuration.TLS? = nil,
  316. connectionBackoff: ConnectionBackoff? = ConnectionBackoff(),
  317. connectionKeepalive: ClientConnectionKeepalive = ClientConnectionKeepalive(),
  318. connectionIdleTimeout: TimeAmount = .minutes(30),
  319. callStartBehavior: CallStartBehavior = .waitsForConnectivity,
  320. httpTargetWindowSize: Int = 65535,
  321. backgroundActivityLogger: Logger = Logger(
  322. label: "io.grpc",
  323. factory: { _ in SwiftLogNoOpLogHandler() }
  324. ),
  325. debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)? = nil
  326. ) {
  327. self.target = target
  328. self.eventLoopGroup = eventLoopGroup
  329. self.errorDelegate = errorDelegate
  330. self.connectivityStateDelegate = connectivityStateDelegate
  331. self.connectivityStateDelegateQueue = connectivityStateDelegateQueue
  332. self.tls = tls
  333. self.connectionBackoff = connectionBackoff
  334. self.connectionKeepalive = connectionKeepalive
  335. self.connectionIdleTimeout = connectionIdleTimeout
  336. self.callStartBehavior = callStartBehavior
  337. self.httpTargetWindowSize = httpTargetWindowSize
  338. self.backgroundActivityLogger = backgroundActivityLogger
  339. self.debugChannelInitializer = debugChannelInitializer
  340. }
  341. }
  342. }
  343. // MARK: - Configuration helpers/extensions
  344. extension ClientBootstrapProtocol {
  345. /// Connect to the given connection target.
  346. ///
  347. /// - Parameter target: The target to connect to.
  348. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  349. switch target.wrapped {
  350. case let .hostAndPort(host, port):
  351. return self.connect(host: host, port: port)
  352. case let .unixDomainSocket(path):
  353. return self.connect(unixDomainSocketPath: path)
  354. case let .socketAddress(address):
  355. return self.connect(to: address)
  356. }
  357. }
  358. }
  359. extension Channel {
  360. func configureGRPCClient(
  361. httpTargetWindowSize: Int,
  362. tlsConfiguration: TLSConfiguration?,
  363. tlsServerHostname: String?,
  364. connectionManager: ConnectionManager,
  365. connectionKeepalive: ClientConnectionKeepalive,
  366. connectionIdleTimeout: TimeAmount,
  367. errorDelegate: ClientErrorDelegate?,
  368. requiresZeroLengthWriteWorkaround: Bool,
  369. logger: Logger,
  370. customVerificationCallback: NIOSSLCustomVerificationCallback?
  371. ) -> EventLoopFuture<Void> {
  372. // We add at most 8 handlers to the pipeline.
  373. var handlers: [ChannelHandler] = []
  374. handlers.reserveCapacity(7)
  375. #if canImport(Network)
  376. // This availability guard is arguably unnecessary, but we add it anyway.
  377. if requiresZeroLengthWriteWorkaround,
  378. #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
  379. handlers.append(NIOFilterEmptyWritesHandler())
  380. }
  381. #endif
  382. if let tlsConfiguration = tlsConfiguration {
  383. do {
  384. if let customVerificationCallback = customVerificationCallback {
  385. let sslClientHandler = try NIOSSLClientHandler(
  386. context: try NIOSSLContext(configuration: tlsConfiguration),
  387. serverHostname: tlsServerHostname,
  388. customVerificationCallback: customVerificationCallback
  389. )
  390. handlers.append(sslClientHandler)
  391. } else {
  392. let sslClientHandler = try NIOSSLClientHandler(
  393. context: try NIOSSLContext(configuration: tlsConfiguration),
  394. serverHostname: tlsServerHostname
  395. )
  396. handlers.append(sslClientHandler)
  397. }
  398. handlers.append(TLSVerificationHandler(logger: logger))
  399. } catch {
  400. return self.eventLoop.makeFailedFuture(error)
  401. }
  402. }
  403. // We could use 'configureHTTP2Pipeline' here, but we need to add a few handlers between the
  404. // two HTTP/2 handlers so we'll do it manually instead.
  405. let h2Multiplexer = HTTP2StreamMultiplexer(
  406. mode: .client,
  407. channel: self,
  408. targetWindowSize: httpTargetWindowSize,
  409. inboundStreamInitializer: nil
  410. )
  411. handlers.append(NIOHTTP2Handler(mode: .client))
  412. // The multiplexer is passed through the idle handler so it is only reported on
  413. // successful channel activation - with happy eyeballs multiple pipelines can
  414. // be constructed so it's not safe to report just yet.
  415. handlers.append(
  416. GRPCIdleHandler(
  417. connectionManager: connectionManager,
  418. multiplexer: h2Multiplexer,
  419. idleTimeout: connectionIdleTimeout,
  420. keepalive: connectionKeepalive,
  421. logger: logger
  422. )
  423. )
  424. handlers.append(h2Multiplexer)
  425. handlers.append(DelegatingErrorHandler(logger: logger, delegate: errorDelegate))
  426. return self.pipeline.addHandlers(handlers)
  427. }
  428. func configureGRPCClient(
  429. errorDelegate: ClientErrorDelegate?,
  430. logger: Logger
  431. ) -> EventLoopFuture<Void> {
  432. return self.configureHTTP2Pipeline(mode: .client, inboundStreamInitializer: nil).flatMap { _ in
  433. self.pipeline.addHandler(DelegatingErrorHandler(logger: logger, delegate: errorDelegate))
  434. }
  435. }
  436. }
  437. extension TimeAmount {
  438. /// Creates a new `TimeAmount` from the given time interval in seconds.
  439. ///
  440. /// - Parameter timeInterval: The amount of time in seconds
  441. static func seconds(timeInterval: TimeInterval) -> TimeAmount {
  442. return .nanoseconds(Int64(timeInterval * 1_000_000_000))
  443. }
  444. }
  445. extension String {
  446. var isIPAddress: Bool {
  447. // We need some scratch space to let inet_pton write into.
  448. var ipv4Addr = in_addr()
  449. var ipv6Addr = in6_addr()
  450. return self.withCString { ptr in
  451. inet_pton(AF_INET, ptr, &ipv4Addr) == 1 ||
  452. inet_pton(AF_INET6, ptr, &ipv6Addr) == 1
  453. }
  454. }
  455. }