GRPCChannelBuilder.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. /*
  2. * Copyright 2020, 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 Dispatch
  17. import Logging
  18. import NIOCore
  19. import NIOSSL
  20. #if canImport(Security)
  21. import Security
  22. #endif
  23. extension ClientConnection {
  24. /// Returns an insecure `ClientConnection` builder which is *not configured with TLS*.
  25. public static func insecure(group: EventLoopGroup) -> ClientConnection.Builder {
  26. return Builder(group: group)
  27. }
  28. /// Returns a `ClientConnection` builder configured with TLS.
  29. @available(
  30. *, deprecated,
  31. message: "Use one of 'usingPlatformAppropriateTLS(for:)', 'usingTLSBackedByNIOSSL(on:)' or 'usingTLSBackedByNetworkFramework(on:)' or 'usingTLS(on:with:)'"
  32. )
  33. public static func secure(group: EventLoopGroup) -> ClientConnection.Builder.Secure {
  34. return ClientConnection.usingTLSBackedByNIOSSL(on: group)
  35. }
  36. /// Returns a `ClientConnection` builder configured with a TLS backend appropriate for the
  37. /// given `EventLoopGroup`.
  38. ///
  39. /// gRPC Swift offers two TLS 'backends'. The 'NIOSSL' backend is available on Darwin and Linux
  40. /// platforms and delegates to SwiftNIO SSL. On recent Darwin platforms (macOS 10.14+, iOS 12+,
  41. /// tvOS 12+, and watchOS 6+) the 'Network.framework' backend is available. The two backends have
  42. /// a number of incompatible configuration options and users are responsible for selecting the
  43. /// appropriate APIs. The TLS configuration options on the builder document which backends they
  44. /// support.
  45. ///
  46. /// TLS backends must also be used with an appropriate `EventLoopGroup` implementation. The
  47. /// 'NIOSSL' backend may be used either a `MultiThreadedEventLoopGroup` or a
  48. /// `NIOTSEventLoopGroup`. The 'Network.framework' backend may only be used with a
  49. /// `NIOTSEventLoopGroup`.
  50. ///
  51. /// This function returns a builder using the `NIOSSL` backend if a `MultiThreadedEventLoopGroup`
  52. /// is supplied and a 'Network.framework' backend if a `NIOTSEventLoopGroup` is used.
  53. public static func usingPlatformAppropriateTLS(
  54. for group: EventLoopGroup
  55. ) -> ClientConnection.Builder.Secure {
  56. let networkPreference = NetworkPreference.userDefined(.matchingEventLoopGroup(group))
  57. return Builder.Secure(
  58. group: group,
  59. tlsConfiguration: .makeClientDefault(for: networkPreference)
  60. )
  61. }
  62. /// Returns a `ClientConnection` builder configured with the 'NIOSSL' TLS backend.
  63. ///
  64. /// This builder may use either a `MultiThreadedEventLoopGroup` or a `NIOTSEventLoopGroup` (or an
  65. /// `EventLoop` from either group).
  66. ///
  67. /// - Parameter group: The `EventLoopGroup` use for the connection.
  68. /// - Returns: A builder for a connection using the NIOSSL TLS backend.
  69. public static func usingTLSBackedByNIOSSL(
  70. on group: EventLoopGroup
  71. ) -> ClientConnection.Builder.Secure {
  72. return Builder.Secure(group: group, tlsConfiguration: .makeClientConfigurationBackedByNIOSSL())
  73. }
  74. #if canImport(Network)
  75. /// Returns a `ClientConnection` builder configured with the Network.framework TLS backend.
  76. ///
  77. /// This builder must use a `NIOTSEventLoopGroup` (or an `EventLoop` from a
  78. /// `NIOTSEventLoopGroup`).
  79. ///
  80. /// - Parameter group: The `EventLoopGroup` use for the connection.
  81. /// - Returns: A builder for a connection using the Network.framework TLS backend.
  82. @available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *)
  83. public static func usingTLSBackedByNetworkFramework(
  84. on group: EventLoopGroup
  85. ) -> ClientConnection.Builder.Secure {
  86. precondition(
  87. PlatformSupport.isTransportServicesEventLoopGroup(group),
  88. "'\(#function)' requires 'group' to be a 'NIOTransportServices.NIOTSEventLoopGroup' or 'NIOTransportServices.QoSEventLoop' (but was '\(type(of: group))'"
  89. )
  90. return Builder.Secure(
  91. group: group,
  92. tlsConfiguration: .makeClientConfigurationBackedByNetworkFramework()
  93. )
  94. }
  95. #endif
  96. /// Returns a `ClientConnection` builder configured with the TLS backend appropriate for the
  97. /// provided configuration and `EventLoopGroup`.
  98. ///
  99. /// - Important: The caller is responsible for ensuring the provided `configuration` may be used
  100. /// the the `group`.
  101. public static func usingTLS(
  102. with configuration: GRPCTLSConfiguration,
  103. on group: EventLoopGroup
  104. ) -> ClientConnection.Builder.Secure {
  105. return Builder.Secure(group: group, tlsConfiguration: configuration)
  106. }
  107. }
  108. extension ClientConnection {
  109. public class Builder {
  110. private var configuration: ClientConnection.Configuration
  111. private var maybeTLS: GRPCTLSConfiguration? { return nil }
  112. private var connectionBackoff = ConnectionBackoff()
  113. private var connectionBackoffIsEnabled = true
  114. fileprivate init(group: EventLoopGroup) {
  115. // This is okay: the configuration is only consumed on a call to `connect` which sets the host
  116. // and port.
  117. self.configuration = .default(target: .hostAndPort("", .max), eventLoopGroup: group)
  118. }
  119. public func connect(host: String, port: Int) -> ClientConnection {
  120. // Finish setting up the configuration.
  121. self.configuration.target = .hostAndPort(host, port)
  122. self.configuration.connectionBackoff =
  123. self.connectionBackoffIsEnabled ? self.connectionBackoff : nil
  124. self.configuration.tlsConfiguration = self.maybeTLS
  125. return ClientConnection(configuration: self.configuration)
  126. }
  127. }
  128. }
  129. extension ClientConnection.Builder {
  130. public class Secure: ClientConnection.Builder {
  131. internal var tls: GRPCTLSConfiguration
  132. override internal var maybeTLS: GRPCTLSConfiguration? {
  133. return self.tls
  134. }
  135. internal init(group: EventLoopGroup, tlsConfiguration: GRPCTLSConfiguration) {
  136. group.preconditionCompatible(with: tlsConfiguration)
  137. self.tls = tlsConfiguration
  138. super.init(group: group)
  139. }
  140. /// Connect to `host` on port 443.
  141. public func connect(host: String) -> ClientConnection {
  142. return self.connect(host: host, port: 443)
  143. }
  144. }
  145. }
  146. extension ClientConnection.Builder {
  147. /// Sets the initial connection backoff. That is, the initial time to wait before re-attempting to
  148. /// establish a connection. Jitter will *not* be applied to the initial backoff. Defaults to
  149. /// 1 second if not set.
  150. @discardableResult
  151. public func withConnectionBackoff(initial amount: TimeAmount) -> Self {
  152. self.connectionBackoff.initialBackoff = .seconds(from: amount)
  153. return self
  154. }
  155. /// Set the maximum connection backoff. That is, the maximum amount of time to wait before
  156. /// re-attempting to establish a connection. Note that this time amount represents the maximum
  157. /// backoff *before* jitter is applied. Defaults to 120 seconds if not set.
  158. @discardableResult
  159. public func withConnectionBackoff(maximum amount: TimeAmount) -> Self {
  160. self.connectionBackoff.maximumBackoff = .seconds(from: amount)
  161. return self
  162. }
  163. /// Backoff is 'jittered' to randomise the amount of time to wait before re-attempting to
  164. /// establish a connection. The jittered backoff will be no more than `jitter ⨯ unjitteredBackoff`
  165. /// from `unjitteredBackoff`. Defaults to 0.2 if not set.
  166. ///
  167. /// - Precondition: `0 <= jitter <= 1`
  168. @discardableResult
  169. public func withConnectionBackoff(jitter: Double) -> Self {
  170. self.connectionBackoff.jitter = jitter
  171. return self
  172. }
  173. /// The multiplier for scaling the unjittered backoff between attempts to establish a connection.
  174. /// Defaults to 1.6 if not set.
  175. @discardableResult
  176. public func withConnectionBackoff(multiplier: Double) -> Self {
  177. self.connectionBackoff.multiplier = multiplier
  178. return self
  179. }
  180. /// The minimum timeout to use when attempting to establishing a connection. The connection
  181. /// timeout for each attempt is the larger of the jittered backoff and the minimum connection
  182. /// timeout. Defaults to 20 seconds if not set.
  183. @discardableResult
  184. public func withConnectionTimeout(minimum amount: TimeAmount) -> Self {
  185. self.connectionBackoff.minimumConnectionTimeout = .seconds(from: amount)
  186. return self
  187. }
  188. /// Sets the initial and maximum backoff to given amount. Disables jitter and sets the backoff
  189. /// multiplier to 1.0.
  190. @discardableResult
  191. public func withConnectionBackoff(fixed amount: TimeAmount) -> Self {
  192. let seconds = Double.seconds(from: amount)
  193. self.connectionBackoff.initialBackoff = seconds
  194. self.connectionBackoff.maximumBackoff = seconds
  195. self.connectionBackoff.multiplier = 1.0
  196. self.connectionBackoff.jitter = 0.0
  197. return self
  198. }
  199. /// Sets the limit on the number of times to attempt to re-establish a connection. Defaults
  200. /// to `.unlimited` if not set.
  201. @discardableResult
  202. public func withConnectionBackoff(retries: ConnectionBackoff.Retries) -> Self {
  203. self.connectionBackoff.retries = retries
  204. return self
  205. }
  206. /// Sets whether the connection should be re-established automatically if it is dropped. Defaults
  207. /// to `true` if not set.
  208. @discardableResult
  209. public func withConnectionReestablishment(enabled: Bool) -> Self {
  210. self.connectionBackoffIsEnabled = enabled
  211. return self
  212. }
  213. /// Sets a custom configuration for keepalive
  214. /// The defaults for client and server are determined by the gRPC keepalive
  215. /// [documentation] (https://github.com/grpc/grpc/blob/master/doc/keepalive.md).
  216. @discardableResult
  217. public func withKeepalive(_ keepalive: ClientConnectionKeepalive) -> Self {
  218. self.configuration.connectionKeepalive = keepalive
  219. return self
  220. }
  221. /// The amount of time to wait before closing the connection. The idle timeout will start only
  222. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start. If a
  223. /// connection becomes idle, starting a new RPC will automatically create a new connection.
  224. /// Defaults to 30 minutes if not set.
  225. @discardableResult
  226. public func withConnectionIdleTimeout(_ timeout: TimeAmount) -> Self {
  227. self.configuration.connectionIdleTimeout = timeout
  228. return self
  229. }
  230. /// The behavior used to determine when an RPC should start. That is, whether it should wait for
  231. /// an active connection or fail quickly if no connection is currently available. Calls will
  232. /// use `.waitsForConnectivity` by default.
  233. @discardableResult
  234. public func withCallStartBehavior(_ behavior: CallStartBehavior) -> Self {
  235. self.configuration.callStartBehavior = behavior
  236. return self
  237. }
  238. }
  239. extension ClientConnection.Builder {
  240. /// Sets the client error delegate.
  241. @discardableResult
  242. public func withErrorDelegate(_ delegate: ClientErrorDelegate?) -> Self {
  243. self.configuration.errorDelegate = delegate
  244. return self
  245. }
  246. }
  247. extension ClientConnection.Builder {
  248. /// Sets the client connectivity state delegate and the `DispatchQueue` on which the delegate
  249. /// should be called. If no `queue` is provided then gRPC will create a `DispatchQueue` on which
  250. /// to run the delegate.
  251. @discardableResult
  252. public func withConnectivityStateDelegate(
  253. _ delegate: ConnectivityStateDelegate?,
  254. executingOn queue: DispatchQueue? = nil
  255. ) -> Self {
  256. self.configuration.connectivityStateDelegate = delegate
  257. self.configuration.connectivityStateDelegateQueue = queue
  258. return self
  259. }
  260. }
  261. // MARK: - Common TLS options
  262. extension ClientConnection.Builder.Secure {
  263. /// Sets a server hostname override to be used for the TLS Server Name Indication (SNI) extension.
  264. /// The hostname from `connect(host:port)` is for TLS SNI if this value is not set and hostname
  265. /// verification is enabled.
  266. ///
  267. /// - Note: May be used with the 'NIOSSL' and 'Network.framework' TLS backend.
  268. /// - Note: `serverHostnameOverride` may not be `nil` when using the 'Network.framework' backend.
  269. @discardableResult
  270. public func withTLS(serverHostnameOverride: String?) -> Self {
  271. self.tls.hostnameOverride = serverHostnameOverride
  272. return self
  273. }
  274. }
  275. // MARK: - NIOSSL TLS backend options
  276. extension ClientConnection.Builder.Secure {
  277. /// Sets the sources of certificates to offer during negotiation. No certificates are offered
  278. /// during negotiation by default.
  279. ///
  280. /// - Note: May only be used with the 'NIOSSL' TLS backend.
  281. @discardableResult
  282. public func withTLS(certificateChain: [NIOSSLCertificate]) -> Self {
  283. self.tls.updateNIOCertificateChain(to: certificateChain)
  284. return self
  285. }
  286. /// Sets the private key associated with the leaf certificate.
  287. ///
  288. /// - Note: May only be used with the 'NIOSSL' TLS backend.
  289. @discardableResult
  290. public func withTLS(privateKey: NIOSSLPrivateKey) -> Self {
  291. self.tls.updateNIOPrivateKey(to: privateKey)
  292. return self
  293. }
  294. /// Sets the trust roots to use to validate certificates. This only needs to be provided if you
  295. /// intend to validate certificates. Defaults to the system provided trust store (`.default`) if
  296. /// not set.
  297. ///
  298. /// - Note: May only be used with the 'NIOSSL' TLS backend.
  299. @discardableResult
  300. public func withTLS(trustRoots: NIOSSLTrustRoots) -> Self {
  301. self.tls.updateNIOTrustRoots(to: trustRoots)
  302. return self
  303. }
  304. /// Whether to verify remote certificates. Defaults to `.fullVerification` if not otherwise
  305. /// configured.
  306. ///
  307. /// - Note: May only be used with the 'NIOSSL' TLS backend.
  308. @discardableResult
  309. public func withTLS(certificateVerification: CertificateVerification) -> Self {
  310. self.tls.updateNIOCertificateVerification(to: certificateVerification)
  311. return self
  312. }
  313. /// A custom verification callback that allows completely overriding the certificate verification logic.
  314. ///
  315. /// - Note: May only be used with the 'NIOSSL' TLS backend.
  316. @discardableResult
  317. public func withTLSCustomVerificationCallback(
  318. _ callback: @escaping NIOSSLCustomVerificationCallback
  319. ) -> Self {
  320. self.tls.updateNIOCustomVerificationCallback(to: callback)
  321. return self
  322. }
  323. }
  324. // MARK: - Network.framework TLS backend options
  325. #if canImport(Network)
  326. extension ClientConnection.Builder.Secure {
  327. /// Update the local identity.
  328. ///
  329. /// - Note: May only be used with the 'Network.framework' TLS backend.
  330. @discardableResult
  331. @available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *)
  332. public func withTLS(localIdentity: SecIdentity) -> Self {
  333. self.tls.updateNetworkLocalIdentity(to: localIdentity)
  334. return self
  335. }
  336. /// Update the callback used to verify a trust object during a TLS handshake.
  337. ///
  338. /// - Note: May only be used with the 'Network.framework' TLS backend.
  339. @discardableResult
  340. @available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *)
  341. public func withTLSHandshakeVerificationCallback(
  342. on queue: DispatchQueue,
  343. verificationCallback callback: @escaping sec_protocol_verify_t
  344. ) -> Self {
  345. self.tls.updateNetworkVerifyCallbackWithQueue(callback: callback, queue: queue)
  346. return self
  347. }
  348. }
  349. #endif
  350. extension ClientConnection.Builder {
  351. /// Sets the HTTP/2 flow control target window size. Defaults to 8MB if not explicitly set.
  352. /// Values are clamped between 1 and 2^31-1 inclusive.
  353. @discardableResult
  354. public func withHTTPTargetWindowSize(_ httpTargetWindowSize: Int) -> Self {
  355. self.configuration.httpTargetWindowSize = httpTargetWindowSize
  356. return self
  357. }
  358. /// Sets the maximum size of an HTTP/2 frame in bytes which the client is willing to receive from
  359. /// the server. Defaults to 16384. Value are clamped between 2^14 and 2^24-1 octets inclusive
  360. /// (the minimum and maximum permitted values per RFC 7540 § 4.2).
  361. ///
  362. /// Raising this value may lower CPU usage for large message at the cost of increasing head of
  363. /// line blocking for small messages.
  364. @discardableResult
  365. public func withHTTPMaxFrameSize(_ httpMaxFrameSize: Int) -> Self {
  366. self.configuration.httpMaxFrameSize = httpMaxFrameSize
  367. return self
  368. }
  369. }
  370. extension ClientConnection.Builder {
  371. /// Sets the maximum message size the client is permitted to receive in bytes.
  372. ///
  373. /// - Precondition: `limit` must not be negative.
  374. @discardableResult
  375. public func withMaximumReceiveMessageLength(_ limit: Int) -> Self {
  376. self.configuration.maximumReceiveMessageLength = limit
  377. return self
  378. }
  379. }
  380. extension ClientConnection.Builder {
  381. /// Sets a logger to be used for background activity such as connection state changes. Defaults
  382. /// to a no-op logger if not explicitly set.
  383. ///
  384. /// Note that individual RPCs will use the logger from `CallOptions`, not the logger specified
  385. /// here.
  386. @discardableResult
  387. public func withBackgroundActivityLogger(_ logger: Logger) -> Self {
  388. self.configuration.backgroundActivityLogger = logger
  389. return self
  390. }
  391. }
  392. extension ClientConnection.Builder {
  393. /// A channel initializer which will be run after gRPC has initialized each channel. This may be
  394. /// used to add additional handlers to the pipeline and is intended for debugging.
  395. ///
  396. /// - Warning: The initializer closure may be invoked *multiple times*.
  397. @discardableResult
  398. public func withDebugChannelInitializer(
  399. _ debugChannelInitializer: @escaping (Channel) -> EventLoopFuture<Void>
  400. ) -> Self {
  401. self.configuration.debugChannelInitializer = debugChannelInitializer
  402. return self
  403. }
  404. }
  405. private extension Double {
  406. static func seconds(from amount: TimeAmount) -> Double {
  407. return Double(amount.nanoseconds) / 1_000_000_000
  408. }
  409. }