HTTP2ClientTransport+Posix.swift 10 KB

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