HTTP2ClientTransport+Posix.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. private let channel: GRPCChannel
  58. /// Creates a new NIOPosix-based HTTP/2 client transport.
  59. ///
  60. /// - Parameters:
  61. /// - target: A target to resolve.
  62. /// - transportSecurity: The configuration for securing network traffic.
  63. /// - config: Configuration for the transport.
  64. /// - resolverRegistry: A registry of resolver factories.
  65. /// - serviceConfig: Service config controlling how the transport should establish and
  66. /// load-balance connections.
  67. /// - eventLoopGroup: The underlying NIO `EventLoopGroup` to run connections on. This must
  68. /// be a `MultiThreadedEventLoopGroup` or an `EventLoop` from
  69. /// a `MultiThreadedEventLoopGroup`.
  70. /// - Throws: When no suitable resolver could be found for the `target`.
  71. public init(
  72. target: any ResolvableTarget,
  73. transportSecurity: TransportSecurity,
  74. config: Config = .defaults,
  75. resolverRegistry: NameResolverRegistry = .defaults,
  76. serviceConfig: ServiceConfig = ServiceConfig(),
  77. eventLoopGroup: any EventLoopGroup = .singletonMultiThreadedEventLoopGroup
  78. ) throws {
  79. guard let resolver = resolverRegistry.makeResolver(for: target) else {
  80. throw RuntimeError(
  81. code: .transportError,
  82. message: """
  83. No suitable resolvers to resolve '\(target)'. You must make sure that the resolver \
  84. registry has a suitable name resolver factory registered for the given target.
  85. """
  86. )
  87. }
  88. self.channel = GRPCChannel(
  89. resolver: resolver,
  90. connector: try Connector(
  91. eventLoopGroup: eventLoopGroup,
  92. config: config,
  93. transportSecurity: transportSecurity
  94. ),
  95. config: GRPCChannel.Config(posix: config),
  96. defaultServiceConfig: serviceConfig
  97. )
  98. }
  99. public var retryThrottle: RetryThrottle? {
  100. self.channel.retryThrottle
  101. }
  102. public func connect() async {
  103. await self.channel.connect()
  104. }
  105. public func config(forMethod descriptor: MethodDescriptor) -> MethodConfig? {
  106. self.channel.config(forMethod: descriptor)
  107. }
  108. public func beginGracefulShutdown() {
  109. self.channel.beginGracefulShutdown()
  110. }
  111. public func withStream<T: Sendable>(
  112. descriptor: MethodDescriptor,
  113. options: CallOptions,
  114. _ closure: (RPCStream<Inbound, Outbound>) async throws -> T
  115. ) async throws -> T {
  116. try await self.channel.withStream(descriptor: descriptor, options: options, closure)
  117. }
  118. }
  119. }
  120. extension HTTP2ClientTransport.Posix {
  121. struct Connector: HTTP2Connector {
  122. private let config: HTTP2ClientTransport.Posix.Config
  123. private let eventLoopGroup: any EventLoopGroup
  124. private let sslContext: NIOSSLContext?
  125. private let isPlainText: Bool
  126. init(
  127. eventLoopGroup: any EventLoopGroup,
  128. config: HTTP2ClientTransport.Posix.Config,
  129. transportSecurity: HTTP2ClientTransport.Posix.TransportSecurity
  130. ) throws {
  131. self.eventLoopGroup = eventLoopGroup
  132. self.config = config
  133. switch transportSecurity.wrapped {
  134. case .plaintext:
  135. self.sslContext = nil
  136. self.isPlainText = true
  137. case .tls(let tlsConfig):
  138. do {
  139. self.sslContext = try NIOSSLContext(configuration: TLSConfiguration(tlsConfig))
  140. self.isPlainText = false
  141. } catch {
  142. throw RuntimeError(
  143. code: .transportError,
  144. message: "Couldn't create SSL context, check your TLS configuration.",
  145. cause: error
  146. )
  147. }
  148. }
  149. }
  150. func establishConnection(
  151. to address: GRPCNIOTransportCore.SocketAddress,
  152. authority: String?
  153. ) async throws -> HTTP2Connection {
  154. let (channel, multiplexer) = try await ClientBootstrap(
  155. group: self.eventLoopGroup
  156. ).connect(to: address) { channel in
  157. channel.eventLoop.makeCompletedFuture {
  158. if let sslContext = self.sslContext {
  159. try channel.pipeline.syncOperations.addHandler(
  160. NIOSSLClientHandler(
  161. context: sslContext,
  162. serverHostname: authority
  163. )
  164. )
  165. }
  166. return try channel.pipeline.syncOperations.configureGRPCClientPipeline(
  167. channel: channel,
  168. config: GRPCChannel.Config(posix: self.config)
  169. )
  170. }
  171. }
  172. return HTTP2Connection(
  173. channel: channel,
  174. multiplexer: multiplexer,
  175. isPlaintext: self.isPlainText
  176. )
  177. }
  178. }
  179. }
  180. extension HTTP2ClientTransport.Posix {
  181. public struct Config: Sendable {
  182. /// Configuration for HTTP/2 connections.
  183. public var http2: HTTP2ClientTransport.Config.HTTP2
  184. /// Configuration for backoff used when establishing a connection.
  185. public var backoff: HTTP2ClientTransport.Config.Backoff
  186. /// Configuration for connection management.
  187. public var connection: HTTP2ClientTransport.Config.Connection
  188. /// Compression configuration.
  189. public var compression: HTTP2ClientTransport.Config.Compression
  190. /// Creates a new connection configuration.
  191. ///
  192. /// - Parameters:
  193. /// - http2: HTTP2 configuration.
  194. /// - backoff: Backoff configuration.
  195. /// - connection: Connection configuration.
  196. /// - compression: Compression configuration.
  197. ///
  198. /// - SeeAlso: ``defaults(configure:)`` and ``defaults``.
  199. public init(
  200. http2: HTTP2ClientTransport.Config.HTTP2,
  201. backoff: HTTP2ClientTransport.Config.Backoff,
  202. connection: HTTP2ClientTransport.Config.Connection,
  203. compression: HTTP2ClientTransport.Config.Compression
  204. ) {
  205. self.http2 = http2
  206. self.connection = connection
  207. self.backoff = backoff
  208. self.compression = compression
  209. }
  210. /// Default configuration.
  211. public static var defaults: Self {
  212. Self.defaults()
  213. }
  214. /// Default values.
  215. ///
  216. /// - Parameters:
  217. /// - configure: A closure which allows you to modify the defaults before returning them.
  218. public static func defaults(
  219. configure: (_ config: inout Self) -> Void = { _ in }
  220. ) -> Self {
  221. var config = Self(
  222. http2: .defaults,
  223. backoff: .defaults,
  224. connection: .defaults,
  225. compression: .defaults
  226. )
  227. configure(&config)
  228. return config
  229. }
  230. }
  231. }
  232. extension GRPCChannel.Config {
  233. init(posix: HTTP2ClientTransport.Posix.Config) {
  234. self.init(
  235. http2: posix.http2,
  236. backoff: posix.backoff,
  237. connection: posix.connection,
  238. compression: posix.compression
  239. )
  240. }
  241. }
  242. extension ClientTransport where Self == HTTP2ClientTransport.Posix {
  243. /// Creates a new Posix based HTTP/2 client transport.
  244. ///
  245. /// - Parameters:
  246. /// - target: A target to resolve.
  247. /// - transportSecurity: The configuration for securing network traffic.
  248. /// - config: Configuration for the transport.
  249. /// - resolverRegistry: A registry of resolver factories.
  250. /// - serviceConfig: Service config controlling how the transport should establish and
  251. /// load-balance connections.
  252. /// - eventLoopGroup: The underlying NIO `EventLoopGroup` to run connections on. This must
  253. /// be a `MultiThreadedEventLoopGroup` or an `EventLoop` from
  254. /// a `MultiThreadedEventLoopGroup`.
  255. /// - Throws: When no suitable resolver could be found for the `target`.
  256. public static func http2NIOPosix(
  257. target: any ResolvableTarget,
  258. transportSecurity: HTTP2ClientTransport.Posix.TransportSecurity,
  259. config: HTTP2ClientTransport.Posix.Config = .defaults,
  260. resolverRegistry: NameResolverRegistry = .defaults,
  261. serviceConfig: ServiceConfig = ServiceConfig(),
  262. eventLoopGroup: any EventLoopGroup = .singletonMultiThreadedEventLoopGroup
  263. ) throws -> Self {
  264. return try HTTP2ClientTransport.Posix(
  265. target: target,
  266. transportSecurity: transportSecurity,
  267. config: config,
  268. resolverRegistry: resolverRegistry,
  269. serviceConfig: serviceConfig,
  270. eventLoopGroup: eventLoopGroup
  271. )
  272. }
  273. }