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