GRPCChannelBuilder.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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 NIO
  19. import NIOSSL
  20. extension ClientConnection {
  21. /// Returns an insecure `ClientConnection` builder which is *not configured with TLS*.
  22. public static func insecure(group: EventLoopGroup) -> ClientConnection.Builder {
  23. return Builder(group: group)
  24. }
  25. /// Returns a `ClientConnection` builder configured with TLS.
  26. public static func secure(group: EventLoopGroup) -> ClientConnection.Builder.Secure {
  27. return Builder.Secure(group: group)
  28. }
  29. }
  30. extension ClientConnection {
  31. public class Builder {
  32. private var configuration: ClientConnection.Configuration
  33. private var maybeTLS: ClientConnection.Configuration.TLS? { return nil }
  34. private var connectionBackoff = ConnectionBackoff()
  35. private var connectionBackoffIsEnabled = true
  36. fileprivate init(group: EventLoopGroup) {
  37. // This is okay: the configuration is only consumed on a call to `connect` which sets the host
  38. // and port.
  39. self.configuration = Configuration(target: .hostAndPort("", .max), eventLoopGroup: group)
  40. }
  41. public func connect(host: String, port: Int) -> ClientConnection {
  42. // Finish setting up the configuration.
  43. self.configuration.target = .hostAndPort(host, port)
  44. self.configuration.connectionBackoff = self.connectionBackoffIsEnabled ? self
  45. .connectionBackoff : nil
  46. self.configuration.tls = self.maybeTLS
  47. return ClientConnection(configuration: self.configuration)
  48. }
  49. }
  50. }
  51. extension ClientConnection.Builder {
  52. public class Secure: ClientConnection.Builder {
  53. internal var tls = ClientConnection.Configuration.TLS()
  54. override internal var maybeTLS: ClientConnection.Configuration.TLS? {
  55. return self.tls
  56. }
  57. }
  58. }
  59. extension ClientConnection.Builder {
  60. /// Sets the initial connection backoff. That is, the initial time to wait before re-attempting to
  61. /// establish a connection. Jitter will *not* be applied to the initial backoff. Defaults to
  62. /// 1 second if not set.
  63. @discardableResult
  64. public func withConnectionBackoff(initial amount: TimeAmount) -> Self {
  65. self.connectionBackoff.initialBackoff = .seconds(from: amount)
  66. return self
  67. }
  68. /// Set the maximum connection backoff. That is, the maximum amount of time to wait before
  69. /// re-attempting to establish a connection. Note that this time amount represents the maximum
  70. /// backoff *before* jitter is applied. Defaults to 120 seconds if not set.
  71. @discardableResult
  72. public func withConnectionBackoff(maximum amount: TimeAmount) -> Self {
  73. self.connectionBackoff.maximumBackoff = .seconds(from: amount)
  74. return self
  75. }
  76. /// Backoff is 'jittered' to randomise the amount of time to wait before re-attempting to
  77. /// establish a connection. The jittered backoff will be no more than `jitter ⨯ unjitteredBackoff`
  78. /// from `unjitteredBackoff`. Defaults to 0.2 if not set.
  79. ///
  80. /// - Precondition: `0 <= jitter <= 1`
  81. @discardableResult
  82. public func withConnectionBackoff(jitter: Double) -> Self {
  83. self.connectionBackoff.jitter = jitter
  84. return self
  85. }
  86. /// The multiplier for scaling the unjittered backoff between attempts to establish a connection.
  87. /// Defaults to 1.6 if not set.
  88. @discardableResult
  89. public func withConnectionBackoff(multiplier: Double) -> Self {
  90. self.connectionBackoff.multiplier = multiplier
  91. return self
  92. }
  93. /// The minimum timeout to use when attempting to establishing a connection. The connection
  94. /// timeout for each attempt is the larger of the jittered backoff and the minimum connection
  95. /// timeout. Defaults to 20 seconds if not set.
  96. @discardableResult
  97. public func withConnectionTimeout(minimum amount: TimeAmount) -> Self {
  98. self.connectionBackoff.minimumConnectionTimeout = .seconds(from: amount)
  99. return self
  100. }
  101. /// Sets the initial and maximum backoff to given amount. Disables jitter and sets the backoff
  102. /// multiplier to 1.0.
  103. @discardableResult
  104. public func withConnectionBackoff(fixed amount: TimeAmount) -> Self {
  105. let seconds = Double.seconds(from: amount)
  106. self.connectionBackoff.initialBackoff = seconds
  107. self.connectionBackoff.maximumBackoff = seconds
  108. self.connectionBackoff.multiplier = 1.0
  109. self.connectionBackoff.jitter = 0.0
  110. return self
  111. }
  112. /// Sets the limit on the number of times to attempt to re-establish a connection. Defaults
  113. /// to `.unlimited` if not set.
  114. @discardableResult
  115. public func withConnectionBackoff(retries: ConnectionBackoff.Retries) -> Self {
  116. self.connectionBackoff.retries = retries
  117. return self
  118. }
  119. /// Sets whether the connection should be re-established automatically if it is dropped. Defaults
  120. /// to `true` if not set.
  121. @discardableResult
  122. public func withConnectionReestablishment(enabled: Bool) -> Self {
  123. self.connectionBackoffIsEnabled = enabled
  124. return self
  125. }
  126. /// Sets a custom configuration for keepalive
  127. /// The defaults for client and server are determined by the gRPC keepalive
  128. /// [documentation] (https://github.com/grpc/grpc/blob/master/doc/keepalive.md).
  129. @discardableResult
  130. public func withKeepalive(_ keepalive: ClientConnectionKeepalive) -> Self {
  131. self.configuration.connectionKeepalive = keepalive
  132. return self
  133. }
  134. /// The amount of time to wait before closing the connection. The idle timeout will start only
  135. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start. If a
  136. /// connection becomes idle, starting a new RPC will automatically create a new connection.
  137. /// Defaults to 30 minutes if not set.
  138. @discardableResult
  139. public func withConnectionIdleTimeout(_ timeout: TimeAmount) -> Self {
  140. self.configuration.connectionIdleTimeout = timeout
  141. return self
  142. }
  143. /// The behavior used to determine when an RPC should start. That is, whether it should wait for
  144. /// an active connection or fail quickly if no connection is currently available. Calls will
  145. /// use `.waitsForConnectivity` by default.
  146. @discardableResult
  147. public func withCallStartBehavior(_ behavior: CallStartBehavior) -> Self {
  148. self.configuration.callStartBehavior = behavior
  149. return self
  150. }
  151. }
  152. extension ClientConnection.Builder {
  153. /// Sets the client error delegate.
  154. @discardableResult
  155. public func withErrorDelegate(_ delegate: ClientErrorDelegate?) -> Self {
  156. self.configuration.errorDelegate = delegate
  157. return self
  158. }
  159. }
  160. extension ClientConnection.Builder {
  161. /// Sets the client connectivity state delegate and the `DispatchQueue` on which the delegate
  162. /// should be called. If no `queue` is provided then gRPC will create a `DispatchQueue` on which
  163. /// to run the delegate.
  164. @discardableResult
  165. public func withConnectivityStateDelegate(
  166. _ delegate: ConnectivityStateDelegate?,
  167. executingOn queue: DispatchQueue? = nil
  168. ) -> Self {
  169. self.configuration.connectivityStateDelegate = delegate
  170. self.configuration.connectivityStateDelegateQueue = queue
  171. return self
  172. }
  173. }
  174. extension ClientConnection.Builder.Secure {
  175. /// Sets a server hostname override to be used for the TLS Server Name Indication (SNI) extension.
  176. /// The hostname from `connect(host:port)` is for TLS SNI if this value is not set and hostname
  177. /// verification is enabled.
  178. @discardableResult
  179. public func withTLS(serverHostnameOverride: String?) -> Self {
  180. self.tls.hostnameOverride = serverHostnameOverride
  181. return self
  182. }
  183. /// Sets the sources of certificates to offer during negotiation. No certificates are offered
  184. /// during negotiation by default.
  185. @discardableResult
  186. public func withTLS(certificateChain: [NIOSSLCertificate]) -> Self {
  187. // `.certificate` is the only non-deprecated case in `NIOSSLCertificateSource`
  188. self.tls.certificateChain = certificateChain.map { .certificate($0) }
  189. return self
  190. }
  191. /// Sets the private key associated with the leaf certificate.
  192. @discardableResult
  193. public func withTLS(privateKey: NIOSSLPrivateKey) -> Self {
  194. // `.privateKey` is the only non-deprecated case in `NIOSSLPrivateKeySource`
  195. self.tls.privateKey = .privateKey(privateKey)
  196. return self
  197. }
  198. /// Sets the trust roots to use to validate certificates. This only needs to be provided if you
  199. /// intend to validate certificates. Defaults to the system provided trust store (`.default`) if
  200. /// not set.
  201. @discardableResult
  202. public func withTLS(trustRoots: NIOSSLTrustRoots) -> Self {
  203. self.tls.trustRoots = trustRoots
  204. return self
  205. }
  206. }
  207. extension ClientConnection.Builder {
  208. /// Sets the HTTP/2 flow control target window size. Defaults to 65,535 if not explicitly set.
  209. @discardableResult
  210. public func withHTTPTargetWindowSize(_ httpTargetWindowSize: Int) -> Self {
  211. self.configuration.httpTargetWindowSize = httpTargetWindowSize
  212. return self
  213. }
  214. }
  215. extension ClientConnection.Builder {
  216. /// Sets a logger to be used for background activity such as connection state changes. Defaults
  217. /// to a no-op logger if not explicitly set.
  218. ///
  219. /// Note that individual RPCs will use the logger from `CallOptions`, not the logger specified
  220. /// here.
  221. @discardableResult
  222. public func withBackgroundActivityLogger(_ logger: Logger) -> Self {
  223. self.configuration.backgroundActivityLogger = logger
  224. return self
  225. }
  226. }
  227. extension ClientConnection.Builder {
  228. /// A channel initializer which will be run after gRPC has initialized each channel. This may be
  229. /// used to add additional handlers to the pipeline and is intended for debugging.
  230. ///
  231. /// - Warning: The initializer closure may be invoked *multiple times*.
  232. @discardableResult
  233. public func withDebugChannelInitializer(
  234. _ debugChannelInitializer: @escaping (Channel) -> EventLoopFuture<Void>
  235. ) -> Self {
  236. self.configuration.debugChannelInitializer = debugChannelInitializer
  237. return self
  238. }
  239. }
  240. private extension Double {
  241. static func seconds(from amount: TimeAmount) -> Double {
  242. return Double(amount.nanoseconds) / 1_000_000_000
  243. }
  244. }