2
0

GRPCChannelBuilder.swift 8.8 KB

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