HTTP2ClientTransport+Posix.swift 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  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 platform (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 and RPC behavior via the
  36. /// ``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 {
  44. /// let transport = try HTTP2ClientTransport.Posix(target: .dns(host: "example.com"))
  45. /// let client = GRPCClient(transport: transport)
  46. /// group.addTask {
  47. /// try await client.run()
  48. /// }
  49. ///
  50. /// // ...
  51. /// }
  52. /// ```
  53. public struct Posix: ClientTransport {
  54. private let channel: GRPCChannel
  55. /// Creates a new Posix based HTTP/2 client transport.
  56. ///
  57. /// - Parameters:
  58. /// - target: A target to resolve.
  59. /// - resolverRegistry: A registry of resolver factories.
  60. /// - config: Configuration for the transport.
  61. /// - serviceConfig: Service config controlling how the transport should establish and
  62. /// load-balance connections.
  63. /// - eventLoopGroup: The underlying NIO `EventLoopGroup` to run connections on. This must
  64. /// be a `MultiThreadedEventLoopGroup` or an `EventLoop` from
  65. /// a `MultiThreadedEventLoopGroup`.
  66. /// - Throws: When no suitable resolver could be found for the `target`.
  67. public init(
  68. target: any ResolvableTarget,
  69. resolverRegistry: NameResolverRegistry = .defaults,
  70. config: Config = .defaults,
  71. serviceConfig: ServiceConfig = ServiceConfig(),
  72. eventLoopGroup: any EventLoopGroup = .singletonMultiThreadedEventLoopGroup
  73. ) throws {
  74. guard let resolver = resolverRegistry.makeResolver(for: target) else {
  75. throw RuntimeError(
  76. code: .transportError,
  77. message: """
  78. No suitable resolvers to resolve '\(target)'. You must make sure that the resolver \
  79. registry has a suitable name resolver factory registered for the given target.
  80. """
  81. )
  82. }
  83. // Configure a connector.
  84. self.channel = GRPCChannel(
  85. resolver: resolver,
  86. connector: Connector(eventLoopGroup: eventLoopGroup, config: config),
  87. config: GRPCChannel.Config(posix: config),
  88. defaultServiceConfig: serviceConfig
  89. )
  90. }
  91. public var retryThrottle: RetryThrottle? {
  92. self.channel.retryThrottle
  93. }
  94. public func connect() async {
  95. await self.channel.connect()
  96. }
  97. public func configuration(forMethod descriptor: MethodDescriptor) -> MethodConfig? {
  98. self.channel.configuration(forMethod: descriptor)
  99. }
  100. public func close() {
  101. self.channel.close()
  102. }
  103. public func withStream<T: Sendable>(
  104. descriptor: MethodDescriptor,
  105. options: CallOptions,
  106. _ closure: (RPCStream<Inbound, Outbound>) async throws -> T
  107. ) async throws -> T {
  108. try await self.channel.withStream(descriptor: descriptor, options: options, closure)
  109. }
  110. }
  111. }
  112. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  113. extension HTTP2ClientTransport.Posix {
  114. struct Connector: HTTP2Connector {
  115. private let config: HTTP2ClientTransport.Posix.Config
  116. private let eventLoopGroup: any EventLoopGroup
  117. init(eventLoopGroup: any EventLoopGroup, config: HTTP2ClientTransport.Posix.Config) {
  118. self.eventLoopGroup = eventLoopGroup
  119. self.config = config
  120. }
  121. func establishConnection(
  122. to address: GRPCHTTP2Core.SocketAddress
  123. ) async throws -> HTTP2Connection {
  124. let (channel, multiplexer) = try await ClientBootstrap(
  125. group: self.eventLoopGroup
  126. ).connect(to: address) { channel in
  127. channel.eventLoop.makeCompletedFuture {
  128. try channel.pipeline.syncOperations.configureGRPCClientPipeline(
  129. channel: channel,
  130. config: GRPCChannel.Config(posix: self.config)
  131. )
  132. }
  133. }
  134. return HTTP2Connection(channel: channel, multiplexer: multiplexer, isPlaintext: true)
  135. }
  136. }
  137. }
  138. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  139. extension HTTP2ClientTransport.Posix {
  140. public struct Config: Sendable {
  141. /// Configuration for HTTP/2 connections.
  142. public var http2: HTTP2ClientTransport.Config.HTTP2
  143. /// Configuration for backoff used when establishing a connection.
  144. public var backoff: HTTP2ClientTransport.Config.Backoff
  145. /// Configuration for connection management.
  146. public var connection: HTTP2ClientTransport.Config.Connection
  147. /// Compression configuration.
  148. public var compression: HTTP2ClientTransport.Config.Compression
  149. /// Creates a new connection configuration.
  150. ///
  151. /// See also ``defaults``.
  152. public init(
  153. http2: HTTP2ClientTransport.Config.HTTP2,
  154. backoff: HTTP2ClientTransport.Config.Backoff,
  155. connection: HTTP2ClientTransport.Config.Connection,
  156. compression: HTTP2ClientTransport.Config.Compression
  157. ) {
  158. self.http2 = http2
  159. self.connection = connection
  160. self.backoff = backoff
  161. self.compression = compression
  162. }
  163. /// Default values.
  164. public static var defaults: Self {
  165. Self(
  166. http2: .defaults,
  167. backoff: .defaults,
  168. connection: .defaults,
  169. compression: .defaults
  170. )
  171. }
  172. }
  173. }
  174. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  175. extension GRPCChannel.Config {
  176. init(posix: HTTP2ClientTransport.Posix.Config) {
  177. self.init(
  178. http2: posix.http2,
  179. backoff: posix.backoff,
  180. connection: posix.connection,
  181. compression: posix.compression
  182. )
  183. }
  184. }