HTTP2ClientTransport+Posix.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /*
  2. * Copyright 2024, 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. public import GRPCCore
  17. public import GRPCNIOTransportCore // should be @usableFromInline
  18. public import NIOCore // has to be public because of EventLoopGroup param in init
  19. public import NIOPosix // has to be public because of default argument value in init
  20. private import NIOSSL
  21. @available(gRPCSwiftNIOTransport 2.0, *)
  22. extension HTTP2ClientTransport {
  23. /// A `ClientTransport` using HTTP/2 built on top of `NIOPosix`.
  24. ///
  25. /// This transport builds on top of SwiftNIO's Posix networking layer and is suitable for use
  26. /// on Linux and Darwin based platforms (macOS, iOS, etc.). However, it's *strongly* recommended
  27. /// that if you are targeting Darwin platforms then you should use the `NIOTS` variant of
  28. /// the `HTTP2ClientTransport`.
  29. ///
  30. /// To use this transport you need to provide a 'target' to connect to which will be resolved
  31. /// by an appropriate resolver from the resolver registry. By default the resolver registry can
  32. /// resolve DNS targets, IPv4 and IPv6 targets, Unix domain socket targets, and Virtual Socket
  33. /// targets. If you use a custom target you must also provide an appropriately configured
  34. /// registry.
  35. ///
  36. /// You can control various aspects of connection creation, management, security and RPC behavior via
  37. /// the ``Config``. Load balancing policies and other RPC specific behavior can be configured via
  38. /// the `ServiceConfig` (if it isn't provided by a resolver).
  39. ///
  40. /// Beyond creating the transport you don't need to interact with it directly, instead, pass it
  41. /// to a `GRPCClient`:
  42. ///
  43. /// ```swift
  44. /// try await withThrowingDiscardingTaskGroup { group in
  45. /// let transport = try HTTP2ClientTransport.Posix(
  46. /// target: .ipv4(host: "example.com"),
  47. /// transportSecurity: .plaintext
  48. /// )
  49. /// let client = GRPCClient(transport: transport)
  50. /// group.addTask {
  51. /// try await client.run()
  52. /// }
  53. ///
  54. /// // ...
  55. /// }
  56. /// ```
  57. public struct Posix: ClientTransport {
  58. public typealias Bytes = GRPCNIOTransportBytes
  59. private let channel: GRPCChannel
  60. /// Creates a new NIOPosix-based HTTP/2 client transport.
  61. ///
  62. /// - Parameters:
  63. /// - target: A target to resolve.
  64. /// - transportSecurity: The configuration for securing network traffic.
  65. /// - config: Configuration for the transport.
  66. /// - resolverRegistry: A registry of resolver factories.
  67. /// - serviceConfig: Service config controlling how the transport should establish and
  68. /// load-balance connections.
  69. /// - eventLoopGroup: The underlying NIO `EventLoopGroup` to run connections on. This must
  70. /// be a `MultiThreadedEventLoopGroup` or an `EventLoop` from
  71. /// a `MultiThreadedEventLoopGroup`.
  72. /// - Throws: When no suitable resolver could be found for the `target`.
  73. public init(
  74. target: any ResolvableTarget,
  75. transportSecurity: TransportSecurity,
  76. config: Config = .defaults,
  77. resolverRegistry: NameResolverRegistry = .defaults,
  78. serviceConfig: ServiceConfig = ServiceConfig(),
  79. eventLoopGroup: any EventLoopGroup = .singletonMultiThreadedEventLoopGroup
  80. ) throws {
  81. guard let resolver = resolverRegistry.makeResolver(for: target) else {
  82. throw RuntimeError(
  83. code: .transportError,
  84. message: """
  85. No suitable resolvers to resolve '\(target)'. You must make sure that the resolver \
  86. registry has a suitable name resolver factory registered for the given target.
  87. """
  88. )
  89. }
  90. self.channel = GRPCChannel(
  91. resolver: resolver,
  92. connector: try Connector(
  93. eventLoopGroup: eventLoopGroup,
  94. config: config,
  95. transportSecurity: transportSecurity
  96. ),
  97. config: GRPCChannel.Config(posix: config),
  98. defaultServiceConfig: serviceConfig
  99. )
  100. }
  101. public var retryThrottle: RetryThrottle? {
  102. self.channel.retryThrottle
  103. }
  104. public func connect() async throws {
  105. await self.channel.connect()
  106. }
  107. public func config(forMethod descriptor: MethodDescriptor) -> MethodConfig? {
  108. self.channel.config(forMethod: descriptor)
  109. }
  110. public func beginGracefulShutdown() {
  111. self.channel.beginGracefulShutdown()
  112. }
  113. public func withStream<T: Sendable>(
  114. descriptor: MethodDescriptor,
  115. options: CallOptions,
  116. _ closure: (RPCStream<Inbound, Outbound>, ClientContext) async throws -> T
  117. ) async throws -> T {
  118. try await self.channel.withStream(descriptor: descriptor, options: options, closure)
  119. }
  120. }
  121. }
  122. @available(gRPCSwiftNIOTransport 2.0, *)
  123. extension HTTP2ClientTransport.Posix {
  124. struct Connector: HTTP2Connector {
  125. private let config: HTTP2ClientTransport.Posix.Config
  126. private let eventLoopGroup: any EventLoopGroup
  127. private let sslContext: NIOSSLContext?
  128. private let isPlainText: Bool
  129. private let customVerificationCallback:
  130. (
  131. @Sendable (
  132. [NIOSSLCertificate], EventLoopPromise<NIOSSLVerificationResultWithMetadata>
  133. ) -> Void
  134. )?
  135. init(
  136. eventLoopGroup: any EventLoopGroup,
  137. config: HTTP2ClientTransport.Posix.Config,
  138. transportSecurity: HTTP2ClientTransport.Posix.TransportSecurity
  139. ) throws {
  140. self.eventLoopGroup = eventLoopGroup
  141. self.config = config
  142. switch transportSecurity.wrapped {
  143. case .plaintext:
  144. self.sslContext = nil
  145. self.isPlainText = true
  146. self.customVerificationCallback = nil
  147. case .tls(let tlsConfig):
  148. do {
  149. self.sslContext = try NIOSSLContext(configuration: TLSConfiguration(tlsConfig))
  150. self.isPlainText = false
  151. self.customVerificationCallback = tlsConfig.customVerificationCallback
  152. } catch {
  153. throw RuntimeError(
  154. code: .transportError,
  155. message: "Couldn't create SSL context, check your TLS configuration.",
  156. cause: error
  157. )
  158. }
  159. }
  160. }
  161. func establishConnection(
  162. to address: GRPCNIOTransportCore.SocketAddress,
  163. sniServerHostname: String?
  164. ) async throws -> HTTP2Connection {
  165. let (channel, multiplexer) = try await ClientBootstrap(
  166. group: self.eventLoopGroup
  167. ).connect(to: address) { channel in
  168. channel.eventLoop.makeCompletedFuture {
  169. if let sslContext = self.sslContext {
  170. if let customVerificationCallback = self.customVerificationCallback {
  171. try channel.pipeline.syncOperations.addHandler(
  172. NIOSSLClientHandler(
  173. context: sslContext,
  174. serverHostname: sniServerHostname,
  175. customVerificationCallbackWithMetadata: customVerificationCallback
  176. )
  177. )
  178. } else {
  179. try channel.pipeline.syncOperations.addHandler(
  180. NIOSSLClientHandler(
  181. context: sslContext,
  182. serverHostname: sniServerHostname
  183. )
  184. )
  185. }
  186. }
  187. return try channel.pipeline.syncOperations.configureGRPCClientPipeline(
  188. channel: channel,
  189. config: GRPCChannel.Config(posix: self.config)
  190. )
  191. }.runInitializerIfSet(
  192. self.config.channelDebuggingCallbacks.onCreateTCPConnection,
  193. on: channel
  194. )
  195. }
  196. return HTTP2Connection(
  197. channel: channel,
  198. multiplexer: multiplexer,
  199. isPlaintext: self.isPlainText,
  200. onCreateHTTP2Stream: self.config.channelDebuggingCallbacks.onCreateHTTP2Stream
  201. )
  202. }
  203. }
  204. }
  205. @available(gRPCSwiftNIOTransport 2.0, *)
  206. extension HTTP2ClientTransport.Posix {
  207. public struct Config: Sendable {
  208. /// Configuration for HTTP/2 connections.
  209. public var http2: HTTP2ClientTransport.Config.HTTP2
  210. /// Configuration for backoff used when establishing a connection.
  211. public var backoff: HTTP2ClientTransport.Config.Backoff
  212. /// Configuration for connection management.
  213. public var connection: HTTP2ClientTransport.Config.Connection
  214. /// Compression configuration.
  215. public var compression: HTTP2ClientTransport.Config.Compression
  216. /// Channel callbacks for debugging.
  217. public var channelDebuggingCallbacks: HTTP2ClientTransport.Config.ChannelDebuggingCallbacks
  218. /// Creates a new connection configuration.
  219. ///
  220. /// - Parameters:
  221. /// - http2: HTTP2 configuration.
  222. /// - backoff: Backoff configuration.
  223. /// - connection: Connection configuration.
  224. /// - compression: Compression configuration.
  225. /// - channelDebuggingCallbacks: Channel callbacks for debugging.
  226. ///
  227. /// - SeeAlso: ``defaults(configure:)`` and ``defaults``.
  228. public init(
  229. http2: HTTP2ClientTransport.Config.HTTP2,
  230. backoff: HTTP2ClientTransport.Config.Backoff,
  231. connection: HTTP2ClientTransport.Config.Connection,
  232. compression: HTTP2ClientTransport.Config.Compression,
  233. channelDebuggingCallbacks: HTTP2ClientTransport.Config.ChannelDebuggingCallbacks
  234. ) {
  235. self.http2 = http2
  236. self.connection = connection
  237. self.backoff = backoff
  238. self.compression = compression
  239. self.channelDebuggingCallbacks = channelDebuggingCallbacks
  240. }
  241. /// Default configuration.
  242. public static var defaults: Self {
  243. Self.defaults()
  244. }
  245. /// Default values.
  246. ///
  247. /// - Parameters:
  248. /// - configure: A closure which allows you to modify the defaults before returning them.
  249. public static func defaults(
  250. configure: (_ config: inout Self) -> Void = { _ in }
  251. ) -> Self {
  252. var config = Self(
  253. http2: .defaults,
  254. backoff: .defaults,
  255. connection: .defaults,
  256. compression: .defaults,
  257. channelDebuggingCallbacks: .defaults
  258. )
  259. configure(&config)
  260. return config
  261. }
  262. }
  263. }
  264. @available(gRPCSwiftNIOTransport 2.0, *)
  265. extension GRPCChannel.Config {
  266. init(posix: HTTP2ClientTransport.Posix.Config) {
  267. self.init(
  268. http2: posix.http2,
  269. backoff: posix.backoff,
  270. connection: posix.connection,
  271. compression: posix.compression
  272. )
  273. }
  274. }
  275. @available(gRPCSwiftNIOTransport 2.0, *)
  276. extension ClientTransport where Self == HTTP2ClientTransport.Posix {
  277. /// Creates a new Posix based HTTP/2 client transport.
  278. ///
  279. /// - Parameters:
  280. /// - target: A target to resolve.
  281. /// - transportSecurity: The configuration for securing network traffic.
  282. /// - config: Configuration for the transport.
  283. /// - resolverRegistry: A registry of resolver factories.
  284. /// - serviceConfig: Service config controlling how the transport should establish and
  285. /// load-balance connections.
  286. /// - eventLoopGroup: The underlying NIO `EventLoopGroup` to run connections on. This must
  287. /// be a `MultiThreadedEventLoopGroup` or an `EventLoop` from
  288. /// a `MultiThreadedEventLoopGroup`.
  289. /// - Throws: When no suitable resolver could be found for the `target`.
  290. public static func http2NIOPosix(
  291. target: any ResolvableTarget,
  292. transportSecurity: HTTP2ClientTransport.Posix.TransportSecurity,
  293. config: HTTP2ClientTransport.Posix.Config = .defaults,
  294. resolverRegistry: NameResolverRegistry = .defaults,
  295. serviceConfig: ServiceConfig = ServiceConfig(),
  296. eventLoopGroup: any EventLoopGroup = .singletonMultiThreadedEventLoopGroup
  297. ) throws -> Self {
  298. return try HTTP2ClientTransport.Posix(
  299. target: target,
  300. transportSecurity: transportSecurity,
  301. config: config,
  302. resolverRegistry: resolverRegistry,
  303. serviceConfig: serviceConfig,
  304. eventLoopGroup: eventLoopGroup
  305. )
  306. }
  307. }