GRPCChannelBuilder.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. extension ClientConnection {
  20. /// Returns an insecure ``ClientConnection`` builder which is *not configured with TLS*.
  21. public static func insecure(group: EventLoopGroup) -> ClientConnection.Builder {
  22. return Builder(group: group)
  23. }
  24. /// Returns a ``ClientConnection`` builder configured with a TLS backend appropriate for the
  25. /// given `EventLoopGroup`.
  26. ///
  27. /// gRPC Swift offers two TLS 'backends'. The 'NIOSSL' backend is available on Darwin and Linux
  28. /// platforms and delegates to SwiftNIO SSL. On recent Darwin platforms (macOS 10.14+, iOS 12+,
  29. /// tvOS 12+, and watchOS 6+) the 'Network.framework' backend is available. The two backends have
  30. /// a number of incompatible configuration options and users are responsible for selecting the
  31. /// appropriate APIs. The TLS configuration options on the builder document which backends they
  32. /// support.
  33. ///
  34. /// TLS backends must also be used with an appropriate `EventLoopGroup` implementation. The
  35. /// 'NIOSSL' backend may be used either a `MultiThreadedEventLoopGroup` or a
  36. /// `NIOTSEventLoopGroup`. The 'Network.framework' backend may only be used with a
  37. /// `NIOTSEventLoopGroup`.
  38. ///
  39. /// This function returns a builder using the `NIOSSL` backend if a `MultiThreadedEventLoopGroup`
  40. /// is supplied and a 'Network.framework' backend if a `NIOTSEventLoopGroup` is used.
  41. public static func usingPlatformAppropriateTLS(
  42. for group: EventLoopGroup
  43. ) -> ClientConnection.Builder.Secure {
  44. let networkPreference = NetworkPreference.userDefined(.matchingEventLoopGroup(group))
  45. return Builder.Secure(
  46. group: group,
  47. tlsConfiguration: .makeClientDefault(for: networkPreference)
  48. )
  49. }
  50. /// Returns a ``ClientConnection`` builder configured with the TLS backend appropriate for the
  51. /// provided configuration and `EventLoopGroup`.
  52. ///
  53. /// - Important: The caller is responsible for ensuring the provided `configuration` may be used
  54. /// the the `group`.
  55. public static func usingTLS(
  56. with configuration: GRPCTLSConfiguration,
  57. on group: EventLoopGroup
  58. ) -> ClientConnection.Builder.Secure {
  59. return Builder.Secure(group: group, tlsConfiguration: configuration)
  60. }
  61. }
  62. extension ClientConnection {
  63. public class Builder {
  64. private var configuration: ClientConnection.Configuration
  65. private var maybeTLS: GRPCTLSConfiguration? { return nil }
  66. private var connectionBackoff = ConnectionBackoff()
  67. private var connectionBackoffIsEnabled = true
  68. fileprivate init(group: EventLoopGroup) {
  69. // This is okay: the configuration is only consumed on a call to `connect` which sets the host
  70. // and port.
  71. self.configuration = .default(target: .hostAndPort("", .max), eventLoopGroup: group)
  72. }
  73. public func connect(host: String, port: Int) -> ClientConnection {
  74. // Finish setting up the configuration.
  75. self.configuration.target = .hostAndPort(host, port)
  76. self.configuration.connectionBackoff =
  77. self.connectionBackoffIsEnabled ? self.connectionBackoff : nil
  78. self.configuration.tlsConfiguration = self.maybeTLS
  79. return ClientConnection(configuration: self.configuration)
  80. }
  81. public func withConnectedSocket(_ socket: NIOBSDSocket.Handle) -> ClientConnection {
  82. precondition(
  83. !PlatformSupport.isTransportServicesEventLoopGroup(self.configuration.eventLoopGroup),
  84. "'\(#function)' requires 'group' to not be a 'NIOTransportServices.NIOTSEventLoopGroup' or 'NIOTransportServices.QoSEventLoop' (but was '\(type(of: self.configuration.eventLoopGroup))'"
  85. )
  86. self.configuration.target = .connectedSocket(socket)
  87. self.configuration.connectionBackoff =
  88. self.connectionBackoffIsEnabled ? self.connectionBackoff : nil
  89. self.configuration.tlsConfiguration = self.maybeTLS
  90. return ClientConnection(configuration: self.configuration)
  91. }
  92. }
  93. }
  94. extension ClientConnection.Builder {
  95. public class Secure: ClientConnection.Builder {
  96. internal var tls: GRPCTLSConfiguration
  97. override internal var maybeTLS: GRPCTLSConfiguration? {
  98. return self.tls
  99. }
  100. internal init(group: EventLoopGroup, tlsConfiguration: GRPCTLSConfiguration) {
  101. group.preconditionCompatible(with: tlsConfiguration)
  102. self.tls = tlsConfiguration
  103. super.init(group: group)
  104. }
  105. /// Connect to `host` on port 443.
  106. public func connect(host: String) -> ClientConnection {
  107. return self.connect(host: host, port: 443)
  108. }
  109. }
  110. }
  111. extension ClientConnection.Builder {
  112. /// Sets the initial connection backoff. That is, the initial time to wait before re-attempting to
  113. /// establish a connection. Jitter will *not* be applied to the initial backoff. Defaults to
  114. /// 1 second if not set.
  115. @discardableResult
  116. public func withConnectionBackoff(initial amount: TimeAmount) -> Self {
  117. self.connectionBackoff.initialBackoff = .seconds(from: amount)
  118. return self
  119. }
  120. /// Set the maximum connection backoff. That is, the maximum amount of time to wait before
  121. /// re-attempting to establish a connection. Note that this time amount represents the maximum
  122. /// backoff *before* jitter is applied. Defaults to 120 seconds if not set.
  123. @discardableResult
  124. public func withConnectionBackoff(maximum amount: TimeAmount) -> Self {
  125. self.connectionBackoff.maximumBackoff = .seconds(from: amount)
  126. return self
  127. }
  128. /// Backoff is 'jittered' to randomise the amount of time to wait before re-attempting to
  129. /// establish a connection. The jittered backoff will be no more than `jitter ⨯ unjitteredBackoff`
  130. /// from `unjitteredBackoff`. Defaults to 0.2 if not set.
  131. ///
  132. /// - Precondition: `0 <= jitter <= 1`
  133. @discardableResult
  134. public func withConnectionBackoff(jitter: Double) -> Self {
  135. self.connectionBackoff.jitter = jitter
  136. return self
  137. }
  138. /// The multiplier for scaling the unjittered backoff between attempts to establish a connection.
  139. /// Defaults to 1.6 if not set.
  140. @discardableResult
  141. public func withConnectionBackoff(multiplier: Double) -> Self {
  142. self.connectionBackoff.multiplier = multiplier
  143. return self
  144. }
  145. /// The minimum timeout to use when attempting to establishing a connection. The connection
  146. /// timeout for each attempt is the larger of the jittered backoff and the minimum connection
  147. /// timeout. Defaults to 20 seconds if not set.
  148. @discardableResult
  149. public func withConnectionTimeout(minimum amount: TimeAmount) -> Self {
  150. self.connectionBackoff.minimumConnectionTimeout = .seconds(from: amount)
  151. return self
  152. }
  153. /// Sets the initial and maximum backoff to given amount. Disables jitter and sets the backoff
  154. /// multiplier to 1.0.
  155. @discardableResult
  156. public func withConnectionBackoff(fixed amount: TimeAmount) -> Self {
  157. let seconds = Double.seconds(from: amount)
  158. self.connectionBackoff.initialBackoff = seconds
  159. self.connectionBackoff.maximumBackoff = seconds
  160. self.connectionBackoff.multiplier = 1.0
  161. self.connectionBackoff.jitter = 0.0
  162. return self
  163. }
  164. /// Sets the limit on the number of times to attempt to re-establish a connection. Defaults
  165. /// to `.unlimited` if not set.
  166. @discardableResult
  167. public func withConnectionBackoff(retries: ConnectionBackoff.Retries) -> Self {
  168. self.connectionBackoff.retries = retries
  169. return self
  170. }
  171. /// Sets whether the connection should be re-established automatically if it is dropped. Defaults
  172. /// to `true` if not set.
  173. @discardableResult
  174. public func withConnectionReestablishment(enabled: Bool) -> Self {
  175. self.connectionBackoffIsEnabled = enabled
  176. return self
  177. }
  178. /// Sets a custom configuration for keepalive
  179. /// The defaults for client and server are determined by the gRPC keepalive
  180. /// [documentation] (https://github.com/grpc/grpc/blob/master/doc/keepalive.md).
  181. @discardableResult
  182. public func withKeepalive(_ keepalive: ClientConnectionKeepalive) -> Self {
  183. self.configuration.connectionKeepalive = keepalive
  184. return self
  185. }
  186. /// The amount of time to wait before closing the connection. The idle timeout will start only
  187. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start. If a
  188. /// connection becomes idle, starting a new RPC will automatically create a new connection.
  189. /// Defaults to 30 minutes if not set.
  190. @discardableResult
  191. public func withConnectionIdleTimeout(_ timeout: TimeAmount) -> Self {
  192. self.configuration.connectionIdleTimeout = timeout
  193. return self
  194. }
  195. /// The behavior used to determine when an RPC should start. That is, whether it should wait for
  196. /// an active connection or fail quickly if no connection is currently available. Calls will
  197. /// use `.waitsForConnectivity` by default.
  198. @discardableResult
  199. public func withCallStartBehavior(_ behavior: CallStartBehavior) -> Self {
  200. self.configuration.callStartBehavior = behavior
  201. return self
  202. }
  203. }
  204. extension ClientConnection.Builder {
  205. /// Sets the client error delegate.
  206. @discardableResult
  207. public func withErrorDelegate(_ delegate: ClientErrorDelegate?) -> Self {
  208. self.configuration.errorDelegate = delegate
  209. return self
  210. }
  211. }
  212. extension ClientConnection.Builder {
  213. /// Sets the client connectivity state delegate and the `DispatchQueue` on which the delegate
  214. /// should be called. If no `queue` is provided then gRPC will create a `DispatchQueue` on which
  215. /// to run the delegate.
  216. @discardableResult
  217. public func withConnectivityStateDelegate(
  218. _ delegate: ConnectivityStateDelegate?,
  219. executingOn queue: DispatchQueue? = nil
  220. ) -> Self {
  221. self.configuration.connectivityStateDelegate = delegate
  222. self.configuration.connectivityStateDelegateQueue = queue
  223. return self
  224. }
  225. }
  226. // MARK: - Common TLS options
  227. extension ClientConnection.Builder.Secure {
  228. /// Sets a server hostname override to be used for the TLS Server Name Indication (SNI) extension.
  229. /// The hostname from `connect(host:port)` is for TLS SNI if this value is not set and hostname
  230. /// verification is enabled.
  231. ///
  232. /// - Note: May be used with the 'NIOSSL' and 'Network.framework' TLS backend.
  233. /// - Note: `serverHostnameOverride` may not be `nil` when using the 'Network.framework' backend.
  234. @discardableResult
  235. public func withTLS(serverHostnameOverride: String?) -> Self {
  236. self.tls.hostnameOverride = serverHostnameOverride
  237. return self
  238. }
  239. }
  240. extension ClientConnection.Builder {
  241. /// Sets the HTTP/2 flow control target window size. Defaults to 8MB if not explicitly set.
  242. /// Values are clamped between 1 and 2^31-1 inclusive.
  243. @discardableResult
  244. public func withHTTPTargetWindowSize(_ httpTargetWindowSize: Int) -> Self {
  245. self.configuration.httpTargetWindowSize = httpTargetWindowSize
  246. return self
  247. }
  248. /// Sets the maximum size of an HTTP/2 frame in bytes which the client is willing to receive from
  249. /// the server. Defaults to 16384. Value are clamped between 2^14 and 2^24-1 octets inclusive
  250. /// (the minimum and maximum permitted values per RFC 7540 § 4.2).
  251. ///
  252. /// Raising this value may lower CPU usage for large message at the cost of increasing head of
  253. /// line blocking for small messages.
  254. @discardableResult
  255. public func withHTTPMaxFrameSize(_ httpMaxFrameSize: Int) -> Self {
  256. self.configuration.httpMaxFrameSize = httpMaxFrameSize
  257. return self
  258. }
  259. }
  260. extension ClientConnection.Builder {
  261. /// Sets the maximum message size the client is permitted to receive in bytes.
  262. ///
  263. /// - Precondition: `limit` must not be negative.
  264. @discardableResult
  265. public func withMaximumReceiveMessageLength(_ limit: Int) -> Self {
  266. self.configuration.maximumReceiveMessageLength = limit
  267. return self
  268. }
  269. }
  270. extension ClientConnection.Builder {
  271. /// Sets a logger to be used for background activity such as connection state changes. Defaults
  272. /// to a no-op logger if not explicitly set.
  273. ///
  274. /// Note that individual RPCs will use the logger from `CallOptions`, not the logger specified
  275. /// here.
  276. @discardableResult
  277. public func withBackgroundActivityLogger(_ logger: Logger) -> Self {
  278. self.configuration.backgroundActivityLogger = logger
  279. return self
  280. }
  281. }
  282. extension ClientConnection.Builder {
  283. /// A channel initializer which will be run after gRPC has initialized each channel. This may be
  284. /// used to add additional handlers to the pipeline and is intended for debugging.
  285. ///
  286. /// - Warning: The initializer closure may be invoked *multiple times*.
  287. #if compiler(>=5.6)
  288. @discardableResult
  289. @preconcurrency
  290. public func withDebugChannelInitializer(
  291. _ debugChannelInitializer: @Sendable @escaping (Channel) -> EventLoopFuture<Void>
  292. ) -> Self {
  293. self.configuration.debugChannelInitializer = debugChannelInitializer
  294. return self
  295. }
  296. #else
  297. @discardableResult
  298. public func withDebugChannelInitializer(
  299. _ debugChannelInitializer: @escaping (Channel) -> EventLoopFuture<Void>
  300. ) -> Self {
  301. self.configuration.debugChannelInitializer = debugChannelInitializer
  302. return self
  303. }
  304. #endif
  305. }
  306. extension Double {
  307. fileprivate static func seconds(from amount: TimeAmount) -> Double {
  308. return Double(amount.nanoseconds) / 1_000_000_000
  309. }
  310. }