GRPCChannelPool.swift 15 KB

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