PooledChannel.swift 8.6 KB

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