PooledChannel.swift 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. tlsMode: tlsMode,
  83. tlsConfiguration: configuration.transportSecurity.tlsConfiguration,
  84. httpTargetWindowSize: configuration.http2.targetWindowSize,
  85. httpMaxFrameSize: configuration.http2.maxFrameSize,
  86. httpMaxResetStreams: configuration.http2.maxResetStreams,
  87. errorDelegate: configuration.errorDelegate,
  88. debugChannelInitializer: configuration.debugChannelInitializer,
  89. nwParametersConfigurator: configuration.transportServices.nwParametersConfigurator
  90. )
  91. } else {
  92. provider = DefaultChannelProvider(
  93. connectionTarget: configuration.target,
  94. connectionKeepalive: configuration.keepalive,
  95. connectionIdleTimeout: configuration.idleTimeout,
  96. tlsMode: tlsMode,
  97. tlsConfiguration: configuration.transportSecurity.tlsConfiguration,
  98. httpTargetWindowSize: configuration.http2.targetWindowSize,
  99. httpMaxFrameSize: configuration.http2.maxFrameSize,
  100. httpMaxResetStreams: configuration.http2.maxResetStreams,
  101. errorDelegate: configuration.errorDelegate,
  102. debugChannelInitializer: configuration.debugChannelInitializer
  103. )
  104. }
  105. #else
  106. provider = DefaultChannelProvider(
  107. connectionTarget: configuration.target,
  108. connectionKeepalive: configuration.keepalive,
  109. connectionIdleTimeout: configuration.idleTimeout,
  110. tlsMode: tlsMode,
  111. tlsConfiguration: configuration.transportSecurity.tlsConfiguration,
  112. httpTargetWindowSize: configuration.http2.targetWindowSize,
  113. httpMaxFrameSize: configuration.http2.maxFrameSize,
  114. httpMaxResetStreams: configuration.http2.maxResetStreams,
  115. errorDelegate: configuration.errorDelegate,
  116. debugChannelInitializer: configuration.debugChannelInitializer
  117. )
  118. #endif
  119. self._pool = PoolManager.makeInitializedPoolManager(
  120. using: configuration.eventLoopGroup,
  121. perPoolConfiguration: .init(
  122. maxConnections: configuration.connectionPool.connectionsPerEventLoop,
  123. maxWaiters: configuration.connectionPool.maxWaitersPerEventLoop,
  124. minConnections: configuration.connectionPool.minConnectionsPerEventLoop,
  125. loadThreshold: configuration.connectionPool.reservationLoadThreshold,
  126. assumedMaxConcurrentStreams: 100,
  127. connectionBackoff: configuration.connectionBackoff,
  128. channelProvider: provider,
  129. delegate: configuration.delegate,
  130. statsPeriod: configuration.statsPeriod
  131. ),
  132. logger: configuration.backgroundActivityLogger
  133. )
  134. }
  135. @inlinable
  136. internal func _makeStreamChannel(
  137. callOptions: CallOptions
  138. ) -> (EventLoopFuture<Channel>, EventLoop) {
  139. let preferredEventLoop = callOptions.eventLoopPreference.exact
  140. let connectionWaitDeadline = NIODeadline.now() + self._configuration.connectionPool.maxWaitTime
  141. let deadline = min(callOptions.timeLimit.makeDeadline(), connectionWaitDeadline)
  142. let streamChannel = self._pool.makeStream(
  143. preferredEventLoop: preferredEventLoop,
  144. deadline: deadline,
  145. logger: callOptions.logger
  146. ) { channel in
  147. return channel.eventLoop.makeSucceededVoidFuture()
  148. }
  149. return (streamChannel.futureResult, preferredEventLoop ?? streamChannel.eventLoop)
  150. }
  151. // MARK: GRPCChannel conformance
  152. @inlinable
  153. internal func makeCall<Request, Response>(
  154. path: String,
  155. type: GRPCCallType,
  156. callOptions: CallOptions,
  157. interceptors: [ClientInterceptor<Request, Response>]
  158. ) -> Call<Request, Response> where Request: Message, Response: Message {
  159. var callOptions = callOptions
  160. if let requestID = callOptions.requestIDProvider.requestID() {
  161. callOptions.applyRequestID(requestID)
  162. }
  163. let (stream, eventLoop) = self._makeStreamChannel(callOptions: callOptions)
  164. return Call(
  165. path: path,
  166. type: type,
  167. eventLoop: eventLoop,
  168. options: callOptions,
  169. interceptors: interceptors,
  170. transportFactory: .http2(
  171. channel: stream,
  172. authority: self._authority,
  173. scheme: self._scheme,
  174. maximumReceiveMessageLength: self._configuration.maximumReceiveMessageLength,
  175. errorDelegate: self._configuration.errorDelegate
  176. )
  177. )
  178. }
  179. @inlinable
  180. internal func makeCall<Request, Response>(
  181. path: String,
  182. type: GRPCCallType,
  183. callOptions: CallOptions,
  184. interceptors: [ClientInterceptor<Request, Response>]
  185. ) -> Call<Request, Response> where Request: GRPCPayload, Response: GRPCPayload {
  186. var callOptions = callOptions
  187. if let requestID = callOptions.requestIDProvider.requestID() {
  188. callOptions.applyRequestID(requestID)
  189. }
  190. let (stream, eventLoop) = self._makeStreamChannel(callOptions: callOptions)
  191. return Call(
  192. path: path,
  193. type: type,
  194. eventLoop: eventLoop,
  195. options: callOptions,
  196. interceptors: interceptors,
  197. transportFactory: .http2(
  198. channel: stream,
  199. authority: self._authority,
  200. scheme: self._scheme,
  201. maximumReceiveMessageLength: self._configuration.maximumReceiveMessageLength,
  202. errorDelegate: self._configuration.errorDelegate
  203. )
  204. )
  205. }
  206. @inlinable
  207. internal func close(promise: EventLoopPromise<Void>) {
  208. self._pool.shutdown(mode: .forceful, promise: promise)
  209. }
  210. @inlinable
  211. internal func close() -> EventLoopFuture<Void> {
  212. let promise = self._configuration.eventLoopGroup.next().makePromise(of: Void.self)
  213. self.close(promise: promise)
  214. return promise.futureResult
  215. }
  216. @usableFromInline
  217. internal func closeGracefully(deadline: NIODeadline, promise: EventLoopPromise<Void>) {
  218. self._pool.shutdown(mode: .graceful(deadline), promise: promise)
  219. }
  220. }
  221. extension CallOptions {
  222. @usableFromInline
  223. mutating func applyRequestID(_ requestID: String) {
  224. self.logger[metadataKey: MetadataKey.requestID] = "\(requestID)"
  225. // Add the request ID header too.
  226. if let requestIDHeader = self.requestIDHeader {
  227. self.customMetadata.add(name: requestIDHeader, value: requestID)
  228. }
  229. }
  230. }