GRPCChannelPool.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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: Sendable {
  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. @preconcurrency
  155. public var debugChannelInitializer: (@Sendable (Channel) -> EventLoopFuture<Void>)?
  156. /// An error delegate which is called when errors are caught.
  157. public var errorDelegate: ClientErrorDelegate?
  158. /// A delegate which will be notified about changes to the state of connections managed by the
  159. /// pool.
  160. public var delegate: GRPCConnectionPoolDelegate?
  161. /// A logger used for background activity, such as connection state changes.
  162. public var backgroundActivityLogger = Logger(
  163. label: "io.grpc",
  164. factory: { _ in
  165. return SwiftLogNoOpLogHandler()
  166. }
  167. )
  168. }
  169. }
  170. extension GRPCChannelPool.Configuration {
  171. public struct TransportSecurity: Sendable {
  172. private init(_ configuration: GRPCTLSConfiguration?) {
  173. self.tlsConfiguration = configuration
  174. }
  175. /// The TLS configuration used. A `nil` value means that no TLS will be used and
  176. /// communication at the transport layer will be plaintext.
  177. public var tlsConfiguration: Optional<GRPCTLSConfiguration>
  178. /// Secure the transport layer with TLS.
  179. ///
  180. /// The TLS backend used depends on the value of `configuration`. See ``GRPCTLSConfiguration``
  181. /// for more details.
  182. ///
  183. /// > Important: the value of `configuration` **must** be compatible with
  184. /// > ``GRPCChannelPool/Configuration/eventLoopGroup``. See the documentation of
  185. /// > ``GRPCChannelPool/with(target:transportSecurity:eventLoopGroup:_:)`` for more details.
  186. public static func tls(_ configuration: GRPCTLSConfiguration) -> TransportSecurity {
  187. return TransportSecurity(configuration)
  188. }
  189. /// Insecure plaintext communication.
  190. public static let plaintext = TransportSecurity(nil)
  191. }
  192. }
  193. extension GRPCChannelPool.Configuration {
  194. public struct HTTP2: Hashable, Sendable {
  195. private static let allowedTargetWindowSizes = (1 ... Int(Int32.max))
  196. private static let allowedMaxFrameSizes = (1 << 14) ... ((1 << 24) - 1)
  197. /// Default HTTP/2 configuration.
  198. public static let defaults = HTTP2()
  199. @inlinable
  200. public static func with(_ configure: (inout HTTP2) -> Void) -> HTTP2 {
  201. var configuration = Self.defaults
  202. configure(&configuration)
  203. return configuration
  204. }
  205. /// The HTTP/2 max frame size. Defaults to 8MB. Values are clamped between 2^14 and 2^24-1
  206. /// octets inclusive (RFC 7540 § 4.2).
  207. public var targetWindowSize = 8 * 1024 * 1024 {
  208. didSet {
  209. self.targetWindowSize = self.targetWindowSize.clamped(to: Self.allowedTargetWindowSizes)
  210. }
  211. }
  212. /// The HTTP/2 max frame size. Defaults to 16384. Value is clamped between 2^14 and 2^24-1
  213. /// octets inclusive (the minimum and maximum allowable values - HTTP/2 RFC 7540 4.2).
  214. public var maxFrameSize: Int = 16384 {
  215. didSet {
  216. self.maxFrameSize = self.maxFrameSize.clamped(to: Self.allowedMaxFrameSizes)
  217. }
  218. }
  219. }
  220. }
  221. extension GRPCChannelPool.Configuration {
  222. public struct ConnectionPool: Hashable, Sendable {
  223. /// Default connection pool configuration.
  224. public static let defaults = ConnectionPool()
  225. @inlinable
  226. public static func with(_ configure: (inout ConnectionPool) -> Void) -> ConnectionPool {
  227. var configuration = Self.defaults
  228. configure(&configuration)
  229. return configuration
  230. }
  231. /// The maximum number of connections per `EventLoop` that may be created at a given time.
  232. ///
  233. /// Defaults to 1.
  234. public var connectionsPerEventLoop: Int = 1
  235. /// The maximum number of callers which may be waiting for a stream at any given time on a
  236. /// given `EventLoop`.
  237. ///
  238. /// Any requests for a stream which would cause this limit to be exceeded will be failed
  239. /// immediately.
  240. ///
  241. /// Defaults to 100.
  242. public var maxWaitersPerEventLoop: Int = 100
  243. /// The maximum amount of time a caller is willing to wait for a stream for before timing out.
  244. ///
  245. /// Defaults to 30 seconds.
  246. public var maxWaitTime: TimeAmount = .seconds(30)
  247. /// The threshold which, if exceeded, when creating a stream determines whether the pool will
  248. /// establish another connection (if doing so will not violate ``connectionsPerEventLoop``).
  249. ///
  250. /// The 'load' is calculated as the ratio of demand for streams (the sum of the number of
  251. /// waiters and the number of reserved streams) and the total number of streams which each
  252. /// thread _could support.
  253. public var reservationLoadThreshold: Double = 0.9
  254. }
  255. }
  256. /// The ID of a connection in the connection pool.
  257. public struct GRPCConnectionID: Hashable, Sendable, CustomStringConvertible {
  258. private let id: ConnectionManagerID
  259. public var description: String {
  260. return String(describing: self.id)
  261. }
  262. internal init(_ id: ConnectionManagerID) {
  263. self.id = id
  264. }
  265. }
  266. /// A delegate for the connection pool which is notified of various lifecycle events.
  267. ///
  268. /// All functions must execute quickly and may be executed on arbitrary threads. The implementor is
  269. /// responsible for ensuring thread safety.
  270. public protocol GRPCConnectionPoolDelegate: Sendable {
  271. /// A new connection was created with the given ID and added to the pool. The connection is not
  272. /// yet active (or connecting).
  273. ///
  274. /// In most cases ``startedConnecting(id:)`` will be the next function called for the given
  275. /// connection but ``connectionRemoved(id:)`` may also be called.
  276. func connectionAdded(id: GRPCConnectionID)
  277. /// The connection with the given ID was removed from the pool.
  278. func connectionRemoved(id: GRPCConnectionID)
  279. /// The connection with the given ID has started trying to establish a connection. The outcome
  280. /// of the connection will be reported as either ``connectSucceeded(id:streamCapacity:)`` or
  281. /// ``connectFailed(id:error:)``.
  282. func startedConnecting(id: GRPCConnectionID)
  283. /// A connection attempt failed with the given error. After some period of
  284. /// time ``startedConnecting(id:)`` may be called again.
  285. func connectFailed(id: GRPCConnectionID, error: Error)
  286. /// A connection was established on the connection with the given ID. `streamCapacity` streams are
  287. /// available to use on the connection. The maximum number of available streams may change over
  288. /// time and is reported via ``connectionUtilizationChanged(id:streamsUsed:streamCapacity:)``. The
  289. func connectSucceeded(id: GRPCConnectionID, streamCapacity: Int)
  290. /// The utlization of the connection changed; a stream may have been used, returned or the
  291. /// maximum number of concurrent streams available on the connection changed.
  292. func connectionUtilizationChanged(id: GRPCConnectionID, streamsUsed: Int, streamCapacity: Int)
  293. /// The remote peer is quiescing the connection: no new streams will be created on it. The
  294. /// connection will eventually be closed and removed from the pool.
  295. func connectionQuiescing(id: GRPCConnectionID)
  296. /// The connection was closed. The connection may be established again in the future (notified
  297. /// via ``startedConnecting(id:)``).
  298. func connectionClosed(id: GRPCConnectionID, error: Error?)
  299. }