GRPCChannelPool.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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. #if canImport(Network)
  21. import Network
  22. #endif
  23. public enum GRPCChannelPool {
  24. /// Make a new ``GRPCChannel`` on which calls may be made to gRPC services.
  25. ///
  26. /// The channel is backed by one connection pool per event loop, each of which may make multiple
  27. /// connections to the given target. The size of the connection pool, and therefore the maximum
  28. /// number of connections it may create at a given time is determined by the number of event loops
  29. /// in the provided `EventLoopGroup` and the value of
  30. /// ``GRPCChannelPool/Configuration/ConnectionPool-swift.struct/connectionsPerEventLoop``.
  31. ///
  32. /// The event loop and therefore connection chosen for a call is determined by
  33. /// ``CallOptions/eventLoopPreference-swift.property``. If the `indifferent` preference is used
  34. /// then the least-used event loop is chosen and a connection on that event loop will be selected.
  35. /// If an `exact` preference is used then a connection on that event loop will be chosen provided
  36. /// the given event loop belongs to the `EventLoopGroup` used to create this ``GRPCChannel``.
  37. ///
  38. /// Each connection in the pool is initially idle, and no connections will be established until
  39. /// a call is made. The pool also closes connections after they have been inactive (i.e. are not
  40. /// being used for calls) for some period of time. This is determined by
  41. /// ``GRPCChannelPool/Configuration/idleTimeout``.
  42. ///
  43. /// > Important: The values of `transportSecurity` and `eventLoopGroup` **must** be compatible.
  44. /// >
  45. /// > For ``GRPCChannelPool/Configuration/TransportSecurity-swift.struct/tls(_:)`` the allowed
  46. /// > `EventLoopGroup`s depends on the value of ``GRPCTLSConfiguration``. If a TLS configuration
  47. /// > is known ahead of time, ``PlatformSupport/makeEventLoopGroup(compatibleWith:loopCount:)``
  48. /// > may be used to construct a compatible `EventLoopGroup`.
  49. /// >
  50. /// > If the `EventLoopGroup` is known ahead of time then a default TLS configuration may be
  51. /// > constructed with ``GRPCTLSConfiguration/makeClientDefault(compatibleWith:)``.
  52. /// >
  53. /// > For ``GRPCChannelPool/Configuration/TransportSecurity-swift.struct/plaintext`` transport
  54. /// > security both `MultiThreadedEventLoopGroup` and `NIOTSEventLoopGroup` (and `EventLoop`s
  55. /// > from either) may be used.
  56. ///
  57. /// - Parameters:
  58. /// - target: The target to connect to.
  59. /// - transportSecurity: Transport layer security for connections.
  60. /// - eventLoopGroup: The `EventLoopGroup` to run connections on.
  61. /// - configure: A closure which may be used to modify defaulted configuration before
  62. /// constructing the ``GRPCChannel``.
  63. /// - Throws: If it is not possible to construct an SSL context. This will never happen when
  64. /// using the ``GRPCChannelPool/Configuration/TransportSecurity-swift.struct/plaintext``
  65. /// transport security.
  66. /// - Returns: A ``GRPCChannel``.
  67. @inlinable
  68. public static func with(
  69. target: ConnectionTarget,
  70. transportSecurity: GRPCChannelPool.Configuration.TransportSecurity,
  71. eventLoopGroup: EventLoopGroup,
  72. _ configure: (inout GRPCChannelPool.Configuration) -> Void = { _ in }
  73. ) throws -> GRPCChannel {
  74. let configuration = GRPCChannelPool.Configuration.with(
  75. target: target,
  76. transportSecurity: transportSecurity,
  77. eventLoopGroup: eventLoopGroup,
  78. configure
  79. )
  80. return try PooledChannel(configuration: configuration)
  81. }
  82. /// See ``GRPCChannelPool/with(target:transportSecurity:eventLoopGroup:_:)``.
  83. public static func with(
  84. configuration: GRPCChannelPool.Configuration
  85. ) throws -> GRPCChannel {
  86. return try PooledChannel(configuration: configuration)
  87. }
  88. }
  89. extension GRPCChannelPool {
  90. public struct Configuration: Sendable {
  91. @inlinable
  92. internal init(
  93. target: ConnectionTarget,
  94. transportSecurity: TransportSecurity,
  95. eventLoopGroup: EventLoopGroup
  96. ) {
  97. self.target = target
  98. self.transportSecurity = transportSecurity
  99. self.eventLoopGroup = eventLoopGroup
  100. }
  101. // Note: we use `configure` blocks to avoid having to add new initializers when properties are
  102. // added to the configuration while allowing the configuration to be constructed as a constant.
  103. /// Construct and configure a ``GRPCChannelPool/Configuration``.
  104. ///
  105. /// - Parameters:
  106. /// - target: The target to connect to.
  107. /// - transportSecurity: Transport layer security for connections. Note that the value of
  108. /// `eventLoopGroup` must be compatible with the value
  109. /// - eventLoopGroup: The `EventLoopGroup` to run connections on.
  110. /// - configure: A closure which may be used to modify defaulted configuration.
  111. @inlinable
  112. public static func with(
  113. target: ConnectionTarget,
  114. transportSecurity: TransportSecurity,
  115. eventLoopGroup: EventLoopGroup,
  116. _ configure: (inout Configuration) -> Void = { _ in }
  117. ) -> Configuration {
  118. var configuration = Configuration(
  119. target: target,
  120. transportSecurity: transportSecurity,
  121. eventLoopGroup: eventLoopGroup
  122. )
  123. configure(&configuration)
  124. return configuration
  125. }
  126. /// The target to connect to.
  127. public var target: ConnectionTarget
  128. /// Connection security.
  129. public var transportSecurity: TransportSecurity
  130. /// The `EventLoopGroup` used by the connection pool.
  131. public var eventLoopGroup: EventLoopGroup
  132. /// Connection pool configuration.
  133. public var connectionPool: ConnectionPool = .defaults
  134. /// HTTP/2 configuration.
  135. public var http2: HTTP2 = .defaults
  136. /// The connection backoff configuration.
  137. public var connectionBackoff = ConnectionBackoff()
  138. /// The amount of time to wait before closing the connection. The idle timeout will start only
  139. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start.
  140. ///
  141. /// If a connection becomes idle, starting a new RPC will automatically create a new connection.
  142. public var idleTimeout = TimeAmount.minutes(30)
  143. /// The connection keepalive configuration.
  144. public var keepalive = ClientConnectionKeepalive()
  145. /// The maximum size in bytes of a message which may be received from a server. Defaults to 4MB.
  146. ///
  147. /// Any received messages whose size exceeds this limit will cause RPCs to fail with
  148. /// a `.resourceExhausted` status code.
  149. public var maximumReceiveMessageLength: Int = 4 * 1024 * 1024 {
  150. willSet {
  151. precondition(newValue >= 0, "maximumReceiveMessageLength must be positive")
  152. }
  153. }
  154. /// A channel initializer which will be run after gRPC has initialized each `NIOCore.Channel`.
  155. /// This may be used to add additional handlers to the pipeline and is intended for debugging.
  156. ///
  157. /// - Warning: The initializer closure may be invoked *multiple times*.
  158. @preconcurrency
  159. public var debugChannelInitializer: (@Sendable (Channel) -> EventLoopFuture<Void>)?
  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. /// The period at which connection pool stats are published to the ``delegate``.
  166. ///
  167. /// Ignored if either this value or ``delegate`` are `nil`.
  168. public var statsPeriod: TimeAmount?
  169. /// A logger used for background activity, such as connection state changes.
  170. public var backgroundActivityLogger = Logger(
  171. label: "io.grpc",
  172. factory: { _ in
  173. return SwiftLogNoOpLogHandler()
  174. }
  175. )
  176. #if canImport(Network)
  177. /// `TransportServices` related configuration. This will be ignored unless an appropriate event loop group
  178. /// (e.g. `NIOTSEventLoopGroup`) is used.
  179. public var transportServices: TransportServices = .defaults
  180. #endif
  181. }
  182. }
  183. extension GRPCChannelPool.Configuration {
  184. public struct TransportSecurity: Sendable {
  185. private init(_ configuration: GRPCTLSConfiguration?) {
  186. self.tlsConfiguration = configuration
  187. }
  188. /// The TLS configuration used. A `nil` value means that no TLS will be used and
  189. /// communication at the transport layer will be plaintext.
  190. public var tlsConfiguration: Optional<GRPCTLSConfiguration>
  191. /// Secure the transport layer with TLS.
  192. ///
  193. /// The TLS backend used depends on the value of `configuration`. See ``GRPCTLSConfiguration``
  194. /// for more details.
  195. ///
  196. /// > Important: the value of `configuration` **must** be compatible with
  197. /// > ``GRPCChannelPool/Configuration/eventLoopGroup``. See the documentation of
  198. /// > ``GRPCChannelPool/with(target:transportSecurity:eventLoopGroup:_:)`` for more details.
  199. public static func tls(_ configuration: GRPCTLSConfiguration) -> TransportSecurity {
  200. return TransportSecurity(configuration)
  201. }
  202. /// Insecure plaintext communication.
  203. public static let plaintext = TransportSecurity(nil)
  204. }
  205. }
  206. extension GRPCChannelPool.Configuration {
  207. public struct HTTP2: Hashable, Sendable {
  208. private static let allowedTargetWindowSizes = (1 ... Int(Int32.max))
  209. private static let allowedMaxFrameSizes = (1 << 14) ... ((1 << 24) - 1)
  210. /// Default HTTP/2 configuration.
  211. public static let defaults = HTTP2()
  212. @inlinable
  213. public static func with(_ configure: (inout HTTP2) -> Void) -> HTTP2 {
  214. var configuration = Self.defaults
  215. configure(&configuration)
  216. return configuration
  217. }
  218. /// The HTTP/2 max frame size. Defaults to 8MB. Values are clamped between 2^14 and 2^24-1
  219. /// octets inclusive (RFC 7540 § 4.2).
  220. public var targetWindowSize = 8 * 1024 * 1024 {
  221. didSet {
  222. self.targetWindowSize = self.targetWindowSize.clamped(to: Self.allowedTargetWindowSizes)
  223. }
  224. }
  225. /// The HTTP/2 max frame size. Defaults to 16384. Value is clamped between 2^14 and 2^24-1
  226. /// octets inclusive (the minimum and maximum allowable values - HTTP/2 RFC 7540 4.2).
  227. public var maxFrameSize: Int = 16384 {
  228. didSet {
  229. self.maxFrameSize = self.maxFrameSize.clamped(to: Self.allowedMaxFrameSizes)
  230. }
  231. }
  232. /// The HTTP/2 max number of reset streams. Defaults to 32. Must be non-negative.
  233. public var maxResetStreams: Int = 32 {
  234. willSet {
  235. precondition(newValue >= 0, "maxResetStreams must be non-negative")
  236. }
  237. }
  238. }
  239. }
  240. extension GRPCChannelPool.Configuration {
  241. public struct ConnectionPool: Hashable, Sendable {
  242. /// Default connection pool configuration.
  243. public static let defaults = ConnectionPool()
  244. @inlinable
  245. public static func with(_ configure: (inout ConnectionPool) -> Void) -> ConnectionPool {
  246. var configuration = Self.defaults
  247. configure(&configuration)
  248. return configuration
  249. }
  250. /// The maximum number of connections per `EventLoop` that may be created at a given time.
  251. ///
  252. /// Defaults to 1.
  253. public var connectionsPerEventLoop: Int = 1
  254. /// The maximum number of callers which may be waiting for a stream at any given time on a
  255. /// given `EventLoop`.
  256. ///
  257. /// Any requests for a stream which would cause this limit to be exceeded will be failed
  258. /// immediately.
  259. ///
  260. /// Defaults to 100.
  261. public var maxWaitersPerEventLoop: Int = 100
  262. /// The minimum number of connections to keep open in this pool, per EventLoop.
  263. /// This number of connections per EventLoop will never go idle and be closed.
  264. public var minConnectionsPerEventLoop: Int = 0
  265. /// The maximum amount of time a caller is willing to wait for a stream for before timing out.
  266. ///
  267. /// Defaults to 30 seconds.
  268. public var maxWaitTime: TimeAmount = .seconds(30)
  269. /// The threshold which, if exceeded, when creating a stream determines whether the pool will
  270. /// establish another connection (if doing so will not violate ``connectionsPerEventLoop``).
  271. ///
  272. /// The 'load' is calculated as the ratio of demand for streams (the sum of the number of
  273. /// waiters and the number of reserved streams) and the total number of streams which each
  274. /// thread _could support.
  275. public var reservationLoadThreshold: Double = 0.9
  276. }
  277. }
  278. #if canImport(Network)
  279. extension GRPCChannelPool.Configuration {
  280. public struct TransportServices: Sendable {
  281. /// Default transport services configuration.
  282. public static let defaults = Self()
  283. @inlinable
  284. public static func with(_ configure: (inout Self) -> Void) -> Self {
  285. var configuration = Self.defaults
  286. configure(&configuration)
  287. return configuration
  288. }
  289. /// A closure allowing to customise the `NWParameters` used when establishing a connection using `NIOTransportServices`.
  290. @available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *)
  291. public var nwParametersConfigurator: (@Sendable (NWParameters) -> Void)? {
  292. get {
  293. self._nwParametersConfigurator as! (@Sendable (NWParameters) -> Void)?
  294. }
  295. set {
  296. self._nwParametersConfigurator = newValue
  297. }
  298. }
  299. private var _nwParametersConfigurator: (any Sendable)?
  300. }
  301. }
  302. #endif // canImport(Network)
  303. /// The ID of a connection in the connection pool.
  304. public struct GRPCConnectionID: Hashable, Sendable, CustomStringConvertible {
  305. private enum Value: Sendable, Hashable {
  306. case managerID(ConnectionManagerID)
  307. case uuid(UUID)
  308. }
  309. private let id: Value
  310. public var description: String {
  311. switch self.id {
  312. case .managerID(let id):
  313. return String(describing: id)
  314. case .uuid(let uuid):
  315. return String(describing: uuid)
  316. }
  317. }
  318. internal init(_ id: ConnectionManagerID) {
  319. self.id = .managerID(id)
  320. }
  321. /// Create a new unique connection ID.
  322. ///
  323. /// Normally you don't have to create connection IDs, gRPC will create them on your behalf.
  324. /// However creating them manually is useful when testing the ``GRPCConnectionPoolDelegate``.
  325. public init() {
  326. self.id = .uuid(UUID())
  327. }
  328. }
  329. /// A delegate for the connection pool which is notified of various lifecycle events.
  330. ///
  331. /// All functions must execute quickly and may be executed on arbitrary threads. The implementor is
  332. /// responsible for ensuring thread safety.
  333. public protocol GRPCConnectionPoolDelegate: Sendable {
  334. /// A new connection was created with the given ID and added to the pool. The connection is not
  335. /// yet active (or connecting).
  336. ///
  337. /// In most cases ``startedConnecting(id:)`` will be the next function called for the given
  338. /// connection but ``connectionRemoved(id:)`` may also be called.
  339. func connectionAdded(id: GRPCConnectionID)
  340. /// The connection with the given ID was removed from the pool.
  341. func connectionRemoved(id: GRPCConnectionID)
  342. /// The connection with the given ID has started trying to establish a connection. The outcome
  343. /// of the connection will be reported as either ``connectSucceeded(id:streamCapacity:)`` or
  344. /// ``connectFailed(id:error:)``.
  345. func startedConnecting(id: GRPCConnectionID)
  346. /// A connection attempt failed with the given error. After some period of
  347. /// time ``startedConnecting(id:)`` may be called again.
  348. func connectFailed(id: GRPCConnectionID, error: Error)
  349. /// A connection was established on the connection with the given ID. `streamCapacity` streams are
  350. /// available to use on the connection. The maximum number of available streams may change over
  351. /// time and is reported via ``connectionUtilizationChanged(id:streamsUsed:streamCapacity:)``. The
  352. func connectSucceeded(id: GRPCConnectionID, streamCapacity: Int)
  353. /// The utilization of the connection changed; a stream may have been used, returned or the
  354. /// maximum number of concurrent streams available on the connection changed.
  355. func connectionUtilizationChanged(id: GRPCConnectionID, streamsUsed: Int, streamCapacity: Int)
  356. /// The remote peer is quiescing the connection: no new streams will be created on it. The
  357. /// connection will eventually be closed and removed from the pool.
  358. func connectionQuiescing(id: GRPCConnectionID)
  359. /// The connection was closed. The connection may be established again in the future (notified
  360. /// via ``startedConnecting(id:)``).
  361. func connectionClosed(id: GRPCConnectionID, error: Error?)
  362. /// Stats about the current state of the connection pool.
  363. ///
  364. /// Each ``GRPCConnectionPoolStats`` includes the stats for a sub-pool. Each sub-pool is tied
  365. /// to an `EventLoop`.
  366. ///
  367. /// Unlike the other delegate methods, this is called periodically based on the value
  368. /// of ``GRPCChannelPool/Configuration/statsPeriod``.
  369. func connectionPoolStats(_ stats: [GRPCSubPoolStats], id: GRPCConnectionPoolID)
  370. }
  371. extension GRPCConnectionPoolDelegate {
  372. public func connectionPoolStats(_ stats: [GRPCSubPoolStats], id: GRPCConnectionPoolID) {
  373. // Default conformance to avoid breaking changes.
  374. }
  375. }
  376. public struct GRPCSubPoolStats: Sendable, Hashable {
  377. public struct ConnectionStates: Sendable, Hashable {
  378. /// The number of idle connections.
  379. public var idle: Int
  380. /// The number of connections trying to establish a connection.
  381. public var connecting: Int
  382. /// The number of connections which are ready to use.
  383. public var ready: Int
  384. /// The number of connections which are backing off waiting to attempt to connect.
  385. public var transientFailure: Int
  386. public init() {
  387. self.idle = 0
  388. self.connecting = 0
  389. self.ready = 0
  390. self.transientFailure = 0
  391. }
  392. }
  393. /// The ID of the subpool.
  394. public var id: GRPCSubPoolID
  395. /// Counts of connection states.
  396. public var connectionStates: ConnectionStates
  397. /// The number of streams currently being used.
  398. public var streamsInUse: Int
  399. /// The number of streams which are currently free to use.
  400. ///
  401. /// The sum of this value and `streamsInUse` gives the capacity of the pool.
  402. public var streamsFreeToUse: Int
  403. /// The number of RPCs currently waiting for a stream.
  404. ///
  405. /// RPCs waiting for a stream are also known as 'waiters'.
  406. public var rpcsWaiting: Int
  407. public init(id: GRPCSubPoolID) {
  408. self.id = id
  409. self.connectionStates = ConnectionStates()
  410. self.streamsInUse = 0
  411. self.streamsFreeToUse = 0
  412. self.rpcsWaiting = 0
  413. }
  414. }