PooledChannel.swift 7.1 KB

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