GRPCHTTP2TransportNIOPosix.swift 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. import GRPCCore
  17. @_spi(Package) import GRPCHTTP2Core
  18. import NIOCore
  19. import NIOExtras
  20. import NIOPosix
  21. extension HTTP2ServerTransport {
  22. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  23. public struct Posix: ServerTransport {
  24. private let address: GRPCHTTP2Core.SocketAddress
  25. private let config: Config
  26. private let eventLoopGroup: MultiThreadedEventLoopGroup
  27. private let serverQuiescingHelper: ServerQuiescingHelper
  28. public init(
  29. address: GRPCHTTP2Core.SocketAddress,
  30. config: Config,
  31. eventLoopGroup: MultiThreadedEventLoopGroup = .singletonMultiThreadedEventLoopGroup
  32. ) {
  33. self.address = address
  34. self.config = config
  35. self.eventLoopGroup = eventLoopGroup
  36. self.serverQuiescingHelper = ServerQuiescingHelper(group: self.eventLoopGroup)
  37. }
  38. public func listen(
  39. _ streamHandler: @escaping (RPCStream<Inbound, Outbound>) async -> Void
  40. ) async throws {
  41. let serverChannel = try await ServerBootstrap(group: self.eventLoopGroup)
  42. .serverChannelInitializer { channel in
  43. let quiescingHandler = self.serverQuiescingHelper.makeServerChannelHandler(
  44. channel: channel
  45. )
  46. return channel.pipeline.addHandler(quiescingHandler)
  47. }
  48. .bind(to: self.address) { channel in
  49. channel.eventLoop.makeCompletedFuture {
  50. return try channel.pipeline.syncOperations.configureGRPCServerPipeline(
  51. channel: channel,
  52. compressionConfig: self.config.compression,
  53. connectionConfig: self.config.connection,
  54. http2Config: self.config.http2,
  55. rpcConfig: self.config.rpc,
  56. useTLS: false
  57. )
  58. }
  59. }
  60. try await serverChannel.executeThenClose { inbound in
  61. try await withThrowingDiscardingTaskGroup { serverTaskGroup in
  62. for try await (connectionChannel, streamMultiplexer) in inbound {
  63. serverTaskGroup.addTask {
  64. try await connectionChannel
  65. .executeThenClose { connectionInbound, connectionOutbound in
  66. await withDiscardingTaskGroup { connectionTaskGroup in
  67. connectionTaskGroup.addTask {
  68. do {
  69. for try await _ in connectionInbound {}
  70. } catch {
  71. // We don't want to close the channel if one connection throws.
  72. return
  73. }
  74. }
  75. connectionTaskGroup.addTask {
  76. await withDiscardingTaskGroup { streamTaskGroup in
  77. do {
  78. for try await (http2Stream, methodDescriptor) in streamMultiplexer.inbound
  79. {
  80. streamTaskGroup.addTask {
  81. // It's okay to ignore these errors:
  82. // - If we get an error because the http2Stream failed to close, then there's nothing we can do
  83. // - If we get an error because the inner closure threw, then the only possible scenario in which
  84. // that could happen is if methodDescriptor.get() throws - in which case, it means we never got
  85. // the RPC metadata, which means we can't do anything either and it's okay to just kill the stream.
  86. try? await http2Stream.executeThenClose { inbound, outbound in
  87. guard let descriptor = try? await methodDescriptor.get() else {
  88. return
  89. }
  90. let rpcStream = RPCStream(
  91. descriptor: descriptor,
  92. inbound: RPCAsyncSequence(wrapping: inbound),
  93. outbound: RPCWriter.Closable(
  94. wrapping: ServerConnection.Stream.Outbound(
  95. responseWriter: outbound,
  96. http2Stream: http2Stream
  97. )
  98. )
  99. )
  100. await streamHandler(rpcStream)
  101. }
  102. }
  103. }
  104. } catch {
  105. // We don't want to close the whole connection if one stream throws.
  106. return
  107. }
  108. }
  109. }
  110. }
  111. }
  112. }
  113. }
  114. }
  115. }
  116. }
  117. public func stopListening() {
  118. self.serverQuiescingHelper.initiateShutdown(promise: nil)
  119. }
  120. }
  121. }
  122. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  123. extension HTTP2ServerTransport.Posix {
  124. /// Configuration for the ``GRPCHTTP2TransportNIOPosix/GRPCHTTP2Core/HTTP2ServerTransport/Posix``.
  125. public struct Config: Sendable {
  126. /// Compression configuration.
  127. public var compression: HTTP2ServerTransport.Config.Compression
  128. /// Connection configuration.
  129. public var connection: HTTP2ServerTransport.Config.Connection
  130. /// HTTP2 configuration.
  131. public var http2: HTTP2ServerTransport.Config.HTTP2
  132. /// RPC configuration.
  133. public var rpc: HTTP2ServerTransport.Config.RPC
  134. /// Construct a new `Config`.
  135. /// - Parameters:
  136. /// - compression: Compression configuration.
  137. /// - connection: Connection configuration.
  138. /// - http2: HTTP2 configuration.
  139. /// - rpc: RPC configuration.
  140. public init(
  141. compression: HTTP2ServerTransport.Config.Compression,
  142. connection: HTTP2ServerTransport.Config.Connection,
  143. http2: HTTP2ServerTransport.Config.HTTP2,
  144. rpc: HTTP2ServerTransport.Config.RPC
  145. ) {
  146. self.compression = compression
  147. self.connection = connection
  148. self.http2 = http2
  149. self.rpc = rpc
  150. }
  151. /// Default values for the different configurations.
  152. public static var defaults: Self {
  153. Self(
  154. compression: .defaults,
  155. connection: .defaults,
  156. http2: .defaults,
  157. rpc: .defaults
  158. )
  159. }
  160. }
  161. }
  162. extension NIOCore.SocketAddress {
  163. fileprivate init(_ socketAddress: GRPCHTTP2Core.SocketAddress) throws {
  164. if let ipv4 = socketAddress.ipv4 {
  165. self = try Self(ipv4)
  166. } else if let ipv6 = socketAddress.ipv6 {
  167. self = try Self(ipv6)
  168. } else if let unixDomainSocket = socketAddress.unixDomainSocket {
  169. self = try Self(unixDomainSocket)
  170. } else {
  171. throw RPCError(
  172. code: .internalError,
  173. message:
  174. "Unsupported mapping to NIOCore/SocketAddress for GRPCHTTP2Core/SocketAddress: \(socketAddress)."
  175. )
  176. }
  177. }
  178. }
  179. extension ServerBootstrap {
  180. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  181. fileprivate func bind<Output: Sendable>(
  182. to address: GRPCHTTP2Core.SocketAddress,
  183. childChannelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture<Output>
  184. ) async throws -> NIOAsyncChannel<Output, Never> {
  185. if let virtualSocket = address.virtualSocket {
  186. return try await self.bind(
  187. to: VsockAddress(virtualSocket),
  188. childChannelInitializer: childChannelInitializer
  189. )
  190. } else {
  191. return try await self.bind(
  192. to: NIOCore.SocketAddress(address),
  193. childChannelInitializer: childChannelInitializer
  194. )
  195. }
  196. }
  197. }