ClientConnection.swift 21 KB

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