HTTP2ClientTransport+Posix.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. private let isPlainText: Bool
  121. init(eventLoopGroup: any EventLoopGroup, config: HTTP2ClientTransport.Posix.Config) throws {
  122. self.eventLoopGroup = eventLoopGroup
  123. self.config = config
  124. switch self.config.transportSecurity.wrapped {
  125. case .plaintext:
  126. self.sslContext = nil
  127. self.serverHostname = nil
  128. self.isPlainText = true
  129. case .tls(let tlsConfig):
  130. do {
  131. self.sslContext = try NIOSSLContext(configuration: TLSConfiguration(tlsConfig))
  132. self.serverHostname = tlsConfig.serverHostname
  133. self.isPlainText = false
  134. } catch {
  135. throw RuntimeError(
  136. code: .transportError,
  137. message: "Couldn't create SSL context, check your TLS configuration.",
  138. cause: error
  139. )
  140. }
  141. }
  142. }
  143. func establishConnection(
  144. to address: GRPCNIOTransportCore.SocketAddress
  145. ) async throws -> HTTP2Connection {
  146. let (channel, multiplexer) = try await ClientBootstrap(
  147. group: self.eventLoopGroup
  148. ).connect(to: address) { channel in
  149. channel.eventLoop.makeCompletedFuture {
  150. if let sslContext = self.sslContext {
  151. try channel.pipeline.syncOperations.addHandler(
  152. NIOSSLClientHandler(
  153. context: sslContext,
  154. serverHostname: self.serverHostname
  155. )
  156. )
  157. }
  158. return try channel.pipeline.syncOperations.configureGRPCClientPipeline(
  159. channel: channel,
  160. config: GRPCChannel.Config(posix: self.config)
  161. )
  162. }
  163. }
  164. return HTTP2Connection(
  165. channel: channel,
  166. multiplexer: multiplexer,
  167. isPlaintext: self.isPlainText
  168. )
  169. }
  170. }
  171. }
  172. extension HTTP2ClientTransport.Posix {
  173. public struct Config: Sendable {
  174. /// Configuration for HTTP/2 connections.
  175. public var http2: HTTP2ClientTransport.Config.HTTP2
  176. /// Configuration for backoff used when establishing a connection.
  177. public var backoff: HTTP2ClientTransport.Config.Backoff
  178. /// Configuration for connection management.
  179. public var connection: HTTP2ClientTransport.Config.Connection
  180. /// Compression configuration.
  181. public var compression: HTTP2ClientTransport.Config.Compression
  182. /// The transport's security.
  183. public var transportSecurity: TransportSecurity
  184. /// Creates a new connection configuration.
  185. ///
  186. /// - Parameters:
  187. /// - http2: HTTP2 configuration.
  188. /// - backoff: Backoff configuration.
  189. /// - connection: Connection configuration.
  190. /// - compression: Compression configuration.
  191. /// - transportSecurity: The transport's security configuration.
  192. ///
  193. /// - SeeAlso: ``defaults(transportSecurity:configure:)``
  194. public init(
  195. http2: HTTP2ClientTransport.Config.HTTP2,
  196. backoff: HTTP2ClientTransport.Config.Backoff,
  197. connection: HTTP2ClientTransport.Config.Connection,
  198. compression: HTTP2ClientTransport.Config.Compression,
  199. transportSecurity: TransportSecurity
  200. ) {
  201. self.http2 = http2
  202. self.connection = connection
  203. self.backoff = backoff
  204. self.compression = compression
  205. self.transportSecurity = transportSecurity
  206. }
  207. /// Default values.
  208. ///
  209. /// - Parameters:
  210. /// - transportSecurity: The security settings applied to the transport.
  211. /// - configure: A closure which allows you to modify the defaults before returning them.
  212. public static func defaults(
  213. transportSecurity: TransportSecurity,
  214. configure: (_ config: inout Self) -> Void = { _ in }
  215. ) -> Self {
  216. var config = Self(
  217. http2: .defaults,
  218. backoff: .defaults,
  219. connection: .defaults,
  220. compression: .defaults,
  221. transportSecurity: transportSecurity
  222. )
  223. configure(&config)
  224. return config
  225. }
  226. }
  227. }
  228. extension GRPCChannel.Config {
  229. init(posix: HTTP2ClientTransport.Posix.Config) {
  230. self.init(
  231. http2: posix.http2,
  232. backoff: posix.backoff,
  233. connection: posix.connection,
  234. compression: posix.compression
  235. )
  236. }
  237. }
  238. extension ClientTransport where Self == HTTP2ClientTransport.Posix {
  239. /// Creates a new Posix based HTTP/2 client transport.
  240. ///
  241. /// - Parameters:
  242. /// - target: A target to resolve.
  243. /// - config: Configuration for the transport.
  244. /// - resolverRegistry: A registry of resolver factories.
  245. /// - serviceConfig: Service config controlling how the transport should establish and
  246. /// load-balance connections.
  247. /// - eventLoopGroup: The underlying NIO `EventLoopGroup` to run connections on. This must
  248. /// be a `MultiThreadedEventLoopGroup` or an `EventLoop` from
  249. /// a `MultiThreadedEventLoopGroup`.
  250. /// - Throws: When no suitable resolver could be found for the `target`.
  251. public static func http2NIOPosix(
  252. target: any ResolvableTarget,
  253. config: HTTP2ClientTransport.Posix.Config,
  254. resolverRegistry: NameResolverRegistry = .defaults,
  255. serviceConfig: ServiceConfig = ServiceConfig(),
  256. eventLoopGroup: any EventLoopGroup = .singletonMultiThreadedEventLoopGroup
  257. ) throws -> Self {
  258. return try HTTP2ClientTransport.Posix(
  259. target: target,
  260. config: config,
  261. resolverRegistry: resolverRegistry,
  262. serviceConfig: serviceConfig,
  263. eventLoopGroup: eventLoopGroup
  264. )
  265. }
  266. }