GRPCChannelBuilder.swift 9.3 KB

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