2
0

GRPCChannelPool.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. /// The period at which connection pool stats are published to the ``delegate``.
  163. ///
  164. /// Ignored if either this value or ``delegate`` are `nil`.
  165. public var statsPeriod: TimeAmount?
  166. /// A logger used for background activity, such as connection state changes.
  167. public var backgroundActivityLogger = Logger(
  168. label: "io.grpc",
  169. factory: { _ in
  170. return SwiftLogNoOpLogHandler()
  171. }
  172. )
  173. }
  174. }
  175. extension GRPCChannelPool.Configuration {
  176. public struct TransportSecurity: Sendable {
  177. private init(_ configuration: GRPCTLSConfiguration?) {
  178. self.tlsConfiguration = configuration
  179. }
  180. /// The TLS configuration used. A `nil` value means that no TLS will be used and
  181. /// communication at the transport layer will be plaintext.
  182. public var tlsConfiguration: Optional<GRPCTLSConfiguration>
  183. /// Secure the transport layer with TLS.
  184. ///
  185. /// The TLS backend used depends on the value of `configuration`. See ``GRPCTLSConfiguration``
  186. /// for more details.
  187. ///
  188. /// > Important: the value of `configuration` **must** be compatible with
  189. /// > ``GRPCChannelPool/Configuration/eventLoopGroup``. See the documentation of
  190. /// > ``GRPCChannelPool/with(target:transportSecurity:eventLoopGroup:_:)`` for more details.
  191. public static func tls(_ configuration: GRPCTLSConfiguration) -> TransportSecurity {
  192. return TransportSecurity(configuration)
  193. }
  194. /// Insecure plaintext communication.
  195. public static let plaintext = TransportSecurity(nil)
  196. }
  197. }
  198. extension GRPCChannelPool.Configuration {
  199. public struct HTTP2: Hashable, Sendable {
  200. private static let allowedTargetWindowSizes = (1 ... Int(Int32.max))
  201. private static let allowedMaxFrameSizes = (1 << 14) ... ((1 << 24) - 1)
  202. /// Default HTTP/2 configuration.
  203. public static let defaults = HTTP2()
  204. @inlinable
  205. public static func with(_ configure: (inout HTTP2) -> Void) -> HTTP2 {
  206. var configuration = Self.defaults
  207. configure(&configuration)
  208. return configuration
  209. }
  210. /// The HTTP/2 max frame size. Defaults to 8MB. Values are clamped between 2^14 and 2^24-1
  211. /// octets inclusive (RFC 7540 § 4.2).
  212. public var targetWindowSize = 8 * 1024 * 1024 {
  213. didSet {
  214. self.targetWindowSize = self.targetWindowSize.clamped(to: Self.allowedTargetWindowSizes)
  215. }
  216. }
  217. /// The HTTP/2 max frame size. Defaults to 16384. Value is clamped between 2^14 and 2^24-1
  218. /// octets inclusive (the minimum and maximum allowable values - HTTP/2 RFC 7540 4.2).
  219. public var maxFrameSize: Int = 16384 {
  220. didSet {
  221. self.maxFrameSize = self.maxFrameSize.clamped(to: Self.allowedMaxFrameSizes)
  222. }
  223. }
  224. }
  225. }
  226. extension GRPCChannelPool.Configuration {
  227. public struct ConnectionPool: Hashable, Sendable {
  228. /// Default connection pool configuration.
  229. public static let defaults = ConnectionPool()
  230. @inlinable
  231. public static func with(_ configure: (inout ConnectionPool) -> Void) -> ConnectionPool {
  232. var configuration = Self.defaults
  233. configure(&configuration)
  234. return configuration
  235. }
  236. /// The maximum number of connections per `EventLoop` that may be created at a given time.
  237. ///
  238. /// Defaults to 1.
  239. public var connectionsPerEventLoop: Int = 1
  240. /// The maximum number of callers which may be waiting for a stream at any given time on a
  241. /// given `EventLoop`.
  242. ///
  243. /// Any requests for a stream which would cause this limit to be exceeded will be failed
  244. /// immediately.
  245. ///
  246. /// Defaults to 100.
  247. public var maxWaitersPerEventLoop: Int = 100
  248. /// The minimum number of connections to keep open in this pool, per EventLoop.
  249. /// This number of connections per EventLoop will never go idle and be closed.
  250. public var minConnectionsPerEventLoop: Int = 0
  251. /// The maximum amount of time a caller is willing to wait for a stream for before timing out.
  252. ///
  253. /// Defaults to 30 seconds.
  254. public var maxWaitTime: TimeAmount = .seconds(30)
  255. /// The threshold which, if exceeded, when creating a stream determines whether the pool will
  256. /// establish another connection (if doing so will not violate ``connectionsPerEventLoop``).
  257. ///
  258. /// The 'load' is calculated as the ratio of demand for streams (the sum of the number of
  259. /// waiters and the number of reserved streams) and the total number of streams which each
  260. /// thread _could support.
  261. public var reservationLoadThreshold: Double = 0.9
  262. }
  263. }
  264. /// The ID of a connection in the connection pool.
  265. public struct GRPCConnectionID: Hashable, Sendable, CustomStringConvertible {
  266. private enum Value: Sendable, Hashable {
  267. case managerID(ConnectionManagerID)
  268. case uuid(UUID)
  269. }
  270. private let id: Value
  271. public var description: String {
  272. switch self.id {
  273. case .managerID(let id):
  274. return String(describing: id)
  275. case .uuid(let uuid):
  276. return String(describing: uuid)
  277. }
  278. }
  279. internal init(_ id: ConnectionManagerID) {
  280. self.id = .managerID(id)
  281. }
  282. /// Create a new unique connection ID.
  283. ///
  284. /// Normally you don't have to create connection IDs, gRPC will create them on your behalf.
  285. /// However creating them manually is useful when testing the ``GRPCConnectionPoolDelegate``.
  286. public init() {
  287. self.id = .uuid(UUID())
  288. }
  289. }
  290. /// A delegate for the connection pool which is notified of various lifecycle events.
  291. ///
  292. /// All functions must execute quickly and may be executed on arbitrary threads. The implementor is
  293. /// responsible for ensuring thread safety.
  294. public protocol GRPCConnectionPoolDelegate: Sendable {
  295. /// A new connection was created with the given ID and added to the pool. The connection is not
  296. /// yet active (or connecting).
  297. ///
  298. /// In most cases ``startedConnecting(id:)`` will be the next function called for the given
  299. /// connection but ``connectionRemoved(id:)`` may also be called.
  300. func connectionAdded(id: GRPCConnectionID)
  301. /// The connection with the given ID was removed from the pool.
  302. func connectionRemoved(id: GRPCConnectionID)
  303. /// The connection with the given ID has started trying to establish a connection. The outcome
  304. /// of the connection will be reported as either ``connectSucceeded(id:streamCapacity:)`` or
  305. /// ``connectFailed(id:error:)``.
  306. func startedConnecting(id: GRPCConnectionID)
  307. /// A connection attempt failed with the given error. After some period of
  308. /// time ``startedConnecting(id:)`` may be called again.
  309. func connectFailed(id: GRPCConnectionID, error: Error)
  310. /// A connection was established on the connection with the given ID. `streamCapacity` streams are
  311. /// available to use on the connection. The maximum number of available streams may change over
  312. /// time and is reported via ``connectionUtilizationChanged(id:streamsUsed:streamCapacity:)``. The
  313. func connectSucceeded(id: GRPCConnectionID, streamCapacity: Int)
  314. /// The utilization of the connection changed; a stream may have been used, returned or the
  315. /// maximum number of concurrent streams available on the connection changed.
  316. func connectionUtilizationChanged(id: GRPCConnectionID, streamsUsed: Int, streamCapacity: Int)
  317. /// The remote peer is quiescing the connection: no new streams will be created on it. The
  318. /// connection will eventually be closed and removed from the pool.
  319. func connectionQuiescing(id: GRPCConnectionID)
  320. /// The connection was closed. The connection may be established again in the future (notified
  321. /// via ``startedConnecting(id:)``).
  322. func connectionClosed(id: GRPCConnectionID, error: Error?)
  323. /// Stats about the current state of the connection pool.
  324. ///
  325. /// Each ``GRPCConnectionPoolStats`` includes the stats for a sub-pool. Each sub-pool is tied
  326. /// to an `EventLoop`.
  327. ///
  328. /// Unlike the other delegate methods, this is called periodically based on the value
  329. /// of ``GRPCChannelPool/Configuration/statsPeriod``.
  330. func connectionPoolStats(_ stats: [GRPCSubPoolStats], id: GRPCConnectionPoolID)
  331. }
  332. extension GRPCConnectionPoolDelegate {
  333. public func connectionPoolStats(_ stats: [GRPCSubPoolStats], id: GRPCConnectionPoolID) {
  334. // Default conformance to avoid breaking changes.
  335. }
  336. }
  337. public struct GRPCSubPoolStats: Sendable, Hashable {
  338. public struct ConnectionStates: Sendable, Hashable {
  339. /// The number of idle connections.
  340. public var idle: Int
  341. /// The number of connections trying to establish a connection.
  342. public var connecting: Int
  343. /// The number of connections which are ready to use.
  344. public var ready: Int
  345. /// The number of connections which are backing off waiting to attempt to connect.
  346. public var transientFailure: Int
  347. public init() {
  348. self.idle = 0
  349. self.connecting = 0
  350. self.ready = 0
  351. self.transientFailure = 0
  352. }
  353. }
  354. /// The ID of the subpool.
  355. public var id: GRPCSubPoolID
  356. /// Counts of connection states.
  357. public var connectionStates: ConnectionStates
  358. /// The number of streams currently being used.
  359. public var streamsInUse: Int
  360. /// The number of streams which are currently free to use.
  361. ///
  362. /// The sum of this value and `streamsInUse` gives the capacity of the pool.
  363. public var streamsFreeToUse: Int
  364. /// The number of RPCs currently waiting for a stream.
  365. ///
  366. /// RPCs waiting for a stream are also known as 'waiters'.
  367. public var rpcsWaiting: Int
  368. public init(id: GRPCSubPoolID) {
  369. self.id = id
  370. self.connectionStates = ConnectionStates()
  371. self.streamsInUse = 0
  372. self.streamsFreeToUse = 0
  373. self.rpcsWaiting = 0
  374. }
  375. }