HTTP2ClientTransport+Posix.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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
  19. public import NIOPosix // has to be public because of default argument value in init
  20. #if canImport(NIOSSL)
  21. 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 platform (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 Posix 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. // Configure a connector.
  90. self.channel = GRPCChannel(
  91. resolver: resolver,
  92. connector: try Connector(eventLoopGroup: eventLoopGroup, config: config),
  93. config: GRPCChannel.Config(posix: config),
  94. defaultServiceConfig: serviceConfig
  95. )
  96. }
  97. public var retryThrottle: RetryThrottle? {
  98. self.channel.retryThrottle
  99. }
  100. public func connect() async {
  101. await self.channel.connect()
  102. }
  103. public func configuration(forMethod descriptor: MethodDescriptor) -> MethodConfig? {
  104. self.channel.configuration(forMethod: descriptor)
  105. }
  106. public func beginGracefulShutdown() {
  107. self.channel.beginGracefulShutdown()
  108. }
  109. public func withStream<T: Sendable>(
  110. descriptor: MethodDescriptor,
  111. options: CallOptions,
  112. _ closure: (RPCStream<Inbound, Outbound>) async throws -> T
  113. ) async throws -> T {
  114. try await self.channel.withStream(descriptor: descriptor, options: options, closure)
  115. }
  116. }
  117. }
  118. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  119. extension HTTP2ClientTransport.Posix {
  120. struct Connector: HTTP2Connector {
  121. private let config: HTTP2ClientTransport.Posix.Config
  122. private let eventLoopGroup: any EventLoopGroup
  123. #if canImport(NIOSSL)
  124. private let nioSSLContext: NIOSSLContext?
  125. private let serverHostname: String?
  126. #endif
  127. init(eventLoopGroup: any EventLoopGroup, config: HTTP2ClientTransport.Posix.Config) throws {
  128. self.eventLoopGroup = eventLoopGroup
  129. self.config = config
  130. #if canImport(NIOSSL)
  131. switch self.config.transportSecurity.wrapped {
  132. case .plaintext:
  133. self.nioSSLContext = nil
  134. self.serverHostname = nil
  135. case .tls(let tlsConfig):
  136. do {
  137. self.nioSSLContext = try NIOSSLContext(configuration: TLSConfiguration(tlsConfig))
  138. self.serverHostname = tlsConfig.serverHostname
  139. } catch {
  140. throw RuntimeError(
  141. code: .transportError,
  142. message: "Couldn't create SSL context, check your TLS configuration.",
  143. cause: error
  144. )
  145. }
  146. }
  147. #endif
  148. }
  149. func establishConnection(
  150. to address: GRPCHTTP2Core.SocketAddress
  151. ) async throws -> HTTP2Connection {
  152. let (channel, multiplexer) = try await ClientBootstrap(
  153. group: self.eventLoopGroup
  154. ).connect(to: address) { channel in
  155. channel.eventLoop.makeCompletedFuture {
  156. #if canImport(NIOSSL)
  157. if let nioSSLContext = self.nioSSLContext {
  158. try channel.pipeline.syncOperations.addHandler(
  159. NIOSSLClientHandler(
  160. context: nioSSLContext,
  161. serverHostname: self.serverHostname
  162. )
  163. )
  164. }
  165. #endif
  166. return try channel.pipeline.syncOperations.configureGRPCClientPipeline(
  167. channel: channel,
  168. config: GRPCChannel.Config(posix: self.config)
  169. )
  170. }
  171. }
  172. return HTTP2Connection(channel: channel, multiplexer: multiplexer, isPlaintext: true)
  173. }
  174. }
  175. }
  176. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  177. extension HTTP2ClientTransport.Posix {
  178. public struct Config: Sendable {
  179. /// Configuration for HTTP/2 connections.
  180. public var http2: HTTP2ClientTransport.Config.HTTP2
  181. /// Configuration for backoff used when establishing a connection.
  182. public var backoff: HTTP2ClientTransport.Config.Backoff
  183. /// Configuration for connection management.
  184. public var connection: HTTP2ClientTransport.Config.Connection
  185. /// Compression configuration.
  186. public var compression: HTTP2ClientTransport.Config.Compression
  187. /// The transport's security.
  188. public var transportSecurity: TransportSecurity
  189. /// Creates a new connection configuration.
  190. ///
  191. /// - Parameters:
  192. /// - http2: HTTP2 configuration.
  193. /// - backoff: Backoff configuration.
  194. /// - connection: Connection configuration.
  195. /// - compression: Compression configuration.
  196. /// - transportSecurity: The transport's security configuration.
  197. ///
  198. /// - SeeAlso: ``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. transportSecurity: TransportSecurity
  205. ) {
  206. self.http2 = http2
  207. self.connection = connection
  208. self.backoff = backoff
  209. self.compression = compression
  210. self.transportSecurity = transportSecurity
  211. }
  212. /// Default values.
  213. ///
  214. /// - Parameters:
  215. /// - transportSecurity: The security settings applied to the transport.
  216. /// - configure: A closure which allows you to modify the defaults before returning them.
  217. public static func defaults(
  218. transportSecurity: TransportSecurity,
  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. transportSecurity: transportSecurity
  227. )
  228. configure(&config)
  229. return config
  230. }
  231. }
  232. }
  233. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  234. extension GRPCChannel.Config {
  235. init(posix: HTTP2ClientTransport.Posix.Config) {
  236. self.init(
  237. http2: posix.http2,
  238. backoff: posix.backoff,
  239. connection: posix.connection,
  240. compression: posix.compression
  241. )
  242. }
  243. }
  244. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  245. extension ClientTransport where Self == HTTP2ClientTransport.Posix {
  246. /// Creates a new Posix based HTTP/2 client transport.
  247. ///
  248. /// - Parameters:
  249. /// - target: A target to resolve.
  250. /// - config: Configuration for the transport.
  251. /// - resolverRegistry: A registry of resolver factories.
  252. /// - serviceConfig: Service config controlling how the transport should establish and
  253. /// load-balance connections.
  254. /// - eventLoopGroup: The underlying NIO `EventLoopGroup` to run connections on. This must
  255. /// be a `MultiThreadedEventLoopGroup` or an `EventLoop` from
  256. /// a `MultiThreadedEventLoopGroup`.
  257. /// - Throws: When no suitable resolver could be found for the `target`.
  258. public static func http2NIOPosix(
  259. target: any ResolvableTarget,
  260. config: HTTP2ClientTransport.Posix.Config,
  261. resolverRegistry: NameResolverRegistry = .defaults,
  262. serviceConfig: ServiceConfig = ServiceConfig(),
  263. eventLoopGroup: any EventLoopGroup = .singletonMultiThreadedEventLoopGroup
  264. ) throws -> Self {
  265. return try HTTP2ClientTransport.Posix(
  266. target: target,
  267. config: config,
  268. resolverRegistry: resolverRegistry,
  269. serviceConfig: serviceConfig,
  270. eventLoopGroup: eventLoopGroup
  271. )
  272. }
  273. }