GRPCChannelBuilder.swift 8.4 KB

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