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