ClientConnection.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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. Defaults to `LoggingClientErrorDelegate`.
  263. public var errorDelegate: ClientErrorDelegate? = LoggingClientErrorDelegate.shared
  264. /// A delegate which is called when the connectivity state is changed. Defaults to `nil`.
  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. Defaults to `nil`.
  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? = 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. ///
  281. /// Defaults to 30 minutes.
  282. public var connectionIdleTimeout: TimeAmount = .minutes(30)
  283. /// The behavior used to determine when an RPC should start. That is, whether it should wait for
  284. /// an active connection or fail quickly if no connection is currently available.
  285. ///
  286. /// Defaults to `waitsForConnectivity`.
  287. public var callStartBehavior: CallStartBehavior = .waitsForConnectivity
  288. /// The HTTP/2 flow control target window size. Defaults to 65535.
  289. public var httpTargetWindowSize = 65535
  290. /// The HTTP protocol used for this connection.
  291. public var httpProtocol: HTTP2FramePayloadToHTTP1ClientCodec.HTTPProtocol {
  292. return self.tls == nil ? .http : .https
  293. }
  294. /// A logger for background information (such as connectivity state). A separate logger for
  295. /// requests may be provided in the `CallOptions`.
  296. ///
  297. /// Defaults to a no-op logger.
  298. public var backgroundActivityLogger = Logger(
  299. label: "io.grpc",
  300. factory: { _ in SwiftLogNoOpLogHandler() }
  301. )
  302. /// A channel initializer which will be run after gRPC has initialized each channel. This may be
  303. /// used to add additional handlers to the pipeline and is intended for debugging.
  304. ///
  305. /// - Warning: The initializer closure may be invoked *multiple times*.
  306. public var debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?
  307. /// Create a `Configuration` with some pre-defined defaults. Prefer using
  308. /// `ClientConnection.secure(group:)` to build a connection secured with TLS or
  309. /// `ClientConnection.insecure(group:)` to build a plaintext connection.
  310. ///
  311. /// - Parameter target: The target to connect to.
  312. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  313. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  314. /// on debug builds.
  315. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`.
  316. /// - Parameter connectivityStateDelegateQueue: A `DispatchQueue` on which to call the
  317. /// `connectivityStateDelegate`.
  318. /// - Parameter tls: TLS configuration, defaulting to `nil`.
  319. /// - Parameter connectionBackoff: The connection backoff configuration to use.
  320. /// - Parameter connectionKeepalive: The keepalive configuration to use.
  321. /// - Parameter connectionIdleTimeout: The amount of time to wait before closing the connection, defaulting to 30 minutes.
  322. /// - Parameter callStartBehavior: The behavior used to determine when a call should start in
  323. /// relation to its underlying connection. Defaults to `waitsForConnectivity`.
  324. /// - Parameter httpTargetWindowSize: The HTTP/2 flow control target window size.
  325. /// - Parameter backgroundActivityLogger: A logger for background information (such as
  326. /// connectivity state). Defaults to a no-op logger.
  327. /// - Parameter debugChannelInitializer: A channel initializer will be called after gRPC has
  328. /// initialized the channel. Defaults to `nil`.
  329. @available(*, deprecated, renamed: "default(target:eventLoopGroup:)")
  330. public init(
  331. target: ConnectionTarget,
  332. eventLoopGroup: EventLoopGroup,
  333. errorDelegate: ClientErrorDelegate? = LoggingClientErrorDelegate(),
  334. connectivityStateDelegate: ConnectivityStateDelegate? = nil,
  335. connectivityStateDelegateQueue: DispatchQueue? = nil,
  336. tls: Configuration.TLS? = nil,
  337. connectionBackoff: ConnectionBackoff? = ConnectionBackoff(),
  338. connectionKeepalive: ClientConnectionKeepalive = ClientConnectionKeepalive(),
  339. connectionIdleTimeout: TimeAmount = .minutes(30),
  340. callStartBehavior: CallStartBehavior = .waitsForConnectivity,
  341. httpTargetWindowSize: Int = 65535,
  342. backgroundActivityLogger: Logger = Logger(
  343. label: "io.grpc",
  344. factory: { _ in SwiftLogNoOpLogHandler() }
  345. ),
  346. debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)? = nil
  347. ) {
  348. self.target = target
  349. self.eventLoopGroup = eventLoopGroup
  350. self.errorDelegate = errorDelegate
  351. self.connectivityStateDelegate = connectivityStateDelegate
  352. self.connectivityStateDelegateQueue = connectivityStateDelegateQueue
  353. self.tls = tls
  354. self.connectionBackoff = connectionBackoff
  355. self.connectionKeepalive = connectionKeepalive
  356. self.connectionIdleTimeout = connectionIdleTimeout
  357. self.callStartBehavior = callStartBehavior
  358. self.httpTargetWindowSize = httpTargetWindowSize
  359. self.backgroundActivityLogger = backgroundActivityLogger
  360. self.debugChannelInitializer = debugChannelInitializer
  361. }
  362. private init(eventLoopGroup: EventLoopGroup, target: ConnectionTarget) {
  363. self.eventLoopGroup = eventLoopGroup
  364. self.target = target
  365. }
  366. /// Make a new configuration using default values.
  367. ///
  368. /// - Parameters:
  369. /// - target: The target to connect to.
  370. /// - eventLoopGroup: The `EventLoopGroup` providing an `EventLoop` for the connection to
  371. /// run on.
  372. /// - Returns: A configuration with default values set.
  373. public static func `default`(
  374. target: ConnectionTarget,
  375. eventLoopGroup: EventLoopGroup
  376. ) -> Configuration {
  377. return .init(eventLoopGroup: eventLoopGroup, target: target)
  378. }
  379. }
  380. }
  381. // MARK: - Configuration helpers/extensions
  382. extension ClientBootstrapProtocol {
  383. /// Connect to the given connection target.
  384. ///
  385. /// - Parameter target: The target to connect to.
  386. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  387. switch target.wrapped {
  388. case let .hostAndPort(host, port):
  389. return self.connect(host: host, port: port)
  390. case let .unixDomainSocket(path):
  391. return self.connect(unixDomainSocketPath: path)
  392. case let .socketAddress(address):
  393. return self.connect(to: address)
  394. }
  395. }
  396. }
  397. extension ChannelPipeline.SynchronousOperations {
  398. internal func configureGRPCClient(
  399. channel: Channel,
  400. httpTargetWindowSize: Int,
  401. sslContext: Result<NIOSSLContext, Error>?,
  402. tlsServerHostname: String?,
  403. connectionManager: ConnectionManager,
  404. connectionKeepalive: ClientConnectionKeepalive,
  405. connectionIdleTimeout: TimeAmount,
  406. errorDelegate: ClientErrorDelegate?,
  407. requiresZeroLengthWriteWorkaround: Bool,
  408. logger: Logger,
  409. customVerificationCallback: NIOSSLCustomVerificationCallback?
  410. ) throws {
  411. #if canImport(Network)
  412. // This availability guard is arguably unnecessary, but we add it anyway.
  413. if requiresZeroLengthWriteWorkaround,
  414. #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
  415. try self.addHandler(NIOFilterEmptyWritesHandler())
  416. }
  417. #endif
  418. if let sslContext = try sslContext?.get() {
  419. let sslClientHandler: NIOSSLClientHandler
  420. if let customVerificationCallback = customVerificationCallback {
  421. sslClientHandler = try NIOSSLClientHandler(
  422. context: sslContext,
  423. serverHostname: tlsServerHostname,
  424. customVerificationCallback: customVerificationCallback
  425. )
  426. } else {
  427. sslClientHandler = try NIOSSLClientHandler(
  428. context: sslContext,
  429. serverHostname: tlsServerHostname
  430. )
  431. }
  432. try self.addHandler(sslClientHandler)
  433. try self.addHandler(TLSVerificationHandler(logger: logger))
  434. }
  435. // We could use 'configureHTTP2Pipeline' here, but we need to add a few handlers between the
  436. // two HTTP/2 handlers so we'll do it manually instead.
  437. try self.addHandler(NIOHTTP2Handler(mode: .client))
  438. let h2Multiplexer = HTTP2StreamMultiplexer(
  439. mode: .client,
  440. channel: channel,
  441. targetWindowSize: httpTargetWindowSize,
  442. inboundStreamInitializer: nil
  443. )
  444. // The multiplexer is passed through the idle handler so it is only reported on
  445. // successful channel activation - with happy eyeballs multiple pipelines can
  446. // be constructed so it's not safe to report just yet.
  447. try self.addHandler(GRPCIdleHandler(
  448. connectionManager: connectionManager,
  449. multiplexer: h2Multiplexer,
  450. idleTimeout: connectionIdleTimeout,
  451. keepalive: connectionKeepalive,
  452. logger: logger
  453. ))
  454. try self.addHandler(h2Multiplexer)
  455. try self.addHandler(DelegatingErrorHandler(logger: logger, delegate: errorDelegate))
  456. }
  457. }
  458. extension Channel {
  459. func configureGRPCClient(
  460. errorDelegate: ClientErrorDelegate?,
  461. logger: Logger
  462. ) -> EventLoopFuture<Void> {
  463. return self.configureHTTP2Pipeline(mode: .client, inboundStreamInitializer: nil).flatMap { _ in
  464. self.pipeline.addHandler(DelegatingErrorHandler(logger: logger, delegate: errorDelegate))
  465. }
  466. }
  467. }
  468. extension TimeAmount {
  469. /// Creates a new `TimeAmount` from the given time interval in seconds.
  470. ///
  471. /// - Parameter timeInterval: The amount of time in seconds
  472. static func seconds(timeInterval: TimeInterval) -> TimeAmount {
  473. return .nanoseconds(Int64(timeInterval * 1_000_000_000))
  474. }
  475. }
  476. extension String {
  477. var isIPAddress: Bool {
  478. // We need some scratch space to let inet_pton write into.
  479. var ipv4Addr = in_addr()
  480. var ipv6Addr = in6_addr()
  481. return self.withCString { ptr in
  482. inet_pton(AF_INET, ptr, &ipv4Addr) == 1 ||
  483. inet_pton(AF_INET6, ptr, &ipv6Addr) == 1
  484. }
  485. }
  486. }