GRPCHTTP2TransportNIOPosix.swift 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. keepaliveConfig: self.config.keepalive,
  54. connectionConfig: self.config.connection,
  55. http2Config: self.config.http2,
  56. rpcConfig: self.config.rpc,
  57. useTLS: false
  58. )
  59. }
  60. }
  61. try await serverChannel.executeThenClose { inbound in
  62. try await withThrowingDiscardingTaskGroup { serverTaskGroup in
  63. for try await (connectionChannel, streamMultiplexer) in inbound {
  64. serverTaskGroup.addTask {
  65. try await connectionChannel
  66. .executeThenClose { connectionInbound, connectionOutbound in
  67. await withDiscardingTaskGroup { connectionTaskGroup in
  68. connectionTaskGroup.addTask {
  69. do {
  70. for try await _ in connectionInbound {}
  71. } catch {
  72. // We don't want to close the channel if one connection throws.
  73. return
  74. }
  75. }
  76. connectionTaskGroup.addTask {
  77. await withDiscardingTaskGroup { streamTaskGroup in
  78. do {
  79. for try await (http2Stream, methodDescriptor) in streamMultiplexer.inbound
  80. {
  81. streamTaskGroup.addTask {
  82. // It's okay to ignore these errors:
  83. // - If we get an error because the http2Stream failed to close, then there's nothing we can do
  84. // - If we get an error because the inner closure threw, then the only possible scenario in which
  85. // that could happen is if methodDescriptor.get() throws - in which case, it means we never got
  86. // the RPC metadata, which means we can't do anything either and it's okay to just kill the stream.
  87. try? await http2Stream.executeThenClose { inbound, outbound in
  88. guard let descriptor = try? await methodDescriptor.get() else {
  89. return
  90. }
  91. let rpcStream = RPCStream(
  92. descriptor: descriptor,
  93. inbound: RPCAsyncSequence(wrapping: inbound),
  94. outbound: RPCWriter.Closable(
  95. wrapping: ServerConnection.Stream.Outbound(
  96. responseWriter: outbound,
  97. http2Stream: http2Stream
  98. )
  99. )
  100. )
  101. await streamHandler(rpcStream)
  102. }
  103. }
  104. }
  105. } catch {
  106. // We don't want to close the whole connection if one stream throws.
  107. return
  108. }
  109. }
  110. }
  111. }
  112. }
  113. }
  114. }
  115. }
  116. }
  117. }
  118. public func stopListening() {
  119. self.serverQuiescingHelper.initiateShutdown(promise: nil)
  120. }
  121. }
  122. }
  123. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  124. extension HTTP2ServerTransport.Posix {
  125. /// Configuration for the ``GRPCHTTP2TransportNIOPosix/GRPCHTTP2Core/HTTP2ServerTransport/Posix``.
  126. public struct Config: Sendable {
  127. /// Compression configuration.
  128. public var compression: HTTP2ServerTransport.Config.Compression
  129. /// Keepalive configuration.
  130. public var keepalive: HTTP2ServerTransport.Config.Keepalive
  131. /// Connection configuration.
  132. public var connection: HTTP2ServerTransport.Config.Connection
  133. /// HTTP2 configuration.
  134. public var http2: HTTP2ServerTransport.Config.HTTP2
  135. /// RPC configuration.
  136. public var rpc: HTTP2ServerTransport.Config.RPC
  137. /// Construct a new `Config`.
  138. /// - Parameters:
  139. /// - compression: Compression configuration.
  140. /// - keepalive: Keepalive configuration.
  141. /// - connection: Connection configuration.
  142. /// - http2: HTTP2 configuration.
  143. /// - rpc: RPC configuration.
  144. public init(
  145. compression: HTTP2ServerTransport.Config.Compression,
  146. keepalive: HTTP2ServerTransport.Config.Keepalive,
  147. connection: HTTP2ServerTransport.Config.Connection,
  148. http2: HTTP2ServerTransport.Config.HTTP2,
  149. rpc: HTTP2ServerTransport.Config.RPC
  150. ) {
  151. self.compression = compression
  152. self.keepalive = keepalive
  153. self.connection = connection
  154. self.http2 = http2
  155. self.rpc = rpc
  156. }
  157. /// Default values for the different configurations.
  158. public static var defaults: Self {
  159. Self(
  160. compression: .defaults,
  161. keepalive: .defaults,
  162. connection: .defaults,
  163. http2: .defaults,
  164. rpc: .defaults
  165. )
  166. }
  167. }
  168. }
  169. extension NIOCore.SocketAddress {
  170. fileprivate init(_ socketAddress: GRPCHTTP2Core.SocketAddress) throws {
  171. if let ipv4 = socketAddress.ipv4 {
  172. self = try Self(ipAddress: ipv4.host, port: ipv4.port)
  173. } else if let ipv6 = socketAddress.ipv6 {
  174. self = try Self(ipAddress: ipv6.host, port: ipv6.port)
  175. } else if let unixDomainSocket = socketAddress.unixDomainSocket {
  176. self = try Self(unixDomainSocketPath: unixDomainSocket.path)
  177. } else {
  178. throw RPCError(
  179. code: .internalError,
  180. message:
  181. "Unsupported mapping to NIOCore/SocketAddress for GRPCHTTP2Core/SocketAddress: \(socketAddress)."
  182. )
  183. }
  184. }
  185. }
  186. extension ServerBootstrap {
  187. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  188. fileprivate func bind<Output: Sendable>(
  189. to address: GRPCHTTP2Core.SocketAddress,
  190. childChannelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture<Output>
  191. ) async throws -> NIOAsyncChannel<Output, Never> {
  192. if let virtualSocket = address.virtualSocket {
  193. return try await self.bind(
  194. to: VsockAddress(
  195. cid: VsockAddress.ContextID(rawValue: virtualSocket.contextID.rawValue),
  196. port: VsockAddress.Port(rawValue: virtualSocket.port.rawValue)
  197. ),
  198. childChannelInitializer: childChannelInitializer
  199. )
  200. } else {
  201. return try await self.bind(
  202. to: NIOCore.SocketAddress(address),
  203. childChannelInitializer: childChannelInitializer
  204. )
  205. }
  206. }
  207. }