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