HTTP2ServerTransport+Posix.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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
  18. internal import NIOCore
  19. internal import NIOExtras
  20. internal import NIOHTTP2
  21. public import NIOPosix // has to be public because of default argument value in init
  22. extension HTTP2ServerTransport {
  23. /// A NIOPosix-backed implementation of a server transport.
  24. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  25. public struct Posix: ServerTransport {
  26. private let address: GRPCHTTP2Core.SocketAddress
  27. private let config: Config
  28. private let eventLoopGroup: MultiThreadedEventLoopGroup
  29. private let serverQuiescingHelper: ServerQuiescingHelper
  30. private enum State {
  31. case idle(EventLoopPromise<GRPCHTTP2Core.SocketAddress>)
  32. case listening(EventLoopFuture<GRPCHTTP2Core.SocketAddress>)
  33. case closedOrInvalidAddress(RuntimeError)
  34. var listeningAddressFuture: EventLoopFuture<GRPCHTTP2Core.SocketAddress> {
  35. get throws {
  36. switch self {
  37. case .idle(let eventLoopPromise):
  38. return eventLoopPromise.futureResult
  39. case .listening(let eventLoopFuture):
  40. return eventLoopFuture
  41. case .closedOrInvalidAddress(let runtimeError):
  42. throw runtimeError
  43. }
  44. }
  45. }
  46. enum OnBound {
  47. case succeedPromise(
  48. _ promise: EventLoopPromise<GRPCHTTP2Core.SocketAddress>,
  49. address: GRPCHTTP2Core.SocketAddress
  50. )
  51. case failPromise(
  52. _ promise: EventLoopPromise<GRPCHTTP2Core.SocketAddress>,
  53. error: RuntimeError
  54. )
  55. }
  56. mutating func addressBound(
  57. _ address: NIOCore.SocketAddress?,
  58. userProvidedAddress: GRPCHTTP2Core.SocketAddress
  59. ) -> OnBound {
  60. switch self {
  61. case .idle(let listeningAddressPromise):
  62. if let address {
  63. self = .listening(listeningAddressPromise.futureResult)
  64. return .succeedPromise(
  65. listeningAddressPromise,
  66. address: GRPCHTTP2Core.SocketAddress(address)
  67. )
  68. } else if userProvidedAddress.virtualSocket != nil {
  69. self = .listening(listeningAddressPromise.futureResult)
  70. return .succeedPromise(listeningAddressPromise, address: userProvidedAddress)
  71. } else {
  72. assertionFailure("Unknown address type")
  73. let invalidAddressError = RuntimeError(
  74. code: .transportError,
  75. message: "Unknown address type returned by transport."
  76. )
  77. self = .closedOrInvalidAddress(invalidAddressError)
  78. return .failPromise(listeningAddressPromise, error: invalidAddressError)
  79. }
  80. case .listening, .closedOrInvalidAddress:
  81. fatalError(
  82. "Invalid state: addressBound should only be called once and when in idle state"
  83. )
  84. }
  85. }
  86. enum OnClose {
  87. case failPromise(
  88. EventLoopPromise<GRPCHTTP2Core.SocketAddress>,
  89. error: RuntimeError
  90. )
  91. case doNothing
  92. }
  93. mutating func close() -> OnClose {
  94. let serverStoppedError = RuntimeError(
  95. code: .serverIsStopped,
  96. message: """
  97. There is no listening address bound for this server: there may have been \
  98. an error which caused the transport to close, or it may have shut down.
  99. """
  100. )
  101. switch self {
  102. case .idle(let listeningAddressPromise):
  103. self = .closedOrInvalidAddress(serverStoppedError)
  104. return .failPromise(listeningAddressPromise, error: serverStoppedError)
  105. case .listening:
  106. self = .closedOrInvalidAddress(serverStoppedError)
  107. return .doNothing
  108. case .closedOrInvalidAddress:
  109. return .doNothing
  110. }
  111. }
  112. }
  113. private let listeningAddressState: LockedValueBox<State>
  114. /// The listening address for this server transport.
  115. ///
  116. /// It is an `async` property because it will only return once the address has been successfully bound.
  117. ///
  118. /// - Throws: A runtime error will be thrown if the address could not be bound or is not bound any
  119. /// longer, because the transport isn't listening anymore. It can also throw if the transport returned an
  120. /// invalid address.
  121. public var listeningAddress: GRPCHTTP2Core.SocketAddress {
  122. get async throws {
  123. try await self.listeningAddressState
  124. .withLockedValue { try $0.listeningAddressFuture }
  125. .get()
  126. }
  127. }
  128. /// Create a new `Posix` transport.
  129. ///
  130. /// - Parameters:
  131. /// - address: The address to which the server should be bound.
  132. /// - config: The transport configuration.
  133. /// - eventLoopGroup: The ELG from which to get ELs to run this transport.
  134. public init(
  135. address: GRPCHTTP2Core.SocketAddress,
  136. config: Config = .defaults,
  137. eventLoopGroup: MultiThreadedEventLoopGroup = .singletonMultiThreadedEventLoopGroup
  138. ) {
  139. self.address = address
  140. self.config = config
  141. self.eventLoopGroup = eventLoopGroup
  142. self.serverQuiescingHelper = ServerQuiescingHelper(group: self.eventLoopGroup)
  143. let eventLoop = eventLoopGroup.any()
  144. self.listeningAddressState = LockedValueBox(.idle(eventLoop.makePromise()))
  145. }
  146. public func listen(
  147. _ streamHandler: @escaping @Sendable (RPCStream<Inbound, Outbound>) async -> Void
  148. ) async throws {
  149. defer {
  150. switch self.listeningAddressState.withLockedValue({ $0.close() }) {
  151. case .failPromise(let promise, let error):
  152. promise.fail(error)
  153. case .doNothing:
  154. ()
  155. }
  156. }
  157. let serverChannel = try await ServerBootstrap(group: self.eventLoopGroup)
  158. .serverChannelOption(
  159. ChannelOptions.socketOption(.so_reuseaddr),
  160. value: 1
  161. )
  162. .serverChannelInitializer { channel in
  163. let quiescingHandler = self.serverQuiescingHelper.makeServerChannelHandler(
  164. channel: channel
  165. )
  166. return channel.pipeline.addHandler(quiescingHandler)
  167. }
  168. .bind(to: self.address) { channel in
  169. channel.eventLoop.makeCompletedFuture {
  170. return try channel.pipeline.syncOperations.configureGRPCServerPipeline(
  171. channel: channel,
  172. compressionConfig: self.config.compression,
  173. connectionConfig: self.config.connection,
  174. http2Config: self.config.http2,
  175. rpcConfig: self.config.rpc,
  176. useTLS: false
  177. )
  178. }
  179. }
  180. let action = self.listeningAddressState.withLockedValue {
  181. $0.addressBound(
  182. serverChannel.channel.localAddress,
  183. userProvidedAddress: self.address
  184. )
  185. }
  186. switch action {
  187. case .succeedPromise(let promise, let address):
  188. promise.succeed(address)
  189. case .failPromise(let promise, let error):
  190. promise.fail(error)
  191. }
  192. try await serverChannel.executeThenClose { inbound in
  193. try await withThrowingDiscardingTaskGroup { group in
  194. for try await (connectionChannel, streamMultiplexer) in inbound {
  195. group.addTask {
  196. try await self.handleConnection(
  197. connectionChannel,
  198. multiplexer: streamMultiplexer,
  199. streamHandler: streamHandler
  200. )
  201. }
  202. }
  203. }
  204. }
  205. }
  206. private func handleConnection(
  207. _ connection: NIOAsyncChannel<HTTP2Frame, HTTP2Frame>,
  208. multiplexer: ChannelPipeline.SynchronousOperations.HTTP2StreamMultiplexer,
  209. streamHandler: @escaping @Sendable (RPCStream<Inbound, Outbound>) async -> Void
  210. ) async throws {
  211. try await connection.executeThenClose { inbound, _ in
  212. await withDiscardingTaskGroup { group in
  213. group.addTask {
  214. do {
  215. for try await _ in inbound {}
  216. } catch {
  217. // We don't want to close the channel if one connection throws.
  218. return
  219. }
  220. }
  221. do {
  222. for try await (stream, descriptor) in multiplexer.inbound {
  223. group.addTask {
  224. await self.handleStream(stream, handler: streamHandler, descriptor: descriptor)
  225. }
  226. }
  227. } catch {
  228. return
  229. }
  230. }
  231. }
  232. }
  233. private func handleStream(
  234. _ stream: NIOAsyncChannel<RPCRequestPart, RPCResponsePart>,
  235. handler streamHandler: @escaping @Sendable (RPCStream<Inbound, Outbound>) async -> Void,
  236. descriptor: EventLoopFuture<MethodDescriptor>
  237. ) async {
  238. // It's okay to ignore these errors:
  239. // - If we get an error because the http2Stream failed to close, then there's nothing we can do
  240. // - If we get an error because the inner closure threw, then the only possible scenario in which
  241. // that could happen is if methodDescriptor.get() throws - in which case, it means we never got
  242. // the RPC metadata, which means we can't do anything either and it's okay to just kill the stream.
  243. try? await stream.executeThenClose { inbound, outbound in
  244. guard let descriptor = try? await descriptor.get() else {
  245. return
  246. }
  247. let rpcStream = RPCStream(
  248. descriptor: descriptor,
  249. inbound: RPCAsyncSequence(wrapping: inbound),
  250. outbound: RPCWriter.Closable(
  251. wrapping: ServerConnection.Stream.Outbound(
  252. responseWriter: outbound,
  253. http2Stream: stream
  254. )
  255. )
  256. )
  257. await streamHandler(rpcStream)
  258. }
  259. }
  260. public func stopListening() {
  261. self.serverQuiescingHelper.initiateShutdown(promise: nil)
  262. }
  263. }
  264. }
  265. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  266. extension HTTP2ServerTransport.Posix {
  267. /// Configuration for the ``GRPCHTTP2TransportNIOPosix/GRPCHTTP2Core/HTTP2ServerTransport/Posix``.
  268. public struct Config: Sendable {
  269. /// Compression configuration.
  270. public var compression: HTTP2ServerTransport.Config.Compression
  271. /// Connection configuration.
  272. public var connection: HTTP2ServerTransport.Config.Connection
  273. /// HTTP2 configuration.
  274. public var http2: HTTP2ServerTransport.Config.HTTP2
  275. /// RPC configuration.
  276. public var rpc: HTTP2ServerTransport.Config.RPC
  277. /// Construct a new `Config`.
  278. /// - Parameters:
  279. /// - compression: Compression configuration.
  280. /// - connection: Connection configuration.
  281. /// - http2: HTTP2 configuration.
  282. /// - rpc: RPC configuration.
  283. public init(
  284. compression: HTTP2ServerTransport.Config.Compression,
  285. connection: HTTP2ServerTransport.Config.Connection,
  286. http2: HTTP2ServerTransport.Config.HTTP2,
  287. rpc: HTTP2ServerTransport.Config.RPC
  288. ) {
  289. self.compression = compression
  290. self.connection = connection
  291. self.http2 = http2
  292. self.rpc = rpc
  293. }
  294. /// Default values for the different configurations.
  295. public static var defaults: Self {
  296. Self(
  297. compression: .defaults,
  298. connection: .defaults,
  299. http2: .defaults,
  300. rpc: .defaults
  301. )
  302. }
  303. }
  304. }
  305. extension NIOCore.SocketAddress {
  306. fileprivate init(_ socketAddress: GRPCHTTP2Core.SocketAddress) throws {
  307. if let ipv4 = socketAddress.ipv4 {
  308. self = try Self(ipv4)
  309. } else if let ipv6 = socketAddress.ipv6 {
  310. self = try Self(ipv6)
  311. } else if let unixDomainSocket = socketAddress.unixDomainSocket {
  312. self = try Self(unixDomainSocket)
  313. } else {
  314. throw RPCError(
  315. code: .internalError,
  316. message:
  317. "Unsupported mapping to NIOCore/SocketAddress for GRPCHTTP2Core/SocketAddress: \(socketAddress)."
  318. )
  319. }
  320. }
  321. }
  322. extension ServerBootstrap {
  323. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  324. fileprivate func bind<Output: Sendable>(
  325. to address: GRPCHTTP2Core.SocketAddress,
  326. childChannelInitializer: @escaping @Sendable (any Channel) -> EventLoopFuture<Output>
  327. ) async throws -> NIOAsyncChannel<Output, Never> {
  328. if let virtualSocket = address.virtualSocket {
  329. return try await self.bind(
  330. to: VsockAddress(virtualSocket),
  331. childChannelInitializer: childChannelInitializer
  332. )
  333. } else {
  334. return try await self.bind(
  335. to: NIOCore.SocketAddress(address),
  336. childChannelInitializer: childChannelInitializer
  337. )
  338. }
  339. }
  340. }