PooledChannel.swift 7.2 KB

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