PooledChannel.swift 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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 NIOHTTP2
  19. import SwiftProtobuf
  20. #if canImport(NIOSSL)
  21. import NIOSSL
  22. #endif
  23. @usableFromInline
  24. internal final class PooledChannel: GRPCChannel {
  25. @usableFromInline
  26. internal let _configuration: GRPCChannelPool.Configuration
  27. @usableFromInline
  28. internal let _pool: PoolManager
  29. @usableFromInline
  30. internal let _authority: String
  31. @usableFromInline
  32. internal let _scheme: String
  33. @inlinable
  34. internal init(configuration: GRPCChannelPool.Configuration) throws {
  35. self._configuration = configuration
  36. self._authority = configuration.target.host
  37. let tlsMode: DefaultChannelProvider.TLSMode
  38. let scheme: String
  39. if let tlsConfiguration = configuration.transportSecurity.tlsConfiguration {
  40. scheme = "https"
  41. #if canImport(NIOSSL)
  42. if let sslContext = try tlsConfiguration.makeNIOSSLContext() {
  43. tlsMode = .configureWithNIOSSL(.success(sslContext))
  44. } else {
  45. #if canImport(Network)
  46. // - TLS is configured
  47. // - NIOSSL is available but we aren't using it
  48. // - Network.framework is available, we MUST be using that.
  49. tlsMode = .configureWithNetworkFramework
  50. #else
  51. // - TLS is configured
  52. // - NIOSSL is available but we aren't using it
  53. // - Network.framework is not available
  54. // NIOSSL or Network.framework must be available as TLS is configured.
  55. fatalError()
  56. #endif
  57. }
  58. #elseif canImport(Network)
  59. // - TLS is configured
  60. // - NIOSSL is not available
  61. // - Network.framework is available, we MUST be using that.
  62. tlsMode = .configureWithNetworkFramework
  63. #else
  64. // - TLS is configured
  65. // - NIOSSL is not available
  66. // - Network.framework is not available
  67. // NIOSSL or Network.framework must be available as TLS is configured.
  68. fatalError()
  69. #endif // canImport(NIOSSL)
  70. } else {
  71. scheme = "http"
  72. tlsMode = .disabled
  73. }
  74. self._scheme = scheme
  75. let provider: DefaultChannelProvider
  76. #if canImport(Network)
  77. if #available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *) {
  78. provider = DefaultChannelProvider(
  79. connectionTarget: configuration.target,
  80. connectionKeepalive: configuration.keepalive,
  81. connectionIdleTimeout: configuration.idleTimeout,
  82. connectionMaxAge: configuration.maxConnectionAge,
  83. tlsMode: tlsMode,
  84. tlsConfiguration: configuration.transportSecurity.tlsConfiguration,
  85. httpTargetWindowSize: configuration.http2.targetWindowSize,
  86. httpMaxFrameSize: configuration.http2.maxFrameSize,
  87. httpMaxResetStreams: configuration.http2.maxResetStreams,
  88. errorDelegate: configuration.errorDelegate,
  89. debugChannelInitializer: configuration.debugChannelInitializer,
  90. nwParametersConfigurator: configuration.transportServices.nwParametersConfigurator
  91. )
  92. } else {
  93. provider = DefaultChannelProvider(
  94. connectionTarget: configuration.target,
  95. connectionKeepalive: configuration.keepalive,
  96. connectionIdleTimeout: configuration.idleTimeout,
  97. connectionMaxAge: configuration.maxConnectionAge,
  98. tlsMode: tlsMode,
  99. tlsConfiguration: configuration.transportSecurity.tlsConfiguration,
  100. httpTargetWindowSize: configuration.http2.targetWindowSize,
  101. httpMaxFrameSize: configuration.http2.maxFrameSize,
  102. httpMaxResetStreams: configuration.http2.maxResetStreams,
  103. errorDelegate: configuration.errorDelegate,
  104. debugChannelInitializer: configuration.debugChannelInitializer
  105. )
  106. }
  107. #else
  108. provider = DefaultChannelProvider(
  109. connectionTarget: configuration.target,
  110. connectionKeepalive: configuration.keepalive,
  111. connectionIdleTimeout: configuration.idleTimeout,
  112. connectionMaxAge: configuration.maxConnectionAge,
  113. tlsMode: tlsMode,
  114. tlsConfiguration: configuration.transportSecurity.tlsConfiguration,
  115. httpTargetWindowSize: configuration.http2.targetWindowSize,
  116. httpMaxFrameSize: configuration.http2.maxFrameSize,
  117. httpMaxResetStreams: configuration.http2.maxResetStreams,
  118. errorDelegate: configuration.errorDelegate,
  119. debugChannelInitializer: configuration.debugChannelInitializer
  120. )
  121. #endif
  122. self._pool = PoolManager.makeInitializedPoolManager(
  123. using: configuration.eventLoopGroup,
  124. perPoolConfiguration: .init(
  125. maxConnections: configuration.connectionPool.connectionsPerEventLoop,
  126. maxWaiters: configuration.connectionPool.maxWaitersPerEventLoop,
  127. minConnections: configuration.connectionPool.minConnectionsPerEventLoop,
  128. loadThreshold: configuration.connectionPool.reservationLoadThreshold,
  129. assumedMaxConcurrentStreams: 100,
  130. connectionBackoff: configuration.connectionBackoff,
  131. channelProvider: provider,
  132. delegate: configuration.delegate,
  133. statsPeriod: configuration.statsPeriod
  134. ),
  135. logger: configuration.backgroundActivityLogger
  136. )
  137. }
  138. @inlinable
  139. internal func _makeStreamChannel(
  140. callOptions: CallOptions
  141. ) -> (EventLoopFuture<Channel>, EventLoop) {
  142. let preferredEventLoop = callOptions.eventLoopPreference.exact
  143. let connectionWaitDeadline = NIODeadline.now() + self._configuration.connectionPool.maxWaitTime
  144. let deadline = min(callOptions.timeLimit.makeDeadline(), connectionWaitDeadline)
  145. let streamChannel = self._pool.makeStream(
  146. preferredEventLoop: preferredEventLoop,
  147. deadline: deadline,
  148. logger: callOptions.logger
  149. ) { channel in
  150. return channel.eventLoop.makeSucceededVoidFuture()
  151. }
  152. return (streamChannel.futureResult, preferredEventLoop ?? streamChannel.eventLoop)
  153. }
  154. // MARK: GRPCChannel conformance
  155. @inlinable
  156. internal func makeCall<Request, Response>(
  157. path: String,
  158. type: GRPCCallType,
  159. callOptions: CallOptions,
  160. interceptors: [ClientInterceptor<Request, Response>]
  161. ) -> Call<Request, Response> where Request: Message, Response: Message {
  162. var callOptions = callOptions
  163. if let requestID = callOptions.requestIDProvider.requestID() {
  164. callOptions.applyRequestID(requestID)
  165. }
  166. let (stream, eventLoop) = self._makeStreamChannel(callOptions: callOptions)
  167. return Call(
  168. path: path,
  169. type: type,
  170. eventLoop: eventLoop,
  171. options: callOptions,
  172. interceptors: interceptors,
  173. transportFactory: .http2(
  174. channel: stream,
  175. authority: self._authority,
  176. scheme: self._scheme,
  177. maximumReceiveMessageLength: self._configuration.maximumReceiveMessageLength,
  178. errorDelegate: self._configuration.errorDelegate
  179. )
  180. )
  181. }
  182. @inlinable
  183. internal func makeCall<Request, Response>(
  184. path: String,
  185. type: GRPCCallType,
  186. callOptions: CallOptions,
  187. interceptors: [ClientInterceptor<Request, Response>]
  188. ) -> Call<Request, Response> where Request: GRPCPayload, Response: GRPCPayload {
  189. var callOptions = callOptions
  190. if let requestID = callOptions.requestIDProvider.requestID() {
  191. callOptions.applyRequestID(requestID)
  192. }
  193. let (stream, eventLoop) = self._makeStreamChannel(callOptions: callOptions)
  194. return Call(
  195. path: path,
  196. type: type,
  197. eventLoop: eventLoop,
  198. options: callOptions,
  199. interceptors: interceptors,
  200. transportFactory: .http2(
  201. channel: stream,
  202. authority: self._authority,
  203. scheme: self._scheme,
  204. maximumReceiveMessageLength: self._configuration.maximumReceiveMessageLength,
  205. errorDelegate: self._configuration.errorDelegate
  206. )
  207. )
  208. }
  209. @inlinable
  210. internal func close(promise: EventLoopPromise<Void>) {
  211. self._pool.shutdown(mode: .forceful, promise: promise)
  212. }
  213. @inlinable
  214. internal func close() -> EventLoopFuture<Void> {
  215. let promise = self._configuration.eventLoopGroup.next().makePromise(of: Void.self)
  216. self.close(promise: promise)
  217. return promise.futureResult
  218. }
  219. @usableFromInline
  220. internal func closeGracefully(deadline: NIODeadline, promise: EventLoopPromise<Void>) {
  221. self._pool.shutdown(mode: .graceful(deadline), promise: promise)
  222. }
  223. }
  224. extension CallOptions {
  225. @usableFromInline
  226. mutating func applyRequestID(_ requestID: String) {
  227. self.logger[metadataKey: MetadataKey.requestID] = "\(requestID)"
  228. // Add the request ID header too.
  229. if let requestIDHeader = self.requestIDHeader {
  230. self.customMetadata.add(name: requestIDHeader, value: requestID)
  231. }
  232. }
  233. }