GRPCChannelBuilder.swift 7.4 KB

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