GRPCChannelPool.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /*
  2. * Copyright 2021, 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 Logging
  17. import NIOCore
  18. import NIOPosix
  19. public enum GRPCChannelPool {
  20. /// Make a new ``GRPCChannel`` on which calls may be made to gRPC services.
  21. ///
  22. /// The channel is backed by one connection pool per event loop, each of which may make multiple
  23. /// connections to the given target. The size of the connection pool, and therefore the maximum
  24. /// number of connections it may create at a given time is determined by the number of event loops
  25. /// in the provided `EventLoopGroup` and the value of
  26. /// ``GRPCChannelPool/Configuration/ConnectionPool-swift.struct/connectionsPerEventLoop``.
  27. ///
  28. /// The event loop and therefore connection chosen for a call is determined by
  29. /// ``CallOptions/eventLoopPreference-swift.property``. If the `indifferent` preference is used
  30. /// then the least-used event loop is chosen and a connection on that event loop will be selected.
  31. /// If an `exact` preference is used then a connection on that event loop will be chosen provided
  32. /// the given event loop belongs to the `EventLoopGroup` used to create this ``GRPCChannel``.
  33. ///
  34. /// Each connection in the pool is initially idle, and no connections will be established until
  35. /// a call is made. The pool also closes connections after they have been inactive (i.e. are not
  36. /// being used for calls) for some period of time. This is determined by
  37. /// ``GRPCChannelPool/Configuration/idleTimeout``.
  38. ///
  39. /// > Important: The values of `transportSecurity` and `eventLoopGroup` **must** be compatible.
  40. /// >
  41. /// > For ``GRPCChannelPool/Configuration/TransportSecurity-swift.struct/tls(_:)`` the allowed
  42. /// > `EventLoopGroup`s depends on the value of ``GRPCTLSConfiguration``. If a TLS configuration
  43. /// > is known ahead of time, ``PlatformSupport/makeEventLoopGroup(compatibleWith:loopCount:)``
  44. /// > may be used to construct a compatible `EventLoopGroup`.
  45. /// >
  46. /// > If the `EventLoopGroup` is known ahead of time then a default TLS configuration may be
  47. /// > constructed with ``GRPCTLSConfiguration/makeClientDefault(compatibleWith:)``.
  48. /// >
  49. /// > For ``GRPCChannelPool/Configuration/TransportSecurity-swift.struct/plaintext`` transport
  50. /// > security both `MultiThreadedEventLoopGroup` and `NIOTSEventLoopGroup` (and `EventLoop`s
  51. /// > from either) may be used.
  52. ///
  53. /// - Parameters:
  54. /// - target: The target to connect to.
  55. /// - transportSecurity: Transport layer security for connections.
  56. /// - eventLoopGroup: The `EventLoopGroup` to run connections on.
  57. /// - configure: A closure which may be used to modify defaulted configuration before
  58. /// constructing the ``GRPCChannel``.
  59. /// - Throws: If it is not possible to construct an SSL context. This will never happen when
  60. /// using the ``GRPCChannelPool/Configuration/TransportSecurity-swift.struct/plaintext``
  61. /// transport security.
  62. /// - Returns: A ``GRPCChannel``.
  63. @inlinable
  64. public static func with(
  65. target: ConnectionTarget,
  66. transportSecurity: GRPCChannelPool.Configuration.TransportSecurity,
  67. eventLoopGroup: EventLoopGroup,
  68. _ configure: (inout GRPCChannelPool.Configuration) -> Void = { _ in }
  69. ) throws -> GRPCChannel {
  70. let configuration = GRPCChannelPool.Configuration.with(
  71. target: target,
  72. transportSecurity: transportSecurity,
  73. eventLoopGroup: eventLoopGroup,
  74. configure
  75. )
  76. return try PooledChannel(configuration: configuration)
  77. }
  78. /// See ``GRPCChannelPool/with(target:transportSecurity:eventLoopGroup:_:)``.
  79. public static func with(
  80. configuration: GRPCChannelPool.Configuration
  81. ) throws -> GRPCChannel {
  82. return try PooledChannel(configuration: configuration)
  83. }
  84. }
  85. extension GRPCChannelPool {
  86. public struct Configuration: GRPCSendable {
  87. @inlinable
  88. internal init(
  89. target: ConnectionTarget,
  90. transportSecurity: TransportSecurity,
  91. eventLoopGroup: EventLoopGroup
  92. ) {
  93. self.target = target
  94. self.transportSecurity = transportSecurity
  95. self.eventLoopGroup = eventLoopGroup
  96. }
  97. // Note: we use `configure` blocks to avoid having to add new initializers when properties are
  98. // added to the configuration while allowing the configuration to be constructed as a constant.
  99. /// Construct and configure a ``GRPCChannelPool/Configuration``.
  100. ///
  101. /// - Parameters:
  102. /// - target: The target to connect to.
  103. /// - transportSecurity: Transport layer security for connections. Note that the value of
  104. /// `eventLoopGroup` must be compatible with the value
  105. /// - eventLoopGroup: The `EventLoopGroup` to run connections on.
  106. /// - configure: A closure which may be used to modify defaulted configuration.
  107. @inlinable
  108. public static func with(
  109. target: ConnectionTarget,
  110. transportSecurity: TransportSecurity,
  111. eventLoopGroup: EventLoopGroup,
  112. _ configure: (inout Configuration) -> Void = { _ in }
  113. ) -> Configuration {
  114. var configuration = Configuration(
  115. target: target,
  116. transportSecurity: transportSecurity,
  117. eventLoopGroup: eventLoopGroup
  118. )
  119. configure(&configuration)
  120. return configuration
  121. }
  122. /// The target to connect to.
  123. public var target: ConnectionTarget
  124. /// Connection security.
  125. public var transportSecurity: TransportSecurity
  126. /// The `EventLoopGroup` used by the connection pool.
  127. public var eventLoopGroup: EventLoopGroup
  128. /// Connection pool configuration.
  129. public var connectionPool: ConnectionPool = .defaults
  130. /// HTTP/2 configuration.
  131. public var http2: HTTP2 = .defaults
  132. /// The connection backoff configuration.
  133. public var connectionBackoff = ConnectionBackoff()
  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.
  136. ///
  137. /// If a connection becomes idle, starting a new RPC will automatically create a new connection.
  138. public var idleTimeout = TimeAmount.minutes(30)
  139. /// The connection keepalive configuration.
  140. public var keepalive = ClientConnectionKeepalive()
  141. /// The maximum size in bytes of a message which may be received from a server. Defaults to 4MB.
  142. ///
  143. /// Any received messages whose size exceeds this limit will cause RPCs to fail with
  144. /// a `.resourceExhausted` status code.
  145. public var maximumReceiveMessageLength: Int = 4 * 1024 * 1024 {
  146. willSet {
  147. precondition(newValue >= 0, "maximumReceiveMessageLength must be positive")
  148. }
  149. }
  150. /// A channel initializer which will be run after gRPC has initialized each `NIOCore.Channel`.
  151. /// This may be used to add additional handlers to the pipeline and is intended for debugging.
  152. ///
  153. /// - Warning: The initializer closure may be invoked *multiple times*.
  154. #if compiler(>=5.6)
  155. @preconcurrency
  156. public var debugChannelInitializer: (@Sendable (Channel) -> EventLoopFuture<Void>)?
  157. #else
  158. public var debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?
  159. #endif
  160. /// An error delegate which is called when errors are caught.
  161. public var errorDelegate: ClientErrorDelegate?
  162. /// A delegate which will be notified about changes to the state of connections managed by the
  163. /// pool.
  164. public var delegate: GRPCConnectionPoolDelegate?
  165. /// A logger used for background activity, such as connection state changes.
  166. public var backgroundActivityLogger = Logger(
  167. label: "io.grpc",
  168. factory: { _ in
  169. return SwiftLogNoOpLogHandler()
  170. }
  171. )
  172. }
  173. }
  174. extension GRPCChannelPool.Configuration {
  175. public struct TransportSecurity: GRPCSendable {
  176. private init(_ configuration: GRPCTLSConfiguration?) {
  177. self.tlsConfiguration = configuration
  178. }
  179. /// The TLS configuration used. A `nil` value means that no TLS will be used and
  180. /// communication at the transport layer will be plaintext.
  181. public var tlsConfiguration: Optional<GRPCTLSConfiguration>
  182. /// Secure the transport layer with TLS.
  183. ///
  184. /// The TLS backend used depends on the value of `configuration`. See ``GRPCTLSConfiguration``
  185. /// for more details.
  186. ///
  187. /// > Important: the value of `configuration` **must** be compatible with
  188. /// > ``GRPCChannelPool/Configuration/eventLoopGroup``. See the documentation of
  189. /// > ``GRPCChannelPool/with(target:transportSecurity:eventLoopGroup:_:)`` for more details.
  190. public static func tls(_ configuration: GRPCTLSConfiguration) -> TransportSecurity {
  191. return TransportSecurity(configuration)
  192. }
  193. /// Insecure plaintext communication.
  194. public static let plaintext = TransportSecurity(nil)
  195. }
  196. }
  197. extension GRPCChannelPool.Configuration {
  198. public struct HTTP2: Hashable, GRPCSendable {
  199. private static let allowedTargetWindowSizes = (1 ... Int(Int32.max))
  200. private static let allowedMaxFrameSizes = (1 << 14) ... ((1 << 24) - 1)
  201. /// Default HTTP/2 configuration.
  202. public static let defaults = HTTP2()
  203. @inlinable
  204. public static func with(_ configure: (inout HTTP2) -> Void) -> HTTP2 {
  205. var configuration = Self.defaults
  206. configure(&configuration)
  207. return configuration
  208. }
  209. /// The HTTP/2 max frame size. Defaults to 8MB. Values are clamped between 2^14 and 2^24-1
  210. /// octets inclusive (RFC 7540 § 4.2).
  211. public var targetWindowSize = 8 * 1024 * 1024 {
  212. didSet {
  213. self.targetWindowSize = self.targetWindowSize.clamped(to: Self.allowedTargetWindowSizes)
  214. }
  215. }
  216. /// The HTTP/2 max frame size. Defaults to 16384. Value is clamped between 2^14 and 2^24-1
  217. /// octets inclusive (the minimum and maximum allowable values - HTTP/2 RFC 7540 4.2).
  218. public var maxFrameSize: Int = 16384 {
  219. didSet {
  220. self.maxFrameSize = self.maxFrameSize.clamped(to: Self.allowedMaxFrameSizes)
  221. }
  222. }
  223. }
  224. }
  225. extension GRPCChannelPool.Configuration {
  226. public struct ConnectionPool: Hashable, GRPCSendable {
  227. /// Default connection pool configuration.
  228. public static let defaults = ConnectionPool()
  229. @inlinable
  230. public static func with(_ configure: (inout ConnectionPool) -> Void) -> ConnectionPool {
  231. var configuration = Self.defaults
  232. configure(&configuration)
  233. return configuration
  234. }
  235. /// The maximum number of connections per `EventLoop` that may be created at a given time.
  236. ///
  237. /// Defaults to 1.
  238. public var connectionsPerEventLoop: Int = 1
  239. /// The maximum number of callers which may be waiting for a stream at any given time on a
  240. /// given `EventLoop`.
  241. ///
  242. /// Any requests for a stream which would cause this limit to be exceeded will be failed
  243. /// immediately.
  244. ///
  245. /// Defaults to 100.
  246. public var maxWaitersPerEventLoop: Int = 100
  247. /// The maximum amount of time a caller is willing to wait for a stream for before timing out.
  248. ///
  249. /// Defaults to 30 seconds.
  250. public var maxWaitTime: TimeAmount = .seconds(30)
  251. /// The threshold which, if exceeded, when creating a stream determines whether the pool will
  252. /// establish another connection (if doing so will not violate ``connectionsPerEventLoop``).
  253. ///
  254. /// The 'load' is calculated as the ratio of demand for streams (the sum of the number of
  255. /// waiters and the number of reserved streams) and the total number of streams which each
  256. /// thread _could support.
  257. public var reservationLoadThreshold: Double = 0.9
  258. }
  259. }
  260. /// The ID of a connection in the connection pool.
  261. public struct GRPCConnectionID: Hashable, GRPCSendable, CustomStringConvertible {
  262. private let id: ConnectionManagerID
  263. public var description: String {
  264. return String(describing: self.id)
  265. }
  266. internal init(_ id: ConnectionManagerID) {
  267. self.id = id
  268. }
  269. }
  270. /// A delegate for the connection pool which is notified of various lifecycle events.
  271. ///
  272. /// All functions must execute quickly and may be executed on arbitrary threads. The implementor is
  273. /// responsible for ensuring thread safety.
  274. public protocol GRPCConnectionPoolDelegate: GRPCSendable {
  275. /// A new connection was created with the given ID and added to the pool. The connection is not
  276. /// yet active (or connecting).
  277. ///
  278. /// In most cases ``startedConnecting(id:)`` will be the next function called for the given
  279. /// connection but ``connectionRemoved(id:)`` may also be called.
  280. func connectionAdded(id: GRPCConnectionID)
  281. /// The connection with the given ID was removed from the pool.
  282. func connectionRemoved(id: GRPCConnectionID)
  283. /// The connection with the given ID has started trying to establish a connection. The outcome
  284. /// of the connection will be reported as either ``connectSucceeded(id:streamCapacity:)`` or
  285. /// ``connectFailed(id:error:)``.
  286. func startedConnecting(id: GRPCConnectionID)
  287. /// A connection attempt failed with the given error. After some period of
  288. /// time ``startedConnecting(id:)`` may be called again.
  289. func connectFailed(id: GRPCConnectionID, error: Error)
  290. /// A connection was established on the connection with the given ID. `streamCapacity` streams are
  291. /// available to use on the connection. The maximum number of available streams may change over
  292. /// time and is reported via ``connectionUtilizationChanged(id:streamsUsed:streamCapacity:)``. The
  293. func connectSucceeded(id: GRPCConnectionID, streamCapacity: Int)
  294. /// The utlization of the connection changed; a stream may have been used, returned or the
  295. /// maximum number of concurrent streams available on the connection changed.
  296. func connectionUtilizationChanged(id: GRPCConnectionID, streamsUsed: Int, streamCapacity: Int)
  297. /// The remote peer is quiescing the connection: no new streams will be created on it. The
  298. /// connection will eventually be closed and removed from the pool.
  299. func connectionQuiescing(id: GRPCConnectionID)
  300. /// The connection was closed. The connection may be established again in the future (notified
  301. /// via ``startedConnecting(id:)``).
  302. func connectionClosed(id: GRPCConnectionID, error: Error?)
  303. }