HTTP2ClientTransport+Posix.swift 11 KB

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